UNPKG

proskomma-core

Version:
58,759 lines 1.92 MB
/*!
 * XRegExp 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2007-present MIT License
 */
const REGEX_DATA = "xregexp";
const features = {
  astral: false,
  namespacing: true
};
const fixed = {};
let regexCache = {};
let patternCache = {};
const tokens = [];
const defaultScope = "default";
const classScope = "class";
const nativeTokens = {
  // Any native multicharacter token in default scope, or any single character
  "default": /\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u(?:[\dA-Fa-f]{4}|{[\dA-Fa-f]+})|c[A-Za-z]|[\s\S])|\(\?(?:[:=!]|<[=!])|[?*+]\?|{\d+(?:,\d*)?}\??|[\s\S]/,
  // Any native multicharacter token in character class scope, or any single character
  "class": /\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u(?:[\dA-Fa-f]{4}|{[\dA-Fa-f]+})|c[A-Za-z]|[\s\S])|[\s\S]/
};
const replacementToken = /\$(?:\{([^\}]+)\}|<([^>]+)>|(\d\d?|[\s\S]?))/g;
const correctExecNpcg = /()??/.exec("")[1] === void 0;
const hasFlagsProp = /x/.flags !== void 0;
function hasNativeFlag(flag) {
  let isSupported = true;
  try {
    new RegExp("", flag);
    if (flag === "y") {
      const gy = (() => "gy")();
      const incompleteY = ".a".replace(new RegExp("a", gy), ".") === "..";
      if (incompleteY) {
        isSupported = false;
      }
    }
  } catch (exception) {
    isSupported = false;
  }
  return isSupported;
}
const hasNativeD = hasNativeFlag("d");
const hasNativeS = hasNativeFlag("s");
const hasNativeU = hasNativeFlag("u");
const hasNativeY = hasNativeFlag("y");
const registeredFlags = {
  d: hasNativeD,
  g: true,
  i: true,
  m: true,
  s: hasNativeS,
  u: hasNativeU,
  y: hasNativeY
};
const nonnativeFlags = hasNativeS ? /[^dgimsuy]+/g : /[^dgimuy]+/g;
function augment(regex, captureNames, xSource, xFlags, isInternalOnly) {
  regex[REGEX_DATA] = {
    captureNames
  };
  if (isInternalOnly) {
    return regex;
  }
  if (regex.__proto__) {
    regex.__proto__ = XRegExp.prototype;
  } else {
    for (const p in XRegExp.prototype) {
      regex[p] = XRegExp.prototype[p];
    }
  }
  regex[REGEX_DATA].source = xSource;
  regex[REGEX_DATA].flags = xFlags ? xFlags.split("").sort().join("") : xFlags;
  return regex;
}
function clipDuplicates(str) {
  return str.replace(/([\s\S])(?=[\s\S]*\1)/g, "");
}
function copyRegex(regex, options2) {
  if (!XRegExp.isRegExp(regex)) {
    throw new TypeError("Type RegExp expected");
  }
  const xData = regex[REGEX_DATA] || {};
  let flags = getNativeFlags(regex);
  let flagsToAdd = "";
  let flagsToRemove = "";
  let xregexpSource = null;
  let xregexpFlags = null;
  options2 = options2 || {};
  if (options2.removeG) {
    flagsToRemove += "g";
  }
  if (options2.removeY) {
    flagsToRemove += "y";
  }
  if (flagsToRemove) {
    flags = flags.replace(new RegExp(`[${flagsToRemove}]+`, "g"), "");
  }
  if (options2.addG) {
    flagsToAdd += "g";
  }
  if (options2.addY) {
    flagsToAdd += "y";
  }
  if (flagsToAdd) {
    flags = clipDuplicates(flags + flagsToAdd);
  }
  if (!options2.isInternalOnly) {
    if (xData.source !== void 0) {
      xregexpSource = xData.source;
    }
    if (xData.flags != null) {
      xregexpFlags = flagsToAdd ? clipDuplicates(xData.flags + flagsToAdd) : xData.flags;
    }
  }
  regex = augment(
    new RegExp(options2.source || regex.source, flags),
    hasNamedCapture(regex) ? xData.captureNames.slice(0) : null,
    xregexpSource,
    xregexpFlags,
    options2.isInternalOnly
  );
  return regex;
}
function dec(hex2) {
  return parseInt(hex2, 16);
}
function getContextualTokenSeparator(match, scope2, flags) {
  const matchEndPos = match.index + match[0].length;
  const precedingChar = match.input[match.index - 1];
  const followingChar = match.input[matchEndPos];
  if (
    // No need to separate tokens if at the beginning or end of a group, before or after a
    // group, or before or after a `|`
    /^[()|]$/.test(precedingChar) || /^[()|]$/.test(followingChar) || // No need to separate tokens if at the beginning or end of the pattern
    match.index === 0 || matchEndPos === match.input.length || // No need to separate tokens if at the beginning of a noncapturing group or lookaround.
    // Looks only at the last 4 chars (at most) for perf when constructing long regexes.
    /\(\?(?:[:=!]|<[=!])$/.test(match.input.substring(match.index - 4, match.index)) || // Avoid separating tokens when the following token is a quantifier
    isQuantifierNext(match.input, matchEndPos, flags)
  ) {
    return "";
  }
  return "(?:)";
}
function getNativeFlags(regex) {
  return hasFlagsProp ? regex.flags : (
    // Explicitly using `RegExp.prototype.toString` (rather than e.g. `String` or concatenation
    // with an empty string) allows this to continue working predictably when
    // `XRegExp.proptotype.toString` is overridden
    /\/([a-z]*)$/i.exec(RegExp.prototype.toString.call(regex))[1]
  );
}
function hasNamedCapture(regex) {
  return !!(regex[REGEX_DATA] && regex[REGEX_DATA].captureNames);
}
function hex(dec2) {
  return parseInt(dec2, 10).toString(16);
}
function isQuantifierNext(pattern2, pos, flags) {
  const inlineCommentPattern = "\\(\\?#[^)]*\\)";
  const lineCommentPattern = "#[^#\\n]*";
  const quantifierPattern = "[?*+]|{\\d+(?:,\\d*)?}";
  const regex = flags.includes("x") ? (
    // Ignore any leading whitespace, line comments, and inline comments
    new RegExp(`^(?:\\s|${lineCommentPattern}|${inlineCommentPattern})*(?:${quantifierPattern})`)
  ) : (
    // Ignore any leading inline comments
    new RegExp(`^(?:${inlineCommentPattern})*(?:${quantifierPattern})`)
  );
  return regex.test(pattern2.slice(pos));
}
function isType$1(value, type2) {
  return Object.prototype.toString.call(value) === `[object ${type2}]`;
}
function nullThrows(value) {
  if (value == null) {
    throw new TypeError("Cannot convert null or undefined to object");
  }
  return value;
}
function pad4(str) {
  while (str.length < 4) {
    str = `0${str}`;
  }
  return str;
}
function prepareFlags(pattern2, flags) {
  if (clipDuplicates(flags) !== flags) {
    throw new SyntaxError(`Invalid duplicate regex flag ${flags}`);
  }
  pattern2 = pattern2.replace(/^\(\?([\w$]+)\)/, ($0, $1) => {
    if (/[dgy]/.test($1)) {
      throw new SyntaxError(`Cannot use flags dgy in mode modifier ${$0}`);
    }
    flags = clipDuplicates(flags + $1);
    return "";
  });
  for (const flag of flags) {
    if (!registeredFlags[flag]) {
      throw new SyntaxError(`Unknown regex flag ${flag}`);
    }
  }
  return {
    pattern: pattern2,
    flags
  };
}
function prepareOptions(value) {
  const options2 = {};
  if (isType$1(value, "String")) {
    XRegExp.forEach(value, /[^\s,]+/, (match) => {
      options2[match] = true;
    });
    return options2;
  }
  return value;
}
function registerFlag(flag) {
  if (!/^[\w$]$/.test(flag)) {
    throw new Error("Flag must be a single character A-Za-z0-9_$");
  }
  registeredFlags[flag] = true;
}
function runTokens(pattern2, flags, pos, scope2, context) {
  let i = tokens.length;
  const leadChar = pattern2[pos];
  let result = null;
  let match;
  let t;
  while (i--) {
    t = tokens[i];
    if (t.leadChar && t.leadChar !== leadChar || t.scope !== scope2 && t.scope !== "all" || t.flag && !flags.includes(t.flag)) {
      continue;
    }
    match = XRegExp.exec(pattern2, t.regex, pos, "sticky");
    if (match) {
      result = {
        matchLength: match[0].length,
        output: t.handler.call(context, match, scope2, flags),
        reparse: t.reparse
      };
      break;
    }
  }
  return result;
}
function setAstral(on) {
  features.astral = on;
}
function setNamespacing(on) {
  features.namespacing = on;
}
function XRegExp(pattern2, flags) {
  if (XRegExp.isRegExp(pattern2)) {
    if (flags !== void 0) {
      throw new TypeError("Cannot supply flags when copying a RegExp");
    }
    return copyRegex(pattern2);
  }
  pattern2 = pattern2 === void 0 ? "" : String(pattern2);
  flags = flags === void 0 ? "" : String(flags);
  if (XRegExp.isInstalled("astral") && !flags.includes("A")) {
    flags += "A";
  }
  if (!patternCache[pattern2]) {
    patternCache[pattern2] = {};
  }
  if (!patternCache[pattern2][flags]) {
    const context = {
      hasNamedCapture: false,
      captureNames: []
    };
    let scope2 = defaultScope;
    let output = "";
    let pos = 0;
    let result;
    const applied = prepareFlags(pattern2, flags);
    let appliedPattern = applied.pattern;
    const appliedFlags = applied.flags;
    while (pos < appliedPattern.length) {
      do {
        result = runTokens(appliedPattern, appliedFlags, pos, scope2, context);
        if (result && result.reparse) {
          appliedPattern = appliedPattern.slice(0, pos) + result.output + appliedPattern.slice(pos + result.matchLength);
        }
      } while (result && result.reparse);
      if (result) {
        output += result.output;
        pos += result.matchLength || 1;
      } else {
        const [token] = XRegExp.exec(appliedPattern, nativeTokens[scope2], pos, "sticky");
        output += token;
        pos += token.length;
        if (token === "[" && scope2 === defaultScope) {
          scope2 = classScope;
        } else if (token === "]" && scope2 === classScope) {
          scope2 = defaultScope;
        }
      }
    }
    patternCache[pattern2][flags] = {
      // Use basic cleanup to collapse repeated empty groups like `(?:)(?:)` to `(?:)`. Empty
      // groups are sometimes inserted during regex transpilation in order to keep tokens
      // separated. However, more than one empty group in a row is never needed.
      pattern: output.replace(/(?:\(\?:\))+/g, "(?:)"),
      // Strip all but native flags
      flags: appliedFlags.replace(nonnativeFlags, ""),
      // `context.captureNames` has an item for each capturing group, even if unnamed
      captures: context.hasNamedCapture ? context.captureNames : null
    };
  }
  const generated = patternCache[pattern2][flags];
  return augment(
    new RegExp(generated.pattern, generated.flags),
    generated.captures,
    pattern2,
    flags
  );
}
XRegExp.prototype = new RegExp();
XRegExp.version = "5.1.1";
XRegExp._clipDuplicates = clipDuplicates;
XRegExp._hasNativeFlag = hasNativeFlag;
XRegExp._dec = dec;
XRegExp._hex = hex;
XRegExp._pad4 = pad4;
XRegExp.addToken = (regex, handler, options2) => {
  options2 = options2 || {};
  let { optionalFlags } = options2;
  if (options2.flag) {
    registerFlag(options2.flag);
  }
  if (optionalFlags) {
    optionalFlags = optionalFlags.split("");
    for (const flag of optionalFlags) {
      registerFlag(flag);
    }
  }
  tokens.push({
    regex: copyRegex(regex, {
      addG: true,
      addY: hasNativeY,
      isInternalOnly: true
    }),
    handler,
    scope: options2.scope || defaultScope,
    flag: options2.flag,
    reparse: options2.reparse,
    leadChar: options2.leadChar
  });
  XRegExp.cache.flush("patterns");
};
XRegExp.cache = (pattern2, flags) => {
  if (!regexCache[pattern2]) {
    regexCache[pattern2] = {};
  }
  return regexCache[pattern2][flags] || (regexCache[pattern2][flags] = XRegExp(pattern2, flags));
};
XRegExp.cache.flush = (cacheName) => {
  if (cacheName === "patterns") {
    patternCache = {};
  } else {
    regexCache = {};
  }
};
XRegExp.escape = (str) => String(nullThrows(str)).replace(/[\\\[\]{}()*+?.^$|]/g, "\\$&").replace(/[\s#\-,]/g, (match) => `\\u${pad4(hex(match.charCodeAt(0)))}`);
XRegExp.exec = (str, regex, pos, sticky) => {
  let cacheKey = "g";
  let addY = false;
  let fakeY = false;
  let match;
  addY = hasNativeY && !!(sticky || regex.sticky && sticky !== false);
  if (addY) {
    cacheKey += "y";
  } else if (sticky) {
    fakeY = true;
    cacheKey += "FakeY";
  }
  regex[REGEX_DATA] = regex[REGEX_DATA] || {};
  const r2 = regex[REGEX_DATA][cacheKey] || (regex[REGEX_DATA][cacheKey] = copyRegex(regex, {
    addG: true,
    addY,
    source: fakeY ? `${regex.source}|()` : void 0,
    removeY: sticky === false,
    isInternalOnly: true
  }));
  pos = pos || 0;
  r2.lastIndex = pos;
  match = fixed.exec.call(r2, str);
  if (fakeY && match && match.pop() === "") {
    match = null;
  }
  if (regex.global) {
    regex.lastIndex = match ? r2.lastIndex : 0;
  }
  return match;
};
XRegExp.forEach = (str, regex, callback) => {
  let pos = 0;
  let i = -1;
  let match;
  while (match = XRegExp.exec(str, regex, pos)) {
    callback(match, ++i, str, regex);
    pos = match.index + (match[0].length || 1);
  }
};
XRegExp.globalize = (regex) => copyRegex(regex, { addG: true });
XRegExp.install = (options2) => {
  options2 = prepareOptions(options2);
  if (!features.astral && options2.astral) {
    setAstral(true);
  }
  if (!features.namespacing && options2.namespacing) {
    setNamespacing(true);
  }
};
XRegExp.isInstalled = (feature) => !!features[feature];
XRegExp.isRegExp = (value) => Object.prototype.toString.call(value) === "[object RegExp]";
XRegExp.match = (str, regex, scope2) => {
  const global2 = regex.global && scope2 !== "one" || scope2 === "all";
  const cacheKey = (global2 ? "g" : "") + (regex.sticky ? "y" : "") || "noGY";
  regex[REGEX_DATA] = regex[REGEX_DATA] || {};
  const r2 = regex[REGEX_DATA][cacheKey] || (regex[REGEX_DATA][cacheKey] = copyRegex(regex, {
    addG: !!global2,
    removeG: scope2 === "one",
    isInternalOnly: true
  }));
  const result = String(nullThrows(str)).match(r2);
  if (regex.global) {
    regex.lastIndex = scope2 === "one" && result ? (
      // Can't use `r2.lastIndex` since `r2` is nonglobal in this case
      result.index + result[0].length
    ) : 0;
  }
  return global2 ? result || [] : result && result[0];
};
XRegExp.matchChain = (str, chain) => function recurseChain(values, level) {
  const item = chain[level].regex ? chain[level] : { regex: chain[level] };
  const matches = [];
  function addMatch(match) {
    if (item.backref) {
      const ERR_UNDEFINED_GROUP = `Backreference to undefined group: ${item.backref}`;
      const isNamedBackref = isNaN(item.backref);
      if (isNamedBackref && XRegExp.isInstalled("namespacing")) {
        if (!(match.groups && item.backref in match.groups)) {
          throw new ReferenceError(ERR_UNDEFINED_GROUP);
        }
      } else if (!match.hasOwnProperty(item.backref)) {
        throw new ReferenceError(ERR_UNDEFINED_GROUP);
      }
      const backrefValue = isNamedBackref && XRegExp.isInstalled("namespacing") ? match.groups[item.backref] : match[item.backref];
      matches.push(backrefValue || "");
    } else {
      matches.push(match[0]);
    }
  }
  for (const value of values) {
    XRegExp.forEach(value, item.regex, addMatch);
  }
  return level === chain.length - 1 || !matches.length ? matches : recurseChain(matches, level + 1);
}([str], 0);
XRegExp.replace = (str, search, replacement, scope2) => {
  const isRegex = XRegExp.isRegExp(search);
  const global2 = search.global && scope2 !== "one" || scope2 === "all";
  const cacheKey = (global2 ? "g" : "") + (search.sticky ? "y" : "") || "noGY";
  let s2 = search;
  if (isRegex) {
    search[REGEX_DATA] = search[REGEX_DATA] || {};
    s2 = search[REGEX_DATA][cacheKey] || (search[REGEX_DATA][cacheKey] = copyRegex(search, {
      addG: !!global2,
      removeG: scope2 === "one",
      isInternalOnly: true
    }));
  } else if (global2) {
    s2 = new RegExp(XRegExp.escape(String(search)), "g");
  }
  const result = fixed.replace.call(nullThrows(str), s2, replacement);
  if (isRegex && search.global) {
    search.lastIndex = 0;
  }
  return result;
};
XRegExp.replaceEach = (str, replacements) => {
  for (const r of replacements) {
    str = XRegExp.replace(str, r[0], r[1], r[2]);
  }
  return str;
};
XRegExp.split = (str, separator, limit) => fixed.split.call(nullThrows(str), separator, limit);
XRegExp.test = (str, regex, pos, sticky) => !!XRegExp.exec(str, regex, pos, sticky);
XRegExp.uninstall = (options2) => {
  options2 = prepareOptions(options2);
  if (features.astral && options2.astral) {
    setAstral(false);
  }
  if (features.namespacing && options2.namespacing) {
    setNamespacing(false);
  }
};
XRegExp.union = (patterns, flags, options2) => {
  options2 = options2 || {};
  const conjunction = options2.conjunction || "or";
  let numCaptures = 0;
  let numPriorCaptures;
  let captureNames;
  function rewrite(match, paren, backref) {
    const name2 = captureNames[numCaptures - numPriorCaptures];
    if (paren) {
      ++numCaptures;
      if (name2) {
        return `(?<${name2}>`;
      }
    } else if (backref) {
      return `\\${+backref + numPriorCaptures}`;
    }
    return match;
  }
  if (!(isType$1(patterns, "Array") && patterns.length)) {
    throw new TypeError("Must provide a nonempty array of patterns to merge");
  }
  const parts = /(\()(?!\?)|\\([1-9]\d*)|\\[\s\S]|\[(?:[^\\\]]|\\[\s\S])*\]/g;
  const output = [];
  for (const pattern2 of patterns) {
    if (XRegExp.isRegExp(pattern2)) {
      numPriorCaptures = numCaptures;
      captureNames = pattern2[REGEX_DATA] && pattern2[REGEX_DATA].captureNames || [];
      output.push(XRegExp(pattern2.source).source.replace(parts, rewrite));
    } else {
      output.push(XRegExp.escape(pattern2));
    }
  }
  const separator = conjunction === "none" ? "" : "|";
  return XRegExp(output.join(separator), flags);
};
fixed.exec = function(str) {
  const origLastIndex = this.lastIndex;
  const match = RegExp.prototype.exec.apply(this, arguments);
  if (match) {
    if (!correctExecNpcg && match.length > 1 && match.includes("")) {
      const r2 = copyRegex(this, {
        removeG: true,
        isInternalOnly: true
      });
      String(str).slice(match.index).replace(r2, (...args) => {
        const len = args.length;
        for (let i = 1; i < len - 2; ++i) {
          if (args[i] === void 0) {
            match[i] = void 0;
          }
        }
      });
    }
    if (this[REGEX_DATA] && this[REGEX_DATA].captureNames) {
      let groupsObject = match;
      if (XRegExp.isInstalled("namespacing")) {
        match.groups = /* @__PURE__ */ Object.create(null);
        groupsObject = match.groups;
      }
      for (let i = 1; i < match.length; ++i) {
        const name2 = this[REGEX_DATA].captureNames[i - 1];
        if (name2) {
          groupsObject[name2] = match[i];
        }
      }
    } else if (!match.groups && XRegExp.isInstalled("namespacing")) {
      match.groups = void 0;
    }
    if (this.global && !match[0].length && this.lastIndex > match.index) {
      this.lastIndex = match.index;
    }
  }
  if (!this.global) {
    this.lastIndex = origLastIndex;
  }
  return match;
};
fixed.test = function(str) {
  return !!fixed.exec.call(this, str);
};
fixed.match = function(regex) {
  if (!XRegExp.isRegExp(regex)) {
    regex = new RegExp(regex);
  } else if (regex.global) {
    const result = String.prototype.match.apply(this, arguments);
    regex.lastIndex = 0;
    return result;
  }
  return fixed.exec.call(regex, nullThrows(this));
};
fixed.replace = function(search, replacement) {
  const isRegex = XRegExp.isRegExp(search);
  let origLastIndex;
  let captureNames;
  let result;
  if (isRegex) {
    if (search[REGEX_DATA]) {
      ({ captureNames } = search[REGEX_DATA]);
    }
    origLastIndex = search.lastIndex;
  } else {
    search += "";
  }
  if (isType$1(replacement, "Function")) {
    result = String(this).replace(search, (...args) => {
      if (captureNames) {
        let groupsObject;
        if (XRegExp.isInstalled("namespacing")) {
          groupsObject = /* @__PURE__ */ Object.create(null);
          args.push(groupsObject);
        } else {
          args[0] = new String(args[0]);
          [groupsObject] = args;
        }
        for (let i = 0; i < captureNames.length; ++i) {
          if (captureNames[i]) {
            groupsObject[captureNames[i]] = args[i + 1];
          }
        }
      }
      return replacement(...args);
    });
  } else {
    result = String(nullThrows(this)).replace(search, (...args) => {
      return String(replacement).replace(replacementToken, replacer);
      function replacer($0, bracketed, angled, dollarToken) {
        bracketed = bracketed || angled;
        const numNonCaptureArgs = isType$1(args[args.length - 1], "Object") ? 4 : 3;
        const numCaptures = args.length - numNonCaptureArgs;
        if (bracketed) {
          if (/^\d+$/.test(bracketed)) {
            const n2 = +bracketed;
            if (n2 <= numCaptures) {
              return args[n2] || "";
            }
          }
          const n = captureNames ? captureNames.indexOf(bracketed) : -1;
          if (n < 0) {
            throw new SyntaxError(`Backreference to undefined group ${$0}`);
          }
          return args[n + 1] || "";
        }
        if (dollarToken === "" || dollarToken === " ") {
          throw new SyntaxError(`Invalid token ${$0}`);
        }
        if (dollarToken === "&" || +dollarToken === 0) {
          return args[0];
        }
        if (dollarToken === "$") {
          return "$";
        }
        if (dollarToken === "`") {
          return args[args.length - 1].slice(0, args[args.length - 2]);
        }
        if (dollarToken === "'") {
          return args[args.length - 1].slice(args[args.length - 2] + args[0].length);
        }
        dollarToken = +dollarToken;
        if (!isNaN(dollarToken)) {
          if (dollarToken > numCaptures) {
            throw new SyntaxError(`Backreference to undefined group ${$0}`);
          }
          return args[dollarToken] || "";
        }
        throw new SyntaxError(`Invalid token ${$0}`);
      }
    });
  }
  if (isRegex) {
    if (search.global) {
      search.lastIndex = 0;
    } else {
      search.lastIndex = origLastIndex;
    }
  }
  return result;
};
fixed.split = function(separator, limit) {
  if (!XRegExp.isRegExp(separator)) {
    return String.prototype.split.apply(this, arguments);
  }
  const str = String(this);
  const output = [];
  const origLastIndex = separator.lastIndex;
  let lastLastIndex = 0;
  let lastLength;
  limit = (limit === void 0 ? -1 : limit) >>> 0;
  XRegExp.forEach(str, separator, (match) => {
    if (match.index + match[0].length > lastLastIndex) {
      output.push(str.slice(lastLastIndex, match.index));
      if (match.length > 1 && match.index < str.length) {
        Array.prototype.push.apply(output, match.slice(1));
      }
      lastLength = match[0].length;
      lastLastIndex = match.index + lastLength;
    }
  });
  if (lastLastIndex === str.length) {
    if (!separator.test("") || lastLength) {
      output.push("");
    }
  } else {
    output.push(str.slice(lastLastIndex));
  }
  separator.lastIndex = origLastIndex;
  return output.length > limit ? output.slice(0, limit) : output;
};
XRegExp.addToken(
  /\\([ABCE-RTUVXYZaeg-mopqyz]|c(?![A-Za-z])|u(?![\dA-Fa-f]{4}|{[\dA-Fa-f]+})|x(?![\dA-Fa-f]{2}))/,
  (match, scope2) => {
    if (match[1] === "B" && scope2 === defaultScope) {
      return match[0];
    }
    throw new SyntaxError(`Invalid escape ${match[0]}`);
  },
  {
    scope: "all",
    leadChar: "\\"
  }
);
XRegExp.addToken(
  /\\u{([\dA-Fa-f]+)}/,
  (match, scope2, flags) => {
    const code2 = dec(match[1]);
    if (code2 > 1114111) {
      throw new SyntaxError(`Invalid Unicode code point ${match[0]}`);
    }
    if (code2 <= 65535) {
      return `\\u${pad4(hex(code2))}`;
    }
    if (hasNativeU && flags.includes("u")) {
      return match[0];
    }
    throw new SyntaxError("Cannot use Unicode code point above \\u{FFFF} without flag u");
  },
  {
    scope: "all",
    leadChar: "\\"
  }
);
XRegExp.addToken(
  /\(\?#[^)]*\)/,
  getContextualTokenSeparator,
  { leadChar: "(" }
);
XRegExp.addToken(
  /\s+|#[^\n]*\n?/,
  getContextualTokenSeparator,
  { flag: "x" }
);
if (!hasNativeS) {
  XRegExp.addToken(
    /\./,
    () => "[\\s\\S]",
    {
      flag: "s",
      leadChar: "."
    }
  );
}
XRegExp.addToken(
  /\\k<([^>]+)>/,
  function(match) {
    const index = isNaN(match[1]) ? this.captureNames.indexOf(match[1]) + 1 : +match[1];
    const endIndex = match.index + match[0].length;
    if (!index || index > this.captureNames.length) {
      throw new SyntaxError(`Backreference to undefined group ${match[0]}`);
    }
    return `\\${index}${endIndex === match.input.length || isNaN(match.input[endIndex]) ? "" : "(?:)"}`;
  },
  { leadChar: "\\" }
);
XRegExp.addToken(
  /\\(\d+)/,
  function(match, scope2) {
    if (!(scope2 === defaultScope && /^[1-9]/.test(match[1]) && +match[1] <= this.captureNames.length) && match[1] !== "0") {
      throw new SyntaxError(`Cannot use octal escape or backreference to undefined group ${match[0]}`);
    }
    return match[0];
  },
  {
    scope: "all",
    leadChar: "\\"
  }
);
XRegExp.addToken(
  /\(\?P?<([\p{ID_Start}$_][\p{ID_Continue}$_\u200C\u200D]*)>/u,
  function(match) {
    if (!XRegExp.isInstalled("namespacing") && (match[1] === "length" || match[1] === "__proto__")) {
      throw new SyntaxError(`Cannot use reserved word as capture name ${match[0]}`);
    }
    if (this.captureNames.includes(match[1])) {
      throw new SyntaxError(`Cannot use same name for multiple groups ${match[0]}`);
    }
    this.captureNames.push(match[1]);
    this.hasNamedCapture = true;
    return "(";
  },
  { leadChar: "(" }
);
XRegExp.addToken(
  /\((?!\?)/,
  function(match, scope2, flags) {
    if (flags.includes("n")) {
      return "(?:";
    }
    this.captureNames.push(null);
    return "(";
  },
  {
    optionalFlags: "n",
    leadChar: "("
  }
);
/*!
 * XRegExp.build 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2012-present MIT License
 */
const build = (XRegExp2) => {
  const REGEX_DATA2 = "xregexp";
  const subParts = /(\()(?!\?)|\\([1-9]\d*)|\\[\s\S]|\[(?:[^\\\]]|\\[\s\S])*\]/g;
  const parts = XRegExp2.union([/\({{([\w$]+)}}\)|{{([\w$]+)}}/, subParts], "g", {
    conjunction: "or"
  });
  function deanchor(pattern2) {
    const leadingAnchor = /^(?:\(\?:\))*\^/;
    const trailingAnchor = /\$(?:\(\?:\))*$/;
    if (leadingAnchor.test(pattern2) && trailingAnchor.test(pattern2) && // Ensure that the trailing `$` isn't escaped
    trailingAnchor.test(pattern2.replace(/\\[\s\S]/g, ""))) {
      return pattern2.replace(leadingAnchor, "").replace(trailingAnchor, "");
    }
    return pattern2;
  }
  function asXRegExp(value, addFlagX) {
    const flags = addFlagX ? "x" : "";
    return XRegExp2.isRegExp(value) ? value[REGEX_DATA2] && value[REGEX_DATA2].captureNames ? (
      // Don't recompile, to preserve capture names
      value
    ) : (
      // Recompile as XRegExp
      XRegExp2(value.source, flags)
    ) : (
      // Compile string as XRegExp
      XRegExp2(value, flags)
    );
  }
  function interpolate(substitution) {
    return substitution instanceof RegExp ? substitution : XRegExp2.escape(substitution);
  }
  function reduceToSubpatternsObject(subpatterns, interpolated, subpatternIndex) {
    subpatterns[`subpattern${subpatternIndex}`] = interpolated;
    return subpatterns;
  }
  function embedSubpatternAfter(raw, subpatternIndex, rawLiterals) {
    const hasSubpattern = subpatternIndex < rawLiterals.length - 1;
    return raw + (hasSubpattern ? `{{subpattern${subpatternIndex}}}` : "");
  }
  XRegExp2.tag = (flags) => (literals, ...substitutions) => {
    const subpatterns = substitutions.map(interpolate).reduce(reduceToSubpatternsObject, {});
    const pattern2 = literals.raw.map(embedSubpatternAfter).join("");
    return XRegExp2.build(pattern2, subpatterns, flags);
  };
  XRegExp2.build = (pattern2, subs, flags) => {
    flags = flags || "";
    const addFlagX = flags.includes("x");
    const inlineFlags = /^\(\?([\w$]+)\)/.exec(pattern2);
    if (inlineFlags) {
      flags = XRegExp2._clipDuplicates(flags + inlineFlags[1]);
    }
    const data = {};
    for (const p in subs) {
      if (subs.hasOwnProperty(p)) {
        const sub = asXRegExp(subs[p], addFlagX);
        data[p] = {
          // Deanchoring allows embedding independently useful anchored regexes. If you
          // really need to keep your anchors, double them (i.e., `^^...$$`).
          pattern: deanchor(sub.source),
          names: sub[REGEX_DATA2].captureNames || []
        };
      }
    }
    const patternAsRegex = asXRegExp(pattern2, addFlagX);
    let numCaps = 0;
    let numPriorCaps;
    let numOuterCaps = 0;
    const outerCapsMap = [0];
    const outerCapNames = patternAsRegex[REGEX_DATA2].captureNames || [];
    const output = patternAsRegex.source.replace(parts, ($0, $1, $2, $3, $4) => {
      const subName = $1 || $2;
      let capName;
      let intro;
      let localCapIndex;
      if (subName) {
        if (!data.hasOwnProperty(subName)) {
          throw new ReferenceError(`Undefined property ${$0}`);
        }
        if ($1) {
          capName = outerCapNames[numOuterCaps];
          outerCapsMap[++numOuterCaps] = ++numCaps;
          intro = `(?<${capName || subName}>`;
        } else {
          intro = "(?:";
        }
        numPriorCaps = numCaps;
        const rewrittenSubpattern = data[subName].pattern.replace(subParts, (match, paren, backref) => {
          if (paren) {
            capName = data[subName].names[numCaps - numPriorCaps];
            ++numCaps;
            if (capName) {
              return `(?<${capName}>`;
            }
          } else if (backref) {
            localCapIndex = +backref - 1;
            return data[subName].names[localCapIndex] ? (
              // Need to preserve the backreference name in case using flag `n`
              `\\k<${data[subName].names[localCapIndex]}>`
            ) : `\\${+backref + numPriorCaps}`;
          }
          return match;
        });
        return `${intro}${rewrittenSubpattern})`;
      }
      if ($3) {
        capName = outerCapNames[numOuterCaps];
        outerCapsMap[++numOuterCaps] = ++numCaps;
        if (capName) {
          return `(?<${capName}>`;
        }
      } else if ($4) {
        localCapIndex = +$4 - 1;
        return outerCapNames[localCapIndex] ? (
          // Need to preserve the backreference name in case using flag `n`
          `\\k<${outerCapNames[localCapIndex]}>`
        ) : `\\${outerCapsMap[+$4]}`;
      }
      return $0;
    });
    return XRegExp2(output, flags);
  };
};
/*!
 * XRegExp.matchRecursive 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2009-present MIT License
 */
const matchRecursive = (XRegExp2) => {
  function row(name2, value, start, end) {
    return {
      name: name2,
      value,
      start,
      end
    };
  }
  XRegExp2.matchRecursive = (str, left, right, flags, options2) => {
    flags = flags || "";
    options2 = options2 || {};
    const global2 = flags.includes("g");
    const sticky = flags.includes("y");
    const basicFlags = flags.replace(/y/g, "");
    left = XRegExp2(left, basicFlags);
    right = XRegExp2(right, basicFlags);
    let esc;
    let { escapeChar } = options2;
    if (escapeChar) {
      if (escapeChar.length > 1) {
        throw new Error("Cannot use more than one escape character");
      }
      escapeChar = XRegExp2.escape(escapeChar);
      esc = new RegExp(
        `(?:${escapeChar}[\\S\\s]|(?:(?!${// Using `XRegExp.union` safely rewrites backreferences in `left` and `right`.
        // Intentionally not passing `basicFlags` to `XRegExp.union` since any syntax
        // transformation resulting from those flags was already applied to `left` and
        // `right` when they were passed through the XRegExp constructor above.
        XRegExp2.union([left, right], "", { conjunction: "or" }).source})[^${escapeChar}])+)+`,
        // Flags `dgy` not needed here
        flags.replace(XRegExp2._hasNativeFlag("s") ? /[^imsu]/g : /[^imu]/g, "")
      );
    }
    let openTokens = 0;
    let delimStart = 0;
    let delimEnd = 0;
    let lastOuterEnd = 0;
    let outerStart;
    let innerStart;
    let leftMatch;
    let rightMatch;
    const vN = options2.valueNames;
    const output = [];
    while (true) {
      if (escapeChar) {
        delimEnd += (XRegExp2.exec(str, esc, delimEnd, "sticky") || [""])[0].length;
      }
      leftMatch = XRegExp2.exec(str, left, delimEnd);
      rightMatch = XRegExp2.exec(str, right, delimEnd);
      if (leftMatch && rightMatch) {
        if (leftMatch.index <= rightMatch.index) {
          rightMatch = null;
        } else {
          leftMatch = null;
        }
      }
      if (leftMatch || rightMatch) {
        delimStart = (leftMatch || rightMatch).index;
        delimEnd = delimStart + (leftMatch || rightMatch)[0].length;
      } else if (!openTokens) {
        break;
      }
      if (sticky && !openTokens && delimStart > lastOuterEnd) {
        break;
      }
      if (leftMatch) {
        if (!openTokens) {
          outerStart = delimStart;
          innerStart = delimEnd;
        }
        openTokens += 1;
      } else if (rightMatch && openTokens) {
        openTokens -= 1;
        if (!openTokens) {
          if (vN) {
            if (vN[0] && outerStart > lastOuterEnd) {
              output.push(row(vN[0], str.slice(lastOuterEnd, outerStart), lastOuterEnd, outerStart));
            }
            if (vN[1]) {
              output.push(row(vN[1], str.slice(outerStart, innerStart), outerStart, innerStart));
            }
            if (vN[2]) {
              output.push(row(vN[2], str.slice(innerStart, delimStart), innerStart, delimStart));
            }
            if (vN[3]) {
              output.push(row(vN[3], str.slice(delimStart, delimEnd), delimStart, delimEnd));
            }
          } else {
            output.push(str.slice(innerStart, delimStart));
          }
          lastOuterEnd = delimEnd;
          if (!global2) {
            break;
          }
        }
      } else {
        const unbalanced = options2.unbalanced || "error";
        if (unbalanced === "skip" || unbalanced === "skip-lazy") {
          if (rightMatch) {
            rightMatch = null;
          } else {
            if (unbalanced === "skip") {
              const outerStartDelimLength = XRegExp2.exec(str, left, outerStart, "sticky")[0].length;
              delimEnd = outerStart + (outerStartDelimLength || 1);
            } else {
              delimEnd = outerStart + 1;
            }
            openTokens = 0;
          }
        } else if (unbalanced === "error") {
          const delimSide = rightMatch ? "right" : "left";
          const errorPos = rightMatch ? delimStart : outerStart;
          throw new Error(`Unbalanced ${delimSide} delimiter found in string at position ${errorPos}`);
        } else {
          throw new Error(`Unsupported value for unbalanced: ${unbalanced}`);
        }
      }
      if (delimStart === delimEnd) {
        delimEnd += 1;
      }
    }
    if (global2 && output.length > 0 && !sticky && vN && vN[0] && str.length > lastOuterEnd) {
      output.push(row(vN[0], str.slice(lastOuterEnd), lastOuterEnd, str.length));
    }
    return output;
  };
};
/*!
 * XRegExp Unicode Base 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2008-present MIT License
 */
const unicodeBase = (XRegExp2) => {
  const unicode = {};
  const unicodeTypes = {};
  const dec2 = XRegExp2._dec;
  const hex2 = XRegExp2._hex;
  const pad42 = XRegExp2._pad4;
  function normalize(name2) {
    return name2.replace(/[- _]+/g, "").toLowerCase();
  }
  function charCode(chr) {
    const esc = /^\\[xu](.+)/.exec(chr);
    return esc ? dec2(esc[1]) : chr.charCodeAt(chr[0] === "\\" ? 1 : 0);
  }
  function invertBmp(range) {
    let output = "";
    let lastEnd = -1;
    XRegExp2.forEach(
      range,
      /(\\x..|\\u....|\\?[\s\S])(?:-(\\x..|\\u....|\\?[\s\S]))?/,
      (m) => {
        const start = charCode(m[1]);
        if (start > lastEnd + 1) {
          output += `\\u${pad42(hex2(lastEnd + 1))}`;
          if (start > lastEnd + 2) {
            output += `-\\u${pad42(hex2(start - 1))}`;
          }
        }
        lastEnd = charCode(m[2] || m[1]);
      }
    );
    if (lastEnd < 65535) {
      output += `\\u${pad42(hex2(lastEnd + 1))}`;
      if (lastEnd < 65534) {
        output += "-\\uFFFF";
      }
    }
    return output;
  }
  function cacheInvertedBmp(slug) {
    const prop = "b!";
    return unicode[slug][prop] || (unicode[slug][prop] = invertBmp(unicode[slug].bmp));
  }
  function buildAstral(slug, isNegated) {
    const item = unicode[slug];
    let combined = "";
    if (item.bmp && !item.isBmpLast) {
      combined = `[${item.bmp}]${item.astral ? "|" : ""}`;
    }
    if (item.astral) {
      combined += item.astral;
    }
    if (item.isBmpLast && item.bmp) {
      combined += `${item.astral ? "|" : ""}[${item.bmp}]`;
    }
    return isNegated ? `(?:(?!${combined})(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|[\0-￿]))` : `(?:${combined})`;
  }
  function cacheAstral(slug, isNegated) {
    const prop = isNegated ? "a!" : "a=";
    return unicode[slug][prop] || (unicode[slug][prop] = buildAstral(slug, isNegated));
  }
  XRegExp2.addToken(
    // Use `*` instead of `+` to avoid capturing `^` as the token name in `\p{^}`
    /\\([pP])(?:{(\^?)(?:(\w+)=)?([^}]*)}|([A-Za-z]))/,
    (match, scope2, flags) => {
      const ERR_DOUBLE_NEG = "Invalid double negation ";
      const ERR_UNKNOWN_NAME = "Unknown Unicode token ";
      const ERR_UNKNOWN_REF = "Unicode token missing data ";
      const ERR_ASTRAL_ONLY = "Astral mode required for Unicode token ";
      const ERR_ASTRAL_IN_CLASS = "Astral mode does not support Unicode tokens within character classes";
      const [
        fullToken,
        pPrefix,
        caretNegation,
        typePrefix,
        tokenName,
        tokenSingleCharName
      ] = match;
      let isNegated = pPrefix === "P" || !!caretNegation;
      const isAstralMode = flags.includes("A");
      let slug = normalize(tokenSingleCharName || tokenName);
      let item = unicode[slug];
      if (pPrefix === "P" && caretNegation) {
        throw new SyntaxError(ERR_DOUBLE_NEG + fullToken);
      }
      if (!unicode.hasOwnProperty(slug)) {
        throw new SyntaxError(ERR_UNKNOWN_NAME + fullToken);
      }
      if (typePrefix) {
        if (!(unicodeTypes[typePrefix] && unicodeTypes[typePrefix][slug])) {
          throw new SyntaxError(ERR_UNKNOWN_NAME + fullToken);
        }
      }
      if (item.inverseOf) {
        slug = normalize(item.inverseOf);
        if (!unicode.hasOwnProperty(slug)) {
          throw new ReferenceError(`${ERR_UNKNOWN_REF + fullToken} -> ${item.inverseOf}`);
        }
        item = unicode[slug];
        isNegated = !isNegated;
      }
      if (!(item.bmp || isAstralMode)) {
        throw new SyntaxError(ERR_ASTRAL_ONLY + fullToken);
      }
      if (isAstralMode) {
        if (scope2 === "class") {
          throw new SyntaxError(ERR_ASTRAL_IN_CLASS);
        }
        return cacheAstral(slug, isNegated);
      }
      return scope2 === "class" ? isNegated ? cacheInvertedBmp(slug) : item.bmp : `${(isNegated ? "[^" : "[") + item.bmp}]`;
    },
    {
      scope: "all",
      optionalFlags: "A",
      leadChar: "\\"
    }
  );
  XRegExp2.addUnicodeData = (data, typePrefix) => {
    const ERR_NO_NAME = "Unicode token requires name";
    const ERR_NO_DATA = "Unicode token has no character data ";
    if (typePrefix) {
      unicodeTypes[typePrefix] = {};
    }
    for (const item of data) {
      if (!item.name) {
        throw new Error(ERR_NO_NAME);
      }
      if (!(item.inverseOf || item.bmp || item.astral)) {
        throw new Error(ERR_NO_DATA + item.name);
      }
      const normalizedName = normalize(item.name);
      unicode[normalizedName] = item;
      if (typePrefix) {
        unicodeTypes[typePrefix][normalizedName] = true;
      }
      if (item.alias) {
        const normalizedAlias = normalize(item.alias);
        unicode[normalizedAlias] = item;
        if (typePrefix) {
          unicodeTypes[typePrefix][normalizedAlias] = true;
        }
      }
    }
    XRegExp2.cache.flush("patterns");
  };
  XRegExp2._getUnicodeProperty = (name2) => {
    const slug = normalize(name2);
    return unicode[slug];
  };
};
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
function getAugmentedNamespace(n) {
  if (n.__esModule)
    return n;
  var f = n.default;
  if (typeof f == "function") {
    var a = function a2() {
      if (this instanceof a2) {
        return Reflect.construct(f, arguments, this.constructor);
      }
      return f.apply(this, arguments);
    };
    a.prototype = f.prototype;
  } else
    a = {};
  Object.defineProperty(a, "__esModule", { value: true });
  Object.keys(n).forEach(function(k) {
    var d = Object.getOwnPropertyDescriptor(n, k);
    Object.defineProperty(a, k, d.get ? d : {
      enumerable: true,
      get: function() {
        return n[k];
      }
    });
  });
  return a;
}
var categories = [
  {
    "name": "C",
    "alias": "Other",
    "isBmpLast": true,
    "bmp": "\0--Ÿ­͸͹΀-΃΋΍΢԰՗՘֋֌֐׈-׏׫-׮׵-؅؜۝܎܏݋݌޲-޿߻߼࠮࠯࠿࡜࡝࡟࡫-࡯࢏-ࢗ࣢঄঍঎঑঒঩঱঳-঵঺঻৅৆৉৊৏-৖৘-৛৞৤৥৿਀਄਋-਎਑਒਩਱਴਷਺਻਽੃-੆੉੊੎-੐੒-੘੝੟-੥੷-઀઄઎઒઩઱઴઺઻૆૊૎૏૑-૟૤૥૲-૸଀଄଍଎଑଒଩଱଴଺଻୅୆୉୊୎-୔୘-୛୞୤୥୸-஁஄஋-஍஑஖-஘஛஝஠-஢஥-஧஫-஭஺-஽௃-௅௉௎௏௑-௖௘-௥௻-௿఍఑఩఺఻౅౉౎-౔౗౛౜౞౟౤౥౰-౶಍಑಩಴಺಻೅೉೎-೔೗-೜೟೤೥೰ೳ-೿഍഑൅൉൐-൓൤൥඀඄඗-඙඲඼඾඿෇-෉෋-෎෕෗෠-෥෰෱෵-฀฻-฾๜-຀຃຅຋຤຦຾຿໅໇໎໏໚໛໠-໿཈཭-཰྘྽࿍࿛-࿿჆჈-჌჎჏቉቎቏቗቙቞቟኉኎኏኱኶኷኿዁዆዇዗጑጖጗፛፜፽-፿᎚-᎟᏶᏷᏾᏿᚝-᚟᛹-᛿᜖-᜞᜷-᜿᝔-᝟᝭᝱᝴-᝿៞៟៪-៯៺-៿᠎᠚-᠟᡹-᡿᢫-᢯᣶-᣿᤟᤬-᤯᤼-᤿᥁-᥃᥮᥯᥵-᥿᦬-᦯᧊-᧏᧛-᧝᨜᨝᩟᩽᩾᪊-᪏᪚-᪟᪮᪯᫏-᫿᭍-᭏᭿᯴-᯻᰸-᰺᱊-᱌Ᲊ-᲏᲻᲼᳈-᳏᳻-᳿἖἗἞἟὆὇὎὏὘὚὜὞὾὿᾵῅῔῕῜῰῱῵῿​-‏‪-‮⁠-⁲⁳₏₝-₟⃁-⃏⃱-⃿↌-↏␧-␿⑋-⑟⭴⭵⮖⳴-⳸⴦⴨-⴬⴮⴯⵨-⵮⵱-⵾⶗-⶟⶧⶯⶷⶿⷇⷏⷗⷟⹞-⹿⺚⻴-⻿⿖-⿯⿼-⿿぀゗゘㄀-㄄㄰㆏㇤-㇯㈟꒍-꒏꓇-꓏꘬-꘿꛸-꛿Ɤ-꟏꟒꟔Ꟛ-꟱꠭-꠯꠺-꠿꡸-꡿꣆-꣍꣚-꣟꥔-꥞꥽-꥿꧎꧚-꧝꧿꨷-꨿꩎꩏꩚꩛꫃-꫚꫷-꬀꬇꬈꬏꬐꬗-꬟꬧꬯꭬-꭯꯮꯯꯺-꯿힤-힯퟇-퟊퟼-﩮﩯﫚-﫿﬇-﬒﬘-﬜﬷﬽﬿﭂﭅﯃-﯒﶐﶑﷈-﷎﷐-﷯︚-︟﹓﹧﹬-﹯﹵﻽-＀﾿-￁￈￉￐￑￘￙￝-￟￧￯-￾￿",
    "astral": "\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDCFF\uDD03-\uDD06\uDD34-\uDD36\uDD8F\uDD9D-\uDD9F\uDDA1-\uDDCF\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEFC-\uDEFF\uDF24-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDFC4-\uDFC7\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDD6E\uDD7B\uDD8B\uDD93\uDD96\uDDA2\uDDB2\uDDBA\uDDBD-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDF7F\uDF86\uDFB1\uDFBB-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56\uDC9F-\uDCA6\uDCB0-\uDCDF\uDCF3\uDCF6-\uDCFA\uDD1C-\uDD1E\uDD3A-\uDD3E\uDD40-\uDD7F\uDDB8-\uDDBB\uDDD0\uDDD1\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE49-\uDE4F\uDE59-\uDE5F\uDEA0-\uDEBF\uDEE7-\uDEEA\uDEF7-\uDEFF\uDF36-\uDF38\uDF56\uDF57\uDF73-\uDF77\uDF92-\uDF98\uDF9D-\uDFA8\uDFB0-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCF9\uDD28-\uDD2F\uDD3A-\uDE5F\uDE7F\uDEAA\uDEAE\uDEAF\uDEB2-\uDEFF\uDF28-\uDF2F\uDF5A-\uDF6F\uDF8A-\uDFAF\uDFCC-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC4E-\uDC51\uDC76-\uDC7E\uDCBD\uDCC3-\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD48-\uDD4F\uDD77-\uDD7F\uDDE0\uDDF5-\uDDFF\uDE12\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEAA-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC5C\uDC62-\uDC7F\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDDE-\uDDFF\uDE45-\uDE4F\uDE5A-\uDE5F\uDE6D-\uDE7F\uDEBA-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF47-\uDFFF]|\uD806[\uDC3C-\uDC9F\uDCF3-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD47-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE5-\uDDFF\uDE48-\uDE4F\uDEA3-\uDEAF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC46-\uDC4F\uDC6D-\uDC6F\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF9-\uDFAF\uDFB1-\uDFBF\uDFF2-\uDFFE]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F\uDC75-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80E-\uD810\uD812-\uD819\uD824-\uD82A\uD82D\uD82E\uD830-\uD832\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDBFF][\uDC00-\uDFFF]|\uD80B[\uDC00-\uDF8F\uDFF3-\uDFFF]|\uD80D[\uDC2F-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDE6D\uDEBF\uDECA-\uDECF\uDEEE\uDEEF\uDEF6-\uDEFF\uDF46-\uDF4F\uDF5A\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE9B-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82B[\uDC00-\uDFEF\uDFF4\uDFFC\uDFFF]|\uD82C[\uDD23-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A\uDC9B\uDCA0-\uDFFF]|\uD833[\uDC00-\uDEFF\uDF2E\uDF2F\uDF47-\uDF4F\uDFC4-\uDFFF]|\uD834[\uDCF6-\uDCFF\uDD27\uDD28\uDD73-\uDD7A\uDDEB-\uDDFF\uDE46-\uDEDF\uDEF4-\uDEFF\uDF57-\uDF5F\uDF79-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]|\uD836[\uDE8C-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD837[\uDC00-\uDEFF\uDF1F-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD50-\uDE8F\uDEAF-\uDEBF\uDEFA-\uDEFE\uDF00-\uDFFF]|\uD839[\uDC00-\uDFDF\uDFE7\uDFEC\uDFEF\uDFFF]|\uD83A[\uDCC5\uDCC6\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDD5D\uDD60-\uDFFF]|\uD83B[\uDC00-\uDC70\uDCB5-\uDD00\uDD3E-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDEEF\uDEF2-\uDFFF]|\uD83C[\uDC2C-\uDC2F\uDC94-\uDC9F\uDCAF\uDCB0\uDCC0\uDCD0\uDCF6-\uDCFF\uDDAE-\uDDE5\uDE03-\uDE0F\uDE3C-\uDE3F\uDE49-\uDE4F\uDE52-\uDE5F\uDE66-\uDEFF]|\uD83D[\uDED8-\uDEDC\uDEED-\uDEEF\uDEFD-\uDEFF\uDF74-\uDF7F\uDFD9-\uDFDF\uDFEC-\uDFEF\uDFF1-\uDFFF]|\uD83E[\uDC0C-\uDC0F\uDC48-\uDC4F\uDC5A-\uDC5F\uDC88-\uDC8F\uDCAE\uDCAF\uDCB2-\uDCFF\uDE54-\uDE5F\uDE6E\uDE6F\uDE75-\uDE77\uDE7D-\uDE7F\uDE87-\uDE8F\uDEAD-\uDEAF\uDEBB-\uDEBF\uDEC6-\uDECF\uDEDA-\uDEDF\uDEE8-\uDEEF\uDEF7-\uDEFF\uDF93\uDFCB-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEE0-\uDEFF]|\uD86D[\uDF39-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00-\uDCFF\uDDF0-\uDFFF]"
  },
  {
    "name": "Cc",
    "alias": "Control",
    "bmp": "\0--Ÿ"
  },
  {
    "name": "Cf",
    "alias": "Format",
    "bmp": "­؀-؅؜۝܏࢐࢑࣢᠎​-‏‪-‮⁠-⁤⁦-\uFEFF-",
    "astral": "\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC38]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]"
  },
  {
    "name": "Cn",
    "alias": "Unassigned",
    "bmp": "͸͹΀-΃΋΍΢԰՗՘֋֌֐׈-׏׫-׮׵-׿܎݋݌޲-޿߻߼࠮࠯࠿࡜࡝࡟࡫-࡯࢏࢒-ࢗ঄঍঎঑঒঩঱঳-঵঺঻৅৆৉৊৏-৖৘-৛৞৤৥৿਀਄਋-਎਑਒਩਱਴਷਺਻਽੃-੆੉੊੎-੐੒-੘੝੟-੥੷-઀઄઎઒઩઱઴઺઻૆૊૎૏૑-૟૤૥૲-૸଀଄଍଎଑଒଩଱଴଺଻୅୆୉୊୎-୔୘-୛୞୤୥୸-஁஄஋-஍஑஖-஘஛஝஠-஢஥-஧஫-஭஺-஽௃-௅௉௎௏௑-௖௘-௥௻-௿఍఑఩఺఻౅౉౎-౔౗౛౜౞౟౤౥౰-౶಍಑಩಴಺಻೅೉೎-೔೗-೜೟೤೥೰ೳ-೿഍഑൅൉൐-൓൤൥඀඄඗-඙඲඼඾඿෇-෉෋-෎෕෗෠-෥෰෱෵-฀฻-฾๜-຀຃຅຋຤຦຾຿໅໇໎໏໚໛໠-໿཈཭-཰྘྽࿍࿛-࿿჆჈-჌჎჏቉቎቏቗቙቞቟኉኎኏኱኶኷኿዁዆዇዗጑጖጗፛፜፽-፿᎚-᎟᏶᏷᏾᏿᚝-᚟᛹-᛿᜖-᜞᜷-᜿᝔-᝟᝭᝱᝴-᝿៞៟៪-៯៺-៿᠚-᠟᡹-᡿᢫-᢯᣶-᣿᤟᤬-᤯᤼-᤿᥁-᥃᥮᥯᥵-᥿᦬-᦯᧊-᧏᧛-᧝᨜᨝᩟᩽᩾᪊-᪏᪚-᪟᪮᪯᫏-᫿᭍-᭏᭿᯴-᯻᰸-᰺᱊-᱌Ᲊ-᲏᲻᲼᳈-᳏᳻-᳿἖἗἞἟὆὇὎὏὘὚὜὞὾὿᾵῅῔῕῜῰῱῵῿⁥⁲⁳₏₝-₟⃁-⃏⃱-⃿↌-↏␧-␿⑋-⑟⭴⭵⮖⳴-⳸⴦⴨-⴬⴮⴯⵨-⵮⵱-⵾⶗-⶟⶧⶯⶷⶿⷇⷏⷗⷟⹞-⹿⺚⻴-⻿⿖-⿯⿼-⿿぀゗゘㄀-㄄㄰㆏㇤-㇯㈟꒍-꒏꓇-꓏꘬-꘿꛸-꛿Ɤ-꟏꟒꟔Ꟛ-꟱꠭-꠯꠺-꠿꡸-꡿꣆-꣍꣚-꣟꥔-꥞꥽-꥿꧎꧚-꧝꧿꨷-꨿꩎꩏꩚꩛꫃-꫚꫷-꬀꬇꬈꬏꬐꬗-꬟꬧꬯꭬-꭯꯮꯯꯺-꯿힤-힯퟇-퟊퟼-퟿﩮﩯﫚-﫿﬇-﬒﬘-﬜﬷﬽﬿﭂﭅﯃-﯒﶐﶑﷈-﷎﷐-﷯︚-︟﹓﹧﹬-﹯﹵﻽﻾＀﾿-￁￈￉￐￑￘￙￝-￟￧￯-￸￾￿",
    "astral": "\uD800[\uDC0C\uDC27\uDC3B\uDC3E\uDC4E\uDC4F\uDC5E-\uDC7F\uDCFB-\uDCFF\uDD03-\uDD06\uDD34-\uDD36\uDD8F\uDD9D-\uDD9F\uDDA1-\uDDCF\uDDFE-\uDE7F\uDE9D-\uDE9F\uDED1-\uDEDF\uDEFC-\uDEFF\uDF24-\uDF2C\uDF4B-\uDF4F\uDF7B-\uDF7F\uDF9E\uDFC4-\uDFC7\uDFD6-\uDFFF]|\uD801[\uDC9E\uDC9F\uDCAA-\uDCAF\uDCD4-\uDCD7\uDCFC-\uDCFF\uDD28-\uDD2F\uDD64-\uDD6E\uDD7B\uDD8B\uDD93\uDD96\uDDA2\uDDB2\uDDBA\uDDBD-\uDDFF\uDF37-\uDF3F\uDF56-\uDF5F\uDF68-\uDF7F\uDF86\uDFB1\uDFBB-\uDFFF]|\uD802[\uDC06\uDC07\uDC09\uDC36\uDC39-\uDC3B\uDC3D\uDC3E\uDC56\uDC9F-\uDCA6\uDCB0-\uDCDF\uDCF3\uDCF6-\uDCFA\uDD1C-\uDD1E\uDD3A-\uDD3E\uDD40-\uDD7F\uDDB8-\uDDBB\uDDD0\uDDD1\uDE04\uDE07-\uDE0B\uDE14\uDE18\uDE36\uDE37\uDE3B-\uDE3E\uDE49-\uDE4F\uDE59-\uDE5F\uDEA0-\uDEBF\uDEE7-\uDEEA\uDEF7-\uDEFF\uDF36-\uDF38\uDF56\uDF57\uDF73-\uDF77\uDF92-\uDF98\uDF9D-\uDFA8\uDFB0-\uDFFF]|\uD803[\uDC49-\uDC7F\uDCB3-\uDCBF\uDCF3-\uDCF9\uDD28-\uDD2F\uDD3A-\uDE5F\uDE7F\uDEAA\uDEAE\uDEAF\uDEB2-\uDEFF\uDF28-\uDF2F\uDF5A-\uDF6F\uDF8A-\uDFAF\uDFCC-\uDFDF\uDFF7-\uDFFF]|\uD804[\uDC4E-\uDC51\uDC76-\uDC7E\uDCC3-\uDCCC\uDCCE\uDCCF\uDCE9-\uDCEF\uDCFA-\uDCFF\uDD35\uDD48-\uDD4F\uDD77-\uDD7F\uDDE0\uDDF5-\uDDFF\uDE12\uDE3F-\uDE7F\uDE87\uDE89\uDE8E\uDE9E\uDEAA-\uDEAF\uDEEB-\uDEEF\uDEFA-\uDEFF\uDF04\uDF0D\uDF0E\uDF11\uDF12\uDF29\uDF31\uDF34\uDF3A\uDF45\uDF46\uDF49\uDF4A\uDF4E\uDF4F\uDF51-\uDF56\uDF58-\uDF5C\uDF64\uDF65\uDF6D-\uDF6F\uDF75-\uDFFF]|\uD805[\uDC5C\uDC62-\uDC7F\uDCC8-\uDCCF\uDCDA-\uDD7F\uDDB6\uDDB7\uDDDE-\uDDFF\uDE45-\uDE4F\uDE5A-\uDE5F\uDE6D-\uDE7F\uDEBA-\uDEBF\uDECA-\uDEFF\uDF1B\uDF1C\uDF2C-\uDF2F\uDF47-\uDFFF]|\uD806[\uDC3C-\uDC9F\uDCF3-\uDCFE\uDD07\uDD08\uDD0A\uDD0B\uDD14\uDD17\uDD36\uDD39\uDD3A\uDD47-\uDD4F\uDD5A-\uDD9F\uDDA8\uDDA9\uDDD8\uDDD9\uDDE5-\uDDFF\uDE48-\uDE4F\uDEA3-\uDEAF\uDEF9-\uDFFF]|\uD807[\uDC09\uDC37\uDC46-\uDC4F\uDC6D-\uDC6F\uDC90\uDC91\uDCA8\uDCB7-\uDCFF\uDD07\uDD0A\uDD37-\uDD39\uDD3B\uDD3E\uDD48-\uDD4F\uDD5A-\uDD5F\uDD66\uDD69\uDD8F\uDD92\uDD99-\uDD9F\uDDAA-\uDEDF\uDEF9-\uDFAF\uDFB1-\uDFBF\uDFF2-\uDFFE]|\uD808[\uDF9A-\uDFFF]|\uD809[\uDC6F\uDC75-\uDC7F\uDD44-\uDFFF]|[\uD80A\uD80E-\uD810\uD812-\uD819\uD824-\uD82A\uD82D\uD82E\uD830-\uD832\uD83F\uD87B-\uD87D\uD87F\uD885-\uDB3F\uDB41-\uDB7F][\uDC00-\uDFFF]|\uD80B[\uDC00-\uDF8F\uDFF3-\uDFFF]|\uD80D[\uDC2F\uDC39-\uDFFF]|\uD811[\uDE47-\uDFFF]|\uD81A[\uDE39-\uDE3F\uDE5F\uDE6A-\uDE6D\uDEBF\uDECA-\uDECF\uDEEE\uDEEF\uDEF6-\uDEFF\uDF46-\uDF4F\uDF5A\uDF62\uDF78-\uDF7C\uDF90-\uDFFF]|\uD81B[\uDC00-\uDE3F\uDE9B-\uDEFF\uDF4B-\uDF4E\uDF88-\uDF8E\uDFA0-\uDFDF\uDFE5-\uDFEF\uDFF2-\uDFFF]|\uD821[\uDFF8-\uDFFF]|\uD823[\uDCD6-\uDCFF\uDD09-\uDFFF]|\uD82B[\uDC00-\uDFEF\uDFF4\uDFFC\uDFFF]|\uD82C[\uDD23-\uDD4F\uDD53-\uDD63\uDD68-\uDD6F\uDEFC-\uDFFF]|\uD82F[\uDC6B-\uDC6F\uDC7D-\uDC7F\uDC89-\uDC8F\uDC9A\uDC9B\uDCA4-\uDFFF]|\uD833[\uDC00-\uDEFF\uDF2E\uDF2F\uDF47-\uDF4F\uDFC4-\uDFFF]|\uD834[\uDCF6-\uDCFF\uDD27\uDD28\uDDEB-\uDDFF\uDE46-\uDEDF\uDEF4-\uDEFF\uDF57-\uDF5F\uDF79-\uDFFF]|\uD835[\uDC55\uDC9D\uDCA0\uDCA1\uDCA3\uDCA4\uDCA7\uDCA8\uDCAD\uDCBA\uDCBC\uDCC4\uDD06\uDD0B\uDD0C\uDD15\uDD1D\uDD3A\uDD3F\uDD45\uDD47-\uDD49\uDD51\uDEA6\uDEA7\uDFCC\uDFCD]|\uD836[\uDE8C-\uDE9A\uDEA0\uDEB0-\uDFFF]|\uD837[\uDC00-\uDEFF\uDF1F-\uDFFF]|\uD838[\uDC07\uDC19\uDC1A\uDC22\uDC25\uDC2B-\uDCFF\uDD2D-\uDD2F\uDD3E\uDD3F\uDD4A-\uDD4D\uDD50-\uDE8F\uDEAF-\uDEBF\uDEFA-\uDEFE\uDF00-\uDFFF]|\uD839[\uDC00-\uDFDF\uDFE7\uDFEC\uDFEF\uDFFF]|\uD83A[\uDCC5\uDCC6\uDCD7-\uDCFF\uDD4C-\uDD4F\uDD5A-\uDD5D\uDD60-\uDFFF]|\uD83B[\uDC00-\uDC70\uDCB5-\uDD00\uDD3E-\uDDFF\uDE04\uDE20\uDE23\uDE25\uDE26\uDE28\uDE33\uDE38\uDE3A\uDE3C-\uDE41\uDE43-\uDE46\uDE48\uDE4A\uDE4C\uDE50\uDE53\uDE55\uDE56\uDE58\uDE5A\uDE5C\uDE5E\uDE60\uDE63\uDE65\uDE66\uDE6B\uDE73\uDE78\uDE7D\uDE7F\uDE8A\uDE9C-\uDEA0\uDEA4\uDEAA\uDEBC-\uDEEF\uDEF2-\uDFFF]|\uD83C[\uDC2C-\uDC2F\uDC94-\uDC9F\uDCAF\uDCB0\uDCC0\uDCD0\uDCF6-\uDCFF\uDDAE-\uDDE5\uDE03-\uDE0F\uDE3C-\uDE3F\uDE49-\uDE4F\uDE52-\uDE5F\uDE66-\uDEFF]|\uD83D[\uDED8-\uDEDC\uDEED-\uDEEF\uDEFD-\uDEFF\uDF74-\uDF7F\uDFD9-\uDFDF\uDFEC-\uDFEF\uDFF1-\uDFFF]|\uD83E[\uDC0C-\uDC0F\uDC48-\uDC4F\uDC5A-\uDC5F\uDC88-\uDC8F\uDCAE\uDCAF\uDCB2-\uDCFF\uDE54-\uDE5F\uDE6E\uDE6F\uDE75-\uDE77\uDE7D-\uDE7F\uDE87-\uDE8F\uDEAD-\uDEAF\uDEBB-\uDEBF\uDEC6-\uDECF\uDEDA-\uDEDF\uDEE8-\uDEEF\uDEF7-\uDEFF\uDF93\uDFCB-\uDFEF\uDFFA-\uDFFF]|\uD869[\uDEE0-\uDEFF]|\uD86D[\uDF39-\uDF3F]|\uD86E[\uDC1E\uDC1F]|\uD873[\uDEA2-\uDEAF]|\uD87A[\uDFE1-\uDFFF]|\uD87E[\uDE1E-\uDFFF]|\uD884[\uDF4B-\uDFFF]|\uDB40[\uDC00\uDC02-\uDC1F\uDC80-\uDCFF\uDDF0-\uDFFF]|[\uDBBF\uDBFF][\uDFFE\uDFFF]"
  },
  {
    "name": "Co",
    "alias": "Private_Use",
    "bmp": "-",
    "astral": "[\uDB80-\uDBBE\uDBC0-\uDBFE][\uDC00-\uDFFF]|[\uDBBF\uDBFF][\uDC00-\uDFFD]"
  },
  {
    "name": "Cs",
    "alias": "Surrogate",
    "bmp": "\uD800-\uDFFF"
  },
  {
    "name": "L",
    "alias": "Letter",
    "bmp": "A-Za-zªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛱ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢄᢇ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々〆〱-〵〻〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛥꜗ-ꜟꜢ-ꞈꞋ-ꟊꟐꟑꟓꟕ-ꟙꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",
    "astral": "\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A]"
  },
  {
    "name": "LC",
    "alias": "Cased_Letter",
    "bmp": "A-Za-zµÀ-ÖØ-öø-ƺƼ-ƿDŽ-ʓʕ-ʯͰ-ͳͶͷͻ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՠ-ֈႠ-ჅჇჍა-ჺჽ-ჿᎠ-Ᏽᏸ-ᏽᲀ-ᲈᲐ-ᲺᲽ-Ჿᴀ-ᴫᵫ-ᵷᵹ-ᶚḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℴℹℼ-ℿⅅ-ⅉⅎↃↄⰀ-ⱻⱾ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭꙀ-ꙭꚀ-ꚛꜢ-ꝯꝱ-ꞇꞋ-ꞎꞐ-ꟊꟐꟑꟓꟕ-ꟙꟵꟶꟺꬰ-ꭚꭠ-ꭨꭰ-ꮿff-stﬓ-ﬗA-Za-z",
    "astral": "\uD801[\uDC00-\uDC4F\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC]|\uD803[\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD806[\uDCA0-\uDCDF]|\uD81B[\uDE40-\uDE7F]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF09\uDF0B-\uDF1E]|\uD83A[\uDD00-\uDD43]"
  },
  {
    "name": "Ll",
    "alias": "Lowercase_Letter",
    "bmp": "a-zµß-öø-ÿāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįıijĵķĸĺļľŀłńņňʼnŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž-ƀƃƅƈƌƍƒƕƙ-ƛƞơƣƥƨƪƫƭưƴƶƹƺƽ-ƿdžljnjǎǐǒǔǖǘǚǜǝǟǡǣǥǧǩǫǭǯǰdzǵǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟȡȣȥȧȩȫȭȯȱȳ-ȹȼȿɀɂɇɉɋɍɏ-ʓʕ-ʯͱͳͷͻ-ͽΐά-ώϐϑϕ-ϗϙϛϝϟϡϣϥϧϩϫϭϯ-ϳϵϸϻϼа-џѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӏӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯՠ-ֈა-ჺჽ-ჿᏸ-ᏽᲀ-ᲈᴀ-ᴫᵫ-ᵷᵹ-ᶚḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕ-ẝẟạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿ-ἇἐ-ἕἠ-ἧἰ-ἷὀ-ὅὐ-ὗὠ-ὧὰ-ώᾀ-ᾇᾐ-ᾗᾠ-ᾧᾰ-ᾴᾶᾷιῂ-ῄῆῇῐ-ΐῖῗῠ-ῧῲ-ῴῶῷℊℎℏℓℯℴℹℼℽⅆ-ⅉⅎↄⰰ-ⱟⱡⱥⱦⱨⱪⱬⱱⱳⱴⱶ-ⱻⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳤⳬⳮⳳⴀ-ⴥⴧⴭꙁꙃꙅꙇꙉꙋꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛꜣꜥꜧꜩꜫꜭꜯ-ꜱꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝱ-ꝸꝺꝼꝿꞁꞃꞅꞇꞌꞎꞑꞓ-ꞕꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩꞯꞵꞷꞹꞻꞽꞿꟁꟃꟈꟊꟑꟓꟕꟗꟙꟶꟺꬰ-ꭚꭠ-ꭨꭰ-ꮿff-stﬓ-ﬗa-z",
    "astral": "\uD801[\uDC28-\uDC4F\uDCD8-\uDCFB\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC]|\uD803[\uDCC0-\uDCF2]|\uD806[\uDCC0-\uDCDF]|\uD81B[\uDE60-\uDE7F]|\uD835[\uDC1A-\uDC33\uDC4E-\uDC54\uDC56-\uDC67\uDC82-\uDC9B\uDCB6-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDCEA-\uDD03\uDD1E-\uDD37\uDD52-\uDD6B\uDD86-\uDD9F\uDDBA-\uDDD3\uDDEE-\uDE07\uDE22-\uDE3B\uDE56-\uDE6F\uDE8A-\uDEA5\uDEC2-\uDEDA\uDEDC-\uDEE1\uDEFC-\uDF14\uDF16-\uDF1B\uDF36-\uDF4E\uDF50-\uDF55\uDF70-\uDF88\uDF8A-\uDF8F\uDFAA-\uDFC2\uDFC4-\uDFC9\uDFCB]|\uD837[\uDF00-\uDF09\uDF0B-\uDF1E]|\uD83A[\uDD22-\uDD43]"
  },
  {
    "name": "Lm",
    "alias": "Modifier_Letter",
    "bmp": "ʰ-ˁˆ-ˑˠ-ˤˬˮʹͺՙـۥۦߴߵߺࠚࠤࠨࣉॱๆໆჼៗᡃᪧᱸ-ᱽᴬ-ᵪᵸᶛ-ᶿⁱⁿₐ-ₜⱼⱽⵯⸯ々〱-〵〻ゝゞー-ヾꀕꓸ-ꓽꘌꙿꚜꚝꜗ-ꜟꝰꞈꟲ-ꟴꟸꟹꧏꧦꩰꫝꫳꫴꭜ-ꭟꭩー゙゚",
    "astral": "\uD801[\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD81A[\uDF40-\uDF43]|\uD81B[\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD838[\uDD37-\uDD3D]|𞥋"
  },
  {
    "name": "Lo",
    "alias": "Other_Letter",
    "bmp": "ªºƻǀ-ǃʔא-תׯ-ײؠ-ؿف-يٮٯٱ-ۓەۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪࠀ-ࠕࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣈऄ-हऽॐक़-ॡॲ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๅກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎᄀ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛱ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៜᠠ-ᡂᡄ-ᡸᢀ-ᢄᢇ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱷᳩ-ᳬᳮ-ᳳᳵᳶᳺℵ-ℸⴰ-ⵧⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ〆〼ぁ-ゖゟァ-ヺヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꀔꀖ-ꒌꓐ-ꓷꔀ-ꘋꘐ-ꘟꘪꘫꙮꚠ-ꛥꞏꟷꟻ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧠ-ꧤꧧ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩯꩱ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛꫜꫠ-ꫪꫲꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎יִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼヲ-ッア-ンᅠ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",
    "astral": "\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC50-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDD00-\uDD23\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDEB8\uDF00-\uDF1A\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDEE0-\uDEF2\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF4A\uDF50]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|𝼊|\uD838[\uDD00-\uDD2C\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A]"
  },
  {
    "name": "Lt",
    "alias": "Titlecase_Letter",
    "bmp": "DžLjNjDzᾈ-ᾏᾘ-ᾟᾨ-ᾯᾼῌῼ"
  },
  {
    "name": "Lu",
    "alias": "Uppercase_Letter",
    "bmp": "A-ZÀ-ÖØ-ÞĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮİIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŸŹŻŽƁƂƄƆƇƉ-ƋƎ-ƑƓƔƖ-ƘƜƝƟƠƢƤƦƧƩƬƮƯƱ-ƳƵƷƸƼDŽLJNJǍǏǑǓǕǗǙǛǞǠǢǤǦǨǪǬǮDZǴǶ-ǸǺǼǾȀȂȄȆȈȊȌȎȐȒȔȖȘȚȜȞȠȢȤȦȨȪȬȮȰȲȺȻȽȾɁɃ-ɆɈɊɌɎͰͲͶͿΆΈ-ΊΌΎΏΑ-ΡΣ-ΫϏϒ-ϔϘϚϜϞϠϢϤϦϨϪϬϮϴϷϹϺϽ-ЯѠѢѤѦѨѪѬѮѰѲѴѶѸѺѼѾҀҊҌҎҐҒҔҖҘҚҜҞҠҢҤҦҨҪҬҮҰҲҴҶҸҺҼҾӀӁӃӅӇӉӋӍӐӒӔӖӘӚӜӞӠӢӤӦӨӪӬӮӰӲӴӶӸӺӼӾԀԂԄԆԈԊԌԎԐԒԔԖԘԚԜԞԠԢԤԦԨԪԬԮԱ-ՖႠ-ჅჇჍᎠ-ᏵᲐ-ᲺᲽ-ᲿḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẞẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸỺỼỾἈ-ἏἘ-ἝἨ-ἯἸ-ἿὈ-ὍὙὛὝὟὨ-ὯᾸ-ΆῈ-ΉῘ-ΊῨ-ῬῸ-Ώℂℇℋ-ℍℐ-ℒℕℙ-ℝℤΩℨK-ℭℰ-ℳℾℿⅅↃⰀ-ⰯⱠⱢ-ⱤⱧⱩⱫⱭ-ⱰⱲⱵⱾ-ⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢⳫⳭⳲꙀꙂꙄꙆꙈꙊꙌꙎꙐꙒꙔꙖꙘꙚꙜꙞꙠꙢꙤꙦꙨꙪꙬꚀꚂꚄꚆꚈꚊꚌꚎꚐꚒꚔꚖꚘꚚꜢꜤꜦꜨꜪꜬꜮꜲꜴꜶꜸꜺꜼꜾꝀꝂꝄꝆꝈꝊꝌꝎꝐꝒꝔꝖꝘꝚꝜꝞꝠꝢꝤꝦꝨꝪꝬꝮꝹꝻꝽꝾꞀꞂꞄꞆꞋꞍꞐꞒꞖꞘꞚꞜꞞꞠꞢꞤꞦꞨꞪ-ꞮꞰ-ꞴꞶꞸꞺꞼꞾꟀꟂꟄ-ꟇꟉꟐꟖꟘꟵA-Z",
    "astral": "\uD801[\uDC00-\uDC27\uDCB0-\uDCD3\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95]|\uD803[\uDC80-\uDCB2]|\uD806[\uDCA0-\uDCBF]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA]|\uD83A[\uDD00-\uDD21]"
  },
  {
    "name": "M",
    "alias": "Mark",
    "bmp": "̀-ͯ҃-҉֑-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࢘-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣඁ-ඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍᠏ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-ᫎᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿⃐-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯-꙲ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯",
    "astral": "\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDEAB\uDEAC\uDF46-\uDF50\uDF82-\uDF85]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC70\uDC73\uDC74\uDC7F-\uDC82\uDCB0-\uDCBA\uDCC2\uDD00-\uDD02\uDD27-\uDD34\uDD45\uDD46\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDDC9-\uDDCC\uDDCE\uDDCF\uDE2C-\uDE37\uDE3E\uDEDF-\uDEEA\uDF00-\uDF03\uDF3B\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC35-\uDC46\uDC5E\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDDDC\uDDDD\uDE30-\uDE40\uDEAB-\uDEB7\uDF1D-\uDF2B]|\uD806[\uDC2C-\uDC3A\uDD30-\uDD35\uDD37\uDD38\uDD3B-\uDD3E\uDD40\uDD42\uDD43\uDDD1-\uDDD7\uDDDA-\uDDE0\uDDE4\uDE01-\uDE0A\uDE33-\uDE39\uDE3B-\uDE3E\uDE47\uDE51-\uDE5B\uDE8A-\uDE99]|\uD807[\uDC2F-\uDC36\uDC38-\uDC3F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD45\uDD47\uDD8A-\uDD8E\uDD90\uDD91\uDD93-\uDD97\uDEF3-\uDEF6]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF4F\uDF51-\uDF87\uDF8F-\uDF92\uDFE4\uDFF0\uDFF1]|\uD82F[\uDC9D\uDC9E]|\uD833[\uDF00-\uDF2D\uDF30-\uDF46]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A\uDD30-\uDD36\uDEAE\uDEEC-\uDEEF]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A]|\uDB40[\uDD00-\uDDEF]"
  },
  {
    "name": "Mc",
    "alias": "Spacing_Mark",
    "bmp": "ःऻा-ीॉ-ौॎॏংঃা-ীেৈোৌৗਃਾ-ੀઃા-ીૉોૌଂଃାୀେୈୋୌୗாிுூெ-ைொ-ௌௗఁ-ఃు-ౄಂಃಾೀ-ೄೇೈೊೋೕೖംഃാ-ീെ-ൈൊ-ൌൗංඃා-ෑෘ-ෟෲෳ༾༿ཿါာေးျြၖၗၢ-ၤၧ-ၭႃႄႇ-ႌႏႚ-ႜ᜕᜴ាើ-ៅះៈᤣ-ᤦᤩ-ᤫᤰᤱᤳ-ᤸᨙᨚᩕᩗᩡᩣᩤᩭ-ᩲᬄᬵᬻᬽ-ᭁᭃ᭄ᮂᮡᮦᮧ᮪ᯧᯪ-ᯬᯮ᯲᯳ᰤ-ᰫᰴᰵ᳡᳷〮〯ꠣꠤꠧꢀꢁꢴ-ꣃꥒ꥓ꦃꦴꦵꦺꦻꦾ-꧀ꨯꨰꨳꨴꩍꩻꩽꫫꫮꫯꫵꯣꯤꯦꯧꯩꯪ꯬",
    "astral": "\uD804[\uDC00\uDC02\uDC82\uDCB0-\uDCB2\uDCB7\uDCB8\uDD2C\uDD45\uDD46\uDD82\uDDB3-\uDDB5\uDDBF\uDDC0\uDDCE\uDE2C-\uDE2E\uDE32\uDE33\uDE35\uDEE0-\uDEE2\uDF02\uDF03\uDF3E\uDF3F\uDF41-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63]|\uD805[\uDC35-\uDC37\uDC40\uDC41\uDC45\uDCB0-\uDCB2\uDCB9\uDCBB-\uDCBE\uDCC1\uDDAF-\uDDB1\uDDB8-\uDDBB\uDDBE\uDE30-\uDE32\uDE3B\uDE3C\uDE3E\uDEAC\uDEAE\uDEAF\uDEB6\uDF20\uDF21\uDF26]|\uD806[\uDC2C-\uDC2E\uDC38\uDD30-\uDD35\uDD37\uDD38\uDD3D\uDD40\uDD42\uDDD1-\uDDD3\uDDDC-\uDDDF\uDDE4\uDE39\uDE57\uDE58\uDE97]|\uD807[\uDC2F\uDC3E\uDCA9\uDCB1\uDCB4\uDD8A-\uDD8E\uDD93\uDD94\uDD96\uDEF5\uDEF6]|\uD81B[\uDF51-\uDF87\uDFF0\uDFF1]|\uD834[\uDD65\uDD66\uDD6D-\uDD72]"
  },
  {
    "name": "Me",
    "alias": "Enclosing_Mark",
    "bmp": "҈҉᪾⃝-⃠⃢-⃤꙰-꙲"
  },
  {
    "name": "Mn",
    "alias": "Nonspacing_Mark",
    "bmp": "̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࢘-࢟࣊-ࣣ࣡-ंऺ़ु-ै्॑-ॗॢॣঁ়ু-ৄ্ৢৣ৾ਁਂ਼ੁੂੇੈੋ-੍ੑੰੱੵઁં઼ુ-ૅેૈ્ૢૣૺ-૿ଁ଼ିୁ-ୄ୍୕ୖୢୣஂீ்ఀఄ఼ా-ీె-ైొ-్ౕౖౢౣಁ಼ಿೆೌ್ೢೣഀഁ഻഼ു-ൄ്ൢൣඁ්ි-ුූัิ-ฺ็-๎ັິ-ຼ່-ໍཱ༹༘༙༵༷-ཾྀ-྄྆྇ྍ-ྗྙ-ྼ࿆ိ-ူဲ-့္်ွှၘၙၞ-ၠၱ-ၴႂႅႆႍႝ፝-፟ᜒ-᜔ᜲᜳᝒᝓᝲᝳ឴឵ិ-ួំ៉-៓៝᠋-᠍᠏ᢅᢆᢩᤠ-ᤢᤧᤨᤲ᤹-᤻ᨘᨗᨛᩖᩘ-ᩞ᩠ᩢᩥ-ᩬᩳ-᩿᩼᪰-᪽ᪿ-ᫎᬀ-ᬃ᬴ᬶ-ᬺᬼᭂ᭫-᭳ᮀᮁᮢ-ᮥᮨᮩ᮫-ᮭ᯦ᯨᯩᯭᯯ-ᯱᰬ-ᰳᰶ᰷᳐-᳔᳒-᳢᳠-᳨᳭᳴᳸᳹᷀-᷿⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〭꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠥꠦ꠬꣄ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-ꥑꦀ-ꦂ꦳ꦶ-ꦹꦼꦽꧥꨩ-ꨮꨱꨲꨵꨶꩃꩌꩼꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫬꫭ꫶ꯥꯨ꯭ﬞ︀-️︠-︯",
    "astral": "\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD803[\uDD24-\uDD27\uDEAB\uDEAC\uDF46-\uDF50\uDF82-\uDF85]|\uD804[\uDC01\uDC38-\uDC46\uDC70\uDC73\uDC74\uDC7F-\uDC81\uDCB3-\uDCB6\uDCB9\uDCBA\uDCC2\uDD00-\uDD02\uDD27-\uDD2B\uDD2D-\uDD34\uDD73\uDD80\uDD81\uDDB6-\uDDBE\uDDC9-\uDDCC\uDDCF\uDE2F-\uDE31\uDE34\uDE36\uDE37\uDE3E\uDEDF\uDEE3-\uDEEA\uDF00\uDF01\uDF3B\uDF3C\uDF40\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC38-\uDC3F\uDC42-\uDC44\uDC46\uDC5E\uDCB3-\uDCB8\uDCBA\uDCBF\uDCC0\uDCC2\uDCC3\uDDB2-\uDDB5\uDDBC\uDDBD\uDDBF\uDDC0\uDDDC\uDDDD\uDE33-\uDE3A\uDE3D\uDE3F\uDE40\uDEAB\uDEAD\uDEB0-\uDEB5\uDEB7\uDF1D-\uDF1F\uDF22-\uDF25\uDF27-\uDF2B]|\uD806[\uDC2F-\uDC37\uDC39\uDC3A\uDD3B\uDD3C\uDD3E\uDD43\uDDD4-\uDDD7\uDDDA\uDDDB\uDDE0\uDE01-\uDE0A\uDE33-\uDE38\uDE3B-\uDE3E\uDE47\uDE51-\uDE56\uDE59-\uDE5B\uDE8A-\uDE96\uDE98\uDE99]|\uD807[\uDC30-\uDC36\uDC38-\uDC3D\uDC3F\uDC92-\uDCA7\uDCAA-\uDCB0\uDCB2\uDCB3\uDCB5\uDCB6\uDD31-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD45\uDD47\uDD90\uDD91\uDD95\uDD97\uDEF3\uDEF4]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF4F\uDF8F-\uDF92\uDFE4]|\uD82F[\uDC9D\uDC9E]|\uD833[\uDF00-\uDF2D\uDF30-\uDF46]|\uD834[\uDD67-\uDD69\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A\uDD30-\uDD36\uDEAE\uDEEC-\uDEEF]|\uD83A[\uDCD0-\uDCD6\uDD44-\uDD4A]|\uDB40[\uDD00-\uDDEF]"
  },
  {
    "name": "N",
    "alias": "Number",
    "bmp": "0-9²³¹¼-¾٠-٩۰-۹߀-߉०-९০-৯৴-৹੦-੯૦-૯୦-୯୲-୷௦-௲౦-౯౸-౾೦-೯൘-൞൦-൸෦-෯๐-๙໐-໙༠-༳၀-၉႐-႙፩-፼ᛮ-ᛰ០-៩៰-៹᠐-᠙᥆-᥏᧐-᧚᪀-᪉᪐-᪙᭐-᭙᮰-᮹᱀-᱉᱐-᱙⁰⁴-⁹₀-₉⅐-ↂↅ-↉①-⒛⓪-⓿❶-➓⳽〇〡-〩〸-〺㆒-㆕㈠-㈩㉈-㉏㉑-㉟㊀-㊉㊱-㊿꘠-꘩ꛦ-ꛯ꠰-꠵꣐-꣙꤀-꤉꧐-꧙꧰-꧹꩐-꩙꯰-꯹0-9",
    "astral": "\uD800[\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDEE1-\uDEFB\uDF20-\uDF23\uDF41\uDF4A\uDFD1-\uDFD5]|\uD801[\uDCA0-\uDCA9]|\uD802[\uDC58-\uDC5F\uDC79-\uDC7F\uDCA7-\uDCAF\uDCFB-\uDCFF\uDD16-\uDD1B\uDDBC\uDDBD\uDDC0-\uDDCF\uDDD2-\uDDFF\uDE40-\uDE48\uDE7D\uDE7E\uDE9D-\uDE9F\uDEEB-\uDEEF\uDF58-\uDF5F\uDF78-\uDF7F\uDFA9-\uDFAF]|\uD803[\uDCFA-\uDCFF\uDD30-\uDD39\uDE60-\uDE7E\uDF1D-\uDF26\uDF51-\uDF54\uDFC5-\uDFCB]|\uD804[\uDC52-\uDC6F\uDCF0-\uDCF9\uDD36-\uDD3F\uDDD0-\uDDD9\uDDE1-\uDDF4\uDEF0-\uDEF9]|\uD805[\uDC50-\uDC59\uDCD0-\uDCD9\uDE50-\uDE59\uDEC0-\uDEC9\uDF30-\uDF3B]|\uD806[\uDCE0-\uDCF2\uDD50-\uDD59]|\uD807[\uDC50-\uDC6C\uDD50-\uDD59\uDDA0-\uDDA9\uDFC0-\uDFD4]|\uD809[\uDC00-\uDC6E]|\uD81A[\uDE60-\uDE69\uDEC0-\uDEC9\uDF50-\uDF59\uDF5B-\uDF61]|\uD81B[\uDE80-\uDE96]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDFCE-\uDFFF]|\uD838[\uDD40-\uDD49\uDEF0-\uDEF9]|\uD83A[\uDCC7-\uDCCF\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]"
  },
  {
    "name": "Nd",
    "alias": "Decimal_Number",
    "bmp": "0-9٠-٩۰-۹߀-߉०-९০-৯੦-੯૦-૯୦-୯௦-௯౦-౯೦-೯൦-൯෦-෯๐-๙໐-໙༠-༩၀-၉႐-႙០-៩᠐-᠙᥆-᥏᧐-᧙᪀-᪉᪐-᪙᭐-᭙᮰-᮹᱀-᱉᱐-᱙꘠-꘩꣐-꣙꤀-꤉꧐-꧙꧰-꧹꩐-꩙꯰-꯹0-9",
    "astral": "\uD801[\uDCA0-\uDCA9]|\uD803[\uDD30-\uDD39]|\uD804[\uDC66-\uDC6F\uDCF0-\uDCF9\uDD36-\uDD3F\uDDD0-\uDDD9\uDEF0-\uDEF9]|\uD805[\uDC50-\uDC59\uDCD0-\uDCD9\uDE50-\uDE59\uDEC0-\uDEC9\uDF30-\uDF39]|\uD806[\uDCE0-\uDCE9\uDD50-\uDD59]|\uD807[\uDC50-\uDC59\uDD50-\uDD59\uDDA0-\uDDA9]|\uD81A[\uDE60-\uDE69\uDEC0-\uDEC9\uDF50-\uDF59]|\uD835[\uDFCE-\uDFFF]|\uD838[\uDD40-\uDD49\uDEF0-\uDEF9]|\uD83A[\uDD50-\uDD59]|\uD83E[\uDFF0-\uDFF9]"
  },
  {
    "name": "Nl",
    "alias": "Letter_Number",
    "bmp": "ᛮ-ᛰⅠ-ↂↅ-ↈ〇〡-〩〸-〺ꛦ-ꛯ",
    "astral": "\uD800[\uDD40-\uDD74\uDF41\uDF4A\uDFD1-\uDFD5]|\uD809[\uDC00-\uDC6E]"
  },
  {
    "name": "No",
    "alias": "Other_Number",
    "bmp": "²³¹¼-¾৴-৹୲-୷௰-௲౸-౾൘-൞൰-൸༪-༳፩-፼៰-៹᧚⁰⁴-⁹₀-₉⅐-⅟↉①-⒛⓪-⓿❶-➓⳽㆒-㆕㈠-㈩㉈-㉏㉑-㉟㊀-㊉㊱-㊿꠰-꠵",
    "astral": "\uD800[\uDD07-\uDD33\uDD75-\uDD78\uDD8A\uDD8B\uDEE1-\uDEFB\uDF20-\uDF23]|\uD802[\uDC58-\uDC5F\uDC79-\uDC7F\uDCA7-\uDCAF\uDCFB-\uDCFF\uDD16-\uDD1B\uDDBC\uDDBD\uDDC0-\uDDCF\uDDD2-\uDDFF\uDE40-\uDE48\uDE7D\uDE7E\uDE9D-\uDE9F\uDEEB-\uDEEF\uDF58-\uDF5F\uDF78-\uDF7F\uDFA9-\uDFAF]|\uD803[\uDCFA-\uDCFF\uDE60-\uDE7E\uDF1D-\uDF26\uDF51-\uDF54\uDFC5-\uDFCB]|\uD804[\uDC52-\uDC65\uDDE1-\uDDF4]|\uD805[\uDF3A\uDF3B]|\uD806[\uDCEA-\uDCF2]|\uD807[\uDC5A-\uDC6C\uDFC0-\uDFD4]|\uD81A[\uDF5B-\uDF61]|\uD81B[\uDE80-\uDE96]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD83A[\uDCC7-\uDCCF]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D]|\uD83C[\uDD00-\uDD0C]"
  },
  {
    "name": "P",
    "alias": "Punctuation",
    "bmp": "!-#%-\\*,-\\/:;\\?@\\[-\\]_\\{\\}¡§«¶·»¿;·՚-՟։֊־׀׃׆׳״؉؊،؍؛؝-؟٪-٭۔܀-܍߷-߹࠰-࠾࡞।॥॰৽੶૰౷಄෴๏๚๛༄-༒༔༺-༽྅࿐-࿔࿙࿚၊-၏჻፠-፨᐀᙮᚛᚜᛫-᛭᜵᜶។-៖៘-៚᠀-᠊᥄᥅᨞᨟᪠-᪦᪨-᪭᭚-᭠᭽᭾᯼-᯿᰻-᰿᱾᱿᳀-᳇᳓‐-‧‰-⁃⁅-⁑⁓-⁞⁽⁾₍₎⌈-⌋〈〉❨-❵⟅⟆⟦-⟯⦃-⦘⧘-⧛⧼⧽⳹-⳼⳾⳿⵰⸀-⸮⸰-⹏⹒-⹝、-〃〈-】〔-〟〰〽゠・꓾꓿꘍-꘏꙳꙾꛲-꛷꡴-꡷꣎꣏꣸-꣺꣼꤮꤯꥟꧁-꧍꧞꧟꩜-꩟꫞꫟꫰꫱꯫﴾﴿︐-︙︰-﹒﹔-﹡﹣﹨﹪﹫!-#%-*,-/:;?@[-]_{}⦅-・",
    "astral": "\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|𐕯|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDEAD\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|𛲟|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]"
  },
  {
    "name": "Pc",
    "alias": "Connector_Punctuation",
    "bmp": "_‿⁀⁔︳︴﹍-﹏_"
  },
  {
    "name": "Pd",
    "alias": "Dash_Punctuation",
    "bmp": "\\-֊־᐀᠆‐-―⸗⸚⸺⸻⹀⹝〜〰゠︱︲﹘﹣-",
    "astral": "𐺭"
  },
  {
    "name": "Pe",
    "alias": "Close_Punctuation",
    "bmp": "\\)\\]\\}༻༽᚜⁆⁾₎⌉⌋〉❩❫❭❯❱❳❵⟆⟧⟩⟫⟭⟯⦄⦆⦈⦊⦌⦎⦐⦒⦔⦖⦘⧙⧛⧽⸣⸥⸧⸩⹖⹘⹚⹜〉》」』】〕〗〙〛〞〟﴾︘︶︸︺︼︾﹀﹂﹄﹈﹚﹜﹞)]}⦆」"
  },
  {
    "name": "Pf",
    "alias": "Final_Punctuation",
    "bmp": "»’”›⸃⸅⸊⸍⸝⸡"
  },
  {
    "name": "Pi",
    "alias": "Initial_Punctuation",
    "bmp": "«‘‛“‟‹⸂⸄⸉⸌⸜⸠"
  },
  {
    "name": "Po",
    "alias": "Other_Punctuation",
    "bmp": "!-#%-'\\*,\\.\\/:;\\?@\\¡§¶·¿;·՚-՟։׀׃׆׳״؉؊،؍؛؝-؟٪-٭۔܀-܍߷-߹࠰-࠾࡞।॥॰৽੶૰౷಄෴๏๚๛༄-༒༔྅࿐-࿔࿙࿚၊-၏჻፠-፨᙮᛫-᛭᜵᜶។-៖៘-៚᠀-᠅᠇-᠊᥄᥅᨞᨟᪠-᪦᪨-᪭᭚-᭠᭽᭾᯼-᯿᰻-᰿᱾᱿᳀-᳇᳓‖‗†-‧‰-‸※-‾⁁-⁃⁇-⁑⁓⁕-⁞⳹-⳼⳾⳿⵰⸀⸁⸆-⸈⸋⸎-⸖⸘⸙⸛⸞⸟⸪-⸮⸰-⸹⸼-⸿⹁⹃-⹏⹒-⹔、-〃〽・꓾꓿꘍-꘏꙳꙾꛲-꛷꡴-꡷꣎꣏꣸-꣺꣼꤮꤯꥟꧁-꧍꧞꧟꩜-꩟꫞꫟꫰꫱꯫︐-︖︙︰﹅﹆﹉-﹌﹐-﹒﹔-﹗﹟-﹡﹨﹪﹫!-#%-'*,./:;?@\。、・",
    "astral": "\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|𐕯|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59\uDF86-\uDF89]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5A\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDEB9\uDF3C-\uDF3E]|\uD806[\uDC3B\uDD44-\uDD46\uDDE2\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8\uDFFF]|\uD809[\uDC70-\uDC74]|\uD80B[\uDFF1\uDFF2]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A\uDFE2]|𛲟|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]"
  },
  {
    "name": "Ps",
    "alias": "Open_Punctuation",
    "bmp": "\\(\\[\\{༺༼᚛‚„⁅⁽₍⌈⌊〈❨❪❬❮❰❲❴⟅⟦⟨⟪⟬⟮⦃⦅⦇⦉⦋⦍⦏⦑⦓⦕⦗⧘⧚⧼⸢⸤⸦⸨⹂⹕⹗⹙⹛〈《「『【〔〖〘〚〝﴿︗︵︷︹︻︽︿﹁﹃﹇﹙﹛﹝([{⦅「"
  },
  {
    "name": "S",
    "alias": "Symbol",
    "bmp": "\\$\\+<->\\^`\\|~¢-¦¨©¬®-±´¸×÷˂-˅˒-˟˥-˫˭˯-˿͵΄΅϶҂֍-֏؆-؈؋؎؏۞۩۽۾߶߾߿࢈৲৳৺৻૱୰௳-௺౿൏൹฿༁-༃༓༕-༗༚-༟༴༶༸྾-࿅࿇-࿌࿎࿏࿕-࿘႞႟᎐-᎙᙭៛᥀᧞-᧿᭡-᭪᭴-᭼᾽᾿-῁῍-῏῝-῟῭-`´῾⁄⁒⁺-⁼₊-₌₠-⃀℀℁℃-℆℈℉℔№-℘℞-℣℥℧℩℮℺℻⅀-⅄⅊-⅍⅏↊↋←-⌇⌌-⌨⌫-␦⑀-⑊⒜-ⓩ─-❧➔-⟄⟇-⟥⟰-⦂⦙-⧗⧜-⧻⧾-⭳⭶-⮕⮗-⯿⳥-⳪⹐⹑⺀-⺙⺛-⻳⼀-⿕⿰-⿻〄〒〓〠〶〷〾〿゛゜㆐㆑㆖-㆟㇀-㇣㈀-㈞㈪-㉇㉐㉠-㉿㊊-㊰㋀-㏿䷀-䷿꒐-꓆꜀-꜖꜠꜡꞉꞊꠨-꠫꠶-꠹꩷-꩹꭛꭪꭫﬩﮲-﯂﵀-﵏﷏﷼-﷿﹢﹤-﹦﹩$+<->^`|~¢-₩│-○�",
    "astral": "\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|𑜿|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|𛲜|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDD-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF73\uDF80-\uDFD8\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE74\uDE78-\uDE7C\uDE80-\uDE86\uDE90-\uDEAC\uDEB0-\uDEBA\uDEC0-\uDEC5\uDED0-\uDED9\uDEE0-\uDEE7\uDEF0-\uDEF6\uDF00-\uDF92\uDF94-\uDFCA]"
  },
  {
    "name": "Sc",
    "alias": "Currency_Symbol",
    "bmp": "\\$¢-¥֏؋߾߿৲৳৻૱௹฿៛₠-⃀꠸﷼﹩$¢£¥₩",
    "astral": "\uD807[\uDFDD-\uDFE0]|𞋿|𞲰"
  },
  {
    "name": "Sk",
    "alias": "Modifier_Symbol",
    "bmp": "\\^`¨¯´¸˂-˅˒-˟˥-˫˭˯-˿͵΄΅࢈᾽᾿-῁῍-῏῝-῟῭-`´῾゛゜꜀-꜖꜠꜡꞉꞊꭛꭪꭫﮲-﯂^` ̄",
    "astral": "\uD83C[\uDFFB-\uDFFF]"
  },
  {
    "name": "Sm",
    "alias": "Math_Symbol",
    "bmp": "\\+<->\\|~¬±×÷϶؆-؈⁄⁒⁺-⁼₊-₌℘⅀-⅄⅋←-↔↚↛↠↣↦↮⇎⇏⇒⇔⇴-⋿⌠⌡⍼⎛-⎳⏜-⏡▷◁◸-◿♯⟀-⟄⟇-⟥⟰-⟿⤀-⦂⦙-⧗⧜-⧻⧾-⫿⬰-⭄⭇-⭌﬩﹢﹤-﹦+<->|~¬←-↓",
    "astral": "\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD83B[\uDEF0\uDEF1]"
  },
  {
    "name": "So",
    "alias": "Other_Symbol",
    "bmp": "¦©®°҂֍֎؎؏۞۩۽۾߶৺୰௳-௸௺౿൏൹༁-༃༓༕-༗༚-༟༴༶༸྾-࿅࿇-࿌࿎࿏࿕-࿘႞႟᎐-᎙᙭᥀᧞-᧿᭡-᭪᭴-᭼℀℁℃-℆℈℉℔№℗℞-℣℥℧℩℮℺℻⅊⅌⅍⅏↊↋↕-↙↜-↟↡↢↤↥↧-↭↯-⇍⇐⇑⇓⇕-⇳⌀-⌇⌌-⌟⌢-⌨⌫-⍻⍽-⎚⎴-⏛⏢-␦⑀-⑊⒜-ⓩ─-▶▸-◀◂-◷☀-♮♰-❧➔-➿⠀-⣿⬀-⬯⭅⭆⭍-⭳⭶-⮕⮗-⯿⳥-⳪⹐⹑⺀-⺙⺛-⻳⼀-⿕⿰-⿻〄〒〓〠〶〷〾〿㆐㆑㆖-㆟㇀-㇣㈀-㈞㈪-㉇㉐㉠-㉿㊊-㊰㋀-㏿䷀-䷿꒐-꓆꠨-꠫꠶꠷꠹꩷-꩹﵀-﵏﷏﷽-﷿¦│■○�",
    "astral": "\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|𑜿|\uD807[\uDFD5-\uDFDC\uDFE1-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|𛲜|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|𞅏|\uD83B[\uDCAC\uDD2E]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFA]|\uD83D[\uDC00-\uDED7\uDEDD-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF73\uDF80-\uDFD8\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE74\uDE78-\uDE7C\uDE80-\uDE86\uDE90-\uDEAC\uDEB0-\uDEBA\uDEC0-\uDEC5\uDED0-\uDED9\uDEE0-\uDEE7\uDEF0-\uDEF6\uDF00-\uDF92\uDF94-\uDFCA]"
  },
  {
    "name": "Z",
    "alias": "Separator",
    "bmp": "    - \u2028\u2029   "
  },
  {
    "name": "Zl",
    "alias": "Line_Separator",
    "bmp": "\u2028"
  },
  {
    "name": "Zp",
    "alias": "Paragraph_Separator",
    "bmp": "\u2029"
  },
  {
    "name": "Zs",
    "alias": "Space_Separator",
    "bmp": "    -    "
  }
];
const categories$1 = /* @__PURE__ */ getDefaultExportFromCjs(categories);
/*!
 * XRegExp Unicode Categories 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2010-present MIT License
 * Unicode data by Mathias Bynens <mathiasbynens.be>
 */
const unicodeCategories = (XRegExp2) => {
  if (!XRegExp2.addUnicodeData) {
    throw new ReferenceError("Unicode Base must be loaded before Unicode Categories");
  }
  XRegExp2.addUnicodeData(categories$1);
};
var properties$z = [
  {
    "name": "ASCII",
    "bmp": "\0-"
  },
  {
    "name": "Alphabetic",
    "bmp": "A-Za-zªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͅͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈְ-ׇֽֿׁׂׅׄא-תׯ-ײؐ-ؚؠ-ٗٙ-ٟٮ-ۓە-ۜۡ-ۭۨ-ۯۺ-ۼۿܐ-ܿݍ-ޱߊ-ߪߴߵߺࠀ-ࠗࠚ-ࠬࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉࣔ-ࣣࣟ-ࣰࣩ-ऻऽ-ौॎ-ॐॕ-ॣॱ-ঃঅ-ঌএঐও-নপ-রলশ-হঽ-ৄেৈোৌৎৗড়ঢ়য়-ৣৰৱৼਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਾ-ੂੇੈੋੌੑਖ਼-ੜਫ਼ੰ-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽ-ૅે-ૉોૌૐૠ-ૣૹ-ૼଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽ-ୄେୈୋୌୖୗଡ଼ଢ଼ୟ-ୣୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-ௌௐௗఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-ౌౕౖౘ-ౚౝౠ-ౣಀ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೄೆ-ೈೊ-ೌೕೖೝೞೠ-ೣೱೲഀ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൌൎൔ-ൗൟ-ൣൺ-ൿඁ-ඃඅ-ඖක-නඳ-රලව-ෆා-ුූෘ-ෟෲෳก-ฺเ-ๆํກຂຄຆ-ຊຌ-ຣລວ-ູົ-ຽເ-ໄໆໍໜ-ໟༀཀ-ཇཉ-ཬཱ-ཱྀྈ-ྗྙ-ྼက-ံးျ-ဿၐ-ႏႚ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜓᜟ-ᜳᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-ឳា-ៈៗៜᠠ-ᡸᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-ᤸᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨛᨠ-ᩞᩡ-ᩴᪧᪿᫀᫌ-ᫎᬀ-ᬳᬵ-ᭃᭅ-ᭌᮀ-ᮩᮬ-ᮯᮺ-ᯥᯧ-ᯱᰀ-ᰶᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿᷧ-ᷴḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⒶ-ⓩⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙴ-ꙻꙿ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟊꟐꟑꟓꟕ-ꟙꟲ-ꠅꠇ-ꠧꡀ-ꡳꢀ-ꣃꣅꣲ-ꣷꣻꣽ-ꣿꤊ-ꤪꤰ-ꥒꥠ-ꥼꦀ-ꦲꦴ-ꦿꧏꧠ-ꧯꧺ-ꧾꨀ-ꨶꩀ-ꩍꩠ-ꩶꩺ-ꪾꫀꫂꫛ-ꫝꫠ-ꫯꫲ-ꫵꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯪ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",
    "astral": "\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDD00-\uDD27\uDE80-\uDEA9\uDEAB\uDEAC\uDEB0\uDEB1\uDF00-\uDF1C\uDF27\uDF30-\uDF45\uDF70-\uDF81\uDFB0-\uDFC4\uDFE0-\uDFF6]|\uD804[\uDC00-\uDC45\uDC71-\uDC75\uDC82-\uDCB8\uDCC2\uDCD0-\uDCE8\uDD00-\uDD32\uDD44-\uDD47\uDD50-\uDD72\uDD76\uDD80-\uDDBF\uDDC1-\uDDC4\uDDCE\uDDCF\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE34\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEE8\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D-\uDF44\uDF47\uDF48\uDF4B\uDF4C\uDF50\uDF57\uDF5D-\uDF63]|\uD805[\uDC00-\uDC41\uDC43-\uDC45\uDC47-\uDC4A\uDC5F-\uDC61\uDC80-\uDCC1\uDCC4\uDCC5\uDCC7\uDD80-\uDDB5\uDDB8-\uDDBE\uDDD8-\uDDDD\uDE00-\uDE3E\uDE40\uDE44\uDE80-\uDEB5\uDEB8\uDF00-\uDF1A\uDF1D-\uDF2A\uDF40-\uDF46]|\uD806[\uDC00-\uDC38\uDCA0-\uDCDF\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD35\uDD37\uDD38\uDD3B\uDD3C\uDD3F-\uDD42\uDDA0-\uDDA7\uDDAA-\uDDD7\uDDDA-\uDDDF\uDDE1\uDDE3\uDDE4\uDE00-\uDE32\uDE35-\uDE3E\uDE50-\uDE97\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC3E\uDC40\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD41\uDD43\uDD46\uDD47\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD8E\uDD90\uDD91\uDD93-\uDD96\uDD98\uDEE0-\uDEF6\uDFB0]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE70-\uDEBE\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE7F\uDF00-\uDF4A\uDF4F-\uDF87\uDF8F-\uDF9F\uDFE0\uDFE1\uDFE3\uDFF0\uDFF1]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9E]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD837[\uDF00-\uDF1E]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A\uDD00-\uDD2C\uDD37-\uDD3D\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43\uDD47\uDD4B]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD30-\uDD49\uDD50-\uDD69\uDD70-\uDD89]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A]"
  },
  {
    "name": "Any",
    "isBmpLast": true,
    "bmp": "\0-￿",
    "astral": "[\uD800-\uDBFF][\uDC00-\uDFFF]"
  },
  {
    "name": "Default_Ignorable_Code_Point",
    "bmp": "­͏؜ᅟᅠ឴឵᠋-᠏​-‏‪-‮⁠-ㅤ︀-️\uFEFFᅠ￰-￸",
    "astral": "\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|[\uDB40-\uDB43][\uDC00-\uDFFF]"
  },
  {
    "name": "Lowercase",
    "bmp": "a-zªµºß-öø-ÿāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįıijĵķĸĺļľŀłńņňʼnŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷźżž-ƀƃƅƈƌƍƒƕƙ-ƛƞơƣƥƨƪƫƭưƴƶƹƺƽ-ƿdžljnjǎǐǒǔǖǘǚǜǝǟǡǣǥǧǩǫǭǯǰdzǵǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟȡȣȥȧȩȫȭȯȱȳ-ȹȼȿɀɂɇɉɋɍɏ-ʓʕ-ʸˀˁˠ-ˤͅͱͳͷͺ-ͽΐά-ώϐϑϕ-ϗϙϛϝϟϡϣϥϧϩϫϭϯ-ϳϵϸϻϼа-џѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӏӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯՠ-ֈა-ჺჽ-ჿᏸ-ᏽᲀ-ᲈᴀ-ᶿḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕ-ẝẟạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿ-ἇἐ-ἕἠ-ἧἰ-ἷὀ-ὅὐ-ὗὠ-ὧὰ-ώᾀ-ᾇᾐ-ᾗᾠ-ᾧᾰ-ᾴᾶᾷιῂ-ῄῆῇῐ-ΐῖῗῠ-ῧῲ-ῴῶῷⁱⁿₐ-ₜℊℎℏℓℯℴℹℼℽⅆ-ⅉⅎⅰ-ⅿↄⓐ-ⓩⰰ-ⱟⱡⱥⱦⱨⱪⱬⱱⱳⱴⱶ-ⱽⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳤⳬⳮⳳⴀ-ⴥⴧⴭꙁꙃꙅꙇꙉꙋꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛ-ꚝꜣꜥꜧꜩꜫꜭꜯ-ꜱꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯ-ꝸꝺꝼꝿꞁꞃꞅꞇꞌꞎꞑꞓ-ꞕꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩꞯꞵꞷꞹꞻꞽꞿꟁꟃꟈꟊꟑꟓꟕꟗꟙꟶꟸ-ꟺꬰ-ꭚꭜ-ꭨꭰ-ꮿff-stﬓ-ﬗa-z",
    "astral": "\uD801[\uDC28-\uDC4F\uDCD8-\uDCFB\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDF80\uDF83-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD803[\uDCC0-\uDCF2]|\uD806[\uDCC0-\uDCDF]|\uD81B[\uDE60-\uDE7F]|\uD835[\uDC1A-\uDC33\uDC4E-\uDC54\uDC56-\uDC67\uDC82-\uDC9B\uDCB6-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDCEA-\uDD03\uDD1E-\uDD37\uDD52-\uDD6B\uDD86-\uDD9F\uDDBA-\uDDD3\uDDEE-\uDE07\uDE22-\uDE3B\uDE56-\uDE6F\uDE8A-\uDEA5\uDEC2-\uDEDA\uDEDC-\uDEE1\uDEFC-\uDF14\uDF16-\uDF1B\uDF36-\uDF4E\uDF50-\uDF55\uDF70-\uDF88\uDF8A-\uDF8F\uDFAA-\uDFC2\uDFC4-\uDFC9\uDFCB]|\uD837[\uDF00-\uDF09\uDF0B-\uDF1E]|\uD83A[\uDD22-\uDD43]"
  },
  {
    "name": "Noncharacter_Code_Point",
    "bmp": "﷐-﷯￾￿",
    "astral": "[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]"
  },
  {
    "name": "Uppercase",
    "bmp": "A-ZÀ-ÖØ-ÞĀĂĄĆĈĊČĎĐĒĔĖĘĚĜĞĠĢĤĦĨĪĬĮİIJĴĶĹĻĽĿŁŃŅŇŊŌŎŐŒŔŖŘŚŜŞŠŢŤŦŨŪŬŮŰŲŴŶŸŹŻŽƁƂƄƆƇƉ-ƋƎ-ƑƓƔƖ-ƘƜƝƟƠƢƤƦƧƩƬƮƯƱ-ƳƵƷƸƼDŽLJNJǍǏǑǓǕǗǙǛǞǠǢǤǦǨǪǬǮDZǴǶ-ǸǺǼǾȀȂȄȆȈȊȌȎȐȒȔȖȘȚȜȞȠȢȤȦȨȪȬȮȰȲȺȻȽȾɁɃ-ɆɈɊɌɎͰͲͶͿΆΈ-ΊΌΎΏΑ-ΡΣ-ΫϏϒ-ϔϘϚϜϞϠϢϤϦϨϪϬϮϴϷϹϺϽ-ЯѠѢѤѦѨѪѬѮѰѲѴѶѸѺѼѾҀҊҌҎҐҒҔҖҘҚҜҞҠҢҤҦҨҪҬҮҰҲҴҶҸҺҼҾӀӁӃӅӇӉӋӍӐӒӔӖӘӚӜӞӠӢӤӦӨӪӬӮӰӲӴӶӸӺӼӾԀԂԄԆԈԊԌԎԐԒԔԖԘԚԜԞԠԢԤԦԨԪԬԮԱ-ՖႠ-ჅჇჍᎠ-ᏵᲐ-ᲺᲽ-ᲿḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẞẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸỺỼỾἈ-ἏἘ-ἝἨ-ἯἸ-ἿὈ-ὍὙὛὝὟὨ-ὯᾸ-ΆῈ-ΉῘ-ΊῨ-ῬῸ-Ώℂℇℋ-ℍℐ-ℒℕℙ-ℝℤΩℨK-ℭℰ-ℳℾℿⅅⅠ-ⅯↃⒶ-ⓏⰀ-ⰯⱠⱢ-ⱤⱧⱩⱫⱭ-ⱰⱲⱵⱾ-ⲀⲂⲄⲆⲈⲊⲌⲎⲐⲒⲔⲖⲘⲚⲜⲞⲠⲢⲤⲦⲨⲪⲬⲮⲰⲲⲴⲶⲸⲺⲼⲾⳀⳂⳄⳆⳈⳊⳌⳎⳐⳒⳔⳖⳘⳚⳜⳞⳠⳢⳫⳭⳲꙀꙂꙄꙆꙈꙊꙌꙎꙐꙒꙔꙖꙘꙚꙜꙞꙠꙢꙤꙦꙨꙪꙬꚀꚂꚄꚆꚈꚊꚌꚎꚐꚒꚔꚖꚘꚚꜢꜤꜦꜨꜪꜬꜮꜲꜴꜶꜸꜺꜼꜾꝀꝂꝄꝆꝈꝊꝌꝎꝐꝒꝔꝖꝘꝚꝜꝞꝠꝢꝤꝦꝨꝪꝬꝮꝹꝻꝽꝾꞀꞂꞄꞆꞋꞍꞐꞒꞖꞘꞚꞜꞞꞠꞢꞤꞦꞨꞪ-ꞮꞰ-ꞴꞶꞸꞺꞼꞾꟀꟂꟄ-ꟇꟉꟐꟖꟘꟵA-Z",
    "astral": "\uD801[\uDC00-\uDC27\uDCB0-\uDCD3\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95]|\uD803[\uDC80-\uDCB2]|\uD806[\uDCA0-\uDCBF]|\uD81B[\uDE40-\uDE5F]|\uD835[\uDC00-\uDC19\uDC34-\uDC4D\uDC68-\uDC81\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB5\uDCD0-\uDCE9\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD38\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD6C-\uDD85\uDDA0-\uDDB9\uDDD4-\uDDED\uDE08-\uDE21\uDE3C-\uDE55\uDE70-\uDE89\uDEA8-\uDEC0\uDEE2-\uDEFA\uDF1C-\uDF34\uDF56-\uDF6E\uDF90-\uDFA8\uDFCA]|\uD83A[\uDD00-\uDD21]|\uD83C[\uDD30-\uDD49\uDD50-\uDD69\uDD70-\uDD89]"
  },
  {
    "name": "White_Space",
    "bmp": "	-\r …   - \u2028\u2029   "
  }
];
const properties$A = /* @__PURE__ */ getDefaultExportFromCjs(properties$z);
/*!
 * XRegExp Unicode Properties 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2012-present MIT License
 * Unicode data by Mathias Bynens <mathiasbynens.be>
 */
const unicodeProperties = (XRegExp2) => {
  if (!XRegExp2.addUnicodeData) {
    throw new ReferenceError("Unicode Base must be loaded before Unicode Properties");
  }
  const unicodeData = properties$A;
  unicodeData.push({
    name: "Assigned",
    // Since this is defined as the inverse of Unicode category Cn (Unassigned), the Unicode
    // Categories addon is required to use this property
    inverseOf: "Cn"
  });
  XRegExp2.addUnicodeData(unicodeData);
};
var scripts$1 = [
  {
    "name": "Adlam",
    "astral": "\uD83A[\uDD00-\uDD4B\uDD50-\uDD59\uDD5E\uDD5F]"
  },
  {
    "name": "Ahom",
    "astral": "\uD805[\uDF00-\uDF1A\uDF1D-\uDF2B\uDF30-\uDF46]"
  },
  {
    "name": "Anatolian_Hieroglyphs",
    "astral": "\uD811[\uDC00-\uDE46]"
  },
  {
    "name": "Arabic",
    "bmp": "؀-؄؆-؋؍-ؚ؜-؞ؠ-ؿف-يٖ-ٯٱ-ۜ۞-ۿݐ-ݿࡰ-ࢎ࢐࢑࢘-ࣣ࣡-ࣿﭐ-﯂ﯓ-ﴽ﵀-ﶏﶒ-ﷇ﷏ﷰ-﷿ﹰ-ﹴﹶ-ﻼ",
    "astral": "\uD803[\uDE60-\uDE7E]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB\uDEF0\uDEF1]"
  },
  {
    "name": "Armenian",
    "bmp": "Ա-Ֆՙ-֊֍-֏ﬓ-ﬗ"
  },
  {
    "name": "Avestan",
    "astral": "\uD802[\uDF00-\uDF35\uDF39-\uDF3F]"
  },
  {
    "name": "Balinese",
    "bmp": "ᬀ-ᭌ᭐-᭾"
  },
  {
    "name": "Bamum",
    "bmp": "ꚠ-꛷",
    "astral": "\uD81A[\uDC00-\uDE38]"
  },
  {
    "name": "Bassa_Vah",
    "astral": "\uD81A[\uDED0-\uDEED\uDEF0-\uDEF5]"
  },
  {
    "name": "Batak",
    "bmp": "ᯀ-᯳᯼-᯿"
  },
  {
    "name": "Bengali",
    "bmp": "ঀ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-৾"
  },
  {
    "name": "Bhaiksuki",
    "astral": "\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC45\uDC50-\uDC6C]"
  },
  {
    "name": "Bopomofo",
    "bmp": "˪˫ㄅ-ㄯㆠ-ㆿ"
  },
  {
    "name": "Brahmi",
    "astral": "\uD804[\uDC00-\uDC4D\uDC52-\uDC75\uDC7F]"
  },
  {
    "name": "Braille",
    "bmp": "⠀-⣿"
  },
  {
    "name": "Buginese",
    "bmp": "ᨀ-ᨛ᨞᨟"
  },
  {
    "name": "Buhid",
    "bmp": "ᝀ-ᝓ"
  },
  {
    "name": "Canadian_Aboriginal",
    "bmp": "᐀-ᙿᢰ-ᣵ",
    "astral": "\uD806[\uDEB0-\uDEBF]"
  },
  {
    "name": "Carian",
    "astral": "\uD800[\uDEA0-\uDED0]"
  },
  {
    "name": "Caucasian_Albanian",
    "astral": "\uD801[\uDD30-\uDD63\uDD6F]"
  },
  {
    "name": "Chakma",
    "astral": "\uD804[\uDD00-\uDD34\uDD36-\uDD47]"
  },
  {
    "name": "Cham",
    "bmp": "ꨀ-ꨶꩀ-ꩍ꩐-꩙꩜-꩟"
  },
  {
    "name": "Cherokee",
    "bmp": "Ꭰ-Ᏽᏸ-ᏽꭰ-ꮿ"
  },
  {
    "name": "Chorasmian",
    "astral": "\uD803[\uDFB0-\uDFCB]"
  },
  {
    "name": "Common",
    "bmp": "\0-@\\[-`\\{-©«-¹»-¿×÷ʹ-˟˥-˩ˬ-˿ʹ;΅·؅،؛؟ـ۝࣢।॥฿࿕-࿘჻᛫-᛭᜵᜶᠂᠃᠅᳓᳡ᳩ-ᳬᳮ-ᳳᳵ-᳷ᳺ -​‎-⁤⁦-⁰⁴-⁾₀-₎₠-⃀℀-℥℧-℩ℬ-ℱℳ-⅍⅏-⅟↉-↋←-␦⑀-⑊①-⟿⤀-⭳⭶-⮕⮗-⯿⸀-⹝⿰-⿻ -〄〆〈-〠〰-〷〼-〿゛゜゠・ー㆐-㆟㇀-㇣㈠-㉟㉿-㋏㋿㍘-㏿䷀-䷿꜀-꜡ꞈ-꞊꠰-꠹꤮ꧏ꭛꭪꭫﴾﴿︐-︙︰-﹒﹔-﹦﹨-﹫\uFEFF!-@[-`{-・ー゙゚¢-₩│-○-�",
    "astral": "\uD800[\uDD00-\uDD02\uDD07-\uDD33\uDD37-\uDD3F\uDD90-\uDD9C\uDDD0-\uDDFC\uDEE1-\uDEFB]|\uD82F[\uDCA0-\uDCA3]|\uD833[\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD66\uDD6A-\uDD7A\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDEE0-\uDEF3\uDF00-\uDF56\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDFCB\uDFCE-\uDFFF]|\uD83B[\uDC71-\uDCB4\uDD01-\uDD3D]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD00-\uDDAD\uDDE6-\uDDFF\uDE01\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED7\uDEDD-\uDEEC\uDEF0-\uDEFC\uDF00-\uDF73\uDF80-\uDFD8\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0\uDCB1\uDD00-\uDE53\uDE60-\uDE6D\uDE70-\uDE74\uDE78-\uDE7C\uDE80-\uDE86\uDE90-\uDEAC\uDEB0-\uDEBA\uDEC0-\uDEC5\uDED0-\uDED9\uDEE0-\uDEE7\uDEF0-\uDEF6\uDF00-\uDF92\uDF94-\uDFCA\uDFF0-\uDFF9]|\uDB40[\uDC01\uDC20-\uDC7F]"
  },
  {
    "name": "Coptic",
    "bmp": "Ϣ-ϯⲀ-ⳳ⳹-⳿"
  },
  {
    "name": "Cuneiform",
    "astral": "\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC70-\uDC74\uDC80-\uDD43]"
  },
  {
    "name": "Cypriot",
    "astral": "\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F]"
  },
  {
    "name": "Cypro_Minoan",
    "astral": "\uD80B[\uDF90-\uDFF2]"
  },
  {
    "name": "Cyrillic",
    "bmp": "Ѐ-҄҇-ԯᲀ-ᲈᴫᵸⷠ-ⷿꙀ-ꚟ︮︯"
  },
  {
    "name": "Deseret",
    "astral": "\uD801[\uDC00-\uDC4F]"
  },
  {
    "name": "Devanagari",
    "bmp": "ऀ-ॐॕ-ॣ०-ॿ꣠-ꣿ"
  },
  {
    "name": "Dives_Akuru",
    "astral": "\uD806[\uDD00-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD35\uDD37\uDD38\uDD3B-\uDD46\uDD50-\uDD59]"
  },
  {
    "name": "Dogra",
    "astral": "\uD806[\uDC00-\uDC3B]"
  },
  {
    "name": "Duployan",
    "astral": "\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9C-\uDC9F]"
  },
  {
    "name": "Egyptian_Hieroglyphs",
    "astral": "\uD80C[\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E\uDC30-\uDC38]"
  },
  {
    "name": "Elbasan",
    "astral": "\uD801[\uDD00-\uDD27]"
  },
  {
    "name": "Elymaic",
    "astral": "\uD803[\uDFE0-\uDFF6]"
  },
  {
    "name": "Ethiopic",
    "bmp": "ሀ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፼ᎀ-᎙ⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮ",
    "astral": "\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]"
  },
  {
    "name": "Georgian",
    "bmp": "Ⴀ-ჅჇჍა-ჺჼ-ჿᲐ-ᲺᲽ-Ჿⴀ-ⴥⴧⴭ"
  },
  {
    "name": "Glagolitic",
    "bmp": "Ⰰ-ⱟ",
    "astral": "\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]"
  },
  {
    "name": "Gothic",
    "astral": "\uD800[\uDF30-\uDF4A]"
  },
  {
    "name": "Grantha",
    "astral": "\uD804[\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]"
  },
  {
    "name": "Greek",
    "bmp": "Ͱ-ͳ͵-ͷͺ-ͽͿ΄ΆΈ-ΊΌΎ-ΡΣ-ϡϰ-Ͽᴦ-ᴪᵝ-ᵡᵦ-ᵪᶿἀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ῄῆ-ΐῖ-Ί῝-`ῲ-ῴῶ-῾Ωꭥ",
    "astral": "\uD800[\uDD40-\uDD8E\uDDA0]|\uD834[\uDE00-\uDE45]"
  },
  {
    "name": "Gujarati",
    "bmp": "ઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૱ૹ-૿"
  },
  {
    "name": "Gunjala_Gondi",
    "astral": "\uD807[\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD8E\uDD90\uDD91\uDD93-\uDD98\uDDA0-\uDDA9]"
  },
  {
    "name": "Gurmukhi",
    "bmp": "ਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-੶"
  },
  {
    "name": "Han",
    "bmp": "⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〻㐀-䶿一-鿿豈-舘並-龎",
    "astral": "\uD81B[\uDFE2\uDFE3\uDFF0\uDFF1]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A]"
  },
  {
    "name": "Hangul",
    "bmp": "ᄀ-ᇿ〮〯ㄱ-ㆎ㈀-㈞㉠-㉾ꥠ-ꥼ가-힣ힰ-ퟆퟋ-ퟻᅠ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ"
  },
  {
    "name": "Hanifi_Rohingya",
    "astral": "\uD803[\uDD00-\uDD27\uDD30-\uDD39]"
  },
  {
    "name": "Hanunoo",
    "bmp": "ᜠ-᜴"
  },
  {
    "name": "Hatran",
    "astral": "\uD802[\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDCFF]"
  },
  {
    "name": "Hebrew",
    "bmp": "֑-ׇא-תׯ-״יִ-זּטּ-לּמּנּסּףּפּצּ-ﭏ"
  },
  {
    "name": "Hiragana",
    "bmp": "ぁ-ゖゝ-ゟ",
    "astral": "\uD82C[\uDC01-\uDD1F\uDD50-\uDD52]|🈀"
  },
  {
    "name": "Imperial_Aramaic",
    "astral": "\uD802[\uDC40-\uDC55\uDC57-\uDC5F]"
  },
  {
    "name": "Inherited",
    "bmp": "̀-ًͯ҅҆-ٰٕ॑-॔᪰-ᫎ᳐-᳔᳒-᳢᳠-᳨᳭᳴᳸᳹᷀-᷿‌‍⃐-〪⃰-゙゚〭︀-️︠-︭",
    "astral": "\uD800[\uDDFD\uDEE0]|𑌻|\uD833[\uDF00-\uDF2D\uDF30-\uDF46]|\uD834[\uDD67-\uDD69\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD]|\uDB40[\uDD00-\uDDEF]"
  },
  {
    "name": "Inscriptional_Pahlavi",
    "astral": "\uD802[\uDF60-\uDF72\uDF78-\uDF7F]"
  },
  {
    "name": "Inscriptional_Parthian",
    "astral": "\uD802[\uDF40-\uDF55\uDF58-\uDF5F]"
  },
  {
    "name": "Javanese",
    "bmp": "ꦀ-꧍꧐-꧙꧞꧟"
  },
  {
    "name": "Kaithi",
    "astral": "\uD804[\uDC80-\uDCC2\uDCCD]"
  },
  {
    "name": "Kannada",
    "bmp": "ಀ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೝೞೠ-ೣ೦-೯ೱೲ"
  },
  {
    "name": "Katakana",
    "bmp": "ァ-ヺヽ-ヿㇰ-ㇿ㋐-㋾㌀-㍗ヲ-ッア-ン",
    "astral": "\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00\uDD20-\uDD22\uDD64-\uDD67]"
  },
  {
    "name": "Kayah_Li",
    "bmp": "꤀-꤭꤯"
  },
  {
    "name": "Kharoshthi",
    "astral": "\uD802[\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE38-\uDE3A\uDE3F-\uDE48\uDE50-\uDE58]"
  },
  {
    "name": "Khitan_Small_Script",
    "astral": "𖿤|\uD822[\uDF00-\uDFFF]|\uD823[\uDC00-\uDCD5]"
  },
  {
    "name": "Khmer",
    "bmp": "ក-៝០-៩៰-៹᧠-᧿"
  },
  {
    "name": "Khojki",
    "astral": "\uD804[\uDE00-\uDE11\uDE13-\uDE3E]"
  },
  {
    "name": "Khudawadi",
    "astral": "\uD804[\uDEB0-\uDEEA\uDEF0-\uDEF9]"
  },
  {
    "name": "Lao",
    "bmp": "ກຂຄຆ-ຊຌ-ຣລວ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟ"
  },
  {
    "name": "Latin",
    "bmp": "A-Za-zªºÀ-ÖØ-öø-ʸˠ-ˤᴀ-ᴥᴬ-ᵜᵢ-ᵥᵫ-ᵷᵹ-ᶾḀ-ỿⁱⁿₐ-ₜKÅℲⅎⅠ-ↈⱠ-ⱿꜢ-ꞇꞋ-ꟊꟐꟑꟓꟕ-ꟙꟲ-ꟿꬰ-ꭚꭜ-ꭤꭦ-ꭩff-stA-Za-z",
    "astral": "\uD801[\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD837[\uDF00-\uDF1E]"
  },
  {
    "name": "Lepcha",
    "bmp": "ᰀ-᰷᰻-᱉ᱍ-ᱏ"
  },
  {
    "name": "Limbu",
    "bmp": "ᤀ-ᤞᤠ-ᤫᤰ-᤻᥀᥄-᥏"
  },
  {
    "name": "Linear_A",
    "astral": "\uD801[\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]"
  },
  {
    "name": "Linear_B",
    "astral": "\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA]"
  },
  {
    "name": "Lisu",
    "bmp": "ꓐ-꓿",
    "astral": "𑾰"
  },
  {
    "name": "Lycian",
    "astral": "\uD800[\uDE80-\uDE9C]"
  },
  {
    "name": "Lydian",
    "astral": "\uD802[\uDD20-\uDD39\uDD3F]"
  },
  {
    "name": "Mahajani",
    "astral": "\uD804[\uDD50-\uDD76]"
  },
  {
    "name": "Makasar",
    "astral": "\uD807[\uDEE0-\uDEF8]"
  },
  {
    "name": "Malayalam",
    "bmp": "ഀ-ഌഎ-ഐഒ-ൄെ-ൈൊ-൏ൔ-ൣ൦-ൿ"
  },
  {
    "name": "Mandaic",
    "bmp": "ࡀ-࡛࡞"
  },
  {
    "name": "Manichaean",
    "astral": "\uD802[\uDEC0-\uDEE6\uDEEB-\uDEF6]"
  },
  {
    "name": "Marchen",
    "astral": "\uD807[\uDC70-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]"
  },
  {
    "name": "Masaram_Gondi",
    "astral": "\uD807[\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]"
  },
  {
    "name": "Medefaidrin",
    "astral": "\uD81B[\uDE40-\uDE9A]"
  },
  {
    "name": "Meetei_Mayek",
    "bmp": "ꫠ-꫶ꯀ-꯭꯰-꯹"
  },
  {
    "name": "Mende_Kikakui",
    "astral": "\uD83A[\uDC00-\uDCC4\uDCC7-\uDCD6]"
  },
  {
    "name": "Meroitic_Cursive",
    "astral": "\uD802[\uDDA0-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDDFF]"
  },
  {
    "name": "Meroitic_Hieroglyphs",
    "astral": "\uD802[\uDD80-\uDD9F]"
  },
  {
    "name": "Miao",
    "astral": "\uD81B[\uDF00-\uDF4A\uDF4F-\uDF87\uDF8F-\uDF9F]"
  },
  {
    "name": "Modi",
    "astral": "\uD805[\uDE00-\uDE44\uDE50-\uDE59]"
  },
  {
    "name": "Mongolian",
    "bmp": "᠀᠁᠄᠆-᠙ᠠ-ᡸᢀ-ᢪ",
    "astral": "\uD805[\uDE60-\uDE6C]"
  },
  {
    "name": "Mro",
    "astral": "\uD81A[\uDE40-\uDE5E\uDE60-\uDE69\uDE6E\uDE6F]"
  },
  {
    "name": "Multani",
    "astral": "\uD804[\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA9]"
  },
  {
    "name": "Myanmar",
    "bmp": "က-႟ꧠ-ꧾꩠ-ꩿ"
  },
  {
    "name": "Nabataean",
    "astral": "\uD802[\uDC80-\uDC9E\uDCA7-\uDCAF]"
  },
  {
    "name": "Nandinagari",
    "astral": "\uD806[\uDDA0-\uDDA7\uDDAA-\uDDD7\uDDDA-\uDDE4]"
  },
  {
    "name": "New_Tai_Lue",
    "bmp": "ᦀ-ᦫᦰ-ᧉ᧐-᧚᧞᧟"
  },
  {
    "name": "Newa",
    "astral": "\uD805[\uDC00-\uDC5B\uDC5D-\uDC61]"
  },
  {
    "name": "Nko",
    "bmp": "߀-ߺ߽-߿"
  },
  {
    "name": "Nushu",
    "astral": "𖿡|\uD82C[\uDD70-\uDEFB]"
  },
  {
    "name": "Nyiakeng_Puachue_Hmong",
    "astral": "\uD838[\uDD00-\uDD2C\uDD30-\uDD3D\uDD40-\uDD49\uDD4E\uDD4F]"
  },
  {
    "name": "Ogham",
    "bmp": " -᚜"
  },
  {
    "name": "Ol_Chiki",
    "bmp": "᱐-᱿"
  },
  {
    "name": "Old_Hungarian",
    "astral": "\uD803[\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDCFF]"
  },
  {
    "name": "Old_Italic",
    "astral": "\uD800[\uDF00-\uDF23\uDF2D-\uDF2F]"
  },
  {
    "name": "Old_North_Arabian",
    "astral": "\uD802[\uDE80-\uDE9F]"
  },
  {
    "name": "Old_Permic",
    "astral": "\uD800[\uDF50-\uDF7A]"
  },
  {
    "name": "Old_Persian",
    "astral": "\uD800[\uDFA0-\uDFC3\uDFC8-\uDFD5]"
  },
  {
    "name": "Old_Sogdian",
    "astral": "\uD803[\uDF00-\uDF27]"
  },
  {
    "name": "Old_South_Arabian",
    "astral": "\uD802[\uDE60-\uDE7F]"
  },
  {
    "name": "Old_Turkic",
    "astral": "\uD803[\uDC00-\uDC48]"
  },
  {
    "name": "Old_Uyghur",
    "astral": "\uD803[\uDF70-\uDF89]"
  },
  {
    "name": "Oriya",
    "bmp": "ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍୕-ୗଡ଼ଢ଼ୟ-ୣ୦-୷"
  },
  {
    "name": "Osage",
    "astral": "\uD801[\uDCB0-\uDCD3\uDCD8-\uDCFB]"
  },
  {
    "name": "Osmanya",
    "astral": "\uD801[\uDC80-\uDC9D\uDCA0-\uDCA9]"
  },
  {
    "name": "Pahawh_Hmong",
    "astral": "\uD81A[\uDF00-\uDF45\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]"
  },
  {
    "name": "Palmyrene",
    "astral": "\uD802[\uDC60-\uDC7F]"
  },
  {
    "name": "Pau_Cin_Hau",
    "astral": "\uD806[\uDEC0-\uDEF8]"
  },
  {
    "name": "Phags_Pa",
    "bmp": "ꡀ-꡷"
  },
  {
    "name": "Phoenician",
    "astral": "\uD802[\uDD00-\uDD1B\uDD1F]"
  },
  {
    "name": "Psalter_Pahlavi",
    "astral": "\uD802[\uDF80-\uDF91\uDF99-\uDF9C\uDFA9-\uDFAF]"
  },
  {
    "name": "Rejang",
    "bmp": "ꤰ-꥓꥟"
  },
  {
    "name": "Runic",
    "bmp": "ᚠ-ᛪᛮ-ᛸ"
  },
  {
    "name": "Samaritan",
    "bmp": "ࠀ-࠭࠰-࠾"
  },
  {
    "name": "Saurashtra",
    "bmp": "ꢀ-ꣅ꣎-꣙"
  },
  {
    "name": "Sharada",
    "astral": "\uD804[\uDD80-\uDDDF]"
  },
  {
    "name": "Shavian",
    "astral": "\uD801[\uDC50-\uDC7F]"
  },
  {
    "name": "Siddham",
    "astral": "\uD805[\uDD80-\uDDB5\uDDB8-\uDDDD]"
  },
  {
    "name": "SignWriting",
    "astral": "\uD836[\uDC00-\uDE8B\uDE9B-\uDE9F\uDEA1-\uDEAF]"
  },
  {
    "name": "Sinhala",
    "bmp": "ඁ-ඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲ-෴",
    "astral": "\uD804[\uDDE1-\uDDF4]"
  },
  {
    "name": "Sogdian",
    "astral": "\uD803[\uDF30-\uDF59]"
  },
  {
    "name": "Sora_Sompeng",
    "astral": "\uD804[\uDCD0-\uDCE8\uDCF0-\uDCF9]"
  },
  {
    "name": "Soyombo",
    "astral": "\uD806[\uDE50-\uDEA2]"
  },
  {
    "name": "Sundanese",
    "bmp": "ᮀ-ᮿ᳀-᳇"
  },
  {
    "name": "Syloti_Nagri",
    "bmp": "ꠀ-꠬"
  },
  {
    "name": "Syriac",
    "bmp": "܀-܍܏-݊ݍ-ݏࡠ-ࡪ"
  },
  {
    "name": "Tagalog",
    "bmp": "ᜀ-᜕ᜟ"
  },
  {
    "name": "Tagbanwa",
    "bmp": "ᝠ-ᝬᝮ-ᝰᝲᝳ"
  },
  {
    "name": "Tai_Le",
    "bmp": "ᥐ-ᥭᥰ-ᥴ"
  },
  {
    "name": "Tai_Tham",
    "bmp": "ᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪠-᪭"
  },
  {
    "name": "Tai_Viet",
    "bmp": "ꪀ-ꫂꫛ-꫟"
  },
  {
    "name": "Takri",
    "astral": "\uD805[\uDE80-\uDEB9\uDEC0-\uDEC9]"
  },
  {
    "name": "Tamil",
    "bmp": "ஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௺",
    "astral": "\uD807[\uDFC0-\uDFF1\uDFFF]"
  },
  {
    "name": "Tangsa",
    "astral": "\uD81A[\uDE70-\uDEBE\uDEC0-\uDEC9]"
  },
  {
    "name": "Tangut",
    "astral": "𖿠|[\uD81C-\uD820][\uDC00-\uDFFF]|\uD821[\uDC00-\uDFF7]|\uD822[\uDC00-\uDEFF]|\uD823[\uDD00-\uDD08]"
  },
  {
    "name": "Telugu",
    "bmp": "ఀ-ఌఎ-ఐఒ-నప-హ఼-ౄె-ైొ-్ౕౖౘ-ౚౝౠ-ౣ౦-౯౷-౿"
  },
  {
    "name": "Thaana",
    "bmp": "ހ-ޱ"
  },
  {
    "name": "Thai",
    "bmp": "ก-ฺเ-๛"
  },
  {
    "name": "Tibetan",
    "bmp": "ༀ-ཇཉ-ཬཱ-ྗྙ-ྼ྾-࿌࿎-࿔࿙࿚"
  },
  {
    "name": "Tifinagh",
    "bmp": "ⴰ-ⵧⵯ⵰⵿"
  },
  {
    "name": "Tirhuta",
    "astral": "\uD805[\uDC80-\uDCC7\uDCD0-\uDCD9]"
  },
  {
    "name": "Toto",
    "astral": "\uD838[\uDE90-\uDEAE]"
  },
  {
    "name": "Ugaritic",
    "astral": "\uD800[\uDF80-\uDF9D\uDF9F]"
  },
  {
    "name": "Vai",
    "bmp": "ꔀ-ꘫ"
  },
  {
    "name": "Vithkuqi",
    "astral": "\uD801[\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC]"
  },
  {
    "name": "Wancho",
    "astral": "\uD838[\uDEC0-\uDEF9\uDEFF]"
  },
  {
    "name": "Warang_Citi",
    "astral": "\uD806[\uDCA0-\uDCF2\uDCFF]"
  },
  {
    "name": "Yezidi",
    "astral": "\uD803[\uDE80-\uDEA9\uDEAB-\uDEAD\uDEB0\uDEB1]"
  },
  {
    "name": "Yi",
    "bmp": "ꀀ-ꒌ꒐-꓆"
  },
  {
    "name": "Zanabazar_Square",
    "astral": "\uD806[\uDE00-\uDE47]"
  }
];
const scripts$2 = /* @__PURE__ */ getDefaultExportFromCjs(scripts$1);
/*!
 * XRegExp Unicode Scripts 5.1.1
 * <xregexp.com>
 * Steven Levithan (c) 2010-present MIT License
 * Unicode data by Mathias Bynens <mathiasbynens.be>
 */
const unicodeScripts = (XRegExp2) => {
  if (!XRegExp2.addUnicodeData) {
    throw new ReferenceError("Unicode Base must be loaded before Unicode Scripts");
  }
  XRegExp2.addUnicodeData(scripts$2, "Script");
};
build(XRegExp);
matchRecursive(XRegExp);
unicodeBase(XRegExp);
unicodeCategories(XRegExp);
unicodeProperties(XRegExp);
unicodeScripts(XRegExp);
const src = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: XRegExp
}, Symbol.toStringTag, { value: "Module" }));
function devAssert(condition, message) {
  const booleanCondition = Boolean(condition);
  if (!booleanCondition) {
    throw new Error(message);
  }
}
function isPromise(value) {
  return typeof (value === null || value === void 0 ? void 0 : value.then) === "function";
}
function isObjectLike(value) {
  return typeof value == "object" && value !== null;
}
function invariant(condition, message) {
  const booleanCondition = Boolean(condition);
  if (!booleanCondition) {
    throw new Error(
      message != null ? message : "Unexpected invariant triggered."
    );
  }
}
const LineRegExp = /\r\n|[\n\r]/g;
function getLocation(source, position) {
  let lastLineStart = 0;
  let line = 1;
  for (const match of source.body.matchAll(LineRegExp)) {
    typeof match.index === "number" || invariant(false);
    if (match.index >= position) {
      break;
    }
    lastLineStart = match.index + match[0].length;
    line += 1;
  }
  return {
    line,
    column: position + 1 - lastLineStart
  };
}
function printLocation(location) {
  return printSourceLocation(
    location.source,
    getLocation(location.source, location.start)
  );
}
function printSourceLocation(source, sourceLocation) {
  const firstLineColumnOffset = source.locationOffset.column - 1;
  const body = "".padStart(firstLineColumnOffset) + source.body;
  const lineIndex = sourceLocation.line - 1;
  const lineOffset = source.locationOffset.line - 1;
  const lineNum = sourceLocation.line + lineOffset;
  const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;
  const columnNum = sourceLocation.column + columnOffset;
  const locationStr = `${source.name}:${lineNum}:${columnNum}
`;
  const lines = body.split(/\r\n|[\n\r]/g);
  const locationLine = lines[lineIndex];
  if (locationLine.length > 120) {
    const subLineIndex = Math.floor(columnNum / 80);
    const subLineColumnNum = columnNum % 80;
    const subLines = [];
    for (let i = 0; i < locationLine.length; i += 80) {
      subLines.push(locationLine.slice(i, i + 80));
    }
    return locationStr + printPrefixedLines([
      [`${lineNum} |`, subLines[0]],
      ...subLines.slice(1, subLineIndex + 1).map((subLine) => ["|", subLine]),
      ["|", "^".padStart(subLineColumnNum)],
      ["|", subLines[subLineIndex + 1]]
    ]);
  }
  return locationStr + printPrefixedLines([
    // Lines specified like this: ["prefix", "string"],
    [`${lineNum - 1} |`, lines[lineIndex - 1]],
    [`${lineNum} |`, locationLine],
    ["|", "^".padStart(columnNum)],
    [`${lineNum + 1} |`, lines[lineIndex + 1]]
  ]);
}
function printPrefixedLines(lines) {
  const existingLines = lines.filter(([_, line]) => line !== void 0);
  const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));
  return existingLines.map(([prefix, line]) => prefix.padStart(padLen) + (line ? " " + line : "")).join("\n");
}
function toNormalizedOptions(args) {
  const firstArg = args[0];
  if (firstArg == null || "kind" in firstArg || "length" in firstArg) {
    return {
      nodes: firstArg,
      source: args[1],
      positions: args[2],
      path: args[3],
      originalError: args[4],
      extensions: args[5]
    };
  }
  return firstArg;
}
class GraphQLError extends Error {
  /**
   * An array of `{ line, column }` locations within the source GraphQL document
   * which correspond to this error.
   *
   * Errors during validation often contain multiple locations, for example to
   * point out two things with the same name. Errors during execution include a
   * single location, the field which produced the error.
   *
   * Enumerable, and appears in the result of JSON.stringify().
   */
  /**
   * An array describing the JSON-path into the execution response which
   * corresponds to this error. Only included for errors during execution.
   *
   * Enumerable, and appears in the result of JSON.stringify().
   */
  /**
   * An array of GraphQL AST Nodes corresponding to this error.
   */
  /**
   * The source GraphQL document for the first location of this error.
   *
   * Note that if this Error represents more than one node, the source may not
   * represent nodes after the first node.
   */
  /**
   * An array of character offsets within the source GraphQL document
   * which correspond to this error.
   */
  /**
   * The original error thrown from a field resolver during execution.
   */
  /**
   * Extension fields to add to the formatted error.
   */
  /**
   * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.
   */
  constructor(message, ...rawArgs) {
    var _this$nodes, _nodeLocations$, _ref;
    const { nodes, source, positions, path, originalError, extensions } = toNormalizedOptions(rawArgs);
    super(message);
    this.name = "GraphQLError";
    this.path = path !== null && path !== void 0 ? path : void 0;
    this.originalError = originalError !== null && originalError !== void 0 ? originalError : void 0;
    this.nodes = undefinedIfEmpty(
      Array.isArray(nodes) ? nodes : nodes ? [nodes] : void 0
    );
    const nodeLocations = undefinedIfEmpty(
      (_this$nodes = this.nodes) === null || _this$nodes === void 0 ? void 0 : _this$nodes.map((node) => node.loc).filter((loc) => loc != null)
    );
    this.source = source !== null && source !== void 0 ? source : nodeLocations === null || nodeLocations === void 0 ? void 0 : (_nodeLocations$ = nodeLocations[0]) === null || _nodeLocations$ === void 0 ? void 0 : _nodeLocations$.source;
    this.positions = positions !== null && positions !== void 0 ? positions : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => loc.start);
    this.locations = positions && source ? positions.map((pos) => getLocation(source, pos)) : nodeLocations === null || nodeLocations === void 0 ? void 0 : nodeLocations.map((loc) => getLocation(loc.source, loc.start));
    const originalExtensions = isObjectLike(
      originalError === null || originalError === void 0 ? void 0 : originalError.extensions
    ) ? originalError === null || originalError === void 0 ? void 0 : originalError.extensions : void 0;
    this.extensions = (_ref = extensions !== null && extensions !== void 0 ? extensions : originalExtensions) !== null && _ref !== void 0 ? _ref : /* @__PURE__ */ Object.create(null);
    Object.defineProperties(this, {
      message: {
        writable: true,
        enumerable: true
      },
      name: {
        enumerable: false
      },
      nodes: {
        enumerable: false
      },
      source: {
        enumerable: false
      },
      positions: {
        enumerable: false
      },
      originalError: {
        enumerable: false
      }
    });
    if (originalError !== null && originalError !== void 0 && originalError.stack) {
      Object.defineProperty(this, "stack", {
        value: originalError.stack,
        writable: true,
        configurable: true
      });
    } else if (Error.captureStackTrace) {
      Error.captureStackTrace(this, GraphQLError);
    } else {
      Object.defineProperty(this, "stack", {
        value: Error().stack,
        writable: true,
        configurable: true
      });
    }
  }
  get [Symbol.toStringTag]() {
    return "GraphQLError";
  }
  toString() {
    let output = this.message;
    if (this.nodes) {
      for (const node of this.nodes) {
        if (node.loc) {
          output += "\n\n" + printLocation(node.loc);
        }
      }
    } else if (this.source && this.locations) {
      for (const location of this.locations) {
        output += "\n\n" + printSourceLocation(this.source, location);
      }
    }
    return output;
  }
  toJSON() {
    const formattedError = {
      message: this.message
    };
    if (this.locations != null) {
      formattedError.locations = this.locations;
    }
    if (this.path != null) {
      formattedError.path = this.path;
    }
    if (this.extensions != null && Object.keys(this.extensions).length > 0) {
      formattedError.extensions = this.extensions;
    }
    return formattedError;
  }
}
function undefinedIfEmpty(array) {
  return array === void 0 || array.length === 0 ? void 0 : array;
}
function syntaxError(source, position, description2) {
  return new GraphQLError(`Syntax Error: ${description2}`, {
    source,
    positions: [position]
  });
}
class Location {
  /**
   * The character offset at which this Node begins.
   */
  /**
   * The character offset at which this Node ends.
   */
  /**
   * The Token at which this Node begins.
   */
  /**
   * The Token at which this Node ends.
   */
  /**
   * The Source document the AST represents.
   */
  constructor(startToken, endToken, source) {
    this.start = startToken.start;
    this.end = endToken.end;
    this.startToken = startToken;
    this.endToken = endToken;
    this.source = source;
  }
  get [Symbol.toStringTag]() {
    return "Location";
  }
  toJSON() {
    return {
      start: this.start,
      end: this.end
    };
  }
}
class Token {
  /**
   * The kind of Token.
   */
  /**
   * The character offset at which this Node begins.
   */
  /**
   * The character offset at which this Node ends.
   */
  /**
   * The 1-indexed line number on which this Token appears.
   */
  /**
   * The 1-indexed column number at which this Token begins.
   */
  /**
   * For non-punctuation tokens, represents the interpreted value of the token.
   *
   * Note: is undefined for punctuation tokens, but typed as string for
   * convenience in the parser.
   */
  /**
   * Tokens exist as nodes in a double-linked-list amongst all tokens
   * including ignored tokens. <SOF> is always the first node and <EOF>
   * the last.
   */
  constructor(kind, start, end, line, column, value) {
    this.kind = kind;
    this.start = start;
    this.end = end;
    this.line = line;
    this.column = column;
    this.value = value;
    this.prev = null;
    this.next = null;
  }
  get [Symbol.toStringTag]() {
    return "Token";
  }
  toJSON() {
    return {
      kind: this.kind,
      value: this.value,
      line: this.line,
      column: this.column
    };
  }
}
const QueryDocumentKeys = {
  Name: [],
  Document: ["definitions"],
  OperationDefinition: [
    "name",
    "variableDefinitions",
    "directives",
    "selectionSet"
  ],
  VariableDefinition: ["variable", "type", "defaultValue", "directives"],
  Variable: ["name"],
  SelectionSet: ["selections"],
  Field: ["alias", "name", "arguments", "directives", "selectionSet"],
  Argument: ["name", "value"],
  FragmentSpread: ["name", "directives"],
  InlineFragment: ["typeCondition", "directives", "selectionSet"],
  FragmentDefinition: [
    "name",
    // Note: fragment variable definitions are deprecated and will removed in v17.0.0
    "variableDefinitions",
    "typeCondition",
    "directives",
    "selectionSet"
  ],
  IntValue: [],
  FloatValue: [],
  StringValue: [],
  BooleanValue: [],
  NullValue: [],
  EnumValue: [],
  ListValue: ["values"],
  ObjectValue: ["fields"],
  ObjectField: ["name", "value"],
  Directive: ["name", "arguments"],
  NamedType: ["name"],
  ListType: ["type"],
  NonNullType: ["type"],
  SchemaDefinition: ["description", "directives", "operationTypes"],
  OperationTypeDefinition: ["type"],
  ScalarTypeDefinition: ["description", "name", "directives"],
  ObjectTypeDefinition: [
    "description",
    "name",
    "interfaces",
    "directives",
    "fields"
  ],
  FieldDefinition: ["description", "name", "arguments", "type", "directives"],
  InputValueDefinition: [
    "description",
    "name",
    "type",
    "defaultValue",
    "directives"
  ],
  InterfaceTypeDefinition: [
    "description",
    "name",
    "interfaces",
    "directives",
    "fields"
  ],
  UnionTypeDefinition: ["description", "name", "directives", "types"],
  EnumTypeDefinition: ["description", "name", "directives", "values"],
  EnumValueDefinition: ["description", "name", "directives"],
  InputObjectTypeDefinition: ["description", "name", "directives", "fields"],
  DirectiveDefinition: ["description", "name", "arguments", "locations"],
  SchemaExtension: ["directives", "operationTypes"],
  ScalarTypeExtension: ["name", "directives"],
  ObjectTypeExtension: ["name", "interfaces", "directives", "fields"],
  InterfaceTypeExtension: ["name", "interfaces", "directives", "fields"],
  UnionTypeExtension: ["name", "directives", "types"],
  EnumTypeExtension: ["name", "directives", "values"],
  InputObjectTypeExtension: ["name", "directives", "fields"]
};
const kindValues = new Set(Object.keys(QueryDocumentKeys));
function isNode(maybeNode) {
  const maybeKind = maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind;
  return typeof maybeKind === "string" && kindValues.has(maybeKind);
}
var OperationTypeNode;
(function(OperationTypeNode2) {
  OperationTypeNode2["QUERY"] = "query";
  OperationTypeNode2["MUTATION"] = "mutation";
  OperationTypeNode2["SUBSCRIPTION"] = "subscription";
})(OperationTypeNode || (OperationTypeNode = {}));
var DirectiveLocation;
(function(DirectiveLocation2) {
  DirectiveLocation2["QUERY"] = "QUERY";
  DirectiveLocation2["MUTATION"] = "MUTATION";
  DirectiveLocation2["SUBSCRIPTION"] = "SUBSCRIPTION";
  DirectiveLocation2["FIELD"] = "FIELD";
  DirectiveLocation2["FRAGMENT_DEFINITION"] = "FRAGMENT_DEFINITION";
  DirectiveLocation2["FRAGMENT_SPREAD"] = "FRAGMENT_SPREAD";
  DirectiveLocation2["INLINE_FRAGMENT"] = "INLINE_FRAGMENT";
  DirectiveLocation2["VARIABLE_DEFINITION"] = "VARIABLE_DEFINITION";
  DirectiveLocation2["SCHEMA"] = "SCHEMA";
  DirectiveLocation2["SCALAR"] = "SCALAR";
  DirectiveLocation2["OBJECT"] = "OBJECT";
  DirectiveLocation2["FIELD_DEFINITION"] = "FIELD_DEFINITION";
  DirectiveLocation2["ARGUMENT_DEFINITION"] = "ARGUMENT_DEFINITION";
  DirectiveLocation2["INTERFACE"] = "INTERFACE";
  DirectiveLocation2["UNION"] = "UNION";
  DirectiveLocation2["ENUM"] = "ENUM";
  DirectiveLocation2["ENUM_VALUE"] = "ENUM_VALUE";
  DirectiveLocation2["INPUT_OBJECT"] = "INPUT_OBJECT";
  DirectiveLocation2["INPUT_FIELD_DEFINITION"] = "INPUT_FIELD_DEFINITION";
})(DirectiveLocation || (DirectiveLocation = {}));
var Kind;
(function(Kind2) {
  Kind2["NAME"] = "Name";
  Kind2["DOCUMENT"] = "Document";
  Kind2["OPERATION_DEFINITION"] = "OperationDefinition";
  Kind2["VARIABLE_DEFINITION"] = "VariableDefinition";
  Kind2["SELECTION_SET"] = "SelectionSet";
  Kind2["FIELD"] = "Field";
  Kind2["ARGUMENT"] = "Argument";
  Kind2["FRAGMENT_SPREAD"] = "FragmentSpread";
  Kind2["INLINE_FRAGMENT"] = "InlineFragment";
  Kind2["FRAGMENT_DEFINITION"] = "FragmentDefinition";
  Kind2["VARIABLE"] = "Variable";
  Kind2["INT"] = "IntValue";
  Kind2["FLOAT"] = "FloatValue";
  Kind2["STRING"] = "StringValue";
  Kind2["BOOLEAN"] = "BooleanValue";
  Kind2["NULL"] = "NullValue";
  Kind2["ENUM"] = "EnumValue";
  Kind2["LIST"] = "ListValue";
  Kind2["OBJECT"] = "ObjectValue";
  Kind2["OBJECT_FIELD"] = "ObjectField";
  Kind2["DIRECTIVE"] = "Directive";
  Kind2["NAMED_TYPE"] = "NamedType";
  Kind2["LIST_TYPE"] = "ListType";
  Kind2["NON_NULL_TYPE"] = "NonNullType";
  Kind2["SCHEMA_DEFINITION"] = "SchemaDefinition";
  Kind2["OPERATION_TYPE_DEFINITION"] = "OperationTypeDefinition";
  Kind2["SCALAR_TYPE_DEFINITION"] = "ScalarTypeDefinition";
  Kind2["OBJECT_TYPE_DEFINITION"] = "ObjectTypeDefinition";
  Kind2["FIELD_DEFINITION"] = "FieldDefinition";
  Kind2["INPUT_VALUE_DEFINITION"] = "InputValueDefinition";
  Kind2["INTERFACE_TYPE_DEFINITION"] = "InterfaceTypeDefinition";
  Kind2["UNION_TYPE_DEFINITION"] = "UnionTypeDefinition";
  Kind2["ENUM_TYPE_DEFINITION"] = "EnumTypeDefinition";
  Kind2["ENUM_VALUE_DEFINITION"] = "EnumValueDefinition";
  Kind2["INPUT_OBJECT_TYPE_DEFINITION"] = "InputObjectTypeDefinition";
  Kind2["DIRECTIVE_DEFINITION"] = "DirectiveDefinition";
  Kind2["SCHEMA_EXTENSION"] = "SchemaExtension";
  Kind2["SCALAR_TYPE_EXTENSION"] = "ScalarTypeExtension";
  Kind2["OBJECT_TYPE_EXTENSION"] = "ObjectTypeExtension";
  Kind2["INTERFACE_TYPE_EXTENSION"] = "InterfaceTypeExtension";
  Kind2["UNION_TYPE_EXTENSION"] = "UnionTypeExtension";
  Kind2["ENUM_TYPE_EXTENSION"] = "EnumTypeExtension";
  Kind2["INPUT_OBJECT_TYPE_EXTENSION"] = "InputObjectTypeExtension";
})(Kind || (Kind = {}));
function isWhiteSpace(code2) {
  return code2 === 9 || code2 === 32;
}
function isDigit$1(code2) {
  return code2 >= 48 && code2 <= 57;
}
function isLetter(code2) {
  return code2 >= 97 && code2 <= 122 || // A-Z
  code2 >= 65 && code2 <= 90;
}
function isNameStart(code2) {
  return isLetter(code2) || code2 === 95;
}
function isNameContinue(code2) {
  return isLetter(code2) || isDigit$1(code2) || code2 === 95;
}
function dedentBlockStringLines(lines) {
  var _firstNonEmptyLine2;
  let commonIndent = Number.MAX_SAFE_INTEGER;
  let firstNonEmptyLine = null;
  let lastNonEmptyLine = -1;
  for (let i = 0; i < lines.length; ++i) {
    var _firstNonEmptyLine;
    const line = lines[i];
    const indent2 = leadingWhitespace$1(line);
    if (indent2 === line.length) {
      continue;
    }
    firstNonEmptyLine = (_firstNonEmptyLine = firstNonEmptyLine) !== null && _firstNonEmptyLine !== void 0 ? _firstNonEmptyLine : i;
    lastNonEmptyLine = i;
    if (i !== 0 && indent2 < commonIndent) {
      commonIndent = indent2;
    }
  }
  return lines.map((line, i) => i === 0 ? line : line.slice(commonIndent)).slice(
    (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && _firstNonEmptyLine2 !== void 0 ? _firstNonEmptyLine2 : 0,
    lastNonEmptyLine + 1
  );
}
function leadingWhitespace$1(str) {
  let i = 0;
  while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {
    ++i;
  }
  return i;
}
function printBlockString$1(value, options2) {
  const escapedValue = value.replace(/"""/g, '\\"""');
  const lines = escapedValue.split(/\r\n|[\n\r]/g);
  const isSingleLine = lines.length === 1;
  const forceLeadingNewLine = lines.length > 1 && lines.slice(1).every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0)));
  const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""');
  const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes;
  const hasTrailingSlash = value.endsWith("\\");
  const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;
  const printAsMultipleLines = !(options2 !== null && options2 !== void 0 && options2.minimize) && // add leading and trailing new lines only if it improves readability
  (!isSingleLine || value.length > 70 || forceTrailingNewline || forceLeadingNewLine || hasTrailingTripleQuotes);
  let result = "";
  const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));
  if (printAsMultipleLines && !skipLeadingNewLine || forceLeadingNewLine) {
    result += "\n";
  }
  result += escapedValue;
  if (printAsMultipleLines || forceTrailingNewline) {
    result += "\n";
  }
  return '"""' + result + '"""';
}
var TokenKind;
(function(TokenKind2) {
  TokenKind2["SOF"] = "<SOF>";
  TokenKind2["EOF"] = "<EOF>";
  TokenKind2["BANG"] = "!";
  TokenKind2["DOLLAR"] = "$";
  TokenKind2["AMP"] = "&";
  TokenKind2["PAREN_L"] = "(";
  TokenKind2["PAREN_R"] = ")";
  TokenKind2["SPREAD"] = "...";
  TokenKind2["COLON"] = ":";
  TokenKind2["EQUALS"] = "=";
  TokenKind2["AT"] = "@";
  TokenKind2["BRACKET_L"] = "[";
  TokenKind2["BRACKET_R"] = "]";
  TokenKind2["BRACE_L"] = "{";
  TokenKind2["PIPE"] = "|";
  TokenKind2["BRACE_R"] = "}";
  TokenKind2["NAME"] = "Name";
  TokenKind2["INT"] = "Int";
  TokenKind2["FLOAT"] = "Float";
  TokenKind2["STRING"] = "String";
  TokenKind2["BLOCK_STRING"] = "BlockString";
  TokenKind2["COMMENT"] = "Comment";
})(TokenKind || (TokenKind = {}));
class Lexer {
  /**
   * The previously focused non-ignored token.
   */
  /**
   * The currently focused non-ignored token.
   */
  /**
   * The (1-indexed) line containing the current token.
   */
  /**
   * The character offset at which the current line begins.
   */
  constructor(source) {
    const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);
    this.source = source;
    this.lastToken = startOfFileToken;
    this.token = startOfFileToken;
    this.line = 1;
    this.lineStart = 0;
  }
  get [Symbol.toStringTag]() {
    return "Lexer";
  }
  /**
   * Advances the token stream to the next non-ignored token.
   */
  advance() {
    this.lastToken = this.token;
    const token = this.token = this.lookahead();
    return token;
  }
  /**
   * Looks ahead and returns the next non-ignored token, but does not change
   * the state of Lexer.
   */
  lookahead() {
    let token = this.token;
    if (token.kind !== TokenKind.EOF) {
      do {
        if (token.next) {
          token = token.next;
        } else {
          const nextToken = readNextToken(this, token.end);
          token.next = nextToken;
          nextToken.prev = token;
          token = nextToken;
        }
      } while (token.kind === TokenKind.COMMENT);
    }
    return token;
  }
}
function isPunctuatorTokenKind(kind) {
  return kind === TokenKind.BANG || kind === TokenKind.DOLLAR || kind === TokenKind.AMP || kind === TokenKind.PAREN_L || kind === TokenKind.PAREN_R || kind === TokenKind.SPREAD || kind === TokenKind.COLON || kind === TokenKind.EQUALS || kind === TokenKind.AT || kind === TokenKind.BRACKET_L || kind === TokenKind.BRACKET_R || kind === TokenKind.BRACE_L || kind === TokenKind.PIPE || kind === TokenKind.BRACE_R;
}
function isUnicodeScalarValue(code2) {
  return code2 >= 0 && code2 <= 55295 || code2 >= 57344 && code2 <= 1114111;
}
function isSupplementaryCodePoint(body, location) {
  return isLeadingSurrogate(body.charCodeAt(location)) && isTrailingSurrogate(body.charCodeAt(location + 1));
}
function isLeadingSurrogate(code2) {
  return code2 >= 55296 && code2 <= 56319;
}
function isTrailingSurrogate(code2) {
  return code2 >= 56320 && code2 <= 57343;
}
function printCodePointAt(lexer, location) {
  const code2 = lexer.source.body.codePointAt(location);
  if (code2 === void 0) {
    return TokenKind.EOF;
  } else if (code2 >= 32 && code2 <= 126) {
    const char = String.fromCodePoint(code2);
    return char === '"' ? `'"'` : `"${char}"`;
  }
  return "U+" + code2.toString(16).toUpperCase().padStart(4, "0");
}
function createToken(lexer, kind, start, end, value) {
  const line = lexer.line;
  const col = 1 + start - lexer.lineStart;
  return new Token(kind, start, end, line, col, value);
}
function readNextToken(lexer, start) {
  const body = lexer.source.body;
  const bodyLength = body.length;
  let position = start;
  while (position < bodyLength) {
    const code2 = body.charCodeAt(position);
    switch (code2) {
      case 65279:
      case 9:
      case 32:
      case 44:
        ++position;
        continue;
      case 10:
        ++position;
        ++lexer.line;
        lexer.lineStart = position;
        continue;
      case 13:
        if (body.charCodeAt(position + 1) === 10) {
          position += 2;
        } else {
          ++position;
        }
        ++lexer.line;
        lexer.lineStart = position;
        continue;
      case 35:
        return readComment(lexer, position);
      case 33:
        return createToken(lexer, TokenKind.BANG, position, position + 1);
      case 36:
        return createToken(lexer, TokenKind.DOLLAR, position, position + 1);
      case 38:
        return createToken(lexer, TokenKind.AMP, position, position + 1);
      case 40:
        return createToken(lexer, TokenKind.PAREN_L, position, position + 1);
      case 41:
        return createToken(lexer, TokenKind.PAREN_R, position, position + 1);
      case 46:
        if (body.charCodeAt(position + 1) === 46 && body.charCodeAt(position + 2) === 46) {
          return createToken(lexer, TokenKind.SPREAD, position, position + 3);
        }
        break;
      case 58:
        return createToken(lexer, TokenKind.COLON, position, position + 1);
      case 61:
        return createToken(lexer, TokenKind.EQUALS, position, position + 1);
      case 64:
        return createToken(lexer, TokenKind.AT, position, position + 1);
      case 91:
        return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);
      case 93:
        return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);
      case 123:
        return createToken(lexer, TokenKind.BRACE_L, position, position + 1);
      case 124:
        return createToken(lexer, TokenKind.PIPE, position, position + 1);
      case 125:
        return createToken(lexer, TokenKind.BRACE_R, position, position + 1);
      case 34:
        if (body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
          return readBlockString(lexer, position);
        }
        return readString(lexer, position);
    }
    if (isDigit$1(code2) || code2 === 45) {
      return readNumber(lexer, position, code2);
    }
    if (isNameStart(code2)) {
      return readName(lexer, position);
    }
    throw syntaxError(
      lexer.source,
      position,
      code2 === 39 ? `Unexpected single quote character ('), did you mean to use a double quote (")?` : isUnicodeScalarValue(code2) || isSupplementaryCodePoint(body, position) ? `Unexpected character: ${printCodePointAt(lexer, position)}.` : `Invalid character: ${printCodePointAt(lexer, position)}.`
    );
  }
  return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);
}
function readComment(lexer, start) {
  const body = lexer.source.body;
  const bodyLength = body.length;
  let position = start + 1;
  while (position < bodyLength) {
    const code2 = body.charCodeAt(position);
    if (code2 === 10 || code2 === 13) {
      break;
    }
    if (isUnicodeScalarValue(code2)) {
      ++position;
    } else if (isSupplementaryCodePoint(body, position)) {
      position += 2;
    } else {
      break;
    }
  }
  return createToken(
    lexer,
    TokenKind.COMMENT,
    start,
    position,
    body.slice(start + 1, position)
  );
}
function readNumber(lexer, start, firstCode) {
  const body = lexer.source.body;
  let position = start;
  let code2 = firstCode;
  let isFloat = false;
  if (code2 === 45) {
    code2 = body.charCodeAt(++position);
  }
  if (code2 === 48) {
    code2 = body.charCodeAt(++position);
    if (isDigit$1(code2)) {
      throw syntaxError(
        lexer.source,
        position,
        `Invalid number, unexpected digit after 0: ${printCodePointAt(
          lexer,
          position
        )}.`
      );
    }
  } else {
    position = readDigits(lexer, position, code2);
    code2 = body.charCodeAt(position);
  }
  if (code2 === 46) {
    isFloat = true;
    code2 = body.charCodeAt(++position);
    position = readDigits(lexer, position, code2);
    code2 = body.charCodeAt(position);
  }
  if (code2 === 69 || code2 === 101) {
    isFloat = true;
    code2 = body.charCodeAt(++position);
    if (code2 === 43 || code2 === 45) {
      code2 = body.charCodeAt(++position);
    }
    position = readDigits(lexer, position, code2);
    code2 = body.charCodeAt(position);
  }
  if (code2 === 46 || isNameStart(code2)) {
    throw syntaxError(
      lexer.source,
      position,
      `Invalid number, expected digit but got: ${printCodePointAt(
        lexer,
        position
      )}.`
    );
  }
  return createToken(
    lexer,
    isFloat ? TokenKind.FLOAT : TokenKind.INT,
    start,
    position,
    body.slice(start, position)
  );
}
function readDigits(lexer, start, firstCode) {
  if (!isDigit$1(firstCode)) {
    throw syntaxError(
      lexer.source,
      start,
      `Invalid number, expected digit but got: ${printCodePointAt(
        lexer,
        start
      )}.`
    );
  }
  const body = lexer.source.body;
  let position = start + 1;
  while (isDigit$1(body.charCodeAt(position))) {
    ++position;
  }
  return position;
}
function readString(lexer, start) {
  const body = lexer.source.body;
  const bodyLength = body.length;
  let position = start + 1;
  let chunkStart = position;
  let value = "";
  while (position < bodyLength) {
    const code2 = body.charCodeAt(position);
    if (code2 === 34) {
      value += body.slice(chunkStart, position);
      return createToken(lexer, TokenKind.STRING, start, position + 1, value);
    }
    if (code2 === 92) {
      value += body.slice(chunkStart, position);
      const escape = body.charCodeAt(position + 1) === 117 ? body.charCodeAt(position + 2) === 123 ? readEscapedUnicodeVariableWidth(lexer, position) : readEscapedUnicodeFixedWidth(lexer, position) : readEscapedCharacter(lexer, position);
      value += escape.value;
      position += escape.size;
      chunkStart = position;
      continue;
    }
    if (code2 === 10 || code2 === 13) {
      break;
    }
    if (isUnicodeScalarValue(code2)) {
      ++position;
    } else if (isSupplementaryCodePoint(body, position)) {
      position += 2;
    } else {
      throw syntaxError(
        lexer.source,
        position,
        `Invalid character within String: ${printCodePointAt(
          lexer,
          position
        )}.`
      );
    }
  }
  throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readEscapedUnicodeVariableWidth(lexer, position) {
  const body = lexer.source.body;
  let point = 0;
  let size = 3;
  while (size < 12) {
    const code2 = body.charCodeAt(position + size++);
    if (code2 === 125) {
      if (size < 5 || !isUnicodeScalarValue(point)) {
        break;
      }
      return {
        value: String.fromCodePoint(point),
        size
      };
    }
    point = point << 4 | readHexDigit(code2);
    if (point < 0) {
      break;
    }
  }
  throw syntaxError(
    lexer.source,
    position,
    `Invalid Unicode escape sequence: "${body.slice(
      position,
      position + size
    )}".`
  );
}
function readEscapedUnicodeFixedWidth(lexer, position) {
  const body = lexer.source.body;
  const code2 = read16BitHexCode(body, position + 2);
  if (isUnicodeScalarValue(code2)) {
    return {
      value: String.fromCodePoint(code2),
      size: 6
    };
  }
  if (isLeadingSurrogate(code2)) {
    if (body.charCodeAt(position + 6) === 92 && body.charCodeAt(position + 7) === 117) {
      const trailingCode = read16BitHexCode(body, position + 8);
      if (isTrailingSurrogate(trailingCode)) {
        return {
          value: String.fromCodePoint(code2, trailingCode),
          size: 12
        };
      }
    }
  }
  throw syntaxError(
    lexer.source,
    position,
    `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`
  );
}
function read16BitHexCode(body, position) {
  return readHexDigit(body.charCodeAt(position)) << 12 | readHexDigit(body.charCodeAt(position + 1)) << 8 | readHexDigit(body.charCodeAt(position + 2)) << 4 | readHexDigit(body.charCodeAt(position + 3));
}
function readHexDigit(code2) {
  return code2 >= 48 && code2 <= 57 ? code2 - 48 : code2 >= 65 && code2 <= 70 ? code2 - 55 : code2 >= 97 && code2 <= 102 ? code2 - 87 : -1;
}
function readEscapedCharacter(lexer, position) {
  const body = lexer.source.body;
  const code2 = body.charCodeAt(position + 1);
  switch (code2) {
    case 34:
      return {
        value: '"',
        size: 2
      };
    case 92:
      return {
        value: "\\",
        size: 2
      };
    case 47:
      return {
        value: "/",
        size: 2
      };
    case 98:
      return {
        value: "\b",
        size: 2
      };
    case 102:
      return {
        value: "\f",
        size: 2
      };
    case 110:
      return {
        value: "\n",
        size: 2
      };
    case 114:
      return {
        value: "\r",
        size: 2
      };
    case 116:
      return {
        value: "	",
        size: 2
      };
  }
  throw syntaxError(
    lexer.source,
    position,
    `Invalid character escape sequence: "${body.slice(
      position,
      position + 2
    )}".`
  );
}
function readBlockString(lexer, start) {
  const body = lexer.source.body;
  const bodyLength = body.length;
  let lineStart = lexer.lineStart;
  let position = start + 3;
  let chunkStart = position;
  let currentLine = "";
  const blockLines = [];
  while (position < bodyLength) {
    const code2 = body.charCodeAt(position);
    if (code2 === 34 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34) {
      currentLine += body.slice(chunkStart, position);
      blockLines.push(currentLine);
      const token = createToken(
        lexer,
        TokenKind.BLOCK_STRING,
        start,
        position + 3,
        // Return a string of the lines joined with U+000A.
        dedentBlockStringLines(blockLines).join("\n")
      );
      lexer.line += blockLines.length - 1;
      lexer.lineStart = lineStart;
      return token;
    }
    if (code2 === 92 && body.charCodeAt(position + 1) === 34 && body.charCodeAt(position + 2) === 34 && body.charCodeAt(position + 3) === 34) {
      currentLine += body.slice(chunkStart, position);
      chunkStart = position + 1;
      position += 4;
      continue;
    }
    if (code2 === 10 || code2 === 13) {
      currentLine += body.slice(chunkStart, position);
      blockLines.push(currentLine);
      if (code2 === 13 && body.charCodeAt(position + 1) === 10) {
        position += 2;
      } else {
        ++position;
      }
      currentLine = "";
      chunkStart = position;
      lineStart = position;
      continue;
    }
    if (isUnicodeScalarValue(code2)) {
      ++position;
    } else if (isSupplementaryCodePoint(body, position)) {
      position += 2;
    } else {
      throw syntaxError(
        lexer.source,
        position,
        `Invalid character within String: ${printCodePointAt(
          lexer,
          position
        )}.`
      );
    }
  }
  throw syntaxError(lexer.source, position, "Unterminated string.");
}
function readName(lexer, start) {
  const body = lexer.source.body;
  const bodyLength = body.length;
  let position = start + 1;
  while (position < bodyLength) {
    const code2 = body.charCodeAt(position);
    if (isNameContinue(code2)) {
      ++position;
    } else {
      break;
    }
  }
  return createToken(
    lexer,
    TokenKind.NAME,
    start,
    position,
    body.slice(start, position)
  );
}
const MAX_ARRAY_LENGTH = 10;
const MAX_RECURSIVE_DEPTH$1 = 2;
function inspect$2(value) {
  return formatValue$1(value, []);
}
function formatValue$1(value, seenValues) {
  switch (typeof value) {
    case "string":
      return JSON.stringify(value);
    case "function":
      return value.name ? `[function ${value.name}]` : "[function]";
    case "object":
      return formatObjectValue$1(value, seenValues);
    default:
      return String(value);
  }
}
function formatObjectValue$1(value, previouslySeenValues) {
  if (value === null) {
    return "null";
  }
  if (previouslySeenValues.includes(value)) {
    return "[Circular]";
  }
  const seenValues = [...previouslySeenValues, value];
  if (isJSONable$1(value)) {
    const jsonValue = value.toJSON();
    if (jsonValue !== value) {
      return typeof jsonValue === "string" ? jsonValue : formatValue$1(jsonValue, seenValues);
    }
  } else if (Array.isArray(value)) {
    return formatArray$1(value, seenValues);
  }
  return formatObject$1(value, seenValues);
}
function isJSONable$1(value) {
  return typeof value.toJSON === "function";
}
function formatObject$1(object, seenValues) {
  const entries = Object.entries(object);
  if (entries.length === 0) {
    return "{}";
  }
  if (seenValues.length > MAX_RECURSIVE_DEPTH$1) {
    return "[" + getObjectTag$1(object) + "]";
  }
  const properties2 = entries.map(
    ([key, value]) => key + ": " + formatValue$1(value, seenValues)
  );
  return "{ " + properties2.join(", ") + " }";
}
function formatArray$1(array, seenValues) {
  if (array.length === 0) {
    return "[]";
  }
  if (seenValues.length > MAX_RECURSIVE_DEPTH$1) {
    return "[Array]";
  }
  const len = Math.min(MAX_ARRAY_LENGTH, array.length);
  const remaining = array.length - len;
  const items2 = [];
  for (let i = 0; i < len; ++i) {
    items2.push(formatValue$1(array[i], seenValues));
  }
  if (remaining === 1) {
    items2.push("... 1 more item");
  } else if (remaining > 1) {
    items2.push(`... ${remaining} more items`);
  }
  return "[" + items2.join(", ") + "]";
}
function getObjectTag$1(object) {
  const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, "");
  if (tag === "Object" && typeof object.constructor === "function") {
    const name2 = object.constructor.name;
    if (typeof name2 === "string" && name2 !== "") {
      return name2;
    }
  }
  return tag;
}
const instanceOf = (
  /* c8 ignore next 6 */
  // FIXME: https://github.com/graphql/graphql-js/issues/2317
  globalThis.process && globalThis.process.env.NODE_ENV === "production" ? function instanceOf2(value, constructor) {
    return value instanceof constructor;
  } : function instanceOf3(value, constructor) {
    if (value instanceof constructor) {
      return true;
    }
    if (typeof value === "object" && value !== null) {
      var _value$constructor;
      const className = constructor.prototype[Symbol.toStringTag];
      const valueClassName = (
        // We still need to support constructor's name to detect conflicts with older versions of this library.
        Symbol.toStringTag in value ? value[Symbol.toStringTag] : (_value$constructor = value.constructor) === null || _value$constructor === void 0 ? void 0 : _value$constructor.name
      );
      if (className === valueClassName) {
        const stringifiedValue = inspect$2(value);
        throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm.

Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.

https://yarnpkg.com/en/docs/selective-version-resolutions

Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.`);
      }
    }
    return false;
  }
);
class Source {
  constructor(body, name2 = "GraphQL request", locationOffset = {
    line: 1,
    column: 1
  }) {
    typeof body === "string" || devAssert(false, `Body must be a string. Received: ${inspect$2(body)}.`);
    this.body = body;
    this.name = name2;
    this.locationOffset = locationOffset;
    this.locationOffset.line > 0 || devAssert(
      false,
      "line in locationOffset is 1-indexed and must be positive."
    );
    this.locationOffset.column > 0 || devAssert(
      false,
      "column in locationOffset is 1-indexed and must be positive."
    );
  }
  get [Symbol.toStringTag]() {
    return "Source";
  }
}
function isSource(source) {
  return instanceOf(source, Source);
}
function parse(source, options2) {
  const parser = new Parser$1(source, options2);
  return parser.parseDocument();
}
let Parser$1 = class Parser {
  constructor(source, options2 = {}) {
    const sourceObj = isSource(source) ? source : new Source(source);
    this._lexer = new Lexer(sourceObj);
    this._options = options2;
    this._tokenCounter = 0;
  }
  /**
   * Converts a name lex token into a name parse node.
   */
  parseName() {
    const token = this.expectToken(TokenKind.NAME);
    return this.node(token, {
      kind: Kind.NAME,
      value: token.value
    });
  }
  // Implements the parsing rules in the Document section.
  /**
   * Document : Definition+
   */
  parseDocument() {
    return this.node(this._lexer.token, {
      kind: Kind.DOCUMENT,
      definitions: this.many(
        TokenKind.SOF,
        this.parseDefinition,
        TokenKind.EOF
      )
    });
  }
  /**
   * Definition :
   *   - ExecutableDefinition
   *   - TypeSystemDefinition
   *   - TypeSystemExtension
   *
   * ExecutableDefinition :
   *   - OperationDefinition
   *   - FragmentDefinition
   *
   * TypeSystemDefinition :
   *   - SchemaDefinition
   *   - TypeDefinition
   *   - DirectiveDefinition
   *
   * TypeDefinition :
   *   - ScalarTypeDefinition
   *   - ObjectTypeDefinition
   *   - InterfaceTypeDefinition
   *   - UnionTypeDefinition
   *   - EnumTypeDefinition
   *   - InputObjectTypeDefinition
   */
  parseDefinition() {
    if (this.peek(TokenKind.BRACE_L)) {
      return this.parseOperationDefinition();
    }
    const hasDescription = this.peekDescription();
    const keywordToken = hasDescription ? this._lexer.lookahead() : this._lexer.token;
    if (keywordToken.kind === TokenKind.NAME) {
      switch (keywordToken.value) {
        case "schema":
          return this.parseSchemaDefinition();
        case "scalar":
          return this.parseScalarTypeDefinition();
        case "type":
          return this.parseObjectTypeDefinition();
        case "interface":
          return this.parseInterfaceTypeDefinition();
        case "union":
          return this.parseUnionTypeDefinition();
        case "enum":
          return this.parseEnumTypeDefinition();
        case "input":
          return this.parseInputObjectTypeDefinition();
        case "directive":
          return this.parseDirectiveDefinition();
      }
      if (hasDescription) {
        throw syntaxError(
          this._lexer.source,
          this._lexer.token.start,
          "Unexpected description, descriptions are supported only on type definitions."
        );
      }
      switch (keywordToken.value) {
        case "query":
        case "mutation":
        case "subscription":
          return this.parseOperationDefinition();
        case "fragment":
          return this.parseFragmentDefinition();
        case "extend":
          return this.parseTypeSystemExtension();
      }
    }
    throw this.unexpected(keywordToken);
  }
  // Implements the parsing rules in the Operations section.
  /**
   * OperationDefinition :
   *  - SelectionSet
   *  - OperationType Name? VariableDefinitions? Directives? SelectionSet
   */
  parseOperationDefinition() {
    const start = this._lexer.token;
    if (this.peek(TokenKind.BRACE_L)) {
      return this.node(start, {
        kind: Kind.OPERATION_DEFINITION,
        operation: OperationTypeNode.QUERY,
        name: void 0,
        variableDefinitions: [],
        directives: [],
        selectionSet: this.parseSelectionSet()
      });
    }
    const operation = this.parseOperationType();
    let name2;
    if (this.peek(TokenKind.NAME)) {
      name2 = this.parseName();
    }
    return this.node(start, {
      kind: Kind.OPERATION_DEFINITION,
      operation,
      name: name2,
      variableDefinitions: this.parseVariableDefinitions(),
      directives: this.parseDirectives(false),
      selectionSet: this.parseSelectionSet()
    });
  }
  /**
   * OperationType : one of query mutation subscription
   */
  parseOperationType() {
    const operationToken = this.expectToken(TokenKind.NAME);
    switch (operationToken.value) {
      case "query":
        return OperationTypeNode.QUERY;
      case "mutation":
        return OperationTypeNode.MUTATION;
      case "subscription":
        return OperationTypeNode.SUBSCRIPTION;
    }
    throw this.unexpected(operationToken);
  }
  /**
   * VariableDefinitions : ( VariableDefinition+ )
   */
  parseVariableDefinitions() {
    return this.optionalMany(
      TokenKind.PAREN_L,
      this.parseVariableDefinition,
      TokenKind.PAREN_R
    );
  }
  /**
   * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?
   */
  parseVariableDefinition() {
    return this.node(this._lexer.token, {
      kind: Kind.VARIABLE_DEFINITION,
      variable: this.parseVariable(),
      type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),
      defaultValue: this.expectOptionalToken(TokenKind.EQUALS) ? this.parseConstValueLiteral() : void 0,
      directives: this.parseConstDirectives()
    });
  }
  /**
   * Variable : $ Name
   */
  parseVariable() {
    const start = this._lexer.token;
    this.expectToken(TokenKind.DOLLAR);
    return this.node(start, {
      kind: Kind.VARIABLE,
      name: this.parseName()
    });
  }
  /**
   * ```
   * SelectionSet : { Selection+ }
   * ```
   */
  parseSelectionSet() {
    return this.node(this._lexer.token, {
      kind: Kind.SELECTION_SET,
      selections: this.many(
        TokenKind.BRACE_L,
        this.parseSelection,
        TokenKind.BRACE_R
      )
    });
  }
  /**
   * Selection :
   *   - Field
   *   - FragmentSpread
   *   - InlineFragment
   */
  parseSelection() {
    return this.peek(TokenKind.SPREAD) ? this.parseFragment() : this.parseField();
  }
  /**
   * Field : Alias? Name Arguments? Directives? SelectionSet?
   *
   * Alias : Name :
   */
  parseField() {
    const start = this._lexer.token;
    const nameOrAlias = this.parseName();
    let alias;
    let name2;
    if (this.expectOptionalToken(TokenKind.COLON)) {
      alias = nameOrAlias;
      name2 = this.parseName();
    } else {
      name2 = nameOrAlias;
    }
    return this.node(start, {
      kind: Kind.FIELD,
      alias,
      name: name2,
      arguments: this.parseArguments(false),
      directives: this.parseDirectives(false),
      selectionSet: this.peek(TokenKind.BRACE_L) ? this.parseSelectionSet() : void 0
    });
  }
  /**
   * Arguments[Const] : ( Argument[?Const]+ )
   */
  parseArguments(isConst) {
    const item = isConst ? this.parseConstArgument : this.parseArgument;
    return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);
  }
  /**
   * Argument[Const] : Name : Value[?Const]
   */
  parseArgument(isConst = false) {
    const start = this._lexer.token;
    const name2 = this.parseName();
    this.expectToken(TokenKind.COLON);
    return this.node(start, {
      kind: Kind.ARGUMENT,
      name: name2,
      value: this.parseValueLiteral(isConst)
    });
  }
  parseConstArgument() {
    return this.parseArgument(true);
  }
  // Implements the parsing rules in the Fragments section.
  /**
   * Corresponds to both FragmentSpread and InlineFragment in the spec.
   *
   * FragmentSpread : ... FragmentName Directives?
   *
   * InlineFragment : ... TypeCondition? Directives? SelectionSet
   */
  parseFragment() {
    const start = this._lexer.token;
    this.expectToken(TokenKind.SPREAD);
    const hasTypeCondition = this.expectOptionalKeyword("on");
    if (!hasTypeCondition && this.peek(TokenKind.NAME)) {
      return this.node(start, {
        kind: Kind.FRAGMENT_SPREAD,
        name: this.parseFragmentName(),
        directives: this.parseDirectives(false)
      });
    }
    return this.node(start, {
      kind: Kind.INLINE_FRAGMENT,
      typeCondition: hasTypeCondition ? this.parseNamedType() : void 0,
      directives: this.parseDirectives(false),
      selectionSet: this.parseSelectionSet()
    });
  }
  /**
   * FragmentDefinition :
   *   - fragment FragmentName on TypeCondition Directives? SelectionSet
   *
   * TypeCondition : NamedType
   */
  parseFragmentDefinition() {
    const start = this._lexer.token;
    this.expectKeyword("fragment");
    if (this._options.allowLegacyFragmentVariables === true) {
      return this.node(start, {
        kind: Kind.FRAGMENT_DEFINITION,
        name: this.parseFragmentName(),
        variableDefinitions: this.parseVariableDefinitions(),
        typeCondition: (this.expectKeyword("on"), this.parseNamedType()),
        directives: this.parseDirectives(false),
        selectionSet: this.parseSelectionSet()
      });
    }
    return this.node(start, {
      kind: Kind.FRAGMENT_DEFINITION,
      name: this.parseFragmentName(),
      typeCondition: (this.expectKeyword("on"), this.parseNamedType()),
      directives: this.parseDirectives(false),
      selectionSet: this.parseSelectionSet()
    });
  }
  /**
   * FragmentName : Name but not `on`
   */
  parseFragmentName() {
    if (this._lexer.token.value === "on") {
      throw this.unexpected();
    }
    return this.parseName();
  }
  // Implements the parsing rules in the Values section.
  /**
   * Value[Const] :
   *   - [~Const] Variable
   *   - IntValue
   *   - FloatValue
   *   - StringValue
   *   - BooleanValue
   *   - NullValue
   *   - EnumValue
   *   - ListValue[?Const]
   *   - ObjectValue[?Const]
   *
   * BooleanValue : one of `true` `false`
   *
   * NullValue : `null`
   *
   * EnumValue : Name but not `true`, `false` or `null`
   */
  parseValueLiteral(isConst) {
    const token = this._lexer.token;
    switch (token.kind) {
      case TokenKind.BRACKET_L:
        return this.parseList(isConst);
      case TokenKind.BRACE_L:
        return this.parseObject(isConst);
      case TokenKind.INT:
        this.advanceLexer();
        return this.node(token, {
          kind: Kind.INT,
          value: token.value
        });
      case TokenKind.FLOAT:
        this.advanceLexer();
        return this.node(token, {
          kind: Kind.FLOAT,
          value: token.value
        });
      case TokenKind.STRING:
      case TokenKind.BLOCK_STRING:
        return this.parseStringLiteral();
      case TokenKind.NAME:
        this.advanceLexer();
        switch (token.value) {
          case "true":
            return this.node(token, {
              kind: Kind.BOOLEAN,
              value: true
            });
          case "false":
            return this.node(token, {
              kind: Kind.BOOLEAN,
              value: false
            });
          case "null":
            return this.node(token, {
              kind: Kind.NULL
            });
          default:
            return this.node(token, {
              kind: Kind.ENUM,
              value: token.value
            });
        }
      case TokenKind.DOLLAR:
        if (isConst) {
          this.expectToken(TokenKind.DOLLAR);
          if (this._lexer.token.kind === TokenKind.NAME) {
            const varName = this._lexer.token.value;
            throw syntaxError(
              this._lexer.source,
              token.start,
              `Unexpected variable "$${varName}" in constant value.`
            );
          } else {
            throw this.unexpected(token);
          }
        }
        return this.parseVariable();
      default:
        throw this.unexpected();
    }
  }
  parseConstValueLiteral() {
    return this.parseValueLiteral(true);
  }
  parseStringLiteral() {
    const token = this._lexer.token;
    this.advanceLexer();
    return this.node(token, {
      kind: Kind.STRING,
      value: token.value,
      block: token.kind === TokenKind.BLOCK_STRING
    });
  }
  /**
   * ListValue[Const] :
   *   - [ ]
   *   - [ Value[?Const]+ ]
   */
  parseList(isConst) {
    const item = () => this.parseValueLiteral(isConst);
    return this.node(this._lexer.token, {
      kind: Kind.LIST,
      values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R)
    });
  }
  /**
   * ```
   * ObjectValue[Const] :
   *   - { }
   *   - { ObjectField[?Const]+ }
   * ```
   */
  parseObject(isConst) {
    const item = () => this.parseObjectField(isConst);
    return this.node(this._lexer.token, {
      kind: Kind.OBJECT,
      fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R)
    });
  }
  /**
   * ObjectField[Const] : Name : Value[?Const]
   */
  parseObjectField(isConst) {
    const start = this._lexer.token;
    const name2 = this.parseName();
    this.expectToken(TokenKind.COLON);
    return this.node(start, {
      kind: Kind.OBJECT_FIELD,
      name: name2,
      value: this.parseValueLiteral(isConst)
    });
  }
  // Implements the parsing rules in the Directives section.
  /**
   * Directives[Const] : Directive[?Const]+
   */
  parseDirectives(isConst) {
    const directives = [];
    while (this.peek(TokenKind.AT)) {
      directives.push(this.parseDirective(isConst));
    }
    return directives;
  }
  parseConstDirectives() {
    return this.parseDirectives(true);
  }
  /**
   * ```
   * Directive[Const] : @ Name Arguments[?Const]?
   * ```
   */
  parseDirective(isConst) {
    const start = this._lexer.token;
    this.expectToken(TokenKind.AT);
    return this.node(start, {
      kind: Kind.DIRECTIVE,
      name: this.parseName(),
      arguments: this.parseArguments(isConst)
    });
  }
  // Implements the parsing rules in the Types section.
  /**
   * Type :
   *   - NamedType
   *   - ListType
   *   - NonNullType
   */
  parseTypeReference() {
    const start = this._lexer.token;
    let type2;
    if (this.expectOptionalToken(TokenKind.BRACKET_L)) {
      const innerType = this.parseTypeReference();
      this.expectToken(TokenKind.BRACKET_R);
      type2 = this.node(start, {
        kind: Kind.LIST_TYPE,
        type: innerType
      });
    } else {
      type2 = this.parseNamedType();
    }
    if (this.expectOptionalToken(TokenKind.BANG)) {
      return this.node(start, {
        kind: Kind.NON_NULL_TYPE,
        type: type2
      });
    }
    return type2;
  }
  /**
   * NamedType : Name
   */
  parseNamedType() {
    return this.node(this._lexer.token, {
      kind: Kind.NAMED_TYPE,
      name: this.parseName()
    });
  }
  // Implements the parsing rules in the Type Definition section.
  peekDescription() {
    return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);
  }
  /**
   * Description : StringValue
   */
  parseDescription() {
    if (this.peekDescription()) {
      return this.parseStringLiteral();
    }
  }
  /**
   * ```
   * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }
   * ```
   */
  parseSchemaDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("schema");
    const directives = this.parseConstDirectives();
    const operationTypes = this.many(
      TokenKind.BRACE_L,
      this.parseOperationTypeDefinition,
      TokenKind.BRACE_R
    );
    return this.node(start, {
      kind: Kind.SCHEMA_DEFINITION,
      description: description2,
      directives,
      operationTypes
    });
  }
  /**
   * OperationTypeDefinition : OperationType : NamedType
   */
  parseOperationTypeDefinition() {
    const start = this._lexer.token;
    const operation = this.parseOperationType();
    this.expectToken(TokenKind.COLON);
    const type2 = this.parseNamedType();
    return this.node(start, {
      kind: Kind.OPERATION_TYPE_DEFINITION,
      operation,
      type: type2
    });
  }
  /**
   * ScalarTypeDefinition : Description? scalar Name Directives[Const]?
   */
  parseScalarTypeDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("scalar");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    return this.node(start, {
      kind: Kind.SCALAR_TYPE_DEFINITION,
      description: description2,
      name: name2,
      directives
    });
  }
  /**
   * ObjectTypeDefinition :
   *   Description?
   *   type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?
   */
  parseObjectTypeDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("type");
    const name2 = this.parseName();
    const interfaces = this.parseImplementsInterfaces();
    const directives = this.parseConstDirectives();
    const fields = this.parseFieldsDefinition();
    return this.node(start, {
      kind: Kind.OBJECT_TYPE_DEFINITION,
      description: description2,
      name: name2,
      interfaces,
      directives,
      fields
    });
  }
  /**
   * ImplementsInterfaces :
   *   - implements `&`? NamedType
   *   - ImplementsInterfaces & NamedType
   */
  parseImplementsInterfaces() {
    return this.expectOptionalKeyword("implements") ? this.delimitedMany(TokenKind.AMP, this.parseNamedType) : [];
  }
  /**
   * ```
   * FieldsDefinition : { FieldDefinition+ }
   * ```
   */
  parseFieldsDefinition() {
    return this.optionalMany(
      TokenKind.BRACE_L,
      this.parseFieldDefinition,
      TokenKind.BRACE_R
    );
  }
  /**
   * FieldDefinition :
   *   - Description? Name ArgumentsDefinition? : Type Directives[Const]?
   */
  parseFieldDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    const name2 = this.parseName();
    const args = this.parseArgumentDefs();
    this.expectToken(TokenKind.COLON);
    const type2 = this.parseTypeReference();
    const directives = this.parseConstDirectives();
    return this.node(start, {
      kind: Kind.FIELD_DEFINITION,
      description: description2,
      name: name2,
      arguments: args,
      type: type2,
      directives
    });
  }
  /**
   * ArgumentsDefinition : ( InputValueDefinition+ )
   */
  parseArgumentDefs() {
    return this.optionalMany(
      TokenKind.PAREN_L,
      this.parseInputValueDef,
      TokenKind.PAREN_R
    );
  }
  /**
   * InputValueDefinition :
   *   - Description? Name : Type DefaultValue? Directives[Const]?
   */
  parseInputValueDef() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    const name2 = this.parseName();
    this.expectToken(TokenKind.COLON);
    const type2 = this.parseTypeReference();
    let defaultValue;
    if (this.expectOptionalToken(TokenKind.EQUALS)) {
      defaultValue = this.parseConstValueLiteral();
    }
    const directives = this.parseConstDirectives();
    return this.node(start, {
      kind: Kind.INPUT_VALUE_DEFINITION,
      description: description2,
      name: name2,
      type: type2,
      defaultValue,
      directives
    });
  }
  /**
   * InterfaceTypeDefinition :
   *   - Description? interface Name Directives[Const]? FieldsDefinition?
   */
  parseInterfaceTypeDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("interface");
    const name2 = this.parseName();
    const interfaces = this.parseImplementsInterfaces();
    const directives = this.parseConstDirectives();
    const fields = this.parseFieldsDefinition();
    return this.node(start, {
      kind: Kind.INTERFACE_TYPE_DEFINITION,
      description: description2,
      name: name2,
      interfaces,
      directives,
      fields
    });
  }
  /**
   * UnionTypeDefinition :
   *   - Description? union Name Directives[Const]? UnionMemberTypes?
   */
  parseUnionTypeDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("union");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    const types2 = this.parseUnionMemberTypes();
    return this.node(start, {
      kind: Kind.UNION_TYPE_DEFINITION,
      description: description2,
      name: name2,
      directives,
      types: types2
    });
  }
  /**
   * UnionMemberTypes :
   *   - = `|`? NamedType
   *   - UnionMemberTypes | NamedType
   */
  parseUnionMemberTypes() {
    return this.expectOptionalToken(TokenKind.EQUALS) ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) : [];
  }
  /**
   * EnumTypeDefinition :
   *   - Description? enum Name Directives[Const]? EnumValuesDefinition?
   */
  parseEnumTypeDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("enum");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    const values = this.parseEnumValuesDefinition();
    return this.node(start, {
      kind: Kind.ENUM_TYPE_DEFINITION,
      description: description2,
      name: name2,
      directives,
      values
    });
  }
  /**
   * ```
   * EnumValuesDefinition : { EnumValueDefinition+ }
   * ```
   */
  parseEnumValuesDefinition() {
    return this.optionalMany(
      TokenKind.BRACE_L,
      this.parseEnumValueDefinition,
      TokenKind.BRACE_R
    );
  }
  /**
   * EnumValueDefinition : Description? EnumValue Directives[Const]?
   */
  parseEnumValueDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    const name2 = this.parseEnumValueName();
    const directives = this.parseConstDirectives();
    return this.node(start, {
      kind: Kind.ENUM_VALUE_DEFINITION,
      description: description2,
      name: name2,
      directives
    });
  }
  /**
   * EnumValue : Name but not `true`, `false` or `null`
   */
  parseEnumValueName() {
    if (this._lexer.token.value === "true" || this._lexer.token.value === "false" || this._lexer.token.value === "null") {
      throw syntaxError(
        this._lexer.source,
        this._lexer.token.start,
        `${getTokenDesc(
          this._lexer.token
        )} is reserved and cannot be used for an enum value.`
      );
    }
    return this.parseName();
  }
  /**
   * InputObjectTypeDefinition :
   *   - Description? input Name Directives[Const]? InputFieldsDefinition?
   */
  parseInputObjectTypeDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("input");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    const fields = this.parseInputFieldsDefinition();
    return this.node(start, {
      kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
      description: description2,
      name: name2,
      directives,
      fields
    });
  }
  /**
   * ```
   * InputFieldsDefinition : { InputValueDefinition+ }
   * ```
   */
  parseInputFieldsDefinition() {
    return this.optionalMany(
      TokenKind.BRACE_L,
      this.parseInputValueDef,
      TokenKind.BRACE_R
    );
  }
  /**
   * TypeSystemExtension :
   *   - SchemaExtension
   *   - TypeExtension
   *
   * TypeExtension :
   *   - ScalarTypeExtension
   *   - ObjectTypeExtension
   *   - InterfaceTypeExtension
   *   - UnionTypeExtension
   *   - EnumTypeExtension
   *   - InputObjectTypeDefinition
   */
  parseTypeSystemExtension() {
    const keywordToken = this._lexer.lookahead();
    if (keywordToken.kind === TokenKind.NAME) {
      switch (keywordToken.value) {
        case "schema":
          return this.parseSchemaExtension();
        case "scalar":
          return this.parseScalarTypeExtension();
        case "type":
          return this.parseObjectTypeExtension();
        case "interface":
          return this.parseInterfaceTypeExtension();
        case "union":
          return this.parseUnionTypeExtension();
        case "enum":
          return this.parseEnumTypeExtension();
        case "input":
          return this.parseInputObjectTypeExtension();
      }
    }
    throw this.unexpected(keywordToken);
  }
  /**
   * ```
   * SchemaExtension :
   *  - extend schema Directives[Const]? { OperationTypeDefinition+ }
   *  - extend schema Directives[Const]
   * ```
   */
  parseSchemaExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("schema");
    const directives = this.parseConstDirectives();
    const operationTypes = this.optionalMany(
      TokenKind.BRACE_L,
      this.parseOperationTypeDefinition,
      TokenKind.BRACE_R
    );
    if (directives.length === 0 && operationTypes.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.SCHEMA_EXTENSION,
      directives,
      operationTypes
    });
  }
  /**
   * ScalarTypeExtension :
   *   - extend scalar Name Directives[Const]
   */
  parseScalarTypeExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("scalar");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    if (directives.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.SCALAR_TYPE_EXTENSION,
      name: name2,
      directives
    });
  }
  /**
   * ObjectTypeExtension :
   *  - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
   *  - extend type Name ImplementsInterfaces? Directives[Const]
   *  - extend type Name ImplementsInterfaces
   */
  parseObjectTypeExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("type");
    const name2 = this.parseName();
    const interfaces = this.parseImplementsInterfaces();
    const directives = this.parseConstDirectives();
    const fields = this.parseFieldsDefinition();
    if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.OBJECT_TYPE_EXTENSION,
      name: name2,
      interfaces,
      directives,
      fields
    });
  }
  /**
   * InterfaceTypeExtension :
   *  - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition
   *  - extend interface Name ImplementsInterfaces? Directives[Const]
   *  - extend interface Name ImplementsInterfaces
   */
  parseInterfaceTypeExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("interface");
    const name2 = this.parseName();
    const interfaces = this.parseImplementsInterfaces();
    const directives = this.parseConstDirectives();
    const fields = this.parseFieldsDefinition();
    if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.INTERFACE_TYPE_EXTENSION,
      name: name2,
      interfaces,
      directives,
      fields
    });
  }
  /**
   * UnionTypeExtension :
   *   - extend union Name Directives[Const]? UnionMemberTypes
   *   - extend union Name Directives[Const]
   */
  parseUnionTypeExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("union");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    const types2 = this.parseUnionMemberTypes();
    if (directives.length === 0 && types2.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.UNION_TYPE_EXTENSION,
      name: name2,
      directives,
      types: types2
    });
  }
  /**
   * EnumTypeExtension :
   *   - extend enum Name Directives[Const]? EnumValuesDefinition
   *   - extend enum Name Directives[Const]
   */
  parseEnumTypeExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("enum");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    const values = this.parseEnumValuesDefinition();
    if (directives.length === 0 && values.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.ENUM_TYPE_EXTENSION,
      name: name2,
      directives,
      values
    });
  }
  /**
   * InputObjectTypeExtension :
   *   - extend input Name Directives[Const]? InputFieldsDefinition
   *   - extend input Name Directives[Const]
   */
  parseInputObjectTypeExtension() {
    const start = this._lexer.token;
    this.expectKeyword("extend");
    this.expectKeyword("input");
    const name2 = this.parseName();
    const directives = this.parseConstDirectives();
    const fields = this.parseInputFieldsDefinition();
    if (directives.length === 0 && fields.length === 0) {
      throw this.unexpected();
    }
    return this.node(start, {
      kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
      name: name2,
      directives,
      fields
    });
  }
  /**
   * ```
   * DirectiveDefinition :
   *   - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations
   * ```
   */
  parseDirectiveDefinition() {
    const start = this._lexer.token;
    const description2 = this.parseDescription();
    this.expectKeyword("directive");
    this.expectToken(TokenKind.AT);
    const name2 = this.parseName();
    const args = this.parseArgumentDefs();
    const repeatable = this.expectOptionalKeyword("repeatable");
    this.expectKeyword("on");
    const locations = this.parseDirectiveLocations();
    return this.node(start, {
      kind: Kind.DIRECTIVE_DEFINITION,
      description: description2,
      name: name2,
      arguments: args,
      repeatable,
      locations
    });
  }
  /**
   * DirectiveLocations :
   *   - `|`? DirectiveLocation
   *   - DirectiveLocations | DirectiveLocation
   */
  parseDirectiveLocations() {
    return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);
  }
  /*
   * DirectiveLocation :
   *   - ExecutableDirectiveLocation
   *   - TypeSystemDirectiveLocation
   *
   * ExecutableDirectiveLocation : one of
   *   `QUERY`
   *   `MUTATION`
   *   `SUBSCRIPTION`
   *   `FIELD`
   *   `FRAGMENT_DEFINITION`
   *   `FRAGMENT_SPREAD`
   *   `INLINE_FRAGMENT`
   *
   * TypeSystemDirectiveLocation : one of
   *   `SCHEMA`
   *   `SCALAR`
   *   `OBJECT`
   *   `FIELD_DEFINITION`
   *   `ARGUMENT_DEFINITION`
   *   `INTERFACE`
   *   `UNION`
   *   `ENUM`
   *   `ENUM_VALUE`
   *   `INPUT_OBJECT`
   *   `INPUT_FIELD_DEFINITION`
   */
  parseDirectiveLocation() {
    const start = this._lexer.token;
    const name2 = this.parseName();
    if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name2.value)) {
      return name2;
    }
    throw this.unexpected(start);
  }
  // Core parsing utility functions
  /**
   * Returns a node that, if configured to do so, sets a "loc" field as a
   * location object, used to identify the place in the source that created a
   * given parsed object.
   */
  node(startToken, node) {
    if (this._options.noLocation !== true) {
      node.loc = new Location(
        startToken,
        this._lexer.lastToken,
        this._lexer.source
      );
    }
    return node;
  }
  /**
   * Determines if the next token is of a given kind
   */
  peek(kind) {
    return this._lexer.token.kind === kind;
  }
  /**
   * If the next token is of the given kind, return that token after advancing the lexer.
   * Otherwise, do not change the parser state and throw an error.
   */
  expectToken(kind) {
    const token = this._lexer.token;
    if (token.kind === kind) {
      this.advanceLexer();
      return token;
    }
    throw syntaxError(
      this._lexer.source,
      token.start,
      `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`
    );
  }
  /**
   * If the next token is of the given kind, return "true" after advancing the lexer.
   * Otherwise, do not change the parser state and return "false".
   */
  expectOptionalToken(kind) {
    const token = this._lexer.token;
    if (token.kind === kind) {
      this.advanceLexer();
      return true;
    }
    return false;
  }
  /**
   * If the next token is a given keyword, advance the lexer.
   * Otherwise, do not change the parser state and throw an error.
   */
  expectKeyword(value) {
    const token = this._lexer.token;
    if (token.kind === TokenKind.NAME && token.value === value) {
      this.advanceLexer();
    } else {
      throw syntaxError(
        this._lexer.source,
        token.start,
        `Expected "${value}", found ${getTokenDesc(token)}.`
      );
    }
  }
  /**
   * If the next token is a given keyword, return "true" after advancing the lexer.
   * Otherwise, do not change the parser state and return "false".
   */
  expectOptionalKeyword(value) {
    const token = this._lexer.token;
    if (token.kind === TokenKind.NAME && token.value === value) {
      this.advanceLexer();
      return true;
    }
    return false;
  }
  /**
   * Helper function for creating an error when an unexpected lexed token is encountered.
   */
  unexpected(atToken) {
    const token = atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;
    return syntaxError(
      this._lexer.source,
      token.start,
      `Unexpected ${getTokenDesc(token)}.`
    );
  }
  /**
   * Returns a possibly empty list of parse nodes, determined by the parseFn.
   * This list begins with a lex token of openKind and ends with a lex token of closeKind.
   * Advances the parser to the next lex token after the closing token.
   */
  any(openKind, parseFn, closeKind) {
    this.expectToken(openKind);
    const nodes = [];
    while (!this.expectOptionalToken(closeKind)) {
      nodes.push(parseFn.call(this));
    }
    return nodes;
  }
  /**
   * Returns a list of parse nodes, determined by the parseFn.
   * It can be empty only if open token is missing otherwise it will always return non-empty list
   * that begins with a lex token of openKind and ends with a lex token of closeKind.
   * Advances the parser to the next lex token after the closing token.
   */
  optionalMany(openKind, parseFn, closeKind) {
    if (this.expectOptionalToken(openKind)) {
      const nodes = [];
      do {
        nodes.push(parseFn.call(this));
      } while (!this.expectOptionalToken(closeKind));
      return nodes;
    }
    return [];
  }
  /**
   * Returns a non-empty list of parse nodes, determined by the parseFn.
   * This list begins with a lex token of openKind and ends with a lex token of closeKind.
   * Advances the parser to the next lex token after the closing token.
   */
  many(openKind, parseFn, closeKind) {
    this.expectToken(openKind);
    const nodes = [];
    do {
      nodes.push(parseFn.call(this));
    } while (!this.expectOptionalToken(closeKind));
    return nodes;
  }
  /**
   * Returns a non-empty list of parse nodes, determined by the parseFn.
   * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.
   * Advances the parser to the next lex token after last item in the list.
   */
  delimitedMany(delimiterKind, parseFn) {
    this.expectOptionalToken(delimiterKind);
    const nodes = [];
    do {
      nodes.push(parseFn.call(this));
    } while (this.expectOptionalToken(delimiterKind));
    return nodes;
  }
  advanceLexer() {
    const { maxTokens } = this._options;
    const token = this._lexer.advance();
    if (maxTokens !== void 0 && token.kind !== TokenKind.EOF) {
      ++this._tokenCounter;
      if (this._tokenCounter > maxTokens) {
        throw syntaxError(
          this._lexer.source,
          token.start,
          `Document contains more that ${maxTokens} tokens. Parsing aborted.`
        );
      }
    }
  }
};
function getTokenDesc(token) {
  const value = token.value;
  return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : "");
}
function getTokenKindDesc(kind) {
  return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind;
}
const MAX_SUGGESTIONS = 5;
function didYouMean(firstArg, secondArg) {
  const [subMessage, suggestionsArg] = secondArg ? [firstArg, secondArg] : [void 0, firstArg];
  let message = " Did you mean ";
  if (subMessage) {
    message += subMessage + " ";
  }
  const suggestions = suggestionsArg.map((x) => `"${x}"`);
  switch (suggestions.length) {
    case 0:
      return "";
    case 1:
      return message + suggestions[0] + "?";
    case 2:
      return message + suggestions[0] + " or " + suggestions[1] + "?";
  }
  const selected = suggestions.slice(0, MAX_SUGGESTIONS);
  const lastItem = selected.pop();
  return message + selected.join(", ") + ", or " + lastItem + "?";
}
function identityFunc(x) {
  return x;
}
function keyMap(list, keyFn) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const item of list) {
    result[keyFn(item)] = item;
  }
  return result;
}
function keyValMap(list, keyFn, valFn) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const item of list) {
    result[keyFn(item)] = valFn(item);
  }
  return result;
}
function mapValue(map, fn) {
  const result = /* @__PURE__ */ Object.create(null);
  for (const key of Object.keys(map)) {
    result[key] = fn(map[key], key);
  }
  return result;
}
function naturalCompare(aStr, bStr) {
  let aIndex = 0;
  let bIndex = 0;
  while (aIndex < aStr.length && bIndex < bStr.length) {
    let aChar = aStr.charCodeAt(aIndex);
    let bChar = bStr.charCodeAt(bIndex);
    if (isDigit(aChar) && isDigit(bChar)) {
      let aNum = 0;
      do {
        ++aIndex;
        aNum = aNum * 10 + aChar - DIGIT_0;
        aChar = aStr.charCodeAt(aIndex);
      } while (isDigit(aChar) && aNum > 0);
      let bNum = 0;
      do {
        ++bIndex;
        bNum = bNum * 10 + bChar - DIGIT_0;
        bChar = bStr.charCodeAt(bIndex);
      } while (isDigit(bChar) && bNum > 0);
      if (aNum < bNum) {
        return -1;
      }
      if (aNum > bNum) {
        return 1;
      }
    } else {
      if (aChar < bChar) {
        return -1;
      }
      if (aChar > bChar) {
        return 1;
      }
      ++aIndex;
      ++bIndex;
    }
  }
  return aStr.length - bStr.length;
}
const DIGIT_0 = 48;
const DIGIT_9 = 57;
function isDigit(code2) {
  return !isNaN(code2) && DIGIT_0 <= code2 && code2 <= DIGIT_9;
}
function suggestionList(input, options2) {
  const optionsByDistance = /* @__PURE__ */ Object.create(null);
  const lexicalDistance = new LexicalDistance(input);
  const threshold = Math.floor(input.length * 0.4) + 1;
  for (const option of options2) {
    const distance = lexicalDistance.measure(option, threshold);
    if (distance !== void 0) {
      optionsByDistance[option] = distance;
    }
  }
  return Object.keys(optionsByDistance).sort((a, b) => {
    const distanceDiff = optionsByDistance[a] - optionsByDistance[b];
    return distanceDiff !== 0 ? distanceDiff : naturalCompare(a, b);
  });
}
class LexicalDistance {
  constructor(input) {
    this._input = input;
    this._inputLowerCase = input.toLowerCase();
    this._inputArray = stringToArray(this._inputLowerCase);
    this._rows = [
      new Array(input.length + 1).fill(0),
      new Array(input.length + 1).fill(0),
      new Array(input.length + 1).fill(0)
    ];
  }
  measure(option, threshold) {
    if (this._input === option) {
      return 0;
    }
    const optionLowerCase = option.toLowerCase();
    if (this._inputLowerCase === optionLowerCase) {
      return 1;
    }
    let a = stringToArray(optionLowerCase);
    let b = this._inputArray;
    if (a.length < b.length) {
      const tmp = a;
      a = b;
      b = tmp;
    }
    const aLength = a.length;
    const bLength = b.length;
    if (aLength - bLength > threshold) {
      return void 0;
    }
    const rows = this._rows;
    for (let j = 0; j <= bLength; j++) {
      rows[0][j] = j;
    }
    for (let i = 1; i <= aLength; i++) {
      const upRow = rows[(i - 1) % 3];
      const currentRow = rows[i % 3];
      let smallestCell = currentRow[0] = i;
      for (let j = 1; j <= bLength; j++) {
        const cost = a[i - 1] === b[j - 1] ? 0 : 1;
        let currentCell = Math.min(
          upRow[j] + 1,
          // delete
          currentRow[j - 1] + 1,
          // insert
          upRow[j - 1] + cost
          // substitute
        );
        if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
          const doubleDiagonalCell = rows[(i - 2) % 3][j - 2];
          currentCell = Math.min(currentCell, doubleDiagonalCell + 1);
        }
        if (currentCell < smallestCell) {
          smallestCell = currentCell;
        }
        currentRow[j] = currentCell;
      }
      if (smallestCell > threshold) {
        return void 0;
      }
    }
    const distance = rows[aLength % 3][bLength];
    return distance <= threshold ? distance : void 0;
  }
}
function stringToArray(str) {
  const strLength = str.length;
  const array = new Array(strLength);
  for (let i = 0; i < strLength; ++i) {
    array[i] = str.charCodeAt(i);
  }
  return array;
}
function toObjMap(obj) {
  if (obj == null) {
    return /* @__PURE__ */ Object.create(null);
  }
  if (Object.getPrototypeOf(obj) === null) {
    return obj;
  }
  const map = /* @__PURE__ */ Object.create(null);
  for (const [key, value] of Object.entries(obj)) {
    map[key] = value;
  }
  return map;
}
function printString(str) {
  return `"${str.replace(escapedRegExp, escapedReplacer)}"`;
}
const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g;
function escapedReplacer(str) {
  return escapeSequences[str.charCodeAt(0)];
}
const escapeSequences = [
  "\\u0000",
  "\\u0001",
  "\\u0002",
  "\\u0003",
  "\\u0004",
  "\\u0005",
  "\\u0006",
  "\\u0007",
  "\\b",
  "\\t",
  "\\n",
  "\\u000B",
  "\\f",
  "\\r",
  "\\u000E",
  "\\u000F",
  "\\u0010",
  "\\u0011",
  "\\u0012",
  "\\u0013",
  "\\u0014",
  "\\u0015",
  "\\u0016",
  "\\u0017",
  "\\u0018",
  "\\u0019",
  "\\u001A",
  "\\u001B",
  "\\u001C",
  "\\u001D",
  "\\u001E",
  "\\u001F",
  "",
  "",
  '\\"',
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  // 2F
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  // 3F
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  // 4F
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "\\\\",
  "",
  "",
  "",
  // 5F
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  // 6F
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "",
  "\\u007F",
  "\\u0080",
  "\\u0081",
  "\\u0082",
  "\\u0083",
  "\\u0084",
  "\\u0085",
  "\\u0086",
  "\\u0087",
  "\\u0088",
  "\\u0089",
  "\\u008A",
  "\\u008B",
  "\\u008C",
  "\\u008D",
  "\\u008E",
  "\\u008F",
  "\\u0090",
  "\\u0091",
  "\\u0092",
  "\\u0093",
  "\\u0094",
  "\\u0095",
  "\\u0096",
  "\\u0097",
  "\\u0098",
  "\\u0099",
  "\\u009A",
  "\\u009B",
  "\\u009C",
  "\\u009D",
  "\\u009E",
  "\\u009F"
];
const BREAK = Object.freeze({});
function visit(root, visitor, visitorKeys = QueryDocumentKeys) {
  const enterLeaveMap = /* @__PURE__ */ new Map();
  for (const kind of Object.values(Kind)) {
    enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind));
  }
  let stack = void 0;
  let inArray = Array.isArray(root);
  let keys = [root];
  let index = -1;
  let edits = [];
  let node = root;
  let key = void 0;
  let parent = void 0;
  const path = [];
  const ancestors = [];
  do {
    index++;
    const isLeaving = index === keys.length;
    const isEdited = isLeaving && edits.length !== 0;
    if (isLeaving) {
      key = ancestors.length === 0 ? void 0 : path[path.length - 1];
      node = parent;
      parent = ancestors.pop();
      if (isEdited) {
        if (inArray) {
          node = node.slice();
          let editOffset = 0;
          for (const [editKey, editValue] of edits) {
            const arrayKey = editKey - editOffset;
            if (editValue === null) {
              node.splice(arrayKey, 1);
              editOffset++;
            } else {
              node[arrayKey] = editValue;
            }
          }
        } else {
          node = Object.defineProperties(
            {},
            Object.getOwnPropertyDescriptors(node)
          );
          for (const [editKey, editValue] of edits) {
            node[editKey] = editValue;
          }
        }
      }
      index = stack.index;
      keys = stack.keys;
      edits = stack.edits;
      inArray = stack.inArray;
      stack = stack.prev;
    } else if (parent) {
      key = inArray ? index : keys[index];
      node = parent[key];
      if (node === null || node === void 0) {
        continue;
      }
      path.push(key);
    }
    let result;
    if (!Array.isArray(node)) {
      var _enterLeaveMap$get, _enterLeaveMap$get2;
      isNode(node) || devAssert(false, `Invalid AST Node: ${inspect$2(node)}.`);
      const visitFn = isLeaving ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get === void 0 ? void 0 : _enterLeaveMap$get.leave : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || _enterLeaveMap$get2 === void 0 ? void 0 : _enterLeaveMap$get2.enter;
      result = visitFn === null || visitFn === void 0 ? void 0 : visitFn.call(visitor, node, key, parent, path, ancestors);
      if (result === BREAK) {
        break;
      }
      if (result === false) {
        if (!isLeaving) {
          path.pop();
          continue;
        }
      } else if (result !== void 0) {
        edits.push([key, result]);
        if (!isLeaving) {
          if (isNode(result)) {
            node = result;
          } else {
            path.pop();
            continue;
          }
        }
      }
    }
    if (result === void 0 && isEdited) {
      edits.push([key, node]);
    }
    if (isLeaving) {
      path.pop();
    } else {
      var _node$kind;
      stack = {
        inArray,
        index,
        keys,
        edits,
        prev: stack
      };
      inArray = Array.isArray(node);
      keys = inArray ? node : (_node$kind = visitorKeys[node.kind]) !== null && _node$kind !== void 0 ? _node$kind : [];
      index = -1;
      edits = [];
      if (parent) {
        ancestors.push(parent);
      }
      parent = node;
    }
  } while (stack !== void 0);
  if (edits.length !== 0) {
    return edits[edits.length - 1][1];
  }
  return root;
}
function visitInParallel(visitors) {
  const skipping = new Array(visitors.length).fill(null);
  const mergedVisitor = /* @__PURE__ */ Object.create(null);
  for (const kind of Object.values(Kind)) {
    let hasVisitor = false;
    const enterList = new Array(visitors.length).fill(void 0);
    const leaveList = new Array(visitors.length).fill(void 0);
    for (let i = 0; i < visitors.length; ++i) {
      const { enter, leave } = getEnterLeaveForKind(visitors[i], kind);
      hasVisitor || (hasVisitor = enter != null || leave != null);
      enterList[i] = enter;
      leaveList[i] = leave;
    }
    if (!hasVisitor) {
      continue;
    }
    const mergedEnterLeave = {
      enter(...args) {
        const node = args[0];
        for (let i = 0; i < visitors.length; i++) {
          if (skipping[i] === null) {
            var _enterList$i;
            const result = (_enterList$i = enterList[i]) === null || _enterList$i === void 0 ? void 0 : _enterList$i.apply(visitors[i], args);
            if (result === false) {
              skipping[i] = node;
            } else if (result === BREAK) {
              skipping[i] = BREAK;
            } else if (result !== void 0) {
              return result;
            }
          }
        }
      },
      leave(...args) {
        const node = args[0];
        for (let i = 0; i < visitors.length; i++) {
          if (skipping[i] === null) {
            var _leaveList$i;
            const result = (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 ? void 0 : _leaveList$i.apply(visitors[i], args);
            if (result === BREAK) {
              skipping[i] = BREAK;
            } else if (result !== void 0 && result !== false) {
              return result;
            }
          } else if (skipping[i] === node) {
            skipping[i] = null;
          }
        }
      }
    };
    mergedVisitor[kind] = mergedEnterLeave;
  }
  return mergedVisitor;
}
function getEnterLeaveForKind(visitor, kind) {
  const kindVisitor = visitor[kind];
  if (typeof kindVisitor === "object") {
    return kindVisitor;
  } else if (typeof kindVisitor === "function") {
    return {
      enter: kindVisitor,
      leave: void 0
    };
  }
  return {
    enter: visitor.enter,
    leave: visitor.leave
  };
}
function print(ast) {
  return visit(ast, printDocASTReducer$1);
}
const MAX_LINE_LENGTH$1 = 80;
const printDocASTReducer$1 = {
  Name: {
    leave: (node) => node.value
  },
  Variable: {
    leave: (node) => "$" + node.name
  },
  // Document
  Document: {
    leave: (node) => join$1(node.definitions, "\n\n")
  },
  OperationDefinition: {
    leave(node) {
      const varDefs = wrap$1("(", join$1(node.variableDefinitions, ", "), ")");
      const prefix = join$1(
        [
          node.operation,
          join$1([node.name, varDefs]),
          join$1(node.directives, " ")
        ],
        " "
      );
      return (prefix === "query" ? "" : prefix + " ") + node.selectionSet;
    }
  },
  VariableDefinition: {
    leave: ({ variable, type: type2, defaultValue, directives }) => variable + ": " + type2 + wrap$1(" = ", defaultValue) + wrap$1(" ", join$1(directives, " "))
  },
  SelectionSet: {
    leave: ({ selections }) => block$1(selections)
  },
  Field: {
    leave({ alias, name: name2, arguments: args, directives, selectionSet }) {
      const prefix = wrap$1("", alias, ": ") + name2;
      let argsLine = prefix + wrap$1("(", join$1(args, ", "), ")");
      if (argsLine.length > MAX_LINE_LENGTH$1) {
        argsLine = prefix + wrap$1("(\n", indent$1(join$1(args, "\n")), "\n)");
      }
      return join$1([argsLine, join$1(directives, " "), selectionSet], " ");
    }
  },
  Argument: {
    leave: ({ name: name2, value }) => name2 + ": " + value
  },
  // Fragments
  FragmentSpread: {
    leave: ({ name: name2, directives }) => "..." + name2 + wrap$1(" ", join$1(directives, " "))
  },
  InlineFragment: {
    leave: ({ typeCondition, directives, selectionSet }) => join$1(
      [
        "...",
        wrap$1("on ", typeCondition),
        join$1(directives, " "),
        selectionSet
      ],
      " "
    )
  },
  FragmentDefinition: {
    leave: ({ name: name2, typeCondition, variableDefinitions, directives, selectionSet }) => (
      // or removed in the future.
      `fragment ${name2}${wrap$1("(", join$1(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap$1("", join$1(directives, " "), " ")}` + selectionSet
    )
  },
  // Value
  IntValue: {
    leave: ({ value }) => value
  },
  FloatValue: {
    leave: ({ value }) => value
  },
  StringValue: {
    leave: ({ value, block: isBlockString }) => isBlockString ? printBlockString$1(value) : printString(value)
  },
  BooleanValue: {
    leave: ({ value }) => value ? "true" : "false"
  },
  NullValue: {
    leave: () => "null"
  },
  EnumValue: {
    leave: ({ value }) => value
  },
  ListValue: {
    leave: ({ values }) => "[" + join$1(values, ", ") + "]"
  },
  ObjectValue: {
    leave: ({ fields }) => "{" + join$1(fields, ", ") + "}"
  },
  ObjectField: {
    leave: ({ name: name2, value }) => name2 + ": " + value
  },
  // Directive
  Directive: {
    leave: ({ name: name2, arguments: args }) => "@" + name2 + wrap$1("(", join$1(args, ", "), ")")
  },
  // Type
  NamedType: {
    leave: ({ name: name2 }) => name2
  },
  ListType: {
    leave: ({ type: type2 }) => "[" + type2 + "]"
  },
  NonNullType: {
    leave: ({ type: type2 }) => type2 + "!"
  },
  // Type System Definitions
  SchemaDefinition: {
    leave: ({ description: description2, directives, operationTypes }) => wrap$1("", description2, "\n") + join$1(["schema", join$1(directives, " "), block$1(operationTypes)], " ")
  },
  OperationTypeDefinition: {
    leave: ({ operation, type: type2 }) => operation + ": " + type2
  },
  ScalarTypeDefinition: {
    leave: ({ description: description2, name: name2, directives }) => wrap$1("", description2, "\n") + join$1(["scalar", name2, join$1(directives, " ")], " ")
  },
  ObjectTypeDefinition: {
    leave: ({ description: description2, name: name2, interfaces, directives, fields }) => wrap$1("", description2, "\n") + join$1(
      [
        "type",
        name2,
        wrap$1("implements ", join$1(interfaces, " & ")),
        join$1(directives, " "),
        block$1(fields)
      ],
      " "
    )
  },
  FieldDefinition: {
    leave: ({ description: description2, name: name2, arguments: args, type: type2, directives }) => wrap$1("", description2, "\n") + name2 + (hasMultilineItems$1(args) ? wrap$1("(\n", indent$1(join$1(args, "\n")), "\n)") : wrap$1("(", join$1(args, ", "), ")")) + ": " + type2 + wrap$1(" ", join$1(directives, " "))
  },
  InputValueDefinition: {
    leave: ({ description: description2, name: name2, type: type2, defaultValue, directives }) => wrap$1("", description2, "\n") + join$1(
      [name2 + ": " + type2, wrap$1("= ", defaultValue), join$1(directives, " ")],
      " "
    )
  },
  InterfaceTypeDefinition: {
    leave: ({ description: description2, name: name2, interfaces, directives, fields }) => wrap$1("", description2, "\n") + join$1(
      [
        "interface",
        name2,
        wrap$1("implements ", join$1(interfaces, " & ")),
        join$1(directives, " "),
        block$1(fields)
      ],
      " "
    )
  },
  UnionTypeDefinition: {
    leave: ({ description: description2, name: name2, directives, types: types2 }) => wrap$1("", description2, "\n") + join$1(
      ["union", name2, join$1(directives, " "), wrap$1("= ", join$1(types2, " | "))],
      " "
    )
  },
  EnumTypeDefinition: {
    leave: ({ description: description2, name: name2, directives, values }) => wrap$1("", description2, "\n") + join$1(["enum", name2, join$1(directives, " "), block$1(values)], " ")
  },
  EnumValueDefinition: {
    leave: ({ description: description2, name: name2, directives }) => wrap$1("", description2, "\n") + join$1([name2, join$1(directives, " ")], " ")
  },
  InputObjectTypeDefinition: {
    leave: ({ description: description2, name: name2, directives, fields }) => wrap$1("", description2, "\n") + join$1(["input", name2, join$1(directives, " "), block$1(fields)], " ")
  },
  DirectiveDefinition: {
    leave: ({ description: description2, name: name2, arguments: args, repeatable, locations }) => wrap$1("", description2, "\n") + "directive @" + name2 + (hasMultilineItems$1(args) ? wrap$1("(\n", indent$1(join$1(args, "\n")), "\n)") : wrap$1("(", join$1(args, ", "), ")")) + (repeatable ? " repeatable" : "") + " on " + join$1(locations, " | ")
  },
  SchemaExtension: {
    leave: ({ directives, operationTypes }) => join$1(
      ["extend schema", join$1(directives, " "), block$1(operationTypes)],
      " "
    )
  },
  ScalarTypeExtension: {
    leave: ({ name: name2, directives }) => join$1(["extend scalar", name2, join$1(directives, " ")], " ")
  },
  ObjectTypeExtension: {
    leave: ({ name: name2, interfaces, directives, fields }) => join$1(
      [
        "extend type",
        name2,
        wrap$1("implements ", join$1(interfaces, " & ")),
        join$1(directives, " "),
        block$1(fields)
      ],
      " "
    )
  },
  InterfaceTypeExtension: {
    leave: ({ name: name2, interfaces, directives, fields }) => join$1(
      [
        "extend interface",
        name2,
        wrap$1("implements ", join$1(interfaces, " & ")),
        join$1(directives, " "),
        block$1(fields)
      ],
      " "
    )
  },
  UnionTypeExtension: {
    leave: ({ name: name2, directives, types: types2 }) => join$1(
      [
        "extend union",
        name2,
        join$1(directives, " "),
        wrap$1("= ", join$1(types2, " | "))
      ],
      " "
    )
  },
  EnumTypeExtension: {
    leave: ({ name: name2, directives, values }) => join$1(["extend enum", name2, join$1(directives, " "), block$1(values)], " ")
  },
  InputObjectTypeExtension: {
    leave: ({ name: name2, directives, fields }) => join$1(["extend input", name2, join$1(directives, " "), block$1(fields)], " ")
  }
};
function join$1(maybeArray, separator = "") {
  var _maybeArray$filter$jo;
  return (_maybeArray$filter$jo = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.filter((x) => x).join(separator)) !== null && _maybeArray$filter$jo !== void 0 ? _maybeArray$filter$jo : "";
}
function block$1(array) {
  return wrap$1("{\n", indent$1(join$1(array, "\n")), "\n}");
}
function wrap$1(start, maybeString, end = "") {
  return maybeString != null && maybeString !== "" ? start + maybeString + end : "";
}
function indent$1(str) {
  return wrap$1("  ", str.replace(/\n/g, "\n  "));
}
function hasMultilineItems$1(maybeArray) {
  var _maybeArray$some;
  return (_maybeArray$some = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some((str) => str.includes("\n"))) !== null && _maybeArray$some !== void 0 ? _maybeArray$some : false;
}
function valueFromASTUntyped(valueNode, variables) {
  switch (valueNode.kind) {
    case Kind.NULL:
      return null;
    case Kind.INT:
      return parseInt(valueNode.value, 10);
    case Kind.FLOAT:
      return parseFloat(valueNode.value);
    case Kind.STRING:
    case Kind.ENUM:
    case Kind.BOOLEAN:
      return valueNode.value;
    case Kind.LIST:
      return valueNode.values.map(
        (node) => valueFromASTUntyped(node, variables)
      );
    case Kind.OBJECT:
      return keyValMap(
        valueNode.fields,
        (field) => field.name.value,
        (field) => valueFromASTUntyped(field.value, variables)
      );
    case Kind.VARIABLE:
      return variables === null || variables === void 0 ? void 0 : variables[valueNode.name.value];
  }
}
function assertName(name2) {
  name2 != null || devAssert(false, "Must provide name.");
  typeof name2 === "string" || devAssert(false, "Expected name to be a string.");
  if (name2.length === 0) {
    throw new GraphQLError("Expected name to be a non-empty string.");
  }
  for (let i = 1; i < name2.length; ++i) {
    if (!isNameContinue(name2.charCodeAt(i))) {
      throw new GraphQLError(
        `Names must only contain [_a-zA-Z0-9] but "${name2}" does not.`
      );
    }
  }
  if (!isNameStart(name2.charCodeAt(0))) {
    throw new GraphQLError(
      `Names must start with [_a-zA-Z] but "${name2}" does not.`
    );
  }
  return name2;
}
function assertEnumValueName(name2) {
  if (name2 === "true" || name2 === "false" || name2 === "null") {
    throw new GraphQLError(`Enum values cannot be named: ${name2}`);
  }
  return assertName(name2);
}
function isType(type2) {
  return isScalarType(type2) || isObjectType(type2) || isInterfaceType(type2) || isUnionType(type2) || isEnumType(type2) || isInputObjectType(type2) || isListType(type2) || isNonNullType(type2);
}
function isScalarType(type2) {
  return instanceOf(type2, GraphQLScalarType);
}
function isObjectType(type2) {
  return instanceOf(type2, GraphQLObjectType);
}
function isInterfaceType(type2) {
  return instanceOf(type2, GraphQLInterfaceType);
}
function isUnionType(type2) {
  return instanceOf(type2, GraphQLUnionType);
}
function isEnumType(type2) {
  return instanceOf(type2, GraphQLEnumType);
}
function isInputObjectType(type2) {
  return instanceOf(type2, GraphQLInputObjectType);
}
function isListType(type2) {
  return instanceOf(type2, GraphQLList);
}
function isNonNullType(type2) {
  return instanceOf(type2, GraphQLNonNull);
}
function isInputType(type2) {
  return isScalarType(type2) || isEnumType(type2) || isInputObjectType(type2) || isWrappingType(type2) && isInputType(type2.ofType);
}
function isOutputType(type2) {
  return isScalarType(type2) || isObjectType(type2) || isInterfaceType(type2) || isUnionType(type2) || isEnumType(type2) || isWrappingType(type2) && isOutputType(type2.ofType);
}
function isLeafType(type2) {
  return isScalarType(type2) || isEnumType(type2);
}
function isCompositeType(type2) {
  return isObjectType(type2) || isInterfaceType(type2) || isUnionType(type2);
}
function isAbstractType(type2) {
  return isInterfaceType(type2) || isUnionType(type2);
}
class GraphQLList {
  constructor(ofType) {
    isType(ofType) || devAssert(false, `Expected ${inspect$2(ofType)} to be a GraphQL type.`);
    this.ofType = ofType;
  }
  get [Symbol.toStringTag]() {
    return "GraphQLList";
  }
  toString() {
    return "[" + String(this.ofType) + "]";
  }
  toJSON() {
    return this.toString();
  }
}
class GraphQLNonNull {
  constructor(ofType) {
    isNullableType(ofType) || devAssert(
      false,
      `Expected ${inspect$2(ofType)} to be a GraphQL nullable type.`
    );
    this.ofType = ofType;
  }
  get [Symbol.toStringTag]() {
    return "GraphQLNonNull";
  }
  toString() {
    return String(this.ofType) + "!";
  }
  toJSON() {
    return this.toString();
  }
}
function isWrappingType(type2) {
  return isListType(type2) || isNonNullType(type2);
}
function isNullableType(type2) {
  return isType(type2) && !isNonNullType(type2);
}
function getNullableType(type2) {
  if (type2) {
    return isNonNullType(type2) ? type2.ofType : type2;
  }
}
function isNamedType(type2) {
  return isScalarType(type2) || isObjectType(type2) || isInterfaceType(type2) || isUnionType(type2) || isEnumType(type2) || isInputObjectType(type2);
}
function getNamedType(type2) {
  if (type2) {
    let unwrappedType = type2;
    while (isWrappingType(unwrappedType)) {
      unwrappedType = unwrappedType.ofType;
    }
    return unwrappedType;
  }
}
function resolveReadonlyArrayThunk(thunk) {
  return typeof thunk === "function" ? thunk() : thunk;
}
function resolveObjMapThunk(thunk) {
  return typeof thunk === "function" ? thunk() : thunk;
}
class GraphQLScalarType {
  constructor(config) {
    var _config$parseValue, _config$serialize, _config$parseLiteral, _config$extensionASTN;
    const parseValue = (_config$parseValue = config.parseValue) !== null && _config$parseValue !== void 0 ? _config$parseValue : identityFunc;
    this.name = assertName(config.name);
    this.description = config.description;
    this.specifiedByURL = config.specifiedByURL;
    this.serialize = (_config$serialize = config.serialize) !== null && _config$serialize !== void 0 ? _config$serialize : identityFunc;
    this.parseValue = parseValue;
    this.parseLiteral = (_config$parseLiteral = config.parseLiteral) !== null && _config$parseLiteral !== void 0 ? _config$parseLiteral : (node, variables) => parseValue(valueFromASTUntyped(node, variables));
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : [];
    config.specifiedByURL == null || typeof config.specifiedByURL === "string" || devAssert(
      false,
      `${this.name} must provide "specifiedByURL" as a string, but got: ${inspect$2(config.specifiedByURL)}.`
    );
    config.serialize == null || typeof config.serialize === "function" || devAssert(
      false,
      `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`
    );
    if (config.parseLiteral) {
      typeof config.parseValue === "function" && typeof config.parseLiteral === "function" || devAssert(
        false,
        `${this.name} must provide both "parseValue" and "parseLiteral" functions.`
      );
    }
  }
  get [Symbol.toStringTag]() {
    return "GraphQLScalarType";
  }
  toConfig() {
    return {
      name: this.name,
      description: this.description,
      specifiedByURL: this.specifiedByURL,
      serialize: this.serialize,
      parseValue: this.parseValue,
      parseLiteral: this.parseLiteral,
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes
    };
  }
  toString() {
    return this.name;
  }
  toJSON() {
    return this.toString();
  }
}
class GraphQLObjectType {
  constructor(config) {
    var _config$extensionASTN2;
    this.name = assertName(config.name);
    this.description = config.description;
    this.isTypeOf = config.isTypeOf;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN2 = config.extensionASTNodes) !== null && _config$extensionASTN2 !== void 0 ? _config$extensionASTN2 : [];
    this._fields = () => defineFieldMap(config);
    this._interfaces = () => defineInterfaces(config);
    config.isTypeOf == null || typeof config.isTypeOf === "function" || devAssert(
      false,
      `${this.name} must provide "isTypeOf" as a function, but got: ${inspect$2(config.isTypeOf)}.`
    );
  }
  get [Symbol.toStringTag]() {
    return "GraphQLObjectType";
  }
  getFields() {
    if (typeof this._fields === "function") {
      this._fields = this._fields();
    }
    return this._fields;
  }
  getInterfaces() {
    if (typeof this._interfaces === "function") {
      this._interfaces = this._interfaces();
    }
    return this._interfaces;
  }
  toConfig() {
    return {
      name: this.name,
      description: this.description,
      interfaces: this.getInterfaces(),
      fields: fieldsToFieldsConfig(this.getFields()),
      isTypeOf: this.isTypeOf,
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes
    };
  }
  toString() {
    return this.name;
  }
  toJSON() {
    return this.toString();
  }
}
function defineInterfaces(config) {
  var _config$interfaces;
  const interfaces = resolveReadonlyArrayThunk(
    (_config$interfaces = config.interfaces) !== null && _config$interfaces !== void 0 ? _config$interfaces : []
  );
  Array.isArray(interfaces) || devAssert(
    false,
    `${config.name} interfaces must be an Array or a function which returns an Array.`
  );
  return interfaces;
}
function defineFieldMap(config) {
  const fieldMap = resolveObjMapThunk(config.fields);
  isPlainObj(fieldMap) || devAssert(
    false,
    `${config.name} fields must be an object with field names as keys or a function which returns such an object.`
  );
  return mapValue(fieldMap, (fieldConfig, fieldName) => {
    var _fieldConfig$args;
    isPlainObj(fieldConfig) || devAssert(
      false,
      `${config.name}.${fieldName} field config must be an object.`
    );
    fieldConfig.resolve == null || typeof fieldConfig.resolve === "function" || devAssert(
      false,
      `${config.name}.${fieldName} field resolver must be a function if provided, but got: ${inspect$2(fieldConfig.resolve)}.`
    );
    const argsConfig = (_fieldConfig$args = fieldConfig.args) !== null && _fieldConfig$args !== void 0 ? _fieldConfig$args : {};
    isPlainObj(argsConfig) || devAssert(
      false,
      `${config.name}.${fieldName} args must be an object with argument names as keys.`
    );
    return {
      name: assertName(fieldName),
      description: fieldConfig.description,
      type: fieldConfig.type,
      args: defineArguments(argsConfig),
      resolve: fieldConfig.resolve,
      subscribe: fieldConfig.subscribe,
      deprecationReason: fieldConfig.deprecationReason,
      extensions: toObjMap(fieldConfig.extensions),
      astNode: fieldConfig.astNode
    };
  });
}
function defineArguments(config) {
  return Object.entries(config).map(([argName, argConfig]) => ({
    name: assertName(argName),
    description: argConfig.description,
    type: argConfig.type,
    defaultValue: argConfig.defaultValue,
    deprecationReason: argConfig.deprecationReason,
    extensions: toObjMap(argConfig.extensions),
    astNode: argConfig.astNode
  }));
}
function isPlainObj(obj) {
  return isObjectLike(obj) && !Array.isArray(obj);
}
function fieldsToFieldsConfig(fields) {
  return mapValue(fields, (field) => ({
    description: field.description,
    type: field.type,
    args: argsToArgsConfig(field.args),
    resolve: field.resolve,
    subscribe: field.subscribe,
    deprecationReason: field.deprecationReason,
    extensions: field.extensions,
    astNode: field.astNode
  }));
}
function argsToArgsConfig(args) {
  return keyValMap(
    args,
    (arg) => arg.name,
    (arg) => ({
      description: arg.description,
      type: arg.type,
      defaultValue: arg.defaultValue,
      deprecationReason: arg.deprecationReason,
      extensions: arg.extensions,
      astNode: arg.astNode
    })
  );
}
function isRequiredArgument(arg) {
  return isNonNullType(arg.type) && arg.defaultValue === void 0;
}
class GraphQLInterfaceType {
  constructor(config) {
    var _config$extensionASTN3;
    this.name = assertName(config.name);
    this.description = config.description;
    this.resolveType = config.resolveType;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN3 = config.extensionASTNodes) !== null && _config$extensionASTN3 !== void 0 ? _config$extensionASTN3 : [];
    this._fields = defineFieldMap.bind(void 0, config);
    this._interfaces = defineInterfaces.bind(void 0, config);
    config.resolveType == null || typeof config.resolveType === "function" || devAssert(
      false,
      `${this.name} must provide "resolveType" as a function, but got: ${inspect$2(config.resolveType)}.`
    );
  }
  get [Symbol.toStringTag]() {
    return "GraphQLInterfaceType";
  }
  getFields() {
    if (typeof this._fields === "function") {
      this._fields = this._fields();
    }
    return this._fields;
  }
  getInterfaces() {
    if (typeof this._interfaces === "function") {
      this._interfaces = this._interfaces();
    }
    return this._interfaces;
  }
  toConfig() {
    return {
      name: this.name,
      description: this.description,
      interfaces: this.getInterfaces(),
      fields: fieldsToFieldsConfig(this.getFields()),
      resolveType: this.resolveType,
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes
    };
  }
  toString() {
    return this.name;
  }
  toJSON() {
    return this.toString();
  }
}
class GraphQLUnionType {
  constructor(config) {
    var _config$extensionASTN4;
    this.name = assertName(config.name);
    this.description = config.description;
    this.resolveType = config.resolveType;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN4 = config.extensionASTNodes) !== null && _config$extensionASTN4 !== void 0 ? _config$extensionASTN4 : [];
    this._types = defineTypes.bind(void 0, config);
    config.resolveType == null || typeof config.resolveType === "function" || devAssert(
      false,
      `${this.name} must provide "resolveType" as a function, but got: ${inspect$2(config.resolveType)}.`
    );
  }
  get [Symbol.toStringTag]() {
    return "GraphQLUnionType";
  }
  getTypes() {
    if (typeof this._types === "function") {
      this._types = this._types();
    }
    return this._types;
  }
  toConfig() {
    return {
      name: this.name,
      description: this.description,
      types: this.getTypes(),
      resolveType: this.resolveType,
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes
    };
  }
  toString() {
    return this.name;
  }
  toJSON() {
    return this.toString();
  }
}
function defineTypes(config) {
  const types2 = resolveReadonlyArrayThunk(config.types);
  Array.isArray(types2) || devAssert(
    false,
    `Must provide Array of types or a function which returns such an array for Union ${config.name}.`
  );
  return types2;
}
class GraphQLEnumType {
  /* <T> */
  constructor(config) {
    var _config$extensionASTN5;
    this.name = assertName(config.name);
    this.description = config.description;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN5 = config.extensionASTNodes) !== null && _config$extensionASTN5 !== void 0 ? _config$extensionASTN5 : [];
    this._values = defineEnumValues(this.name, config.values);
    this._valueLookup = new Map(
      this._values.map((enumValue) => [enumValue.value, enumValue])
    );
    this._nameLookup = keyMap(this._values, (value) => value.name);
  }
  get [Symbol.toStringTag]() {
    return "GraphQLEnumType";
  }
  getValues() {
    return this._values;
  }
  getValue(name2) {
    return this._nameLookup[name2];
  }
  serialize(outputValue) {
    const enumValue = this._valueLookup.get(outputValue);
    if (enumValue === void 0) {
      throw new GraphQLError(
        `Enum "${this.name}" cannot represent value: ${inspect$2(outputValue)}`
      );
    }
    return enumValue.name;
  }
  parseValue(inputValue) {
    if (typeof inputValue !== "string") {
      const valueStr = inspect$2(inputValue);
      throw new GraphQLError(
        `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr)
      );
    }
    const enumValue = this.getValue(inputValue);
    if (enumValue == null) {
      throw new GraphQLError(
        `Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue)
      );
    }
    return enumValue.value;
  }
  parseLiteral(valueNode, _variables) {
    if (valueNode.kind !== Kind.ENUM) {
      const valueStr = print(valueNode);
      throw new GraphQLError(
        `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr),
        {
          nodes: valueNode
        }
      );
    }
    const enumValue = this.getValue(valueNode.value);
    if (enumValue == null) {
      const valueStr = print(valueNode);
      throw new GraphQLError(
        `Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr),
        {
          nodes: valueNode
        }
      );
    }
    return enumValue.value;
  }
  toConfig() {
    const values = keyValMap(
      this.getValues(),
      (value) => value.name,
      (value) => ({
        description: value.description,
        value: value.value,
        deprecationReason: value.deprecationReason,
        extensions: value.extensions,
        astNode: value.astNode
      })
    );
    return {
      name: this.name,
      description: this.description,
      values,
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes
    };
  }
  toString() {
    return this.name;
  }
  toJSON() {
    return this.toString();
  }
}
function didYouMeanEnumValue(enumType, unknownValueStr) {
  const allNames = enumType.getValues().map((value) => value.name);
  const suggestedValues = suggestionList(unknownValueStr, allNames);
  return didYouMean("the enum value", suggestedValues);
}
function defineEnumValues(typeName, valueMap) {
  isPlainObj(valueMap) || devAssert(
    false,
    `${typeName} values must be an object with value names as keys.`
  );
  return Object.entries(valueMap).map(([valueName, valueConfig]) => {
    isPlainObj(valueConfig) || devAssert(
      false,
      `${typeName}.${valueName} must refer to an object with a "value" key representing an internal value but got: ${inspect$2(valueConfig)}.`
    );
    return {
      name: assertEnumValueName(valueName),
      description: valueConfig.description,
      value: valueConfig.value !== void 0 ? valueConfig.value : valueName,
      deprecationReason: valueConfig.deprecationReason,
      extensions: toObjMap(valueConfig.extensions),
      astNode: valueConfig.astNode
    };
  });
}
class GraphQLInputObjectType {
  constructor(config) {
    var _config$extensionASTN6;
    this.name = assertName(config.name);
    this.description = config.description;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN6 = config.extensionASTNodes) !== null && _config$extensionASTN6 !== void 0 ? _config$extensionASTN6 : [];
    this._fields = defineInputFieldMap.bind(void 0, config);
  }
  get [Symbol.toStringTag]() {
    return "GraphQLInputObjectType";
  }
  getFields() {
    if (typeof this._fields === "function") {
      this._fields = this._fields();
    }
    return this._fields;
  }
  toConfig() {
    const fields = mapValue(this.getFields(), (field) => ({
      description: field.description,
      type: field.type,
      defaultValue: field.defaultValue,
      deprecationReason: field.deprecationReason,
      extensions: field.extensions,
      astNode: field.astNode
    }));
    return {
      name: this.name,
      description: this.description,
      fields,
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes
    };
  }
  toString() {
    return this.name;
  }
  toJSON() {
    return this.toString();
  }
}
function defineInputFieldMap(config) {
  const fieldMap = resolveObjMapThunk(config.fields);
  isPlainObj(fieldMap) || devAssert(
    false,
    `${config.name} fields must be an object with field names as keys or a function which returns such an object.`
  );
  return mapValue(fieldMap, (fieldConfig, fieldName) => {
    !("resolve" in fieldConfig) || devAssert(
      false,
      `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`
    );
    return {
      name: assertName(fieldName),
      description: fieldConfig.description,
      type: fieldConfig.type,
      defaultValue: fieldConfig.defaultValue,
      deprecationReason: fieldConfig.deprecationReason,
      extensions: toObjMap(fieldConfig.extensions),
      astNode: fieldConfig.astNode
    };
  });
}
function isRequiredInputField(field) {
  return isNonNullType(field.type) && field.defaultValue === void 0;
}
function isEqualType(typeA, typeB) {
  if (typeA === typeB) {
    return true;
  }
  if (isNonNullType(typeA) && isNonNullType(typeB)) {
    return isEqualType(typeA.ofType, typeB.ofType);
  }
  if (isListType(typeA) && isListType(typeB)) {
    return isEqualType(typeA.ofType, typeB.ofType);
  }
  return false;
}
function isTypeSubTypeOf(schema, maybeSubType, superType) {
  if (maybeSubType === superType) {
    return true;
  }
  if (isNonNullType(superType)) {
    if (isNonNullType(maybeSubType)) {
      return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
    }
    return false;
  }
  if (isNonNullType(maybeSubType)) {
    return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);
  }
  if (isListType(superType)) {
    if (isListType(maybeSubType)) {
      return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);
    }
    return false;
  }
  if (isListType(maybeSubType)) {
    return false;
  }
  return isAbstractType(superType) && (isInterfaceType(maybeSubType) || isObjectType(maybeSubType)) && schema.isSubType(superType, maybeSubType);
}
function doTypesOverlap(schema, typeA, typeB) {
  if (typeA === typeB) {
    return true;
  }
  if (isAbstractType(typeA)) {
    if (isAbstractType(typeB)) {
      return schema.getPossibleTypes(typeA).some((type2) => schema.isSubType(typeB, type2));
    }
    return schema.isSubType(typeA, typeB);
  }
  if (isAbstractType(typeB)) {
    return schema.isSubType(typeB, typeA);
  }
  return false;
}
const GRAPHQL_MAX_INT = 2147483647;
const GRAPHQL_MIN_INT = -2147483648;
const GraphQLInt = new GraphQLScalarType({
  name: "Int",
  description: "The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.",
  serialize(outputValue) {
    const coercedValue = serializeObject(outputValue);
    if (typeof coercedValue === "boolean") {
      return coercedValue ? 1 : 0;
    }
    let num = coercedValue;
    if (typeof coercedValue === "string" && coercedValue !== "") {
      num = Number(coercedValue);
    }
    if (typeof num !== "number" || !Number.isInteger(num)) {
      throw new GraphQLError(
        `Int cannot represent non-integer value: ${inspect$2(coercedValue)}`
      );
    }
    if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) {
      throw new GraphQLError(
        "Int cannot represent non 32-bit signed integer value: " + inspect$2(coercedValue)
      );
    }
    return num;
  },
  parseValue(inputValue) {
    if (typeof inputValue !== "number" || !Number.isInteger(inputValue)) {
      throw new GraphQLError(
        `Int cannot represent non-integer value: ${inspect$2(inputValue)}`
      );
    }
    if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) {
      throw new GraphQLError(
        `Int cannot represent non 32-bit signed integer value: ${inputValue}`
      );
    }
    return inputValue;
  },
  parseLiteral(valueNode) {
    if (valueNode.kind !== Kind.INT) {
      throw new GraphQLError(
        `Int cannot represent non-integer value: ${print(valueNode)}`,
        {
          nodes: valueNode
        }
      );
    }
    const num = parseInt(valueNode.value, 10);
    if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) {
      throw new GraphQLError(
        `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`,
        {
          nodes: valueNode
        }
      );
    }
    return num;
  }
});
const GraphQLFloat = new GraphQLScalarType({
  name: "Float",
  description: "The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).",
  serialize(outputValue) {
    const coercedValue = serializeObject(outputValue);
    if (typeof coercedValue === "boolean") {
      return coercedValue ? 1 : 0;
    }
    let num = coercedValue;
    if (typeof coercedValue === "string" && coercedValue !== "") {
      num = Number(coercedValue);
    }
    if (typeof num !== "number" || !Number.isFinite(num)) {
      throw new GraphQLError(
        `Float cannot represent non numeric value: ${inspect$2(coercedValue)}`
      );
    }
    return num;
  },
  parseValue(inputValue) {
    if (typeof inputValue !== "number" || !Number.isFinite(inputValue)) {
      throw new GraphQLError(
        `Float cannot represent non numeric value: ${inspect$2(inputValue)}`
      );
    }
    return inputValue;
  },
  parseLiteral(valueNode) {
    if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) {
      throw new GraphQLError(
        `Float cannot represent non numeric value: ${print(valueNode)}`,
        valueNode
      );
    }
    return parseFloat(valueNode.value);
  }
});
const GraphQLString = new GraphQLScalarType({
  name: "String",
  description: "The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.",
  serialize(outputValue) {
    const coercedValue = serializeObject(outputValue);
    if (typeof coercedValue === "string") {
      return coercedValue;
    }
    if (typeof coercedValue === "boolean") {
      return coercedValue ? "true" : "false";
    }
    if (typeof coercedValue === "number" && Number.isFinite(coercedValue)) {
      return coercedValue.toString();
    }
    throw new GraphQLError(
      `String cannot represent value: ${inspect$2(outputValue)}`
    );
  },
  parseValue(inputValue) {
    if (typeof inputValue !== "string") {
      throw new GraphQLError(
        `String cannot represent a non string value: ${inspect$2(inputValue)}`
      );
    }
    return inputValue;
  },
  parseLiteral(valueNode) {
    if (valueNode.kind !== Kind.STRING) {
      throw new GraphQLError(
        `String cannot represent a non string value: ${print(valueNode)}`,
        {
          nodes: valueNode
        }
      );
    }
    return valueNode.value;
  }
});
const GraphQLBoolean = new GraphQLScalarType({
  name: "Boolean",
  description: "The `Boolean` scalar type represents `true` or `false`.",
  serialize(outputValue) {
    const coercedValue = serializeObject(outputValue);
    if (typeof coercedValue === "boolean") {
      return coercedValue;
    }
    if (Number.isFinite(coercedValue)) {
      return coercedValue !== 0;
    }
    throw new GraphQLError(
      `Boolean cannot represent a non boolean value: ${inspect$2(coercedValue)}`
    );
  },
  parseValue(inputValue) {
    if (typeof inputValue !== "boolean") {
      throw new GraphQLError(
        `Boolean cannot represent a non boolean value: ${inspect$2(inputValue)}`
      );
    }
    return inputValue;
  },
  parseLiteral(valueNode) {
    if (valueNode.kind !== Kind.BOOLEAN) {
      throw new GraphQLError(
        `Boolean cannot represent a non boolean value: ${print(valueNode)}`,
        {
          nodes: valueNode
        }
      );
    }
    return valueNode.value;
  }
});
const GraphQLID = new GraphQLScalarType({
  name: "ID",
  description: 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.',
  serialize(outputValue) {
    const coercedValue = serializeObject(outputValue);
    if (typeof coercedValue === "string") {
      return coercedValue;
    }
    if (Number.isInteger(coercedValue)) {
      return String(coercedValue);
    }
    throw new GraphQLError(
      `ID cannot represent value: ${inspect$2(outputValue)}`
    );
  },
  parseValue(inputValue) {
    if (typeof inputValue === "string") {
      return inputValue;
    }
    if (typeof inputValue === "number" && Number.isInteger(inputValue)) {
      return inputValue.toString();
    }
    throw new GraphQLError(`ID cannot represent value: ${inspect$2(inputValue)}`);
  },
  parseLiteral(valueNode) {
    if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) {
      throw new GraphQLError(
        "ID cannot represent a non-string and non-integer value: " + print(valueNode),
        {
          nodes: valueNode
        }
      );
    }
    return valueNode.value;
  }
});
const specifiedScalarTypes = Object.freeze([
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLBoolean,
  GraphQLID
]);
function isSpecifiedScalarType(type2) {
  return specifiedScalarTypes.some(({ name: name2 }) => type2.name === name2);
}
function serializeObject(outputValue) {
  if (isObjectLike(outputValue)) {
    if (typeof outputValue.valueOf === "function") {
      const valueOfResult = outputValue.valueOf();
      if (!isObjectLike(valueOfResult)) {
        return valueOfResult;
      }
    }
    if (typeof outputValue.toJSON === "function") {
      return outputValue.toJSON();
    }
  }
  return outputValue;
}
function isDirective(directive) {
  return instanceOf(directive, GraphQLDirective);
}
class GraphQLDirective {
  constructor(config) {
    var _config$isRepeatable, _config$args;
    this.name = assertName(config.name);
    this.description = config.description;
    this.locations = config.locations;
    this.isRepeatable = (_config$isRepeatable = config.isRepeatable) !== null && _config$isRepeatable !== void 0 ? _config$isRepeatable : false;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    Array.isArray(config.locations) || devAssert(false, `@${config.name} locations must be an Array.`);
    const args = (_config$args = config.args) !== null && _config$args !== void 0 ? _config$args : {};
    isObjectLike(args) && !Array.isArray(args) || devAssert(
      false,
      `@${config.name} args must be an object with argument names as keys.`
    );
    this.args = defineArguments(args);
  }
  get [Symbol.toStringTag]() {
    return "GraphQLDirective";
  }
  toConfig() {
    return {
      name: this.name,
      description: this.description,
      locations: this.locations,
      args: argsToArgsConfig(this.args),
      isRepeatable: this.isRepeatable,
      extensions: this.extensions,
      astNode: this.astNode
    };
  }
  toString() {
    return "@" + this.name;
  }
  toJSON() {
    return this.toString();
  }
}
const GraphQLIncludeDirective = new GraphQLDirective({
  name: "include",
  description: "Directs the executor to include this field or fragment only when the `if` argument is true.",
  locations: [
    DirectiveLocation.FIELD,
    DirectiveLocation.FRAGMENT_SPREAD,
    DirectiveLocation.INLINE_FRAGMENT
  ],
  args: {
    if: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: "Included when true."
    }
  }
});
const GraphQLSkipDirective = new GraphQLDirective({
  name: "skip",
  description: "Directs the executor to skip this field or fragment when the `if` argument is true.",
  locations: [
    DirectiveLocation.FIELD,
    DirectiveLocation.FRAGMENT_SPREAD,
    DirectiveLocation.INLINE_FRAGMENT
  ],
  args: {
    if: {
      type: new GraphQLNonNull(GraphQLBoolean),
      description: "Skipped when true."
    }
  }
});
const DEFAULT_DEPRECATION_REASON = "No longer supported";
const GraphQLDeprecatedDirective = new GraphQLDirective({
  name: "deprecated",
  description: "Marks an element of a GraphQL schema as no longer supported.",
  locations: [
    DirectiveLocation.FIELD_DEFINITION,
    DirectiveLocation.ARGUMENT_DEFINITION,
    DirectiveLocation.INPUT_FIELD_DEFINITION,
    DirectiveLocation.ENUM_VALUE
  ],
  args: {
    reason: {
      type: GraphQLString,
      description: "Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).",
      defaultValue: DEFAULT_DEPRECATION_REASON
    }
  }
});
const GraphQLSpecifiedByDirective = new GraphQLDirective({
  name: "specifiedBy",
  description: "Exposes a URL that specifies the behavior of this scalar.",
  locations: [DirectiveLocation.SCALAR],
  args: {
    url: {
      type: new GraphQLNonNull(GraphQLString),
      description: "The URL that specifies the behavior of this scalar."
    }
  }
});
const specifiedDirectives = Object.freeze([
  GraphQLIncludeDirective,
  GraphQLSkipDirective,
  GraphQLDeprecatedDirective,
  GraphQLSpecifiedByDirective
]);
function isSpecifiedDirective(directive) {
  return specifiedDirectives.some(({ name: name2 }) => name2 === directive.name);
}
function isIterableObject(maybeIterable) {
  return typeof maybeIterable === "object" && typeof (maybeIterable === null || maybeIterable === void 0 ? void 0 : maybeIterable[Symbol.iterator]) === "function";
}
function astFromValue(value, type2) {
  if (isNonNullType(type2)) {
    const astValue = astFromValue(value, type2.ofType);
    if ((astValue === null || astValue === void 0 ? void 0 : astValue.kind) === Kind.NULL) {
      return null;
    }
    return astValue;
  }
  if (value === null) {
    return {
      kind: Kind.NULL
    };
  }
  if (value === void 0) {
    return null;
  }
  if (isListType(type2)) {
    const itemType = type2.ofType;
    if (isIterableObject(value)) {
      const valuesNodes = [];
      for (const item of value) {
        const itemNode = astFromValue(item, itemType);
        if (itemNode != null) {
          valuesNodes.push(itemNode);
        }
      }
      return {
        kind: Kind.LIST,
        values: valuesNodes
      };
    }
    return astFromValue(value, itemType);
  }
  if (isInputObjectType(type2)) {
    if (!isObjectLike(value)) {
      return null;
    }
    const fieldNodes = [];
    for (const field of Object.values(type2.getFields())) {
      const fieldValue = astFromValue(value[field.name], field.type);
      if (fieldValue) {
        fieldNodes.push({
          kind: Kind.OBJECT_FIELD,
          name: {
            kind: Kind.NAME,
            value: field.name
          },
          value: fieldValue
        });
      }
    }
    return {
      kind: Kind.OBJECT,
      fields: fieldNodes
    };
  }
  if (isLeafType(type2)) {
    const serialized = type2.serialize(value);
    if (serialized == null) {
      return null;
    }
    if (typeof serialized === "boolean") {
      return {
        kind: Kind.BOOLEAN,
        value: serialized
      };
    }
    if (typeof serialized === "number" && Number.isFinite(serialized)) {
      const stringNum = String(serialized);
      return integerStringRegExp$1.test(stringNum) ? {
        kind: Kind.INT,
        value: stringNum
      } : {
        kind: Kind.FLOAT,
        value: stringNum
      };
    }
    if (typeof serialized === "string") {
      if (isEnumType(type2)) {
        return {
          kind: Kind.ENUM,
          value: serialized
        };
      }
      if (type2 === GraphQLID && integerStringRegExp$1.test(serialized)) {
        return {
          kind: Kind.INT,
          value: serialized
        };
      }
      return {
        kind: Kind.STRING,
        value: serialized
      };
    }
    throw new TypeError(`Cannot convert value to AST: ${inspect$2(serialized)}.`);
  }
  invariant(false, "Unexpected input type: " + inspect$2(type2));
}
const integerStringRegExp$1 = /^-?(?:0|[1-9][0-9]*)$/;
const __Schema = new GraphQLObjectType({
  name: "__Schema",
  description: "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.",
  fields: () => ({
    description: {
      type: GraphQLString,
      resolve: (schema) => schema.description
    },
    types: {
      description: "A list of all types supported by this server.",
      type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__Type))),
      resolve(schema) {
        return Object.values(schema.getTypeMap());
      }
    },
    queryType: {
      description: "The type that query operations will be rooted at.",
      type: new GraphQLNonNull(__Type),
      resolve: (schema) => schema.getQueryType()
    },
    mutationType: {
      description: "If this server supports mutation, the type that mutation operations will be rooted at.",
      type: __Type,
      resolve: (schema) => schema.getMutationType()
    },
    subscriptionType: {
      description: "If this server support subscription, the type that subscription operations will be rooted at.",
      type: __Type,
      resolve: (schema) => schema.getSubscriptionType()
    },
    directives: {
      description: "A list of all directives supported by this server.",
      type: new GraphQLNonNull(
        new GraphQLList(new GraphQLNonNull(__Directive))
      ),
      resolve: (schema) => schema.getDirectives()
    }
  })
});
const __Directive = new GraphQLObjectType({
  name: "__Directive",
  description: "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",
  fields: () => ({
    name: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: (directive) => directive.name
    },
    description: {
      type: GraphQLString,
      resolve: (directive) => directive.description
    },
    isRepeatable: {
      type: new GraphQLNonNull(GraphQLBoolean),
      resolve: (directive) => directive.isRepeatable
    },
    locations: {
      type: new GraphQLNonNull(
        new GraphQLList(new GraphQLNonNull(__DirectiveLocation))
      ),
      resolve: (directive) => directive.locations
    },
    args: {
      type: new GraphQLNonNull(
        new GraphQLList(new GraphQLNonNull(__InputValue))
      ),
      args: {
        includeDeprecated: {
          type: GraphQLBoolean,
          defaultValue: false
        }
      },
      resolve(field, { includeDeprecated }) {
        return includeDeprecated ? field.args : field.args.filter((arg) => arg.deprecationReason == null);
      }
    }
  })
});
const __DirectiveLocation = new GraphQLEnumType({
  name: "__DirectiveLocation",
  description: "A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.",
  values: {
    QUERY: {
      value: DirectiveLocation.QUERY,
      description: "Location adjacent to a query operation."
    },
    MUTATION: {
      value: DirectiveLocation.MUTATION,
      description: "Location adjacent to a mutation operation."
    },
    SUBSCRIPTION: {
      value: DirectiveLocation.SUBSCRIPTION,
      description: "Location adjacent to a subscription operation."
    },
    FIELD: {
      value: DirectiveLocation.FIELD,
      description: "Location adjacent to a field."
    },
    FRAGMENT_DEFINITION: {
      value: DirectiveLocation.FRAGMENT_DEFINITION,
      description: "Location adjacent to a fragment definition."
    },
    FRAGMENT_SPREAD: {
      value: DirectiveLocation.FRAGMENT_SPREAD,
      description: "Location adjacent to a fragment spread."
    },
    INLINE_FRAGMENT: {
      value: DirectiveLocation.INLINE_FRAGMENT,
      description: "Location adjacent to an inline fragment."
    },
    VARIABLE_DEFINITION: {
      value: DirectiveLocation.VARIABLE_DEFINITION,
      description: "Location adjacent to a variable definition."
    },
    SCHEMA: {
      value: DirectiveLocation.SCHEMA,
      description: "Location adjacent to a schema definition."
    },
    SCALAR: {
      value: DirectiveLocation.SCALAR,
      description: "Location adjacent to a scalar definition."
    },
    OBJECT: {
      value: DirectiveLocation.OBJECT,
      description: "Location adjacent to an object type definition."
    },
    FIELD_DEFINITION: {
      value: DirectiveLocation.FIELD_DEFINITION,
      description: "Location adjacent to a field definition."
    },
    ARGUMENT_DEFINITION: {
      value: DirectiveLocation.ARGUMENT_DEFINITION,
      description: "Location adjacent to an argument definition."
    },
    INTERFACE: {
      value: DirectiveLocation.INTERFACE,
      description: "Location adjacent to an interface definition."
    },
    UNION: {
      value: DirectiveLocation.UNION,
      description: "Location adjacent to a union definition."
    },
    ENUM: {
      value: DirectiveLocation.ENUM,
      description: "Location adjacent to an enum definition."
    },
    ENUM_VALUE: {
      value: DirectiveLocation.ENUM_VALUE,
      description: "Location adjacent to an enum value definition."
    },
    INPUT_OBJECT: {
      value: DirectiveLocation.INPUT_OBJECT,
      description: "Location adjacent to an input object type definition."
    },
    INPUT_FIELD_DEFINITION: {
      value: DirectiveLocation.INPUT_FIELD_DEFINITION,
      description: "Location adjacent to an input object field definition."
    }
  }
});
const __Type = new GraphQLObjectType({
  name: "__Type",
  description: "The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.",
  fields: () => ({
    kind: {
      type: new GraphQLNonNull(__TypeKind),
      resolve(type2) {
        if (isScalarType(type2)) {
          return TypeKind.SCALAR;
        }
        if (isObjectType(type2)) {
          return TypeKind.OBJECT;
        }
        if (isInterfaceType(type2)) {
          return TypeKind.INTERFACE;
        }
        if (isUnionType(type2)) {
          return TypeKind.UNION;
        }
        if (isEnumType(type2)) {
          return TypeKind.ENUM;
        }
        if (isInputObjectType(type2)) {
          return TypeKind.INPUT_OBJECT;
        }
        if (isListType(type2)) {
          return TypeKind.LIST;
        }
        if (isNonNullType(type2)) {
          return TypeKind.NON_NULL;
        }
        invariant(false, `Unexpected type: "${inspect$2(type2)}".`);
      }
    },
    name: {
      type: GraphQLString,
      resolve: (type2) => "name" in type2 ? type2.name : void 0
    },
    description: {
      type: GraphQLString,
      resolve: (type2) => (
        /* c8 ignore next */
        "description" in type2 ? type2.description : void 0
      )
    },
    specifiedByURL: {
      type: GraphQLString,
      resolve: (obj) => "specifiedByURL" in obj ? obj.specifiedByURL : void 0
    },
    fields: {
      type: new GraphQLList(new GraphQLNonNull(__Field)),
      args: {
        includeDeprecated: {
          type: GraphQLBoolean,
          defaultValue: false
        }
      },
      resolve(type2, { includeDeprecated }) {
        if (isObjectType(type2) || isInterfaceType(type2)) {
          const fields = Object.values(type2.getFields());
          return includeDeprecated ? fields : fields.filter((field) => field.deprecationReason == null);
        }
      }
    },
    interfaces: {
      type: new GraphQLList(new GraphQLNonNull(__Type)),
      resolve(type2) {
        if (isObjectType(type2) || isInterfaceType(type2)) {
          return type2.getInterfaces();
        }
      }
    },
    possibleTypes: {
      type: new GraphQLList(new GraphQLNonNull(__Type)),
      resolve(type2, _args, _context, { schema }) {
        if (isAbstractType(type2)) {
          return schema.getPossibleTypes(type2);
        }
      }
    },
    enumValues: {
      type: new GraphQLList(new GraphQLNonNull(__EnumValue)),
      args: {
        includeDeprecated: {
          type: GraphQLBoolean,
          defaultValue: false
        }
      },
      resolve(type2, { includeDeprecated }) {
        if (isEnumType(type2)) {
          const values = type2.getValues();
          return includeDeprecated ? values : values.filter((field) => field.deprecationReason == null);
        }
      }
    },
    inputFields: {
      type: new GraphQLList(new GraphQLNonNull(__InputValue)),
      args: {
        includeDeprecated: {
          type: GraphQLBoolean,
          defaultValue: false
        }
      },
      resolve(type2, { includeDeprecated }) {
        if (isInputObjectType(type2)) {
          const values = Object.values(type2.getFields());
          return includeDeprecated ? values : values.filter((field) => field.deprecationReason == null);
        }
      }
    },
    ofType: {
      type: __Type,
      resolve: (type2) => "ofType" in type2 ? type2.ofType : void 0
    }
  })
});
const __Field = new GraphQLObjectType({
  name: "__Field",
  description: "Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.",
  fields: () => ({
    name: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: (field) => field.name
    },
    description: {
      type: GraphQLString,
      resolve: (field) => field.description
    },
    args: {
      type: new GraphQLNonNull(
        new GraphQLList(new GraphQLNonNull(__InputValue))
      ),
      args: {
        includeDeprecated: {
          type: GraphQLBoolean,
          defaultValue: false
        }
      },
      resolve(field, { includeDeprecated }) {
        return includeDeprecated ? field.args : field.args.filter((arg) => arg.deprecationReason == null);
      }
    },
    type: {
      type: new GraphQLNonNull(__Type),
      resolve: (field) => field.type
    },
    isDeprecated: {
      type: new GraphQLNonNull(GraphQLBoolean),
      resolve: (field) => field.deprecationReason != null
    },
    deprecationReason: {
      type: GraphQLString,
      resolve: (field) => field.deprecationReason
    }
  })
});
const __InputValue = new GraphQLObjectType({
  name: "__InputValue",
  description: "Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.",
  fields: () => ({
    name: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: (inputValue) => inputValue.name
    },
    description: {
      type: GraphQLString,
      resolve: (inputValue) => inputValue.description
    },
    type: {
      type: new GraphQLNonNull(__Type),
      resolve: (inputValue) => inputValue.type
    },
    defaultValue: {
      type: GraphQLString,
      description: "A GraphQL-formatted string representing the default value for this input value.",
      resolve(inputValue) {
        const { type: type2, defaultValue } = inputValue;
        const valueAST = astFromValue(defaultValue, type2);
        return valueAST ? print(valueAST) : null;
      }
    },
    isDeprecated: {
      type: new GraphQLNonNull(GraphQLBoolean),
      resolve: (field) => field.deprecationReason != null
    },
    deprecationReason: {
      type: GraphQLString,
      resolve: (obj) => obj.deprecationReason
    }
  })
});
const __EnumValue = new GraphQLObjectType({
  name: "__EnumValue",
  description: "One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.",
  fields: () => ({
    name: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: (enumValue) => enumValue.name
    },
    description: {
      type: GraphQLString,
      resolve: (enumValue) => enumValue.description
    },
    isDeprecated: {
      type: new GraphQLNonNull(GraphQLBoolean),
      resolve: (enumValue) => enumValue.deprecationReason != null
    },
    deprecationReason: {
      type: GraphQLString,
      resolve: (enumValue) => enumValue.deprecationReason
    }
  })
});
var TypeKind;
(function(TypeKind2) {
  TypeKind2["SCALAR"] = "SCALAR";
  TypeKind2["OBJECT"] = "OBJECT";
  TypeKind2["INTERFACE"] = "INTERFACE";
  TypeKind2["UNION"] = "UNION";
  TypeKind2["ENUM"] = "ENUM";
  TypeKind2["INPUT_OBJECT"] = "INPUT_OBJECT";
  TypeKind2["LIST"] = "LIST";
  TypeKind2["NON_NULL"] = "NON_NULL";
})(TypeKind || (TypeKind = {}));
const __TypeKind = new GraphQLEnumType({
  name: "__TypeKind",
  description: "An enum describing what kind of type a given `__Type` is.",
  values: {
    SCALAR: {
      value: TypeKind.SCALAR,
      description: "Indicates this type is a scalar."
    },
    OBJECT: {
      value: TypeKind.OBJECT,
      description: "Indicates this type is an object. `fields` and `interfaces` are valid fields."
    },
    INTERFACE: {
      value: TypeKind.INTERFACE,
      description: "Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields."
    },
    UNION: {
      value: TypeKind.UNION,
      description: "Indicates this type is a union. `possibleTypes` is a valid field."
    },
    ENUM: {
      value: TypeKind.ENUM,
      description: "Indicates this type is an enum. `enumValues` is a valid field."
    },
    INPUT_OBJECT: {
      value: TypeKind.INPUT_OBJECT,
      description: "Indicates this type is an input object. `inputFields` is a valid field."
    },
    LIST: {
      value: TypeKind.LIST,
      description: "Indicates this type is a list. `ofType` is a valid field."
    },
    NON_NULL: {
      value: TypeKind.NON_NULL,
      description: "Indicates this type is a non-null. `ofType` is a valid field."
    }
  }
});
const SchemaMetaFieldDef = {
  name: "__schema",
  type: new GraphQLNonNull(__Schema),
  description: "Access the current type schema of this server.",
  args: [],
  resolve: (_source, _args, _context, { schema }) => schema,
  deprecationReason: void 0,
  extensions: /* @__PURE__ */ Object.create(null),
  astNode: void 0
};
const TypeMetaFieldDef = {
  name: "__type",
  type: __Type,
  description: "Request the type information of a single type.",
  args: [
    {
      name: "name",
      description: void 0,
      type: new GraphQLNonNull(GraphQLString),
      defaultValue: void 0,
      deprecationReason: void 0,
      extensions: /* @__PURE__ */ Object.create(null),
      astNode: void 0
    }
  ],
  resolve: (_source, { name: name2 }, _context, { schema }) => schema.getType(name2),
  deprecationReason: void 0,
  extensions: /* @__PURE__ */ Object.create(null),
  astNode: void 0
};
const TypeNameMetaFieldDef = {
  name: "__typename",
  type: new GraphQLNonNull(GraphQLString),
  description: "The name of the current Object type at runtime.",
  args: [],
  resolve: (_source, _args, _context, { parentType }) => parentType.name,
  deprecationReason: void 0,
  extensions: /* @__PURE__ */ Object.create(null),
  astNode: void 0
};
const introspectionTypes = Object.freeze([
  __Schema,
  __Directive,
  __DirectiveLocation,
  __Type,
  __Field,
  __InputValue,
  __EnumValue,
  __TypeKind
]);
function isIntrospectionType(type2) {
  return introspectionTypes.some(({ name: name2 }) => type2.name === name2);
}
function isSchema(schema) {
  return instanceOf(schema, GraphQLSchema);
}
function assertSchema(schema) {
  if (!isSchema(schema)) {
    throw new Error(`Expected ${inspect$2(schema)} to be a GraphQL schema.`);
  }
  return schema;
}
class GraphQLSchema {
  // Used as a cache for validateSchema().
  constructor(config) {
    var _config$extensionASTN, _config$directives;
    this.__validationErrors = config.assumeValid === true ? [] : void 0;
    isObjectLike(config) || devAssert(false, "Must provide configuration object.");
    !config.types || Array.isArray(config.types) || devAssert(
      false,
      `"types" must be Array if provided but got: ${inspect$2(config.types)}.`
    );
    !config.directives || Array.isArray(config.directives) || devAssert(
      false,
      `"directives" must be Array if provided but got: ${inspect$2(config.directives)}.`
    );
    this.description = config.description;
    this.extensions = toObjMap(config.extensions);
    this.astNode = config.astNode;
    this.extensionASTNodes = (_config$extensionASTN = config.extensionASTNodes) !== null && _config$extensionASTN !== void 0 ? _config$extensionASTN : [];
    this._queryType = config.query;
    this._mutationType = config.mutation;
    this._subscriptionType = config.subscription;
    this._directives = (_config$directives = config.directives) !== null && _config$directives !== void 0 ? _config$directives : specifiedDirectives;
    const allReferencedTypes = new Set(config.types);
    if (config.types != null) {
      for (const type2 of config.types) {
        allReferencedTypes.delete(type2);
        collectReferencedTypes(type2, allReferencedTypes);
      }
    }
    if (this._queryType != null) {
      collectReferencedTypes(this._queryType, allReferencedTypes);
    }
    if (this._mutationType != null) {
      collectReferencedTypes(this._mutationType, allReferencedTypes);
    }
    if (this._subscriptionType != null) {
      collectReferencedTypes(this._subscriptionType, allReferencedTypes);
    }
    for (const directive of this._directives) {
      if (isDirective(directive)) {
        for (const arg of directive.args) {
          collectReferencedTypes(arg.type, allReferencedTypes);
        }
      }
    }
    collectReferencedTypes(__Schema, allReferencedTypes);
    this._typeMap = /* @__PURE__ */ Object.create(null);
    this._subTypeMap = /* @__PURE__ */ Object.create(null);
    this._implementationsMap = /* @__PURE__ */ Object.create(null);
    for (const namedType of allReferencedTypes) {
      if (namedType == null) {
        continue;
      }
      const typeName = namedType.name;
      typeName || devAssert(
        false,
        "One of the provided types for building the Schema is missing a name."
      );
      if (this._typeMap[typeName] !== void 0) {
        throw new Error(
          `Schema must contain uniquely named types but contains multiple types named "${typeName}".`
        );
      }
      this._typeMap[typeName] = namedType;
      if (isInterfaceType(namedType)) {
        for (const iface of namedType.getInterfaces()) {
          if (isInterfaceType(iface)) {
            let implementations = this._implementationsMap[iface.name];
            if (implementations === void 0) {
              implementations = this._implementationsMap[iface.name] = {
                objects: [],
                interfaces: []
              };
            }
            implementations.interfaces.push(namedType);
          }
        }
      } else if (isObjectType(namedType)) {
        for (const iface of namedType.getInterfaces()) {
          if (isInterfaceType(iface)) {
            let implementations = this._implementationsMap[iface.name];
            if (implementations === void 0) {
              implementations = this._implementationsMap[iface.name] = {
                objects: [],
                interfaces: []
              };
            }
            implementations.objects.push(namedType);
          }
        }
      }
    }
  }
  get [Symbol.toStringTag]() {
    return "GraphQLSchema";
  }
  getQueryType() {
    return this._queryType;
  }
  getMutationType() {
    return this._mutationType;
  }
  getSubscriptionType() {
    return this._subscriptionType;
  }
  getRootType(operation) {
    switch (operation) {
      case OperationTypeNode.QUERY:
        return this.getQueryType();
      case OperationTypeNode.MUTATION:
        return this.getMutationType();
      case OperationTypeNode.SUBSCRIPTION:
        return this.getSubscriptionType();
    }
  }
  getTypeMap() {
    return this._typeMap;
  }
  getType(name2) {
    return this.getTypeMap()[name2];
  }
  getPossibleTypes(abstractType) {
    return isUnionType(abstractType) ? abstractType.getTypes() : this.getImplementations(abstractType).objects;
  }
  getImplementations(interfaceType) {
    const implementations = this._implementationsMap[interfaceType.name];
    return implementations !== null && implementations !== void 0 ? implementations : {
      objects: [],
      interfaces: []
    };
  }
  isSubType(abstractType, maybeSubType) {
    let map = this._subTypeMap[abstractType.name];
    if (map === void 0) {
      map = /* @__PURE__ */ Object.create(null);
      if (isUnionType(abstractType)) {
        for (const type2 of abstractType.getTypes()) {
          map[type2.name] = true;
        }
      } else {
        const implementations = this.getImplementations(abstractType);
        for (const type2 of implementations.objects) {
          map[type2.name] = true;
        }
        for (const type2 of implementations.interfaces) {
          map[type2.name] = true;
        }
      }
      this._subTypeMap[abstractType.name] = map;
    }
    return map[maybeSubType.name] !== void 0;
  }
  getDirectives() {
    return this._directives;
  }
  getDirective(name2) {
    return this.getDirectives().find((directive) => directive.name === name2);
  }
  toConfig() {
    return {
      description: this.description,
      query: this.getQueryType(),
      mutation: this.getMutationType(),
      subscription: this.getSubscriptionType(),
      types: Object.values(this.getTypeMap()),
      directives: this.getDirectives(),
      extensions: this.extensions,
      astNode: this.astNode,
      extensionASTNodes: this.extensionASTNodes,
      assumeValid: this.__validationErrors !== void 0
    };
  }
}
function collectReferencedTypes(type2, typeSet) {
  const namedType = getNamedType(type2);
  if (!typeSet.has(namedType)) {
    typeSet.add(namedType);
    if (isUnionType(namedType)) {
      for (const memberType of namedType.getTypes()) {
        collectReferencedTypes(memberType, typeSet);
      }
    } else if (isObjectType(namedType) || isInterfaceType(namedType)) {
      for (const interfaceType of namedType.getInterfaces()) {
        collectReferencedTypes(interfaceType, typeSet);
      }
      for (const field of Object.values(namedType.getFields())) {
        collectReferencedTypes(field.type, typeSet);
        for (const arg of field.args) {
          collectReferencedTypes(arg.type, typeSet);
        }
      }
    } else if (isInputObjectType(namedType)) {
      for (const field of Object.values(namedType.getFields())) {
        collectReferencedTypes(field.type, typeSet);
      }
    }
  }
  return typeSet;
}
function validateSchema(schema) {
  assertSchema(schema);
  if (schema.__validationErrors) {
    return schema.__validationErrors;
  }
  const context = new SchemaValidationContext(schema);
  validateRootTypes(context);
  validateDirectives(context);
  validateTypes(context);
  const errors2 = context.getErrors();
  schema.__validationErrors = errors2;
  return errors2;
}
function assertValidSchema(schema) {
  const errors2 = validateSchema(schema);
  if (errors2.length !== 0) {
    throw new Error(errors2.map((error2) => error2.message).join("\n\n"));
  }
}
class SchemaValidationContext {
  constructor(schema) {
    this._errors = [];
    this.schema = schema;
  }
  reportError(message, nodes) {
    const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes;
    this._errors.push(
      new GraphQLError(message, {
        nodes: _nodes
      })
    );
  }
  getErrors() {
    return this._errors;
  }
}
function validateRootTypes(context) {
  const schema = context.schema;
  const queryType = schema.getQueryType();
  if (!queryType) {
    context.reportError("Query root type must be provided.", schema.astNode);
  } else if (!isObjectType(queryType)) {
    var _getOperationTypeNode;
    context.reportError(
      `Query root type must be Object type, it cannot be ${inspect$2(
        queryType
      )}.`,
      (_getOperationTypeNode = getOperationTypeNode(
        schema,
        OperationTypeNode.QUERY
      )) !== null && _getOperationTypeNode !== void 0 ? _getOperationTypeNode : queryType.astNode
    );
  }
  const mutationType = schema.getMutationType();
  if (mutationType && !isObjectType(mutationType)) {
    var _getOperationTypeNode2;
    context.reportError(
      `Mutation root type must be Object type if provided, it cannot be ${inspect$2(mutationType)}.`,
      (_getOperationTypeNode2 = getOperationTypeNode(
        schema,
        OperationTypeNode.MUTATION
      )) !== null && _getOperationTypeNode2 !== void 0 ? _getOperationTypeNode2 : mutationType.astNode
    );
  }
  const subscriptionType = schema.getSubscriptionType();
  if (subscriptionType && !isObjectType(subscriptionType)) {
    var _getOperationTypeNode3;
    context.reportError(
      `Subscription root type must be Object type if provided, it cannot be ${inspect$2(subscriptionType)}.`,
      (_getOperationTypeNode3 = getOperationTypeNode(
        schema,
        OperationTypeNode.SUBSCRIPTION
      )) !== null && _getOperationTypeNode3 !== void 0 ? _getOperationTypeNode3 : subscriptionType.astNode
    );
  }
}
function getOperationTypeNode(schema, operation) {
  var _flatMap$find;
  return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes].flatMap(
    // FIXME: https://github.com/graphql/graphql-js/issues/2203
    (schemaNode) => {
      var _schemaNode$operation;
      return (
        /* c8 ignore next */
        (_schemaNode$operation = schemaNode === null || schemaNode === void 0 ? void 0 : schemaNode.operationTypes) !== null && _schemaNode$operation !== void 0 ? _schemaNode$operation : []
      );
    }
  ).find((operationNode) => operationNode.operation === operation)) === null || _flatMap$find === void 0 ? void 0 : _flatMap$find.type;
}
function validateDirectives(context) {
  for (const directive of context.schema.getDirectives()) {
    if (!isDirective(directive)) {
      context.reportError(
        `Expected directive but got: ${inspect$2(directive)}.`,
        directive === null || directive === void 0 ? void 0 : directive.astNode
      );
      continue;
    }
    validateName(context, directive);
    for (const arg of directive.args) {
      validateName(context, arg);
      if (!isInputType(arg.type)) {
        context.reportError(
          `The type of @${directive.name}(${arg.name}:) must be Input Type but got: ${inspect$2(arg.type)}.`,
          arg.astNode
        );
      }
      if (isRequiredArgument(arg) && arg.deprecationReason != null) {
        var _arg$astNode;
        context.reportError(
          `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`,
          [
            getDeprecatedDirectiveNode(arg.astNode),
            (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 ? void 0 : _arg$astNode.type
          ]
        );
      }
    }
  }
}
function validateName(context, node) {
  if (node.name.startsWith("__")) {
    context.reportError(
      `Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`,
      node.astNode
    );
  }
}
function validateTypes(context) {
  const validateInputObjectCircularRefs = createInputObjectCircularRefsValidator(context);
  const typeMap = context.schema.getTypeMap();
  for (const type2 of Object.values(typeMap)) {
    if (!isNamedType(type2)) {
      context.reportError(
        `Expected GraphQL named type but got: ${inspect$2(type2)}.`,
        type2.astNode
      );
      continue;
    }
    if (!isIntrospectionType(type2)) {
      validateName(context, type2);
    }
    if (isObjectType(type2)) {
      validateFields(context, type2);
      validateInterfaces(context, type2);
    } else if (isInterfaceType(type2)) {
      validateFields(context, type2);
      validateInterfaces(context, type2);
    } else if (isUnionType(type2)) {
      validateUnionMembers(context, type2);
    } else if (isEnumType(type2)) {
      validateEnumValues(context, type2);
    } else if (isInputObjectType(type2)) {
      validateInputFields(context, type2);
      validateInputObjectCircularRefs(type2);
    }
  }
}
function validateFields(context, type2) {
  const fields = Object.values(type2.getFields());
  if (fields.length === 0) {
    context.reportError(`Type ${type2.name} must define one or more fields.`, [
      type2.astNode,
      ...type2.extensionASTNodes
    ]);
  }
  for (const field of fields) {
    validateName(context, field);
    if (!isOutputType(field.type)) {
      var _field$astNode;
      context.reportError(
        `The type of ${type2.name}.${field.name} must be Output Type but got: ${inspect$2(field.type)}.`,
        (_field$astNode = field.astNode) === null || _field$astNode === void 0 ? void 0 : _field$astNode.type
      );
    }
    for (const arg of field.args) {
      const argName = arg.name;
      validateName(context, arg);
      if (!isInputType(arg.type)) {
        var _arg$astNode2;
        context.reportError(
          `The type of ${type2.name}.${field.name}(${argName}:) must be Input Type but got: ${inspect$2(arg.type)}.`,
          (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 ? void 0 : _arg$astNode2.type
        );
      }
      if (isRequiredArgument(arg) && arg.deprecationReason != null) {
        var _arg$astNode3;
        context.reportError(
          `Required argument ${type2.name}.${field.name}(${argName}:) cannot be deprecated.`,
          [
            getDeprecatedDirectiveNode(arg.astNode),
            (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 ? void 0 : _arg$astNode3.type
          ]
        );
      }
    }
  }
}
function validateInterfaces(context, type2) {
  const ifaceTypeNames = /* @__PURE__ */ Object.create(null);
  for (const iface of type2.getInterfaces()) {
    if (!isInterfaceType(iface)) {
      context.reportError(
        `Type ${inspect$2(type2)} must only implement Interface types, it cannot implement ${inspect$2(iface)}.`,
        getAllImplementsInterfaceNodes(type2, iface)
      );
      continue;
    }
    if (type2 === iface) {
      context.reportError(
        `Type ${type2.name} cannot implement itself because it would create a circular reference.`,
        getAllImplementsInterfaceNodes(type2, iface)
      );
      continue;
    }
    if (ifaceTypeNames[iface.name]) {
      context.reportError(
        `Type ${type2.name} can only implement ${iface.name} once.`,
        getAllImplementsInterfaceNodes(type2, iface)
      );
      continue;
    }
    ifaceTypeNames[iface.name] = true;
    validateTypeImplementsAncestors(context, type2, iface);
    validateTypeImplementsInterface(context, type2, iface);
  }
}
function validateTypeImplementsInterface(context, type2, iface) {
  const typeFieldMap = type2.getFields();
  for (const ifaceField of Object.values(iface.getFields())) {
    const fieldName = ifaceField.name;
    const typeField = typeFieldMap[fieldName];
    if (!typeField) {
      context.reportError(
        `Interface field ${iface.name}.${fieldName} expected but ${type2.name} does not provide it.`,
        [ifaceField.astNode, type2.astNode, ...type2.extensionASTNodes]
      );
      continue;
    }
    if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) {
      var _ifaceField$astNode, _typeField$astNode;
      context.reportError(
        `Interface field ${iface.name}.${fieldName} expects type ${inspect$2(ifaceField.type)} but ${type2.name}.${fieldName} is type ${inspect$2(typeField.type)}.`,
        [
          (_ifaceField$astNode = ifaceField.astNode) === null || _ifaceField$astNode === void 0 ? void 0 : _ifaceField$astNode.type,
          (_typeField$astNode = typeField.astNode) === null || _typeField$astNode === void 0 ? void 0 : _typeField$astNode.type
        ]
      );
    }
    for (const ifaceArg of ifaceField.args) {
      const argName = ifaceArg.name;
      const typeArg = typeField.args.find((arg) => arg.name === argName);
      if (!typeArg) {
        context.reportError(
          `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type2.name}.${fieldName} does not provide it.`,
          [ifaceArg.astNode, typeField.astNode]
        );
        continue;
      }
      if (!isEqualType(ifaceArg.type, typeArg.type)) {
        var _ifaceArg$astNode, _typeArg$astNode;
        context.reportError(
          `Interface field argument ${iface.name}.${fieldName}(${argName}:) expects type ${inspect$2(ifaceArg.type)} but ${type2.name}.${fieldName}(${argName}:) is type ${inspect$2(typeArg.type)}.`,
          [
            (_ifaceArg$astNode = ifaceArg.astNode) === null || _ifaceArg$astNode === void 0 ? void 0 : _ifaceArg$astNode.type,
            (_typeArg$astNode = typeArg.astNode) === null || _typeArg$astNode === void 0 ? void 0 : _typeArg$astNode.type
          ]
        );
      }
    }
    for (const typeArg of typeField.args) {
      const argName = typeArg.name;
      const ifaceArg = ifaceField.args.find((arg) => arg.name === argName);
      if (!ifaceArg && isRequiredArgument(typeArg)) {
        context.reportError(
          `Object field ${type2.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`,
          [typeArg.astNode, ifaceField.astNode]
        );
      }
    }
  }
}
function validateTypeImplementsAncestors(context, type2, iface) {
  const ifaceInterfaces = type2.getInterfaces();
  for (const transitive of iface.getInterfaces()) {
    if (!ifaceInterfaces.includes(transitive)) {
      context.reportError(
        transitive === type2 ? `Type ${type2.name} cannot implement ${iface.name} because it would create a circular reference.` : `Type ${type2.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`,
        [
          ...getAllImplementsInterfaceNodes(iface, transitive),
          ...getAllImplementsInterfaceNodes(type2, iface)
        ]
      );
    }
  }
}
function validateUnionMembers(context, union) {
  const memberTypes = union.getTypes();
  if (memberTypes.length === 0) {
    context.reportError(
      `Union type ${union.name} must define one or more member types.`,
      [union.astNode, ...union.extensionASTNodes]
    );
  }
  const includedTypeNames = /* @__PURE__ */ Object.create(null);
  for (const memberType of memberTypes) {
    if (includedTypeNames[memberType.name]) {
      context.reportError(
        `Union type ${union.name} can only include type ${memberType.name} once.`,
        getUnionMemberTypeNodes(union, memberType.name)
      );
      continue;
    }
    includedTypeNames[memberType.name] = true;
    if (!isObjectType(memberType)) {
      context.reportError(
        `Union type ${union.name} can only include Object types, it cannot include ${inspect$2(memberType)}.`,
        getUnionMemberTypeNodes(union, String(memberType))
      );
    }
  }
}
function validateEnumValues(context, enumType) {
  const enumValues = enumType.getValues();
  if (enumValues.length === 0) {
    context.reportError(
      `Enum type ${enumType.name} must define one or more values.`,
      [enumType.astNode, ...enumType.extensionASTNodes]
    );
  }
  for (const enumValue of enumValues) {
    validateName(context, enumValue);
  }
}
function validateInputFields(context, inputObj) {
  const fields = Object.values(inputObj.getFields());
  if (fields.length === 0) {
    context.reportError(
      `Input Object type ${inputObj.name} must define one or more fields.`,
      [inputObj.astNode, ...inputObj.extensionASTNodes]
    );
  }
  for (const field of fields) {
    validateName(context, field);
    if (!isInputType(field.type)) {
      var _field$astNode2;
      context.reportError(
        `The type of ${inputObj.name}.${field.name} must be Input Type but got: ${inspect$2(field.type)}.`,
        (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 ? void 0 : _field$astNode2.type
      );
    }
    if (isRequiredInputField(field) && field.deprecationReason != null) {
      var _field$astNode3;
      context.reportError(
        `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`,
        [
          getDeprecatedDirectiveNode(field.astNode),
          (_field$astNode3 = field.astNode) === null || _field$astNode3 === void 0 ? void 0 : _field$astNode3.type
        ]
      );
    }
  }
}
function createInputObjectCircularRefsValidator(context) {
  const visitedTypes = /* @__PURE__ */ Object.create(null);
  const fieldPath = [];
  const fieldPathIndexByTypeName = /* @__PURE__ */ Object.create(null);
  return detectCycleRecursive;
  function detectCycleRecursive(inputObj) {
    if (visitedTypes[inputObj.name]) {
      return;
    }
    visitedTypes[inputObj.name] = true;
    fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;
    const fields = Object.values(inputObj.getFields());
    for (const field of fields) {
      if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) {
        const fieldType = field.type.ofType;
        const cycleIndex = fieldPathIndexByTypeName[fieldType.name];
        fieldPath.push(field);
        if (cycleIndex === void 0) {
          detectCycleRecursive(fieldType);
        } else {
          const cyclePath = fieldPath.slice(cycleIndex);
          const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join(".");
          context.reportError(
            `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`,
            cyclePath.map((fieldObj) => fieldObj.astNode)
          );
        }
        fieldPath.pop();
      }
    }
    fieldPathIndexByTypeName[inputObj.name] = void 0;
  }
}
function getAllImplementsInterfaceNodes(type2, iface) {
  const { astNode, extensionASTNodes } = type2;
  const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes;
  return nodes.flatMap((typeNode) => {
    var _typeNode$interfaces;
    return (
      /* c8 ignore next */
      (_typeNode$interfaces = typeNode.interfaces) !== null && _typeNode$interfaces !== void 0 ? _typeNode$interfaces : []
    );
  }).filter((ifaceNode) => ifaceNode.name.value === iface.name);
}
function getUnionMemberTypeNodes(union, typeName) {
  const { astNode, extensionASTNodes } = union;
  const nodes = astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes;
  return nodes.flatMap((unionNode) => {
    var _unionNode$types;
    return (
      /* c8 ignore next */
      (_unionNode$types = unionNode.types) !== null && _unionNode$types !== void 0 ? _unionNode$types : []
    );
  }).filter((typeNode) => typeNode.name.value === typeName);
}
function getDeprecatedDirectiveNode(definitionNode) {
  var _definitionNode$direc;
  return definitionNode === null || definitionNode === void 0 ? void 0 : (_definitionNode$direc = definitionNode.directives) === null || _definitionNode$direc === void 0 ? void 0 : _definitionNode$direc.find(
    (node) => node.name.value === GraphQLDeprecatedDirective.name
  );
}
function typeFromAST(schema, typeNode) {
  switch (typeNode.kind) {
    case Kind.LIST_TYPE: {
      const innerType = typeFromAST(schema, typeNode.type);
      return innerType && new GraphQLList(innerType);
    }
    case Kind.NON_NULL_TYPE: {
      const innerType = typeFromAST(schema, typeNode.type);
      return innerType && new GraphQLNonNull(innerType);
    }
    case Kind.NAMED_TYPE:
      return schema.getType(typeNode.name.value);
  }
}
class TypeInfo {
  constructor(schema, initialType, getFieldDefFn) {
    this._schema = schema;
    this._typeStack = [];
    this._parentTypeStack = [];
    this._inputTypeStack = [];
    this._fieldDefStack = [];
    this._defaultValueStack = [];
    this._directive = null;
    this._argument = null;
    this._enumValue = null;
    this._getFieldDef = getFieldDefFn !== null && getFieldDefFn !== void 0 ? getFieldDefFn : getFieldDef$1;
    if (initialType) {
      if (isInputType(initialType)) {
        this._inputTypeStack.push(initialType);
      }
      if (isCompositeType(initialType)) {
        this._parentTypeStack.push(initialType);
      }
      if (isOutputType(initialType)) {
        this._typeStack.push(initialType);
      }
    }
  }
  get [Symbol.toStringTag]() {
    return "TypeInfo";
  }
  getType() {
    if (this._typeStack.length > 0) {
      return this._typeStack[this._typeStack.length - 1];
    }
  }
  getParentType() {
    if (this._parentTypeStack.length > 0) {
      return this._parentTypeStack[this._parentTypeStack.length - 1];
    }
  }
  getInputType() {
    if (this._inputTypeStack.length > 0) {
      return this._inputTypeStack[this._inputTypeStack.length - 1];
    }
  }
  getParentInputType() {
    if (this._inputTypeStack.length > 1) {
      return this._inputTypeStack[this._inputTypeStack.length - 2];
    }
  }
  getFieldDef() {
    if (this._fieldDefStack.length > 0) {
      return this._fieldDefStack[this._fieldDefStack.length - 1];
    }
  }
  getDefaultValue() {
    if (this._defaultValueStack.length > 0) {
      return this._defaultValueStack[this._defaultValueStack.length - 1];
    }
  }
  getDirective() {
    return this._directive;
  }
  getArgument() {
    return this._argument;
  }
  getEnumValue() {
    return this._enumValue;
  }
  enter(node) {
    const schema = this._schema;
    switch (node.kind) {
      case Kind.SELECTION_SET: {
        const namedType = getNamedType(this.getType());
        this._parentTypeStack.push(
          isCompositeType(namedType) ? namedType : void 0
        );
        break;
      }
      case Kind.FIELD: {
        const parentType = this.getParentType();
        let fieldDef;
        let fieldType;
        if (parentType) {
          fieldDef = this._getFieldDef(schema, parentType, node);
          if (fieldDef) {
            fieldType = fieldDef.type;
          }
        }
        this._fieldDefStack.push(fieldDef);
        this._typeStack.push(isOutputType(fieldType) ? fieldType : void 0);
        break;
      }
      case Kind.DIRECTIVE:
        this._directive = schema.getDirective(node.name.value);
        break;
      case Kind.OPERATION_DEFINITION: {
        const rootType = schema.getRootType(node.operation);
        this._typeStack.push(isObjectType(rootType) ? rootType : void 0);
        break;
      }
      case Kind.INLINE_FRAGMENT:
      case Kind.FRAGMENT_DEFINITION: {
        const typeConditionAST = node.typeCondition;
        const outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType());
        this._typeStack.push(isOutputType(outputType) ? outputType : void 0);
        break;
      }
      case Kind.VARIABLE_DEFINITION: {
        const inputType = typeFromAST(schema, node.type);
        this._inputTypeStack.push(
          isInputType(inputType) ? inputType : void 0
        );
        break;
      }
      case Kind.ARGUMENT: {
        var _this$getDirective;
        let argDef;
        let argType;
        const fieldOrDirective = (_this$getDirective = this.getDirective()) !== null && _this$getDirective !== void 0 ? _this$getDirective : this.getFieldDef();
        if (fieldOrDirective) {
          argDef = fieldOrDirective.args.find(
            (arg) => arg.name === node.name.value
          );
          if (argDef) {
            argType = argDef.type;
          }
        }
        this._argument = argDef;
        this._defaultValueStack.push(argDef ? argDef.defaultValue : void 0);
        this._inputTypeStack.push(isInputType(argType) ? argType : void 0);
        break;
      }
      case Kind.LIST: {
        const listType = getNullableType(this.getInputType());
        const itemType = isListType(listType) ? listType.ofType : listType;
        this._defaultValueStack.push(void 0);
        this._inputTypeStack.push(isInputType(itemType) ? itemType : void 0);
        break;
      }
      case Kind.OBJECT_FIELD: {
        const objectType2 = getNamedType(this.getInputType());
        let inputFieldType;
        let inputField;
        if (isInputObjectType(objectType2)) {
          inputField = objectType2.getFields()[node.name.value];
          if (inputField) {
            inputFieldType = inputField.type;
          }
        }
        this._defaultValueStack.push(
          inputField ? inputField.defaultValue : void 0
        );
        this._inputTypeStack.push(
          isInputType(inputFieldType) ? inputFieldType : void 0
        );
        break;
      }
      case Kind.ENUM: {
        const enumType = getNamedType(this.getInputType());
        let enumValue;
        if (isEnumType(enumType)) {
          enumValue = enumType.getValue(node.value);
        }
        this._enumValue = enumValue;
        break;
      }
    }
  }
  leave(node) {
    switch (node.kind) {
      case Kind.SELECTION_SET:
        this._parentTypeStack.pop();
        break;
      case Kind.FIELD:
        this._fieldDefStack.pop();
        this._typeStack.pop();
        break;
      case Kind.DIRECTIVE:
        this._directive = null;
        break;
      case Kind.OPERATION_DEFINITION:
      case Kind.INLINE_FRAGMENT:
      case Kind.FRAGMENT_DEFINITION:
        this._typeStack.pop();
        break;
      case Kind.VARIABLE_DEFINITION:
        this._inputTypeStack.pop();
        break;
      case Kind.ARGUMENT:
        this._argument = null;
        this._defaultValueStack.pop();
        this._inputTypeStack.pop();
        break;
      case Kind.LIST:
      case Kind.OBJECT_FIELD:
        this._defaultValueStack.pop();
        this._inputTypeStack.pop();
        break;
      case Kind.ENUM:
        this._enumValue = null;
        break;
    }
  }
}
function getFieldDef$1(schema, parentType, fieldNode) {
  const name2 = fieldNode.name.value;
  if (name2 === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
    return SchemaMetaFieldDef;
  }
  if (name2 === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
    return TypeMetaFieldDef;
  }
  if (name2 === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {
    return TypeNameMetaFieldDef;
  }
  if (isObjectType(parentType) || isInterfaceType(parentType)) {
    return parentType.getFields()[name2];
  }
}
function visitWithTypeInfo(typeInfo, visitor) {
  return {
    enter(...args) {
      const node = args[0];
      typeInfo.enter(node);
      const fn = getEnterLeaveForKind(visitor, node.kind).enter;
      if (fn) {
        const result = fn.apply(visitor, args);
        if (result !== void 0) {
          typeInfo.leave(node);
          if (isNode(result)) {
            typeInfo.enter(result);
          }
        }
        return result;
      }
    },
    leave(...args) {
      const node = args[0];
      const fn = getEnterLeaveForKind(visitor, node.kind).leave;
      let result;
      if (fn) {
        result = fn.apply(visitor, args);
      }
      typeInfo.leave(node);
      return result;
    }
  };
}
function isDefinitionNode(node) {
  return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node);
}
function isExecutableDefinitionNode(node) {
  return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION;
}
function isTypeSystemDefinitionNode(node) {
  return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION;
}
function isTypeDefinitionNode(node) {
  return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION;
}
function isTypeSystemExtensionNode(node) {
  return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node);
}
function isTypeExtensionNode(node) {
  return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION;
}
function ExecutableDefinitionsRule(context) {
  return {
    Document(node) {
      for (const definition of node.definitions) {
        if (!isExecutableDefinitionNode(definition)) {
          const defName = definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? "schema" : '"' + definition.name.value + '"';
          context.reportError(
            new GraphQLError(`The ${defName} definition is not executable.`, {
              nodes: definition
            })
          );
        }
      }
      return false;
    }
  };
}
function FieldsOnCorrectTypeRule(context) {
  return {
    Field(node) {
      const type2 = context.getParentType();
      if (type2) {
        const fieldDef = context.getFieldDef();
        if (!fieldDef) {
          const schema = context.getSchema();
          const fieldName = node.name.value;
          let suggestion = didYouMean(
            "to use an inline fragment on",
            getSuggestedTypeNames(schema, type2, fieldName)
          );
          if (suggestion === "") {
            suggestion = didYouMean(getSuggestedFieldNames(type2, fieldName));
          }
          context.reportError(
            new GraphQLError(
              `Cannot query field "${fieldName}" on type "${type2.name}".` + suggestion,
              {
                nodes: node
              }
            )
          );
        }
      }
    }
  };
}
function getSuggestedTypeNames(schema, type2, fieldName) {
  if (!isAbstractType(type2)) {
    return [];
  }
  const suggestedTypes = /* @__PURE__ */ new Set();
  const usageCount = /* @__PURE__ */ Object.create(null);
  for (const possibleType of schema.getPossibleTypes(type2)) {
    if (!possibleType.getFields()[fieldName]) {
      continue;
    }
    suggestedTypes.add(possibleType);
    usageCount[possibleType.name] = 1;
    for (const possibleInterface of possibleType.getInterfaces()) {
      var _usageCount$possibleI;
      if (!possibleInterface.getFields()[fieldName]) {
        continue;
      }
      suggestedTypes.add(possibleInterface);
      usageCount[possibleInterface.name] = ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== null && _usageCount$possibleI !== void 0 ? _usageCount$possibleI : 0) + 1;
    }
  }
  return [...suggestedTypes].sort((typeA, typeB) => {
    const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name];
    if (usageCountDiff !== 0) {
      return usageCountDiff;
    }
    if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) {
      return -1;
    }
    if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) {
      return 1;
    }
    return naturalCompare(typeA.name, typeB.name);
  }).map((x) => x.name);
}
function getSuggestedFieldNames(type2, fieldName) {
  if (isObjectType(type2) || isInterfaceType(type2)) {
    const possibleFieldNames = Object.keys(type2.getFields());
    return suggestionList(fieldName, possibleFieldNames);
  }
  return [];
}
function FragmentsOnCompositeTypesRule(context) {
  return {
    InlineFragment(node) {
      const typeCondition = node.typeCondition;
      if (typeCondition) {
        const type2 = typeFromAST(context.getSchema(), typeCondition);
        if (type2 && !isCompositeType(type2)) {
          const typeStr = print(typeCondition);
          context.reportError(
            new GraphQLError(
              `Fragment cannot condition on non composite type "${typeStr}".`,
              {
                nodes: typeCondition
              }
            )
          );
        }
      }
    },
    FragmentDefinition(node) {
      const type2 = typeFromAST(context.getSchema(), node.typeCondition);
      if (type2 && !isCompositeType(type2)) {
        const typeStr = print(node.typeCondition);
        context.reportError(
          new GraphQLError(
            `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`,
            {
              nodes: node.typeCondition
            }
          )
        );
      }
    }
  };
}
function KnownArgumentNamesRule(context) {
  return {
    // eslint-disable-next-line new-cap
    ...KnownArgumentNamesOnDirectivesRule(context),
    Argument(argNode) {
      const argDef = context.getArgument();
      const fieldDef = context.getFieldDef();
      const parentType = context.getParentType();
      if (!argDef && fieldDef && parentType) {
        const argName = argNode.name.value;
        const knownArgsNames = fieldDef.args.map((arg) => arg.name);
        const suggestions = suggestionList(argName, knownArgsNames);
        context.reportError(
          new GraphQLError(
            `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + didYouMean(suggestions),
            {
              nodes: argNode
            }
          )
        );
      }
    }
  };
}
function KnownArgumentNamesOnDirectivesRule(context) {
  const directiveArgs = /* @__PURE__ */ Object.create(null);
  const schema = context.getSchema();
  const definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
  for (const directive of definedDirectives) {
    directiveArgs[directive.name] = directive.args.map((arg) => arg.name);
  }
  const astDefinitions = context.getDocument().definitions;
  for (const def2 of astDefinitions) {
    if (def2.kind === Kind.DIRECTIVE_DEFINITION) {
      var _def$arguments;
      const argsNodes = (_def$arguments = def2.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : [];
      directiveArgs[def2.name.value] = argsNodes.map((arg) => arg.name.value);
    }
  }
  return {
    Directive(directiveNode) {
      const directiveName = directiveNode.name.value;
      const knownArgs = directiveArgs[directiveName];
      if (directiveNode.arguments && knownArgs) {
        for (const argNode of directiveNode.arguments) {
          const argName = argNode.name.value;
          if (!knownArgs.includes(argName)) {
            const suggestions = suggestionList(argName, knownArgs);
            context.reportError(
              new GraphQLError(
                `Unknown argument "${argName}" on directive "@${directiveName}".` + didYouMean(suggestions),
                {
                  nodes: argNode
                }
              )
            );
          }
        }
      }
      return false;
    }
  };
}
function KnownDirectivesRule(context) {
  const locationsMap = /* @__PURE__ */ Object.create(null);
  const schema = context.getSchema();
  const definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
  for (const directive of definedDirectives) {
    locationsMap[directive.name] = directive.locations;
  }
  const astDefinitions = context.getDocument().definitions;
  for (const def2 of astDefinitions) {
    if (def2.kind === Kind.DIRECTIVE_DEFINITION) {
      locationsMap[def2.name.value] = def2.locations.map((name2) => name2.value);
    }
  }
  return {
    Directive(node, _key, _parent, _path, ancestors) {
      const name2 = node.name.value;
      const locations = locationsMap[name2];
      if (!locations) {
        context.reportError(
          new GraphQLError(`Unknown directive "@${name2}".`, {
            nodes: node
          })
        );
        return;
      }
      const candidateLocation = getDirectiveLocationForASTPath(ancestors);
      if (candidateLocation && !locations.includes(candidateLocation)) {
        context.reportError(
          new GraphQLError(
            `Directive "@${name2}" may not be used on ${candidateLocation}.`,
            {
              nodes: node
            }
          )
        );
      }
    }
  };
}
function getDirectiveLocationForASTPath(ancestors) {
  const appliedTo = ancestors[ancestors.length - 1];
  "kind" in appliedTo || invariant(false);
  switch (appliedTo.kind) {
    case Kind.OPERATION_DEFINITION:
      return getDirectiveLocationForOperation(appliedTo.operation);
    case Kind.FIELD:
      return DirectiveLocation.FIELD;
    case Kind.FRAGMENT_SPREAD:
      return DirectiveLocation.FRAGMENT_SPREAD;
    case Kind.INLINE_FRAGMENT:
      return DirectiveLocation.INLINE_FRAGMENT;
    case Kind.FRAGMENT_DEFINITION:
      return DirectiveLocation.FRAGMENT_DEFINITION;
    case Kind.VARIABLE_DEFINITION:
      return DirectiveLocation.VARIABLE_DEFINITION;
    case Kind.SCHEMA_DEFINITION:
    case Kind.SCHEMA_EXTENSION:
      return DirectiveLocation.SCHEMA;
    case Kind.SCALAR_TYPE_DEFINITION:
    case Kind.SCALAR_TYPE_EXTENSION:
      return DirectiveLocation.SCALAR;
    case Kind.OBJECT_TYPE_DEFINITION:
    case Kind.OBJECT_TYPE_EXTENSION:
      return DirectiveLocation.OBJECT;
    case Kind.FIELD_DEFINITION:
      return DirectiveLocation.FIELD_DEFINITION;
    case Kind.INTERFACE_TYPE_DEFINITION:
    case Kind.INTERFACE_TYPE_EXTENSION:
      return DirectiveLocation.INTERFACE;
    case Kind.UNION_TYPE_DEFINITION:
    case Kind.UNION_TYPE_EXTENSION:
      return DirectiveLocation.UNION;
    case Kind.ENUM_TYPE_DEFINITION:
    case Kind.ENUM_TYPE_EXTENSION:
      return DirectiveLocation.ENUM;
    case Kind.ENUM_VALUE_DEFINITION:
      return DirectiveLocation.ENUM_VALUE;
    case Kind.INPUT_OBJECT_TYPE_DEFINITION:
    case Kind.INPUT_OBJECT_TYPE_EXTENSION:
      return DirectiveLocation.INPUT_OBJECT;
    case Kind.INPUT_VALUE_DEFINITION: {
      const parentNode = ancestors[ancestors.length - 3];
      "kind" in parentNode || invariant(false);
      return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION;
    }
    default:
      invariant(false, "Unexpected kind: " + inspect$2(appliedTo.kind));
  }
}
function getDirectiveLocationForOperation(operation) {
  switch (operation) {
    case OperationTypeNode.QUERY:
      return DirectiveLocation.QUERY;
    case OperationTypeNode.MUTATION:
      return DirectiveLocation.MUTATION;
    case OperationTypeNode.SUBSCRIPTION:
      return DirectiveLocation.SUBSCRIPTION;
  }
}
function KnownFragmentNamesRule(context) {
  return {
    FragmentSpread(node) {
      const fragmentName = node.name.value;
      const fragment = context.getFragment(fragmentName);
      if (!fragment) {
        context.reportError(
          new GraphQLError(`Unknown fragment "${fragmentName}".`, {
            nodes: node.name
          })
        );
      }
    }
  };
}
function KnownTypeNamesRule(context) {
  const schema = context.getSchema();
  const existingTypesMap = schema ? schema.getTypeMap() : /* @__PURE__ */ Object.create(null);
  const definedTypes = /* @__PURE__ */ Object.create(null);
  for (const def2 of context.getDocument().definitions) {
    if (isTypeDefinitionNode(def2)) {
      definedTypes[def2.name.value] = true;
    }
  }
  const typeNames = [
    ...Object.keys(existingTypesMap),
    ...Object.keys(definedTypes)
  ];
  return {
    NamedType(node, _1, parent, _2, ancestors) {
      const typeName = node.name.value;
      if (!existingTypesMap[typeName] && !definedTypes[typeName]) {
        var _ancestors$;
        const definitionNode = (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 ? _ancestors$ : parent;
        const isSDL = definitionNode != null && isSDLNode(definitionNode);
        if (isSDL && standardTypeNames.includes(typeName)) {
          return;
        }
        const suggestedTypes = suggestionList(
          typeName,
          isSDL ? standardTypeNames.concat(typeNames) : typeNames
        );
        context.reportError(
          new GraphQLError(
            `Unknown type "${typeName}".` + didYouMean(suggestedTypes),
            {
              nodes: node
            }
          )
        );
      }
    }
  };
}
const standardTypeNames = [...specifiedScalarTypes, ...introspectionTypes].map(
  (type2) => type2.name
);
function isSDLNode(value) {
  return "kind" in value && (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value));
}
function LoneAnonymousOperationRule(context) {
  let operationCount = 0;
  return {
    Document(node) {
      operationCount = node.definitions.filter(
        (definition) => definition.kind === Kind.OPERATION_DEFINITION
      ).length;
    },
    OperationDefinition(node) {
      if (!node.name && operationCount > 1) {
        context.reportError(
          new GraphQLError(
            "This anonymous operation must be the only defined operation.",
            {
              nodes: node
            }
          )
        );
      }
    }
  };
}
function LoneSchemaDefinitionRule(context) {
  var _ref, _ref2, _oldSchema$astNode;
  const oldSchema = context.getSchema();
  const alreadyDefined = (_ref = (_ref2 = (_oldSchema$astNode = oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 ? _oldSchema$astNode : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getQueryType()) !== null && _ref2 !== void 0 ? _ref2 : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getMutationType()) !== null && _ref !== void 0 ? _ref : oldSchema === null || oldSchema === void 0 ? void 0 : oldSchema.getSubscriptionType();
  let schemaDefinitionsCount = 0;
  return {
    SchemaDefinition(node) {
      if (alreadyDefined) {
        context.reportError(
          new GraphQLError(
            "Cannot define a new schema within a schema extension.",
            {
              nodes: node
            }
          )
        );
        return;
      }
      if (schemaDefinitionsCount > 0) {
        context.reportError(
          new GraphQLError("Must provide only one schema definition.", {
            nodes: node
          })
        );
      }
      ++schemaDefinitionsCount;
    }
  };
}
function NoFragmentCyclesRule(context) {
  const visitedFrags = /* @__PURE__ */ Object.create(null);
  const spreadPath = [];
  const spreadPathIndexByName = /* @__PURE__ */ Object.create(null);
  return {
    OperationDefinition: () => false,
    FragmentDefinition(node) {
      detectCycleRecursive(node);
      return false;
    }
  };
  function detectCycleRecursive(fragment) {
    if (visitedFrags[fragment.name.value]) {
      return;
    }
    const fragmentName = fragment.name.value;
    visitedFrags[fragmentName] = true;
    const spreadNodes = context.getFragmentSpreads(fragment.selectionSet);
    if (spreadNodes.length === 0) {
      return;
    }
    spreadPathIndexByName[fragmentName] = spreadPath.length;
    for (const spreadNode of spreadNodes) {
      const spreadName = spreadNode.name.value;
      const cycleIndex = spreadPathIndexByName[spreadName];
      spreadPath.push(spreadNode);
      if (cycleIndex === void 0) {
        const spreadFragment = context.getFragment(spreadName);
        if (spreadFragment) {
          detectCycleRecursive(spreadFragment);
        }
      } else {
        const cyclePath = spreadPath.slice(cycleIndex);
        const viaPath = cyclePath.slice(0, -1).map((s) => '"' + s.name.value + '"').join(", ");
        context.reportError(
          new GraphQLError(
            `Cannot spread fragment "${spreadName}" within itself` + (viaPath !== "" ? ` via ${viaPath}.` : "."),
            {
              nodes: cyclePath
            }
          )
        );
      }
      spreadPath.pop();
    }
    spreadPathIndexByName[fragmentName] = void 0;
  }
}
function NoUndefinedVariablesRule(context) {
  let variableNameDefined = /* @__PURE__ */ Object.create(null);
  return {
    OperationDefinition: {
      enter() {
        variableNameDefined = /* @__PURE__ */ Object.create(null);
      },
      leave(operation) {
        const usages = context.getRecursiveVariableUsages(operation);
        for (const { node } of usages) {
          const varName = node.name.value;
          if (variableNameDefined[varName] !== true) {
            context.reportError(
              new GraphQLError(
                operation.name ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` : `Variable "$${varName}" is not defined.`,
                {
                  nodes: [node, operation]
                }
              )
            );
          }
        }
      }
    },
    VariableDefinition(node) {
      variableNameDefined[node.variable.name.value] = true;
    }
  };
}
function NoUnusedFragmentsRule(context) {
  const operationDefs = [];
  const fragmentDefs = [];
  return {
    OperationDefinition(node) {
      operationDefs.push(node);
      return false;
    },
    FragmentDefinition(node) {
      fragmentDefs.push(node);
      return false;
    },
    Document: {
      leave() {
        const fragmentNameUsed = /* @__PURE__ */ Object.create(null);
        for (const operation of operationDefs) {
          for (const fragment of context.getRecursivelyReferencedFragments(
            operation
          )) {
            fragmentNameUsed[fragment.name.value] = true;
          }
        }
        for (const fragmentDef of fragmentDefs) {
          const fragName = fragmentDef.name.value;
          if (fragmentNameUsed[fragName] !== true) {
            context.reportError(
              new GraphQLError(`Fragment "${fragName}" is never used.`, {
                nodes: fragmentDef
              })
            );
          }
        }
      }
    }
  };
}
function NoUnusedVariablesRule(context) {
  let variableDefs = [];
  return {
    OperationDefinition: {
      enter() {
        variableDefs = [];
      },
      leave(operation) {
        const variableNameUsed = /* @__PURE__ */ Object.create(null);
        const usages = context.getRecursiveVariableUsages(operation);
        for (const { node } of usages) {
          variableNameUsed[node.name.value] = true;
        }
        for (const variableDef of variableDefs) {
          const variableName = variableDef.variable.name.value;
          if (variableNameUsed[variableName] !== true) {
            context.reportError(
              new GraphQLError(
                operation.name ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` : `Variable "$${variableName}" is never used.`,
                {
                  nodes: variableDef
                }
              )
            );
          }
        }
      }
    },
    VariableDefinition(def2) {
      variableDefs.push(def2);
    }
  };
}
function sortValueNode(valueNode) {
  switch (valueNode.kind) {
    case Kind.OBJECT:
      return { ...valueNode, fields: sortFields(valueNode.fields) };
    case Kind.LIST:
      return { ...valueNode, values: valueNode.values.map(sortValueNode) };
    case Kind.INT:
    case Kind.FLOAT:
    case Kind.STRING:
    case Kind.BOOLEAN:
    case Kind.NULL:
    case Kind.ENUM:
    case Kind.VARIABLE:
      return valueNode;
  }
}
function sortFields(fields) {
  return fields.map((fieldNode) => ({
    ...fieldNode,
    value: sortValueNode(fieldNode.value)
  })).sort(
    (fieldA, fieldB) => naturalCompare(fieldA.name.value, fieldB.name.value)
  );
}
function reasonMessage(reason) {
  if (Array.isArray(reason)) {
    return reason.map(
      ([responseName, subReason]) => `subfields "${responseName}" conflict because ` + reasonMessage(subReason)
    ).join(" and ");
  }
  return reason;
}
function OverlappingFieldsCanBeMergedRule(context) {
  const comparedFragmentPairs = new PairSet();
  const cachedFieldsAndFragmentNames = /* @__PURE__ */ new Map();
  return {
    SelectionSet(selectionSet) {
      const conflicts = findConflictsWithinSelectionSet(
        context,
        cachedFieldsAndFragmentNames,
        comparedFragmentPairs,
        context.getParentType(),
        selectionSet
      );
      for (const [[responseName, reason], fields1, fields2] of conflicts) {
        const reasonMsg = reasonMessage(reason);
        context.reportError(
          new GraphQLError(
            `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`,
            {
              nodes: fields1.concat(fields2)
            }
          )
        );
      }
    }
  };
}
function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) {
  const conflicts = [];
  const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    parentType,
    selectionSet
  );
  collectConflictsWithin(
    context,
    conflicts,
    cachedFieldsAndFragmentNames,
    comparedFragmentPairs,
    fieldMap
  );
  if (fragmentNames.length !== 0) {
    for (let i = 0; i < fragmentNames.length; i++) {
      collectConflictsBetweenFieldsAndFragment(
        context,
        conflicts,
        cachedFieldsAndFragmentNames,
        comparedFragmentPairs,
        false,
        fieldMap,
        fragmentNames[i]
      );
      for (let j = i + 1; j < fragmentNames.length; j++) {
        collectConflictsBetweenFragments(
          context,
          conflicts,
          cachedFieldsAndFragmentNames,
          comparedFragmentPairs,
          false,
          fragmentNames[i],
          fragmentNames[j]
        );
      }
    }
  }
  return conflicts;
}
function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) {
  const fragment = context.getFragment(fragmentName);
  if (!fragment) {
    return;
  }
  const [fieldMap2, referencedFragmentNames] = getReferencedFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    fragment
  );
  if (fieldMap === fieldMap2) {
    return;
  }
  collectConflictsBetween(
    context,
    conflicts,
    cachedFieldsAndFragmentNames,
    comparedFragmentPairs,
    areMutuallyExclusive,
    fieldMap,
    fieldMap2
  );
  for (const referencedFragmentName of referencedFragmentNames) {
    if (comparedFragmentPairs.has(
      referencedFragmentName,
      fragmentName,
      areMutuallyExclusive
    )) {
      continue;
    }
    comparedFragmentPairs.add(
      referencedFragmentName,
      fragmentName,
      areMutuallyExclusive
    );
    collectConflictsBetweenFieldsAndFragment(
      context,
      conflicts,
      cachedFieldsAndFragmentNames,
      comparedFragmentPairs,
      areMutuallyExclusive,
      fieldMap,
      referencedFragmentName
    );
  }
}
function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) {
  if (fragmentName1 === fragmentName2) {
    return;
  }
  if (comparedFragmentPairs.has(
    fragmentName1,
    fragmentName2,
    areMutuallyExclusive
  )) {
    return;
  }
  comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);
  const fragment1 = context.getFragment(fragmentName1);
  const fragment2 = context.getFragment(fragmentName2);
  if (!fragment1 || !fragment2) {
    return;
  }
  const [fieldMap1, referencedFragmentNames1] = getReferencedFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    fragment1
  );
  const [fieldMap2, referencedFragmentNames2] = getReferencedFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    fragment2
  );
  collectConflictsBetween(
    context,
    conflicts,
    cachedFieldsAndFragmentNames,
    comparedFragmentPairs,
    areMutuallyExclusive,
    fieldMap1,
    fieldMap2
  );
  for (const referencedFragmentName2 of referencedFragmentNames2) {
    collectConflictsBetweenFragments(
      context,
      conflicts,
      cachedFieldsAndFragmentNames,
      comparedFragmentPairs,
      areMutuallyExclusive,
      fragmentName1,
      referencedFragmentName2
    );
  }
  for (const referencedFragmentName1 of referencedFragmentNames1) {
    collectConflictsBetweenFragments(
      context,
      conflicts,
      cachedFieldsAndFragmentNames,
      comparedFragmentPairs,
      areMutuallyExclusive,
      referencedFragmentName1,
      fragmentName2
    );
  }
}
function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) {
  const conflicts = [];
  const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    parentType1,
    selectionSet1
  );
  const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    parentType2,
    selectionSet2
  );
  collectConflictsBetween(
    context,
    conflicts,
    cachedFieldsAndFragmentNames,
    comparedFragmentPairs,
    areMutuallyExclusive,
    fieldMap1,
    fieldMap2
  );
  for (const fragmentName2 of fragmentNames2) {
    collectConflictsBetweenFieldsAndFragment(
      context,
      conflicts,
      cachedFieldsAndFragmentNames,
      comparedFragmentPairs,
      areMutuallyExclusive,
      fieldMap1,
      fragmentName2
    );
  }
  for (const fragmentName1 of fragmentNames1) {
    collectConflictsBetweenFieldsAndFragment(
      context,
      conflicts,
      cachedFieldsAndFragmentNames,
      comparedFragmentPairs,
      areMutuallyExclusive,
      fieldMap2,
      fragmentName1
    );
  }
  for (const fragmentName1 of fragmentNames1) {
    for (const fragmentName2 of fragmentNames2) {
      collectConflictsBetweenFragments(
        context,
        conflicts,
        cachedFieldsAndFragmentNames,
        comparedFragmentPairs,
        areMutuallyExclusive,
        fragmentName1,
        fragmentName2
      );
    }
  }
  return conflicts;
}
function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) {
  for (const [responseName, fields] of Object.entries(fieldMap)) {
    if (fields.length > 1) {
      for (let i = 0; i < fields.length; i++) {
        for (let j = i + 1; j < fields.length; j++) {
          const conflict = findConflict(
            context,
            cachedFieldsAndFragmentNames,
            comparedFragmentPairs,
            false,
            // within one collection is never mutually exclusive
            responseName,
            fields[i],
            fields[j]
          );
          if (conflict) {
            conflicts.push(conflict);
          }
        }
      }
    }
  }
}
function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) {
  for (const [responseName, fields1] of Object.entries(fieldMap1)) {
    const fields2 = fieldMap2[responseName];
    if (fields2) {
      for (const field1 of fields1) {
        for (const field2 of fields2) {
          const conflict = findConflict(
            context,
            cachedFieldsAndFragmentNames,
            comparedFragmentPairs,
            parentFieldsAreMutuallyExclusive,
            responseName,
            field1,
            field2
          );
          if (conflict) {
            conflicts.push(conflict);
          }
        }
      }
    }
  }
}
function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) {
  const [parentType1, node1, def1] = field1;
  const [parentType2, node2, def2] = field2;
  const areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2);
  if (!areMutuallyExclusive) {
    const name1 = node1.name.value;
    const name2 = node2.name.value;
    if (name1 !== name2) {
      return [
        [responseName, `"${name1}" and "${name2}" are different fields`],
        [node1],
        [node2]
      ];
    }
    if (!sameArguments(node1, node2)) {
      return [
        [responseName, "they have differing arguments"],
        [node1],
        [node2]
      ];
    }
  }
  const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type;
  const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type;
  if (type1 && type2 && doTypesConflict(type1, type2)) {
    return [
      [
        responseName,
        `they return conflicting types "${inspect$2(type1)}" and "${inspect$2(
          type2
        )}"`
      ],
      [node1],
      [node2]
    ];
  }
  const selectionSet1 = node1.selectionSet;
  const selectionSet2 = node2.selectionSet;
  if (selectionSet1 && selectionSet2) {
    const conflicts = findConflictsBetweenSubSelectionSets(
      context,
      cachedFieldsAndFragmentNames,
      comparedFragmentPairs,
      areMutuallyExclusive,
      getNamedType(type1),
      selectionSet1,
      getNamedType(type2),
      selectionSet2
    );
    return subfieldConflicts(conflicts, responseName, node1, node2);
  }
}
function sameArguments(node1, node2) {
  const args1 = node1.arguments;
  const args2 = node2.arguments;
  if (args1 === void 0 || args1.length === 0) {
    return args2 === void 0 || args2.length === 0;
  }
  if (args2 === void 0 || args2.length === 0) {
    return false;
  }
  if (args1.length !== args2.length) {
    return false;
  }
  const values2 = new Map(args2.map(({ name: name2, value }) => [name2.value, value]));
  return args1.every((arg1) => {
    const value1 = arg1.value;
    const value2 = values2.get(arg1.name.value);
    if (value2 === void 0) {
      return false;
    }
    return stringifyValue(value1) === stringifyValue(value2);
  });
}
function stringifyValue(value) {
  return print(sortValueNode(value));
}
function doTypesConflict(type1, type2) {
  if (isListType(type1)) {
    return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
  }
  if (isListType(type2)) {
    return true;
  }
  if (isNonNullType(type1)) {
    return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true;
  }
  if (isNonNullType(type2)) {
    return true;
  }
  if (isLeafType(type1) || isLeafType(type2)) {
    return type1 !== type2;
  }
  return false;
}
function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) {
  const cached = cachedFieldsAndFragmentNames.get(selectionSet);
  if (cached) {
    return cached;
  }
  const nodeAndDefs = /* @__PURE__ */ Object.create(null);
  const fragmentNames = /* @__PURE__ */ Object.create(null);
  _collectFieldsAndFragmentNames(
    context,
    parentType,
    selectionSet,
    nodeAndDefs,
    fragmentNames
  );
  const result = [nodeAndDefs, Object.keys(fragmentNames)];
  cachedFieldsAndFragmentNames.set(selectionSet, result);
  return result;
}
function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) {
  const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);
  if (cached) {
    return cached;
  }
  const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);
  return getFieldsAndFragmentNames(
    context,
    cachedFieldsAndFragmentNames,
    fragmentType,
    fragment.selectionSet
  );
}
function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) {
  for (const selection of selectionSet.selections) {
    switch (selection.kind) {
      case Kind.FIELD: {
        const fieldName = selection.name.value;
        let fieldDef;
        if (isObjectType(parentType) || isInterfaceType(parentType)) {
          fieldDef = parentType.getFields()[fieldName];
        }
        const responseName = selection.alias ? selection.alias.value : fieldName;
        if (!nodeAndDefs[responseName]) {
          nodeAndDefs[responseName] = [];
        }
        nodeAndDefs[responseName].push([parentType, selection, fieldDef]);
        break;
      }
      case Kind.FRAGMENT_SPREAD:
        fragmentNames[selection.name.value] = true;
        break;
      case Kind.INLINE_FRAGMENT: {
        const typeCondition = selection.typeCondition;
        const inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType;
        _collectFieldsAndFragmentNames(
          context,
          inlineFragmentType,
          selection.selectionSet,
          nodeAndDefs,
          fragmentNames
        );
        break;
      }
    }
  }
}
function subfieldConflicts(conflicts, responseName, node1, node2) {
  if (conflicts.length > 0) {
    return [
      [responseName, conflicts.map(([reason]) => reason)],
      [node1, ...conflicts.map(([, fields1]) => fields1).flat()],
      [node2, ...conflicts.map(([, , fields2]) => fields2).flat()]
    ];
  }
}
class PairSet {
  constructor() {
    this._data = /* @__PURE__ */ new Map();
  }
  has(a, b, areMutuallyExclusive) {
    var _this$_data$get;
    const [key1, key2] = a < b ? [a, b] : [b, a];
    const result = (_this$_data$get = this._data.get(key1)) === null || _this$_data$get === void 0 ? void 0 : _this$_data$get.get(key2);
    if (result === void 0) {
      return false;
    }
    return areMutuallyExclusive ? true : areMutuallyExclusive === result;
  }
  add(a, b, areMutuallyExclusive) {
    const [key1, key2] = a < b ? [a, b] : [b, a];
    const map = this._data.get(key1);
    if (map === void 0) {
      this._data.set(key1, /* @__PURE__ */ new Map([[key2, areMutuallyExclusive]]));
    } else {
      map.set(key2, areMutuallyExclusive);
    }
  }
}
function PossibleFragmentSpreadsRule(context) {
  return {
    InlineFragment(node) {
      const fragType = context.getType();
      const parentType = context.getParentType();
      if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) {
        const parentTypeStr = inspect$2(parentType);
        const fragTypeStr = inspect$2(fragType);
        context.reportError(
          new GraphQLError(
            `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`,
            {
              nodes: node
            }
          )
        );
      }
    },
    FragmentSpread(node) {
      const fragName = node.name.value;
      const fragType = getFragmentType(context, fragName);
      const parentType = context.getParentType();
      if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) {
        const parentTypeStr = inspect$2(parentType);
        const fragTypeStr = inspect$2(fragType);
        context.reportError(
          new GraphQLError(
            `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`,
            {
              nodes: node
            }
          )
        );
      }
    }
  };
}
function getFragmentType(context, name2) {
  const frag = context.getFragment(name2);
  if (frag) {
    const type2 = typeFromAST(context.getSchema(), frag.typeCondition);
    if (isCompositeType(type2)) {
      return type2;
    }
  }
}
function PossibleTypeExtensionsRule(context) {
  const schema = context.getSchema();
  const definedTypes = /* @__PURE__ */ Object.create(null);
  for (const def2 of context.getDocument().definitions) {
    if (isTypeDefinitionNode(def2)) {
      definedTypes[def2.name.value] = def2;
    }
  }
  return {
    ScalarTypeExtension: checkExtension,
    ObjectTypeExtension: checkExtension,
    InterfaceTypeExtension: checkExtension,
    UnionTypeExtension: checkExtension,
    EnumTypeExtension: checkExtension,
    InputObjectTypeExtension: checkExtension
  };
  function checkExtension(node) {
    const typeName = node.name.value;
    const defNode = definedTypes[typeName];
    const existingType = schema === null || schema === void 0 ? void 0 : schema.getType(typeName);
    let expectedKind;
    if (defNode) {
      expectedKind = defKindToExtKind[defNode.kind];
    } else if (existingType) {
      expectedKind = typeToExtKind(existingType);
    }
    if (expectedKind) {
      if (expectedKind !== node.kind) {
        const kindStr = extensionKindToTypeName(node.kind);
        context.reportError(
          new GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, {
            nodes: defNode ? [defNode, node] : node
          })
        );
      }
    } else {
      const allTypeNames = Object.keys({
        ...definedTypes,
        ...schema === null || schema === void 0 ? void 0 : schema.getTypeMap()
      });
      const suggestedTypes = suggestionList(typeName, allTypeNames);
      context.reportError(
        new GraphQLError(
          `Cannot extend type "${typeName}" because it is not defined.` + didYouMean(suggestedTypes),
          {
            nodes: node.name
          }
        )
      );
    }
  }
}
const defKindToExtKind = {
  [Kind.SCALAR_TYPE_DEFINITION]: Kind.SCALAR_TYPE_EXTENSION,
  [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,
  [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,
  [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,
  [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,
  [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION
};
function typeToExtKind(type2) {
  if (isScalarType(type2)) {
    return Kind.SCALAR_TYPE_EXTENSION;
  }
  if (isObjectType(type2)) {
    return Kind.OBJECT_TYPE_EXTENSION;
  }
  if (isInterfaceType(type2)) {
    return Kind.INTERFACE_TYPE_EXTENSION;
  }
  if (isUnionType(type2)) {
    return Kind.UNION_TYPE_EXTENSION;
  }
  if (isEnumType(type2)) {
    return Kind.ENUM_TYPE_EXTENSION;
  }
  if (isInputObjectType(type2)) {
    return Kind.INPUT_OBJECT_TYPE_EXTENSION;
  }
  invariant(false, "Unexpected type: " + inspect$2(type2));
}
function extensionKindToTypeName(kind) {
  switch (kind) {
    case Kind.SCALAR_TYPE_EXTENSION:
      return "scalar";
    case Kind.OBJECT_TYPE_EXTENSION:
      return "object";
    case Kind.INTERFACE_TYPE_EXTENSION:
      return "interface";
    case Kind.UNION_TYPE_EXTENSION:
      return "union";
    case Kind.ENUM_TYPE_EXTENSION:
      return "enum";
    case Kind.INPUT_OBJECT_TYPE_EXTENSION:
      return "input object";
    default:
      invariant(false, "Unexpected kind: " + inspect$2(kind));
  }
}
function ProvidedRequiredArgumentsRule(context) {
  return {
    // eslint-disable-next-line new-cap
    ...ProvidedRequiredArgumentsOnDirectivesRule(context),
    Field: {
      // Validate on leave to allow for deeper errors to appear first.
      leave(fieldNode) {
        var _fieldNode$arguments;
        const fieldDef = context.getFieldDef();
        if (!fieldDef) {
          return false;
        }
        const providedArgs = new Set(
          // FIXME: https://github.com/graphql/graphql-js/issues/2203
          /* c8 ignore next */
          (_fieldNode$arguments = fieldNode.arguments) === null || _fieldNode$arguments === void 0 ? void 0 : _fieldNode$arguments.map((arg) => arg.name.value)
        );
        for (const argDef of fieldDef.args) {
          if (!providedArgs.has(argDef.name) && isRequiredArgument(argDef)) {
            const argTypeStr = inspect$2(argDef.type);
            context.reportError(
              new GraphQLError(
                `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`,
                {
                  nodes: fieldNode
                }
              )
            );
          }
        }
      }
    }
  };
}
function ProvidedRequiredArgumentsOnDirectivesRule(context) {
  var _schema$getDirectives;
  const requiredArgsMap = /* @__PURE__ */ Object.create(null);
  const schema = context.getSchema();
  const definedDirectives = (_schema$getDirectives = schema === null || schema === void 0 ? void 0 : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 ? _schema$getDirectives : specifiedDirectives;
  for (const directive of definedDirectives) {
    requiredArgsMap[directive.name] = keyMap(
      directive.args.filter(isRequiredArgument),
      (arg) => arg.name
    );
  }
  const astDefinitions = context.getDocument().definitions;
  for (const def2 of astDefinitions) {
    if (def2.kind === Kind.DIRECTIVE_DEFINITION) {
      var _def$arguments;
      const argNodes = (_def$arguments = def2.arguments) !== null && _def$arguments !== void 0 ? _def$arguments : [];
      requiredArgsMap[def2.name.value] = keyMap(
        argNodes.filter(isRequiredArgumentNode),
        (arg) => arg.name.value
      );
    }
  }
  return {
    Directive: {
      // Validate on leave to allow for deeper errors to appear first.
      leave(directiveNode) {
        const directiveName = directiveNode.name.value;
        const requiredArgs = requiredArgsMap[directiveName];
        if (requiredArgs) {
          var _directiveNode$argume;
          const argNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : [];
          const argNodeMap = new Set(argNodes.map((arg) => arg.name.value));
          for (const [argName, argDef] of Object.entries(requiredArgs)) {
            if (!argNodeMap.has(argName)) {
              const argType = isType(argDef.type) ? inspect$2(argDef.type) : print(argDef.type);
              context.reportError(
                new GraphQLError(
                  `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`,
                  {
                    nodes: directiveNode
                  }
                )
              );
            }
          }
        }
      }
    }
  };
}
function isRequiredArgumentNode(arg) {
  return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null;
}
function ScalarLeafsRule(context) {
  return {
    Field(node) {
      const type2 = context.getType();
      const selectionSet = node.selectionSet;
      if (type2) {
        if (isLeafType(getNamedType(type2))) {
          if (selectionSet) {
            const fieldName = node.name.value;
            const typeStr = inspect$2(type2);
            context.reportError(
              new GraphQLError(
                `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`,
                {
                  nodes: selectionSet
                }
              )
            );
          }
        } else if (!selectionSet) {
          const fieldName = node.name.value;
          const typeStr = inspect$2(type2);
          context.reportError(
            new GraphQLError(
              `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`,
              {
                nodes: node
              }
            )
          );
        }
      }
    }
  };
}
function printPathArray(path) {
  return path.map(
    (key) => typeof key === "number" ? "[" + key.toString() + "]" : "." + key
  ).join("");
}
function addPath(prev, key, typename) {
  return {
    prev,
    key,
    typename
  };
}
function pathToArray(path) {
  const flattened = [];
  let curr = path;
  while (curr) {
    flattened.push(curr.key);
    curr = curr.prev;
  }
  return flattened.reverse();
}
function coerceInputValue(inputValue, type2, onError = defaultOnError) {
  return coerceInputValueImpl(inputValue, type2, onError, void 0);
}
function defaultOnError(path, invalidValue, error2) {
  let errorPrefix = "Invalid value " + inspect$2(invalidValue);
  if (path.length > 0) {
    errorPrefix += ` at "value${printPathArray(path)}"`;
  }
  error2.message = errorPrefix + ": " + error2.message;
  throw error2;
}
function coerceInputValueImpl(inputValue, type2, onError, path) {
  if (isNonNullType(type2)) {
    if (inputValue != null) {
      return coerceInputValueImpl(inputValue, type2.ofType, onError, path);
    }
    onError(
      pathToArray(path),
      inputValue,
      new GraphQLError(
        `Expected non-nullable type "${inspect$2(type2)}" not to be null.`
      )
    );
    return;
  }
  if (inputValue == null) {
    return null;
  }
  if (isListType(type2)) {
    const itemType = type2.ofType;
    if (isIterableObject(inputValue)) {
      return Array.from(inputValue, (itemValue, index) => {
        const itemPath = addPath(path, index, void 0);
        return coerceInputValueImpl(itemValue, itemType, onError, itemPath);
      });
    }
    return [coerceInputValueImpl(inputValue, itemType, onError, path)];
  }
  if (isInputObjectType(type2)) {
    if (!isObjectLike(inputValue)) {
      onError(
        pathToArray(path),
        inputValue,
        new GraphQLError(`Expected type "${type2.name}" to be an object.`)
      );
      return;
    }
    const coercedValue = {};
    const fieldDefs = type2.getFields();
    for (const field of Object.values(fieldDefs)) {
      const fieldValue = inputValue[field.name];
      if (fieldValue === void 0) {
        if (field.defaultValue !== void 0) {
          coercedValue[field.name] = field.defaultValue;
        } else if (isNonNullType(field.type)) {
          const typeStr = inspect$2(field.type);
          onError(
            pathToArray(path),
            inputValue,
            new GraphQLError(
              `Field "${field.name}" of required type "${typeStr}" was not provided.`
            )
          );
        }
        continue;
      }
      coercedValue[field.name] = coerceInputValueImpl(
        fieldValue,
        field.type,
        onError,
        addPath(path, field.name, type2.name)
      );
    }
    for (const fieldName of Object.keys(inputValue)) {
      if (!fieldDefs[fieldName]) {
        const suggestions = suggestionList(
          fieldName,
          Object.keys(type2.getFields())
        );
        onError(
          pathToArray(path),
          inputValue,
          new GraphQLError(
            `Field "${fieldName}" is not defined by type "${type2.name}".` + didYouMean(suggestions)
          )
        );
      }
    }
    return coercedValue;
  }
  if (isLeafType(type2)) {
    let parseResult;
    try {
      parseResult = type2.parseValue(inputValue);
    } catch (error2) {
      if (error2 instanceof GraphQLError) {
        onError(pathToArray(path), inputValue, error2);
      } else {
        onError(
          pathToArray(path),
          inputValue,
          new GraphQLError(`Expected type "${type2.name}". ` + error2.message, {
            originalError: error2
          })
        );
      }
      return;
    }
    if (parseResult === void 0) {
      onError(
        pathToArray(path),
        inputValue,
        new GraphQLError(`Expected type "${type2.name}".`)
      );
    }
    return parseResult;
  }
  invariant(false, "Unexpected input type: " + inspect$2(type2));
}
function valueFromAST(valueNode, type2, variables) {
  if (!valueNode) {
    return;
  }
  if (valueNode.kind === Kind.VARIABLE) {
    const variableName = valueNode.name.value;
    if (variables == null || variables[variableName] === void 0) {
      return;
    }
    const variableValue = variables[variableName];
    if (variableValue === null && isNonNullType(type2)) {
      return;
    }
    return variableValue;
  }
  if (isNonNullType(type2)) {
    if (valueNode.kind === Kind.NULL) {
      return;
    }
    return valueFromAST(valueNode, type2.ofType, variables);
  }
  if (valueNode.kind === Kind.NULL) {
    return null;
  }
  if (isListType(type2)) {
    const itemType = type2.ofType;
    if (valueNode.kind === Kind.LIST) {
      const coercedValues = [];
      for (const itemNode of valueNode.values) {
        if (isMissingVariable(itemNode, variables)) {
          if (isNonNullType(itemType)) {
            return;
          }
          coercedValues.push(null);
        } else {
          const itemValue = valueFromAST(itemNode, itemType, variables);
          if (itemValue === void 0) {
            return;
          }
          coercedValues.push(itemValue);
        }
      }
      return coercedValues;
    }
    const coercedValue = valueFromAST(valueNode, itemType, variables);
    if (coercedValue === void 0) {
      return;
    }
    return [coercedValue];
  }
  if (isInputObjectType(type2)) {
    if (valueNode.kind !== Kind.OBJECT) {
      return;
    }
    const coercedObj = /* @__PURE__ */ Object.create(null);
    const fieldNodes = keyMap(valueNode.fields, (field) => field.name.value);
    for (const field of Object.values(type2.getFields())) {
      const fieldNode = fieldNodes[field.name];
      if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {
        if (field.defaultValue !== void 0) {
          coercedObj[field.name] = field.defaultValue;
        } else if (isNonNullType(field.type)) {
          return;
        }
        continue;
      }
      const fieldValue = valueFromAST(fieldNode.value, field.type, variables);
      if (fieldValue === void 0) {
        return;
      }
      coercedObj[field.name] = fieldValue;
    }
    return coercedObj;
  }
  if (isLeafType(type2)) {
    let result;
    try {
      result = type2.parseLiteral(valueNode, variables);
    } catch (_error) {
      return;
    }
    if (result === void 0) {
      return;
    }
    return result;
  }
  invariant(false, "Unexpected input type: " + inspect$2(type2));
}
function isMissingVariable(valueNode, variables) {
  return valueNode.kind === Kind.VARIABLE && (variables == null || variables[valueNode.name.value] === void 0);
}
function getVariableValues(schema, varDefNodes, inputs, options2) {
  const errors2 = [];
  const maxErrors = options2 === null || options2 === void 0 ? void 0 : options2.maxErrors;
  try {
    const coerced = coerceVariableValues(
      schema,
      varDefNodes,
      inputs,
      (error2) => {
        if (maxErrors != null && errors2.length >= maxErrors) {
          throw new GraphQLError(
            "Too many errors processing variables, error limit reached. Execution aborted."
          );
        }
        errors2.push(error2);
      }
    );
    if (errors2.length === 0) {
      return {
        coerced
      };
    }
  } catch (error2) {
    errors2.push(error2);
  }
  return {
    errors: errors2
  };
}
function coerceVariableValues(schema, varDefNodes, inputs, onError) {
  const coercedValues = {};
  for (const varDefNode of varDefNodes) {
    const varName = varDefNode.variable.name.value;
    const varType = typeFromAST(schema, varDefNode.type);
    if (!isInputType(varType)) {
      const varTypeStr = print(varDefNode.type);
      onError(
        new GraphQLError(
          `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`,
          {
            nodes: varDefNode.type
          }
        )
      );
      continue;
    }
    if (!hasOwnProperty(inputs, varName)) {
      if (varDefNode.defaultValue) {
        coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);
      } else if (isNonNullType(varType)) {
        const varTypeStr = inspect$2(varType);
        onError(
          new GraphQLError(
            `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`,
            {
              nodes: varDefNode
            }
          )
        );
      }
      continue;
    }
    const value = inputs[varName];
    if (value === null && isNonNullType(varType)) {
      const varTypeStr = inspect$2(varType);
      onError(
        new GraphQLError(
          `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`,
          {
            nodes: varDefNode
          }
        )
      );
      continue;
    }
    coercedValues[varName] = coerceInputValue(
      value,
      varType,
      (path, invalidValue, error2) => {
        let prefix = `Variable "$${varName}" got invalid value ` + inspect$2(invalidValue);
        if (path.length > 0) {
          prefix += ` at "${varName}${printPathArray(path)}"`;
        }
        onError(
          new GraphQLError(prefix + "; " + error2.message, {
            nodes: varDefNode,
            originalError: error2
          })
        );
      }
    );
  }
  return coercedValues;
}
function getArgumentValues(def2, node, variableValues) {
  var _node$arguments;
  const coercedValues = {};
  const argumentNodes = (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 ? _node$arguments : [];
  const argNodeMap = keyMap(argumentNodes, (arg) => arg.name.value);
  for (const argDef of def2.args) {
    const name2 = argDef.name;
    const argType = argDef.type;
    const argumentNode = argNodeMap[name2];
    if (!argumentNode) {
      if (argDef.defaultValue !== void 0) {
        coercedValues[name2] = argDef.defaultValue;
      } else if (isNonNullType(argType)) {
        throw new GraphQLError(
          `Argument "${name2}" of required type "${inspect$2(argType)}" was not provided.`,
          {
            nodes: node
          }
        );
      }
      continue;
    }
    const valueNode = argumentNode.value;
    let isNull = valueNode.kind === Kind.NULL;
    if (valueNode.kind === Kind.VARIABLE) {
      const variableName = valueNode.name.value;
      if (variableValues == null || !hasOwnProperty(variableValues, variableName)) {
        if (argDef.defaultValue !== void 0) {
          coercedValues[name2] = argDef.defaultValue;
        } else if (isNonNullType(argType)) {
          throw new GraphQLError(
            `Argument "${name2}" of required type "${inspect$2(argType)}" was provided the variable "$${variableName}" which was not provided a runtime value.`,
            {
              nodes: valueNode
            }
          );
        }
        continue;
      }
      isNull = variableValues[variableName] == null;
    }
    if (isNull && isNonNullType(argType)) {
      throw new GraphQLError(
        `Argument "${name2}" of non-null type "${inspect$2(argType)}" must not be null.`,
        {
          nodes: valueNode
        }
      );
    }
    const coercedValue = valueFromAST(valueNode, argType, variableValues);
    if (coercedValue === void 0) {
      throw new GraphQLError(
        `Argument "${name2}" has invalid value ${print(valueNode)}.`,
        {
          nodes: valueNode
        }
      );
    }
    coercedValues[name2] = coercedValue;
  }
  return coercedValues;
}
function getDirectiveValues(directiveDef, node, variableValues) {
  var _node$directives;
  const directiveNode = (_node$directives = node.directives) === null || _node$directives === void 0 ? void 0 : _node$directives.find(
    (directive) => directive.name.value === directiveDef.name
  );
  if (directiveNode) {
    return getArgumentValues(directiveDef, directiveNode, variableValues);
  }
}
function hasOwnProperty(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
function collectFields(schema, fragments, variableValues, runtimeType, selectionSet) {
  const fields = /* @__PURE__ */ new Map();
  collectFieldsImpl(
    schema,
    fragments,
    variableValues,
    runtimeType,
    selectionSet,
    fields,
    /* @__PURE__ */ new Set()
  );
  return fields;
}
function collectSubfields$1(schema, fragments, variableValues, returnType, fieldNodes) {
  const subFieldNodes = /* @__PURE__ */ new Map();
  const visitedFragmentNames = /* @__PURE__ */ new Set();
  for (const node of fieldNodes) {
    if (node.selectionSet) {
      collectFieldsImpl(
        schema,
        fragments,
        variableValues,
        returnType,
        node.selectionSet,
        subFieldNodes,
        visitedFragmentNames
      );
    }
  }
  return subFieldNodes;
}
function collectFieldsImpl(schema, fragments, variableValues, runtimeType, selectionSet, fields, visitedFragmentNames) {
  for (const selection of selectionSet.selections) {
    switch (selection.kind) {
      case Kind.FIELD: {
        if (!shouldIncludeNode(variableValues, selection)) {
          continue;
        }
        const name2 = getFieldEntryKey(selection);
        const fieldList = fields.get(name2);
        if (fieldList !== void 0) {
          fieldList.push(selection);
        } else {
          fields.set(name2, [selection]);
        }
        break;
      }
      case Kind.INLINE_FRAGMENT: {
        if (!shouldIncludeNode(variableValues, selection) || !doesFragmentConditionMatch(schema, selection, runtimeType)) {
          continue;
        }
        collectFieldsImpl(
          schema,
          fragments,
          variableValues,
          runtimeType,
          selection.selectionSet,
          fields,
          visitedFragmentNames
        );
        break;
      }
      case Kind.FRAGMENT_SPREAD: {
        const fragName = selection.name.value;
        if (visitedFragmentNames.has(fragName) || !shouldIncludeNode(variableValues, selection)) {
          continue;
        }
        visitedFragmentNames.add(fragName);
        const fragment = fragments[fragName];
        if (!fragment || !doesFragmentConditionMatch(schema, fragment, runtimeType)) {
          continue;
        }
        collectFieldsImpl(
          schema,
          fragments,
          variableValues,
          runtimeType,
          fragment.selectionSet,
          fields,
          visitedFragmentNames
        );
        break;
      }
    }
  }
}
function shouldIncludeNode(variableValues, node) {
  const skip = getDirectiveValues(GraphQLSkipDirective, node, variableValues);
  if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {
    return false;
  }
  const include = getDirectiveValues(
    GraphQLIncludeDirective,
    node,
    variableValues
  );
  if ((include === null || include === void 0 ? void 0 : include.if) === false) {
    return false;
  }
  return true;
}
function doesFragmentConditionMatch(schema, fragment, type2) {
  const typeConditionNode = fragment.typeCondition;
  if (!typeConditionNode) {
    return true;
  }
  const conditionalType = typeFromAST(schema, typeConditionNode);
  if (conditionalType === type2) {
    return true;
  }
  if (isAbstractType(conditionalType)) {
    return schema.isSubType(conditionalType, type2);
  }
  return false;
}
function getFieldEntryKey(node) {
  return node.alias ? node.alias.value : node.name.value;
}
function SingleFieldSubscriptionsRule(context) {
  return {
    OperationDefinition(node) {
      if (node.operation === "subscription") {
        const schema = context.getSchema();
        const subscriptionType = schema.getSubscriptionType();
        if (subscriptionType) {
          const operationName = node.name ? node.name.value : null;
          const variableValues = /* @__PURE__ */ Object.create(null);
          const document = context.getDocument();
          const fragments = /* @__PURE__ */ Object.create(null);
          for (const definition of document.definitions) {
            if (definition.kind === Kind.FRAGMENT_DEFINITION) {
              fragments[definition.name.value] = definition;
            }
          }
          const fields = collectFields(
            schema,
            fragments,
            variableValues,
            subscriptionType,
            node.selectionSet
          );
          if (fields.size > 1) {
            const fieldSelectionLists = [...fields.values()];
            const extraFieldSelectionLists = fieldSelectionLists.slice(1);
            const extraFieldSelections = extraFieldSelectionLists.flat();
            context.reportError(
              new GraphQLError(
                operationName != null ? `Subscription "${operationName}" must select only one top level field.` : "Anonymous Subscription must select only one top level field.",
                {
                  nodes: extraFieldSelections
                }
              )
            );
          }
          for (const fieldNodes of fields.values()) {
            const field = fieldNodes[0];
            const fieldName = field.name.value;
            if (fieldName.startsWith("__")) {
              context.reportError(
                new GraphQLError(
                  operationName != null ? `Subscription "${operationName}" must not select an introspection top level field.` : "Anonymous Subscription must not select an introspection top level field.",
                  {
                    nodes: fieldNodes
                  }
                )
              );
            }
          }
        }
      }
    }
  };
}
function groupBy(list, keyFn) {
  const result = /* @__PURE__ */ new Map();
  for (const item of list) {
    const key = keyFn(item);
    const group = result.get(key);
    if (group === void 0) {
      result.set(key, [item]);
    } else {
      group.push(item);
    }
  }
  return result;
}
function UniqueArgumentDefinitionNamesRule(context) {
  return {
    DirectiveDefinition(directiveNode) {
      var _directiveNode$argume;
      const argumentNodes = (_directiveNode$argume = directiveNode.arguments) !== null && _directiveNode$argume !== void 0 ? _directiveNode$argume : [];
      return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes);
    },
    InterfaceTypeDefinition: checkArgUniquenessPerField,
    InterfaceTypeExtension: checkArgUniquenessPerField,
    ObjectTypeDefinition: checkArgUniquenessPerField,
    ObjectTypeExtension: checkArgUniquenessPerField
  };
  function checkArgUniquenessPerField(typeNode) {
    var _typeNode$fields;
    const typeName = typeNode.name.value;
    const fieldNodes = (_typeNode$fields = typeNode.fields) !== null && _typeNode$fields !== void 0 ? _typeNode$fields : [];
    for (const fieldDef of fieldNodes) {
      var _fieldDef$arguments;
      const fieldName = fieldDef.name.value;
      const argumentNodes = (_fieldDef$arguments = fieldDef.arguments) !== null && _fieldDef$arguments !== void 0 ? _fieldDef$arguments : [];
      checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes);
    }
    return false;
  }
  function checkArgUniqueness(parentName, argumentNodes) {
    const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value);
    for (const [argName, argNodes] of seenArgs) {
      if (argNodes.length > 1) {
        context.reportError(
          new GraphQLError(
            `Argument "${parentName}(${argName}:)" can only be defined once.`,
            {
              nodes: argNodes.map((node) => node.name)
            }
          )
        );
      }
    }
    return false;
  }
}
function UniqueArgumentNamesRule(context) {
  return {
    Field: checkArgUniqueness,
    Directive: checkArgUniqueness
  };
  function checkArgUniqueness(parentNode) {
    var _parentNode$arguments;
    const argumentNodes = (_parentNode$arguments = parentNode.arguments) !== null && _parentNode$arguments !== void 0 ? _parentNode$arguments : [];
    const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value);
    for (const [argName, argNodes] of seenArgs) {
      if (argNodes.length > 1) {
        context.reportError(
          new GraphQLError(
            `There can be only one argument named "${argName}".`,
            {
              nodes: argNodes.map((node) => node.name)
            }
          )
        );
      }
    }
  }
}
function UniqueDirectiveNamesRule(context) {
  const knownDirectiveNames = /* @__PURE__ */ Object.create(null);
  const schema = context.getSchema();
  return {
    DirectiveDefinition(node) {
      const directiveName = node.name.value;
      if (schema !== null && schema !== void 0 && schema.getDirective(directiveName)) {
        context.reportError(
          new GraphQLError(
            `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`,
            {
              nodes: node.name
            }
          )
        );
        return;
      }
      if (knownDirectiveNames[directiveName]) {
        context.reportError(
          new GraphQLError(
            `There can be only one directive named "@${directiveName}".`,
            {
              nodes: [knownDirectiveNames[directiveName], node.name]
            }
          )
        );
      } else {
        knownDirectiveNames[directiveName] = node.name;
      }
      return false;
    }
  };
}
function UniqueDirectivesPerLocationRule(context) {
  const uniqueDirectiveMap = /* @__PURE__ */ Object.create(null);
  const schema = context.getSchema();
  const definedDirectives = schema ? schema.getDirectives() : specifiedDirectives;
  for (const directive of definedDirectives) {
    uniqueDirectiveMap[directive.name] = !directive.isRepeatable;
  }
  const astDefinitions = context.getDocument().definitions;
  for (const def2 of astDefinitions) {
    if (def2.kind === Kind.DIRECTIVE_DEFINITION) {
      uniqueDirectiveMap[def2.name.value] = !def2.repeatable;
    }
  }
  const schemaDirectives = /* @__PURE__ */ Object.create(null);
  const typeDirectivesMap = /* @__PURE__ */ Object.create(null);
  return {
    // Many different AST nodes may contain directives. Rather than listing
    // them all, just listen for entering any node, and check to see if it
    // defines any directives.
    enter(node) {
      if (!("directives" in node) || !node.directives) {
        return;
      }
      let seenDirectives;
      if (node.kind === Kind.SCHEMA_DEFINITION || node.kind === Kind.SCHEMA_EXTENSION) {
        seenDirectives = schemaDirectives;
      } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) {
        const typeName = node.name.value;
        seenDirectives = typeDirectivesMap[typeName];
        if (seenDirectives === void 0) {
          typeDirectivesMap[typeName] = seenDirectives = /* @__PURE__ */ Object.create(null);
        }
      } else {
        seenDirectives = /* @__PURE__ */ Object.create(null);
      }
      for (const directive of node.directives) {
        const directiveName = directive.name.value;
        if (uniqueDirectiveMap[directiveName]) {
          if (seenDirectives[directiveName]) {
            context.reportError(
              new GraphQLError(
                `The directive "@${directiveName}" can only be used once at this location.`,
                {
                  nodes: [seenDirectives[directiveName], directive]
                }
              )
            );
          } else {
            seenDirectives[directiveName] = directive;
          }
        }
      }
    }
  };
}
function UniqueEnumValueNamesRule(context) {
  const schema = context.getSchema();
  const existingTypeMap = schema ? schema.getTypeMap() : /* @__PURE__ */ Object.create(null);
  const knownValueNames = /* @__PURE__ */ Object.create(null);
  return {
    EnumTypeDefinition: checkValueUniqueness,
    EnumTypeExtension: checkValueUniqueness
  };
  function checkValueUniqueness(node) {
    var _node$values;
    const typeName = node.name.value;
    if (!knownValueNames[typeName]) {
      knownValueNames[typeName] = /* @__PURE__ */ Object.create(null);
    }
    const valueNodes = (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : [];
    const valueNames = knownValueNames[typeName];
    for (const valueDef of valueNodes) {
      const valueName = valueDef.name.value;
      const existingType = existingTypeMap[typeName];
      if (isEnumType(existingType) && existingType.getValue(valueName)) {
        context.reportError(
          new GraphQLError(
            `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`,
            {
              nodes: valueDef.name
            }
          )
        );
      } else if (valueNames[valueName]) {
        context.reportError(
          new GraphQLError(
            `Enum value "${typeName}.${valueName}" can only be defined once.`,
            {
              nodes: [valueNames[valueName], valueDef.name]
            }
          )
        );
      } else {
        valueNames[valueName] = valueDef.name;
      }
    }
    return false;
  }
}
function UniqueFieldDefinitionNamesRule(context) {
  const schema = context.getSchema();
  const existingTypeMap = schema ? schema.getTypeMap() : /* @__PURE__ */ Object.create(null);
  const knownFieldNames = /* @__PURE__ */ Object.create(null);
  return {
    InputObjectTypeDefinition: checkFieldUniqueness,
    InputObjectTypeExtension: checkFieldUniqueness,
    InterfaceTypeDefinition: checkFieldUniqueness,
    InterfaceTypeExtension: checkFieldUniqueness,
    ObjectTypeDefinition: checkFieldUniqueness,
    ObjectTypeExtension: checkFieldUniqueness
  };
  function checkFieldUniqueness(node) {
    var _node$fields;
    const typeName = node.name.value;
    if (!knownFieldNames[typeName]) {
      knownFieldNames[typeName] = /* @__PURE__ */ Object.create(null);
    }
    const fieldNodes = (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : [];
    const fieldNames = knownFieldNames[typeName];
    for (const fieldDef of fieldNodes) {
      const fieldName = fieldDef.name.value;
      if (hasField(existingTypeMap[typeName], fieldName)) {
        context.reportError(
          new GraphQLError(
            `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`,
            {
              nodes: fieldDef.name
            }
          )
        );
      } else if (fieldNames[fieldName]) {
        context.reportError(
          new GraphQLError(
            `Field "${typeName}.${fieldName}" can only be defined once.`,
            {
              nodes: [fieldNames[fieldName], fieldDef.name]
            }
          )
        );
      } else {
        fieldNames[fieldName] = fieldDef.name;
      }
    }
    return false;
  }
}
function hasField(type2, fieldName) {
  if (isObjectType(type2) || isInterfaceType(type2) || isInputObjectType(type2)) {
    return type2.getFields()[fieldName] != null;
  }
  return false;
}
function UniqueFragmentNamesRule(context) {
  const knownFragmentNames = /* @__PURE__ */ Object.create(null);
  return {
    OperationDefinition: () => false,
    FragmentDefinition(node) {
      const fragmentName = node.name.value;
      if (knownFragmentNames[fragmentName]) {
        context.reportError(
          new GraphQLError(
            `There can be only one fragment named "${fragmentName}".`,
            {
              nodes: [knownFragmentNames[fragmentName], node.name]
            }
          )
        );
      } else {
        knownFragmentNames[fragmentName] = node.name;
      }
      return false;
    }
  };
}
function UniqueInputFieldNamesRule(context) {
  const knownNameStack = [];
  let knownNames = /* @__PURE__ */ Object.create(null);
  return {
    ObjectValue: {
      enter() {
        knownNameStack.push(knownNames);
        knownNames = /* @__PURE__ */ Object.create(null);
      },
      leave() {
        const prevKnownNames = knownNameStack.pop();
        prevKnownNames || invariant(false);
        knownNames = prevKnownNames;
      }
    },
    ObjectField(node) {
      const fieldName = node.name.value;
      if (knownNames[fieldName]) {
        context.reportError(
          new GraphQLError(
            `There can be only one input field named "${fieldName}".`,
            {
              nodes: [knownNames[fieldName], node.name]
            }
          )
        );
      } else {
        knownNames[fieldName] = node.name;
      }
    }
  };
}
function UniqueOperationNamesRule(context) {
  const knownOperationNames = /* @__PURE__ */ Object.create(null);
  return {
    OperationDefinition(node) {
      const operationName = node.name;
      if (operationName) {
        if (knownOperationNames[operationName.value]) {
          context.reportError(
            new GraphQLError(
              `There can be only one operation named "${operationName.value}".`,
              {
                nodes: [
                  knownOperationNames[operationName.value],
                  operationName
                ]
              }
            )
          );
        } else {
          knownOperationNames[operationName.value] = operationName;
        }
      }
      return false;
    },
    FragmentDefinition: () => false
  };
}
function UniqueOperationTypesRule(context) {
  const schema = context.getSchema();
  const definedOperationTypes = /* @__PURE__ */ Object.create(null);
  const existingOperationTypes = schema ? {
    query: schema.getQueryType(),
    mutation: schema.getMutationType(),
    subscription: schema.getSubscriptionType()
  } : {};
  return {
    SchemaDefinition: checkOperationTypes,
    SchemaExtension: checkOperationTypes
  };
  function checkOperationTypes(node) {
    var _node$operationTypes;
    const operationTypesNodes = (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : [];
    for (const operationType of operationTypesNodes) {
      const operation = operationType.operation;
      const alreadyDefinedOperationType = definedOperationTypes[operation];
      if (existingOperationTypes[operation]) {
        context.reportError(
          new GraphQLError(
            `Type for ${operation} already defined in the schema. It cannot be redefined.`,
            {
              nodes: operationType
            }
          )
        );
      } else if (alreadyDefinedOperationType) {
        context.reportError(
          new GraphQLError(
            `There can be only one ${operation} type in schema.`,
            {
              nodes: [alreadyDefinedOperationType, operationType]
            }
          )
        );
      } else {
        definedOperationTypes[operation] = operationType;
      }
    }
    return false;
  }
}
function UniqueTypeNamesRule(context) {
  const knownTypeNames = /* @__PURE__ */ Object.create(null);
  const schema = context.getSchema();
  return {
    ScalarTypeDefinition: checkTypeName,
    ObjectTypeDefinition: checkTypeName,
    InterfaceTypeDefinition: checkTypeName,
    UnionTypeDefinition: checkTypeName,
    EnumTypeDefinition: checkTypeName,
    InputObjectTypeDefinition: checkTypeName
  };
  function checkTypeName(node) {
    const typeName = node.name.value;
    if (schema !== null && schema !== void 0 && schema.getType(typeName)) {
      context.reportError(
        new GraphQLError(
          `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`,
          {
            nodes: node.name
          }
        )
      );
      return;
    }
    if (knownTypeNames[typeName]) {
      context.reportError(
        new GraphQLError(`There can be only one type named "${typeName}".`, {
          nodes: [knownTypeNames[typeName], node.name]
        })
      );
    } else {
      knownTypeNames[typeName] = node.name;
    }
    return false;
  }
}
function UniqueVariableNamesRule(context) {
  return {
    OperationDefinition(operationNode) {
      var _operationNode$variab;
      const variableDefinitions = (_operationNode$variab = operationNode.variableDefinitions) !== null && _operationNode$variab !== void 0 ? _operationNode$variab : [];
      const seenVariableDefinitions = groupBy(
        variableDefinitions,
        (node) => node.variable.name.value
      );
      for (const [variableName, variableNodes] of seenVariableDefinitions) {
        if (variableNodes.length > 1) {
          context.reportError(
            new GraphQLError(
              `There can be only one variable named "$${variableName}".`,
              {
                nodes: variableNodes.map((node) => node.variable.name)
              }
            )
          );
        }
      }
    }
  };
}
function ValuesOfCorrectTypeRule(context) {
  return {
    ListValue(node) {
      const type2 = getNullableType(context.getParentInputType());
      if (!isListType(type2)) {
        isValidValueNode(context, node);
        return false;
      }
    },
    ObjectValue(node) {
      const type2 = getNamedType(context.getInputType());
      if (!isInputObjectType(type2)) {
        isValidValueNode(context, node);
        return false;
      }
      const fieldNodeMap = keyMap(node.fields, (field) => field.name.value);
      for (const fieldDef of Object.values(type2.getFields())) {
        const fieldNode = fieldNodeMap[fieldDef.name];
        if (!fieldNode && isRequiredInputField(fieldDef)) {
          const typeStr = inspect$2(fieldDef.type);
          context.reportError(
            new GraphQLError(
              `Field "${type2.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`,
              {
                nodes: node
              }
            )
          );
        }
      }
    },
    ObjectField(node) {
      const parentType = getNamedType(context.getParentInputType());
      const fieldType = context.getInputType();
      if (!fieldType && isInputObjectType(parentType)) {
        const suggestions = suggestionList(
          node.name.value,
          Object.keys(parentType.getFields())
        );
        context.reportError(
          new GraphQLError(
            `Field "${node.name.value}" is not defined by type "${parentType.name}".` + didYouMean(suggestions),
            {
              nodes: node
            }
          )
        );
      }
    },
    NullValue(node) {
      const type2 = context.getInputType();
      if (isNonNullType(type2)) {
        context.reportError(
          new GraphQLError(
            `Expected value of type "${inspect$2(type2)}", found ${print(node)}.`,
            {
              nodes: node
            }
          )
        );
      }
    },
    EnumValue: (node) => isValidValueNode(context, node),
    IntValue: (node) => isValidValueNode(context, node),
    FloatValue: (node) => isValidValueNode(context, node),
    StringValue: (node) => isValidValueNode(context, node),
    BooleanValue: (node) => isValidValueNode(context, node)
  };
}
function isValidValueNode(context, node) {
  const locationType = context.getInputType();
  if (!locationType) {
    return;
  }
  const type2 = getNamedType(locationType);
  if (!isLeafType(type2)) {
    const typeStr = inspect$2(locationType);
    context.reportError(
      new GraphQLError(
        `Expected value of type "${typeStr}", found ${print(node)}.`,
        {
          nodes: node
        }
      )
    );
    return;
  }
  try {
    const parseResult = type2.parseLiteral(
      node,
      void 0
      /* variables */
    );
    if (parseResult === void 0) {
      const typeStr = inspect$2(locationType);
      context.reportError(
        new GraphQLError(
          `Expected value of type "${typeStr}", found ${print(node)}.`,
          {
            nodes: node
          }
        )
      );
    }
  } catch (error2) {
    const typeStr = inspect$2(locationType);
    if (error2 instanceof GraphQLError) {
      context.reportError(error2);
    } else {
      context.reportError(
        new GraphQLError(
          `Expected value of type "${typeStr}", found ${print(node)}; ` + error2.message,
          {
            nodes: node,
            originalError: error2
          }
        )
      );
    }
  }
}
function VariablesAreInputTypesRule(context) {
  return {
    VariableDefinition(node) {
      const type2 = typeFromAST(context.getSchema(), node.type);
      if (type2 !== void 0 && !isInputType(type2)) {
        const variableName = node.variable.name.value;
        const typeName = print(node.type);
        context.reportError(
          new GraphQLError(
            `Variable "$${variableName}" cannot be non-input type "${typeName}".`,
            {
              nodes: node.type
            }
          )
        );
      }
    }
  };
}
function VariablesInAllowedPositionRule(context) {
  let varDefMap = /* @__PURE__ */ Object.create(null);
  return {
    OperationDefinition: {
      enter() {
        varDefMap = /* @__PURE__ */ Object.create(null);
      },
      leave(operation) {
        const usages = context.getRecursiveVariableUsages(operation);
        for (const { node, type: type2, defaultValue } of usages) {
          const varName = node.name.value;
          const varDef = varDefMap[varName];
          if (varDef && type2) {
            const schema = context.getSchema();
            const varType = typeFromAST(schema, varDef.type);
            if (varType && !allowedVariableUsage(
              schema,
              varType,
              varDef.defaultValue,
              type2,
              defaultValue
            )) {
              const varTypeStr = inspect$2(varType);
              const typeStr = inspect$2(type2);
              context.reportError(
                new GraphQLError(
                  `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`,
                  {
                    nodes: [varDef, node]
                  }
                )
              );
            }
          }
        }
      }
    },
    VariableDefinition(node) {
      varDefMap[node.variable.name.value] = node;
    }
  };
}
function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) {
  if (isNonNullType(locationType) && !isNonNullType(varType)) {
    const hasNonNullVariableDefaultValue = varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;
    const hasLocationDefaultValue = locationDefaultValue !== void 0;
    if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {
      return false;
    }
    const nullableLocationType = locationType.ofType;
    return isTypeSubTypeOf(schema, varType, nullableLocationType);
  }
  return isTypeSubTypeOf(schema, varType, locationType);
}
const specifiedRules = Object.freeze([
  ExecutableDefinitionsRule,
  UniqueOperationNamesRule,
  LoneAnonymousOperationRule,
  SingleFieldSubscriptionsRule,
  KnownTypeNamesRule,
  FragmentsOnCompositeTypesRule,
  VariablesAreInputTypesRule,
  ScalarLeafsRule,
  FieldsOnCorrectTypeRule,
  UniqueFragmentNamesRule,
  KnownFragmentNamesRule,
  NoUnusedFragmentsRule,
  PossibleFragmentSpreadsRule,
  NoFragmentCyclesRule,
  UniqueVariableNamesRule,
  NoUndefinedVariablesRule,
  NoUnusedVariablesRule,
  KnownDirectivesRule,
  UniqueDirectivesPerLocationRule,
  KnownArgumentNamesRule,
  UniqueArgumentNamesRule,
  ValuesOfCorrectTypeRule,
  ProvidedRequiredArgumentsRule,
  VariablesInAllowedPositionRule,
  OverlappingFieldsCanBeMergedRule,
  UniqueInputFieldNamesRule
]);
const specifiedSDLRules = Object.freeze([
  LoneSchemaDefinitionRule,
  UniqueOperationTypesRule,
  UniqueTypeNamesRule,
  UniqueEnumValueNamesRule,
  UniqueFieldDefinitionNamesRule,
  UniqueArgumentDefinitionNamesRule,
  UniqueDirectiveNamesRule,
  KnownTypeNamesRule,
  KnownDirectivesRule,
  UniqueDirectivesPerLocationRule,
  PossibleTypeExtensionsRule,
  KnownArgumentNamesOnDirectivesRule,
  UniqueArgumentNamesRule,
  UniqueInputFieldNamesRule,
  ProvidedRequiredArgumentsOnDirectivesRule
]);
class ASTValidationContext {
  constructor(ast, onError) {
    this._ast = ast;
    this._fragments = void 0;
    this._fragmentSpreads = /* @__PURE__ */ new Map();
    this._recursivelyReferencedFragments = /* @__PURE__ */ new Map();
    this._onError = onError;
  }
  get [Symbol.toStringTag]() {
    return "ASTValidationContext";
  }
  reportError(error2) {
    this._onError(error2);
  }
  getDocument() {
    return this._ast;
  }
  getFragment(name2) {
    let fragments;
    if (this._fragments) {
      fragments = this._fragments;
    } else {
      fragments = /* @__PURE__ */ Object.create(null);
      for (const defNode of this.getDocument().definitions) {
        if (defNode.kind === Kind.FRAGMENT_DEFINITION) {
          fragments[defNode.name.value] = defNode;
        }
      }
      this._fragments = fragments;
    }
    return fragments[name2];
  }
  getFragmentSpreads(node) {
    let spreads = this._fragmentSpreads.get(node);
    if (!spreads) {
      spreads = [];
      const setsToVisit = [node];
      let set;
      while (set = setsToVisit.pop()) {
        for (const selection of set.selections) {
          if (selection.kind === Kind.FRAGMENT_SPREAD) {
            spreads.push(selection);
          } else if (selection.selectionSet) {
            setsToVisit.push(selection.selectionSet);
          }
        }
      }
      this._fragmentSpreads.set(node, spreads);
    }
    return spreads;
  }
  getRecursivelyReferencedFragments(operation) {
    let fragments = this._recursivelyReferencedFragments.get(operation);
    if (!fragments) {
      fragments = [];
      const collectedNames = /* @__PURE__ */ Object.create(null);
      const nodesToVisit = [operation.selectionSet];
      let node;
      while (node = nodesToVisit.pop()) {
        for (const spread of this.getFragmentSpreads(node)) {
          const fragName = spread.name.value;
          if (collectedNames[fragName] !== true) {
            collectedNames[fragName] = true;
            const fragment = this.getFragment(fragName);
            if (fragment) {
              fragments.push(fragment);
              nodesToVisit.push(fragment.selectionSet);
            }
          }
        }
      }
      this._recursivelyReferencedFragments.set(operation, fragments);
    }
    return fragments;
  }
}
class SDLValidationContext extends ASTValidationContext {
  constructor(ast, schema, onError) {
    super(ast, onError);
    this._schema = schema;
  }
  get [Symbol.toStringTag]() {
    return "SDLValidationContext";
  }
  getSchema() {
    return this._schema;
  }
}
class ValidationContext extends ASTValidationContext {
  constructor(schema, ast, typeInfo, onError) {
    super(ast, onError);
    this._schema = schema;
    this._typeInfo = typeInfo;
    this._variableUsages = /* @__PURE__ */ new Map();
    this._recursiveVariableUsages = /* @__PURE__ */ new Map();
  }
  get [Symbol.toStringTag]() {
    return "ValidationContext";
  }
  getSchema() {
    return this._schema;
  }
  getVariableUsages(node) {
    let usages = this._variableUsages.get(node);
    if (!usages) {
      const newUsages = [];
      const typeInfo = new TypeInfo(this._schema);
      visit(
        node,
        visitWithTypeInfo(typeInfo, {
          VariableDefinition: () => false,
          Variable(variable) {
            newUsages.push({
              node: variable,
              type: typeInfo.getInputType(),
              defaultValue: typeInfo.getDefaultValue()
            });
          }
        })
      );
      usages = newUsages;
      this._variableUsages.set(node, usages);
    }
    return usages;
  }
  getRecursiveVariableUsages(operation) {
    let usages = this._recursiveVariableUsages.get(operation);
    if (!usages) {
      usages = this.getVariableUsages(operation);
      for (const frag of this.getRecursivelyReferencedFragments(operation)) {
        usages = usages.concat(this.getVariableUsages(frag));
      }
      this._recursiveVariableUsages.set(operation, usages);
    }
    return usages;
  }
  getType() {
    return this._typeInfo.getType();
  }
  getParentType() {
    return this._typeInfo.getParentType();
  }
  getInputType() {
    return this._typeInfo.getInputType();
  }
  getParentInputType() {
    return this._typeInfo.getParentInputType();
  }
  getFieldDef() {
    return this._typeInfo.getFieldDef();
  }
  getDirective() {
    return this._typeInfo.getDirective();
  }
  getArgument() {
    return this._typeInfo.getArgument();
  }
  getEnumValue() {
    return this._typeInfo.getEnumValue();
  }
}
function validate$1(schema, documentAST, rules2 = specifiedRules, options2, typeInfo = new TypeInfo(schema)) {
  var _options$maxErrors;
  const maxErrors = (_options$maxErrors = options2 === null || options2 === void 0 ? void 0 : options2.maxErrors) !== null && _options$maxErrors !== void 0 ? _options$maxErrors : 100;
  documentAST || devAssert(false, "Must provide document.");
  assertValidSchema(schema);
  const abortObj = Object.freeze({});
  const errors2 = [];
  const context = new ValidationContext(
    schema,
    documentAST,
    typeInfo,
    (error2) => {
      if (errors2.length >= maxErrors) {
        errors2.push(
          new GraphQLError(
            "Too many validation errors, error limit reached. Validation aborted."
          )
        );
        throw abortObj;
      }
      errors2.push(error2);
    }
  );
  const visitor = visitInParallel(rules2.map((rule) => rule(context)));
  try {
    visit(documentAST, visitWithTypeInfo(typeInfo, visitor));
  } catch (e) {
    if (e !== abortObj) {
      throw e;
    }
  }
  return errors2;
}
function validateSDL(documentAST, schemaToExtend, rules2 = specifiedSDLRules) {
  const errors2 = [];
  const context = new SDLValidationContext(
    documentAST,
    schemaToExtend,
    (error2) => {
      errors2.push(error2);
    }
  );
  const visitors = rules2.map((rule) => rule(context));
  visit(documentAST, visitInParallel(visitors));
  return errors2;
}
function assertValidSDL(documentAST) {
  const errors2 = validateSDL(documentAST);
  if (errors2.length !== 0) {
    throw new Error(errors2.map((error2) => error2.message).join("\n\n"));
  }
}
function memoize3(fn) {
  let cache0;
  return function memoized(a1, a2, a3) {
    if (cache0 === void 0) {
      cache0 = /* @__PURE__ */ new WeakMap();
    }
    let cache1 = cache0.get(a1);
    if (cache1 === void 0) {
      cache1 = /* @__PURE__ */ new WeakMap();
      cache0.set(a1, cache1);
    }
    let cache2 = cache1.get(a2);
    if (cache2 === void 0) {
      cache2 = /* @__PURE__ */ new WeakMap();
      cache1.set(a2, cache2);
    }
    let fnResult = cache2.get(a3);
    if (fnResult === void 0) {
      fnResult = fn(a1, a2, a3);
      cache2.set(a3, fnResult);
    }
    return fnResult;
  };
}
function promiseForObject(object) {
  return Promise.all(Object.values(object)).then((resolvedValues) => {
    const resolvedObject = /* @__PURE__ */ Object.create(null);
    for (const [i, key] of Object.keys(object).entries()) {
      resolvedObject[key] = resolvedValues[i];
    }
    return resolvedObject;
  });
}
function promiseReduce(values, callbackFn, initialValue) {
  let accumulator = initialValue;
  for (const value of values) {
    accumulator = isPromise(accumulator) ? accumulator.then((resolved) => callbackFn(resolved, value)) : callbackFn(accumulator, value);
  }
  return accumulator;
}
function toError(thrownValue) {
  return thrownValue instanceof Error ? thrownValue : new NonErrorThrown(thrownValue);
}
class NonErrorThrown extends Error {
  constructor(thrownValue) {
    super("Unexpected error value: " + inspect$2(thrownValue));
    this.name = "NonErrorThrown";
    this.thrownValue = thrownValue;
  }
}
function locatedError(rawOriginalError, nodes, path) {
  var _nodes;
  const originalError = toError(rawOriginalError);
  if (isLocatedGraphQLError(originalError)) {
    return originalError;
  }
  return new GraphQLError(originalError.message, {
    nodes: (_nodes = originalError.nodes) !== null && _nodes !== void 0 ? _nodes : nodes,
    source: originalError.source,
    positions: originalError.positions,
    path,
    originalError
  });
}
function isLocatedGraphQLError(error2) {
  return Array.isArray(error2.path);
}
const collectSubfields = memoize3(
  (exeContext, returnType, fieldNodes) => collectSubfields$1(
    exeContext.schema,
    exeContext.fragments,
    exeContext.variableValues,
    returnType,
    fieldNodes
  )
);
function execute(args) {
  arguments.length < 2 || devAssert(
    false,
    "graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead."
  );
  const { schema, document, variableValues, rootValue } = args;
  assertValidExecutionArguments(schema, document, variableValues);
  const exeContext = buildExecutionContext(args);
  if (!("schema" in exeContext)) {
    return {
      errors: exeContext
    };
  }
  try {
    const { operation } = exeContext;
    const result = executeOperation(exeContext, operation, rootValue);
    if (isPromise(result)) {
      return result.then(
        (data) => buildResponse(data, exeContext.errors),
        (error2) => {
          exeContext.errors.push(error2);
          return buildResponse(null, exeContext.errors);
        }
      );
    }
    return buildResponse(result, exeContext.errors);
  } catch (error2) {
    exeContext.errors.push(error2);
    return buildResponse(null, exeContext.errors);
  }
}
function buildResponse(data, errors2) {
  return errors2.length === 0 ? {
    data
  } : {
    errors: errors2,
    data
  };
}
function assertValidExecutionArguments(schema, document, rawVariableValues) {
  document || devAssert(false, "Must provide document.");
  assertValidSchema(schema);
  rawVariableValues == null || isObjectLike(rawVariableValues) || devAssert(
    false,
    "Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided."
  );
}
function buildExecutionContext(args) {
  var _definition$name, _operation$variableDe;
  const {
    schema,
    document,
    rootValue,
    contextValue,
    variableValues: rawVariableValues,
    operationName,
    fieldResolver,
    typeResolver,
    subscribeFieldResolver
  } = args;
  let operation;
  const fragments = /* @__PURE__ */ Object.create(null);
  for (const definition of document.definitions) {
    switch (definition.kind) {
      case Kind.OPERATION_DEFINITION:
        if (operationName == null) {
          if (operation !== void 0) {
            return [
              new GraphQLError(
                "Must provide operation name if query contains multiple operations."
              )
            ];
          }
          operation = definition;
        } else if (((_definition$name = definition.name) === null || _definition$name === void 0 ? void 0 : _definition$name.value) === operationName) {
          operation = definition;
        }
        break;
      case Kind.FRAGMENT_DEFINITION:
        fragments[definition.name.value] = definition;
        break;
    }
  }
  if (!operation) {
    if (operationName != null) {
      return [new GraphQLError(`Unknown operation named "${operationName}".`)];
    }
    return [new GraphQLError("Must provide an operation.")];
  }
  const variableDefinitions = (_operation$variableDe = operation.variableDefinitions) !== null && _operation$variableDe !== void 0 ? _operation$variableDe : [];
  const coercedVariableValues = getVariableValues(
    schema,
    variableDefinitions,
    rawVariableValues !== null && rawVariableValues !== void 0 ? rawVariableValues : {},
    {
      maxErrors: 50
    }
  );
  if (coercedVariableValues.errors) {
    return coercedVariableValues.errors;
  }
  return {
    schema,
    fragments,
    rootValue,
    contextValue,
    operation,
    variableValues: coercedVariableValues.coerced,
    fieldResolver: fieldResolver !== null && fieldResolver !== void 0 ? fieldResolver : defaultFieldResolver,
    typeResolver: typeResolver !== null && typeResolver !== void 0 ? typeResolver : defaultTypeResolver,
    subscribeFieldResolver: subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 ? subscribeFieldResolver : defaultFieldResolver,
    errors: []
  };
}
function executeOperation(exeContext, operation, rootValue) {
  const rootType = exeContext.schema.getRootType(operation.operation);
  if (rootType == null) {
    throw new GraphQLError(
      `Schema is not configured to execute ${operation.operation} operation.`,
      {
        nodes: operation
      }
    );
  }
  const rootFields = collectFields(
    exeContext.schema,
    exeContext.fragments,
    exeContext.variableValues,
    rootType,
    operation.selectionSet
  );
  const path = void 0;
  switch (operation.operation) {
    case OperationTypeNode.QUERY:
      return executeFields(exeContext, rootType, rootValue, path, rootFields);
    case OperationTypeNode.MUTATION:
      return executeFieldsSerially(
        exeContext,
        rootType,
        rootValue,
        path,
        rootFields
      );
    case OperationTypeNode.SUBSCRIPTION:
      return executeFields(exeContext, rootType, rootValue, path, rootFields);
  }
}
function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) {
  return promiseReduce(
    fields.entries(),
    (results, [responseName, fieldNodes]) => {
      const fieldPath = addPath(path, responseName, parentType.name);
      const result = executeField(
        exeContext,
        parentType,
        sourceValue,
        fieldNodes,
        fieldPath
      );
      if (result === void 0) {
        return results;
      }
      if (isPromise(result)) {
        return result.then((resolvedResult) => {
          results[responseName] = resolvedResult;
          return results;
        });
      }
      results[responseName] = result;
      return results;
    },
    /* @__PURE__ */ Object.create(null)
  );
}
function executeFields(exeContext, parentType, sourceValue, path, fields) {
  const results = /* @__PURE__ */ Object.create(null);
  let containsPromise = false;
  try {
    for (const [responseName, fieldNodes] of fields.entries()) {
      const fieldPath = addPath(path, responseName, parentType.name);
      const result = executeField(
        exeContext,
        parentType,
        sourceValue,
        fieldNodes,
        fieldPath
      );
      if (result !== void 0) {
        results[responseName] = result;
        if (isPromise(result)) {
          containsPromise = true;
        }
      }
    }
  } catch (error2) {
    if (containsPromise) {
      return promiseForObject(results).finally(() => {
        throw error2;
      });
    }
    throw error2;
  }
  if (!containsPromise) {
    return results;
  }
  return promiseForObject(results);
}
function executeField(exeContext, parentType, source, fieldNodes, path) {
  var _fieldDef$resolve;
  const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]);
  if (!fieldDef) {
    return;
  }
  const returnType = fieldDef.type;
  const resolveFn = (_fieldDef$resolve = fieldDef.resolve) !== null && _fieldDef$resolve !== void 0 ? _fieldDef$resolve : exeContext.fieldResolver;
  const info = buildResolveInfo(
    exeContext,
    fieldDef,
    fieldNodes,
    parentType,
    path
  );
  try {
    const args = getArgumentValues(
      fieldDef,
      fieldNodes[0],
      exeContext.variableValues
    );
    const contextValue = exeContext.contextValue;
    const result = resolveFn(source, args, contextValue, info);
    let completed;
    if (isPromise(result)) {
      completed = result.then(
        (resolved) => completeValue(exeContext, returnType, fieldNodes, info, path, resolved)
      );
    } else {
      completed = completeValue(
        exeContext,
        returnType,
        fieldNodes,
        info,
        path,
        result
      );
    }
    if (isPromise(completed)) {
      return completed.then(void 0, (rawError) => {
        const error2 = locatedError(rawError, fieldNodes, pathToArray(path));
        return handleFieldError(error2, returnType, exeContext);
      });
    }
    return completed;
  } catch (rawError) {
    const error2 = locatedError(rawError, fieldNodes, pathToArray(path));
    return handleFieldError(error2, returnType, exeContext);
  }
}
function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) {
  return {
    fieldName: fieldDef.name,
    fieldNodes,
    returnType: fieldDef.type,
    parentType,
    path,
    schema: exeContext.schema,
    fragments: exeContext.fragments,
    rootValue: exeContext.rootValue,
    operation: exeContext.operation,
    variableValues: exeContext.variableValues
  };
}
function handleFieldError(error2, returnType, exeContext) {
  if (isNonNullType(returnType)) {
    throw error2;
  }
  exeContext.errors.push(error2);
  return null;
}
function completeValue(exeContext, returnType, fieldNodes, info, path, result) {
  if (result instanceof Error) {
    throw result;
  }
  if (isNonNullType(returnType)) {
    const completed = completeValue(
      exeContext,
      returnType.ofType,
      fieldNodes,
      info,
      path,
      result
    );
    if (completed === null) {
      throw new Error(
        `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`
      );
    }
    return completed;
  }
  if (result == null) {
    return null;
  }
  if (isListType(returnType)) {
    return completeListValue(
      exeContext,
      returnType,
      fieldNodes,
      info,
      path,
      result
    );
  }
  if (isLeafType(returnType)) {
    return completeLeafValue(returnType, result);
  }
  if (isAbstractType(returnType)) {
    return completeAbstractValue(
      exeContext,
      returnType,
      fieldNodes,
      info,
      path,
      result
    );
  }
  if (isObjectType(returnType)) {
    return completeObjectValue(
      exeContext,
      returnType,
      fieldNodes,
      info,
      path,
      result
    );
  }
  invariant(
    false,
    "Cannot complete value of unexpected output type: " + inspect$2(returnType)
  );
}
function completeListValue(exeContext, returnType, fieldNodes, info, path, result) {
  if (!isIterableObject(result)) {
    throw new GraphQLError(
      `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`
    );
  }
  const itemType = returnType.ofType;
  let containsPromise = false;
  const completedResults = Array.from(result, (item, index) => {
    const itemPath = addPath(path, index, void 0);
    try {
      let completedItem;
      if (isPromise(item)) {
        completedItem = item.then(
          (resolved) => completeValue(
            exeContext,
            itemType,
            fieldNodes,
            info,
            itemPath,
            resolved
          )
        );
      } else {
        completedItem = completeValue(
          exeContext,
          itemType,
          fieldNodes,
          info,
          itemPath,
          item
        );
      }
      if (isPromise(completedItem)) {
        containsPromise = true;
        return completedItem.then(void 0, (rawError) => {
          const error2 = locatedError(
            rawError,
            fieldNodes,
            pathToArray(itemPath)
          );
          return handleFieldError(error2, itemType, exeContext);
        });
      }
      return completedItem;
    } catch (rawError) {
      const error2 = locatedError(rawError, fieldNodes, pathToArray(itemPath));
      return handleFieldError(error2, itemType, exeContext);
    }
  });
  return containsPromise ? Promise.all(completedResults) : completedResults;
}
function completeLeafValue(returnType, result) {
  const serializedResult = returnType.serialize(result);
  if (serializedResult == null) {
    throw new Error(
      `Expected \`${inspect$2(returnType)}.serialize(${inspect$2(result)})\` to return non-nullable value, returned: ${inspect$2(serializedResult)}`
    );
  }
  return serializedResult;
}
function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) {
  var _returnType$resolveTy;
  const resolveTypeFn = (_returnType$resolveTy = returnType.resolveType) !== null && _returnType$resolveTy !== void 0 ? _returnType$resolveTy : exeContext.typeResolver;
  const contextValue = exeContext.contextValue;
  const runtimeType = resolveTypeFn(result, contextValue, info, returnType);
  if (isPromise(runtimeType)) {
    return runtimeType.then(
      (resolvedRuntimeType) => completeObjectValue(
        exeContext,
        ensureValidRuntimeType(
          resolvedRuntimeType,
          exeContext,
          returnType,
          fieldNodes,
          info,
          result
        ),
        fieldNodes,
        info,
        path,
        result
      )
    );
  }
  return completeObjectValue(
    exeContext,
    ensureValidRuntimeType(
      runtimeType,
      exeContext,
      returnType,
      fieldNodes,
      info,
      result
    ),
    fieldNodes,
    info,
    path,
    result
  );
}
function ensureValidRuntimeType(runtimeTypeName, exeContext, returnType, fieldNodes, info, result) {
  if (runtimeTypeName == null) {
    throw new GraphQLError(
      `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}". Either the "${returnType.name}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`,
      fieldNodes
    );
  }
  if (isObjectType(runtimeTypeName)) {
    throw new GraphQLError(
      "Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead."
    );
  }
  if (typeof runtimeTypeName !== "string") {
    throw new GraphQLError(
      `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with value ${inspect$2(result)}, received "${inspect$2(runtimeTypeName)}".`
    );
  }
  const runtimeType = exeContext.schema.getType(runtimeTypeName);
  if (runtimeType == null) {
    throw new GraphQLError(
      `Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`,
      {
        nodes: fieldNodes
      }
    );
  }
  if (!isObjectType(runtimeType)) {
    throw new GraphQLError(
      `Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`,
      {
        nodes: fieldNodes
      }
    );
  }
  if (!exeContext.schema.isSubType(returnType, runtimeType)) {
    throw new GraphQLError(
      `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`,
      {
        nodes: fieldNodes
      }
    );
  }
  return runtimeType;
}
function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) {
  const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes);
  if (returnType.isTypeOf) {
    const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);
    if (isPromise(isTypeOf)) {
      return isTypeOf.then((resolvedIsTypeOf) => {
        if (!resolvedIsTypeOf) {
          throw invalidReturnTypeError(returnType, result, fieldNodes);
        }
        return executeFields(
          exeContext,
          returnType,
          result,
          path,
          subFieldNodes
        );
      });
    }
    if (!isTypeOf) {
      throw invalidReturnTypeError(returnType, result, fieldNodes);
    }
  }
  return executeFields(exeContext, returnType, result, path, subFieldNodes);
}
function invalidReturnTypeError(returnType, result, fieldNodes) {
  return new GraphQLError(
    `Expected value of type "${returnType.name}" but got: ${inspect$2(result)}.`,
    {
      nodes: fieldNodes
    }
  );
}
const defaultTypeResolver = function(value, contextValue, info, abstractType) {
  if (isObjectLike(value) && typeof value.__typename === "string") {
    return value.__typename;
  }
  const possibleTypes = info.schema.getPossibleTypes(abstractType);
  const promisedIsTypeOfResults = [];
  for (let i = 0; i < possibleTypes.length; i++) {
    const type2 = possibleTypes[i];
    if (type2.isTypeOf) {
      const isTypeOfResult = type2.isTypeOf(value, contextValue, info);
      if (isPromise(isTypeOfResult)) {
        promisedIsTypeOfResults[i] = isTypeOfResult;
      } else if (isTypeOfResult) {
        return type2.name;
      }
    }
  }
  if (promisedIsTypeOfResults.length) {
    return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => {
      for (let i = 0; i < isTypeOfResults.length; i++) {
        if (isTypeOfResults[i]) {
          return possibleTypes[i].name;
        }
      }
    });
  }
};
const defaultFieldResolver = function(source, args, contextValue, info) {
  if (isObjectLike(source) || typeof source === "function") {
    const property = source[info.fieldName];
    if (typeof property === "function") {
      return source[info.fieldName](args, contextValue, info);
    }
    return property;
  }
};
function getFieldDef(schema, parentType, fieldNode) {
  const fieldName = fieldNode.name.value;
  if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) {
    return SchemaMetaFieldDef;
  } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {
    return TypeMetaFieldDef;
  } else if (fieldName === TypeNameMetaFieldDef.name) {
    return TypeNameMetaFieldDef;
  }
  return parentType.getFields()[fieldName];
}
function graphql(args) {
  return new Promise((resolve2) => resolve2(graphqlImpl(args)));
}
function graphqlSync(args) {
  const result = graphqlImpl(args);
  if (isPromise(result)) {
    throw new Error("GraphQL execution failed to complete synchronously.");
  }
  return result;
}
function graphqlImpl(args) {
  arguments.length < 2 || devAssert(
    false,
    "graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead."
  );
  const {
    schema,
    source,
    rootValue,
    contextValue,
    variableValues,
    operationName,
    fieldResolver,
    typeResolver
  } = args;
  const schemaValidationErrors = validateSchema(schema);
  if (schemaValidationErrors.length > 0) {
    return {
      errors: schemaValidationErrors
    };
  }
  let document;
  try {
    document = parse(source);
  } catch (syntaxError2) {
    return {
      errors: [syntaxError2]
    };
  }
  const validationErrors = validate$1(schema, document);
  if (validationErrors.length > 0) {
    return {
      errors: validationErrors
    };
  }
  return execute({
    schema,
    document,
    rootValue,
    contextValue,
    variableValues,
    operationName,
    fieldResolver,
    typeResolver
  });
}
function extendSchemaImpl(schemaConfig, documentAST, options2) {
  var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;
  const typeDefs2 = [];
  const typeExtensionsMap = /* @__PURE__ */ Object.create(null);
  const directiveDefs = [];
  let schemaDef;
  const schemaExtensions = [];
  for (const def2 of documentAST.definitions) {
    if (def2.kind === Kind.SCHEMA_DEFINITION) {
      schemaDef = def2;
    } else if (def2.kind === Kind.SCHEMA_EXTENSION) {
      schemaExtensions.push(def2);
    } else if (isTypeDefinitionNode(def2)) {
      typeDefs2.push(def2);
    } else if (isTypeExtensionNode(def2)) {
      const extendedTypeName = def2.name.value;
      const existingTypeExtensions = typeExtensionsMap[extendedTypeName];
      typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def2]) : [def2];
    } else if (def2.kind === Kind.DIRECTIVE_DEFINITION) {
      directiveDefs.push(def2);
    }
  }
  if (Object.keys(typeExtensionsMap).length === 0 && typeDefs2.length === 0 && directiveDefs.length === 0 && schemaExtensions.length === 0 && schemaDef == null) {
    return schemaConfig;
  }
  const typeMap = /* @__PURE__ */ Object.create(null);
  for (const existingType of schemaConfig.types) {
    typeMap[existingType.name] = extendNamedType(existingType);
  }
  for (const typeNode of typeDefs2) {
    var _stdTypeMap$name;
    const name2 = typeNode.name.value;
    typeMap[name2] = (_stdTypeMap$name = stdTypeMap[name2]) !== null && _stdTypeMap$name !== void 0 ? _stdTypeMap$name : buildType(typeNode);
  }
  const operationTypes = {
    // Get the extended root operation types.
    query: schemaConfig.query && replaceNamedType(schemaConfig.query),
    mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),
    subscription: schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),
    // Then, incorporate schema definition and all schema extensions.
    ...schemaDef && getOperationTypes([schemaDef]),
    ...getOperationTypes(schemaExtensions)
  };
  return {
    description: (_schemaDef = schemaDef) === null || _schemaDef === void 0 ? void 0 : (_schemaDef$descriptio = _schemaDef.description) === null || _schemaDef$descriptio === void 0 ? void 0 : _schemaDef$descriptio.value,
    ...operationTypes,
    types: Object.values(typeMap),
    directives: [
      ...schemaConfig.directives.map(replaceDirective),
      ...directiveDefs.map(buildDirective)
    ],
    extensions: /* @__PURE__ */ Object.create(null),
    astNode: (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 ? _schemaDef2 : schemaConfig.astNode,
    extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),
    assumeValid: (_options$assumeValid = options2 === null || options2 === void 0 ? void 0 : options2.assumeValid) !== null && _options$assumeValid !== void 0 ? _options$assumeValid : false
  };
  function replaceType(type2) {
    if (isListType(type2)) {
      return new GraphQLList(replaceType(type2.ofType));
    }
    if (isNonNullType(type2)) {
      return new GraphQLNonNull(replaceType(type2.ofType));
    }
    return replaceNamedType(type2);
  }
  function replaceNamedType(type2) {
    return typeMap[type2.name];
  }
  function replaceDirective(directive) {
    const config = directive.toConfig();
    return new GraphQLDirective({
      ...config,
      args: mapValue(config.args, extendArg)
    });
  }
  function extendNamedType(type2) {
    if (isIntrospectionType(type2) || isSpecifiedScalarType(type2)) {
      return type2;
    }
    if (isScalarType(type2)) {
      return extendScalarType(type2);
    }
    if (isObjectType(type2)) {
      return extendObjectType(type2);
    }
    if (isInterfaceType(type2)) {
      return extendInterfaceType(type2);
    }
    if (isUnionType(type2)) {
      return extendUnionType(type2);
    }
    if (isEnumType(type2)) {
      return extendEnumType(type2);
    }
    if (isInputObjectType(type2)) {
      return extendInputObjectType(type2);
    }
    invariant(false, "Unexpected type: " + inspect$2(type2));
  }
  function extendInputObjectType(type2) {
    var _typeExtensionsMap$co;
    const config = type2.toConfig();
    const extensions = (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co !== void 0 ? _typeExtensionsMap$co : [];
    return new GraphQLInputObjectType({
      ...config,
      fields: () => ({
        ...mapValue(config.fields, (field) => ({
          ...field,
          type: replaceType(field.type)
        })),
        ...buildInputFieldMap(extensions)
      }),
      extensionASTNodes: config.extensionASTNodes.concat(extensions)
    });
  }
  function extendEnumType(type2) {
    var _typeExtensionsMap$ty;
    const config = type2.toConfig();
    const extensions = (_typeExtensionsMap$ty = typeExtensionsMap[type2.name]) !== null && _typeExtensionsMap$ty !== void 0 ? _typeExtensionsMap$ty : [];
    return new GraphQLEnumType({
      ...config,
      values: { ...config.values, ...buildEnumValueMap(extensions) },
      extensionASTNodes: config.extensionASTNodes.concat(extensions)
    });
  }
  function extendScalarType(type2) {
    var _typeExtensionsMap$co2;
    const config = type2.toConfig();
    const extensions = (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co2 !== void 0 ? _typeExtensionsMap$co2 : [];
    let specifiedByURL = config.specifiedByURL;
    for (const extensionNode of extensions) {
      var _getSpecifiedByURL;
      specifiedByURL = (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && _getSpecifiedByURL !== void 0 ? _getSpecifiedByURL : specifiedByURL;
    }
    return new GraphQLScalarType({
      ...config,
      specifiedByURL,
      extensionASTNodes: config.extensionASTNodes.concat(extensions)
    });
  }
  function extendObjectType(type2) {
    var _typeExtensionsMap$co3;
    const config = type2.toConfig();
    const extensions = (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co3 !== void 0 ? _typeExtensionsMap$co3 : [];
    return new GraphQLObjectType({
      ...config,
      interfaces: () => [
        ...type2.getInterfaces().map(replaceNamedType),
        ...buildInterfaces(extensions)
      ],
      fields: () => ({
        ...mapValue(config.fields, extendField),
        ...buildFieldMap(extensions)
      }),
      extensionASTNodes: config.extensionASTNodes.concat(extensions)
    });
  }
  function extendInterfaceType(type2) {
    var _typeExtensionsMap$co4;
    const config = type2.toConfig();
    const extensions = (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co4 !== void 0 ? _typeExtensionsMap$co4 : [];
    return new GraphQLInterfaceType({
      ...config,
      interfaces: () => [
        ...type2.getInterfaces().map(replaceNamedType),
        ...buildInterfaces(extensions)
      ],
      fields: () => ({
        ...mapValue(config.fields, extendField),
        ...buildFieldMap(extensions)
      }),
      extensionASTNodes: config.extensionASTNodes.concat(extensions)
    });
  }
  function extendUnionType(type2) {
    var _typeExtensionsMap$co5;
    const config = type2.toConfig();
    const extensions = (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && _typeExtensionsMap$co5 !== void 0 ? _typeExtensionsMap$co5 : [];
    return new GraphQLUnionType({
      ...config,
      types: () => [
        ...type2.getTypes().map(replaceNamedType),
        ...buildUnionTypes(extensions)
      ],
      extensionASTNodes: config.extensionASTNodes.concat(extensions)
    });
  }
  function extendField(field) {
    return {
      ...field,
      type: replaceType(field.type),
      args: field.args && mapValue(field.args, extendArg)
    };
  }
  function extendArg(arg) {
    return { ...arg, type: replaceType(arg.type) };
  }
  function getOperationTypes(nodes) {
    const opTypes = {};
    for (const node of nodes) {
      var _node$operationTypes;
      const operationTypesNodes = (
        /* c8 ignore next */
        (_node$operationTypes = node.operationTypes) !== null && _node$operationTypes !== void 0 ? _node$operationTypes : []
      );
      for (const operationType of operationTypesNodes) {
        opTypes[operationType.operation] = getNamedType2(operationType.type);
      }
    }
    return opTypes;
  }
  function getNamedType2(node) {
    var _stdTypeMap$name2;
    const name2 = node.name.value;
    const type2 = (_stdTypeMap$name2 = stdTypeMap[name2]) !== null && _stdTypeMap$name2 !== void 0 ? _stdTypeMap$name2 : typeMap[name2];
    if (type2 === void 0) {
      throw new Error(`Unknown type: "${name2}".`);
    }
    return type2;
  }
  function getWrappedType(node) {
    if (node.kind === Kind.LIST_TYPE) {
      return new GraphQLList(getWrappedType(node.type));
    }
    if (node.kind === Kind.NON_NULL_TYPE) {
      return new GraphQLNonNull(getWrappedType(node.type));
    }
    return getNamedType2(node);
  }
  function buildDirective(node) {
    var _node$description;
    return new GraphQLDirective({
      name: node.name.value,
      description: (_node$description = node.description) === null || _node$description === void 0 ? void 0 : _node$description.value,
      // @ts-expect-error
      locations: node.locations.map(({ value }) => value),
      isRepeatable: node.repeatable,
      args: buildArgumentMap(node.arguments),
      astNode: node
    });
  }
  function buildFieldMap(nodes) {
    const fieldConfigMap = /* @__PURE__ */ Object.create(null);
    for (const node of nodes) {
      var _node$fields;
      const nodeFields = (
        /* c8 ignore next */
        (_node$fields = node.fields) !== null && _node$fields !== void 0 ? _node$fields : []
      );
      for (const field of nodeFields) {
        var _field$description;
        fieldConfigMap[field.name.value] = {
          // Note: While this could make assertions to get the correctly typed
          // value, that would throw immediately while type system validation
          // with validateSchema() will produce more actionable results.
          type: getWrappedType(field.type),
          description: (_field$description = field.description) === null || _field$description === void 0 ? void 0 : _field$description.value,
          args: buildArgumentMap(field.arguments),
          deprecationReason: getDeprecationReason(field),
          astNode: field
        };
      }
    }
    return fieldConfigMap;
  }
  function buildArgumentMap(args) {
    const argsNodes = (
      /* c8 ignore next */
      args !== null && args !== void 0 ? args : []
    );
    const argConfigMap = /* @__PURE__ */ Object.create(null);
    for (const arg of argsNodes) {
      var _arg$description;
      const type2 = getWrappedType(arg.type);
      argConfigMap[arg.name.value] = {
        type: type2,
        description: (_arg$description = arg.description) === null || _arg$description === void 0 ? void 0 : _arg$description.value,
        defaultValue: valueFromAST(arg.defaultValue, type2),
        deprecationReason: getDeprecationReason(arg),
        astNode: arg
      };
    }
    return argConfigMap;
  }
  function buildInputFieldMap(nodes) {
    const inputFieldMap = /* @__PURE__ */ Object.create(null);
    for (const node of nodes) {
      var _node$fields2;
      const fieldsNodes = (
        /* c8 ignore next */
        (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 ? _node$fields2 : []
      );
      for (const field of fieldsNodes) {
        var _field$description2;
        const type2 = getWrappedType(field.type);
        inputFieldMap[field.name.value] = {
          type: type2,
          description: (_field$description2 = field.description) === null || _field$description2 === void 0 ? void 0 : _field$description2.value,
          defaultValue: valueFromAST(field.defaultValue, type2),
          deprecationReason: getDeprecationReason(field),
          astNode: field
        };
      }
    }
    return inputFieldMap;
  }
  function buildEnumValueMap(nodes) {
    const enumValueMap = /* @__PURE__ */ Object.create(null);
    for (const node of nodes) {
      var _node$values;
      const valuesNodes = (
        /* c8 ignore next */
        (_node$values = node.values) !== null && _node$values !== void 0 ? _node$values : []
      );
      for (const value of valuesNodes) {
        var _value$description;
        enumValueMap[value.name.value] = {
          description: (_value$description = value.description) === null || _value$description === void 0 ? void 0 : _value$description.value,
          deprecationReason: getDeprecationReason(value),
          astNode: value
        };
      }
    }
    return enumValueMap;
  }
  function buildInterfaces(nodes) {
    return nodes.flatMap(
      // FIXME: https://github.com/graphql/graphql-js/issues/2203
      (node) => {
        var _node$interfaces$map, _node$interfaces;
        return (
          /* c8 ignore next */
          (_node$interfaces$map = (_node$interfaces = node.interfaces) === null || _node$interfaces === void 0 ? void 0 : _node$interfaces.map(getNamedType2)) !== null && _node$interfaces$map !== void 0 ? _node$interfaces$map : []
        );
      }
    );
  }
  function buildUnionTypes(nodes) {
    return nodes.flatMap(
      // FIXME: https://github.com/graphql/graphql-js/issues/2203
      (node) => {
        var _node$types$map, _node$types;
        return (
          /* c8 ignore next */
          (_node$types$map = (_node$types = node.types) === null || _node$types === void 0 ? void 0 : _node$types.map(getNamedType2)) !== null && _node$types$map !== void 0 ? _node$types$map : []
        );
      }
    );
  }
  function buildType(astNode) {
    var _typeExtensionsMap$na;
    const name2 = astNode.name.value;
    const extensionASTNodes = (_typeExtensionsMap$na = typeExtensionsMap[name2]) !== null && _typeExtensionsMap$na !== void 0 ? _typeExtensionsMap$na : [];
    switch (astNode.kind) {
      case Kind.OBJECT_TYPE_DEFINITION: {
        var _astNode$description;
        const allNodes = [astNode, ...extensionASTNodes];
        return new GraphQLObjectType({
          name: name2,
          description: (_astNode$description = astNode.description) === null || _astNode$description === void 0 ? void 0 : _astNode$description.value,
          interfaces: () => buildInterfaces(allNodes),
          fields: () => buildFieldMap(allNodes),
          astNode,
          extensionASTNodes
        });
      }
      case Kind.INTERFACE_TYPE_DEFINITION: {
        var _astNode$description2;
        const allNodes = [astNode, ...extensionASTNodes];
        return new GraphQLInterfaceType({
          name: name2,
          description: (_astNode$description2 = astNode.description) === null || _astNode$description2 === void 0 ? void 0 : _astNode$description2.value,
          interfaces: () => buildInterfaces(allNodes),
          fields: () => buildFieldMap(allNodes),
          astNode,
          extensionASTNodes
        });
      }
      case Kind.ENUM_TYPE_DEFINITION: {
        var _astNode$description3;
        const allNodes = [astNode, ...extensionASTNodes];
        return new GraphQLEnumType({
          name: name2,
          description: (_astNode$description3 = astNode.description) === null || _astNode$description3 === void 0 ? void 0 : _astNode$description3.value,
          values: buildEnumValueMap(allNodes),
          astNode,
          extensionASTNodes
        });
      }
      case Kind.UNION_TYPE_DEFINITION: {
        var _astNode$description4;
        const allNodes = [astNode, ...extensionASTNodes];
        return new GraphQLUnionType({
          name: name2,
          description: (_astNode$description4 = astNode.description) === null || _astNode$description4 === void 0 ? void 0 : _astNode$description4.value,
          types: () => buildUnionTypes(allNodes),
          astNode,
          extensionASTNodes
        });
      }
      case Kind.SCALAR_TYPE_DEFINITION: {
        var _astNode$description5;
        return new GraphQLScalarType({
          name: name2,
          description: (_astNode$description5 = astNode.description) === null || _astNode$description5 === void 0 ? void 0 : _astNode$description5.value,
          specifiedByURL: getSpecifiedByURL(astNode),
          astNode,
          extensionASTNodes
        });
      }
      case Kind.INPUT_OBJECT_TYPE_DEFINITION: {
        var _astNode$description6;
        const allNodes = [astNode, ...extensionASTNodes];
        return new GraphQLInputObjectType({
          name: name2,
          description: (_astNode$description6 = astNode.description) === null || _astNode$description6 === void 0 ? void 0 : _astNode$description6.value,
          fields: () => buildInputFieldMap(allNodes),
          astNode,
          extensionASTNodes
        });
      }
    }
  }
}
const stdTypeMap = keyMap(
  [...specifiedScalarTypes, ...introspectionTypes],
  (type2) => type2.name
);
function getDeprecationReason(node) {
  const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);
  return deprecated === null || deprecated === void 0 ? void 0 : deprecated.reason;
}
function getSpecifiedByURL(node) {
  const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node);
  return specifiedBy === null || specifiedBy === void 0 ? void 0 : specifiedBy.url;
}
function buildASTSchema(documentAST, options2) {
  documentAST != null && documentAST.kind === Kind.DOCUMENT || devAssert(false, "Must provide valid Document AST.");
  if ((options2 === null || options2 === void 0 ? void 0 : options2.assumeValid) !== true && (options2 === null || options2 === void 0 ? void 0 : options2.assumeValidSDL) !== true) {
    assertValidSDL(documentAST);
  }
  const emptySchemaConfig = {
    description: void 0,
    types: [],
    directives: [],
    extensions: /* @__PURE__ */ Object.create(null),
    extensionASTNodes: [],
    assumeValid: false
  };
  const config = extendSchemaImpl(emptySchemaConfig, documentAST, options2);
  if (config.astNode == null) {
    for (const type2 of config.types) {
      switch (type2.name) {
        case "Query":
          config.query = type2;
          break;
        case "Mutation":
          config.mutation = type2;
          break;
        case "Subscription":
          config.subscription = type2;
          break;
      }
    }
  }
  const directives = [
    ...config.directives,
    // If specified directives were not explicitly declared, add them.
    ...specifiedDirectives.filter(
      (stdDirective) => config.directives.every(
        (directive) => directive.name !== stdDirective.name
      )
    )
  ];
  return new GraphQLSchema({ ...config, directives });
}
function buildSchema(source, options2) {
  const document = parse(source, {
    noLocation: options2 === null || options2 === void 0 ? void 0 : options2.noLocation,
    allowLegacyFragmentVariables: options2 === null || options2 === void 0 ? void 0 : options2.allowLegacyFragmentVariables
  });
  return buildASTSchema(document, {
    assumeValidSDL: options2 === null || options2 === void 0 ? void 0 : options2.assumeValidSDL,
    assumeValid: options2 === null || options2 === void 0 ? void 0 : options2.assumeValid
  });
}
const asArray = (fns) => Array.isArray(fns) ? fns : fns ? [fns] : [];
function compareStrings(a, b) {
  if (String(a) < String(b)) {
    return -1;
  }
  if (String(a) > String(b)) {
    return 1;
  }
  return 0;
}
function nodeToString(a) {
  var _a, _b;
  let name2;
  if ("alias" in a) {
    name2 = (_a = a.alias) === null || _a === void 0 ? void 0 : _a.value;
  }
  if (name2 == null && "name" in a) {
    name2 = (_b = a.name) === null || _b === void 0 ? void 0 : _b.value;
  }
  if (name2 == null) {
    name2 = a.kind;
  }
  return name2;
}
function compareNodes(a, b, customFn) {
  const aStr = nodeToString(a);
  const bStr = nodeToString(b);
  if (typeof customFn === "function") {
    return customFn(aStr, bStr);
  }
  return compareStrings(aStr, bStr);
}
function isSome(input) {
  return input != null;
}
if (typeof AggregateError === "undefined")
  ;
else {
  AggregateError;
}
function isAggregateError(error2) {
  return "errors" in error2 && Array.isArray(error2["errors"]);
}
const MAX_RECURSIVE_DEPTH = 3;
function inspect$1(value) {
  return formatValue(value, []);
}
function formatValue(value, seenValues) {
  switch (typeof value) {
    case "string":
      return JSON.stringify(value);
    case "function":
      return value.name ? `[function ${value.name}]` : "[function]";
    case "object":
      return formatObjectValue(value, seenValues);
    default:
      return String(value);
  }
}
function formatError(value) {
  if (value instanceof GraphQLError) {
    return value.toString();
  }
  return `${value.name}: ${value.message};
 ${value.stack}`;
}
function formatObjectValue(value, previouslySeenValues) {
  if (value === null) {
    return "null";
  }
  if (value instanceof Error) {
    if (isAggregateError(value)) {
      return formatError(value) + "\n" + formatArray(value.errors, previouslySeenValues);
    }
    return formatError(value);
  }
  if (previouslySeenValues.includes(value)) {
    return "[Circular]";
  }
  const seenValues = [...previouslySeenValues, value];
  if (isJSONable(value)) {
    const jsonValue = value.toJSON();
    if (jsonValue !== value) {
      return typeof jsonValue === "string" ? jsonValue : formatValue(jsonValue, seenValues);
    }
  } else if (Array.isArray(value)) {
    return formatArray(value, seenValues);
  }
  return formatObject(value, seenValues);
}
function isJSONable(value) {
  return typeof value.toJSON === "function";
}
function formatObject(object, seenValues) {
  const entries = Object.entries(object);
  if (entries.length === 0) {
    return "{}";
  }
  if (seenValues.length > MAX_RECURSIVE_DEPTH) {
    return "[" + getObjectTag(object) + "]";
  }
  const properties2 = entries.map(([key, value]) => key + ": " + formatValue(value, seenValues));
  return "{ " + properties2.join(", ") + " }";
}
function formatArray(array, seenValues) {
  if (array.length === 0) {
    return "[]";
  }
  if (seenValues.length > MAX_RECURSIVE_DEPTH) {
    return "[Array]";
  }
  const len = array.length;
  const items2 = [];
  for (let i = 0; i < len; ++i) {
    items2.push(formatValue(array[i], seenValues));
  }
  return "[" + items2.join(", ") + "]";
}
function getObjectTag(object) {
  const tag = Object.prototype.toString.call(object).replace(/^\[object /, "").replace(/]$/, "");
  if (tag === "Object" && typeof object.constructor === "function") {
    const name2 = object.constructor.name;
    if (typeof name2 === "string" && name2 !== "") {
      return name2;
    }
  }
  return tag;
}
function getDirectivesInExtensions(node, pathToDirectivesInExtensions = ["directives"]) {
  return pathToDirectivesInExtensions.reduce((acc, pathSegment) => acc == null ? acc : acc[pathSegment], node === null || node === void 0 ? void 0 : node.extensions);
}
function astFromType(type2) {
  if (isNonNullType(type2)) {
    const innerType = astFromType(type2.ofType);
    if (innerType.kind === Kind.NON_NULL_TYPE) {
      throw new Error(`Invalid type node ${inspect$1(type2)}. Inner type of non-null type cannot be a non-null type.`);
    }
    return {
      kind: Kind.NON_NULL_TYPE,
      type: innerType
    };
  } else if (isListType(type2)) {
    return {
      kind: Kind.LIST_TYPE,
      type: astFromType(type2.ofType)
    };
  }
  return {
    kind: Kind.NAMED_TYPE,
    name: {
      kind: Kind.NAME,
      value: type2.name
    }
  };
}
function astFromValueUntyped(value) {
  if (value === null) {
    return { kind: Kind.NULL };
  }
  if (value === void 0) {
    return null;
  }
  if (Array.isArray(value)) {
    const valuesNodes = [];
    for (const item of value) {
      const itemNode = astFromValueUntyped(item);
      if (itemNode != null) {
        valuesNodes.push(itemNode);
      }
    }
    return { kind: Kind.LIST, values: valuesNodes };
  }
  if (typeof value === "object") {
    const fieldNodes = [];
    for (const fieldName in value) {
      const fieldValue = value[fieldName];
      const ast = astFromValueUntyped(fieldValue);
      if (ast) {
        fieldNodes.push({
          kind: Kind.OBJECT_FIELD,
          name: { kind: Kind.NAME, value: fieldName },
          value: ast
        });
      }
    }
    return { kind: Kind.OBJECT, fields: fieldNodes };
  }
  if (typeof value === "boolean") {
    return { kind: Kind.BOOLEAN, value };
  }
  if (typeof value === "number" && isFinite(value)) {
    const stringNum = String(value);
    return integerStringRegExp.test(stringNum) ? { kind: Kind.INT, value: stringNum } : { kind: Kind.FLOAT, value: stringNum };
  }
  if (typeof value === "string") {
    return { kind: Kind.STRING, value };
  }
  throw new TypeError(`Cannot convert value to AST: ${value}.`);
}
const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;
function memoize1(fn) {
  const memoize1cache = /* @__PURE__ */ new WeakMap();
  return function memoized(a1) {
    const cachedValue = memoize1cache.get(a1);
    if (cachedValue === void 0) {
      const newValue = fn(a1);
      memoize1cache.set(a1, newValue);
      return newValue;
    }
    return cachedValue;
  };
}
const getRootTypeMap = memoize1(function getRootTypeMap2(schema) {
  const rootTypeMap = /* @__PURE__ */ new Map();
  const queryType = schema.getQueryType();
  if (queryType) {
    rootTypeMap.set("query", queryType);
  }
  const mutationType = schema.getMutationType();
  if (mutationType) {
    rootTypeMap.set("mutation", mutationType);
  }
  const subscriptionType = schema.getSubscriptionType();
  if (subscriptionType) {
    rootTypeMap.set("subscription", subscriptionType);
  }
  return rootTypeMap;
});
function getDocumentNodeFromSchema(schema, options2 = {}) {
  const pathToDirectivesInExtensions = options2.pathToDirectivesInExtensions;
  const typesMap = schema.getTypeMap();
  const schemaNode = astFromSchema(schema, pathToDirectivesInExtensions);
  const definitions2 = schemaNode != null ? [schemaNode] : [];
  const directives = schema.getDirectives();
  for (const directive of directives) {
    if (isSpecifiedDirective(directive)) {
      continue;
    }
    definitions2.push(astFromDirective(directive, schema, pathToDirectivesInExtensions));
  }
  for (const typeName in typesMap) {
    const type2 = typesMap[typeName];
    const isPredefinedScalar = isSpecifiedScalarType(type2);
    const isIntrospection = isIntrospectionType(type2);
    if (isPredefinedScalar || isIntrospection) {
      continue;
    }
    if (isObjectType(type2)) {
      definitions2.push(astFromObjectType(type2, schema, pathToDirectivesInExtensions));
    } else if (isInterfaceType(type2)) {
      definitions2.push(astFromInterfaceType(type2, schema, pathToDirectivesInExtensions));
    } else if (isUnionType(type2)) {
      definitions2.push(astFromUnionType(type2, schema, pathToDirectivesInExtensions));
    } else if (isInputObjectType(type2)) {
      definitions2.push(astFromInputObjectType(type2, schema, pathToDirectivesInExtensions));
    } else if (isEnumType(type2)) {
      definitions2.push(astFromEnumType(type2, schema, pathToDirectivesInExtensions));
    } else if (isScalarType(type2)) {
      definitions2.push(astFromScalarType(type2, schema, pathToDirectivesInExtensions));
    } else {
      throw new Error(`Unknown type ${type2}.`);
    }
  }
  return {
    kind: Kind.DOCUMENT,
    definitions: definitions2
  };
}
function astFromSchema(schema, pathToDirectivesInExtensions) {
  var _a, _b;
  const operationTypeMap = /* @__PURE__ */ new Map([
    ["query", void 0],
    ["mutation", void 0],
    ["subscription", void 0]
  ]);
  const nodes = [];
  if (schema.astNode != null) {
    nodes.push(schema.astNode);
  }
  if (schema.extensionASTNodes != null) {
    for (const extensionASTNode of schema.extensionASTNodes) {
      nodes.push(extensionASTNode);
    }
  }
  for (const node of nodes) {
    if (node.operationTypes) {
      for (const operationTypeDefinitionNode of node.operationTypes) {
        operationTypeMap.set(operationTypeDefinitionNode.operation, operationTypeDefinitionNode);
      }
    }
  }
  const rootTypeMap = getRootTypeMap(schema);
  for (const [operationTypeNode, operationTypeDefinitionNode] of operationTypeMap) {
    const rootType = rootTypeMap.get(operationTypeNode);
    if (rootType != null) {
      const rootTypeAST = astFromType(rootType);
      if (operationTypeDefinitionNode != null) {
        operationTypeDefinitionNode.type = rootTypeAST;
      } else {
        operationTypeMap.set(operationTypeNode, {
          kind: Kind.OPERATION_TYPE_DEFINITION,
          operation: operationTypeNode,
          type: rootTypeAST
        });
      }
    }
  }
  const operationTypes = [...operationTypeMap.values()].filter(isSome);
  const directives = getDirectiveNodes(schema, schema, pathToDirectivesInExtensions);
  if (!operationTypes.length && !directives.length) {
    return null;
  }
  const schemaNode = {
    kind: operationTypes != null ? Kind.SCHEMA_DEFINITION : Kind.SCHEMA_EXTENSION,
    operationTypes,
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives
  };
  schemaNode.description = ((_b = (_a = schema.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : schema.description != null) ? {
    kind: Kind.STRING,
    value: schema.description,
    block: true
  } : void 0;
  return schemaNode;
}
function astFromDirective(directive, schema, pathToDirectivesInExtensions) {
  var _a, _b, _c, _d;
  return {
    kind: Kind.DIRECTIVE_DEFINITION,
    description: (_b = (_a = directive.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : directive.description ? {
      kind: Kind.STRING,
      value: directive.description
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: directive.name
    },
    arguments: (_c = directive.args) === null || _c === void 0 ? void 0 : _c.map((arg) => astFromArg(arg, schema, pathToDirectivesInExtensions)),
    repeatable: directive.isRepeatable,
    locations: ((_d = directive.locations) === null || _d === void 0 ? void 0 : _d.map((location) => ({
      kind: Kind.NAME,
      value: location
    }))) || []
  };
}
function getDirectiveNodes(entity, schema, pathToDirectivesInExtensions) {
  const directivesInExtensions = getDirectivesInExtensions(entity, pathToDirectivesInExtensions);
  let nodes = [];
  if (entity.astNode != null) {
    nodes.push(entity.astNode);
  }
  if ("extensionASTNodes" in entity && entity.extensionASTNodes != null) {
    nodes = nodes.concat(entity.extensionASTNodes);
  }
  let directives;
  if (directivesInExtensions != null) {
    directives = makeDirectiveNodes(schema, directivesInExtensions);
  } else {
    directives = [];
    for (const node of nodes) {
      if (node.directives) {
        directives.push(...node.directives);
      }
    }
  }
  return directives;
}
function getDeprecatableDirectiveNodes(entity, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  let directiveNodesBesidesDeprecated = [];
  let deprecatedDirectiveNode = null;
  const directivesInExtensions = getDirectivesInExtensions(entity, pathToDirectivesInExtensions);
  let directives;
  if (directivesInExtensions != null) {
    directives = makeDirectiveNodes(schema, directivesInExtensions);
  } else {
    directives = (_a = entity.astNode) === null || _a === void 0 ? void 0 : _a.directives;
  }
  if (directives != null) {
    directiveNodesBesidesDeprecated = directives.filter((directive) => directive.name.value !== "deprecated");
    if (entity.deprecationReason != null) {
      deprecatedDirectiveNode = (_b = directives.filter((directive) => directive.name.value === "deprecated")) === null || _b === void 0 ? void 0 : _b[0];
    }
  }
  if (entity.deprecationReason != null && deprecatedDirectiveNode == null) {
    deprecatedDirectiveNode = makeDeprecatedDirective(entity.deprecationReason);
  }
  return deprecatedDirectiveNode == null ? directiveNodesBesidesDeprecated : [deprecatedDirectiveNode].concat(directiveNodesBesidesDeprecated);
}
function astFromArg(arg, schema, pathToDirectivesInExtensions) {
  var _a, _b, _c;
  return {
    kind: Kind.INPUT_VALUE_DEFINITION,
    description: (_b = (_a = arg.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : arg.description ? {
      kind: Kind.STRING,
      value: arg.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: arg.name
    },
    type: astFromType(arg.type),
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    defaultValue: arg.defaultValue !== void 0 ? (_c = astFromValue(arg.defaultValue, arg.type)) !== null && _c !== void 0 ? _c : void 0 : void 0,
    directives: getDeprecatableDirectiveNodes(arg, schema, pathToDirectivesInExtensions)
  };
}
function astFromObjectType(type2, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  return {
    kind: Kind.OBJECT_TYPE_DEFINITION,
    description: (_b = (_a = type2.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type2.description ? {
      kind: Kind.STRING,
      value: type2.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: type2.name
    },
    fields: Object.values(type2.getFields()).map((field) => astFromField(field, schema, pathToDirectivesInExtensions)),
    interfaces: Object.values(type2.getInterfaces()).map((iFace) => astFromType(iFace)),
    directives: getDirectiveNodes(type2, schema, pathToDirectivesInExtensions)
  };
}
function astFromInterfaceType(type2, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  const node = {
    kind: Kind.INTERFACE_TYPE_DEFINITION,
    description: (_b = (_a = type2.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type2.description ? {
      kind: Kind.STRING,
      value: type2.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: type2.name
    },
    fields: Object.values(type2.getFields()).map((field) => astFromField(field, schema, pathToDirectivesInExtensions)),
    directives: getDirectiveNodes(type2, schema, pathToDirectivesInExtensions)
  };
  if ("getInterfaces" in type2) {
    node.interfaces = Object.values(type2.getInterfaces()).map((iFace) => astFromType(iFace));
  }
  return node;
}
function astFromUnionType(type2, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  return {
    kind: Kind.UNION_TYPE_DEFINITION,
    description: (_b = (_a = type2.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type2.description ? {
      kind: Kind.STRING,
      value: type2.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: type2.name
    },
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives: getDirectiveNodes(type2, schema, pathToDirectivesInExtensions),
    types: type2.getTypes().map((type3) => astFromType(type3))
  };
}
function astFromInputObjectType(type2, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  return {
    kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
    description: (_b = (_a = type2.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type2.description ? {
      kind: Kind.STRING,
      value: type2.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: type2.name
    },
    fields: Object.values(type2.getFields()).map((field) => astFromInputField(field, schema, pathToDirectivesInExtensions)),
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives: getDirectiveNodes(type2, schema, pathToDirectivesInExtensions)
  };
}
function astFromEnumType(type2, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  return {
    kind: Kind.ENUM_TYPE_DEFINITION,
    description: (_b = (_a = type2.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type2.description ? {
      kind: Kind.STRING,
      value: type2.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: type2.name
    },
    values: Object.values(type2.getValues()).map((value) => astFromEnumValue(value, schema, pathToDirectivesInExtensions)),
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives: getDirectiveNodes(type2, schema, pathToDirectivesInExtensions)
  };
}
function astFromScalarType(type2, schema, pathToDirectivesInExtensions) {
  var _a, _b, _c;
  const directivesInExtensions = getDirectivesInExtensions(type2, pathToDirectivesInExtensions);
  const directives = directivesInExtensions ? makeDirectiveNodes(schema, directivesInExtensions) : ((_a = type2.astNode) === null || _a === void 0 ? void 0 : _a.directives) || [];
  const specifiedByValue = type2["specifiedByUrl"] || type2["specifiedByURL"];
  if (specifiedByValue && !directives.some((directiveNode) => directiveNode.name.value === "specifiedBy")) {
    const specifiedByArgs = {
      url: specifiedByValue
    };
    directives.push(makeDirectiveNode("specifiedBy", specifiedByArgs));
  }
  return {
    kind: Kind.SCALAR_TYPE_DEFINITION,
    description: (_c = (_b = type2.astNode) === null || _b === void 0 ? void 0 : _b.description) !== null && _c !== void 0 ? _c : type2.description ? {
      kind: Kind.STRING,
      value: type2.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: type2.name
    },
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives
  };
}
function astFromField(field, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  return {
    kind: Kind.FIELD_DEFINITION,
    description: (_b = (_a = field.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : field.description ? {
      kind: Kind.STRING,
      value: field.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: field.name
    },
    arguments: field.args.map((arg) => astFromArg(arg, schema, pathToDirectivesInExtensions)),
    type: astFromType(field.type),
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives: getDeprecatableDirectiveNodes(field, schema, pathToDirectivesInExtensions)
  };
}
function astFromInputField(field, schema, pathToDirectivesInExtensions) {
  var _a, _b, _c;
  return {
    kind: Kind.INPUT_VALUE_DEFINITION,
    description: (_b = (_a = field.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : field.description ? {
      kind: Kind.STRING,
      value: field.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: field.name
    },
    type: astFromType(field.type),
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives: getDeprecatableDirectiveNodes(field, schema, pathToDirectivesInExtensions),
    defaultValue: (_c = astFromValue(field.defaultValue, field.type)) !== null && _c !== void 0 ? _c : void 0
  };
}
function astFromEnumValue(value, schema, pathToDirectivesInExtensions) {
  var _a, _b;
  return {
    kind: Kind.ENUM_VALUE_DEFINITION,
    description: (_b = (_a = value.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : value.description ? {
      kind: Kind.STRING,
      value: value.description,
      block: true
    } : void 0,
    name: {
      kind: Kind.NAME,
      value: value.name
    },
    // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
    directives: getDeprecatableDirectiveNodes(value, schema, pathToDirectivesInExtensions)
  };
}
function makeDeprecatedDirective(deprecationReason) {
  return makeDirectiveNode("deprecated", { reason: deprecationReason }, GraphQLDeprecatedDirective);
}
function makeDirectiveNode(name2, args, directive) {
  const directiveArguments = [];
  if (directive != null) {
    for (const arg of directive.args) {
      const argName = arg.name;
      const argValue = args[argName];
      if (argValue !== void 0) {
        const value = astFromValue(argValue, arg.type);
        if (value) {
          directiveArguments.push({
            kind: Kind.ARGUMENT,
            name: {
              kind: Kind.NAME,
              value: argName
            },
            value
          });
        }
      }
    }
  } else {
    for (const argName in args) {
      const argValue = args[argName];
      const value = astFromValueUntyped(argValue);
      if (value) {
        directiveArguments.push({
          kind: Kind.ARGUMENT,
          name: {
            kind: Kind.NAME,
            value: argName
          },
          value
        });
      }
    }
  }
  return {
    kind: Kind.DIRECTIVE,
    name: {
      kind: Kind.NAME,
      value: name2
    },
    arguments: directiveArguments
  };
}
function makeDirectiveNodes(schema, directiveValues) {
  const directiveNodes = [];
  for (const directiveName in directiveValues) {
    const arrayOrSingleValue = directiveValues[directiveName];
    const directive = schema === null || schema === void 0 ? void 0 : schema.getDirective(directiveName);
    if (Array.isArray(arrayOrSingleValue)) {
      for (const value of arrayOrSingleValue) {
        directiveNodes.push(makeDirectiveNode(directiveName, value, directive));
      }
    } else {
      directiveNodes.push(makeDirectiveNode(directiveName, arrayOrSingleValue, directive));
    }
  }
  return directiveNodes;
}
const MAX_LINE_LENGTH = 80;
let commentsRegistry = {};
function resetComments() {
  commentsRegistry = {};
}
function collectComment(node) {
  var _a;
  const entityName = (_a = node.name) === null || _a === void 0 ? void 0 : _a.value;
  if (entityName == null) {
    return;
  }
  pushComment(node, entityName);
  switch (node.kind) {
    case "EnumTypeDefinition":
      if (node.values) {
        for (const value of node.values) {
          pushComment(value, entityName, value.name.value);
        }
      }
      break;
    case "ObjectTypeDefinition":
    case "InputObjectTypeDefinition":
    case "InterfaceTypeDefinition":
      if (node.fields) {
        for (const field of node.fields) {
          pushComment(field, entityName, field.name.value);
          if (isFieldDefinitionNode(field) && field.arguments) {
            for (const arg of field.arguments) {
              pushComment(arg, entityName, field.name.value, arg.name.value);
            }
          }
        }
      }
      break;
  }
}
function pushComment(node, entity, field, argument) {
  const comment = getComment(node);
  if (typeof comment !== "string" || comment.length === 0) {
    return;
  }
  const keys = [entity];
  if (field) {
    keys.push(field);
    if (argument) {
      keys.push(argument);
    }
  }
  const path = keys.join(".");
  if (!commentsRegistry[path]) {
    commentsRegistry[path] = [];
  }
  commentsRegistry[path].push(comment);
}
function printComment(comment) {
  return "\n# " + comment.replace(/\n/g, "\n# ");
}
function join(maybeArray, separator) {
  return maybeArray ? maybeArray.filter((x) => x).join(separator || "") : "";
}
function hasMultilineItems(maybeArray) {
  var _a;
  return (_a = maybeArray === null || maybeArray === void 0 ? void 0 : maybeArray.some((str) => str.includes("\n"))) !== null && _a !== void 0 ? _a : false;
}
function addDescription(cb) {
  return (node, _key, _parent, path, ancestors) => {
    var _a;
    const keys = [];
    const parent = path.reduce((prev, key2) => {
      if (["fields", "arguments", "values"].includes(key2) && prev.name) {
        keys.push(prev.name.value);
      }
      return prev[key2];
    }, ancestors[0]);
    const key = [...keys, (_a = parent === null || parent === void 0 ? void 0 : parent.name) === null || _a === void 0 ? void 0 : _a.value].filter(Boolean).join(".");
    const items2 = [];
    if (node.kind.includes("Definition") && commentsRegistry[key]) {
      items2.push(...commentsRegistry[key]);
    }
    return join([...items2.map(printComment), node.description, cb(node, _key, _parent, path, ancestors)], "\n");
  };
}
function indent(maybeString) {
  return maybeString && `  ${maybeString.replace(/\n/g, "\n  ")}`;
}
function block(array) {
  return array && array.length !== 0 ? `{
${indent(join(array, "\n"))}
}` : "";
}
function wrap(start, maybeString, end) {
  return maybeString ? start + maybeString + (end || "") : "";
}
function printBlockString(value, isDescription = false) {
  const escaped = value.replace(/"""/g, '\\"""');
  return (value[0] === " " || value[0] === "	") && value.indexOf("\n") === -1 ? `"""${escaped.replace(/"$/, '"\n')}"""` : `"""
${isDescription ? escaped : indent(escaped)}
"""`;
}
const printDocASTReducer = {
  Name: { leave: (node) => node.value },
  Variable: { leave: (node) => "$" + node.name },
  // Document
  Document: {
    leave: (node) => join(node.definitions, "\n\n")
  },
  OperationDefinition: {
    leave: (node) => {
      const varDefs = wrap("(", join(node.variableDefinitions, ", "), ")");
      const prefix = join([node.operation, join([node.name, varDefs]), join(node.directives, " ")], " ");
      return prefix + " " + node.selectionSet;
    }
  },
  VariableDefinition: {
    leave: ({ variable, type: type2, defaultValue, directives }) => variable + ": " + type2 + wrap(" = ", defaultValue) + wrap(" ", join(directives, " "))
  },
  SelectionSet: { leave: ({ selections }) => block(selections) },
  Field: {
    leave({ alias, name: name2, arguments: args, directives, selectionSet }) {
      const prefix = wrap("", alias, ": ") + name2;
      let argsLine = prefix + wrap("(", join(args, ", "), ")");
      if (argsLine.length > MAX_LINE_LENGTH) {
        argsLine = prefix + wrap("(\n", indent(join(args, "\n")), "\n)");
      }
      return join([argsLine, join(directives, " "), selectionSet], " ");
    }
  },
  Argument: { leave: ({ name: name2, value }) => name2 + ": " + value },
  // Fragments
  FragmentSpread: {
    leave: ({ name: name2, directives }) => "..." + name2 + wrap(" ", join(directives, " "))
  },
  InlineFragment: {
    leave: ({ typeCondition, directives, selectionSet }) => join(["...", wrap("on ", typeCondition), join(directives, " "), selectionSet], " ")
  },
  FragmentDefinition: {
    leave: ({ name: name2, typeCondition, variableDefinitions, directives, selectionSet }) => (
      // Note: fragment variable definitions are experimental and may be changed
      // or removed in the future.
      `fragment ${name2}${wrap("(", join(variableDefinitions, ", "), ")")} on ${typeCondition} ${wrap("", join(directives, " "), " ")}` + selectionSet
    )
  },
  // Value
  IntValue: { leave: ({ value }) => value },
  FloatValue: { leave: ({ value }) => value },
  StringValue: {
    leave: ({ value, block: isBlockString }) => {
      if (isBlockString) {
        return printBlockString(value);
      }
      return JSON.stringify(value);
    }
  },
  BooleanValue: { leave: ({ value }) => value ? "true" : "false" },
  NullValue: { leave: () => "null" },
  EnumValue: { leave: ({ value }) => value },
  ListValue: { leave: ({ values }) => "[" + join(values, ", ") + "]" },
  ObjectValue: { leave: ({ fields }) => "{" + join(fields, ", ") + "}" },
  ObjectField: { leave: ({ name: name2, value }) => name2 + ": " + value },
  // Directive
  Directive: {
    leave: ({ name: name2, arguments: args }) => "@" + name2 + wrap("(", join(args, ", "), ")")
  },
  // Type
  NamedType: { leave: ({ name: name2 }) => name2 },
  ListType: { leave: ({ type: type2 }) => "[" + type2 + "]" },
  NonNullType: { leave: ({ type: type2 }) => type2 + "!" },
  // Type System Definitions
  SchemaDefinition: {
    leave: ({ directives, operationTypes }) => join(["schema", join(directives, " "), block(operationTypes)], " ")
  },
  OperationTypeDefinition: {
    leave: ({ operation, type: type2 }) => operation + ": " + type2
  },
  ScalarTypeDefinition: {
    leave: ({ name: name2, directives }) => join(["scalar", name2, join(directives, " ")], " ")
  },
  ObjectTypeDefinition: {
    leave: ({ name: name2, interfaces, directives, fields }) => join(["type", name2, wrap("implements ", join(interfaces, " & ")), join(directives, " "), block(fields)], " ")
  },
  FieldDefinition: {
    leave: ({ name: name2, arguments: args, type: type2, directives }) => name2 + (hasMultilineItems(args) ? wrap("(\n", indent(join(args, "\n")), "\n)") : wrap("(", join(args, ", "), ")")) + ": " + type2 + wrap(" ", join(directives, " "))
  },
  InputValueDefinition: {
    leave: ({ name: name2, type: type2, defaultValue, directives }) => join([name2 + ": " + type2, wrap("= ", defaultValue), join(directives, " ")], " ")
  },
  InterfaceTypeDefinition: {
    leave: ({ name: name2, interfaces, directives, fields }) => join(["interface", name2, wrap("implements ", join(interfaces, " & ")), join(directives, " "), block(fields)], " ")
  },
  UnionTypeDefinition: {
    leave: ({ name: name2, directives, types: types2 }) => join(["union", name2, join(directives, " "), wrap("= ", join(types2, " | "))], " ")
  },
  EnumTypeDefinition: {
    leave: ({ name: name2, directives, values }) => join(["enum", name2, join(directives, " "), block(values)], " ")
  },
  EnumValueDefinition: {
    leave: ({ name: name2, directives }) => join([name2, join(directives, " ")], " ")
  },
  InputObjectTypeDefinition: {
    leave: ({ name: name2, directives, fields }) => join(["input", name2, join(directives, " "), block(fields)], " ")
  },
  DirectiveDefinition: {
    leave: ({ name: name2, arguments: args, repeatable, locations }) => "directive @" + name2 + (hasMultilineItems(args) ? wrap("(\n", indent(join(args, "\n")), "\n)") : wrap("(", join(args, ", "), ")")) + (repeatable ? " repeatable" : "") + " on " + join(locations, " | ")
  },
  SchemaExtension: {
    leave: ({ directives, operationTypes }) => join(["extend schema", join(directives, " "), block(operationTypes)], " ")
  },
  ScalarTypeExtension: {
    leave: ({ name: name2, directives }) => join(["extend scalar", name2, join(directives, " ")], " ")
  },
  ObjectTypeExtension: {
    leave: ({ name: name2, interfaces, directives, fields }) => join(["extend type", name2, wrap("implements ", join(interfaces, " & ")), join(directives, " "), block(fields)], " ")
  },
  InterfaceTypeExtension: {
    leave: ({ name: name2, interfaces, directives, fields }) => join(["extend interface", name2, wrap("implements ", join(interfaces, " & ")), join(directives, " "), block(fields)], " ")
  },
  UnionTypeExtension: {
    leave: ({ name: name2, directives, types: types2 }) => join(["extend union", name2, join(directives, " "), wrap("= ", join(types2, " | "))], " ")
  },
  EnumTypeExtension: {
    leave: ({ name: name2, directives, values }) => join(["extend enum", name2, join(directives, " "), block(values)], " ")
  },
  InputObjectTypeExtension: {
    leave: ({ name: name2, directives, fields }) => join(["extend input", name2, join(directives, " "), block(fields)], " ")
  }
};
const printDocASTReducerWithComments = Object.keys(printDocASTReducer).reduce((prev, key) => ({
  ...prev,
  [key]: {
    leave: addDescription(printDocASTReducer[key].leave)
  }
}), {});
function printWithComments(ast) {
  return visit(ast, printDocASTReducerWithComments);
}
function isFieldDefinitionNode(node) {
  return node.kind === "FieldDefinition";
}
function getComment(node) {
  const rawValue = getLeadingCommentBlock(node);
  if (rawValue !== void 0) {
    return dedentBlockStringValue(`
${rawValue}`);
  }
}
function getLeadingCommentBlock(node) {
  const loc = node.loc;
  if (!loc) {
    return;
  }
  const comments = [];
  let token = loc.startToken.prev;
  while (token != null && token.kind === TokenKind.COMMENT && token.next != null && token.prev != null && token.line + 1 === token.next.line && token.line !== token.prev.line) {
    const value = String(token.value);
    comments.push(value);
    token = token.prev;
  }
  return comments.length > 0 ? comments.reverse().join("\n") : void 0;
}
function dedentBlockStringValue(rawString) {
  const lines = rawString.split(/\r\n|[\n\r]/g);
  const commonIndent = getBlockStringIndentation(lines);
  if (commonIndent !== 0) {
    for (let i = 1; i < lines.length; i++) {
      lines[i] = lines[i].slice(commonIndent);
    }
  }
  while (lines.length > 0 && isBlank(lines[0])) {
    lines.shift();
  }
  while (lines.length > 0 && isBlank(lines[lines.length - 1])) {
    lines.pop();
  }
  return lines.join("\n");
}
function getBlockStringIndentation(lines) {
  let commonIndent = null;
  for (let i = 1; i < lines.length; i++) {
    const line = lines[i];
    const indent2 = leadingWhitespace(line);
    if (indent2 === line.length) {
      continue;
    }
    if (commonIndent === null || indent2 < commonIndent) {
      commonIndent = indent2;
      if (commonIndent === 0) {
        break;
      }
    }
  }
  return commonIndent === null ? 0 : commonIndent;
}
function leadingWhitespace(str) {
  let i = 0;
  while (i < str.length && (str[i] === " " || str[i] === "	")) {
    i++;
  }
  return i;
}
function isBlank(str) {
  return leadingWhitespace(str) === str.length;
}
var MapperKind;
(function(MapperKind2) {
  MapperKind2["TYPE"] = "MapperKind.TYPE";
  MapperKind2["SCALAR_TYPE"] = "MapperKind.SCALAR_TYPE";
  MapperKind2["ENUM_TYPE"] = "MapperKind.ENUM_TYPE";
  MapperKind2["COMPOSITE_TYPE"] = "MapperKind.COMPOSITE_TYPE";
  MapperKind2["OBJECT_TYPE"] = "MapperKind.OBJECT_TYPE";
  MapperKind2["INPUT_OBJECT_TYPE"] = "MapperKind.INPUT_OBJECT_TYPE";
  MapperKind2["ABSTRACT_TYPE"] = "MapperKind.ABSTRACT_TYPE";
  MapperKind2["UNION_TYPE"] = "MapperKind.UNION_TYPE";
  MapperKind2["INTERFACE_TYPE"] = "MapperKind.INTERFACE_TYPE";
  MapperKind2["ROOT_OBJECT"] = "MapperKind.ROOT_OBJECT";
  MapperKind2["QUERY"] = "MapperKind.QUERY";
  MapperKind2["MUTATION"] = "MapperKind.MUTATION";
  MapperKind2["SUBSCRIPTION"] = "MapperKind.SUBSCRIPTION";
  MapperKind2["DIRECTIVE"] = "MapperKind.DIRECTIVE";
  MapperKind2["FIELD"] = "MapperKind.FIELD";
  MapperKind2["COMPOSITE_FIELD"] = "MapperKind.COMPOSITE_FIELD";
  MapperKind2["OBJECT_FIELD"] = "MapperKind.OBJECT_FIELD";
  MapperKind2["ROOT_FIELD"] = "MapperKind.ROOT_FIELD";
  MapperKind2["QUERY_ROOT_FIELD"] = "MapperKind.QUERY_ROOT_FIELD";
  MapperKind2["MUTATION_ROOT_FIELD"] = "MapperKind.MUTATION_ROOT_FIELD";
  MapperKind2["SUBSCRIPTION_ROOT_FIELD"] = "MapperKind.SUBSCRIPTION_ROOT_FIELD";
  MapperKind2["INTERFACE_FIELD"] = "MapperKind.INTERFACE_FIELD";
  MapperKind2["INPUT_OBJECT_FIELD"] = "MapperKind.INPUT_OBJECT_FIELD";
  MapperKind2["ARGUMENT"] = "MapperKind.ARGUMENT";
  MapperKind2["ENUM_VALUE"] = "MapperKind.ENUM_VALUE";
})(MapperKind || (MapperKind = {}));
function getObjectTypeFromTypeMap(typeMap, type2) {
  if (type2) {
    const maybeObjectType = typeMap[type2.name];
    if (isObjectType(maybeObjectType)) {
      return maybeObjectType;
    }
  }
}
function isNamedStub(type2) {
  if ("getFields" in type2) {
    const fields = type2.getFields();
    for (const fieldName in fields) {
      const field = fields[fieldName];
      return field.name === "_fake";
    }
  }
  return false;
}
function getBuiltInForStub(type2) {
  switch (type2.name) {
    case GraphQLInt.name:
      return GraphQLInt;
    case GraphQLFloat.name:
      return GraphQLFloat;
    case GraphQLString.name:
      return GraphQLString;
    case GraphQLBoolean.name:
      return GraphQLBoolean;
    case GraphQLID.name:
      return GraphQLID;
    default:
      return type2;
  }
}
function rewireTypes(originalTypeMap, directives) {
  const referenceTypeMap = /* @__PURE__ */ Object.create(null);
  for (const typeName in originalTypeMap) {
    referenceTypeMap[typeName] = originalTypeMap[typeName];
  }
  const newTypeMap = /* @__PURE__ */ Object.create(null);
  for (const typeName in referenceTypeMap) {
    const namedType = referenceTypeMap[typeName];
    if (namedType == null || typeName.startsWith("__")) {
      continue;
    }
    const newName = namedType.name;
    if (newName.startsWith("__")) {
      continue;
    }
    if (newTypeMap[newName] != null) {
      console.warn(`Duplicate schema type name ${newName} found; keeping the existing one found in the schema`);
      continue;
    }
    newTypeMap[newName] = namedType;
  }
  for (const typeName in newTypeMap) {
    newTypeMap[typeName] = rewireNamedType(newTypeMap[typeName]);
  }
  const newDirectives = directives.map((directive) => rewireDirective(directive));
  return {
    typeMap: newTypeMap,
    directives: newDirectives
  };
  function rewireDirective(directive) {
    if (isSpecifiedDirective(directive)) {
      return directive;
    }
    const directiveConfig = directive.toConfig();
    directiveConfig.args = rewireArgs(directiveConfig.args);
    return new GraphQLDirective(directiveConfig);
  }
  function rewireArgs(args) {
    const rewiredArgs = {};
    for (const argName in args) {
      const arg = args[argName];
      const rewiredArgType = rewireType(arg.type);
      if (rewiredArgType != null) {
        arg.type = rewiredArgType;
        rewiredArgs[argName] = arg;
      }
    }
    return rewiredArgs;
  }
  function rewireNamedType(type2) {
    if (isObjectType(type2)) {
      const config = type2.toConfig();
      const newConfig = {
        ...config,
        fields: () => rewireFields(config.fields),
        interfaces: () => rewireNamedTypes(config.interfaces)
      };
      return new GraphQLObjectType(newConfig);
    } else if (isInterfaceType(type2)) {
      const config = type2.toConfig();
      const newConfig = {
        ...config,
        fields: () => rewireFields(config.fields)
      };
      if ("interfaces" in newConfig) {
        newConfig.interfaces = () => rewireNamedTypes(config.interfaces);
      }
      return new GraphQLInterfaceType(newConfig);
    } else if (isUnionType(type2)) {
      const config = type2.toConfig();
      const newConfig = {
        ...config,
        types: () => rewireNamedTypes(config.types)
      };
      return new GraphQLUnionType(newConfig);
    } else if (isInputObjectType(type2)) {
      const config = type2.toConfig();
      const newConfig = {
        ...config,
        fields: () => rewireInputFields(config.fields)
      };
      return new GraphQLInputObjectType(newConfig);
    } else if (isEnumType(type2)) {
      const enumConfig = type2.toConfig();
      return new GraphQLEnumType(enumConfig);
    } else if (isScalarType(type2)) {
      if (isSpecifiedScalarType(type2)) {
        return type2;
      }
      const scalarConfig = type2.toConfig();
      return new GraphQLScalarType(scalarConfig);
    }
    throw new Error(`Unexpected schema type: ${type2}`);
  }
  function rewireFields(fields) {
    const rewiredFields = {};
    for (const fieldName in fields) {
      const field = fields[fieldName];
      const rewiredFieldType = rewireType(field.type);
      if (rewiredFieldType != null && field.args) {
        field.type = rewiredFieldType;
        field.args = rewireArgs(field.args);
        rewiredFields[fieldName] = field;
      }
    }
    return rewiredFields;
  }
  function rewireInputFields(fields) {
    const rewiredFields = {};
    for (const fieldName in fields) {
      const field = fields[fieldName];
      const rewiredFieldType = rewireType(field.type);
      if (rewiredFieldType != null) {
        field.type = rewiredFieldType;
        rewiredFields[fieldName] = field;
      }
    }
    return rewiredFields;
  }
  function rewireNamedTypes(namedTypes) {
    const rewiredTypes = [];
    for (const namedType of namedTypes) {
      const rewiredType = rewireType(namedType);
      if (rewiredType != null) {
        rewiredTypes.push(rewiredType);
      }
    }
    return rewiredTypes;
  }
  function rewireType(type2) {
    if (isListType(type2)) {
      const rewiredType = rewireType(type2.ofType);
      return rewiredType != null ? new GraphQLList(rewiredType) : null;
    } else if (isNonNullType(type2)) {
      const rewiredType = rewireType(type2.ofType);
      return rewiredType != null ? new GraphQLNonNull(rewiredType) : null;
    } else if (isNamedType(type2)) {
      let rewiredType = referenceTypeMap[type2.name];
      if (rewiredType === void 0) {
        rewiredType = isNamedStub(type2) ? getBuiltInForStub(type2) : rewireNamedType(type2);
        newTypeMap[rewiredType.name] = referenceTypeMap[type2.name] = rewiredType;
      }
      return rewiredType != null ? newTypeMap[rewiredType.name] : null;
    }
    return null;
  }
}
function transformInputValue(type2, value, inputLeafValueTransformer = null, inputObjectValueTransformer = null) {
  if (value == null) {
    return value;
  }
  const nullableType = getNullableType(type2);
  if (isLeafType(nullableType)) {
    return inputLeafValueTransformer != null ? inputLeafValueTransformer(nullableType, value) : value;
  } else if (isListType(nullableType)) {
    return asArray(value).map((listMember) => transformInputValue(nullableType.ofType, listMember, inputLeafValueTransformer, inputObjectValueTransformer));
  } else if (isInputObjectType(nullableType)) {
    const fields = nullableType.getFields();
    const newValue = {};
    for (const key in value) {
      const field = fields[key];
      if (field != null) {
        newValue[key] = transformInputValue(field.type, value[key], inputLeafValueTransformer, inputObjectValueTransformer);
      }
    }
    return inputObjectValueTransformer != null ? inputObjectValueTransformer(nullableType, newValue) : newValue;
  }
}
function serializeInputValue(type2, value) {
  return transformInputValue(type2, value, (t, v) => {
    try {
      return t.serialize(v);
    } catch (_a) {
      return v;
    }
  });
}
function parseInputValue(type2, value) {
  return transformInputValue(type2, value, (t, v) => {
    try {
      return t.parseValue(v);
    } catch (_a) {
      return v;
    }
  });
}
function mapSchema(schema, schemaMapper = {}) {
  const newTypeMap = mapArguments(mapFields(mapTypes(mapDefaultValues(mapEnumValues(mapTypes(mapDefaultValues(schema.getTypeMap(), schema, serializeInputValue), schema, schemaMapper, (type2) => isLeafType(type2)), schema, schemaMapper), schema, parseInputValue), schema, schemaMapper, (type2) => !isLeafType(type2)), schema, schemaMapper), schema, schemaMapper);
  const originalDirectives = schema.getDirectives();
  const newDirectives = mapDirectives(originalDirectives, schema, schemaMapper);
  const { typeMap, directives } = rewireTypes(newTypeMap, newDirectives);
  return new GraphQLSchema({
    ...schema.toConfig(),
    query: getObjectTypeFromTypeMap(typeMap, getObjectTypeFromTypeMap(newTypeMap, schema.getQueryType())),
    mutation: getObjectTypeFromTypeMap(typeMap, getObjectTypeFromTypeMap(newTypeMap, schema.getMutationType())),
    subscription: getObjectTypeFromTypeMap(typeMap, getObjectTypeFromTypeMap(newTypeMap, schema.getSubscriptionType())),
    types: Object.values(typeMap),
    directives
  });
}
function mapTypes(originalTypeMap, schema, schemaMapper, testFn = () => true) {
  const newTypeMap = {};
  for (const typeName in originalTypeMap) {
    if (!typeName.startsWith("__")) {
      const originalType = originalTypeMap[typeName];
      if (originalType == null || !testFn(originalType)) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      const typeMapper = getTypeMapper(schema, schemaMapper, typeName);
      if (typeMapper == null) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      const maybeNewType = typeMapper(originalType, schema);
      if (maybeNewType === void 0) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      newTypeMap[typeName] = maybeNewType;
    }
  }
  return newTypeMap;
}
function mapEnumValues(originalTypeMap, schema, schemaMapper) {
  const enumValueMapper = getEnumValueMapper(schemaMapper);
  if (!enumValueMapper) {
    return originalTypeMap;
  }
  return mapTypes(originalTypeMap, schema, {
    [MapperKind.ENUM_TYPE]: (type2) => {
      const config = type2.toConfig();
      const originalEnumValueConfigMap = config.values;
      const newEnumValueConfigMap = {};
      for (const externalValue in originalEnumValueConfigMap) {
        const originalEnumValueConfig = originalEnumValueConfigMap[externalValue];
        const mappedEnumValue = enumValueMapper(originalEnumValueConfig, type2.name, schema, externalValue);
        if (mappedEnumValue === void 0) {
          newEnumValueConfigMap[externalValue] = originalEnumValueConfig;
        } else if (Array.isArray(mappedEnumValue)) {
          const [newExternalValue, newEnumValueConfig] = mappedEnumValue;
          newEnumValueConfigMap[newExternalValue] = newEnumValueConfig === void 0 ? originalEnumValueConfig : newEnumValueConfig;
        } else if (mappedEnumValue !== null) {
          newEnumValueConfigMap[externalValue] = mappedEnumValue;
        }
      }
      return correctASTNodes(new GraphQLEnumType({
        ...config,
        values: newEnumValueConfigMap
      }));
    }
  }, (type2) => isEnumType(type2));
}
function mapDefaultValues(originalTypeMap, schema, fn) {
  const newTypeMap = mapArguments(originalTypeMap, schema, {
    [MapperKind.ARGUMENT]: (argumentConfig) => {
      if (argumentConfig.defaultValue === void 0) {
        return argumentConfig;
      }
      const maybeNewType = getNewType(originalTypeMap, argumentConfig.type);
      if (maybeNewType != null) {
        return {
          ...argumentConfig,
          defaultValue: fn(maybeNewType, argumentConfig.defaultValue)
        };
      }
    }
  });
  return mapFields(newTypeMap, schema, {
    [MapperKind.INPUT_OBJECT_FIELD]: (inputFieldConfig) => {
      if (inputFieldConfig.defaultValue === void 0) {
        return inputFieldConfig;
      }
      const maybeNewType = getNewType(newTypeMap, inputFieldConfig.type);
      if (maybeNewType != null) {
        return {
          ...inputFieldConfig,
          defaultValue: fn(maybeNewType, inputFieldConfig.defaultValue)
        };
      }
    }
  });
}
function getNewType(newTypeMap, type2) {
  if (isListType(type2)) {
    const newType = getNewType(newTypeMap, type2.ofType);
    return newType != null ? new GraphQLList(newType) : null;
  } else if (isNonNullType(type2)) {
    const newType = getNewType(newTypeMap, type2.ofType);
    return newType != null ? new GraphQLNonNull(newType) : null;
  } else if (isNamedType(type2)) {
    const newType = newTypeMap[type2.name];
    return newType != null ? newType : null;
  }
  return null;
}
function mapFields(originalTypeMap, schema, schemaMapper) {
  const newTypeMap = {};
  for (const typeName in originalTypeMap) {
    if (!typeName.startsWith("__")) {
      const originalType = originalTypeMap[typeName];
      if (!isObjectType(originalType) && !isInterfaceType(originalType) && !isInputObjectType(originalType)) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      const fieldMapper = getFieldMapper(schema, schemaMapper, typeName);
      if (fieldMapper == null) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      const config = originalType.toConfig();
      const originalFieldConfigMap = config.fields;
      const newFieldConfigMap = {};
      for (const fieldName in originalFieldConfigMap) {
        const originalFieldConfig = originalFieldConfigMap[fieldName];
        const mappedField = fieldMapper(originalFieldConfig, fieldName, typeName, schema);
        if (mappedField === void 0) {
          newFieldConfigMap[fieldName] = originalFieldConfig;
        } else if (Array.isArray(mappedField)) {
          const [newFieldName, newFieldConfig] = mappedField;
          if (newFieldConfig.astNode != null) {
            newFieldConfig.astNode = {
              ...newFieldConfig.astNode,
              name: {
                ...newFieldConfig.astNode.name,
                value: newFieldName
              }
            };
          }
          newFieldConfigMap[newFieldName] = newFieldConfig === void 0 ? originalFieldConfig : newFieldConfig;
        } else if (mappedField !== null) {
          newFieldConfigMap[fieldName] = mappedField;
        }
      }
      if (isObjectType(originalType)) {
        newTypeMap[typeName] = correctASTNodes(new GraphQLObjectType({
          ...config,
          fields: newFieldConfigMap
        }));
      } else if (isInterfaceType(originalType)) {
        newTypeMap[typeName] = correctASTNodes(new GraphQLInterfaceType({
          ...config,
          fields: newFieldConfigMap
        }));
      } else {
        newTypeMap[typeName] = correctASTNodes(new GraphQLInputObjectType({
          ...config,
          fields: newFieldConfigMap
        }));
      }
    }
  }
  return newTypeMap;
}
function mapArguments(originalTypeMap, schema, schemaMapper) {
  const newTypeMap = {};
  for (const typeName in originalTypeMap) {
    if (!typeName.startsWith("__")) {
      const originalType = originalTypeMap[typeName];
      if (!isObjectType(originalType) && !isInterfaceType(originalType)) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      const argumentMapper = getArgumentMapper(schemaMapper);
      if (argumentMapper == null) {
        newTypeMap[typeName] = originalType;
        continue;
      }
      const config = originalType.toConfig();
      const originalFieldConfigMap = config.fields;
      const newFieldConfigMap = {};
      for (const fieldName in originalFieldConfigMap) {
        const originalFieldConfig = originalFieldConfigMap[fieldName];
        const originalArgumentConfigMap = originalFieldConfig.args;
        if (originalArgumentConfigMap == null) {
          newFieldConfigMap[fieldName] = originalFieldConfig;
          continue;
        }
        const argumentNames = Object.keys(originalArgumentConfigMap);
        if (!argumentNames.length) {
          newFieldConfigMap[fieldName] = originalFieldConfig;
          continue;
        }
        const newArgumentConfigMap = {};
        for (const argumentName of argumentNames) {
          const originalArgumentConfig = originalArgumentConfigMap[argumentName];
          const mappedArgument = argumentMapper(originalArgumentConfig, fieldName, typeName, schema);
          if (mappedArgument === void 0) {
            newArgumentConfigMap[argumentName] = originalArgumentConfig;
          } else if (Array.isArray(mappedArgument)) {
            const [newArgumentName, newArgumentConfig] = mappedArgument;
            newArgumentConfigMap[newArgumentName] = newArgumentConfig;
          } else if (mappedArgument !== null) {
            newArgumentConfigMap[argumentName] = mappedArgument;
          }
        }
        newFieldConfigMap[fieldName] = {
          ...originalFieldConfig,
          args: newArgumentConfigMap
        };
      }
      if (isObjectType(originalType)) {
        newTypeMap[typeName] = new GraphQLObjectType({
          ...config,
          fields: newFieldConfigMap
        });
      } else if (isInterfaceType(originalType)) {
        newTypeMap[typeName] = new GraphQLInterfaceType({
          ...config,
          fields: newFieldConfigMap
        });
      } else {
        newTypeMap[typeName] = new GraphQLInputObjectType({
          ...config,
          fields: newFieldConfigMap
        });
      }
    }
  }
  return newTypeMap;
}
function mapDirectives(originalDirectives, schema, schemaMapper) {
  const directiveMapper = getDirectiveMapper(schemaMapper);
  if (directiveMapper == null) {
    return originalDirectives.slice();
  }
  const newDirectives = [];
  for (const directive of originalDirectives) {
    const mappedDirective = directiveMapper(directive, schema);
    if (mappedDirective === void 0) {
      newDirectives.push(directive);
    } else if (mappedDirective !== null) {
      newDirectives.push(mappedDirective);
    }
  }
  return newDirectives;
}
function getTypeSpecifiers(schema, typeName) {
  var _a, _b, _c;
  const type2 = schema.getType(typeName);
  const specifiers = [MapperKind.TYPE];
  if (isObjectType(type2)) {
    specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.OBJECT_TYPE);
    if (typeName === ((_a = schema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name)) {
      specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.QUERY);
    } else if (typeName === ((_b = schema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name)) {
      specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.MUTATION);
    } else if (typeName === ((_c = schema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name)) {
      specifiers.push(MapperKind.ROOT_OBJECT, MapperKind.SUBSCRIPTION);
    }
  } else if (isInputObjectType(type2)) {
    specifiers.push(MapperKind.INPUT_OBJECT_TYPE);
  } else if (isInterfaceType(type2)) {
    specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.INTERFACE_TYPE);
  } else if (isUnionType(type2)) {
    specifiers.push(MapperKind.COMPOSITE_TYPE, MapperKind.ABSTRACT_TYPE, MapperKind.UNION_TYPE);
  } else if (isEnumType(type2)) {
    specifiers.push(MapperKind.ENUM_TYPE);
  } else if (isScalarType(type2)) {
    specifiers.push(MapperKind.SCALAR_TYPE);
  }
  return specifiers;
}
function getTypeMapper(schema, schemaMapper, typeName) {
  const specifiers = getTypeSpecifiers(schema, typeName);
  let typeMapper;
  const stack = [...specifiers];
  while (!typeMapper && stack.length > 0) {
    const next = stack.pop();
    typeMapper = schemaMapper[next];
  }
  return typeMapper != null ? typeMapper : null;
}
function getFieldSpecifiers(schema, typeName) {
  var _a, _b, _c;
  const type2 = schema.getType(typeName);
  const specifiers = [MapperKind.FIELD];
  if (isObjectType(type2)) {
    specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.OBJECT_FIELD);
    if (typeName === ((_a = schema.getQueryType()) === null || _a === void 0 ? void 0 : _a.name)) {
      specifiers.push(MapperKind.ROOT_FIELD, MapperKind.QUERY_ROOT_FIELD);
    } else if (typeName === ((_b = schema.getMutationType()) === null || _b === void 0 ? void 0 : _b.name)) {
      specifiers.push(MapperKind.ROOT_FIELD, MapperKind.MUTATION_ROOT_FIELD);
    } else if (typeName === ((_c = schema.getSubscriptionType()) === null || _c === void 0 ? void 0 : _c.name)) {
      specifiers.push(MapperKind.ROOT_FIELD, MapperKind.SUBSCRIPTION_ROOT_FIELD);
    }
  } else if (isInterfaceType(type2)) {
    specifiers.push(MapperKind.COMPOSITE_FIELD, MapperKind.INTERFACE_FIELD);
  } else if (isInputObjectType(type2)) {
    specifiers.push(MapperKind.INPUT_OBJECT_FIELD);
  }
  return specifiers;
}
function getFieldMapper(schema, schemaMapper, typeName) {
  const specifiers = getFieldSpecifiers(schema, typeName);
  let fieldMapper;
  const stack = [...specifiers];
  while (!fieldMapper && stack.length > 0) {
    const next = stack.pop();
    fieldMapper = schemaMapper[next];
  }
  return fieldMapper !== null && fieldMapper !== void 0 ? fieldMapper : null;
}
function getArgumentMapper(schemaMapper) {
  const argumentMapper = schemaMapper[MapperKind.ARGUMENT];
  return argumentMapper != null ? argumentMapper : null;
}
function getDirectiveMapper(schemaMapper) {
  const directiveMapper = schemaMapper[MapperKind.DIRECTIVE];
  return directiveMapper != null ? directiveMapper : null;
}
function getEnumValueMapper(schemaMapper) {
  const enumValueMapper = schemaMapper[MapperKind.ENUM_VALUE];
  return enumValueMapper != null ? enumValueMapper : null;
}
function correctASTNodes(type2) {
  if (isObjectType(type2)) {
    const config = type2.toConfig();
    if (config.astNode != null) {
      const fields = [];
      for (const fieldName in config.fields) {
        const fieldConfig = config.fields[fieldName];
        if (fieldConfig.astNode != null) {
          fields.push(fieldConfig.astNode);
        }
      }
      config.astNode = {
        ...config.astNode,
        kind: Kind.OBJECT_TYPE_DEFINITION,
        fields
      };
    }
    if (config.extensionASTNodes != null) {
      config.extensionASTNodes = config.extensionASTNodes.map((node) => ({
        ...node,
        kind: Kind.OBJECT_TYPE_EXTENSION,
        fields: void 0
      }));
    }
    return new GraphQLObjectType(config);
  } else if (isInterfaceType(type2)) {
    const config = type2.toConfig();
    if (config.astNode != null) {
      const fields = [];
      for (const fieldName in config.fields) {
        const fieldConfig = config.fields[fieldName];
        if (fieldConfig.astNode != null) {
          fields.push(fieldConfig.astNode);
        }
      }
      config.astNode = {
        ...config.astNode,
        kind: Kind.INTERFACE_TYPE_DEFINITION,
        fields
      };
    }
    if (config.extensionASTNodes != null) {
      config.extensionASTNodes = config.extensionASTNodes.map((node) => ({
        ...node,
        kind: Kind.INTERFACE_TYPE_EXTENSION,
        fields: void 0
      }));
    }
    return new GraphQLInterfaceType(config);
  } else if (isInputObjectType(type2)) {
    const config = type2.toConfig();
    if (config.astNode != null) {
      const fields = [];
      for (const fieldName in config.fields) {
        const fieldConfig = config.fields[fieldName];
        if (fieldConfig.astNode != null) {
          fields.push(fieldConfig.astNode);
        }
      }
      config.astNode = {
        ...config.astNode,
        kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
        fields
      };
    }
    if (config.extensionASTNodes != null) {
      config.extensionASTNodes = config.extensionASTNodes.map((node) => ({
        ...node,
        kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,
        fields: void 0
      }));
    }
    return new GraphQLInputObjectType(config);
  } else if (isEnumType(type2)) {
    const config = type2.toConfig();
    if (config.astNode != null) {
      const values = [];
      for (const enumKey in config.values) {
        const enumValueConfig = config.values[enumKey];
        if (enumValueConfig.astNode != null) {
          values.push(enumValueConfig.astNode);
        }
      }
      config.astNode = {
        ...config.astNode,
        values
      };
    }
    if (config.extensionASTNodes != null) {
      config.extensionASTNodes = config.extensionASTNodes.map((node) => ({
        ...node,
        values: void 0
      }));
    }
    return new GraphQLEnumType(config);
  } else {
    return type2;
  }
}
function healSchema(schema) {
  healTypes(schema.getTypeMap(), schema.getDirectives());
  return schema;
}
function healTypes(originalTypeMap, directives) {
  const actualNamedTypeMap = /* @__PURE__ */ Object.create(null);
  for (const typeName in originalTypeMap) {
    const namedType = originalTypeMap[typeName];
    if (namedType == null || typeName.startsWith("__")) {
      continue;
    }
    const actualName = namedType.name;
    if (actualName.startsWith("__")) {
      continue;
    }
    if (actualNamedTypeMap[actualName] != null) {
      console.warn(`Duplicate schema type name ${actualName} found; keeping the existing one found in the schema`);
      continue;
    }
    actualNamedTypeMap[actualName] = namedType;
  }
  for (const typeName in actualNamedTypeMap) {
    const namedType = actualNamedTypeMap[typeName];
    originalTypeMap[typeName] = namedType;
  }
  for (const decl of directives) {
    decl.args = decl.args.filter((arg) => {
      arg.type = healType(arg.type);
      return arg.type !== null;
    });
  }
  for (const typeName in originalTypeMap) {
    const namedType = originalTypeMap[typeName];
    if (!typeName.startsWith("__") && typeName in actualNamedTypeMap) {
      if (namedType != null) {
        healNamedType(namedType);
      }
    }
  }
  for (const typeName in originalTypeMap) {
    if (!typeName.startsWith("__") && !(typeName in actualNamedTypeMap)) {
      delete originalTypeMap[typeName];
    }
  }
  function healNamedType(type2) {
    if (isObjectType(type2)) {
      healFields(type2);
      healInterfaces(type2);
      return;
    } else if (isInterfaceType(type2)) {
      healFields(type2);
      if ("getInterfaces" in type2) {
        healInterfaces(type2);
      }
      return;
    } else if (isUnionType(type2)) {
      healUnderlyingTypes(type2);
      return;
    } else if (isInputObjectType(type2)) {
      healInputFields(type2);
      return;
    } else if (isLeafType(type2)) {
      return;
    }
    throw new Error(`Unexpected schema type: ${type2}`);
  }
  function healFields(type2) {
    const fieldMap = type2.getFields();
    for (const [key, field] of Object.entries(fieldMap)) {
      field.args.map((arg) => {
        arg.type = healType(arg.type);
        return arg.type === null ? null : arg;
      }).filter(Boolean);
      field.type = healType(field.type);
      if (field.type === null) {
        delete fieldMap[key];
      }
    }
  }
  function healInterfaces(type2) {
    if ("getInterfaces" in type2) {
      const interfaces = type2.getInterfaces();
      interfaces.push(...interfaces.splice(0).map((iface) => healType(iface)).filter(Boolean));
    }
  }
  function healInputFields(type2) {
    const fieldMap = type2.getFields();
    for (const [key, field] of Object.entries(fieldMap)) {
      field.type = healType(field.type);
      if (field.type === null) {
        delete fieldMap[key];
      }
    }
  }
  function healUnderlyingTypes(type2) {
    const types2 = type2.getTypes();
    types2.push(...types2.splice(0).map((t) => healType(t)).filter(Boolean));
  }
  function healType(type2) {
    if (isListType(type2)) {
      const healedType = healType(type2.ofType);
      return healedType != null ? new GraphQLList(healedType) : null;
    } else if (isNonNullType(type2)) {
      const healedType = healType(type2.ofType);
      return healedType != null ? new GraphQLNonNull(healedType) : null;
    } else if (isNamedType(type2)) {
      const officialType = originalTypeMap[type2.name];
      if (officialType && type2 !== officialType) {
        return officialType;
      }
    }
    return type2;
  }
}
function forEachField(schema, fn) {
  const typeMap = schema.getTypeMap();
  for (const typeName in typeMap) {
    const type2 = typeMap[typeName];
    if (!getNamedType(type2).name.startsWith("__") && isObjectType(type2)) {
      const fields = type2.getFields();
      for (const fieldName in fields) {
        const field = fields[fieldName];
        fn(field, typeName, fieldName);
      }
    }
  }
}
function forEachDefaultValue(schema, fn) {
  const typeMap = schema.getTypeMap();
  for (const typeName in typeMap) {
    const type2 = typeMap[typeName];
    if (!getNamedType(type2).name.startsWith("__")) {
      if (isObjectType(type2)) {
        const fields = type2.getFields();
        for (const fieldName in fields) {
          const field = fields[fieldName];
          for (const arg of field.args) {
            arg.defaultValue = fn(arg.type, arg.defaultValue);
          }
        }
      } else if (isInputObjectType(type2)) {
        const fields = type2.getFields();
        for (const fieldName in fields) {
          const field = fields[fieldName];
          field.defaultValue = fn(field.type, field.defaultValue);
        }
      }
    }
  }
}
function mergeDeep(sources, respectPrototype = false) {
  const target = sources[0] || {};
  const output = {};
  if (respectPrototype) {
    Object.setPrototypeOf(output, Object.create(Object.getPrototypeOf(target)));
  }
  for (const source of sources) {
    if (isObject(target) && isObject(source)) {
      if (respectPrototype) {
        const outputPrototype = Object.getPrototypeOf(output);
        const sourcePrototype = Object.getPrototypeOf(source);
        if (sourcePrototype) {
          for (const key of Object.getOwnPropertyNames(sourcePrototype)) {
            const descriptor = Object.getOwnPropertyDescriptor(sourcePrototype, key);
            if (isSome(descriptor)) {
              Object.defineProperty(outputPrototype, key, descriptor);
            }
          }
        }
      }
      for (const key in source) {
        if (isObject(source[key])) {
          if (!(key in output)) {
            Object.assign(output, { [key]: source[key] });
          } else {
            output[key] = mergeDeep([output[key], source[key]], respectPrototype);
          }
        } else {
          Object.assign(output, { [key]: source[key] });
        }
      }
    }
  }
  return output;
}
function isObject(item) {
  return item && typeof item === "object" && !Array.isArray(item);
}
function isDocumentNode(object) {
  return object && typeof object === "object" && "kind" in object && object.kind === Kind.DOCUMENT;
}
function assertResolversPresent(schema, resolverValidationOptions = {}) {
  const { requireResolversForArgs, requireResolversForNonScalar, requireResolversForAllFields } = resolverValidationOptions;
  if (requireResolversForAllFields && (requireResolversForArgs || requireResolversForNonScalar)) {
    throw new TypeError("requireResolversForAllFields takes precedence over the more specific assertions. Please configure either requireResolversForAllFields or requireResolversForArgs / requireResolversForNonScalar, but not a combination of them.");
  }
  forEachField(schema, (field, typeName, fieldName) => {
    if (requireResolversForAllFields) {
      expectResolver("requireResolversForAllFields", requireResolversForAllFields, field, typeName, fieldName);
    }
    if (requireResolversForArgs && field.args.length > 0) {
      expectResolver("requireResolversForArgs", requireResolversForArgs, field, typeName, fieldName);
    }
    if (requireResolversForNonScalar !== "ignore" && !isScalarType(getNamedType(field.type))) {
      expectResolver("requireResolversForNonScalar", requireResolversForNonScalar, field, typeName, fieldName);
    }
  });
}
function expectResolver(validator2, behavior, field, typeName, fieldName) {
  if (!field.resolve) {
    const message = `Resolver missing for "${typeName}.${fieldName}".
To disable this validator, use:
  resolverValidationOptions: {
    ${validator2}: 'ignore'
  }`;
    if (behavior === "error") {
      throw new Error(message);
    }
    if (behavior === "warn") {
      console.warn(message);
    }
    return;
  }
  if (typeof field.resolve !== "function") {
    throw new Error(`Resolver "${typeName}.${fieldName}" must be a function`);
  }
}
function checkForResolveTypeResolver(schema, requireResolversForResolveType) {
  mapSchema(schema, {
    [MapperKind.ABSTRACT_TYPE]: (type2) => {
      if (!type2.resolveType) {
        const message = `Type "${type2.name}" is missing a "__resolveType" resolver. Pass 'ignore' into "resolverValidationOptions.requireResolversForResolveType" to disable this error.`;
        if (requireResolversForResolveType === "error") {
          throw new Error(message);
        }
        if (requireResolversForResolveType === "warn") {
          console.warn(message);
        }
      }
      return void 0;
    }
  });
}
function extendResolversFromInterfaces(schema, resolvers2) {
  const extendedResolvers = {};
  const typeMap = schema.getTypeMap();
  for (const typeName in typeMap) {
    const type2 = typeMap[typeName];
    if ("getInterfaces" in type2) {
      extendedResolvers[typeName] = {};
      for (const iFace of type2.getInterfaces()) {
        if (resolvers2[iFace.name]) {
          for (const fieldName in resolvers2[iFace.name]) {
            if (fieldName === "__isTypeOf" || !fieldName.startsWith("__")) {
              extendedResolvers[typeName][fieldName] = resolvers2[iFace.name][fieldName];
            }
          }
        }
      }
      const typeResolvers = resolvers2[typeName];
      extendedResolvers[typeName] = {
        ...extendedResolvers[typeName],
        ...typeResolvers
      };
    } else {
      const typeResolvers = resolvers2[typeName];
      if (typeResolvers != null) {
        extendedResolvers[typeName] = typeResolvers;
      }
    }
  }
  return extendedResolvers;
}
function addResolversToSchema({ schema, resolvers: inputResolvers, defaultFieldResolver: defaultFieldResolver2, resolverValidationOptions = {}, inheritResolversFromInterfaces = false, updateResolversInPlace = false }) {
  const { requireResolversToMatchSchema = "error", requireResolversForResolveType } = resolverValidationOptions;
  const resolvers2 = inheritResolversFromInterfaces ? extendResolversFromInterfaces(schema, inputResolvers) : inputResolvers;
  for (const typeName in resolvers2) {
    const resolverValue = resolvers2[typeName];
    const resolverType = typeof resolverValue;
    if (resolverType !== "object") {
      throw new Error(`"${typeName}" defined in resolvers, but has invalid value "${resolverValue}". The resolver's value must be of type object.`);
    }
    const type2 = schema.getType(typeName);
    if (type2 == null) {
      if (requireResolversToMatchSchema === "ignore") {
        continue;
      }
      throw new Error(`"${typeName}" defined in resolvers, but not in schema`);
    } else if (isSpecifiedScalarType(type2)) {
      for (const fieldName in resolverValue) {
        if (fieldName.startsWith("__")) {
          type2[fieldName.substring(2)] = resolverValue[fieldName];
        } else {
          type2[fieldName] = resolverValue[fieldName];
        }
      }
    } else if (isEnumType(type2)) {
      const values = type2.getValues();
      for (const fieldName in resolverValue) {
        if (!fieldName.startsWith("__") && !values.some((value) => value.name === fieldName) && requireResolversToMatchSchema && requireResolversToMatchSchema !== "ignore") {
          throw new Error(`${type2.name}.${fieldName} was defined in resolvers, but not present within ${type2.name}`);
        }
      }
    } else if (isUnionType(type2)) {
      for (const fieldName in resolverValue) {
        if (!fieldName.startsWith("__") && requireResolversToMatchSchema && requireResolversToMatchSchema !== "ignore") {
          throw new Error(`${type2.name}.${fieldName} was defined in resolvers, but ${type2.name} is not an object or interface type`);
        }
      }
    } else if (isObjectType(type2) || isInterfaceType(type2)) {
      for (const fieldName in resolverValue) {
        if (!fieldName.startsWith("__")) {
          const fields = type2.getFields();
          const field = fields[fieldName];
          if (field == null) {
            if (requireResolversToMatchSchema && requireResolversToMatchSchema !== "ignore") {
              throw new Error(`${typeName}.${fieldName} defined in resolvers, but not in schema`);
            }
          } else {
            const fieldResolve = resolverValue[fieldName];
            if (typeof fieldResolve !== "function" && typeof fieldResolve !== "object") {
              throw new Error(`Resolver ${typeName}.${fieldName} must be object or function`);
            }
          }
        }
      }
    }
  }
  schema = updateResolversInPlace ? addResolversToExistingSchema(schema, resolvers2, defaultFieldResolver2) : createNewSchemaWithResolvers(schema, resolvers2, defaultFieldResolver2);
  if (requireResolversForResolveType && requireResolversForResolveType !== "ignore") {
    checkForResolveTypeResolver(schema, requireResolversForResolveType);
  }
  return schema;
}
function addResolversToExistingSchema(schema, resolvers2, defaultFieldResolver2) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
  const typeMap = schema.getTypeMap();
  for (const typeName in resolvers2) {
    const type2 = schema.getType(typeName);
    const resolverValue = resolvers2[typeName];
    if (isScalarType(type2)) {
      for (const fieldName in resolverValue) {
        if (fieldName.startsWith("__")) {
          type2[fieldName.substring(2)] = resolverValue[fieldName];
        } else if (fieldName === "astNode" && type2.astNode != null) {
          type2.astNode = {
            ...type2.astNode,
            description: (_b = (_a = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : type2.astNode.description,
            directives: ((_c = type2.astNode.directives) !== null && _c !== void 0 ? _c : []).concat((_e = (_d = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _d === void 0 ? void 0 : _d.directives) !== null && _e !== void 0 ? _e : [])
          };
        } else if (fieldName === "extensionASTNodes" && type2.extensionASTNodes != null) {
          type2.extensionASTNodes = type2.extensionASTNodes.concat((_f = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.extensionASTNodes) !== null && _f !== void 0 ? _f : []);
        } else if (fieldName === "extensions" && type2.extensions != null && resolverValue.extensions != null) {
          type2.extensions = Object.assign(/* @__PURE__ */ Object.create(null), type2.extensions, resolverValue.extensions);
        } else {
          type2[fieldName] = resolverValue[fieldName];
        }
      }
    } else if (isEnumType(type2)) {
      const config = type2.toConfig();
      const enumValueConfigMap = config.values;
      for (const fieldName in resolverValue) {
        if (fieldName.startsWith("__")) {
          config[fieldName.substring(2)] = resolverValue[fieldName];
        } else if (fieldName === "astNode" && config.astNode != null) {
          config.astNode = {
            ...config.astNode,
            description: (_h = (_g = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _g === void 0 ? void 0 : _g.description) !== null && _h !== void 0 ? _h : config.astNode.description,
            directives: ((_j = config.astNode.directives) !== null && _j !== void 0 ? _j : []).concat((_l = (_k = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _k === void 0 ? void 0 : _k.directives) !== null && _l !== void 0 ? _l : [])
          };
        } else if (fieldName === "extensionASTNodes" && config.extensionASTNodes != null) {
          config.extensionASTNodes = config.extensionASTNodes.concat((_m = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.extensionASTNodes) !== null && _m !== void 0 ? _m : []);
        } else if (fieldName === "extensions" && type2.extensions != null && resolverValue.extensions != null) {
          type2.extensions = Object.assign(/* @__PURE__ */ Object.create(null), type2.extensions, resolverValue.extensions);
        } else if (enumValueConfigMap[fieldName]) {
          enumValueConfigMap[fieldName].value = resolverValue[fieldName];
        }
      }
      typeMap[typeName] = new GraphQLEnumType(config);
    } else if (isUnionType(type2)) {
      for (const fieldName in resolverValue) {
        if (fieldName.startsWith("__")) {
          type2[fieldName.substring(2)] = resolverValue[fieldName];
        }
      }
    } else if (isObjectType(type2) || isInterfaceType(type2)) {
      for (const fieldName in resolverValue) {
        if (fieldName.startsWith("__")) {
          type2[fieldName.substring(2)] = resolverValue[fieldName];
          continue;
        }
        const fields = type2.getFields();
        const field = fields[fieldName];
        if (field != null) {
          const fieldResolve = resolverValue[fieldName];
          if (typeof fieldResolve === "function") {
            field.resolve = fieldResolve.bind(resolverValue);
          } else {
            setFieldProperties(field, fieldResolve);
          }
        }
      }
    }
  }
  forEachDefaultValue(schema, serializeInputValue);
  healSchema(schema);
  forEachDefaultValue(schema, parseInputValue);
  if (defaultFieldResolver2 != null) {
    forEachField(schema, (field) => {
      if (!field.resolve) {
        field.resolve = defaultFieldResolver2;
      }
    });
  }
  return schema;
}
function createNewSchemaWithResolvers(schema, resolvers2, defaultFieldResolver2) {
  schema = mapSchema(schema, {
    [MapperKind.SCALAR_TYPE]: (type2) => {
      var _a, _b, _c, _d, _e, _f;
      const config = type2.toConfig();
      const resolverValue = resolvers2[type2.name];
      if (!isSpecifiedScalarType(type2) && resolverValue != null) {
        for (const fieldName in resolverValue) {
          if (fieldName.startsWith("__")) {
            config[fieldName.substring(2)] = resolverValue[fieldName];
          } else if (fieldName === "astNode" && config.astNode != null) {
            config.astNode = {
              ...config.astNode,
              description: (_b = (_a = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : config.astNode.description,
              directives: ((_c = config.astNode.directives) !== null && _c !== void 0 ? _c : []).concat((_e = (_d = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _d === void 0 ? void 0 : _d.directives) !== null && _e !== void 0 ? _e : [])
            };
          } else if (fieldName === "extensionASTNodes" && config.extensionASTNodes != null) {
            config.extensionASTNodes = config.extensionASTNodes.concat((_f = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.extensionASTNodes) !== null && _f !== void 0 ? _f : []);
          } else if (fieldName === "extensions" && config.extensions != null && resolverValue.extensions != null) {
            config.extensions = Object.assign(/* @__PURE__ */ Object.create(null), type2.extensions, resolverValue.extensions);
          } else {
            config[fieldName] = resolverValue[fieldName];
          }
        }
        return new GraphQLScalarType(config);
      }
    },
    [MapperKind.ENUM_TYPE]: (type2) => {
      var _a, _b, _c, _d, _e, _f;
      const resolverValue = resolvers2[type2.name];
      const config = type2.toConfig();
      const enumValueConfigMap = config.values;
      if (resolverValue != null) {
        for (const fieldName in resolverValue) {
          if (fieldName.startsWith("__")) {
            config[fieldName.substring(2)] = resolverValue[fieldName];
          } else if (fieldName === "astNode" && config.astNode != null) {
            config.astNode = {
              ...config.astNode,
              description: (_b = (_a = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _a === void 0 ? void 0 : _a.description) !== null && _b !== void 0 ? _b : config.astNode.description,
              directives: ((_c = config.astNode.directives) !== null && _c !== void 0 ? _c : []).concat((_e = (_d = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.astNode) === null || _d === void 0 ? void 0 : _d.directives) !== null && _e !== void 0 ? _e : [])
            };
          } else if (fieldName === "extensionASTNodes" && config.extensionASTNodes != null) {
            config.extensionASTNodes = config.extensionASTNodes.concat((_f = resolverValue === null || resolverValue === void 0 ? void 0 : resolverValue.extensionASTNodes) !== null && _f !== void 0 ? _f : []);
          } else if (fieldName === "extensions" && config.extensions != null && resolverValue.extensions != null) {
            config.extensions = Object.assign(/* @__PURE__ */ Object.create(null), type2.extensions, resolverValue.extensions);
          } else if (enumValueConfigMap[fieldName]) {
            enumValueConfigMap[fieldName].value = resolverValue[fieldName];
          }
        }
        return new GraphQLEnumType(config);
      }
    },
    [MapperKind.UNION_TYPE]: (type2) => {
      const resolverValue = resolvers2[type2.name];
      if (resolverValue != null) {
        const config = type2.toConfig();
        if (resolverValue["__resolveType"]) {
          config.resolveType = resolverValue["__resolveType"];
        }
        return new GraphQLUnionType(config);
      }
    },
    [MapperKind.OBJECT_TYPE]: (type2) => {
      const resolverValue = resolvers2[type2.name];
      if (resolverValue != null) {
        const config = type2.toConfig();
        if (resolverValue["__isTypeOf"]) {
          config.isTypeOf = resolverValue["__isTypeOf"];
        }
        return new GraphQLObjectType(config);
      }
    },
    [MapperKind.INTERFACE_TYPE]: (type2) => {
      const resolverValue = resolvers2[type2.name];
      if (resolverValue != null) {
        const config = type2.toConfig();
        if (resolverValue["__resolveType"]) {
          config.resolveType = resolverValue["__resolveType"];
        }
        return new GraphQLInterfaceType(config);
      }
    },
    [MapperKind.COMPOSITE_FIELD]: (fieldConfig, fieldName, typeName) => {
      const resolverValue = resolvers2[typeName];
      if (resolverValue != null) {
        const fieldResolve = resolverValue[fieldName];
        if (fieldResolve != null) {
          const newFieldConfig = { ...fieldConfig };
          if (typeof fieldResolve === "function") {
            newFieldConfig.resolve = fieldResolve.bind(resolverValue);
          } else {
            setFieldProperties(newFieldConfig, fieldResolve);
          }
          return newFieldConfig;
        }
      }
    }
  });
  if (defaultFieldResolver2 != null) {
    schema = mapSchema(schema, {
      [MapperKind.OBJECT_FIELD]: (fieldConfig) => ({
        ...fieldConfig,
        resolve: fieldConfig.resolve != null ? fieldConfig.resolve : defaultFieldResolver2
      })
    });
  }
  return schema;
}
function setFieldProperties(field, propertiesObj) {
  for (const propertyName in propertiesObj) {
    field[propertyName] = propertiesObj[propertyName];
  }
}
function mergeResolvers(resolversDefinitions, options2) {
  if (!resolversDefinitions || Array.isArray(resolversDefinitions) && resolversDefinitions.length === 0) {
    return {};
  }
  if (!Array.isArray(resolversDefinitions)) {
    return resolversDefinitions;
  }
  if (resolversDefinitions.length === 1) {
    return resolversDefinitions[0] || {};
  }
  const resolvers2 = new Array();
  for (let resolversDefinition of resolversDefinitions) {
    if (Array.isArray(resolversDefinition)) {
      resolversDefinition = mergeResolvers(resolversDefinition);
    }
    if (typeof resolversDefinition === "object" && resolversDefinition) {
      resolvers2.push(resolversDefinition);
    }
  }
  const result = mergeDeep(resolvers2, true);
  if (options2 === null || options2 === void 0 ? void 0 : options2.exclusions) {
    for (const exclusion of options2.exclusions) {
      const [typeName, fieldName] = exclusion.split(".");
      if (!fieldName || fieldName === "*") {
        delete result[typeName];
      } else if (result[typeName]) {
        delete result[typeName][fieldName];
      }
    }
  }
  return result;
}
function mergeArguments$1(args1, args2, config) {
  const result = deduplicateArguments([...args2, ...args1].filter(isSome), config);
  if (config && config.sort) {
    result.sort(compareNodes);
  }
  return result;
}
function deduplicateArguments(args, config) {
  return args.reduce((acc, current) => {
    const dupIndex = acc.findIndex((arg) => arg.name.value === current.name.value);
    if (dupIndex === -1) {
      return acc.concat([current]);
    } else if (!(config === null || config === void 0 ? void 0 : config.reverseArguments)) {
      acc[dupIndex] = current;
    }
    return acc;
  }, []);
}
function directiveAlreadyExists(directivesArr, otherDirective) {
  return !!directivesArr.find((directive) => directive.name.value === otherDirective.name.value);
}
function isRepeatableDirective(directive, directives) {
  var _a;
  return !!((_a = directives === null || directives === void 0 ? void 0 : directives[directive.name.value]) === null || _a === void 0 ? void 0 : _a.repeatable);
}
function nameAlreadyExists(name2, namesArr) {
  return namesArr.some(({ value }) => value === name2.value);
}
function mergeArguments(a1, a2) {
  const result = [...a2];
  for (const argument of a1) {
    const existingIndex = result.findIndex((a) => a.name.value === argument.name.value);
    if (existingIndex > -1) {
      const existingArg = result[existingIndex];
      if (existingArg.value.kind === "ListValue") {
        const source = existingArg.value.values;
        const target = argument.value.values;
        existingArg.value.values = deduplicateLists(source, target, (targetVal, source2) => {
          const value = targetVal.value;
          return !value || !source2.some((sourceVal) => sourceVal.value === value);
        });
      } else {
        existingArg.value = argument.value;
      }
    } else {
      result.push(argument);
    }
  }
  return result;
}
function deduplicateDirectives(directives, definitions2) {
  return directives.map((directive, i, all) => {
    const firstAt = all.findIndex((d) => d.name.value === directive.name.value);
    if (firstAt !== i && !isRepeatableDirective(directive, definitions2)) {
      const dup = all[firstAt];
      directive.arguments = mergeArguments(directive.arguments, dup.arguments);
      return null;
    }
    return directive;
  }).filter(isSome);
}
function mergeDirectives(d1 = [], d2 = [], config, directives) {
  const reverseOrder = config && config.reverseDirectives;
  const asNext = reverseOrder ? d1 : d2;
  const asFirst = reverseOrder ? d2 : d1;
  const result = deduplicateDirectives([...asNext], directives);
  for (const directive of asFirst) {
    if (directiveAlreadyExists(result, directive) && !isRepeatableDirective(directive, directives)) {
      const existingDirectiveIndex = result.findIndex((d) => d.name.value === directive.name.value);
      const existingDirective = result[existingDirectiveIndex];
      result[existingDirectiveIndex].arguments = mergeArguments(directive.arguments || [], existingDirective.arguments || []);
    } else {
      result.push(directive);
    }
  }
  return result;
}
function validateInputs(node, existingNode) {
  const printedNode = print({
    ...node,
    description: void 0
  });
  const printedExistingNode = print({
    ...existingNode,
    description: void 0
  });
  const leaveInputs = new RegExp("(directive @w*d*)|( on .*$)", "g");
  const sameArguments2 = printedNode.replace(leaveInputs, "") === printedExistingNode.replace(leaveInputs, "");
  if (!sameArguments2) {
    throw new Error(`Unable to merge GraphQL directive "${node.name.value}". 
Existing directive:  
	${printedExistingNode} 
Received directive: 
	${printedNode}`);
  }
}
function mergeDirective(node, existingNode) {
  if (existingNode) {
    validateInputs(node, existingNode);
    return {
      ...node,
      locations: [
        ...existingNode.locations,
        ...node.locations.filter((name2) => !nameAlreadyExists(name2, existingNode.locations))
      ]
    };
  }
  return node;
}
function deduplicateLists(source, target, filterFn) {
  return source.concat(target.filter((val) => filterFn(val, source)));
}
function mergeEnumValues(first, second, config, directives) {
  if (config === null || config === void 0 ? void 0 : config.consistentEnumMerge) {
    const reversed = [];
    if (first) {
      reversed.push(...first);
    }
    first = second;
    second = reversed;
  }
  const enumValueMap = /* @__PURE__ */ new Map();
  if (first) {
    for (const firstValue of first) {
      enumValueMap.set(firstValue.name.value, firstValue);
    }
  }
  if (second) {
    for (const secondValue of second) {
      const enumValue = secondValue.name.value;
      if (enumValueMap.has(enumValue)) {
        const firstValue = enumValueMap.get(enumValue);
        firstValue.description = secondValue.description || firstValue.description;
        firstValue.directives = mergeDirectives(secondValue.directives, firstValue.directives, directives);
      } else {
        enumValueMap.set(enumValue, secondValue);
      }
    }
  }
  const result = [...enumValueMap.values()];
  if (config && config.sort) {
    result.sort(compareNodes);
  }
  return result;
}
function mergeEnum(e1, e2, config, directives) {
  if (e2) {
    return {
      name: e1.name,
      description: e1["description"] || e2["description"],
      kind: (config === null || config === void 0 ? void 0 : config.convertExtensions) || e1.kind === "EnumTypeDefinition" || e2.kind === "EnumTypeDefinition" ? "EnumTypeDefinition" : "EnumTypeExtension",
      loc: e1.loc,
      directives: mergeDirectives(e1.directives, e2.directives, config, directives),
      values: mergeEnumValues(e1.values, e2.values, config)
    };
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...e1,
    kind: Kind.ENUM_TYPE_DEFINITION
  } : e1;
}
function isStringTypes(types2) {
  return typeof types2 === "string";
}
function isSourceTypes(types2) {
  return types2 instanceof Source;
}
function extractType(type2) {
  let visitedType = type2;
  while (visitedType.kind === Kind.LIST_TYPE || visitedType.kind === "NonNullType") {
    visitedType = visitedType.type;
  }
  return visitedType;
}
function isWrappingTypeNode(type2) {
  return type2.kind !== Kind.NAMED_TYPE;
}
function isListTypeNode(type2) {
  return type2.kind === Kind.LIST_TYPE;
}
function isNonNullTypeNode(type2) {
  return type2.kind === Kind.NON_NULL_TYPE;
}
function printTypeNode(type2) {
  if (isListTypeNode(type2)) {
    return `[${printTypeNode(type2.type)}]`;
  }
  if (isNonNullTypeNode(type2)) {
    return `${printTypeNode(type2.type)}!`;
  }
  return type2.name.value;
}
var CompareVal;
(function(CompareVal2) {
  CompareVal2[CompareVal2["A_SMALLER_THAN_B"] = -1] = "A_SMALLER_THAN_B";
  CompareVal2[CompareVal2["A_EQUALS_B"] = 0] = "A_EQUALS_B";
  CompareVal2[CompareVal2["A_GREATER_THAN_B"] = 1] = "A_GREATER_THAN_B";
})(CompareVal || (CompareVal = {}));
function defaultStringComparator(a, b) {
  if (a == null && b == null) {
    return CompareVal.A_EQUALS_B;
  }
  if (a == null) {
    return CompareVal.A_SMALLER_THAN_B;
  }
  if (b == null) {
    return CompareVal.A_GREATER_THAN_B;
  }
  if (a < b)
    return CompareVal.A_SMALLER_THAN_B;
  if (a > b)
    return CompareVal.A_GREATER_THAN_B;
  return CompareVal.A_EQUALS_B;
}
function fieldAlreadyExists(fieldsArr, otherField) {
  const resultIndex = fieldsArr.findIndex((field) => field.name.value === otherField.name.value);
  return [resultIndex > -1 ? fieldsArr[resultIndex] : null, resultIndex];
}
function mergeFields(type2, f1, f2, config, directives) {
  const result = [];
  if (f2 != null) {
    result.push(...f2);
  }
  if (f1 != null) {
    for (const field of f1) {
      const [existing, existingIndex] = fieldAlreadyExists(result, field);
      if (existing && !(config === null || config === void 0 ? void 0 : config.ignoreFieldConflicts)) {
        const newField = (config === null || config === void 0 ? void 0 : config.onFieldTypeConflict) && config.onFieldTypeConflict(existing, field, type2, config === null || config === void 0 ? void 0 : config.throwOnConflict) || preventConflicts(type2, existing, field, config === null || config === void 0 ? void 0 : config.throwOnConflict);
        newField.arguments = mergeArguments$1(field["arguments"] || [], existing["arguments"] || [], config);
        newField.directives = mergeDirectives(field.directives, existing.directives, config, directives);
        newField.description = field.description || existing.description;
        result[existingIndex] = newField;
      } else {
        result.push(field);
      }
    }
  }
  if (config && config.sort) {
    result.sort(compareNodes);
  }
  if (config && config.exclusions) {
    const exclusions = config.exclusions;
    return result.filter((field) => !exclusions.includes(`${type2.name.value}.${field.name.value}`));
  }
  return result;
}
function preventConflicts(type2, a, b, ignoreNullability = false) {
  const aType = printTypeNode(a.type);
  const bType = printTypeNode(b.type);
  if (aType !== bType) {
    const t1 = extractType(a.type);
    const t2 = extractType(b.type);
    if (t1.name.value !== t2.name.value) {
      throw new Error(`Field "${b.name.value}" already defined with a different type. Declared as "${t1.name.value}", but you tried to override with "${t2.name.value}"`);
    }
    if (!safeChangeForFieldType(a.type, b.type, !ignoreNullability)) {
      throw new Error(`Field '${type2.name.value}.${a.name.value}' changed type from '${aType}' to '${bType}'`);
    }
  }
  if (isNonNullTypeNode(b.type) && !isNonNullTypeNode(a.type)) {
    a.type = b.type;
  }
  return a;
}
function safeChangeForFieldType(oldType, newType, ignoreNullability = false) {
  if (!isWrappingTypeNode(oldType) && !isWrappingTypeNode(newType)) {
    return oldType.toString() === newType.toString();
  }
  if (isNonNullTypeNode(newType)) {
    const ofType = isNonNullTypeNode(oldType) ? oldType.type : oldType;
    return safeChangeForFieldType(ofType, newType.type);
  }
  if (isNonNullTypeNode(oldType)) {
    return safeChangeForFieldType(newType, oldType, ignoreNullability);
  }
  if (isListTypeNode(oldType)) {
    return isListTypeNode(newType) && safeChangeForFieldType(oldType.type, newType.type) || isNonNullTypeNode(newType) && safeChangeForFieldType(oldType, newType["type"]);
  }
  return false;
}
function mergeInputType(node, existingNode, config, directives) {
  if (existingNode) {
    try {
      return {
        name: node.name,
        description: node["description"] || existingNode["description"],
        kind: (config === null || config === void 0 ? void 0 : config.convertExtensions) || node.kind === "InputObjectTypeDefinition" || existingNode.kind === "InputObjectTypeDefinition" ? "InputObjectTypeDefinition" : "InputObjectTypeExtension",
        loc: node.loc,
        fields: mergeFields(node, node.fields, existingNode.fields, config),
        directives: mergeDirectives(node.directives, existingNode.directives, config, directives)
      };
    } catch (e) {
      throw new Error(`Unable to merge GraphQL input type "${node.name.value}": ${e.message}`);
    }
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...node,
    kind: Kind.INPUT_OBJECT_TYPE_DEFINITION
  } : node;
}
function alreadyExists(arr, other) {
  return !!arr.find((i) => i.name.value === other.name.value);
}
function mergeNamedTypeArray(first = [], second = [], config = {}) {
  const result = [...second, ...first.filter((d) => !alreadyExists(second, d))];
  if (config && config.sort) {
    result.sort(compareNodes);
  }
  return result;
}
function mergeInterface(node, existingNode, config, directives) {
  if (existingNode) {
    try {
      return {
        name: node.name,
        description: node["description"] || existingNode["description"],
        kind: (config === null || config === void 0 ? void 0 : config.convertExtensions) || node.kind === "InterfaceTypeDefinition" || existingNode.kind === "InterfaceTypeDefinition" ? "InterfaceTypeDefinition" : "InterfaceTypeExtension",
        loc: node.loc,
        fields: mergeFields(node, node.fields, existingNode.fields, config),
        directives: mergeDirectives(node.directives, existingNode.directives, config, directives),
        interfaces: node["interfaces"] ? mergeNamedTypeArray(node["interfaces"], existingNode["interfaces"], config) : void 0
      };
    } catch (e) {
      throw new Error(`Unable to merge GraphQL interface "${node.name.value}": ${e.message}`);
    }
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...node,
    kind: Kind.INTERFACE_TYPE_DEFINITION
  } : node;
}
function mergeType(node, existingNode, config, directives) {
  if (existingNode) {
    try {
      return {
        name: node.name,
        description: node["description"] || existingNode["description"],
        kind: (config === null || config === void 0 ? void 0 : config.convertExtensions) || node.kind === "ObjectTypeDefinition" || existingNode.kind === "ObjectTypeDefinition" ? "ObjectTypeDefinition" : "ObjectTypeExtension",
        loc: node.loc,
        fields: mergeFields(node, node.fields, existingNode.fields, config),
        directives: mergeDirectives(node.directives, existingNode.directives, config, directives),
        interfaces: mergeNamedTypeArray(node.interfaces, existingNode.interfaces, config)
      };
    } catch (e) {
      throw new Error(`Unable to merge GraphQL type "${node.name.value}": ${e.message}`);
    }
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...node,
    kind: Kind.OBJECT_TYPE_DEFINITION
  } : node;
}
function mergeScalar(node, existingNode, config, directives) {
  if (existingNode) {
    return {
      name: node.name,
      description: node["description"] || existingNode["description"],
      kind: (config === null || config === void 0 ? void 0 : config.convertExtensions) || node.kind === "ScalarTypeDefinition" || existingNode.kind === "ScalarTypeDefinition" ? "ScalarTypeDefinition" : "ScalarTypeExtension",
      loc: node.loc,
      directives: mergeDirectives(node.directives, existingNode.directives, config, directives)
    };
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...node,
    kind: Kind.SCALAR_TYPE_DEFINITION
  } : node;
}
function mergeUnion(first, second, config, directives) {
  if (second) {
    return {
      name: first.name,
      description: first["description"] || second["description"],
      // ConstXNode has been introduced in v16 but it is not compatible with XNode so we do `as any` for backwards compatibility
      directives: mergeDirectives(first.directives, second.directives, config, directives),
      kind: (config === null || config === void 0 ? void 0 : config.convertExtensions) || first.kind === "UnionTypeDefinition" || second.kind === "UnionTypeDefinition" ? Kind.UNION_TYPE_DEFINITION : Kind.UNION_TYPE_EXTENSION,
      loc: first.loc,
      types: mergeNamedTypeArray(first.types, second.types, config)
    };
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...first,
    kind: Kind.UNION_TYPE_DEFINITION
  } : first;
}
const DEFAULT_OPERATION_TYPE_NAME_MAP = {
  query: "Query",
  mutation: "Mutation",
  subscription: "Subscription"
};
function mergeOperationTypes(opNodeList = [], existingOpNodeList = []) {
  const finalOpNodeList = [];
  for (const opNodeType in DEFAULT_OPERATION_TYPE_NAME_MAP) {
    const opNode = opNodeList.find((n) => n.operation === opNodeType) || existingOpNodeList.find((n) => n.operation === opNodeType);
    if (opNode) {
      finalOpNodeList.push(opNode);
    }
  }
  return finalOpNodeList;
}
function mergeSchemaDefs(node, existingNode, config, directives) {
  if (existingNode) {
    return {
      kind: node.kind === Kind.SCHEMA_DEFINITION || existingNode.kind === Kind.SCHEMA_DEFINITION ? Kind.SCHEMA_DEFINITION : Kind.SCHEMA_EXTENSION,
      description: node["description"] || existingNode["description"],
      directives: mergeDirectives(node.directives, existingNode.directives, config, directives),
      operationTypes: mergeOperationTypes(node.operationTypes, existingNode.operationTypes)
    };
  }
  return (config === null || config === void 0 ? void 0 : config.convertExtensions) ? {
    ...node,
    kind: Kind.SCHEMA_DEFINITION
  } : node;
}
const schemaDefSymbol = "SCHEMA_DEF_SYMBOL";
function isNamedDefinitionNode(definitionNode) {
  return "name" in definitionNode;
}
function mergeGraphQLNodes(nodes, config, directives = {}) {
  var _a, _b, _c;
  const mergedResultMap = directives;
  for (const nodeDefinition of nodes) {
    if (isNamedDefinitionNode(nodeDefinition)) {
      const name2 = (_a = nodeDefinition.name) === null || _a === void 0 ? void 0 : _a.value;
      if (config === null || config === void 0 ? void 0 : config.commentDescriptions) {
        collectComment(nodeDefinition);
      }
      if (name2 == null) {
        continue;
      }
      if (((_b = config === null || config === void 0 ? void 0 : config.exclusions) === null || _b === void 0 ? void 0 : _b.includes(name2 + ".*")) || ((_c = config === null || config === void 0 ? void 0 : config.exclusions) === null || _c === void 0 ? void 0 : _c.includes(name2))) {
        delete mergedResultMap[name2];
      } else {
        switch (nodeDefinition.kind) {
          case Kind.OBJECT_TYPE_DEFINITION:
          case Kind.OBJECT_TYPE_EXTENSION:
            mergedResultMap[name2] = mergeType(nodeDefinition, mergedResultMap[name2], config, directives);
            break;
          case Kind.ENUM_TYPE_DEFINITION:
          case Kind.ENUM_TYPE_EXTENSION:
            mergedResultMap[name2] = mergeEnum(nodeDefinition, mergedResultMap[name2], config, directives);
            break;
          case Kind.UNION_TYPE_DEFINITION:
          case Kind.UNION_TYPE_EXTENSION:
            mergedResultMap[name2] = mergeUnion(nodeDefinition, mergedResultMap[name2], config, directives);
            break;
          case Kind.SCALAR_TYPE_DEFINITION:
          case Kind.SCALAR_TYPE_EXTENSION:
            mergedResultMap[name2] = mergeScalar(nodeDefinition, mergedResultMap[name2], config, directives);
            break;
          case Kind.INPUT_OBJECT_TYPE_DEFINITION:
          case Kind.INPUT_OBJECT_TYPE_EXTENSION:
            mergedResultMap[name2] = mergeInputType(nodeDefinition, mergedResultMap[name2], config, directives);
            break;
          case Kind.INTERFACE_TYPE_DEFINITION:
          case Kind.INTERFACE_TYPE_EXTENSION:
            mergedResultMap[name2] = mergeInterface(nodeDefinition, mergedResultMap[name2], config, directives);
            break;
          case Kind.DIRECTIVE_DEFINITION:
            mergedResultMap[name2] = mergeDirective(nodeDefinition, mergedResultMap[name2]);
            break;
        }
      }
    } else if (nodeDefinition.kind === Kind.SCHEMA_DEFINITION || nodeDefinition.kind === Kind.SCHEMA_EXTENSION) {
      mergedResultMap[schemaDefSymbol] = mergeSchemaDefs(nodeDefinition, mergedResultMap[schemaDefSymbol], config);
    }
  }
  return mergedResultMap;
}
function mergeTypeDefs(typeSource, config) {
  resetComments();
  const doc = {
    kind: Kind.DOCUMENT,
    definitions: mergeGraphQLTypes(typeSource, {
      useSchemaDefinition: true,
      forceSchemaDefinition: false,
      throwOnConflict: false,
      commentDescriptions: false,
      ...config
    })
  };
  let result;
  if (config === null || config === void 0 ? void 0 : config.commentDescriptions) {
    result = printWithComments(doc);
  } else {
    result = doc;
  }
  resetComments();
  return result;
}
function visitTypeSources(typeSource, options2, allDirectives = [], allNodes = [], visitedTypeSources = /* @__PURE__ */ new Set()) {
  if (typeSource && !visitedTypeSources.has(typeSource)) {
    visitedTypeSources.add(typeSource);
    if (typeof typeSource === "function") {
      visitTypeSources(typeSource(), options2, allDirectives, allNodes, visitedTypeSources);
    } else if (Array.isArray(typeSource)) {
      for (const type2 of typeSource) {
        visitTypeSources(type2, options2, allDirectives, allNodes, visitedTypeSources);
      }
    } else if (isSchema(typeSource)) {
      const documentNode = getDocumentNodeFromSchema(typeSource, options2);
      visitTypeSources(documentNode.definitions, options2, allDirectives, allNodes, visitedTypeSources);
    } else if (isStringTypes(typeSource) || isSourceTypes(typeSource)) {
      const documentNode = parse(typeSource, options2);
      visitTypeSources(documentNode.definitions, options2, allDirectives, allNodes, visitedTypeSources);
    } else if (typeof typeSource === "object" && isDefinitionNode(typeSource)) {
      if (typeSource.kind === Kind.DIRECTIVE_DEFINITION) {
        allDirectives.push(typeSource);
      } else {
        allNodes.push(typeSource);
      }
    } else if (isDocumentNode(typeSource)) {
      visitTypeSources(typeSource.definitions, options2, allDirectives, allNodes, visitedTypeSources);
    } else {
      throw new Error(`typeDefs must contain only strings, documents, schemas, or functions, got ${typeof typeSource}`);
    }
  }
  return { allDirectives, allNodes };
}
function mergeGraphQLTypes(typeSource, config) {
  var _a, _b, _c;
  resetComments();
  const { allDirectives, allNodes } = visitTypeSources(typeSource, config);
  const mergedDirectives = mergeGraphQLNodes(allDirectives, config);
  const mergedNodes = mergeGraphQLNodes(allNodes, config, mergedDirectives);
  if (config === null || config === void 0 ? void 0 : config.useSchemaDefinition) {
    const schemaDef = mergedNodes[schemaDefSymbol] || {
      kind: Kind.SCHEMA_DEFINITION,
      operationTypes: []
    };
    const operationTypes = schemaDef.operationTypes;
    for (const opTypeDefNodeType in DEFAULT_OPERATION_TYPE_NAME_MAP) {
      const opTypeDefNode = operationTypes.find((operationType) => operationType.operation === opTypeDefNodeType);
      if (!opTypeDefNode) {
        const possibleRootTypeName = DEFAULT_OPERATION_TYPE_NAME_MAP[opTypeDefNodeType];
        const existingPossibleRootType = mergedNodes[possibleRootTypeName];
        if (existingPossibleRootType != null && existingPossibleRootType.name != null) {
          operationTypes.push({
            kind: Kind.OPERATION_TYPE_DEFINITION,
            type: {
              kind: Kind.NAMED_TYPE,
              name: existingPossibleRootType.name
            },
            operation: opTypeDefNodeType
          });
        }
      }
    }
    if (((_a = schemaDef === null || schemaDef === void 0 ? void 0 : schemaDef.operationTypes) === null || _a === void 0 ? void 0 : _a.length) != null && schemaDef.operationTypes.length > 0) {
      mergedNodes[schemaDefSymbol] = schemaDef;
    }
  }
  if ((config === null || config === void 0 ? void 0 : config.forceSchemaDefinition) && !((_c = (_b = mergedNodes[schemaDefSymbol]) === null || _b === void 0 ? void 0 : _b.operationTypes) === null || _c === void 0 ? void 0 : _c.length)) {
    mergedNodes[schemaDefSymbol] = {
      kind: Kind.SCHEMA_DEFINITION,
      operationTypes: [
        {
          kind: Kind.OPERATION_TYPE_DEFINITION,
          operation: "query",
          type: {
            kind: Kind.NAMED_TYPE,
            name: {
              kind: Kind.NAME,
              value: "Query"
            }
          }
        }
      ]
    };
  }
  const mergedNodeDefinitions = Object.values(mergedNodes);
  if (config === null || config === void 0 ? void 0 : config.sort) {
    const sortFn = typeof config.sort === "function" ? config.sort : defaultStringComparator;
    mergedNodeDefinitions.sort((a, b) => {
      var _a2, _b2;
      return sortFn((_a2 = a.name) === null || _a2 === void 0 ? void 0 : _a2.value, (_b2 = b.name) === null || _b2 === void 0 ? void 0 : _b2.value);
    });
  }
  return mergedNodeDefinitions;
}
function mergeExtensions(extensions) {
  return mergeDeep(extensions);
}
function applyExtensionObject(obj, extensions) {
  if (!obj) {
    return;
  }
  obj.extensions = mergeDeep([obj.extensions || {}, extensions || {}]);
}
function applyExtensions(schema, extensions) {
  applyExtensionObject(schema, extensions.schemaExtensions);
  for (const [typeName, data] of Object.entries(extensions.types || {})) {
    const type2 = schema.getType(typeName);
    if (type2) {
      applyExtensionObject(type2, data.extensions);
      if (data.type === "object" || data.type === "interface") {
        for (const [fieldName, fieldData] of Object.entries(data.fields)) {
          const field = type2.getFields()[fieldName];
          if (field) {
            applyExtensionObject(field, fieldData.extensions);
            for (const [arg, argData] of Object.entries(fieldData.arguments)) {
              applyExtensionObject(field.args.find((a) => a.name === arg), argData);
            }
          }
        }
      } else if (data.type === "input") {
        for (const [fieldName, fieldData] of Object.entries(data.fields)) {
          const field = type2.getFields()[fieldName];
          applyExtensionObject(field, fieldData.extensions);
        }
      } else if (data.type === "enum") {
        for (const [valueName, valueData] of Object.entries(data.values)) {
          const value = type2.getValue(valueName);
          applyExtensionObject(value, valueData);
        }
      }
    }
  }
  return schema;
}
function makeExecutableSchema({ typeDefs: typeDefs2, resolvers: resolvers2 = {}, resolverValidationOptions = {}, inheritResolversFromInterfaces = false, updateResolversInPlace = false, schemaExtensions, ...otherOptions }) {
  if (typeof resolverValidationOptions !== "object") {
    throw new Error("Expected `resolverValidationOptions` to be an object");
  }
  if (!typeDefs2) {
    throw new Error("Must provide typeDefs");
  }
  let schema;
  if (isSchema(typeDefs2)) {
    schema = typeDefs2;
  } else if (otherOptions === null || otherOptions === void 0 ? void 0 : otherOptions.commentDescriptions) {
    const mergedTypeDefs = mergeTypeDefs(typeDefs2, {
      ...otherOptions,
      commentDescriptions: true
    });
    schema = buildSchema(mergedTypeDefs, otherOptions);
  } else {
    const mergedTypeDefs = mergeTypeDefs(typeDefs2, otherOptions);
    schema = buildASTSchema(mergedTypeDefs, otherOptions);
  }
  schema = addResolversToSchema({
    schema,
    resolvers: mergeResolvers(resolvers2),
    resolverValidationOptions,
    inheritResolversFromInterfaces,
    updateResolversInPlace
  });
  if (Object.keys(resolverValidationOptions).length > 0) {
    assertResolversPresent(schema, resolverValidationOptions);
  }
  if (schemaExtensions) {
    schemaExtensions = mergeExtensions(asArray(schemaExtensions));
    applyExtensions(schema, schemaExtensions);
  }
  return schema;
}
const E_CANCELED = new Error("request for lock canceled");
var __awaiter$2 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class Semaphore {
  constructor(_value, _cancelError = E_CANCELED) {
    this._value = _value;
    this._cancelError = _cancelError;
    this._weightedQueues = [];
    this._weightedWaiters = [];
  }
  acquire(weight = 1) {
    if (weight <= 0)
      throw new Error(`invalid weight ${weight}: must be positive`);
    return new Promise((resolve2, reject) => {
      if (!this._weightedQueues[weight - 1])
        this._weightedQueues[weight - 1] = [];
      this._weightedQueues[weight - 1].push({ resolve: resolve2, reject });
      this._dispatch();
    });
  }
  runExclusive(callback, weight = 1) {
    return __awaiter$2(this, void 0, void 0, function* () {
      const [value, release] = yield this.acquire(weight);
      try {
        return yield callback(value);
      } finally {
        release();
      }
    });
  }
  waitForUnlock(weight = 1) {
    if (weight <= 0)
      throw new Error(`invalid weight ${weight}: must be positive`);
    return new Promise((resolve2) => {
      if (!this._weightedWaiters[weight - 1])
        this._weightedWaiters[weight - 1] = [];
      this._weightedWaiters[weight - 1].push(resolve2);
      this._dispatch();
    });
  }
  isLocked() {
    return this._value <= 0;
  }
  getValue() {
    return this._value;
  }
  setValue(value) {
    this._value = value;
    this._dispatch();
  }
  release(weight = 1) {
    if (weight <= 0)
      throw new Error(`invalid weight ${weight}: must be positive`);
    this._value += weight;
    this._dispatch();
  }
  cancel() {
    this._weightedQueues.forEach((queue) => queue.forEach((entry) => entry.reject(this._cancelError)));
    this._weightedQueues = [];
  }
  _dispatch() {
    var _a;
    for (let weight = this._value; weight > 0; weight--) {
      const queueEntry = (_a = this._weightedQueues[weight - 1]) === null || _a === void 0 ? void 0 : _a.shift();
      if (!queueEntry)
        continue;
      const previousValue = this._value;
      const previousWeight = weight;
      this._value -= weight;
      weight = this._value + 1;
      queueEntry.resolve([previousValue, this._newReleaser(previousWeight)]);
    }
    this._drainUnlockWaiters();
  }
  _newReleaser(weight) {
    let called = false;
    return () => {
      if (called)
        return;
      called = true;
      this.release(weight);
    };
  }
  _drainUnlockWaiters() {
    for (let weight = this._value; weight > 0; weight--) {
      if (!this._weightedWaiters[weight - 1])
        continue;
      this._weightedWaiters[weight - 1].forEach((waiter) => waiter());
      this._weightedWaiters[weight - 1] = [];
    }
  }
}
var __awaiter$1 = function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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 ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class Mutex {
  constructor(cancelError) {
    this._semaphore = new Semaphore(1, cancelError);
  }
  acquire() {
    return __awaiter$1(this, void 0, void 0, function* () {
      const [, releaser] = yield this._semaphore.acquire();
      return releaser;
    });
  }
  runExclusive(callback) {
    return this._semaphore.runExclusive(() => callback());
  }
  isLocked() {
    return this._semaphore.isLocked();
  }
  waitForUnlock() {
    return this._semaphore.waitForUnlock();
  }
  release() {
    if (this._semaphore.isLocked())
      this._semaphore.release();
  }
  cancel() {
    return this._semaphore.cancel();
  }
}
var easyCrc32$1 = {};
easyCrc32$1.calculate = function(str) {
  if (str == null)
    return null;
  var utf8CharCodes = utf8encode(str), crc = -1;
  var charLen = utf8CharCodes.length;
  for (var i = 0, len = charLen, y; i < len; ++i) {
    y = (crc ^ utf8CharCodes[i]) & 255;
    crc = crc >>> 8 ^ crcTable[y];
  }
  return (crc ^ -1) >>> 0;
};
function utf8encode(str) {
  var utf8CharCodes = [];
  for (var i = 0, len = str.length, c; i < len; ++i) {
    c = str.charCodeAt(i);
    if (c < 128) {
      utf8CharCodes.push(c);
    } else if (c < 2048) {
      utf8CharCodes.push(c >> 6 | 192, c & 63 | 128);
    } else {
      utf8CharCodes.push(c >> 12 | 224, c >> 6 & 63 | 128, c & 63 | 128);
    }
  }
  return utf8CharCodes;
}
var crcTable = [
  0,
  1996959894,
  3993919788,
  2567524794,
  124634137,
  1886057615,
  3915621685,
  2657392035,
  249268274,
  2044508324,
  3772115230,
  2547177864,
  162941995,
  2125561021,
  3887607047,
  2428444049,
  498536548,
  1789927666,
  4089016648,
  2227061214,
  450548861,
  1843258603,
  4107580753,
  2211677639,
  325883990,
  1684777152,
  4251122042,
  2321926636,
  335633487,
  1661365465,
  4195302755,
  2366115317,
  997073096,
  1281953886,
  3579855332,
  2724688242,
  1006888145,
  1258607687,
  3524101629,
  2768942443,
  901097722,
  1119000684,
  3686517206,
  2898065728,
  853044451,
  1172266101,
  3705015759,
  2882616665,
  651767980,
  1373503546,
  3369554304,
  3218104598,
  565507253,
  1454621731,
  3485111705,
  3099436303,
  671266974,
  1594198024,
  3322730930,
  2970347812,
  795835527,
  1483230225,
  3244367275,
  3060149565,
  1994146192,
  31158534,
  2563907772,
  4023717930,
  1907459465,
  112637215,
  2680153253,
  3904427059,
  2013776290,
  251722036,
  2517215374,
  3775830040,
  2137656763,
  141376813,
  2439277719,
  3865271297,
  1802195444,
  476864866,
  2238001368,
  4066508878,
  1812370925,
  453092731,
  2181625025,
  4111451223,
  1706088902,
  314042704,
  2344532202,
  4240017532,
  1658658271,
  366619977,
  2362670323,
  4224994405,
  1303535960,
  984961486,
  2747007092,
  3569037538,
  1256170817,
  1037604311,
  2765210733,
  3554079995,
  1131014506,
  879679996,
  2909243462,
  3663771856,
  1141124467,
  855842277,
  2852801631,
  3708648649,
  1342533948,
  654459306,
  3188396048,
  3373015174,
  1466479909,
  544179635,
  3110523913,
  3462522015,
  1591671054,
  702138776,
  2966460450,
  3352799412,
  1504918807,
  783551873,
  3082640443,
  3233442989,
  3988292384,
  2596254646,
  62317068,
  1957810842,
  3939845945,
  2647816111,
  81470997,
  1943803523,
  3814918930,
  2489596804,
  225274430,
  2053790376,
  3826175755,
  2466906013,
  167816743,
  2097651377,
  4027552580,
  2265490386,
  503444072,
  1762050814,
  4150417245,
  2154129355,
  426522225,
  1852507879,
  4275313526,
  2312317920,
  282753626,
  1742555852,
  4189708143,
  2394877945,
  397917763,
  1622183637,
  3604390888,
  2714866558,
  953729732,
  1340076626,
  3518719985,
  2797360999,
  1068828381,
  1219638859,
  3624741850,
  2936675148,
  906185462,
  1090812512,
  3747672003,
  2825379669,
  829329135,
  1181335161,
  3412177804,
  3160834842,
  628085408,
  1382605366,
  3423369109,
  3138078467,
  570562233,
  1426400815,
  3317316542,
  2998733608,
  733239954,
  1555261956,
  3268935591,
  3050360625,
  752459403,
  1541320221,
  2607071920,
  3965973030,
  1969922972,
  40735498,
  2617837225,
  3943577151,
  1913087877,
  83908371,
  2512341634,
  3803740692,
  2075208622,
  213261112,
  2463272603,
  3855990285,
  2094854071,
  198958881,
  2262029012,
  4057260610,
  1759359992,
  534414190,
  2176718541,
  4139329115,
  1873836001,
  414664567,
  2282248934,
  4279200368,
  1711684554,
  285281116,
  2405801727,
  4167216745,
  1634467795,
  376229701,
  2685067896,
  3608007406,
  1308918612,
  956543938,
  2808555105,
  3495958263,
  1231636301,
  1047427035,
  2932959818,
  3654703836,
  1088359270,
  936918e3,
  2847714899,
  3736837829,
  1202900863,
  817233897,
  3183342108,
  3401237130,
  1404277552,
  615818150,
  3134207493,
  3453421203,
  1423857449,
  601450431,
  3009837614,
  3294710456,
  1567103746,
  711928724,
  3020668471,
  3272380065,
  1510334235,
  755167117
];
var easyCrc32 = easyCrc32$1;
const crc32 = /* @__PURE__ */ getDefaultExportFromCjs(easyCrc32);
var bitset = { exports: {} };
/**
 * @license BitSet.js v5.1.1 2/1/2020
 * http://www.xarg.org/2014/03/javascript-bit-array/
 *
 * Copyright (c) 2020, Robert Eisele (robert@xarg.org)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 **/
(function(module2, exports2) {
  (function(root) {
    var WORD_LENGTH = 32;
    var WORD_LOG = 5;
    function popCount(v) {
      v -= v >>> 1 & 1431655765;
      v = (v & 858993459) + (v >>> 2 & 858993459);
      return (v + (v >>> 4) & 252645135) * 16843009 >>> 24;
    }
    function divide(arr, B) {
      var r = 0;
      for (var i = 0; i < arr.length; i++) {
        r *= 2;
        var d = (arr[i] + r) / B | 0;
        r = (arr[i] + r) % B;
        arr[i] = d;
      }
      return r;
    }
    function parse2(P2, val) {
      if (val == null) {
        P2["data"] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        P2["_"] = 0;
        return;
      }
      if (val instanceof BitSet2) {
        P2["data"] = val["data"];
        P2["_"] = val["_"];
        return;
      }
      switch (typeof val) {
        case "number":
          P2["data"] = [val | 0];
          P2["_"] = 0;
          break;
        case "string":
          var base = 2;
          var len = WORD_LENGTH;
          if (val.indexOf("0b") === 0) {
            val = val.substr(2);
          } else if (val.indexOf("0x") === 0) {
            val = val.substr(2);
            base = 16;
            len = 8;
          }
          P2["data"] = [];
          P2["_"] = 0;
          var a = val.length - len;
          var b = val.length;
          do {
            var num = parseInt(val.slice(a > 0 ? a : 0, b), base);
            if (isNaN(num)) {
              throw SyntaxError("Invalid param");
            }
            P2["data"].push(num | 0);
            if (a <= 0)
              break;
            a -= len;
            b -= len;
          } while (1);
          break;
        default:
          P2["data"] = [0];
          var data = P2["data"];
          if (val instanceof Array) {
            for (var i = val.length - 1; i >= 0; i--) {
              var ndx = val[i];
              if (ndx === Infinity) {
                P2["_"] = -1;
              } else {
                scale(P2, ndx);
                data[ndx >>> WORD_LOG] |= 1 << ndx;
              }
            }
            break;
          }
          if (Uint8Array && val instanceof Uint8Array) {
            var bits = 8;
            scale(P2, val.length * bits);
            for (var i = 0; i < val.length; i++) {
              var n = val[i];
              for (var j = 0; j < bits; j++) {
                var k = i * bits + j;
                data[k >>> WORD_LOG] |= (n >> j & 1) << k;
              }
            }
            break;
          }
          throw SyntaxError("Invalid param");
      }
    }
    function BitSet2(param) {
      if (!(this instanceof BitSet2)) {
        return new BitSet2(param);
      }
      parse2(this, param);
      this["data"] = this["data"].slice();
    }
    function scale(dst, ndx) {
      var l = ndx >>> WORD_LOG;
      var d = dst["data"];
      var v = dst["_"];
      for (var i = d.length; l >= i; l--) {
        d.push(v);
      }
    }
    var P = {
      "data": [],
      // Holds the actual bits in form of a 32bit integer array.
      "_": 0
      // Holds the MSB flag information to make indefinitely large bitsets inversion-proof
    };
    BitSet2.prototype = {
      "data": [],
      "_": 0,
      /**
       * Set a single bit flag
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * bs1.set(3, 1);
       *
       * @param {number} ndx The index of the bit to be set
       * @param {number=} value Optional value that should be set on the index (0 or 1)
       * @returns {BitSet} this
       */
      "set": function(ndx, value) {
        ndx |= 0;
        scale(this, ndx);
        if (value === void 0 || value) {
          this["data"][ndx >>> WORD_LOG] |= 1 << ndx;
        } else {
          this["data"][ndx >>> WORD_LOG] &= ~(1 << ndx);
        }
        return this;
      },
      /**
       * Get a single bit flag of a certain bit position
       *
       * Ex:
       * bs1 = new BitSet();
       * var isValid = bs1.get(12);
       *
       * @param {number} ndx the index to be fetched
       * @returns {number} The binary flag
       */
      "get": function(ndx) {
        ndx |= 0;
        var d = this["data"];
        var n = ndx >>> WORD_LOG;
        if (n >= d.length) {
          return this["_"] & 1;
        }
        return d[n] >>> ndx & 1;
      },
      /**
       * Creates the bitwise NOT of a set.
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * res = bs1.not();
       *
       * @returns {BitSet} A new BitSet object, containing the bitwise NOT of this
       */
      "not": function() {
        var t = this["clone"]();
        var d = t["data"];
        for (var i = 0; i < d.length; i++) {
          d[i] = ~d[i];
        }
        t["_"] = ~t["_"];
        return t;
      },
      /**
       * Creates the bitwise AND of two sets.
       *
       * Ex:
       * bs1 = new BitSet(10);
       * bs2 = new BitSet(10);
       *
       * res = bs1.and(bs2);
       *
       * @param {BitSet} value A bitset object
       * @returns {BitSet} A new BitSet object, containing the bitwise AND of this and value
       */
      "and": function(value) {
        parse2(P, value);
        var T = this["clone"]();
        var t = T["data"];
        var p = P["data"];
        var pl = p.length;
        var p_ = P["_"];
        var t_ = T["_"];
        if (t_ !== 0) {
          scale(T, pl * WORD_LENGTH - 1);
        }
        var tl = t.length;
        var l = Math.min(pl, tl);
        var i = 0;
        for (; i < l; i++) {
          t[i] &= p[i];
        }
        for (; i < tl; i++) {
          t[i] &= p_;
        }
        T["_"] &= p_;
        return T;
      },
      /**
       * Creates the bitwise OR of two sets.
       *
       * Ex:
       * bs1 = new BitSet(10);
       * bs2 = new BitSet(10);
       *
       * res = bs1.or(bs2);
       *
       * @param {BitSet} val A bitset object
       * @returns {BitSet} A new BitSet object, containing the bitwise OR of this and val
       */
      "or": function(val) {
        parse2(P, val);
        var t = this["clone"]();
        var d = t["data"];
        var p = P["data"];
        var pl = p.length - 1;
        var tl = d.length - 1;
        var minLength = Math.min(tl, pl);
        for (var i = pl; i > minLength; i--) {
          d[i] = p[i];
        }
        for (; i >= 0; i--) {
          d[i] |= p[i];
        }
        t["_"] |= P["_"];
        return t;
      },
      /**
       * Creates the bitwise XOR of two sets.
       *
       * Ex:
       * bs1 = new BitSet(10);
       * bs2 = new BitSet(10);
       *
       * res = bs1.xor(bs2);
       *
       * @param {BitSet} val A bitset object
       * @returns {BitSet} A new BitSet object, containing the bitwise XOR of this and val
       */
      "xor": function(val) {
        parse2(P, val);
        var t = this["clone"]();
        var d = t["data"];
        var p = P["data"];
        var t_ = t["_"];
        var p_ = P["_"];
        var i = 0;
        var tl = d.length - 1;
        var pl = p.length - 1;
        for (i = tl; i > pl; i--) {
          d[i] ^= p_;
        }
        for (i = pl; i > tl; i--) {
          d[i] = t_ ^ p[i];
        }
        for (; i >= 0; i--) {
          d[i] ^= p[i];
        }
        t["_"] ^= p_;
        return t;
      },
      /**
       * Creates the bitwise AND NOT (not confuse with NAND!) of two sets.
       *
       * Ex:
       * bs1 = new BitSet(10);
       * bs2 = new BitSet(10);
       *
       * res = bs1.notAnd(bs2);
       *
       * @param {BitSet} val A bitset object
       * @returns {BitSet} A new BitSet object, containing the bitwise AND NOT of this and other
       */
      "andNot": function(val) {
        return this["and"](new BitSet2(val)["flip"]());
      },
      /**
       * Flip/Invert a range of bits by setting
       *
       * Ex:
       * bs1 = new BitSet();
       * bs1.flip(); // Flip entire set
       * bs1.flip(5); // Flip single bit
       * bs1.flip(3,10); // Flip a bit range
       *
       * @param {number=} from The start index of the range to be flipped
       * @param {number=} to The end index of the range to be flipped
       * @returns {BitSet} this
       */
      "flip": function(from, to) {
        if (from === void 0) {
          var d = this["data"];
          for (var i = 0; i < d.length; i++) {
            d[i] = ~d[i];
          }
          this["_"] = ~this["_"];
        } else if (to === void 0) {
          scale(this, from);
          this["data"][from >>> WORD_LOG] ^= 1 << from;
        } else if (0 <= from && from <= to) {
          scale(this, to);
          for (var i = from; i <= to; i++) {
            this["data"][i >>> WORD_LOG] ^= 1 << i;
          }
        }
        return this;
      },
      /**
       * Clear a range of bits by setting it to 0
       *
       * Ex:
       * bs1 = new BitSet();
       * bs1.clear(); // Clear entire set
       * bs1.clear(5); // Clear single bit
       * bs1.clear(3,10); // Clear a bit range
       *
       * @param {number=} from The start index of the range to be cleared
       * @param {number=} to The end index of the range to be cleared
       * @returns {BitSet} this
       */
      "clear": function(from, to) {
        var data = this["data"];
        if (from === void 0) {
          for (var i = data.length - 1; i >= 0; i--) {
            data[i] = 0;
          }
          this["_"] = 0;
        } else if (to === void 0) {
          from |= 0;
          scale(this, from);
          data[from >>> WORD_LOG] &= ~(1 << from);
        } else if (from <= to) {
          scale(this, to);
          for (var i = from; i <= to; i++) {
            data[i >>> WORD_LOG] &= ~(1 << i);
          }
        }
        return this;
      },
      /**
       * Gets an entire range as a new bitset object
       *
       * Ex:
       * bs1 = new BitSet();
       * bs1.slice(4, 8);
       *
       * @param {number=} from The start index of the range to be get
       * @param {number=} to The end index of the range to be get
       * @returns {BitSet} A new smaller bitset object, containing the extracted range
       */
      "slice": function(from, to) {
        if (from === void 0) {
          return this["clone"]();
        } else if (to === void 0) {
          to = this["data"].length * WORD_LENGTH;
          var im = Object.create(BitSet2.prototype);
          im["_"] = this["_"];
          im["data"] = [0];
          for (var i = from; i <= to; i++) {
            im["set"](i - from, this["get"](i));
          }
          return im;
        } else if (from <= to && 0 <= from) {
          var im = Object.create(BitSet2.prototype);
          im["data"] = [0];
          for (var i = from; i <= to; i++) {
            im["set"](i - from, this["get"](i));
          }
          return im;
        }
        return null;
      },
      /**
       * Set a range of bits
       *
       * Ex:
       * bs1 = new BitSet();
       *
       * bs1.setRange(10, 15, 1);
       *
       * @param {number} from The start index of the range to be set
       * @param {number} to The end index of the range to be set
       * @param {number} value Optional value that should be set on the index (0 or 1)
       * @returns {BitSet} this
       */
      "setRange": function(from, to, value) {
        for (var i = from; i <= to; i++) {
          this["set"](i, value);
        }
        return this;
      },
      /**
       * Clones the actual object
       *
       * Ex:
       * bs1 = new BitSet(10);
       * bs2 = bs1.clone();
       *
       * @returns {BitSet|Object} A new BitSet object, containing a copy of the actual object
       */
      "clone": function() {
        var im = Object.create(BitSet2.prototype);
        im["data"] = this["data"].slice();
        im["_"] = this["_"];
        return im;
      },
      /**
       * Gets a list of set bits
       *
       * @returns {Array}
       */
      "toArray": Math["clz32"] ? function() {
        var ret = [];
        var data = this["data"];
        for (var i = data.length - 1; i >= 0; i--) {
          var num = data[i];
          while (num !== 0) {
            var t = 31 - Math["clz32"](num);
            num ^= 1 << t;
            ret.unshift(i * WORD_LENGTH + t);
          }
        }
        if (this["_"] !== 0)
          ret.push(Infinity);
        return ret;
      } : function() {
        var ret = [];
        var data = this["data"];
        for (var i = 0; i < data.length; i++) {
          var num = data[i];
          while (num !== 0) {
            var t = num & -num;
            num ^= t;
            ret.push(i * WORD_LENGTH + popCount(t - 1));
          }
        }
        if (this["_"] !== 0)
          ret.push(Infinity);
        return ret;
      },
      /**
       * Overrides the toString method to get a binary representation of the BitSet
       *
       * @param {number=} base
       * @returns string A binary string
       */
      "toString": function(base) {
        var data = this["data"];
        if (!base)
          base = 2;
        if ((base & base - 1) === 0 && base < 36) {
          var ret = "";
          var len = 2 + Math.log(
            4294967295
            /*Math.pow(2, WORD_LENGTH)-1*/
          ) / Math.log(base) | 0;
          for (var i = data.length - 1; i >= 0; i--) {
            var cur = data[i];
            if (cur < 0)
              cur += 4294967296;
            var tmp = cur.toString(base);
            if (ret !== "") {
              ret += "0".repeat(len - tmp.length - 1);
            }
            ret += tmp;
          }
          if (this["_"] === 0) {
            ret = ret.replace(/^0+/, "");
            if (ret === "")
              ret = "0";
            return ret;
          } else {
            ret = "1111" + ret;
            return ret.replace(/^1+/, "...1111");
          }
        } else {
          if (2 > base || base > 36)
            throw SyntaxError("Invalid base");
          var ret = [];
          var arr = [];
          for (var i = data.length; i--; ) {
            for (var j = WORD_LENGTH; j--; ) {
              arr.push(data[i] >>> j & 1);
            }
          }
          do {
            ret.unshift(divide(arr, base).toString(base));
          } while (!arr.every(function(x) {
            return x === 0;
          }));
          return ret.join("");
        }
      },
      /**
       * Check if the BitSet is empty, means all bits are unset
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * bs1.isEmpty() ? 'yes' : 'no'
       *
       * @returns {boolean} Whether the bitset is empty
       */
      "isEmpty": function() {
        if (this["_"] !== 0)
          return false;
        var d = this["data"];
        for (var i = d.length - 1; i >= 0; i--) {
          if (d[i] !== 0)
            return false;
        }
        return true;
      },
      /**
       * Calculates the number of bits set
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * var num = bs1.cardinality();
       *
       * @returns {number} The number of bits set
       */
      "cardinality": function() {
        if (this["_"] !== 0) {
          return Infinity;
        }
        var s = 0;
        var d = this["data"];
        for (var i = 0; i < d.length; i++) {
          var n = d[i];
          if (n !== 0)
            s += popCount(n);
        }
        return s;
      },
      /**
       * Calculates the Most Significant Bit / log base two
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * var logbase2 = bs1.msb();
       *
       * var truncatedTwo = Math.pow(2, logbase2); // May overflow!
       *
       * @returns {number} The index of the highest bit set
       */
      "msb": Math["clz32"] ? function() {
        if (this["_"] !== 0) {
          return Infinity;
        }
        var data = this["data"];
        for (var i = data.length; i-- > 0; ) {
          var c = Math["clz32"](data[i]);
          if (c !== WORD_LENGTH) {
            return i * WORD_LENGTH + WORD_LENGTH - 1 - c;
          }
        }
        return Infinity;
      } : function() {
        if (this["_"] !== 0) {
          return Infinity;
        }
        var data = this["data"];
        for (var i = data.length; i-- > 0; ) {
          var v = data[i];
          var c = 0;
          if (v) {
            for (; (v >>>= 1) > 0; c++) {
            }
            return i * WORD_LENGTH + c;
          }
        }
        return Infinity;
      },
      /**
       * Calculates the number of trailing zeros
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * var ntz = bs1.ntz();
       *
       * @returns {number} The index of the lowest bit set
       */
      "ntz": function() {
        var data = this["data"];
        for (var j = 0; j < data.length; j++) {
          var v = data[j];
          if (v !== 0) {
            v = (v ^ v - 1) >>> 1;
            return j * WORD_LENGTH + popCount(v);
          }
        }
        return Infinity;
      },
      /**
       * Calculates the Least Significant Bit
       *
       * Ex:
       * bs1 = new BitSet(10);
       *
       * var lsb = bs1.lsb();
       *
       * @returns {number} The index of the lowest bit set
       */
      "lsb": function() {
        var data = this["data"];
        for (var i = 0; i < data.length; i++) {
          var v = data[i];
          var c = 0;
          if (v) {
            var bit = v & -v;
            for (; bit >>>= 1; c++) {
            }
            return WORD_LENGTH * i + c;
          }
        }
        return this["_"] & 1;
      },
      /**
       * Compares two BitSet objects
       *
       * Ex:
       * bs1 = new BitSet(10);
       * bs2 = new BitSet(10);
       *
       * bs1.equals(bs2) ? 'yes' : 'no'
       *
       * @param {BitSet} val A bitset object
       * @returns {boolean} Whether the two BitSets have the same bits set (valid for indefinite sets as well)
       */
      "equals": function(val) {
        parse2(P, val);
        var t = this["data"];
        var p = P["data"];
        var t_ = this["_"];
        var p_ = P["_"];
        var tl = t.length - 1;
        var pl = p.length - 1;
        if (p_ !== t_) {
          return false;
        }
        var minLength = tl < pl ? tl : pl;
        var i = 0;
        for (; i <= minLength; i++) {
          if (t[i] !== p[i])
            return false;
        }
        for (i = tl; i > pl; i--) {
          if (t[i] !== p_)
            return false;
        }
        for (i = pl; i > tl; i--) {
          if (p[i] !== t_)
            return false;
        }
        return true;
      },
      [Symbol.iterator]: function() {
        var d = this["data"];
        var ndx = 0;
        if (this["_"] === 0) {
          var highest = 0;
          for (var i = d.length - 1; i >= 0; i--) {
            if (d[i] !== 0) {
              highest = i;
              break;
            }
          }
          return {
            "next": function() {
              var n = ndx >>> WORD_LOG;
              return {
                "done": n > highest || n === highest && d[n] >>> ndx === 0,
                "value": n > highest ? 0 : d[n] >>> ndx++ & 1
              };
            }
          };
        } else {
          return {
            "next": function() {
              var n = ndx >>> WORD_LOG;
              return {
                "done": false,
                "value": n < d.length ? d[n] >>> ndx++ & 1 : 1
              };
            }
          };
        }
      }
    };
    BitSet2["fromBinaryString"] = function(str) {
      return new BitSet2("0b" + str);
    };
    BitSet2["fromHexString"] = function(str) {
      return new BitSet2("0x" + str);
    };
    BitSet2["Random"] = function(n) {
      if (n === void 0 || n < 0) {
        n = WORD_LENGTH;
      }
      var m = n % WORD_LENGTH;
      var t = [];
      var len = Math.ceil(n / WORD_LENGTH);
      var s = Object.create(BitSet2.prototype);
      for (var i = 0; i < len; i++) {
        t.push(Math.random() * 4294967296 | 0);
      }
      if (m > 0) {
        t[len - 1] &= (1 << m) - 1;
      }
      s["data"] = t;
      s["_"] = 0;
      return s;
    };
    {
      Object.defineProperty(exports2, "__esModule", { "value": true });
      BitSet2["default"] = BitSet2;
      BitSet2["BitSet"] = BitSet2;
      module2["exports"] = BitSet2;
    }
  })();
})(bitset, bitset.exports);
var bitsetExports = bitset.exports;
const BitSet = /* @__PURE__ */ getDefaultExportFromCjs(bitsetExports);
const name = "proskomma-core";
const version = "0.11.3";
const description$h = "A Scripture Runtime Engine";
const files = [
  "dist"
];
const main = "./dist/index.js";
const module = "./dist/module.mjs";
const exports = {
  ".": {
    require: "./dist/index.js",
    "import": "./dist/index.mjs"
  }
};
const scripts = {
  build: "rm -fr dist && vite build",
  test: 'rm -fr dist && vite build && export PKSRC=dist && bash -c "tape -r @babel/register test/code/**/*.cjs | node_modules/tap-summary/bin/cmd.js"',
  "win:test": 'rm -fr dist && vite build && set PKSRC=dist&& bash -c "tape -r @babel/register test/code/**/*.cjs | node_modules/tap-summary/bin/cmd.js"',
  rawTest: 'rm -fr dist && vite build && export PKSRC=dist && bash -c "tape -r @babel/register test/code/**/*.cjs"',
  oneTest: 'rm -fr dist && vite build && export PKSRC=dist && bash -c "tape -r @babel/register test/code/$TESTSCRIPT.cjs"',
  prepublishOnly: "npm run build"
};
const repository = {
  type: "git",
  url: "git+https://github.com/Proskomma/proskomma-core.git"
};
const keywords = [
  "USFM",
  "USX",
  "Scripture",
  "parser",
  "lexer",
  "Proskomma"
];
const author = "Mark Howe";
const license = "MIT";
const bugs = {
  url: "https://github.com/Proskomma/proskomma-core/issues"
};
const homepage = "https://github.com/Proskomma/proskomma-core#readme";
const dependencies$1 = {
  "@babel/preset-env": "^7.20.2",
  "@graphql-tools/schema": "^9.0.3",
  "async-mutex": "^0.4.0",
  "base-64": "^1.0.0",
  "base64-js": "^1.5.1",
  bitset: "^5.1.1",
  buffer: "^6.0.3",
  "deep-copy-all": "^1.3.4",
  "deep-equal": "^2.0.5",
  "easy-crc32": "^0.0.2",
  "fs-extra": "^11.1.0",
  graphql: "^v16.6.0",
  "proskomma-json-tools": "^0.9.1",
  "pure-uuid": "^1.6.2",
  sax: "^1.2.4",
  stream: "0.0.2",
  string_decoder: "^1.3.0",
  "utf8-string-bytes": "^1.0.3",
  util: "^0.12.4",
  xregexp: "^5.1.1"
};
const devDependencies = {
  "@babel/eslint-parser": "^7.19.1",
  "@babel/register": "^7.18.9",
  "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
  events: "^3.3.0",
  parcel: "^2.12.0",
  process: "^0.11.10",
  "stream-browserify": "^3.0.0",
  "tap-summary": "^4.0.0",
  tape: "^5.7.5",
  typescript: "^4.9.5",
  vite: "^4.1.4"
};
const packageJson = {
  name,
  version,
  description: description$h,
  files,
  main,
  module,
  exports,
  scripts,
  repository,
  keywords,
  author,
  license,
  bugs,
  homepage,
  dependencies: dependencies$1,
  devDependencies
};
const stringToUtf8ByteArray$1 = function(str) {
  var out = [], p = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    if (c < 128) {
      out[p++] = c;
    } else if (c < 2048) {
      out[p++] = c >> 6 | 192;
      out[p++] = c & 63 | 128;
    } else if ((c & 64512) == 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) == 56320) {
      c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023);
      out[p++] = c >> 18 | 240;
      out[p++] = c >> 12 & 63 | 128;
      out[p++] = c >> 6 & 63 | 128;
      out[p++] = c & 63 | 128;
    } else {
      out[p++] = c >> 12 | 224;
      out[p++] = c >> 6 & 63 | 128;
      out[p++] = c & 63 | 128;
    }
  }
  return out;
};
const utf8ByteArrayToString = function(bytes) {
  var out = [], pos = 0, c = 0;
  while (pos < bytes.length) {
    var c1 = bytes[pos++];
    if (c1 < 128) {
      out[c++] = String.fromCharCode(c1);
    } else if (c1 > 191 && c1 < 224) {
      var c2 = bytes[pos++];
      out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);
    } else if (c1 > 239 && c1 < 365) {
      var c2 = bytes[pos++];
      var c3 = bytes[pos++];
      var c4 = bytes[pos++];
      var u = ((c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 65536;
      out[c++] = String.fromCharCode(55296 + (u >> 10));
      out[c++] = String.fromCharCode(56320 + (u & 1023));
    } else {
      var c2 = bytes[pos++];
      var c3 = bytes[pos++];
      out[c++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
    }
  }
  return out.join("");
};
var utf8StringBytes = {
  utf8ByteArrayToString,
  stringToUtf8ByteArray: stringToUtf8ByteArray$1
};
var base64Js = {};
base64Js.byteLength = byteLength;
base64Js.toByteArray = toByteArray;
base64Js.fromByteArray = fromByteArray;
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var code$2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (var i = 0, len = code$2.length; i < len; ++i) {
  lookup[i] = code$2[i];
  revLookup[code$2.charCodeAt(i)] = i;
}
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
function getLens(b64) {
  var len = b64.length;
  if (len % 4 > 0) {
    throw new Error("Invalid string. Length must be a multiple of 4");
  }
  var validLen = b64.indexOf("=");
  if (validLen === -1)
    validLen = len;
  var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
  return [validLen, placeHoldersLen];
}
function byteLength(b64) {
  var lens = getLens(b64);
  var validLen = lens[0];
  var placeHoldersLen = lens[1];
  return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function _byteLength(b64, validLen, placeHoldersLen) {
  return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
}
function toByteArray(b64) {
  var tmp;
  var lens = getLens(b64);
  var validLen = lens[0];
  var placeHoldersLen = lens[1];
  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  var curByte = 0;
  var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
  var i;
  for (i = 0; i < len; i += 4) {
    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
    arr[curByte++] = tmp >> 16 & 255;
    arr[curByte++] = tmp >> 8 & 255;
    arr[curByte++] = tmp & 255;
  }
  if (placeHoldersLen === 2) {
    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
    arr[curByte++] = tmp & 255;
  }
  if (placeHoldersLen === 1) {
    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
    arr[curByte++] = tmp >> 8 & 255;
    arr[curByte++] = tmp & 255;
  }
  return arr;
}
function tripletToBase64(num) {
  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
  var tmp;
  var output = [];
  for (var i = start; i < end; i += 3) {
    tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);
    output.push(tripletToBase64(tmp));
  }
  return output.join("");
}
function fromByteArray(uint8) {
  var tmp;
  var len = uint8.length;
  var extraBytes = len % 3;
  var parts = [];
  var maxChunkLength = 16383;
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  }
  if (extraBytes === 1) {
    tmp = uint8[len - 1];
    parts.push(
      lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
    );
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1];
    parts.push(
      lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
    );
  }
  return parts.join("");
}
const checkNum = (n, func, field) => {
  if (typeof n !== "number") {
    throw new Error(
      `Argument ${field} of ${func} should be a number, not '${n}' (${typeof n})`
    );
  }
};
let ByteArray$6 = class ByteArray {
  constructor(initialArraySize, initialLength) {
    initialArraySize = initialArraySize || 64;
    initialLength = initialLength || 0;
    this.growMax = 1024 * 16;
    this.length = initialLength;
    this.byteArray = new Uint8Array(initialArraySize);
  }
  byte(n) {
    checkNum(n, "byte", "n");
    if (n > this.length - 1) {
      throw Error(
        `Attempt to read byte ${n} of ByteArray of length ${this.length}`
      );
    }
    return this.byteArray[n];
  }
  bytes(n, l) {
    checkNum(n, "bytes", "n");
    checkNum(l, "bytes", "l");
    if (n + l > this.length) {
      throw Error(
        `Attempt to read ${l} bytes from start ${n} of ByteArray of length ${this.length}`
      );
    }
    return this.byteArray.subarray(n, n + l);
  }
  setByte(n, v) {
    checkNum(n, "setByte", "n");
    checkNum(v, "setByte", "v");
    if (n > this.length - 1) {
      throw Error(
        `Attempt to set byte ${n} of ByteArray of length ${this.length}`
      );
    }
    if (typeof v !== "number" || v < 0 || v > 255) {
      throw Error(`Expected value 0-255 when setting ByteArray, found ${v}`);
    }
    this.byteArray[n] = v;
  }
  setBytes(n, v) {
    checkNum(n, "setBytes", "n");
    if (n + v.length > this.length) {
      throw Error(
        `Attempt to set ${v.length} bytes from start ${n} of ByteArray of length ${this.length}`
      );
    }
    this.byteArray.set(v, n);
  }
  pushByte(v) {
    if (typeof v !== "number" || v < 0 || v > 255) {
      throw Error(`Expected value 0-255 when pushing to ByteArray, found ${v}`);
    }
    if (this.length === this.byteArray.length) {
      this.grow();
    }
    this.byteArray[this.length] = v;
    this.length++;
  }
  grow(minNewSize) {
    const newBytes = new Uint8Array(
      Math.max(
        minNewSize || 0,
        this.byteArray.length + Math.min(this.growMax, Math.max(16, this.byteArray.length))
      )
    );
    newBytes.set(this.byteArray);
    this.byteArray = newBytes;
  }
  trim() {
    const newBytes = new Uint8Array(this.length);
    newBytes.set(this.byteArray.subarray(0, this.length));
    this.byteArray = newBytes;
  }
  pushBytes(v) {
    for (const ve of v) {
      this.pushByte(ve);
    }
  }
  pushNByte(v) {
    checkNum(v, "pushNByte", "v");
    if (typeof v !== "number" || v < 0) {
      throw Error(`Expected positive number in pushNByte, found ${v}`);
    }
    if (v < 128) {
      this.pushByte(v + 128);
    } else {
      const modulo = v % 128;
      this.pushByte(modulo);
      this.pushNByte(v >> 7);
    }
  }
  pushNBytes(vArray) {
    for (const v of vArray) {
      try {
        this.pushNByte(v);
      } catch (err) {
        throw Error(
          `Error from pushNByte, called as pushNBytes(${JSON.stringify(
            vArray
          )})`
        );
      }
    }
  }
  nByte(n) {
    checkNum(n, "nByte", "n");
    if (n > this.length - 1) {
      throw Error(
        `Attempt to read nByte ${n} of ByteArray of length ${this.length}`
      );
    }
    const v = this.byteArray[n];
    if (v > 127) {
      return v - 128;
    } else {
      return v + 128 * this.nByte(n + 1);
    }
  }
  nBytes(n, nValues) {
    checkNum(n, "nBytes", "n");
    checkNum(nValues, "nBytes", "nValues");
    const ret = [];
    while (nValues > 0) {
      let done = false;
      let currentValue = 0;
      let multiplier = 1;
      do {
        if (n > this.length - 1) {
          throw Error(
            `Attempt to read nByte ${n} of ByteArray of length ${this.length} in nBytes(${n}, ${nValues})`
          );
        }
        const v = this.byteArray[n];
        if (v > 127) {
          currentValue += (v - 128) * multiplier;
          ret.push(currentValue);
          currentValue = 0;
          done = true;
        } else {
          currentValue += v * multiplier;
          multiplier *= 128;
        }
        n++;
      } while (!done);
      nValues--;
    }
    return ret;
  }
  nByteLength(v) {
    checkNum(v, "nByteLength", "v");
    if (v >= 128 ** 4) {
      throw new Error("> 4 bytes found in nByteLength");
    }
    let ret = 1;
    while (v > 127) {
      v = v >> 7;
      ret += 1;
    }
    return ret;
  }
  pushCountedString(s) {
    const sA = utf8StringBytes.stringToUtf8ByteArray(s);
    this.pushByte(sA.length);
    this.pushBytes(sA);
  }
  countedString(n) {
    checkNum(n, "countedString", "n");
    const sLength = this.byte(n);
    return utf8StringBytes.utf8ByteArrayToString(this.bytes(n + 1, sLength));
  }
  clear() {
    this.byteArray.fill(0);
    this.length = 0;
  }
  base64() {
    return base64Js.fromByteArray(this.byteArray);
  }
  fromBase64(s) {
    this.byteArray = base64Js.toByteArray(s);
    this.length = this.byteArray.length;
  }
  deleteItem(n) {
    checkNum(n, "deleteItem", "n");
    const itemLength = this.byte(n) & 63;
    this.length -= itemLength;
    if (this.length > n) {
      const remainingBytes = this.byteArray.slice(n + itemLength);
      this.byteArray.set(remainingBytes, n);
    }
  }
  insert(n, iba) {
    checkNum(n, "insert", "n");
    const insertLength = iba.length;
    const newLength = this.length + insertLength;
    if (newLength >= this.byteArray.length + insertLength) {
      this.grow(newLength);
    }
    if (n < newLength) {
      const displacedBytes = this.byteArray.slice(n, this.length);
      this.byteArray.set(displacedBytes, n + insertLength);
    }
    this.byteArray.set(iba.byteArray.slice(0, iba.length), n);
    this.length = newLength;
  }
};
const ptBookArray = [
  { code: "GEN", categories: ["ot", "pentateuch"] },
  { code: "EXO", categories: ["ot", "pentateuch"] },
  { code: "LEV", categories: ["ot", "pentateuch"] },
  { code: "NUM", categories: ["ot", "pentateuch"] },
  { code: "DEU", categories: ["ot", "pentateuch"] },
  { code: "JOS", categories: ["ot", "history"] },
  { code: "JDG", categories: ["ot", "history"] },
  { code: "RUT", categories: ["ot", "history"] },
  { code: "1SA", categories: ["ot", "history"] },
  { code: "2SA", categories: ["ot", "history"] },
  { code: "1KI", categories: ["ot", "history"] },
  { code: "2KI", categories: ["ot", "history"] },
  { code: "1CH", categories: ["ot", "history"] },
  { code: "2CH", categories: ["ot", "history"] },
  { code: "EZR", categories: ["ot", "history"] },
  { code: "NEH", categories: ["ot", "history"] },
  { code: "EST", categories: ["ot", "history"] },
  { code: "JOB", categories: ["ot", "wisdom"] },
  { code: "PSA", categories: ["ot", "wisdom"] },
  { code: "PRO", categories: ["ot", "wisdom"] },
  { code: "ECC", categories: ["ot", "wisdom"] },
  { code: "SNG", categories: ["ot", "wisdom"] },
  { code: "ISA", categories: ["ot", "prophecy"] },
  { code: "JER", categories: ["ot", "prophecy"] },
  { code: "LAM", categories: ["ot", "prophecy"] },
  { code: "EZK", categories: ["ot", "prophecy"] },
  { code: "DAN", categories: ["ot", "prophecy"] },
  { code: "HOS", categories: ["ot", "prophecy"] },
  { code: "JOL", categories: ["ot", "prophecy"] },
  { code: "AMO", categories: ["ot", "prophecy"] },
  { code: "OBA", categories: ["ot", "prophecy"] },
  { code: "JON", categories: ["ot", "prophecy"] },
  { code: "MIC", categories: ["ot", "prophecy"] },
  { code: "NAM", categories: ["ot", "prophecy"] },
  { code: "HAB", categories: ["ot", "prophecy"] },
  { code: "ZEP", categories: ["ot", "prophecy"] },
  { code: "HAG", categories: ["ot", "prophecy"] },
  { code: "ZEC", categories: ["ot", "prophecy"] },
  { code: "MAL", categories: ["ot", "prophecy"] },
  { code: "MAT", categories: ["nt", "gospel", "synoptic"] },
  { code: "MRK", categories: ["nt", "gospel", "synoptic"] },
  { code: "LUK", categories: ["nt", "gospel", "synoptic"] },
  { code: "JHN", categories: ["nt", "gospel"] },
  { code: "ACT", categories: ["nt", "gospel"] },
  { code: "ROM", categories: ["nt", "epistle"] },
  { code: "1CO", categories: ["nt", "epistle"] },
  { code: "2CO", categories: ["nt", "epistle"] },
  { code: "GAL", categories: ["nt", "epistle"] },
  { code: "EPH", categories: ["nt", "epistle"] },
  { code: "PHP", categories: ["nt", "epistle"] },
  { code: "COL", categories: ["nt", "epistle"] },
  { code: "1TH", categories: ["nt", "epistle"] },
  { code: "2TH", categories: ["nt", "epistle"] },
  { code: "1TI", categories: ["nt", "epistle"] },
  { code: "2TI", categories: ["nt", "epistle"] },
  { code: "TIT", categories: ["nt", "epistle"] },
  { code: "PHM", categories: ["nt", "epistle"] },
  { code: "HEB", categories: ["nt", "epistle"] },
  { code: "JAS", categories: ["nt", "epistle"] },
  { code: "1PE", categories: ["nt", "epistle"] },
  { code: "2PE", categories: ["nt", "epistle"] },
  { code: "1JN", categories: ["nt", "epistle"] },
  { code: "2JN", categories: ["nt", "epistle"] },
  { code: "3JN", categories: ["nt", "epistle"] },
  { code: "JUD", categories: ["nt", "epistle"] },
  { code: "REV", categories: ["nt", "epistle"] },
  { code: "TOB", categories: ["dc"] },
  { code: "JDT", categories: ["dc"] },
  { code: "ESG", categories: ["dc", "history"] },
  { code: "WIS", categories: ["dc", "wisdom"] },
  { code: "SIR", categories: ["dc", "wisdom"] },
  { code: "BAR", categories: ["dc", "prophecy"] },
  { code: "LJE", categories: ["dc"] },
  { code: "S3Y", categories: ["dc"] },
  { code: "SUS", categories: ["dc"] },
  { code: "BEL", categories: ["dc"] },
  { code: "1MA", categories: ["dc"] },
  { code: "2MA", categories: ["dc"] },
  { code: "3MA", categories: ["dc"] },
  { code: "4MA", categories: ["dc"] },
  { code: "1ES", categories: ["dc"] },
  { code: "2ES", categories: ["dc"] },
  { code: "MAN", categories: ["dc"] },
  { code: "PS2", categories: ["dc"] },
  { code: "ODA", categories: ["dc"] },
  { code: "PSS", categories: ["dc"] },
  { code: "JSA", categories: ["dc"] },
  { code: "JDB", categories: ["dc"] },
  { code: "TBS", categories: ["dc"] },
  { code: "SST", categories: ["dc"] },
  { code: "DNT", categories: ["dc"] },
  { code: "BLT", categories: ["dc"] },
  { code: "EZA", categories: ["dc"] },
  { code: "5EZ", categories: ["dc"] },
  { code: "6EZ", categories: ["dc"] },
  { code: "DAG", categories: ["dc"] },
  { code: "PS3", categories: ["dc"] },
  { code: "2BA", categories: ["dc"] },
  { code: "LBA", categories: ["dc"] },
  { code: "JUB", categories: ["dc"] },
  { code: "ENO", categories: ["dc"] },
  { code: "1MQ", categories: ["dc"] },
  { code: "2MQ", categories: ["dc"] },
  { code: "3MQ", categories: ["dc"] },
  { code: "REP", categories: ["dc"] },
  { code: "4BA", categories: ["dc"] },
  { code: "LAO", categories: ["dc"] }
];
let ptBooks = {};
for (const br of ptBookArray.entries()) {
  ptBooks[br[1].code] = { ...br[1], position: br[0] };
}
const canons = { ptBookArray, ptBooks };
const enumStringIndex = (enumSuccinct, str) => {
  let pos = 0;
  let count = 0;
  while (pos < enumSuccinct.length) {
    const stringLength = enumSuccinct.byte(pos);
    const enumString = enumSuccinct.countedString(pos);
    if (enumString === str) {
      return count;
    }
    pos += stringLength + 1;
    count += 1;
  }
  return -1;
};
const enumRegexIndexTuples = (enumSuccinct, regex) => {
  let pos = 0;
  let count = 0;
  const ret = [];
  while (pos < enumSuccinct.length) {
    const stringLength = enumSuccinct.byte(pos);
    const enumString = enumSuccinct.countedString(pos);
    if (XRegExp.exec(enumString, XRegExp(regex, "i"))) {
      ret.push([count, enumString]);
    }
    pos += stringLength + 1;
    count += 1;
  }
  return ret;
};
const enums = { enumStringIndex, enumRegexIndexTuples };
var uuid = { exports: {} };
/*!
**  Pure-UUID -- Pure JavaScript Based Universally Unique Identifier (UUID)
**  Copyright (c) 2004-2023 Dr. Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function(module2) {
  (function(root, name2, factory) {
    {
      module2.exports = factory(root);
      module2.exports.default = module2.exports;
    }
  })(commonjsGlobal, "UUID", function() {
    var a2hs = function(bytes, begin, end, uppercase, str, pos) {
      var mkNum = function(num, uppercase2) {
        var base16 = num.toString(16);
        if (base16.length < 2)
          base16 = "0" + base16;
        if (uppercase2)
          base16 = base16.toUpperCase();
        return base16;
      };
      for (var i = begin; i <= end; i++)
        str[pos++] = mkNum(bytes[i], uppercase);
      return str;
    };
    var hs2a = function(str, begin, end, bytes, pos) {
      for (var i = begin; i <= end; i += 2)
        bytes[pos++] = parseInt(str.substr(i, 2), 16);
    };
    var z85_encoder = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#".split("");
    var z85_decoder = [
      0,
      68,
      0,
      84,
      83,
      82,
      72,
      0,
      75,
      76,
      70,
      65,
      0,
      63,
      62,
      69,
      0,
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      64,
      0,
      73,
      66,
      74,
      71,
      81,
      36,
      37,
      38,
      39,
      40,
      41,
      42,
      43,
      44,
      45,
      46,
      47,
      48,
      49,
      50,
      51,
      52,
      53,
      54,
      55,
      56,
      57,
      58,
      59,
      60,
      61,
      77,
      0,
      78,
      67,
      0,
      0,
      10,
      11,
      12,
      13,
      14,
      15,
      16,
      17,
      18,
      19,
      20,
      21,
      22,
      23,
      24,
      25,
      26,
      27,
      28,
      29,
      30,
      31,
      32,
      33,
      34,
      35,
      79,
      0,
      80,
      0,
      0
    ];
    var z85_encode = function(data, size) {
      if (size % 4 !== 0)
        throw new Error("z85_encode: invalid input length (multiple of 4 expected)");
      var str = "";
      var i = 0;
      var value = 0;
      while (i < size) {
        value = value * 256 + data[i++];
        if (i % 4 === 0) {
          var divisor = 85 * 85 * 85 * 85;
          while (divisor >= 1) {
            var idx = Math.floor(value / divisor) % 85;
            str += z85_encoder[idx];
            divisor /= 85;
          }
          value = 0;
        }
      }
      return str;
    };
    var z85_decode = function(str, dest) {
      var l = str.length;
      if (l % 5 !== 0)
        throw new Error("z85_decode: invalid input length (multiple of 5 expected)");
      if (typeof dest === "undefined")
        dest = new Array(l * 4 / 5);
      var i = 0;
      var j = 0;
      var value = 0;
      while (i < l) {
        var idx = str.charCodeAt(i++) - 32;
        if (idx < 0 || idx >= z85_decoder.length)
          break;
        value = value * 85 + z85_decoder[idx];
        if (i % 5 === 0) {
          var divisor = 256 * 256 * 256;
          while (divisor >= 1) {
            dest[j++] = Math.trunc(value / divisor % 256);
            divisor /= 256;
          }
          value = 0;
        }
      }
      return dest;
    };
    var s2a = function(s, _options) {
      var options2 = { ibits: 8, obits: 8, obigendian: true };
      for (var opt in _options)
        if (typeof options2[opt] !== "undefined")
          options2[opt] = _options[opt];
      var a = [];
      var i = 0;
      var c, C;
      var ck = 0;
      var w;
      var wk = 0;
      var sl = s.length;
      for (; ; ) {
        if (ck === 0)
          C = s.charCodeAt(i++);
        c = C >> options2.ibits - (ck + 8) & 255;
        ck = (ck + 8) % options2.ibits;
        if (options2.obigendian) {
          if (wk === 0)
            w = c << options2.obits - 8;
          else
            w |= c << options2.obits - 8 - wk;
        } else {
          if (wk === 0)
            w = c;
          else
            w |= c << wk;
        }
        wk = (wk + 8) % options2.obits;
        if (wk === 0) {
          a.push(w);
          if (i >= sl)
            break;
        }
      }
      return a;
    };
    var a2s = function(a, _options) {
      var options2 = { ibits: 32, ibigendian: true };
      for (var opt in _options)
        if (typeof options2[opt] !== "undefined")
          options2[opt] = _options[opt];
      var s = "";
      var imask = 4294967295;
      if (options2.ibits < 32)
        imask = (1 << options2.ibits) - 1;
      var al = a.length;
      for (var i = 0; i < al; i++) {
        var w = a[i] & imask;
        for (var j = 0; j < options2.ibits; j += 8) {
          if (options2.ibigendian)
            s += String.fromCharCode(w >> options2.ibits - 8 - j & 255);
          else
            s += String.fromCharCode(w >> j & 255);
        }
      }
      return s;
    };
    var UI64_DIGITS = 8;
    var UI64_DIGIT_BITS = 8;
    var UI64_DIGIT_BASE = 256;
    var ui64_d2i = function(d7, d6, d5, d4, d3, d2, d1, d0) {
      return [d0, d1, d2, d3, d4, d5, d6, d7];
    };
    var ui64_zero = function() {
      return ui64_d2i(0, 0, 0, 0, 0, 0, 0, 0);
    };
    var ui64_clone = function(x) {
      return x.slice(0);
    };
    var ui64_n2i = function(n) {
      var ui64 = ui64_zero();
      for (var i = 0; i < UI64_DIGITS; i++) {
        ui64[i] = Math.floor(n % UI64_DIGIT_BASE);
        n /= UI64_DIGIT_BASE;
      }
      return ui64;
    };
    var ui64_i2n = function(x) {
      var n = 0;
      for (var i = UI64_DIGITS - 1; i >= 0; i--) {
        n *= UI64_DIGIT_BASE;
        n += x[i];
      }
      return Math.floor(n);
    };
    var ui64_add = function(x, y) {
      var carry = 0;
      for (var i = 0; i < UI64_DIGITS; i++) {
        carry += x[i] + y[i];
        x[i] = Math.floor(carry % UI64_DIGIT_BASE);
        carry = Math.floor(carry / UI64_DIGIT_BASE);
      }
      return carry;
    };
    var ui64_muln = function(x, n) {
      var carry = 0;
      for (var i = 0; i < UI64_DIGITS; i++) {
        carry += x[i] * n;
        x[i] = Math.floor(carry % UI64_DIGIT_BASE);
        carry = Math.floor(carry / UI64_DIGIT_BASE);
      }
      return carry;
    };
    var ui64_mul = function(x, y) {
      var i, j;
      var zx = new Array(UI64_DIGITS + UI64_DIGITS);
      for (i = 0; i < UI64_DIGITS + UI64_DIGITS; i++)
        zx[i] = 0;
      var carry;
      for (i = 0; i < UI64_DIGITS; i++) {
        carry = 0;
        for (j = 0; j < UI64_DIGITS; j++) {
          carry += x[i] * y[j] + zx[i + j];
          zx[i + j] = carry % UI64_DIGIT_BASE;
          carry /= UI64_DIGIT_BASE;
        }
        for (; j < UI64_DIGITS + UI64_DIGITS - i; j++) {
          carry += zx[i + j];
          zx[i + j] = carry % UI64_DIGIT_BASE;
          carry /= UI64_DIGIT_BASE;
        }
      }
      for (i = 0; i < UI64_DIGITS; i++)
        x[i] = zx[i];
      return zx.slice(UI64_DIGITS, UI64_DIGITS);
    };
    var ui64_and = function(x, y) {
      for (var i = 0; i < UI64_DIGITS; i++)
        x[i] &= y[i];
      return x;
    };
    var ui64_or = function(x, y) {
      for (var i = 0; i < UI64_DIGITS; i++)
        x[i] |= y[i];
      return x;
    };
    var ui64_rorn = function(x, s) {
      var ov = ui64_zero();
      if (s % UI64_DIGIT_BITS !== 0)
        throw new Error("ui64_rorn: only bit rotations supported with a multiple of digit bits");
      var k = Math.floor(s / UI64_DIGIT_BITS);
      for (var i = 0; i < k; i++) {
        for (var j = UI64_DIGITS - 1 - 1; j >= 0; j--)
          ov[j + 1] = ov[j];
        ov[0] = x[0];
        for (j = 0; j < UI64_DIGITS - 1; j++)
          x[j] = x[j + 1];
        x[j] = 0;
      }
      return ui64_i2n(ov);
    };
    var ui64_ror = function(x, s) {
      if (s > UI64_DIGITS * UI64_DIGIT_BITS)
        throw new Error("ui64_ror: invalid number of bits to shift");
      var zx = new Array(UI64_DIGITS + UI64_DIGITS);
      var i;
      for (i = 0; i < UI64_DIGITS; i++) {
        zx[i + UI64_DIGITS] = x[i];
        zx[i] = 0;
      }
      var k1 = Math.floor(s / UI64_DIGIT_BITS);
      var k2 = s % UI64_DIGIT_BITS;
      for (i = k1; i < UI64_DIGITS + UI64_DIGITS - 1; i++) {
        zx[i - k1] = (zx[i] >>> k2 | zx[i + 1] << UI64_DIGIT_BITS - k2) & (1 << UI64_DIGIT_BITS) - 1;
      }
      zx[UI64_DIGITS + UI64_DIGITS - 1 - k1] = zx[UI64_DIGITS + UI64_DIGITS - 1] >>> k2 & (1 << UI64_DIGIT_BITS) - 1;
      for (i = UI64_DIGITS + UI64_DIGITS - 1 - k1 + 1; i < UI64_DIGITS + UI64_DIGITS; i++)
        zx[i] = 0;
      for (i = 0; i < UI64_DIGITS; i++)
        x[i] = zx[i + UI64_DIGITS];
      return zx.slice(0, UI64_DIGITS);
    };
    var ui64_rol = function(x, s) {
      if (s > UI64_DIGITS * UI64_DIGIT_BITS)
        throw new Error("ui64_rol: invalid number of bits to shift");
      var zx = new Array(UI64_DIGITS + UI64_DIGITS);
      var i;
      for (i = 0; i < UI64_DIGITS; i++) {
        zx[i + UI64_DIGITS] = 0;
        zx[i] = x[i];
      }
      var k1 = Math.floor(s / UI64_DIGIT_BITS);
      var k2 = s % UI64_DIGIT_BITS;
      for (i = UI64_DIGITS - 1 - k1; i > 0; i--) {
        zx[i + k1] = (zx[i] << k2 | zx[i - 1] >>> UI64_DIGIT_BITS - k2) & (1 << UI64_DIGIT_BITS) - 1;
      }
      zx[0 + k1] = zx[0] << k2 & (1 << UI64_DIGIT_BITS) - 1;
      for (i = 0 + k1 - 1; i >= 0; i--)
        zx[i] = 0;
      for (i = 0; i < UI64_DIGITS; i++)
        x[i] = zx[i];
      return zx.slice(UI64_DIGITS, UI64_DIGITS);
    };
    var ui64_xor = function(x, y) {
      for (var i = 0; i < UI64_DIGITS; i++)
        x[i] ^= y[i];
    };
    var ui32_add = function(x, y) {
      var lsw = (x & 65535) + (y & 65535);
      var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
      return msw << 16 | lsw & 65535;
    };
    var ui32_rol = function(num, cnt) {
      return num << cnt & 4294967295 | num >>> 32 - cnt & 4294967295;
    };
    var sha1_core = function(x, len) {
      function sha1_ft(t2, b2, c2, d2) {
        if (t2 < 20)
          return b2 & c2 | ~b2 & d2;
        if (t2 < 40)
          return b2 ^ c2 ^ d2;
        if (t2 < 60)
          return b2 & c2 | b2 & d2 | c2 & d2;
        return b2 ^ c2 ^ d2;
      }
      function sha1_kt(t2) {
        return t2 < 20 ? 1518500249 : t2 < 40 ? 1859775393 : t2 < 60 ? -1894007588 : -899497514;
      }
      x[len >> 5] |= 128 << 24 - len % 32;
      x[(len + 64 >> 9 << 4) + 15] = len;
      var w = Array(80);
      var a = 1732584193;
      var b = -271733879;
      var c = -1732584194;
      var d = 271733878;
      var e = -1009589776;
      for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        var olde = e;
        for (var j = 0; j < 80; j++) {
          if (j < 16)
            w[j] = x[i + j];
          else
            w[j] = ui32_rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
          var t = ui32_add(
            ui32_add(ui32_rol(a, 5), sha1_ft(j, b, c, d)),
            ui32_add(ui32_add(e, w[j]), sha1_kt(j))
          );
          e = d;
          d = c;
          c = ui32_rol(b, 30);
          b = a;
          a = t;
        }
        a = ui32_add(a, olda);
        b = ui32_add(b, oldb);
        c = ui32_add(c, oldc);
        d = ui32_add(d, oldd);
        e = ui32_add(e, olde);
      }
      return [a, b, c, d, e];
    };
    var sha1 = function(s) {
      return a2s(
        sha1_core(
          s2a(s, { ibits: 8, obits: 32, obigendian: true }),
          s.length * 8
        ),
        { ibits: 32, ibigendian: true }
      );
    };
    var md5_core = function(x, len) {
      function md5_cmn(q, a2, b2, x2, s, t) {
        return ui32_add(ui32_rol(ui32_add(ui32_add(a2, q), ui32_add(x2, t)), s), b2);
      }
      function md5_ff(a2, b2, c2, d2, x2, s, t) {
        return md5_cmn(b2 & c2 | ~b2 & d2, a2, b2, x2, s, t);
      }
      function md5_gg(a2, b2, c2, d2, x2, s, t) {
        return md5_cmn(b2 & d2 | c2 & ~d2, a2, b2, x2, s, t);
      }
      function md5_hh(a2, b2, c2, d2, x2, s, t) {
        return md5_cmn(b2 ^ c2 ^ d2, a2, b2, x2, s, t);
      }
      function md5_ii(a2, b2, c2, d2, x2, s, t) {
        return md5_cmn(c2 ^ (b2 | ~d2), a2, b2, x2, s, t);
      }
      x[len >> 5] |= 128 << len % 32;
      x[(len + 64 >>> 9 << 4) + 14] = len;
      var a = 1732584193;
      var b = -271733879;
      var c = -1732584194;
      var d = 271733878;
      for (var i = 0; i < x.length; i += 16) {
        var olda = a;
        var oldb = b;
        var oldc = c;
        var oldd = d;
        a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
        d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
        c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
        b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
        a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
        d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
        c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
        b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
        a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
        d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
        c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
        b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
        a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
        d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
        c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
        b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
        a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
        d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
        c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
        b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
        a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
        d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
        c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
        b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
        a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
        d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
        c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
        b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
        a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
        d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
        c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
        b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
        a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
        d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
        c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
        b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
        a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
        d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
        c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
        b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
        a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
        d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
        c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
        b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
        a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
        d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
        c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
        b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
        a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
        d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
        c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
        b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
        a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
        d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
        c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
        b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
        a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
        d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
        c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
        b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
        a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
        d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
        c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
        b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
        a = ui32_add(a, olda);
        b = ui32_add(b, oldb);
        c = ui32_add(c, oldc);
        d = ui32_add(d, oldd);
      }
      return [a, b, c, d];
    };
    var md5 = function(s) {
      return a2s(
        md5_core(
          s2a(s, { ibits: 8, obits: 32, obigendian: false }),
          s.length * 8
        ),
        { ibits: 32, ibigendian: false }
      );
    };
    var PCG = function(seed) {
      this.mul = ui64_d2i(88, 81, 244, 45, 76, 149, 127, 45);
      this.inc = ui64_d2i(20, 5, 123, 126, 247, 103, 129, 79);
      this.mask = ui64_d2i(0, 0, 0, 0, 255, 255, 255, 255);
      this.state = ui64_clone(this.inc);
      this.next();
      ui64_and(this.state, this.mask);
      var arr;
      if (seed !== void 0)
        seed = ui64_n2i(seed >>> 0);
      else if (typeof window === "object" && typeof window.crypto === "object" && typeof window.crypto.getRandomValues === "function") {
        arr = new Uint32Array(2);
        window.crypto.getRandomValues(arr);
        seed = ui64_or(ui64_n2i(arr[0] >>> 0), ui64_ror(ui64_n2i(arr[1] >>> 0), 32));
      } else if (typeof globalThis === "object" && typeof globalThis.crypto === "object" && typeof globalThis.crypto.getRandomValues === "function") {
        arr = new Uint32Array(2);
        globalThis.crypto.getRandomValues(arr);
        seed = ui64_or(ui64_n2i(arr[0] >>> 0), ui64_ror(ui64_n2i(arr[1] >>> 0), 32));
      } else {
        seed = ui64_n2i(Math.random() * 4294967295 >>> 0);
        ui64_or(seed, ui64_ror(ui64_n2i((/* @__PURE__ */ new Date()).getTime()), 32));
      }
      ui64_or(this.state, seed);
      this.next();
    };
    PCG.prototype.next = function() {
      var state = ui64_clone(this.state);
      ui64_mul(this.state, this.mul);
      ui64_add(this.state, this.inc);
      var output = ui64_clone(state);
      ui64_ror(output, 18);
      ui64_xor(output, state);
      ui64_ror(output, 27);
      var rot = ui64_clone(state);
      ui64_ror(rot, 59);
      ui64_and(output, this.mask);
      var k = ui64_i2n(rot);
      var output2 = ui64_clone(output);
      ui64_rol(output2, 32 - k);
      ui64_ror(output, k);
      ui64_xor(output, output2);
      return ui64_i2n(output);
    };
    PCG.prototype.reseed = function(seed) {
      if (typeof seed !== "string")
        throw new Error("UUID: PCG: seed: invalid argument (string expected)");
      var arr = sha1_core(s2a(seed, { ibits: 8, obits: 32, obigendian: true }), seed.length * 8);
      for (var i = 0; i < arr.length; i++)
        ui64_xor(pcg.state, ui64_n2i(arr[i] >>> 0));
    };
    var pcg = new PCG();
    PCG.reseed = function(seed) {
      pcg.reseed(seed);
    };
    var prng = function(len, radix) {
      var bytes = [];
      for (var i = 0; i < len; i++)
        bytes[i] = pcg.next() % radix;
      return bytes;
    };
    var time_last = 0;
    var time_seq = 0;
    var UUID2 = function() {
      if (arguments.length === 1 && typeof arguments[0] === "string")
        this.parse.apply(this, arguments);
      else if (arguments.length >= 1 && typeof arguments[0] === "number")
        this.make.apply(this, arguments);
      else if (arguments.length >= 1)
        throw new Error("UUID: constructor: invalid arguments");
      else
        for (var i = 0; i < 16; i++)
          this[i] = 0;
    };
    if (typeof Uint8Array !== "undefined")
      UUID2.prototype = new Uint8Array(16);
    else if (Buffer)
      UUID2.prototype = Buffer.alloc(16);
    else
      UUID2.prototype = new Array(16);
    UUID2.prototype.constructor = UUID2;
    UUID2.prototype.make = function(version2) {
      var i;
      var uuid2 = this;
      if (version2 === 1) {
        var date = /* @__PURE__ */ new Date();
        var time_now = date.getTime();
        if (time_now !== time_last)
          time_seq = 0;
        else
          time_seq++;
        time_last = time_now;
        var t = ui64_n2i(time_now);
        ui64_muln(t, 1e3 * 10);
        ui64_add(t, ui64_d2i(1, 178, 29, 210, 19, 129, 64, 0));
        if (time_seq > 0)
          ui64_add(t, ui64_n2i(time_seq));
        var ov;
        ov = ui64_rorn(t, 8);
        uuid2[3] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[2] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[1] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[0] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[5] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[4] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[7] = ov & 255;
        ov = ui64_rorn(t, 8);
        uuid2[6] = ov & 15;
        var clock = prng(2, 255);
        uuid2[8] = clock[0];
        uuid2[9] = clock[1];
        var node = prng(6, 255);
        node[0] |= 1;
        node[0] |= 2;
        for (i = 0; i < 6; i++)
          uuid2[10 + i] = node[i];
      } else if (version2 === 4) {
        var data = prng(16, 255);
        for (i = 0; i < 16; i++)
          this[i] = data[i];
      } else if (version2 === 3 || version2 === 5) {
        var input = "";
        var nsUUID = typeof arguments[1] === "object" && arguments[1] instanceof UUID2 ? arguments[1] : new UUID2().parse(arguments[1]);
        for (i = 0; i < 16; i++)
          input += String.fromCharCode(nsUUID[i]);
        input += arguments[2];
        var s = version2 === 3 ? md5(input) : sha1(input);
        for (i = 0; i < 16; i++)
          uuid2[i] = s.charCodeAt(i);
      } else
        throw new Error("UUID: make: invalid version");
      uuid2[6] &= 15;
      uuid2[6] |= version2 << 4;
      uuid2[8] &= 63;
      uuid2[8] |= 2 << 6;
      return uuid2;
    };
    UUID2.prototype.format = function(type2) {
      var str, arr;
      if (type2 === "z85")
        str = z85_encode(this, 16);
      else if (type2 === "b16") {
        arr = Array(32);
        a2hs(this, 0, 15, true, arr, 0);
        str = arr.join("");
      } else if (type2 === void 0 || type2 === "std") {
        arr = new Array(36);
        a2hs(this, 0, 3, false, arr, 0);
        arr[8] = "-";
        a2hs(this, 4, 5, false, arr, 9);
        arr[13] = "-";
        a2hs(this, 6, 7, false, arr, 14);
        arr[18] = "-";
        a2hs(this, 8, 9, false, arr, 19);
        arr[23] = "-";
        a2hs(this, 10, 15, false, arr, 24);
        str = arr.join("");
      }
      return str;
    };
    UUID2.prototype.toString = function(type2) {
      return this.format(type2);
    };
    UUID2.prototype.toJSON = function() {
      return this.format("std");
    };
    UUID2.prototype.parse = function(str, type2) {
      if (typeof str !== "string")
        throw new Error("UUID: parse: invalid argument (type string expected)");
      if (type2 === "z85")
        z85_decode(str, this);
      else if (type2 === "b16")
        hs2a(str, 0, 35, this, 0);
      else if (type2 === void 0 || type2 === "std") {
        var map = {
          "nil": "00000000-0000-0000-0000-000000000000",
          "ns:DNS": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
          "ns:URL": "6ba7b811-9dad-11d1-80b4-00c04fd430c8",
          "ns:OID": "6ba7b812-9dad-11d1-80b4-00c04fd430c8",
          "ns:X500": "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
        };
        if (map[str] !== void 0)
          str = map[str];
        else if (!str.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/))
          throw new Error('UUID: parse: invalid string representation (expected "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")');
        hs2a(str, 0, 7, this, 0);
        hs2a(str, 9, 12, this, 4);
        hs2a(str, 14, 17, this, 6);
        hs2a(str, 19, 22, this, 8);
        hs2a(str, 24, 35, this, 10);
      }
      return this;
    };
    UUID2.prototype.export = function() {
      var arr = Array(16);
      for (var i = 0; i < 16; i++)
        arr[i] = this[i];
      return arr;
    };
    UUID2.prototype.import = function(arr) {
      if (!(typeof arr === "object" && arr instanceof Array))
        throw new Error("UUID: import: invalid argument (type Array expected)");
      if (arr.length !== 16)
        throw new Error("UUID: import: invalid argument (Array of length 16 expected)");
      for (var i = 0; i < 16; i++) {
        if (typeof arr[i] !== "number")
          throw new Error("UUID: import: invalid array element #" + i + " (type Number expected)");
        if (!(isFinite(arr[i]) && Math.floor(arr[i]) === arr[i]))
          throw new Error("UUID: import: invalid array element #" + i + " (Number with integer value expected)");
        if (!(arr[i] >= 0 && arr[i] <= 255))
          throw new Error("UUID: import: invalid array element #" + i + " (Number with integer value in range 0...255 expected)");
        this[i] = arr[i];
      }
      return this;
    };
    UUID2.prototype.compare = function(other) {
      if (typeof other !== "object")
        throw new Error("UUID: compare: invalid argument (type UUID expected)");
      if (!(other instanceof UUID2))
        throw new Error("UUID: compare: invalid argument (type UUID expected)");
      for (var i = 0; i < 16; i++) {
        if (this[i] < other[i])
          return -1;
        else if (this[i] > other[i])
          return 1;
      }
      return 0;
    };
    UUID2.prototype.equal = function(other) {
      return this.compare(other) === 0;
    };
    UUID2.prototype.fold = function(k) {
      if (typeof k === "undefined")
        throw new Error("UUID: fold: invalid argument (number of fold operations expected)");
      if (k < 1 || k > 4)
        throw new Error("UUID: fold: invalid argument (1-4 fold operations expected)");
      var n = 16 / Math.pow(2, k);
      var hash = new Array(n);
      for (var i = 0; i < n; i++) {
        var h = 0;
        for (var j = 0; i + j < 16; j += n)
          h ^= this[i + j];
        hash[i] = h;
      }
      return hash;
    };
    UUID2.PCG = PCG;
    return UUID2;
  });
})(uuid);
var uuidExports = uuid.exports;
const UUID = /* @__PURE__ */ getDefaultExportFromCjs(uuidExports);
var base64$1 = { exports: {} };
/*! https://mths.be/base64 v1.0.0 by @mathias | MIT license */
base64$1.exports;
(function(module2, exports2) {
  (function(root) {
    var freeExports = exports2;
    var freeModule = module2 && module2.exports == freeExports && module2;
    var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal;
    if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
      root = freeGlobal;
    }
    var InvalidCharacterError = function(message) {
      this.message = message;
    };
    InvalidCharacterError.prototype = new Error();
    InvalidCharacterError.prototype.name = "InvalidCharacterError";
    var error2 = function(message) {
      throw new InvalidCharacterError(message);
    };
    var TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g;
    var decode = function(input) {
      input = String(input).replace(REGEX_SPACE_CHARACTERS, "");
      var length = input.length;
      if (length % 4 == 0) {
        input = input.replace(/==?$/, "");
        length = input.length;
      }
      if (length % 4 == 1 || // http://whatwg.org/C#alphanumeric-ascii-characters
      /[^+a-zA-Z0-9/]/.test(input)) {
        error2(
          "Invalid character: the string to be decoded is not correctly encoded."
        );
      }
      var bitCounter = 0;
      var bitStorage;
      var buffer2;
      var output = "";
      var position = -1;
      while (++position < length) {
        buffer2 = TABLE.indexOf(input.charAt(position));
        bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer2 : buffer2;
        if (bitCounter++ % 4) {
          output += String.fromCharCode(
            255 & bitStorage >> (-2 * bitCounter & 6)
          );
        }
      }
      return output;
    };
    var encode = function(input) {
      input = String(input);
      if (/[^\0-\xFF]/.test(input)) {
        error2(
          "The string to be encoded contains characters outside of the Latin1 range."
        );
      }
      var padding = input.length % 3;
      var output = "";
      var position = -1;
      var a;
      var b;
      var c;
      var buffer2;
      var length = input.length - padding;
      while (++position < length) {
        a = input.charCodeAt(position) << 16;
        b = input.charCodeAt(++position) << 8;
        c = input.charCodeAt(++position);
        buffer2 = a + b + c;
        output += TABLE.charAt(buffer2 >> 18 & 63) + TABLE.charAt(buffer2 >> 12 & 63) + TABLE.charAt(buffer2 >> 6 & 63) + TABLE.charAt(buffer2 & 63);
      }
      if (padding == 2) {
        a = input.charCodeAt(position) << 8;
        b = input.charCodeAt(++position);
        buffer2 = a + b;
        output += TABLE.charAt(buffer2 >> 10) + TABLE.charAt(buffer2 >> 4 & 63) + TABLE.charAt(buffer2 << 2 & 63) + "=";
      } else if (padding == 1) {
        buffer2 = input.charCodeAt(position);
        output += TABLE.charAt(buffer2 >> 2) + TABLE.charAt(buffer2 << 4 & 63) + "==";
      }
      return output;
    };
    var base642 = {
      "encode": encode,
      "decode": decode,
      "version": "1.0.0"
    };
    if (freeExports && !freeExports.nodeType) {
      if (freeModule) {
        freeModule.exports = base642;
      } else {
        for (var key in base642) {
          base642.hasOwnProperty(key) && (freeExports[key] = base642[key]);
        }
      }
    } else {
      root.base64 = base642;
    }
  })(commonjsGlobal);
})(base64$1, base64$1.exports);
var base64Exports = base64$1.exports;
const base64 = /* @__PURE__ */ getDefaultExportFromCjs(base64Exports);
const generateId = () => base64.encode(new UUID(4)).substring(0, 12);
const graftLocation = {
  heading: "block",
  title: "block",
  endTitle: "block",
  remark: "block",
  footnote: "inline",
  xref: "inline",
  noteCaller: "inline",
  esbCat: "inline",
  table: "block",
  tree: "block",
  kv: "block"
};
const graftDefs = { graftLocation };
const tokenEnum$4 = {
  wordLike: 0,
  punctuation: 1,
  lineSpace: 2,
  eol: 3,
  softLineBreak: 4,
  noBreakSpace: 5,
  bareSlash: 6,
  unknown: 7
};
const tokenEnumLabels$1 = Object.entries(tokenEnum$4).sort((a, b) => a[1] - b[1]).map((kv) => kv[0]);
const tokenCategory$3 = {
  wordLike: "wordLike",
  punctuation: "notWordLike",
  lineSpace: "notWordLike",
  eol: "notWordLike",
  softLineBreak: "notWordLike",
  noBreakSpace: "notWordLike",
  bareSlash: "notWordLike",
  unknown: "notWordLike"
};
const tokenDefs = { tokenEnum: tokenEnum$4, tokenEnumLabels: tokenEnumLabels$1, tokenCategory: tokenCategory$3 };
const scopeEnum$3 = {
  blockTag: 0,
  inline: 1,
  chapter: 2,
  pubChapter: 3,
  altChapter: 4,
  verses: 5,
  verse: 6,
  pubVerse: 7,
  altVerse: 8,
  esbCat: 9,
  span: 10,
  table: 11,
  cell: 12,
  milestone: 13,
  spanWithAtts: 14,
  attribute: 15,
  hangingGraft: 16,
  orphanTokens: 17,
  tTableRow: 18,
  tTableCol: 19,
  tTreeNode: 20,
  tTreeParent: 21,
  tTreeChild: 22,
  tTreeContent: 23,
  kvPrimary: 24,
  kvSecondary: 25,
  kvField: 26
};
const scopeEnumLabels$1 = Object.entries(scopeEnum$3).sort((a, b) => a[1] - b[1]).map((kv) => kv[0]);
const splitTagNumber = (fullTagName) => {
  const tagBits = XRegExp.exec(fullTagName, XRegExp("([^1-9]+)(.*)"));
  const tagName = tagBits[1];
  const tagNo = tagBits[2].length > 0 ? tagBits[2] : "1";
  return [tagName, tagNo];
};
const cellScope = (fullTagName) => {
  const tagProps = {
    th: {
      type: "colHeading",
      align: "left"
    },
    thr: {
      type: "colHeading",
      align: "right"
    },
    tc: {
      type: "body",
      align: "left"
    },
    tcr: {
      type: "body",
      align: "right"
    }
  };
  const [tagName, tagNo] = splitTagNumber(fullTagName);
  let tagField = "1";
  if (tagNo.includes("-")) {
    const [fromN, toN] = tagNo.split("-");
    tagField = `${parseInt(toN) - parseInt(fromN) + 1}`;
  }
  return `cell/${tagProps[tagName].type}/${tagProps[tagName].align}/${tagField}`;
};
const labelForScope$6 = (scopeType, scopeFields) => {
  switch (scopeType) {
    case "blockTag":
      return `blockTag/${scopeFields[0]}`;
    case "inline":
      return `inline/${scopeFields[0]}`;
    case "chapter":
      return `chapter/${scopeFields[0]}`;
    case "verses":
      return `verses/${scopeFields[0]}`;
    case "verse":
      return `verse/${scopeFields[0]}`;
    case "span":
      return `span/${scopeFields[0]}`;
    case "table":
      return "table";
    case "cell":
      return cellScope(scopeFields[0]);
    case "milestone":
      return `milestone/${scopeFields[0]}`;
    case "spanWithAtts":
      return `spanWithAtts/${scopeFields[0]}`;
    case "attribute":
      return `attribute/${scopeFields[0]}/${scopeFields[1]}/${scopeFields[2]}/${scopeFields[3]}`;
    case "orphanTokens":
      return `orphanTokens`;
    case "hangingGraft":
      return `hangingGraft`;
    case "pubChapter":
      return `pubChapter/${scopeFields[0]}`;
    case "pubVerse":
      return `pubVerse/${scopeFields[0]}`;
    case "altChapter":
      return `altChapter/${scopeFields[0]}`;
    case "altVerse":
      return `altVerse/${scopeFields[0]}`;
    case "esbCat":
      return `esbCat/${scopeFields[0]}`;
    case "tTableRow":
      return `tTableRow/${scopeFields[0]}`;
    case "tTableCol":
      return `tTableCol/${scopeFields[0]}`;
    case "tTreeNode":
      return `tTreeNode/${scopeFields[0]}`;
    case "tTreeParent":
      return `tTreeParent/${scopeFields[0]}`;
    case "tTreeChild":
      return `tTreeChild/${scopeFields[0]}/${scopeFields[1]}`;
    case "tTreeContent":
      return `tTreeContent/${scopeFields[0]}`;
    case "kvPrimary":
      return `kvPrimary/${scopeFields[0]}`;
    case "kvSecondary":
      return `kvSecondary/${scopeFields[0]}/${scopeFields[1]}`;
    case "kvField":
      return `kvField/${scopeFields[0]}`;
    default:
      throw new Error(`Unknown scope type '${scopeType}' in labelForScope`);
  }
};
const nComponentsForScope$1 = (scopeType) => {
  switch (scopeType) {
    case "orphanTokens":
    case "hangingGraft":
    case "table":
      return 1;
    case "blockTag":
    case "inline":
    case "chapter":
    case "verses":
    case "verse":
    case "span":
    case "milestone":
    case "spanWithAtts":
    case "pubChapter":
    case "altChapter":
    case "pubVerse":
    case "altVerse":
    case "esbCat":
    case "tTableRow":
    case "tTableCol":
    case "tTreeNode":
    case "tTreeParent":
    case "tTreeContent":
    case "kvPrimary":
    case "kvField":
      return 2;
    case "tTreeChild":
    case "kvSecondary":
      return 3;
    case "cell":
      return 4;
    case "attribute":
      return 6;
    default:
      throw new Error(
        `Unknown scope type '${scopeType}' in nComponentsForScope`
      );
  }
};
const scopeDefs = {
  scopeEnum: scopeEnum$3,
  scopeEnumLabels: scopeEnumLabels$1,
  labelForScope: labelForScope$6,
  nComponentsForScope: nComponentsForScope$1
};
const itemEnum$6 = {
  token: 0,
  graft: 1,
  startScope: 2,
  endScope: 3
};
const itemEnumLabels = Object.entries(itemEnum$6).sort((a, b) => a[1] - b[1]).map((kv) => kv[0]);
const itemArray2Object = (a) => ({
  type: a[0],
  subType: a[1],
  payload: a[2]
});
const itemObject2Array = (ob) => [ob.type, ob.subType, ob.payload];
const itemArrays2Objects = (aa) => aa.map((a) => itemArray2Object(a));
const itemObjects2Arrays = (obs) => obs.map((ob) => itemObject2Array(ob));
const itemDefs = {
  itemEnum: itemEnum$6,
  itemEnumLabels,
  itemArray2Object,
  itemObject2Array,
  itemArrays2Objects,
  itemObjects2Arrays
};
const headerBytes$2 = (succinct2, pos) => {
  const headerByte = succinct2.byte(pos);
  const itemType = headerByte >> 6;
  const itemLength = headerByte & 63;
  const itemSubtype = succinct2.byte(pos + 1);
  return [itemLength, itemType, itemSubtype];
};
const succinctTokenChars$1 = (enums2, enumIndexes2, succinct2, itemSubtype, pos) => {
  const itemCategory = tokenDefs.tokenCategory[tokenDefs.tokenEnumLabels[itemSubtype]];
  const itemIndex = enumIndexes2[itemCategory][succinct2.nByte(pos + 2)];
  return enums2[itemCategory].countedString(itemIndex);
};
const succinctScopeLabel$1 = (enums2, enumIndexes2, succinct2, itemSubtype, pos) => {
  const scopeType = scopeDefs.scopeEnumLabels[itemSubtype];
  let nScopeBits = scopeDefs.nComponentsForScope(scopeType);
  let offset = 2;
  let scopeBits = "";
  while (nScopeBits > 1) {
    const itemIndexIndex = succinct2.nByte(pos + offset);
    const itemIndex = enumIndexes2.scopeBits[itemIndexIndex];
    const scopeBitString = enums2.scopeBits.countedString(itemIndex);
    scopeBits += `/${scopeBitString}`;
    offset += succinct2.nByteLength(itemIndexIndex);
    nScopeBits--;
  }
  return `${scopeType}${scopeBits}`;
};
const succinctScopeType = (itemSubtype) => {
  return scopeDefs.scopeEnumLabels[itemSubtype];
};
const succinctGraftName$1 = (enums2, enumIndexes2, itemSubtype) => {
  const graftIndex = enumIndexes2.graftTypes[itemSubtype];
  return enums2.graftTypes.countedString(graftIndex);
};
const succinctGraftSeqId$1 = (enums2, enumIndexes2, succinct2, pos) => {
  const seqIndex = enumIndexes2.ids[succinct2.nByte(pos + 2)];
  return enums2.ids.countedString(seqIndex);
};
const enumIndexes$1 = (enums2) => {
  const ret = {};
  for (const [category, succinct2] of Object.entries(enums2)) {
    ret[category] = enumIndex$1(category, succinct2);
  }
  return ret;
};
const enumIndex$1 = (category, enumSuccinct) => {
  const indexSuccinct = new Uint32Array(enumSuccinct.length);
  let pos = 0;
  let count = 0;
  while (pos < enumSuccinct.length) {
    indexSuccinct[count] = pos;
    const stringLength = enumSuccinct.byte(pos);
    pos += stringLength + 1;
    count += 1;
  }
  return indexSuccinct;
};
const unpackEnum = (succinct2, includeIndex) => {
  if (!includeIndex) {
    includeIndex = false;
  }
  let pos = 0;
  let count = 0;
  const ret = [];
  while (pos < succinct2.length) {
    const stringLength = succinct2.byte(pos);
    const unpacked = succinct2.countedString(pos);
    ret.push(includeIndex ? [count, unpacked] : unpacked);
    pos += stringLength + 1;
    count++;
  }
  return ret;
};
const undefinedArgError = (func, field) => {
  throw new Error(`Undefined or null argument '${field}' in '${func}'`);
};
const pushSuccinctTokenBytes$3 = (bA, tokenEnumIndex, charsEnumIndex) => {
  if (tokenEnumIndex === void 0 || tokenEnumIndex === null) {
    undefinedArgError("pushSuccinctTokenBytes", "tokenEnumIndex");
  }
  if (charsEnumIndex === void 0 || charsEnumIndex === null) {
    undefinedArgError("pushSuccinctTokenBytes", "charsEnumIndex");
  }
  const lengthPos = bA.length;
  bA.pushByte(0);
  bA.pushByte(tokenEnumIndex);
  bA.pushNByte(charsEnumIndex);
  bA.setByte(
    lengthPos,
    bA.length - lengthPos | itemDefs.itemEnum.token << 6
  );
};
const pushSuccinctGraftBytes$3 = (bA, graftTypeEnumIndex, seqEnumIndex) => {
  if (graftTypeEnumIndex === void 0 || graftTypeEnumIndex === null) {
    undefinedArgError("pushSuccinctGraftBytes", "graftTypeEnumIndex");
  }
  if (seqEnumIndex === void 0 || seqEnumIndex === null) {
    undefinedArgError("pushSuccinctGraftBytes", "seqEnumIndex");
  }
  const lengthPos = bA.length;
  bA.pushByte(0);
  bA.pushByte(graftTypeEnumIndex);
  bA.pushNByte(seqEnumIndex);
  bA.setByte(
    lengthPos,
    bA.length - lengthPos | itemDefs.itemEnum.graft << 6
  );
};
const pushSuccinctScopeBytes$3 = (bA, itemTypeByte, scopeTypeByte, scopeBitBytes) => {
  if (itemTypeByte === void 0 || itemTypeByte === null) {
    undefinedArgError("pushSuccinctScopeBytes", "itemTypeByte");
  }
  if (scopeTypeByte === void 0 || scopeTypeByte === null) {
    undefinedArgError("pushSuccinctScopeBytes", "scopeTypeByte");
  }
  if (scopeBitBytes === void 0 || scopeBitBytes === null) {
    undefinedArgError("pushSuccinctScopeBytes", "scopeBitBytes");
  }
  const lengthPos = bA.length;
  bA.pushByte(0);
  bA.pushByte(scopeTypeByte);
  for (const sbb of scopeBitBytes) {
    bA.pushNByte(sbb);
  }
  bA.setByte(lengthPos, bA.length - lengthPos | itemTypeByte << 6);
};
const succinct = {
  enumIndex: enumIndex$1,
  enumIndexes: enumIndexes$1,
  headerBytes: headerBytes$2,
  pushSuccinctTokenBytes: pushSuccinctTokenBytes$3,
  pushSuccinctGraftBytes: pushSuccinctGraftBytes$3,
  pushSuccinctScopeBytes: pushSuccinctScopeBytes$3,
  succinctTokenChars: succinctTokenChars$1,
  succinctScopeLabel: succinctScopeLabel$1,
  succinctScopeType,
  succinctGraftName: succinctGraftName$1,
  succinctGraftSeqId: succinctGraftSeqId$1,
  unpackEnum
};
const inspectEnum = (enumString) => {
  const ba = new ByteArray$6();
  ba.fromBase64(enumString);
  const ret = [];
  ret.push(`* Char length ${ba.length} *`);
  for (const [count, text] of succinct.unpackEnum(ba, true)) {
    ret.push(`${count}	"${text}"`);
  }
  return ret.join("\n");
};
const inspectSuccinct = (succinctdoc, enumStrings) => {
  const ba = new ByteArray$6();
  ba.fromBase64(succinctdoc);
  const enums2 = {};
  for (const [category, enumString] of Object.entries(enumStrings)) {
    enums2[category] = new ByteArray$6();
    enums2[category].fromBase64(enumString);
  }
  const indexes = succinct.enumIndexes(enums2);
  const ret = [];
  ret.push(`* Char length ${ba.length} *`);
  let pos = 0;
  while (pos < ba.length) {
    const [itemLength, itemType, itemSubtype] = succinct.headerBytes(ba, pos);
    let subtypeLabel = itemSubtype;
    let extra = "";
    switch (itemDefs.itemEnumLabels[itemType]) {
      case "token":
        subtypeLabel = tokenDefs.tokenEnumLabels[itemSubtype];
        extra = `"${succinct.succinctTokenChars(
          enums2,
          indexes,
          ba,
          itemSubtype,
          pos
        )}"`;
        break;
      case "startScope":
      case "endScope":
        subtypeLabel = scopeDefs.scopeEnumLabels[itemSubtype];
        extra = succinct.succinctScopeLabel(
          enums2,
          indexes,
          ba,
          itemSubtype,
          pos
        );
        break;
      case "graft":
        subtypeLabel = succinct.succinctGraftName(enums2, indexes, itemSubtype);
        extra = succinct.succinctGraftSeqId(enums2, indexes, ba, pos);
    }
    ret.push(
      `${itemDefs.itemEnumLabels[itemType]}	${subtypeLabel}	(${itemLength})	${extra}`
    );
    pos += itemLength;
  }
  return ret.join("\n");
};
const inspect = { inspectEnum, inspectSuccinct };
const parserConstants = {
  usfm: {
    baseSequenceTypes: {
      main: "1",
      introduction: "*",
      introTitle: "?",
      introEndTitle: "?",
      title: "?",
      endTitle: "?",
      heading: "*",
      header: "*",
      remark: "*",
      sidebar: "*",
      table: "*",
      tree: "*",
      kv: "*"
    },
    inlineSequenceTypes: {
      footnote: "*",
      noteCaller: "*",
      xref: "*",
      pubNumber: "*",
      altNumber: "*",
      esbCat: "*",
      fig: "*",
      temp: "?"
    }
  }
};
const validateTags$2 = (tags2) => {
  for (const tag of tags2) {
    validateTag(tag);
  }
};
const validateTag = (tag) => {
  if (!XRegExp.exec(tag, /^[a-z][A-za-z0-9]*(:.+)?$/)) {
    throw new Error(
      `Tag '${tag}' is not valid (should be [a-z][A-za-z0-9]*(:.+)?)`
    );
  }
};
const addTag$3 = (tags2, tag) => {
  validateTag(tag);
  tags2.add(tag);
};
const removeTag$2 = (tags2, tag) => {
  validateTag(tag);
  tags2.delete(tag);
};
const tags = { validateTags: validateTags$2, validateTag, addTag: addTag$3, removeTag: removeTag$2 };
const cvMappingType = 2;
const bcvMappingType = 3;
const bookCodes = [
  // From Paratext via Scripture Burrito
  "GEN",
  "EXO",
  "LEV",
  "NUM",
  "DEU",
  "JOS",
  "JDG",
  "RUT",
  "1SA",
  "2SA",
  "1KI",
  "2KI",
  "1CH",
  "2CH",
  "EZR",
  "NEH",
  "EST",
  "JOB",
  "PSA",
  "PRO",
  "ECC",
  "SNG",
  "ISA",
  "JER",
  "LAM",
  "EZK",
  "DAN",
  "HOS",
  "JOL",
  "AMO",
  "OBA",
  "JON",
  "MIC",
  "NAM",
  "HAB",
  "ZEP",
  "HAG",
  "ZEC",
  "MAL",
  "MAT",
  "MRK",
  "LUK",
  "JHN",
  "ACT",
  "ROM",
  "1CO",
  "2CO",
  "GAL",
  "EPH",
  "PHP",
  "COL",
  "1TH",
  "2TH",
  "1TI",
  "2TI",
  "TIT",
  "PHM",
  "HEB",
  "JAS",
  "1PE",
  "2PE",
  "1JN",
  "2JN",
  "3JN",
  "JUD",
  "REV",
  "TOB",
  "JDT",
  "ESG",
  "WIS",
  "SIR",
  "BAR",
  "LJE",
  "S3Y",
  "SUS",
  "BEL",
  "1MA",
  "2MA",
  "3MA",
  "4MA",
  "1ES",
  "2ES",
  "MAN",
  "PS2",
  "ODA",
  "PSS",
  "JSA",
  "JDB",
  "TBS",
  "SST",
  "DNT",
  "BLT",
  "EZA",
  "5EZ",
  "6EZ",
  "DAG",
  "PS3",
  "2BA",
  "LBA",
  "JUB",
  "ENO",
  "1MQ",
  "2MQ",
  "3MQ",
  "REP",
  "4BA",
  "LAO"
];
const bookCodeIndex = () => {
  const ret = {};
  for (const [bookN, book] of Object.entries(bookCodes)) {
    ret[book] = parseInt(bookN);
  }
  return ret;
};
const vrs2json = (vrsString) => {
  const ret = {};
  for (const vrsLineBits of vrsString.split(/[\n\r]+/).map((l) => l.trim()).map(
    (l) => XRegExp.exec(
      l,
      XRegExp(
        "^([A-Z1-6]{3} [0-9]+:[0-9]+(-[0-9]+)?) = ([A-Z1-6]{3} [0-9]+:[0-9]+[a-z]?(-[0-9]+)?)$"
      )
    )
  )) {
    if (!vrsLineBits) {
      continue;
    }
    if (!(vrsLineBits[1] in ret)) {
      ret[vrsLineBits[1]] = [];
    }
    ret[vrsLineBits[1]].push(vrsLineBits[3]);
  }
  return { mappedVerses: ret };
};
const reverseVersification = (vrsJson) => {
  const ret = {};
  for (const [fromSpec, toSpecs] of Object.entries(vrsJson.mappedVerses)) {
    for (const toSpec of toSpecs) {
      if (toSpec in ret) {
        ret[toSpec].push(fromSpec);
      } else {
        ret[toSpec] = [fromSpec];
      }
    }
  }
  return { reverseMappedVerses: ret };
};
const preSuccinctVerseMapping = (mappingJson) => {
  const ret = {};
  for (let [fromSpec, toSpecs] of Object.entries(mappingJson)) {
    if (typeof toSpecs === "string") {
      toSpecs = [toSpecs];
    }
    const [fromBook, fromCVV] = fromSpec.split(" ");
    const toBook = toSpecs[0].split(" ")[0];
    const record = toBook === fromBook ? ["cv"] : ["bcv"];
    let [fromCh, fromV] = fromCVV.split(":");
    let toV = fromV;
    if (fromV.includes("-")) {
      const vBits = fromV.split("-");
      fromV = vBits[0];
      toV = vBits[1];
    }
    record.push([parseInt(fromV), parseInt(toV)]);
    record.push([]);
    for (const toCVV of toSpecs.map((ts) => ts.split(" ")[1])) {
      let [toCh, fromV2] = toCVV.split(":");
      let toV2 = fromV2;
      if (fromV2.includes("-")) {
        const vBits = fromV2.split("-");
        fromV2 = vBits[0];
        toV2 = vBits[1];
      }
      if (record[0] === "cv") {
        record[2].push([parseInt(toCh), parseInt(fromV2), parseInt(toV2)]);
      } else {
        record[2].push([
          parseInt(toCh),
          parseInt(fromV2),
          parseInt(toV2),
          toBook
        ]);
      }
    }
    if (!(fromBook in ret)) {
      ret[fromBook] = {};
    }
    if (!(fromCh in ret[fromBook])) {
      ret[fromBook][fromCh] = [];
    }
    ret[fromBook][fromCh].push(record);
  }
  return ret;
};
const succinctifyVerseMappings = (preSuccinct) => {
  const ret = {};
  const bci = bookCodeIndex();
  for (const [book, chapters] of Object.entries(
    preSuccinctVerseMapping(preSuccinct)
  )) {
    ret[book] = {};
    for (const [chapter, mappings] of Object.entries(chapters)) {
      ret[book][chapter] = succinctifyVerseMapping(mappings, bci);
    }
  }
  return ret;
};
const succinctifyVerseMapping = (preSuccinctBC, bci) => {
  const makeMappingLengthByte = (recordType, length) => length + recordType * 64;
  const ret = new ByteArray$6(64);
  for (const [
    recordTypeStr,
    [fromVerseStart, fromVerseEnd],
    mappings
  ] of preSuccinctBC) {
    const pos = ret.length;
    const recordType = recordTypeStr === "bcv" ? bcvMappingType : cvMappingType;
    ret.pushNBytes([0, fromVerseStart, fromVerseEnd]);
    if (recordType === bcvMappingType) {
      const bookIndex = bci[mappings[0][3]];
      ret.pushNByte(bookIndex);
    }
    ret.pushNByte(mappings.length);
    for (const [ch, fromV] of mappings) {
      ret.pushNBytes([ch, fromV]);
    }
    const recordLength = ret.length - pos;
    if (recordLength > 63) {
      throw new Error(
        `Mapping in succinctifyVerseMapping ${JSON.stringify(
          mappings
        )} is too long (${recordLength} bytes)`
      );
    }
    ret.setByte(pos, makeMappingLengthByte(recordType, recordLength));
  }
  ret.trim();
  return ret;
};
const mappingLengthByte = (succinct2, pos) => {
  const sByte = succinct2.byte(pos);
  return [sByte >> 6, sByte % 64];
};
const unsuccinctifyVerseMapping = (succinctBC, fromBookCode, bci) => {
  const ret = [];
  let pos = 0;
  while (pos < succinctBC.length) {
    let recordPos = pos;
    const unsuccinctRecord = {};
    const [recordType, recordLength] = mappingLengthByte(succinctBC, pos);
    recordPos++;
    unsuccinctRecord.fromVerseStart = succinctBC.nByte(recordPos);
    recordPos += succinctBC.nByteLength(unsuccinctRecord.fromVerseStart);
    unsuccinctRecord.fromVerseEnd = succinctBC.nByte(recordPos);
    recordPos += succinctBC.nByteLength(unsuccinctRecord.fromVerseEnd);
    unsuccinctRecord.bookCode = fromBookCode;
    if (recordType === bcvMappingType) {
      const bookIndex = succinctBC.nByte(recordPos);
      unsuccinctRecord.bookCode = bookCodes[bookIndex];
      recordPos += succinctBC.nByteLength(bookIndex);
    }
    const nMappings = succinctBC.nByte(recordPos);
    recordPos += succinctBC.nByteLength(nMappings);
    const mappings = [];
    while (mappings.length < nMappings) {
      const mapping = {};
      mapping.ch = succinctBC.nByte(recordPos);
      recordPos += succinctBC.nByteLength(mapping.ch);
      mapping.verseStart = succinctBC.nByte(recordPos);
      recordPos += succinctBC.nByteLength(mapping.verseStart);
      mappings.push(mapping);
    }
    unsuccinctRecord.mapping = mappings;
    ret.push(unsuccinctRecord);
    pos += recordLength;
  }
  return ret;
};
const mapVerse = (succinct2, b, c, v) => {
  let ret = null;
  let pos = 0;
  while (pos < succinct2.length) {
    let recordPos = pos;
    const [recordType, recordLength] = mappingLengthByte(succinct2, pos);
    recordPos++;
    const fromVerseStart = succinct2.nByte(recordPos);
    recordPos += succinct2.nByteLength(fromVerseStart);
    const fromVerseEnd = succinct2.nByte(recordPos);
    recordPos += succinct2.nByteLength(fromVerseEnd);
    if (v < fromVerseStart || v > fromVerseEnd) {
      pos += recordLength;
      continue;
    }
    let bookCode = b;
    if (recordType === bcvMappingType) {
      const bookIndex = succinct2.nByte(recordPos);
      bookCode = bookCodes[bookIndex];
      recordPos += succinct2.nByteLength(bookIndex);
    }
    ret = [bookCode, []];
    const nMappings = succinct2.nByte(recordPos);
    recordPos += succinct2.nByteLength(nMappings);
    while (ret[1].length < nMappings) {
      const ch = succinct2.nByte(recordPos);
      recordPos += succinct2.nByteLength(ch);
      const verseStart = succinct2.nByte(recordPos);
      recordPos += succinct2.nByteLength(verseStart);
      ret[1].push([ch, v - fromVerseStart + verseStart]);
    }
    break;
  }
  return ret || [b, [[c, v]]];
};
const versification = {
  vrs2json,
  reverseVersification,
  preSuccinctVerseMapping,
  bookCodes,
  succinctifyVerseMapping,
  succinctifyVerseMappings,
  unsuccinctifyVerseMapping,
  bookCodeIndex,
  mapVerse
};
const utils = {
  ByteArray: ByteArray$6,
  canons,
  enums,
  generateId,
  graftDefs,
  inspect,
  itemDefs,
  parserConstants,
  scopeDefs,
  succinct,
  tags,
  tokenDefs,
  versification
};
const validateSelectors = (docSet, selectors) => {
  if (typeof selectors !== "object") {
    throw new Error(
      `DocSet constructor expects selectors to be object, found ${typeof docSet.selectors}`
    );
  }
  const expectedSelectors = {};
  for (const selector of docSet.processor.selectors) {
    expectedSelectors[selector.name] = selector;
  }
  for (const [name2, value] of Object.entries(selectors)) {
    if (!(name2 in expectedSelectors)) {
      throw new Error(
        `Unexpected selector '${name2}' (expected one of [${Object.keys(
          expectedSelectors
        ).join(", ")}])`
      );
    }
    if (typeof value === "string" && expectedSelectors[name2].type !== "string" || typeof value === "number" && expectedSelectors[name2].type !== "integer") {
      throw new Error(
        `Selector '${name2}' is of type ${typeof value} (expected ${expectedSelectors[name2].type})`
      );
    }
    if (typeof value === "number") {
      if (!Number.isInteger(value)) {
        throw new Error(
          `Value '${value}' of integer selector '${name2}' is not an integer`
        );
      }
      if ("min" in expectedSelectors[name2] && value < expectedSelectors[name2].min) {
        throw new Error(
          `Value '${value}' is less than ${expectedSelectors[name2].min}`
        );
      }
      if ("max" in expectedSelectors[name2] && value > expectedSelectors[name2].max) {
        throw new Error(
          `Value '${value}' is greater than ${expectedSelectors[name2].max}`
        );
      }
    } else {
      if ("regex" in expectedSelectors[name2] && !XRegExp.exec(value, XRegExp(expectedSelectors[name2].regex), 0)) {
        throw new Error(
          `Value '${value}' does not match regex '${expectedSelectors[name2].regex}'`
        );
      }
    }
    if ("enum" in expectedSelectors[name2] && !expectedSelectors[name2].enum.includes(value)) {
      throw new Error(`Value '${value}' of selector '${name2}' is not in enum`);
    }
  }
  for (const name2 of Object.keys(expectedSelectors)) {
    if (!(name2 in selectors)) {
      throw new Error(`Expected selector '${name2}' not found`);
    }
  }
  return selectors;
};
const blocksWithScriptureCV = (docSet, blocks, cv) => {
  const hasMiddleChapter = (b, fromC, toC) => {
    const blockChapterScopes = [
      ...docSet.unsuccinctifyScopes(b.os).map((s) => s[2]),
      ...docSet.unsuccinctifyScopes(b.is).map((s) => s[2])
    ].filter((s) => s.startsWith("chapter/"));
    return blockChapterScopes.map((s) => parseInt(s.split("/")[1])).filter((n) => n > fromC && n < toC).length > 0;
  };
  const hasFirstChapter = (b, fromC, fromV) => {
    const hasFirstChapterScope = [
      ...docSet.unsuccinctifyScopes(b.os).map((s) => s[2]),
      ...docSet.unsuccinctifyScopes(b.is).map((s) => s[2])
    ].includes(`chapter/${fromC}`);
    return hasFirstChapterScope && docSet.blockHasMatchingItem(
      b,
      (item, openScopes) => {
        if (!openScopes.has(`chapter/${fromC}`)) {
          return false;
        }
        return Array.from(openScopes).filter((s) => s.startsWith("verse/")).filter((s) => parseInt(s.split("/")[1]) >= fromV).length > 0 || fromV === 0 && item[0] === "token" && item[2] && Array.from(openScopes).filter((s) => s.startsWith("verse")).length === 0;
      },
      {}
    );
  };
  const hasLastChapter = (b, toC, toV) => {
    const hasLastChapterScope = [
      ...docSet.unsuccinctifyScopes(b.os).map((s) => s[2]),
      ...docSet.unsuccinctifyScopes(b.is).map((s) => s[2])
    ].includes(`chapter/${toC}`);
    return hasLastChapterScope && docSet.blockHasMatchingItem(
      b,
      (item, openScopes) => {
        if (!openScopes.has(`chapter/${toC}`)) {
          return false;
        }
        return Array.from(openScopes).filter((s) => s.startsWith("verse/")).filter((s) => parseInt(s.split("/")[1]) <= toV).length > 0 || toV === 0 && item[0] === "token" && item[2] && Array.from(openScopes).filter((s) => s.startsWith("verse")).length === 0;
      },
      {}
    );
  };
  if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*$"))) {
    const scopes = [`chapter/${cv}`];
    return blocks.filter((b) => docSet.allScopesInBlock(b, scopes));
  } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*-[1-9][0-9]*$"))) {
    const [fromC, toC] = cv.split("-").map((v) => parseInt(v));
    if (fromC > toC) {
      throw new Error(`Chapter range must be from min to max, not '${cv}'`);
    }
    const scopes = [...Array(toC - fromC + 1).keys()].map(
      (n) => `chapter/${n + fromC}`
    );
    return blocks.filter((b) => docSet.anyScopeInBlock(b, scopes));
  } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*:[0-9]+$"))) {
    const [fromC, fromV] = cv.split(":").map((v) => parseInt(v));
    if (fromV === 0) {
      const scopes = [`chapter/${fromC}`];
      return blocks.filter((b) => docSet.allScopesInBlock(b, scopes)).filter(
        (b) => [...docSet.allBlockScopes(b)].filter((s) => s.startsWith("verse")).length === 0
      );
    } else {
      const scopes = [`chapter/${fromC}`, `verse/${fromV}`];
      return blocks.filter((b) => docSet.allScopesInBlock(b, scopes));
    }
  } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*:[0-9]+-[1-9][0-9]*$"))) {
    const [fromC, vs] = cv.split(":");
    const [fromV, toV] = vs.split("-").map((v) => parseInt(v));
    if (fromV > toV) {
      throw new Error(`Verse range must be from min to max, not '${vs}'`);
    }
    const chapterScopes = [`chapter/${fromC}`];
    const verseScopes = [...Array(toV - fromV + 1).keys()].map(
      (n) => `verse/${n + fromV}`
    );
    return blocks.filter((b) => docSet.allScopesInBlock(b, chapterScopes)).filter(
      (b) => docSet.anyScopeInBlock(b, verseScopes) || fromV === 0 && [...docSet.allBlockScopes(b)].filter((s) => s.startsWith("verse")).length === 0
    );
  } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*:[0-9]+-[1-9][0-9]*:[0-9]+$"))) {
    const [fromCV, toCV] = cv.split("-");
    const [fromC, fromV] = fromCV.split(":").map((c) => parseInt(c));
    const [toC, toV] = toCV.split(":").map((v) => parseInt(v));
    if (fromC > toC) {
      throw new Error(
        `Chapter range must be from min to max, not '${fromC}-${toV}'`
      );
    }
    const chapterScopes = [...Array(toC - fromC + 1).keys()].map(
      (n) => `chapter/${n + fromC}`
    );
    const chapterBlocks = blocks.filter(
      (b) => docSet.anyScopeInBlock(b, chapterScopes)
    );
    return chapterBlocks.filter(
      (b) => hasMiddleChapter(b, fromC, toC) || hasFirstChapter(b, fromC, fromV) || hasLastChapter(b, toC, toV)
    );
  } else {
    throw new Error(`Bad cv reference '${cv}'`);
  }
};
const allBlockScopes = (docSet, block2) => {
  const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
    block2.bs,
    0
  );
  const blockScope = docSet.unsuccinctifyScope(
    block2.bs,
    itemType,
    itemSubtype,
    0
  );
  return /* @__PURE__ */ new Set([
    ...docSet.unsuccinctifyScopes(block2.os).map((s) => s[2]),
    ...docSet.unsuccinctifyScopes(block2.is).map((s) => s[2]),
    blockScope[2]
  ]);
};
const allScopesInBlock = (docSet, block2, scopes) => {
  const allBlockScopes2 = docSet.allBlockScopes(block2);
  for (const scope2 of scopes) {
    if (!allBlockScopes2.has(scope2)) {
      return false;
    }
  }
  return true;
};
const anyScopeInBlock = (docSet, block2, scopes) => {
  const allBlockScopes2 = docSet.allBlockScopes(block2);
  for (const scope2 of scopes) {
    if (allBlockScopes2.has(scope2)) {
      return true;
    }
  }
  return false;
};
const blockHasBlockScope = (docSet, block2, scope2) => {
  const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
    block2.bs,
    0
  );
  const blockScope = docSet.unsuccinctifyScope(
    block2.bs,
    itemType,
    itemSubtype,
    0
  );
  return blockScope[2] === scope2;
};
const blockHasChars = (docSet, block2, charsIndexes) => {
  let ret = false;
  let pos = 0;
  const succinct2 = block2.c;
  if (charsIndexes.includes(-1)) {
    return false;
  }
  while (!ret && pos < succinct2.length) {
    const [itemLength, itemType] = utils.succinct.headerBytes(succinct2, pos);
    if (itemType === utils.itemDefs.itemEnum["token"]) {
      if (charsIndexes.includes(succinct2.nByte(pos + 2))) {
        ret = true;
      }
    }
    pos += itemLength;
  }
  return ret;
};
const blockHasMatchingItem = (docSet, block2, testFunction, options2) => {
  const openScopes = new Set(
    docSet.unsuccinctifyScopes(block2.os).map((ri) => ri[2])
  );
  for (const item of docSet.unsuccinctifyItems(block2.c, options2, 0)) {
    if (item[0] === "scope" && item[1] === "start") {
      openScopes.add(item[2]);
    }
    if (testFunction(item, openScopes)) {
      return true;
    }
    if (item[0] === "scope" && item[1] === "end") {
      openScopes.delete(item[2]);
    }
  }
  return false;
};
const unsuccinctifyBlock = (docSet, block2, options2) => {
  docSet.maybeBuildEnumIndexes();
  const succinctBlockScope = block2.bs;
  const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
    succinctBlockScope,
    0
  );
  const blockScope = docSet.unsuccinctifyScope(
    succinctBlockScope,
    itemType,
    itemSubtype,
    0
  );
  const blockGrafts = docSet.unsuccinctifyGrafts(block2.bg);
  const openScopes = docSet.unsuccinctifyScopes(block2.os);
  const includedScopes = docSet.unsuccinctifyScopes(block2.is);
  const nextToken = block2.nt.nByte(0);
  const blockItems = docSet.unsuccinctifyItems(
    block2.c,
    options2 || {},
    nextToken
  );
  return {
    bs: blockScope,
    bg: blockGrafts,
    c: blockItems,
    os: openScopes,
    is: includedScopes,
    nt: nextToken
  };
};
const unsuccinctifyItems = (docSet, succinct2, options2, nextToken, openScopes) => {
  if (nextToken === void 0) {
    throw new Error(
      "nextToken (previously includeContext) must now be provided to unsuccinctifyItems"
    );
  }
  if (nextToken !== null && typeof nextToken !== "number") {
    throw new Error(
      `nextToken (previously includeContext) must be null or an integer, not ${typeof nextToken} '${JSON.stringify(
        nextToken
      )}' in unsuccinctifyItems`
    );
  }
  const ret = [];
  let pos = 0;
  let tokenCount = nextToken || 0;
  const scopes = new Set(openScopes || []);
  const scopeEnums = [utils.itemDefs.itemEnum.startScope, utils.itemDefs.itemEnum.endScope];
  while (pos < succinct2.length) {
    const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
      succinct2,
      pos
    );
    if (Object.keys(options2).length > 0) {
      if (!options2.scopes && scopeEnums.includes(itemType)) {
        pos += itemLength;
        continue;
      }
      if (!options2.tokens && itemType === utils.itemDefs.itemEnum.token) {
        pos += itemLength;
        continue;
      }
      if (!options2.grafts && itemType === utils.itemDefs.itemEnum.graft) {
        pos += itemLength;
        continue;
      }
    }
    if (scopeEnums.includes(itemType)) {
      const itemTypeName = utils.succinct.succinctScopeType(itemSubtype);
      if (Object.keys(options2).length > 0 && options2.scopes && options2.excludeScopeTypes && options2.excludeScopeTypes.includes(itemTypeName)) {
        pos += itemLength;
        continue;
      }
    }
    const item = docSet.unsuccinctifyItem(succinct2, pos, {})[0];
    if (item[0] === "token") {
      if (Object.keys(options2).length === 0 || options2.tokens) {
        if (nextToken !== null) {
          item.push(
            item[0] === "token" && item[1] === "wordLike" ? tokenCount++ : null
          );
          item.push([...scopes]);
        }
        ret.push(item);
      }
    } else if (item[0] === "scope" && item[1] === "start") {
      if (Object.keys(options2).length === 0 || options2.scopes) {
        scopes.add(item[2]);
        ret.push(item);
      }
    } else if (item[0] === "scope" && item[1] === "end") {
      if (Object.keys(options2).length === 0 || options2.scopes) {
        scopes.delete(item[2]);
        ret.push(item);
      }
    } else if (item[0] === "graft") {
      if (Object.keys(options2).length === 0 || options2.grafts) {
        ret.push(item);
      }
    }
    pos += itemLength;
  }
  return ret;
};
const unsuccinctifyItem = (docSet, succinct2, pos, options2) => {
  let item = null;
  const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
    succinct2,
    pos
  );
  switch (itemType) {
    case utils.itemDefs.itemEnum.token:
      if (Object.keys(options2).length === 0 || options2.tokens) {
        item = docSet.unsuccinctifyToken(succinct2, itemSubtype, pos);
      }
      break;
    case utils.itemDefs.itemEnum.startScope:
    case utils.itemDefs.itemEnum.endScope:
      if (Object.keys(options2).length === 0 || options2.scopes) {
        item = docSet.unsuccinctifyScope(succinct2, itemType, itemSubtype, pos);
      }
      break;
    case utils.itemDefs.itemEnum.graft:
      if (Object.keys(options2).length === 0 || options2.grafts) {
        item = docSet.unsuccinctifyGraft(succinct2, itemSubtype, pos);
      }
      break;
  }
  return [item, itemLength];
};
const unsuccinctifyPrunedItems = (docSet, block2, options2) => {
  const openScopes = new Set(
    docSet.unsuccinctifyScopes(block2.os).map((ri) => ri[2])
  );
  const requiredScopes = options2.requiredScopes || [];
  const anyScope = options2.anyScope || false;
  const allScopesInItem = () => {
    for (const scope2 of requiredScopes) {
      if (!openScopes.has(scope2)) {
        return false;
      }
    }
    return true;
  };
  const anyScopeInItem = () => {
    for (const scope2 of requiredScopes) {
      if (openScopes.has(scope2)) {
        return true;
      }
    }
    return requiredScopes.length === 0;
  };
  const scopeTest = anyScope ? anyScopeInItem : allScopesInItem;
  const charsTest = (item) => !options2.withChars || options2.withChars.length === 0 || item[0] === "token" && options2.withChars.includes(item[2]);
  const ret = [];
  for (const item of docSet.unsuccinctifyItems(
    block2.c,
    options2,
    block2.nt.nByte(0),
    openScopes
  )) {
    if (item[0] === "scope" && item[1] === "start") {
      openScopes.add(item[2]);
    }
    if (scopeTest() && charsTest(item)) {
      ret.push(item);
    }
    if (item[0] === "scope" && item[1] === "end") {
      openScopes.delete(item[2]);
    }
  }
  return ret;
};
const unsuccinctifyItemsWithScriptureCV = (docSet, block2, cv, options2) => {
  options2 = options2 || {};
  const openScopes = new Set(
    docSet.unsuccinctifyScopes(block2.os).map((ri) => ri[2])
  );
  const cvMatchFunction = () => {
    if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*$"))) {
      return () => openScopes.has(`chapter/${cv}`);
    } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*-[1-9][0-9]*$"))) {
      return () => {
        const [fromC, toC] = cv.split("-").map((v) => parseInt(v));
        if (fromC > toC) {
          throw new Error(`Chapter range must be from min to max, not '${cv}'`);
        }
        for (const scope2 of [...Array(toC - fromC + 1).keys()].map(
          (n) => `chapter/${n + fromC}`
        )) {
          if (openScopes.has(scope2)) {
            return true;
          }
        }
        return false;
      };
    } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*:[0-9]+$"))) {
      return () => {
        const [fromC, fromV] = cv.split(":").map((v) => parseInt(v));
        if (fromV === 0) {
          return openScopes.has(`chapter/${fromC}`) && [...openScopes].filter((s) => s.startsWith("verse")).length === 0;
        } else {
          for (const scope2 of [`chapter/${fromC}`, `verse/${fromV}`]) {
            if (!openScopes.has(scope2)) {
              return false;
            }
          }
          return true;
        }
      };
    } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*:[0-9]+-[1-9][0-9]*$"))) {
      return () => {
        const [fromC, vs] = cv.split(":");
        const [fromV, toV] = vs.split("-").map((v) => parseInt(v));
        if (fromV > toV) {
          throw new Error(`Verse range must be from min to max, not '${vs}'`);
        }
        const chapterScope = `chapter/${fromC}`;
        const verseScopes = [...Array(toV - fromV + 1).keys()].map(
          (n) => `verse/${n + fromV}`
        );
        if (!openScopes.has(chapterScope)) {
          return false;
        }
        for (const scope2 of verseScopes) {
          if (openScopes.has(scope2)) {
            return true;
          }
        }
        return fromV === 0 && [...openScopes].filter((s) => s.startsWith("verse")).length === 0;
      };
    } else if (XRegExp.exec(cv, XRegExp("^[1-9][0-9]*:[0-9]+-[1-9][0-9]*:[0-9]+$"))) {
      return () => {
        const [fromCV, toCV] = cv.split("-");
        const [fromC, fromV] = fromCV.split(":").map((c) => parseInt(c));
        const [toC, toV] = toCV.split(":").map((v) => parseInt(v));
        if (fromC > toC) {
          throw new Error(
            `Chapter range must be from min to max, not '${fromC}-${toV}'`
          );
        }
        const scopeArray = [...openScopes];
        const chapterScopes = scopeArray.filter(
          (s) => s.startsWith("chapter/")
        );
        if (chapterScopes.length > 1) {
          throw new Error(
            `Expected zero or one chapter for item, found ${chapterScopes.length}`
          );
        }
        const chapterNo = parseInt(chapterScopes[0].split("/")[1]);
        if (chapterNo < fromC || chapterNo > toC) {
          return false;
        } else if (chapterNo === fromC) {
          return scopeArray.filter(
            (s) => s.startsWith("verse/") && parseInt(s.split("/")[1]) >= fromV
          ).length > 0 || fromV === 0 && scopeArray.filter((s) => s.startsWith("verse")).length === 0;
        } else if (chapterNo === toC) {
          return scopeArray.filter(
            (s) => s.startsWith("verse/") && parseInt(s.split("/")[1]) <= toV
          ).length > 0 || toV === 0 && scopeArray.filter((s) => s.startsWith("verse")).length === 0;
        } else {
          return true;
        }
      };
    } else {
      throw new Error(`Bad cv reference '${cv}'`);
    }
  };
  const itemMatchesCV = cvMatchFunction();
  const itemInOptions = (item) => {
    if (!options2 || Object.keys(options2).length === 0) {
      return true;
    } else {
      const itemType = item[0];
      return itemType === "token" && "tokens" in options2 || itemType === "graft" && "grafts" in options2 || itemType === "scope" && "scopes" in options2;
    }
  };
  const ret = [];
  if (options2.excludeScopeTypes) {
    for (const item of docSet.unsuccinctifyItems(
      block2.c,
      options2,
      block2.nt.nByte(0)
    )) {
      if (item[0] === "scope" && item[1] === "start") {
        openScopes.add(item[2]);
      }
      if (itemMatchesCV() && itemInOptions(item)) {
        ret.push(item);
      }
      if (item[0] === "scope" && item[1] === "end") {
        openScopes.delete(item[2]);
      }
    }
  } else {
    for (const item of docSet.unsuccinctifyItems(
      block2.c,
      {},
      block2.nt.nByte(0)
    )) {
      if (item[0] === "scope" && item[1] === "start") {
        openScopes.add(item[2]);
      }
      if (itemMatchesCV() && itemInOptions(item)) {
        ret.push(item);
      }
      if (item[0] === "scope" && item[1] === "end") {
        openScopes.delete(item[2]);
      }
    }
  }
  return ret;
};
const buildPreEnum = (docSet, succinct2) => {
  const ret = /* @__PURE__ */ new Map();
  let pos = 0;
  let enumCount = 0;
  while (pos < succinct2.length) {
    ret.set(succinct2.countedString(pos), {
      enum: enumCount++,
      frequency: 0
    });
    pos += succinct2.byte(pos) + 1;
  }
  return ret;
};
const recordPreEnum = (docSet, category, value) => {
  if (!(category in docSet.preEnums)) {
    throw new Error(
      `Unknown category ${category} in recordPreEnum. Maybe call buildPreEnums()?`
    );
  }
  if (value.length > 255) {
    console.log("Value length of", value.length, "in recordPreEnum");
  }
  if (!docSet.preEnums[category].has(value)) {
    docSet.preEnums[category].set(value, {
      enum: docSet.preEnums[category].size,
      frequency: 1
    });
  } else {
    docSet.preEnums[category].get(value).frequency++;
  }
};
const stringToUtf8ByteArray = (s) => {
  const encoder = new TextEncoder();
  return Array.from(encoder.encode(s));
};
const buildEnum = (docSet, category, preEnumOb) => {
  const sortedPreEnums = new Map([...preEnumOb.entries()]);
  for (const enumText of sortedPreEnums.keys()) {
    let truncatedText = enumText;
    const utf8Bytes = stringToUtf8ByteArray(enumText);
    if (utf8Bytes.length > 255) {
      console.log(
        "enum text for",
        category,
        "has byte length",
        utf8Bytes.length,
        "in buildEnum - truncating to 255 bytes"
      );
      let byteCount = 0;
      let charCount = 0;
      for (const char of enumText) {
        const charBytes = stringToUtf8ByteArray(char).length;
        if (byteCount + charBytes > 255) {
          break;
        }
        byteCount += charBytes;
        charCount++;
      }
      truncatedText = enumText.substring(0, charCount);
    }
    docSet.enums[category].pushCountedString(truncatedText);
  }
  docSet.enums[category].trim();
};
const enumForCategoryValue = (docSet, category, value, addUnknown) => {
  if (!addUnknown) {
    addUnknown = false;
  }
  if (!(category in docSet.preEnums)) {
    throw new Error(
      `Unknown category ${category} in preEnums. Maybe call buildPreEnums()?`
    );
  }
  if (docSet.preEnums[category].has(value)) {
    return docSet.preEnums[category].get(value).enum;
  } else if (addUnknown) {
    docSet.preEnums[category].set(value, {
      enum: docSet.preEnums[category].size,
      frequency: 1
    });
    let truncatedValue = value;
    const utf8Bytes = stringToUtf8ByteArray(value);
    if (utf8Bytes.length > 255) {
      let byteCount = 0;
      let charCount = 0;
      for (const char of value) {
        const charBytes = stringToUtf8ByteArray(char).length;
        if (byteCount + charBytes > 255) {
          break;
        }
        byteCount += charBytes;
        charCount++;
      }
      truncatedValue = value.substring(0, charCount);
    }
    docSet.enums[category].pushCountedString(truncatedValue);
    docSet.buildEnumIndex(category);
    return docSet.preEnums[category].get(value).enum;
  } else {
    throw new Error(
      `Unknown value '${value}' for category ${category} in enumForCategoryValue. Maybe call buildPreEnums()?`
    );
  }
};
const countItems = (docSet, succinct2) => {
  let count = 0;
  let pos = 0;
  while (pos < succinct2.length) {
    count++;
    const headerByte = succinct2.byte(pos);
    const itemLength = headerByte & 63;
    pos += itemLength;
  }
  return count;
};
const itemsByIndex = (docSet, mainSequence, index, includeContext) => {
  let ret = [];
  if (!index) {
    return ret;
  }
  let currentBlock = index.startBlock;
  let nextToken = index.nextToken;
  while (currentBlock <= index.endBlock) {
    let blockItems = docSet.unsuccinctifyItems(
      mainSequence.blocks[currentBlock].c,
      {},
      nextToken
    );
    const blockScope = docSet.unsuccinctifyScopes(
      mainSequence.blocks[currentBlock].bs
    )[0];
    const blockGrafts = docSet.unsuccinctifyGrafts(
      mainSequence.blocks[currentBlock].bg
    );
    if (currentBlock === index.startBlock && currentBlock === index.endBlock) {
      blockItems = blockItems.slice(index.startItem, index.endItem + 1);
    } else if (currentBlock === index.startBlock) {
      blockItems = blockItems.slice(index.startItem);
    } else if (currentBlock === index.endBlock) {
      blockItems = blockItems.slice(0, index.endItem + 1);
    }
    if (includeContext) {
      let extendedBlockItems = [];
      for (const bi of blockItems) {
        extendedBlockItems.push(
          bi.concat([
            bi[0] === "token" && bi[1] === "wordLike" ? nextToken++ : null
          ])
        );
      }
      blockItems = extendedBlockItems;
    }
    ret.push([
      ...blockGrafts,
      ["scope", "start", blockScope[2]],
      ...blockItems,
      ["scope", "end", blockScope[2]]
    ]);
    currentBlock++;
  }
  return ret;
};
const sequenceItemsByScopes = (docSet, blocks, byScopes) => {
  let allBlockScopes2 = [];
  const allScopesPresent = () => {
    for (const requiredScope of byScopes) {
      if (!matchingScope(requiredScope)) {
        return false;
      }
    }
    return true;
  };
  const matchingScope = (scopeToMatch) => {
    for (const blockScope of allBlockScopes2) {
      if (blockScope.startsWith(scopeToMatch)) {
        return blockScope;
      }
    }
    return null;
  };
  docSet.maybeBuildEnumIndexes();
  const ret = [];
  let waitingScopes = /* @__PURE__ */ new Set([]);
  let scopeMatchEnded = true;
  for (const [blockN, block2] of blocks.entries()) {
    const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
      block2.bs,
      0
    );
    const blockScope = docSet.unsuccinctifyScope(
      block2.bs,
      itemType,
      itemSubtype,
      0
    )[2];
    const startBlockScope = ["scope", "start", blockScope];
    const endBlockScope = ["scope", "end", blockScope];
    const blockGrafts = docSet.unsuccinctifyGrafts(block2.bg);
    allBlockScopes2 = new Set(
      docSet.unsuccinctifyScopes(block2.os).map((s) => s[2]).concat([blockScope])
    );
    for (const item of blockGrafts.concat([
      startBlockScope,
      ...docSet.unsuccinctifyItems(
        block2.c,
        {},
        block2.nt.nByte(0),
        allBlockScopes2
      ),
      endBlockScope
    ]).concat(
      blockN !== blocks.length - 1 ? [["token", "lineSpace", " "]] : []
    )) {
      if (item[0] === "scope" && item[1] === "start") {
        waitingScopes.add(item[2]);
      }
      if (item[0] === "token" && waitingScopes.size > 0) {
        for (const waiting of Array.from(waitingScopes)) {
          allBlockScopes2.add(waiting);
        }
        waitingScopes.clear();
      }
      if (allScopesPresent()) {
        if (scopeMatchEnded) {
          ret.push([[...allBlockScopes2], []]);
        }
        ret[ret.length - 1][1].push(item);
        scopeMatchEnded = false;
      } else {
        scopeMatchEnded = true;
      }
      if (item[0] === "scope" && item[1] === "end") {
        allBlockScopes2.delete(item[2]);
        waitingScopes.delete(item[2]);
      }
    }
  }
  return ret;
};
const sequenceItemsByMilestones = (docSet, blocks, byMilestones) => {
  let allBlockScopes2 = /* @__PURE__ */ new Set([]);
  const milestoneFound = (item) => item[0] === "scope" && item[1] === "start" && byMilestones.includes(item[2]);
  docSet.maybeBuildEnumIndexes();
  const ret = [[[], []]];
  for (const block2 of blocks) {
    const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
      block2.bs,
      0
    );
    const blockScope = docSet.unsuccinctifyScope(
      block2.bs,
      itemType,
      itemSubtype,
      0
    )[2];
    const blockGrafts = docSet.unsuccinctifyGrafts(block2.bg);
    allBlockScopes2.add(blockScope);
    docSet.unsuccinctifyScopes(block2.os).forEach((s) => allBlockScopes2.add(s[2]));
    const items2 = blockGrafts.concat(
      [blockScope].concat(
        docSet.unsuccinctifyItems(block2.c, {}, block2.nt.nByte(0))
      )
    );
    for (const item of items2) {
      if (item[0] === "scope" && item[1] === "start") {
        allBlockScopes2.add(item[2]);
      }
      if (milestoneFound(item)) {
        ret[ret.length - 1][0] = [...allBlockScopes2].sort();
        ret.push([[], []]);
        for (const bs of [...allBlockScopes2].filter((s) => {
          const excludes = ["blockTag", "verse", "verses", "chapter"];
          return excludes.includes(s.split("/")[0]) || byMilestones.includes(s);
        })) {
          allBlockScopes2.delete(bs);
        }
        allBlockScopes2.add(blockScope);
      }
      ret[ret.length - 1][1].push(item);
    }
    ret[ret.length - 1][1].push(["scope", "end", blockScope]);
    ret[ret.length - 1][1].push(["token", "punctuation", "\n"]);
  }
  ret[ret.length - 1][0] = [...allBlockScopes2].sort();
  return ret;
};
const rehash = (docSet) => {
  docSet.preEnums = {};
  for (const category of Object.keys(docSet.enums)) {
    docSet.preEnums[category] = /* @__PURE__ */ new Map();
  }
  docSet.maybeBuildEnumIndexes();
  for (const document of docSet.documents()) {
    for (const sequence of Object.values(document.sequences)) {
      document.rerecordPreEnums(docSet, sequence);
    }
  }
  docSet.sortPreEnums();
  const oldToNew = docSet.makeRehashEnumMap();
  for (const document of docSet.documents()) {
    for (const sequence of Object.values(document.sequences)) {
      document.rewriteSequenceBlocks(sequence.id, oldToNew);
    }
  }
  docSet.buildEnums();
  docSet.buildEnumIndexes();
  return true;
};
const makeRehashEnumMap = (docSet) => {
  const ret = {};
  for (const [category, enumSuccinct] of Object.entries(docSet.enums)) {
    ret[category] = [];
    let pos = 0;
    while (pos < enumSuccinct.length) {
      const stringLength = enumSuccinct.byte(pos);
      const enumString = enumSuccinct.countedString(pos);
      if (docSet.preEnums[category].has(enumString)) {
        ret[category].push(docSet.preEnums[category].get(enumString).enum);
      } else {
        ret[category].push(null);
      }
      pos += stringLength + 1;
    }
  }
  return ret;
};
const ByteArray$5 = utils.ByteArray;
const {
  pushSuccinctGraftBytes: pushSuccinctGraftBytes$2,
  pushSuccinctScopeBytes: pushSuccinctScopeBytes$2,
  pushSuccinctTokenBytes: pushSuccinctTokenBytes$2
} = utils.succinct;
const { itemEnum: itemEnum$5 } = utils.itemDefs;
const { scopeEnum: scopeEnum$2 } = utils.scopeDefs;
const { tokenCategory: tokenCategory$2, tokenEnum: tokenEnum$3 } = utils.tokenDefs;
const updateItems1 = (docSet, documentId, sequenceId, blockPosition, typedArrayName, itemObjects) => {
  const document = docSet.processor.documents[documentId];
  if (!document) {
    throw new Error(`Document '${documentId}' not found`);
  }
  let sequence;
  if (sequenceId) {
    sequence = document.sequences[sequenceId];
    if (!sequence) {
      throw new Error(`Sequence '${sequenceId}' not found`);
    }
  } else {
    sequence = document.sequences[document.mainId];
  }
  if (sequence.blocks.length <= blockPosition) {
    throw new Error(
      `Could not find block ${blockPosition} (length=${sequence.blocks.length})`
    );
  }
  const block2 = sequence.blocks[blockPosition];
  const newItemsBA = new ByteArray$5(itemObjects.length);
  docSet.maybeBuildPreEnums();
  let nextToken = 0;
  if (blockPosition < 0) {
    nextToken = sequence.blocks[blockPosition - 1].nt.nByte(0);
  }
  let charsEnumIndex, graftTypeEnumIndex, seqEnumIndex, scopeBits, scopeTypeByte, scopeBitBytes = null;
  for (const item of itemObjects) {
    switch (item.type) {
      case "token":
        charsEnumIndex = docSet.enumForCategoryValue(
          tokenCategory$2[item.subType],
          item.payload,
          true
        );
        pushSuccinctTokenBytes$2(
          newItemsBA,
          tokenEnum$3[item.subType],
          charsEnumIndex
        );
        nextToken++;
        break;
      case "graft":
        graftTypeEnumIndex = docSet.enumForCategoryValue(
          "graftTypes",
          item.subType,
          true
        );
        seqEnumIndex = docSet.enumForCategoryValue("ids", item.payload, true);
        pushSuccinctGraftBytes$2(newItemsBA, graftTypeEnumIndex, seqEnumIndex);
        break;
      case "scope":
        scopeBits = item.payload.split("/");
        scopeTypeByte = scopeEnum$2[scopeBits[0]];
        if (!scopeTypeByte && scopeTypeByte !== 0) {
          throw new Error(`"${scopeBits[0]}" is not a scope type`);
        }
        scopeBitBytes = scopeBits.slice(1).map((b) => docSet.enumForCategoryValue("scopeBits", b, true));
        pushSuccinctScopeBytes$2(
          newItemsBA,
          itemEnum$5[`${item.subType}Scope`],
          scopeTypeByte,
          scopeBitBytes
        );
        break;
    }
  }
  newItemsBA.trim();
  block2[typedArrayName] = newItemsBA;
  if (typedArrayName === "c") {
    block2.nt.clear();
    block2.nt.pushNByte(nextToken);
  }
  return true;
};
const updateItems = (docSet, documentId, sequenceId, blockPosition, itemObjects) => updateItems1(docSet, documentId, sequenceId, blockPosition, "c", itemObjects);
const updateBlockGrafts = (docSet, documentId, sequenceId, blockPosition, itemObjects) => updateItems1(
  docSet,
  documentId,
  sequenceId,
  blockPosition,
  "bg",
  itemObjects
);
const updateBlockScope = (docSet, documentId, sequenceId, blockPosition, bsObject) => updateItems1(docSet, documentId, sequenceId, blockPosition, "bs", [bsObject]);
const updateOpenScopes = (docSet, documentId, sequenceId, blockPosition, osObjects) => updateItems1(docSet, documentId, sequenceId, blockPosition, "os", osObjects);
const updateIncludedScopes = (docSet, documentId, sequenceId, blockPosition, isObjects) => updateItems1(docSet, documentId, sequenceId, blockPosition, "is", isObjects);
const updateBlockIndexesAfterEdit = (docSet, sequence, blockPosition) => {
  const labelsMatch = (firstA, secondA) => {
    for (const first of Array.from(firstA)) {
      if (!secondA.has(first)) {
        return false;
      }
    }
    for (const second of Array.from(secondA)) {
      if (!firstA.has(second)) {
        return false;
      }
    }
    return true;
  };
  const addSuccinctScope = (docSet2, succinct2, scopeLabel) => {
    const scopeBits = scopeLabel.split("/");
    const scopeTypeByte = scopeEnum$2[scopeBits[0]];
    if (!scopeTypeByte && scopeTypeByte !== 0) {
      throw new Error(`"${scopeBits[0]}" is not a scope type`);
    }
    const scopeBitBytes = scopeBits.slice(1).map((b) => docSet2.enumForCategoryValue("scopeBits", b, true));
    pushSuccinctScopeBytes$2(
      succinct2,
      itemEnum$5[`startScope`],
      scopeTypeByte,
      scopeBitBytes
    );
  };
  const block2 = sequence.blocks[blockPosition];
  const includedScopeLabels = /* @__PURE__ */ new Set();
  const openScopeLabels = /* @__PURE__ */ new Set();
  for (const openScope of docSet.unsuccinctifyScopes(block2.os)) {
    openScopeLabels.add(openScope[2]);
  }
  for (const scope2 of docSet.unsuccinctifyItems(
    block2.c,
    { scopes: true },
    null
  )) {
    if (scope2[1] === "start") {
      includedScopeLabels.add(scope2[2]);
      openScopeLabels.add(scope2[2]);
    } else {
      openScopeLabels.delete(scope2[2]);
    }
  }
  const isArray = Array.from(includedScopeLabels);
  const isBA = new ByteArray$5(isArray.length);
  for (const scopeLabel of isArray) {
    addSuccinctScope(docSet, isBA, scopeLabel);
  }
  isBA.trim();
  block2.is = isBA;
  if (blockPosition < sequence.blocks.length - 1) {
    const nextOsBlock = sequence.blocks[blockPosition + 1];
    const nextOsBA = nextOsBlock.os;
    const nextOSLabels = new Set(
      docSet.unsuccinctifyScopes(nextOsBA).map((s) => s[2])
    );
    if (!labelsMatch(openScopeLabels, nextOSLabels)) {
      const osBA = new ByteArray$5(nextOSLabels.length);
      for (const scopeLabel of Array.from(openScopeLabels)) {
        addSuccinctScope(docSet, osBA, scopeLabel);
      }
      osBA.trim();
      nextOsBlock.os = osBA;
      docSet.updateBlockIndexesAfterEdit(sequence, blockPosition + 1);
    }
  }
};
const updateBlockIndexesAfterFilter = (docSet, sequence) => {
  const addSuccinctScope = (docSet2, succinct2, scopeLabel) => {
    const scopeBits = scopeLabel.split("/");
    const scopeTypeByte = scopeEnum$2[scopeBits[0]];
    if (!scopeTypeByte && scopeTypeByte !== 0) {
      throw new Error(`"${scopeBits[0]}" is not a scope type`);
    }
    const scopeBitBytes = scopeBits.slice(1).map((b) => docSet2.enumForCategoryValue("scopeBits", b, true));
    pushSuccinctScopeBytes$2(
      succinct2,
      itemEnum$5[`startScope`],
      scopeTypeByte,
      scopeBitBytes
    );
  };
  const openScopeLabels = /* @__PURE__ */ new Set();
  for (const block2 of sequence.blocks) {
    const osArray = Array.from(openScopeLabels);
    const osBA = new ByteArray$5(osArray.length);
    for (const scopeLabel of osArray) {
      addSuccinctScope(docSet, osBA, scopeLabel);
    }
    osBA.trim();
    block2.os = osBA;
    const includedScopeLabels = /* @__PURE__ */ new Set();
    for (const scope2 of docSet.unsuccinctifyItems(
      block2.c,
      { scopes: true },
      null
    )) {
      if (scope2[1] === "start") {
        includedScopeLabels.add(scope2[2]);
        openScopeLabels.add(scope2[2]);
      } else {
        openScopeLabels.delete(scope2[2]);
      }
    }
    const isArray = Array.from(includedScopeLabels);
    const isBA = new ByteArray$5(isArray.length);
    for (const scopeLabel of isArray) {
      addSuccinctScope(docSet, isBA, scopeLabel);
    }
    isBA.trim();
    block2.is = isBA;
  }
};
const serializeSuccinct$1 = (docSet) => {
  const ret = {
    id: docSet.id,
    metadata: { selectors: docSet.selectors },
    enums: {},
    docs: {},
    tags: Array.from(docSet.tags)
  };
  for (const [eK, eV] of Object.entries(docSet.enums)) {
    eV.trim();
    ret.enums[eK] = eV.base64();
  }
  ret.docs = {};
  for (const docId of docSet.docIds) {
    ret.docs[docId] = docSet.processor.documents[docId].serializeSuccinct();
  }
  return ret;
};
const ByteArray$4 = utils.ByteArray;
const { addTag: addTag$2, removeTag: removeTag$1, validateTags: validateTags$1 } = utils.tags;
const {
  succinctGraftName,
  succinctGraftSeqId,
  succinctScopeLabel,
  succinctTokenChars,
  headerBytes: headerBytes$1,
  enumIndex,
  enumIndexes
} = utils.succinct;
const { itemEnum: itemEnum$4 } = utils.itemDefs;
const { tokenEnumLabels } = utils.tokenDefs;
class DocSet {
  constructor(processor, selectors, tags2, succinctJson) {
    this.processor = processor;
    this.preEnums = {};
    this.enumIndexes = {};
    this.docIds = [];
    if (succinctJson) {
      this.fromSuccinct(processor, succinctJson);
    } else {
      this.fromScratch(processor, selectors, tags2);
    }
    validateTags$1(this.tags);
  }
  fromScratch(processor, selectors, tags2) {
    const defaultedSelectors = selectors || processor.selectors;
    this.selectors = validateSelectors(this, defaultedSelectors);
    this.id = this.selectorString();
    this.tags = new Set(tags2 || []);
    this.enums = {
      ids: new ByteArray$4(512),
      wordLike: new ByteArray$4(8192),
      notWordLike: new ByteArray$4(256),
      scopeBits: new ByteArray$4(256),
      graftTypes: new ByteArray$4(10)
    };
  }
  fromSuccinct(processor, succinctJson) {
    const populatedByteArray = (succinct2) => {
      const ret = new ByteArray$4(256);
      ret.fromBase64(succinct2);
      ret.trim();
      return ret;
    };
    this.id = succinctJson.id;
    this.selectors = validateSelectors(this, succinctJson.metadata.selectors);
    this.tags = new Set(succinctJson.tags);
    validateTags$1(this.tags);
    this.preEnums = {};
    this.enums = {
      ids: populatedByteArray(succinctJson.enums.ids),
      wordLike: populatedByteArray(succinctJson.enums.wordLike),
      notWordLike: populatedByteArray(succinctJson.enums.notWordLike),
      scopeBits: populatedByteArray(succinctJson.enums.scopeBits),
      graftTypes: populatedByteArray(succinctJson.enums.graftTypes)
    };
    this.enumIndexes = {};
    this.docIds = [];
  }
  addTag(tag) {
    addTag$2(this.tags, tag);
  }
  removeTag(tag) {
    removeTag$1(this.tags, tag);
  }
  selectorString() {
    return this.processor.selectorString(this.selectors);
  }
  documents() {
    return this.docIds.map((did) => this.processor.documents[did]);
  }
  documentWithBook(bookCode) {
    const docsWithBook = Object.values(this.documents()).filter(
      (doc) => "bookCode" in doc.headers && doc.headers["bookCode"] === bookCode
    );
    return docsWithBook.length === 1 ? docsWithBook[0] : null;
  }
  maybeBuildPreEnums() {
    if (Object.keys(this.preEnums).length === 0) {
      this.buildPreEnums();
    }
  }
  buildPreEnums() {
    for (const [category, succinct2] of Object.entries(this.enums)) {
      this.preEnums[category] = buildPreEnum(this, succinct2);
    }
  }
  recordPreEnum(category, value) {
    recordPreEnum(this, category, value);
  }
  sortPreEnums() {
    for (const catKey of Object.keys(this.preEnums)) {
      this.preEnums[catKey] = new Map(
        [...this.preEnums[catKey].entries()].sort(
          (a, b) => b[1].frequency - a[1].frequency
        )
      );
      let count = 0;
      for (const [k, v] of this.preEnums[catKey]) {
        v.enum = count++;
      }
    }
  }
  enumForCategoryValue(category, value, addUnknown) {
    return enumForCategoryValue(this, category, value, addUnknown);
  }
  buildEnums() {
    for (const [category, catOb] of Object.entries(this.preEnums)) {
      this.enums[category].clear();
      this.buildEnum(category, catOb);
    }
  }
  buildEnum(category, preEnumOb) {
    buildEnum(this, category, preEnumOb);
  }
  maybeBuildEnumIndexes() {
    if (Object.keys(this.enumIndexes).length === 0) {
      this.buildEnumIndexes();
    }
  }
  buildEnumIndexes() {
    this.enumIndexes = enumIndexes(this.enums);
  }
  buildEnumIndex(category) {
    this.enumIndexes[category] = enumIndex(category, this.enums[category]);
  }
  unsuccinctifyBlock(block2, options2) {
    return unsuccinctifyBlock(this, block2, options2);
  }
  unsuccinctifyItems(succinct2, options2, nextToken, openScopes) {
    return unsuccinctifyItems(this, succinct2, options2, nextToken, openScopes);
  }
  unsuccinctifyItem(succinct2, pos, options2) {
    return unsuccinctifyItem(this, succinct2, pos, options2);
  }
  unsuccinctifyPrunedItems(block2, options2) {
    return unsuccinctifyPrunedItems(this, block2, options2);
  }
  unsuccinctifyScopes(succinct2) {
    const ret = [];
    let pos = 0;
    while (pos < succinct2.length) {
      const [itemLength, itemType, itemSubtype] = headerBytes$1(succinct2, pos);
      ret.push(this.unsuccinctifyScope(succinct2, itemType, itemSubtype, pos));
      pos += itemLength;
    }
    return ret;
  }
  unsuccinctifyGrafts(succinct2) {
    const ret = [];
    let pos = 0;
    while (pos < succinct2.length) {
      const [itemLength, itemType, itemSubtype] = headerBytes$1(succinct2, pos);
      ret.push(this.unsuccinctifyGraft(succinct2, itemSubtype, pos));
      pos += itemLength;
    }
    return ret;
  }
  unsuccinctifyToken(succinct2, itemSubtype, pos) {
    try {
      return [
        "token",
        tokenEnumLabels[itemSubtype],
        this.succinctTokenChars(succinct2, itemSubtype, pos)
      ];
    } catch (err) {
      throw new Error(`Error from unsuccinctifyToken: ${err}`);
    }
  }
  unsuccinctifyScope(succinct2, itemType, itemSubtype, pos) {
    try {
      return [
        "scope",
        itemType === itemEnum$4.startScope ? "start" : "end",
        this.succinctScopeLabel(succinct2, itemSubtype, pos)
      ];
    } catch (err) {
      throw new Error(`Error from unsuccinctifyScope: ${err}`);
    }
  }
  unsuccinctifyGraft(succinct2, itemSubtype, pos) {
    try {
      return [
        "graft",
        this.succinctGraftName(itemSubtype),
        this.succinctGraftSeqId(succinct2, pos)
      ];
    } catch (err) {
      throw new Error(`Error from unsuccinctifyGraft: ${err}`);
    }
  }
  unsuccinctifyBlockScopeLabelsSet(block2) {
    const [itemLength, itemType, itemSubtype] = headerBytes$1(block2.bs, 0);
    const blockScope = this.unsuccinctifyScope(
      block2.bs,
      itemType,
      itemSubtype,
      0
    );
    return new Set(
      this.unsuccinctifyScopes(block2.os).concat(this.unsuccinctifyScopes(block2.is)).concat([blockScope]).map((ri) => ri[2])
    );
  }
  unsuccinctifyItemsWithScriptureCV(block2, cv, options2) {
    return unsuccinctifyItemsWithScriptureCV(this, block2, cv, options2);
  }
  succinctTokenChars(succinct2, itemSubtype, pos) {
    return succinctTokenChars(
      this.enums,
      this.enumIndexes,
      succinct2,
      itemSubtype,
      pos
    );
  }
  succinctScopeLabel(succinct2, itemSubtype, pos) {
    return succinctScopeLabel(
      this.enums,
      this.enumIndexes,
      succinct2,
      itemSubtype,
      pos
    );
  }
  succinctGraftName(itemSubtype) {
    return succinctGraftName(this.enums, this.enumIndexes, itemSubtype);
  }
  succinctGraftSeqId(succinct2, pos) {
    return succinctGraftSeqId(this.enums, this.enumIndexes, succinct2, pos);
  }
  countItems(succinct2) {
    return countItems(this, succinct2);
  }
  itemsByIndex(mainSequence, index, includeContext) {
    return itemsByIndex(this, mainSequence, index, includeContext);
  }
  blocksWithScriptureCV(blocks, cv) {
    return blocksWithScriptureCV(this, blocks, cv);
  }
  allBlockScopes(block2) {
    return allBlockScopes(this, block2);
  }
  allScopesInBlock(block2, scopes) {
    return allScopesInBlock(this, block2, scopes);
  }
  anyScopeInBlock(block2, scopes) {
    return anyScopeInBlock(this, block2, scopes);
  }
  blockHasBlockScope(block2, scope2) {
    return blockHasBlockScope(this, block2, scope2);
  }
  blockHasChars(block2, charsIndexes) {
    return blockHasChars(this, block2, charsIndexes);
  }
  blockHasMatchingItem(block2, testFunction, options2) {
    return blockHasMatchingItem(this, block2, testFunction, options2);
  }
  sequenceItemsByScopes(blocks, byScopes) {
    return sequenceItemsByScopes(this, blocks, byScopes);
  }
  sequenceItemsByMilestones(blocks, byMilestones) {
    return sequenceItemsByMilestones(this, blocks, byMilestones);
  }
  rehash() {
    return rehash(this);
  }
  makeRehashEnumMap() {
    return makeRehashEnumMap(this);
  }
  updateItems(documentId, sequenceId, blockPosition, itemObjects) {
    return updateItems(
      this,
      documentId,
      sequenceId,
      blockPosition,
      itemObjects
    );
  }
  updateBlockGrafts(documentId, sequenceId, blockPosition, itemObjects) {
    return updateBlockGrafts(
      this,
      documentId,
      sequenceId,
      blockPosition,
      itemObjects
    );
  }
  updateBlockScope(documentId, sequenceId, blockPosition, bsObject) {
    return updateBlockScope(
      this,
      documentId,
      sequenceId,
      blockPosition,
      bsObject
    );
  }
  updateOpenScopes(documentId, sequenceId, blockPosition, osObjects) {
    return updateOpenScopes(
      this,
      documentId,
      sequenceId,
      blockPosition,
      osObjects
    );
  }
  updateIncludedScopes(documentId, sequenceId, blockPosition, isObjects) {
    return updateIncludedScopes(
      this,
      documentId,
      sequenceId,
      blockPosition,
      isObjects
    );
  }
  updateBlockIndexesAfterEdit(sequence, blockPosition) {
    updateBlockIndexesAfterEdit(this, sequence, blockPosition);
  }
  updateBlockIndexesAfterFilter(sequence) {
    updateBlockIndexesAfterFilter(this, sequence);
  }
  serializeSuccinct() {
    return serializeSuccinct$1(this);
  }
  checksum() {
    const docIdsString = [...this.docIds].sort().join(" ");
    return crc32.calculate(docIdsString);
  }
}
var ajv = { exports: {} };
var core$2 = {};
var validate = {};
var boolSchema = {};
var errors = {};
var codegen = {};
var code$1 = {};
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.regexpCode = exports2.getEsmExportName = exports2.getProperty = exports2.safeStringify = exports2.stringify = exports2.strConcat = exports2.addCodeArg = exports2.str = exports2._ = exports2.nil = exports2._Code = exports2.Name = exports2.IDENTIFIER = exports2._CodeOrName = void 0;
  class _CodeOrName {
  }
  exports2._CodeOrName = _CodeOrName;
  exports2.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  class Name extends _CodeOrName {
    constructor(s) {
      super();
      if (!exports2.IDENTIFIER.test(s))
        throw new Error("CodeGen: name must be a valid identifier");
      this.str = s;
    }
    toString() {
      return this.str;
    }
    emptyStr() {
      return false;
    }
    get names() {
      return { [this.str]: 1 };
    }
  }
  exports2.Name = Name;
  class _Code extends _CodeOrName {
    constructor(code2) {
      super();
      this._items = typeof code2 === "string" ? [code2] : code2;
    }
    toString() {
      return this.str;
    }
    emptyStr() {
      if (this._items.length > 1)
        return false;
      const item = this._items[0];
      return item === "" || item === '""';
    }
    get str() {
      var _a;
      return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
    }
    get names() {
      var _a;
      return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names2, c) => {
        if (c instanceof Name)
          names2[c.str] = (names2[c.str] || 0) + 1;
        return names2;
      }, {});
    }
  }
  exports2._Code = _Code;
  exports2.nil = new _Code("");
  function _(strs, ...args) {
    const code2 = [strs[0]];
    let i = 0;
    while (i < args.length) {
      addCodeArg(code2, args[i]);
      code2.push(strs[++i]);
    }
    return new _Code(code2);
  }
  exports2._ = _;
  const plus = new _Code("+");
  function str(strs, ...args) {
    const expr = [safeStringify(strs[0])];
    let i = 0;
    while (i < args.length) {
      expr.push(plus);
      addCodeArg(expr, args[i]);
      expr.push(plus, safeStringify(strs[++i]));
    }
    optimize(expr);
    return new _Code(expr);
  }
  exports2.str = str;
  function addCodeArg(code2, arg) {
    if (arg instanceof _Code)
      code2.push(...arg._items);
    else if (arg instanceof Name)
      code2.push(arg);
    else
      code2.push(interpolate(arg));
  }
  exports2.addCodeArg = addCodeArg;
  function optimize(expr) {
    let i = 1;
    while (i < expr.length - 1) {
      if (expr[i] === plus) {
        const res = mergeExprItems(expr[i - 1], expr[i + 1]);
        if (res !== void 0) {
          expr.splice(i - 1, 3, res);
          continue;
        }
        expr[i++] = "+";
      }
      i++;
    }
  }
  function mergeExprItems(a, b) {
    if (b === '""')
      return a;
    if (a === '""')
      return b;
    if (typeof a == "string") {
      if (b instanceof Name || a[a.length - 1] !== '"')
        return;
      if (typeof b != "string")
        return `${a.slice(0, -1)}${b}"`;
      if (b[0] === '"')
        return a.slice(0, -1) + b.slice(1);
      return;
    }
    if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
      return `"${a}${b.slice(1)}`;
    return;
  }
  function strConcat(c1, c2) {
    return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
  }
  exports2.strConcat = strConcat;
  function interpolate(x) {
    return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
  }
  function stringify(x) {
    return new _Code(safeStringify(x));
  }
  exports2.stringify = stringify;
  function safeStringify(x) {
    return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
  }
  exports2.safeStringify = safeStringify;
  function getProperty(key) {
    return typeof key == "string" && exports2.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
  }
  exports2.getProperty = getProperty;
  function getEsmExportName(key) {
    if (typeof key == "string" && exports2.IDENTIFIER.test(key)) {
      return new _Code(`${key}`);
    }
    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
  }
  exports2.getEsmExportName = getEsmExportName;
  function regexpCode(rx) {
    return new _Code(rx.toString());
  }
  exports2.regexpCode = regexpCode;
})(code$1);
var scope = {};
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.ValueScope = exports2.ValueScopeName = exports2.Scope = exports2.varKinds = exports2.UsedValueState = void 0;
  const code_12 = code$1;
  class ValueError extends Error {
    constructor(name2) {
      super(`CodeGen: "code" for ${name2} not defined`);
      this.value = name2.value;
    }
  }
  var UsedValueState;
  (function(UsedValueState2) {
    UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
    UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
  })(UsedValueState || (exports2.UsedValueState = UsedValueState = {}));
  exports2.varKinds = {
    const: new code_12.Name("const"),
    let: new code_12.Name("let"),
    var: new code_12.Name("var")
  };
  class Scope {
    constructor({ prefixes, parent } = {}) {
      this._names = {};
      this._prefixes = prefixes;
      this._parent = parent;
    }
    toName(nameOrPrefix) {
      return nameOrPrefix instanceof code_12.Name ? nameOrPrefix : this.name(nameOrPrefix);
    }
    name(prefix) {
      return new code_12.Name(this._newName(prefix));
    }
    _newName(prefix) {
      const ng = this._names[prefix] || this._nameGroup(prefix);
      return `${prefix}${ng.index++}`;
    }
    _nameGroup(prefix) {
      var _a, _b;
      if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
        throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
      }
      return this._names[prefix] = { prefix, index: 0 };
    }
  }
  exports2.Scope = Scope;
  class ValueScopeName extends code_12.Name {
    constructor(prefix, nameStr) {
      super(nameStr);
      this.prefix = prefix;
    }
    setValue(value, { property, itemIndex }) {
      this.value = value;
      this.scopePath = (0, code_12._)`.${new code_12.Name(property)}[${itemIndex}]`;
    }
  }
  exports2.ValueScopeName = ValueScopeName;
  const line = (0, code_12._)`\n`;
  class ValueScope extends Scope {
    constructor(opts) {
      super(opts);
      this._values = {};
      this._scope = opts.scope;
      this.opts = { ...opts, _n: opts.lines ? line : code_12.nil };
    }
    get() {
      return this._scope;
    }
    name(prefix) {
      return new ValueScopeName(prefix, this._newName(prefix));
    }
    value(nameOrPrefix, value) {
      var _a;
      if (value.ref === void 0)
        throw new Error("CodeGen: ref must be passed in value");
      const name2 = this.toName(nameOrPrefix);
      const { prefix } = name2;
      const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref;
      let vs = this._values[prefix];
      if (vs) {
        const _name = vs.get(valueKey);
        if (_name)
          return _name;
      } else {
        vs = this._values[prefix] = /* @__PURE__ */ new Map();
      }
      vs.set(valueKey, name2);
      const s = this._scope[prefix] || (this._scope[prefix] = []);
      const itemIndex = s.length;
      s[itemIndex] = value.ref;
      name2.setValue(value, { property: prefix, itemIndex });
      return name2;
    }
    getValue(prefix, keyOrRef) {
      const vs = this._values[prefix];
      if (!vs)
        return;
      return vs.get(keyOrRef);
    }
    scopeRefs(scopeName, values = this._values) {
      return this._reduceValues(values, (name2) => {
        if (name2.scopePath === void 0)
          throw new Error(`CodeGen: name "${name2}" has no value`);
        return (0, code_12._)`${scopeName}${name2.scopePath}`;
      });
    }
    scopeCode(values = this._values, usedValues, getCode) {
      return this._reduceValues(values, (name2) => {
        if (name2.value === void 0)
          throw new Error(`CodeGen: name "${name2}" has no value`);
        return name2.value.code;
      }, usedValues, getCode);
    }
    _reduceValues(values, valueCode, usedValues = {}, getCode) {
      let code2 = code_12.nil;
      for (const prefix in values) {
        const vs = values[prefix];
        if (!vs)
          continue;
        const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
        vs.forEach((name2) => {
          if (nameSet.has(name2))
            return;
          nameSet.set(name2, UsedValueState.Started);
          let c = valueCode(name2);
          if (c) {
            const def2 = this.opts.es5 ? exports2.varKinds.var : exports2.varKinds.const;
            code2 = (0, code_12._)`${code2}${def2} ${name2} = ${c};${this.opts._n}`;
          } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name2)) {
            code2 = (0, code_12._)`${code2}${c}${this.opts._n}`;
          } else {
            throw new ValueError(name2);
          }
          nameSet.set(name2, UsedValueState.Completed);
        });
      }
      return code2;
    }
  }
  exports2.ValueScope = ValueScope;
})(scope);
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.or = exports2.and = exports2.not = exports2.CodeGen = exports2.operators = exports2.varKinds = exports2.ValueScopeName = exports2.ValueScope = exports2.Scope = exports2.Name = exports2.regexpCode = exports2.stringify = exports2.getProperty = exports2.nil = exports2.strConcat = exports2.str = exports2._ = void 0;
  const code_12 = code$1;
  const scope_1 = scope;
  var code_2 = code$1;
  Object.defineProperty(exports2, "_", { enumerable: true, get: function() {
    return code_2._;
  } });
  Object.defineProperty(exports2, "str", { enumerable: true, get: function() {
    return code_2.str;
  } });
  Object.defineProperty(exports2, "strConcat", { enumerable: true, get: function() {
    return code_2.strConcat;
  } });
  Object.defineProperty(exports2, "nil", { enumerable: true, get: function() {
    return code_2.nil;
  } });
  Object.defineProperty(exports2, "getProperty", { enumerable: true, get: function() {
    return code_2.getProperty;
  } });
  Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
    return code_2.stringify;
  } });
  Object.defineProperty(exports2, "regexpCode", { enumerable: true, get: function() {
    return code_2.regexpCode;
  } });
  Object.defineProperty(exports2, "Name", { enumerable: true, get: function() {
    return code_2.Name;
  } });
  var scope_2 = scope;
  Object.defineProperty(exports2, "Scope", { enumerable: true, get: function() {
    return scope_2.Scope;
  } });
  Object.defineProperty(exports2, "ValueScope", { enumerable: true, get: function() {
    return scope_2.ValueScope;
  } });
  Object.defineProperty(exports2, "ValueScopeName", { enumerable: true, get: function() {
    return scope_2.ValueScopeName;
  } });
  Object.defineProperty(exports2, "varKinds", { enumerable: true, get: function() {
    return scope_2.varKinds;
  } });
  exports2.operators = {
    GT: new code_12._Code(">"),
    GTE: new code_12._Code(">="),
    LT: new code_12._Code("<"),
    LTE: new code_12._Code("<="),
    EQ: new code_12._Code("==="),
    NEQ: new code_12._Code("!=="),
    NOT: new code_12._Code("!"),
    OR: new code_12._Code("||"),
    AND: new code_12._Code("&&"),
    ADD: new code_12._Code("+")
  };
  class Node {
    optimizeNodes() {
      return this;
    }
    optimizeNames(_names, _constants) {
      return this;
    }
  }
  class Def extends Node {
    constructor(varKind, name2, rhs) {
      super();
      this.varKind = varKind;
      this.name = name2;
      this.rhs = rhs;
    }
    render({ es5, _n }) {
      const varKind = es5 ? scope_1.varKinds.var : this.varKind;
      const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
      return `${varKind} ${this.name}${rhs};` + _n;
    }
    optimizeNames(names2, constants) {
      if (!names2[this.name.str])
        return;
      if (this.rhs)
        this.rhs = optimizeExpr(this.rhs, names2, constants);
      return this;
    }
    get names() {
      return this.rhs instanceof code_12._CodeOrName ? this.rhs.names : {};
    }
  }
  class Assign extends Node {
    constructor(lhs, rhs, sideEffects) {
      super();
      this.lhs = lhs;
      this.rhs = rhs;
      this.sideEffects = sideEffects;
    }
    render({ _n }) {
      return `${this.lhs} = ${this.rhs};` + _n;
    }
    optimizeNames(names2, constants) {
      if (this.lhs instanceof code_12.Name && !names2[this.lhs.str] && !this.sideEffects)
        return;
      this.rhs = optimizeExpr(this.rhs, names2, constants);
      return this;
    }
    get names() {
      const names2 = this.lhs instanceof code_12.Name ? {} : { ...this.lhs.names };
      return addExprNames(names2, this.rhs);
    }
  }
  class AssignOp extends Assign {
    constructor(lhs, op, rhs, sideEffects) {
      super(lhs, rhs, sideEffects);
      this.op = op;
    }
    render({ _n }) {
      return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
    }
  }
  class Label extends Node {
    constructor(label) {
      super();
      this.label = label;
      this.names = {};
    }
    render({ _n }) {
      return `${this.label}:` + _n;
    }
  }
  class Break extends Node {
    constructor(label) {
      super();
      this.label = label;
      this.names = {};
    }
    render({ _n }) {
      const label = this.label ? ` ${this.label}` : "";
      return `break${label};` + _n;
    }
  }
  class Throw extends Node {
    constructor(error2) {
      super();
      this.error = error2;
    }
    render({ _n }) {
      return `throw ${this.error};` + _n;
    }
    get names() {
      return this.error.names;
    }
  }
  class AnyCode extends Node {
    constructor(code2) {
      super();
      this.code = code2;
    }
    render({ _n }) {
      return `${this.code};` + _n;
    }
    optimizeNodes() {
      return `${this.code}` ? this : void 0;
    }
    optimizeNames(names2, constants) {
      this.code = optimizeExpr(this.code, names2, constants);
      return this;
    }
    get names() {
      return this.code instanceof code_12._CodeOrName ? this.code.names : {};
    }
  }
  class ParentNode extends Node {
    constructor(nodes = []) {
      super();
      this.nodes = nodes;
    }
    render(opts) {
      return this.nodes.reduce((code2, n) => code2 + n.render(opts), "");
    }
    optimizeNodes() {
      const { nodes } = this;
      let i = nodes.length;
      while (i--) {
        const n = nodes[i].optimizeNodes();
        if (Array.isArray(n))
          nodes.splice(i, 1, ...n);
        else if (n)
          nodes[i] = n;
        else
          nodes.splice(i, 1);
      }
      return nodes.length > 0 ? this : void 0;
    }
    optimizeNames(names2, constants) {
      const { nodes } = this;
      let i = nodes.length;
      while (i--) {
        const n = nodes[i];
        if (n.optimizeNames(names2, constants))
          continue;
        subtractNames(names2, n.names);
        nodes.splice(i, 1);
      }
      return nodes.length > 0 ? this : void 0;
    }
    get names() {
      return this.nodes.reduce((names2, n) => addNames(names2, n.names), {});
    }
  }
  class BlockNode extends ParentNode {
    render(opts) {
      return "{" + opts._n + super.render(opts) + "}" + opts._n;
    }
  }
  class Root extends ParentNode {
  }
  class Else extends BlockNode {
  }
  Else.kind = "else";
  class If extends BlockNode {
    constructor(condition, nodes) {
      super(nodes);
      this.condition = condition;
    }
    render(opts) {
      let code2 = `if(${this.condition})` + super.render(opts);
      if (this.else)
        code2 += "else " + this.else.render(opts);
      return code2;
    }
    optimizeNodes() {
      super.optimizeNodes();
      const cond = this.condition;
      if (cond === true)
        return this.nodes;
      let e = this.else;
      if (e) {
        const ns = e.optimizeNodes();
        e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
      }
      if (e) {
        if (cond === false)
          return e instanceof If ? e : e.nodes;
        if (this.nodes.length)
          return this;
        return new If(not2(cond), e instanceof If ? [e] : e.nodes);
      }
      if (cond === false || !this.nodes.length)
        return void 0;
      return this;
    }
    optimizeNames(names2, constants) {
      var _a;
      this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names2, constants);
      if (!(super.optimizeNames(names2, constants) || this.else))
        return;
      this.condition = optimizeExpr(this.condition, names2, constants);
      return this;
    }
    get names() {
      const names2 = super.names;
      addExprNames(names2, this.condition);
      if (this.else)
        addNames(names2, this.else.names);
      return names2;
    }
  }
  If.kind = "if";
  class For extends BlockNode {
  }
  For.kind = "for";
  class ForLoop extends For {
    constructor(iteration) {
      super();
      this.iteration = iteration;
    }
    render(opts) {
      return `for(${this.iteration})` + super.render(opts);
    }
    optimizeNames(names2, constants) {
      if (!super.optimizeNames(names2, constants))
        return;
      this.iteration = optimizeExpr(this.iteration, names2, constants);
      return this;
    }
    get names() {
      return addNames(super.names, this.iteration.names);
    }
  }
  class ForRange extends For {
    constructor(varKind, name2, from, to) {
      super();
      this.varKind = varKind;
      this.name = name2;
      this.from = from;
      this.to = to;
    }
    render(opts) {
      const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
      const { name: name2, from, to } = this;
      return `for(${varKind} ${name2}=${from}; ${name2}<${to}; ${name2}++)` + super.render(opts);
    }
    get names() {
      const names2 = addExprNames(super.names, this.from);
      return addExprNames(names2, this.to);
    }
  }
  class ForIter extends For {
    constructor(loop, varKind, name2, iterable) {
      super();
      this.loop = loop;
      this.varKind = varKind;
      this.name = name2;
      this.iterable = iterable;
    }
    render(opts) {
      return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
    }
    optimizeNames(names2, constants) {
      if (!super.optimizeNames(names2, constants))
        return;
      this.iterable = optimizeExpr(this.iterable, names2, constants);
      return this;
    }
    get names() {
      return addNames(super.names, this.iterable.names);
    }
  }
  class Func extends BlockNode {
    constructor(name2, args, async) {
      super();
      this.name = name2;
      this.args = args;
      this.async = async;
    }
    render(opts) {
      const _async = this.async ? "async " : "";
      return `${_async}function ${this.name}(${this.args})` + super.render(opts);
    }
  }
  Func.kind = "func";
  class Return extends ParentNode {
    render(opts) {
      return "return " + super.render(opts);
    }
  }
  Return.kind = "return";
  class Try extends BlockNode {
    render(opts) {
      let code2 = "try" + super.render(opts);
      if (this.catch)
        code2 += this.catch.render(opts);
      if (this.finally)
        code2 += this.finally.render(opts);
      return code2;
    }
    optimizeNodes() {
      var _a, _b;
      super.optimizeNodes();
      (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes();
      (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
      return this;
    }
    optimizeNames(names2, constants) {
      var _a, _b;
      super.optimizeNames(names2, constants);
      (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names2, constants);
      (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names2, constants);
      return this;
    }
    get names() {
      const names2 = super.names;
      if (this.catch)
        addNames(names2, this.catch.names);
      if (this.finally)
        addNames(names2, this.finally.names);
      return names2;
    }
  }
  class Catch extends BlockNode {
    constructor(error2) {
      super();
      this.error = error2;
    }
    render(opts) {
      return `catch(${this.error})` + super.render(opts);
    }
  }
  Catch.kind = "catch";
  class Finally extends BlockNode {
    render(opts) {
      return "finally" + super.render(opts);
    }
  }
  Finally.kind = "finally";
  class CodeGen {
    constructor(extScope, opts = {}) {
      this._values = {};
      this._blockStarts = [];
      this._constants = {};
      this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
      this._extScope = extScope;
      this._scope = new scope_1.Scope({ parent: extScope });
      this._nodes = [new Root()];
    }
    toString() {
      return this._root.render(this.opts);
    }
    // returns unique name in the internal scope
    name(prefix) {
      return this._scope.name(prefix);
    }
    // reserves unique name in the external scope
    scopeName(prefix) {
      return this._extScope.name(prefix);
    }
    // reserves unique name in the external scope and assigns value to it
    scopeValue(prefixOrName, value) {
      const name2 = this._extScope.value(prefixOrName, value);
      const vs = this._values[name2.prefix] || (this._values[name2.prefix] = /* @__PURE__ */ new Set());
      vs.add(name2);
      return name2;
    }
    getScopeValue(prefix, keyOrRef) {
      return this._extScope.getValue(prefix, keyOrRef);
    }
    // return code that assigns values in the external scope to the names that are used internally
    // (same names that were returned by gen.scopeName or gen.scopeValue)
    scopeRefs(scopeName) {
      return this._extScope.scopeRefs(scopeName, this._values);
    }
    scopeCode() {
      return this._extScope.scopeCode(this._values);
    }
    _def(varKind, nameOrPrefix, rhs, constant) {
      const name2 = this._scope.toName(nameOrPrefix);
      if (rhs !== void 0 && constant)
        this._constants[name2.str] = rhs;
      this._leafNode(new Def(varKind, name2, rhs));
      return name2;
    }
    // `const` declaration (`var` in es5 mode)
    const(nameOrPrefix, rhs, _constant) {
      return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
    }
    // `let` declaration with optional assignment (`var` in es5 mode)
    let(nameOrPrefix, rhs, _constant) {
      return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
    }
    // `var` declaration with optional assignment
    var(nameOrPrefix, rhs, _constant) {
      return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
    }
    // assignment code
    assign(lhs, rhs, sideEffects) {
      return this._leafNode(new Assign(lhs, rhs, sideEffects));
    }
    // `+=` code
    add(lhs, rhs) {
      return this._leafNode(new AssignOp(lhs, exports2.operators.ADD, rhs));
    }
    // appends passed SafeExpr to code or executes Block
    code(c) {
      if (typeof c == "function")
        c();
      else if (c !== code_12.nil)
        this._leafNode(new AnyCode(c));
      return this;
    }
    // returns code for object literal for the passed argument list of key-value pairs
    object(...keyValues) {
      const code2 = ["{"];
      for (const [key, value] of keyValues) {
        if (code2.length > 1)
          code2.push(",");
        code2.push(key);
        if (key !== value || this.opts.es5) {
          code2.push(":");
          (0, code_12.addCodeArg)(code2, value);
        }
      }
      code2.push("}");
      return new code_12._Code(code2);
    }
    // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
    if(condition, thenBody, elseBody) {
      this._blockNode(new If(condition));
      if (thenBody && elseBody) {
        this.code(thenBody).else().code(elseBody).endIf();
      } else if (thenBody) {
        this.code(thenBody).endIf();
      } else if (elseBody) {
        throw new Error('CodeGen: "else" body without "then" body');
      }
      return this;
    }
    // `else if` clause - invalid without `if` or after `else` clauses
    elseIf(condition) {
      return this._elseNode(new If(condition));
    }
    // `else` clause - only valid after `if` or `else if` clauses
    else() {
      return this._elseNode(new Else());
    }
    // end `if` statement (needed if gen.if was used only with condition)
    endIf() {
      return this._endBlockNode(If, Else);
    }
    _for(node, forBody) {
      this._blockNode(node);
      if (forBody)
        this.code(forBody).endFor();
      return this;
    }
    // a generic `for` clause (or statement if `forBody` is passed)
    for(iteration, forBody) {
      return this._for(new ForLoop(iteration), forBody);
    }
    // `for` statement for a range of values
    forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
      const name2 = this._scope.toName(nameOrPrefix);
      return this._for(new ForRange(varKind, name2, from, to), () => forBody(name2));
    }
    // `for-of` statement (in es5 mode replace with a normal for loop)
    forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
      const name2 = this._scope.toName(nameOrPrefix);
      if (this.opts.es5) {
        const arr = iterable instanceof code_12.Name ? iterable : this.var("_arr", iterable);
        return this.forRange("_i", 0, (0, code_12._)`${arr}.length`, (i) => {
          this.var(name2, (0, code_12._)`${arr}[${i}]`);
          forBody(name2);
        });
      }
      return this._for(new ForIter("of", varKind, name2, iterable), () => forBody(name2));
    }
    // `for-in` statement.
    // With option `ownProperties` replaced with a `for-of` loop for object keys
    forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
      if (this.opts.ownProperties) {
        return this.forOf(nameOrPrefix, (0, code_12._)`Object.keys(${obj})`, forBody);
      }
      const name2 = this._scope.toName(nameOrPrefix);
      return this._for(new ForIter("in", varKind, name2, obj), () => forBody(name2));
    }
    // end `for` loop
    endFor() {
      return this._endBlockNode(For);
    }
    // `label` statement
    label(label) {
      return this._leafNode(new Label(label));
    }
    // `break` statement
    break(label) {
      return this._leafNode(new Break(label));
    }
    // `return` statement
    return(value) {
      const node = new Return();
      this._blockNode(node);
      this.code(value);
      if (node.nodes.length !== 1)
        throw new Error('CodeGen: "return" should have one node');
      return this._endBlockNode(Return);
    }
    // `try` statement
    try(tryBody, catchCode, finallyCode) {
      if (!catchCode && !finallyCode)
        throw new Error('CodeGen: "try" without "catch" and "finally"');
      const node = new Try();
      this._blockNode(node);
      this.code(tryBody);
      if (catchCode) {
        const error2 = this.name("e");
        this._currNode = node.catch = new Catch(error2);
        catchCode(error2);
      }
      if (finallyCode) {
        this._currNode = node.finally = new Finally();
        this.code(finallyCode);
      }
      return this._endBlockNode(Catch, Finally);
    }
    // `throw` statement
    throw(error2) {
      return this._leafNode(new Throw(error2));
    }
    // start self-balancing block
    block(body, nodeCount) {
      this._blockStarts.push(this._nodes.length);
      if (body)
        this.code(body).endBlock(nodeCount);
      return this;
    }
    // end the current self-balancing block
    endBlock(nodeCount) {
      const len = this._blockStarts.pop();
      if (len === void 0)
        throw new Error("CodeGen: not in self-balancing block");
      const toClose = this._nodes.length - len;
      if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
        throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
      }
      this._nodes.length = len;
      return this;
    }
    // `function` heading (or definition if funcBody is passed)
    func(name2, args = code_12.nil, async, funcBody) {
      this._blockNode(new Func(name2, args, async));
      if (funcBody)
        this.code(funcBody).endFunc();
      return this;
    }
    // end function definition
    endFunc() {
      return this._endBlockNode(Func);
    }
    optimize(n = 1) {
      while (n-- > 0) {
        this._root.optimizeNodes();
        this._root.optimizeNames(this._root.names, this._constants);
      }
    }
    _leafNode(node) {
      this._currNode.nodes.push(node);
      return this;
    }
    _blockNode(node) {
      this._currNode.nodes.push(node);
      this._nodes.push(node);
    }
    _endBlockNode(N1, N2) {
      const n = this._currNode;
      if (n instanceof N1 || N2 && n instanceof N2) {
        this._nodes.pop();
        return this;
      }
      throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
    }
    _elseNode(node) {
      const n = this._currNode;
      if (!(n instanceof If)) {
        throw new Error('CodeGen: "else" without "if"');
      }
      this._currNode = n.else = node;
      return this;
    }
    get _root() {
      return this._nodes[0];
    }
    get _currNode() {
      const ns = this._nodes;
      return ns[ns.length - 1];
    }
    set _currNode(node) {
      const ns = this._nodes;
      ns[ns.length - 1] = node;
    }
  }
  exports2.CodeGen = CodeGen;
  function addNames(names2, from) {
    for (const n in from)
      names2[n] = (names2[n] || 0) + (from[n] || 0);
    return names2;
  }
  function addExprNames(names2, from) {
    return from instanceof code_12._CodeOrName ? addNames(names2, from.names) : names2;
  }
  function optimizeExpr(expr, names2, constants) {
    if (expr instanceof code_12.Name)
      return replaceName(expr);
    if (!canOptimize(expr))
      return expr;
    return new code_12._Code(expr._items.reduce((items2, c) => {
      if (c instanceof code_12.Name)
        c = replaceName(c);
      if (c instanceof code_12._Code)
        items2.push(...c._items);
      else
        items2.push(c);
      return items2;
    }, []));
    function replaceName(n) {
      const c = constants[n.str];
      if (c === void 0 || names2[n.str] !== 1)
        return n;
      delete names2[n.str];
      return c;
    }
    function canOptimize(e) {
      return e instanceof code_12._Code && e._items.some((c) => c instanceof code_12.Name && names2[c.str] === 1 && constants[c.str] !== void 0);
    }
  }
  function subtractNames(names2, from) {
    for (const n in from)
      names2[n] = (names2[n] || 0) - (from[n] || 0);
  }
  function not2(x) {
    return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_12._)`!${par(x)}`;
  }
  exports2.not = not2;
  const andCode = mappend(exports2.operators.AND);
  function and(...args) {
    return args.reduce(andCode);
  }
  exports2.and = and;
  const orCode = mappend(exports2.operators.OR);
  function or(...args) {
    return args.reduce(orCode);
  }
  exports2.or = or;
  function mappend(op) {
    return (x, y) => x === code_12.nil ? y : y === code_12.nil ? x : (0, code_12._)`${par(x)} ${op} ${par(y)}`;
  }
  function par(x) {
    return x instanceof code_12.Name ? x : (0, code_12._)`(${x})`;
  }
})(codegen);
var util = {};
Object.defineProperty(util, "__esModule", { value: true });
util.checkStrictMode = util.getErrorPath = util.Type = util.useFunc = util.setEvaluated = util.evaluatedPropsToName = util.mergeEvaluated = util.eachItem = util.unescapeJsonPointer = util.escapeJsonPointer = util.escapeFragment = util.unescapeFragment = util.schemaRefOrVal = util.schemaHasRulesButRef = util.schemaHasRules = util.checkUnknownRules = util.alwaysValidSchema = util.toHash = void 0;
const codegen_1$v = codegen;
const code_1$a = code$1;
function toHash(arr) {
  const hash = {};
  for (const item of arr)
    hash[item] = true;
  return hash;
}
util.toHash = toHash;
function alwaysValidSchema(it, schema) {
  if (typeof schema == "boolean")
    return schema;
  if (Object.keys(schema).length === 0)
    return true;
  checkUnknownRules(it, schema);
  return !schemaHasRules(schema, it.self.RULES.all);
}
util.alwaysValidSchema = alwaysValidSchema;
function checkUnknownRules(it, schema = it.schema) {
  const { opts, self: self2 } = it;
  if (!opts.strictSchema)
    return;
  if (typeof schema === "boolean")
    return;
  const rules2 = self2.RULES.keywords;
  for (const key in schema) {
    if (!rules2[key])
      checkStrictMode(it, `unknown keyword: "${key}"`);
  }
}
util.checkUnknownRules = checkUnknownRules;
function schemaHasRules(schema, rules2) {
  if (typeof schema == "boolean")
    return !schema;
  for (const key in schema)
    if (rules2[key])
      return true;
  return false;
}
util.schemaHasRules = schemaHasRules;
function schemaHasRulesButRef(schema, RULES) {
  if (typeof schema == "boolean")
    return !schema;
  for (const key in schema)
    if (key !== "$ref" && RULES.all[key])
      return true;
  return false;
}
util.schemaHasRulesButRef = schemaHasRulesButRef;
function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword2, $data) {
  if (!$data) {
    if (typeof schema == "number" || typeof schema == "boolean")
      return schema;
    if (typeof schema == "string")
      return (0, codegen_1$v._)`${schema}`;
  }
  return (0, codegen_1$v._)`${topSchemaRef}${schemaPath}${(0, codegen_1$v.getProperty)(keyword2)}`;
}
util.schemaRefOrVal = schemaRefOrVal;
function unescapeFragment(str) {
  return unescapeJsonPointer(decodeURIComponent(str));
}
util.unescapeFragment = unescapeFragment;
function escapeFragment(str) {
  return encodeURIComponent(escapeJsonPointer(str));
}
util.escapeFragment = escapeFragment;
function escapeJsonPointer(str) {
  if (typeof str == "number")
    return `${str}`;
  return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
util.escapeJsonPointer = escapeJsonPointer;
function unescapeJsonPointer(str) {
  return str.replace(/~1/g, "/").replace(/~0/g, "~");
}
util.unescapeJsonPointer = unescapeJsonPointer;
function eachItem(xs, f) {
  if (Array.isArray(xs)) {
    for (const x of xs)
      f(x);
  } else {
    f(xs);
  }
}
util.eachItem = eachItem;
function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) {
  return (gen, from, to, toName) => {
    const res = to === void 0 ? from : to instanceof codegen_1$v.Name ? (from instanceof codegen_1$v.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1$v.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to);
    return toName === codegen_1$v.Name && !(res instanceof codegen_1$v.Name) ? resultToName(gen, res) : res;
  };
}
util.mergeEvaluated = {
  props: makeMergeEvaluated({
    mergeNames: (gen, from, to) => gen.if((0, codegen_1$v._)`${to} !== true && ${from} !== undefined`, () => {
      gen.if((0, codegen_1$v._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1$v._)`${to} || {}`).code((0, codegen_1$v._)`Object.assign(${to}, ${from})`));
    }),
    mergeToName: (gen, from, to) => gen.if((0, codegen_1$v._)`${to} !== true`, () => {
      if (from === true) {
        gen.assign(to, true);
      } else {
        gen.assign(to, (0, codegen_1$v._)`${to} || {}`);
        setEvaluated(gen, to, from);
      }
    }),
    mergeValues: (from, to) => from === true ? true : { ...from, ...to },
    resultToName: evaluatedPropsToName
  }),
  items: makeMergeEvaluated({
    mergeNames: (gen, from, to) => gen.if((0, codegen_1$v._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1$v._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
    mergeToName: (gen, from, to) => gen.if((0, codegen_1$v._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1$v._)`${to} > ${from} ? ${to} : ${from}`)),
    mergeValues: (from, to) => from === true ? true : Math.max(from, to),
    resultToName: (gen, items2) => gen.var("items", items2)
  })
};
function evaluatedPropsToName(gen, ps) {
  if (ps === true)
    return gen.var("props", true);
  const props = gen.var("props", (0, codegen_1$v._)`{}`);
  if (ps !== void 0)
    setEvaluated(gen, props, ps);
  return props;
}
util.evaluatedPropsToName = evaluatedPropsToName;
function setEvaluated(gen, props, ps) {
  Object.keys(ps).forEach((p) => gen.assign((0, codegen_1$v._)`${props}${(0, codegen_1$v.getProperty)(p)}`, true));
}
util.setEvaluated = setEvaluated;
const snippets = {};
function useFunc(gen, f) {
  return gen.scopeValue("func", {
    ref: f,
    code: snippets[f.code] || (snippets[f.code] = new code_1$a._Code(f.code))
  });
}
util.useFunc = useFunc;
var Type;
(function(Type2) {
  Type2[Type2["Num"] = 0] = "Num";
  Type2[Type2["Str"] = 1] = "Str";
})(Type || (util.Type = Type = {}));
function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
  if (dataProp instanceof codegen_1$v.Name) {
    const isNumber = dataPropType === Type.Num;
    return jsPropertySyntax ? isNumber ? (0, codegen_1$v._)`"[" + ${dataProp} + "]"` : (0, codegen_1$v._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1$v._)`"/" + ${dataProp}` : (0, codegen_1$v._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
  }
  return jsPropertySyntax ? (0, codegen_1$v.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
}
util.getErrorPath = getErrorPath;
function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
  if (!mode)
    return;
  msg = `strict mode: ${msg}`;
  if (mode === true)
    throw new Error(msg);
  it.self.logger.warn(msg);
}
util.checkStrictMode = checkStrictMode;
var names$1 = {};
Object.defineProperty(names$1, "__esModule", { value: true });
const codegen_1$u = codegen;
const names = {
  // validation function arguments
  data: new codegen_1$u.Name("data"),
  // data passed to validation function
  // args passed from referencing schema
  valCxt: new codegen_1$u.Name("valCxt"),
  // validation/data context - should not be used directly, it is destructured to the names below
  instancePath: new codegen_1$u.Name("instancePath"),
  parentData: new codegen_1$u.Name("parentData"),
  parentDataProperty: new codegen_1$u.Name("parentDataProperty"),
  rootData: new codegen_1$u.Name("rootData"),
  // root data - same as the data passed to the first/top validation function
  dynamicAnchors: new codegen_1$u.Name("dynamicAnchors"),
  // used to support recursiveRef and dynamicRef
  // function scoped variables
  vErrors: new codegen_1$u.Name("vErrors"),
  // null or array of validation errors
  errors: new codegen_1$u.Name("errors"),
  // counter of validation errors
  this: new codegen_1$u.Name("this"),
  // "globals"
  self: new codegen_1$u.Name("self"),
  scope: new codegen_1$u.Name("scope"),
  // JTD serialize/parse name for JSON string and position
  json: new codegen_1$u.Name("json"),
  jsonPos: new codegen_1$u.Name("jsonPos"),
  jsonLen: new codegen_1$u.Name("jsonLen"),
  jsonPart: new codegen_1$u.Name("jsonPart")
};
names$1.default = names;
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.extendErrors = exports2.resetErrorsCount = exports2.reportExtraError = exports2.reportError = exports2.keyword$DataError = exports2.keywordError = void 0;
  const codegen_12 = codegen;
  const util_12 = util;
  const names_12 = names$1;
  exports2.keywordError = {
    message: ({ keyword: keyword2 }) => (0, codegen_12.str)`must pass "${keyword2}" keyword validation`
  };
  exports2.keyword$DataError = {
    message: ({ keyword: keyword2, schemaType }) => schemaType ? (0, codegen_12.str)`"${keyword2}" keyword must be ${schemaType} ($data)` : (0, codegen_12.str)`"${keyword2}" keyword is invalid ($data)`
  };
  function reportError(cxt, error2 = exports2.keywordError, errorPaths, overrideAllErrors) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error2, errorPaths);
    if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
      addError(gen, errObj);
    } else {
      returnErrors(it, (0, codegen_12._)`[${errObj}]`);
    }
  }
  exports2.reportError = reportError;
  function reportExtraError(cxt, error2 = exports2.keywordError, errorPaths) {
    const { it } = cxt;
    const { gen, compositeRule, allErrors } = it;
    const errObj = errorObjectCode(cxt, error2, errorPaths);
    addError(gen, errObj);
    if (!(compositeRule || allErrors)) {
      returnErrors(it, names_12.default.vErrors);
    }
  }
  exports2.reportExtraError = reportExtraError;
  function resetErrorsCount(gen, errsCount) {
    gen.assign(names_12.default.errors, errsCount);
    gen.if((0, codegen_12._)`${names_12.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_12._)`${names_12.default.vErrors}.length`, errsCount), () => gen.assign(names_12.default.vErrors, null)));
  }
  exports2.resetErrorsCount = resetErrorsCount;
  function extendErrors({ gen, keyword: keyword2, schemaValue, data, errsCount, it }) {
    if (errsCount === void 0)
      throw new Error("ajv implementation error");
    const err = gen.name("err");
    gen.forRange("i", errsCount, names_12.default.errors, (i) => {
      gen.const(err, (0, codegen_12._)`${names_12.default.vErrors}[${i}]`);
      gen.if((0, codegen_12._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_12._)`${err}.instancePath`, (0, codegen_12.strConcat)(names_12.default.instancePath, it.errorPath)));
      gen.assign((0, codegen_12._)`${err}.schemaPath`, (0, codegen_12.str)`${it.errSchemaPath}/${keyword2}`);
      if (it.opts.verbose) {
        gen.assign((0, codegen_12._)`${err}.schema`, schemaValue);
        gen.assign((0, codegen_12._)`${err}.data`, data);
      }
    });
  }
  exports2.extendErrors = extendErrors;
  function addError(gen, errObj) {
    const err = gen.const("err", errObj);
    gen.if((0, codegen_12._)`${names_12.default.vErrors} === null`, () => gen.assign(names_12.default.vErrors, (0, codegen_12._)`[${err}]`), (0, codegen_12._)`${names_12.default.vErrors}.push(${err})`);
    gen.code((0, codegen_12._)`${names_12.default.errors}++`);
  }
  function returnErrors(it, errs) {
    const { gen, validateName: validateName2, schemaEnv } = it;
    if (schemaEnv.$async) {
      gen.throw((0, codegen_12._)`new ${it.ValidationError}(${errs})`);
    } else {
      gen.assign((0, codegen_12._)`${validateName2}.errors`, errs);
      gen.return(false);
    }
  }
  const E = {
    keyword: new codegen_12.Name("keyword"),
    schemaPath: new codegen_12.Name("schemaPath"),
    // also used in JTD errors
    params: new codegen_12.Name("params"),
    propertyName: new codegen_12.Name("propertyName"),
    message: new codegen_12.Name("message"),
    schema: new codegen_12.Name("schema"),
    parentSchema: new codegen_12.Name("parentSchema")
  };
  function errorObjectCode(cxt, error2, errorPaths) {
    const { createErrors } = cxt.it;
    if (createErrors === false)
      return (0, codegen_12._)`{}`;
    return errorObject(cxt, error2, errorPaths);
  }
  function errorObject(cxt, error2, errorPaths = {}) {
    const { gen, it } = cxt;
    const keyValues = [
      errorInstancePath(it, errorPaths),
      errorSchemaPath(cxt, errorPaths)
    ];
    extraErrorProps(cxt, error2, keyValues);
    return gen.object(...keyValues);
  }
  function errorInstancePath({ errorPath }, { instancePath }) {
    const instPath = instancePath ? (0, codegen_12.str)`${errorPath}${(0, util_12.getErrorPath)(instancePath, util_12.Type.Str)}` : errorPath;
    return [names_12.default.instancePath, (0, codegen_12.strConcat)(names_12.default.instancePath, instPath)];
  }
  function errorSchemaPath({ keyword: keyword2, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
    let schPath = parentSchema ? errSchemaPath : (0, codegen_12.str)`${errSchemaPath}/${keyword2}`;
    if (schemaPath) {
      schPath = (0, codegen_12.str)`${schPath}${(0, util_12.getErrorPath)(schemaPath, util_12.Type.Str)}`;
    }
    return [E.schemaPath, schPath];
  }
  function extraErrorProps(cxt, { params, message }, keyValues) {
    const { keyword: keyword2, data, schemaValue, it } = cxt;
    const { opts, propertyName, topSchemaRef, schemaPath } = it;
    keyValues.push([E.keyword, keyword2], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_12._)`{}`]);
    if (opts.messages) {
      keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
    }
    if (opts.verbose) {
      keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_12._)`${topSchemaRef}${schemaPath}`], [names_12.default.data, data]);
    }
    if (propertyName)
      keyValues.push([E.propertyName, propertyName]);
  }
})(errors);
Object.defineProperty(boolSchema, "__esModule", { value: true });
boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0;
const errors_1$3 = errors;
const codegen_1$t = codegen;
const names_1$6 = names$1;
const boolError = {
  message: "boolean schema is false"
};
function topBoolOrEmptySchema(it) {
  const { gen, schema, validateName: validateName2 } = it;
  if (schema === false) {
    falseSchemaError(it, false);
  } else if (typeof schema == "object" && schema.$async === true) {
    gen.return(names_1$6.default.data);
  } else {
    gen.assign((0, codegen_1$t._)`${validateName2}.errors`, null);
    gen.return(true);
  }
}
boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema;
function boolOrEmptySchema(it, valid) {
  const { gen, schema } = it;
  if (schema === false) {
    gen.var(valid, false);
    falseSchemaError(it);
  } else {
    gen.var(valid, true);
  }
}
boolSchema.boolOrEmptySchema = boolOrEmptySchema;
function falseSchemaError(it, overrideAllErrors) {
  const { gen, data } = it;
  const cxt = {
    gen,
    keyword: "false schema",
    data,
    schema: false,
    schemaCode: false,
    schemaValue: false,
    params: {},
    it
  };
  (0, errors_1$3.reportError)(cxt, boolError, void 0, overrideAllErrors);
}
var dataType = {};
var rules = {};
Object.defineProperty(rules, "__esModule", { value: true });
rules.getRules = rules.isJSONType = void 0;
const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
const jsonTypes = new Set(_jsonTypes);
function isJSONType(x) {
  return typeof x == "string" && jsonTypes.has(x);
}
rules.isJSONType = isJSONType;
function getRules() {
  const groups = {
    number: { type: "number", rules: [] },
    string: { type: "string", rules: [] },
    array: { type: "array", rules: [] },
    object: { type: "object", rules: [] }
  };
  return {
    types: { ...groups, integer: true, boolean: true, null: true },
    rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
    post: { rules: [] },
    all: {},
    keywords: {}
  };
}
rules.getRules = getRules;
var applicability = {};
Object.defineProperty(applicability, "__esModule", { value: true });
applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0;
function schemaHasRulesForType({ schema, self: self2 }, type2) {
  const group = self2.RULES.types[type2];
  return group && group !== true && shouldUseGroup(schema, group);
}
applicability.schemaHasRulesForType = schemaHasRulesForType;
function shouldUseGroup(schema, group) {
  return group.rules.some((rule) => shouldUseRule(schema, rule));
}
applicability.shouldUseGroup = shouldUseGroup;
function shouldUseRule(schema, rule) {
  var _a;
  return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0));
}
applicability.shouldUseRule = shouldUseRule;
Object.defineProperty(dataType, "__esModule", { value: true });
dataType.reportTypeError = dataType.checkDataTypes = dataType.checkDataType = dataType.coerceAndCheckDataType = dataType.getJSONTypes = dataType.getSchemaTypes = dataType.DataType = void 0;
const rules_1 = rules;
const applicability_1$1 = applicability;
const errors_1$2 = errors;
const codegen_1$s = codegen;
const util_1$q = util;
var DataType;
(function(DataType2) {
  DataType2[DataType2["Correct"] = 0] = "Correct";
  DataType2[DataType2["Wrong"] = 1] = "Wrong";
})(DataType || (dataType.DataType = DataType = {}));
function getSchemaTypes(schema) {
  const types2 = getJSONTypes(schema.type);
  const hasNull = types2.includes("null");
  if (hasNull) {
    if (schema.nullable === false)
      throw new Error("type: null contradicts nullable: false");
  } else {
    if (!types2.length && schema.nullable !== void 0) {
      throw new Error('"nullable" cannot be used without "type"');
    }
    if (schema.nullable === true)
      types2.push("null");
  }
  return types2;
}
dataType.getSchemaTypes = getSchemaTypes;
function getJSONTypes(ts) {
  const types2 = Array.isArray(ts) ? ts : ts ? [ts] : [];
  if (types2.every(rules_1.isJSONType))
    return types2;
  throw new Error("type must be JSONType or JSONType[]: " + types2.join(","));
}
dataType.getJSONTypes = getJSONTypes;
function coerceAndCheckDataType(it, types2) {
  const { gen, data, opts } = it;
  const coerceTo = coerceToTypes(types2, opts.coerceTypes);
  const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1$1.schemaHasRulesForType)(it, types2[0]));
  if (checkTypes) {
    const wrongType = checkDataTypes(types2, data, opts.strictNumbers, DataType.Wrong);
    gen.if(wrongType, () => {
      if (coerceTo.length)
        coerceData(it, types2, coerceTo);
      else
        reportTypeError(it);
    });
  }
  return checkTypes;
}
dataType.coerceAndCheckDataType = coerceAndCheckDataType;
const COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
function coerceToTypes(types2, coerceTypes) {
  return coerceTypes ? types2.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];
}
function coerceData(it, types2, coerceTo) {
  const { gen, data, opts } = it;
  const dataType2 = gen.let("dataType", (0, codegen_1$s._)`typeof ${data}`);
  const coerced = gen.let("coerced", (0, codegen_1$s._)`undefined`);
  if (opts.coerceTypes === "array") {
    gen.if((0, codegen_1$s._)`${dataType2} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1$s._)`${data}[0]`).assign(dataType2, (0, codegen_1$s._)`typeof ${data}`).if(checkDataTypes(types2, data, opts.strictNumbers), () => gen.assign(coerced, data)));
  }
  gen.if((0, codegen_1$s._)`${coerced} !== undefined`);
  for (const t of coerceTo) {
    if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {
      coerceSpecificType(t);
    }
  }
  gen.else();
  reportTypeError(it);
  gen.endIf();
  gen.if((0, codegen_1$s._)`${coerced} !== undefined`, () => {
    gen.assign(data, coerced);
    assignParentData(it, coerced);
  });
  function coerceSpecificType(t) {
    switch (t) {
      case "string":
        gen.elseIf((0, codegen_1$s._)`${dataType2} == "number" || ${dataType2} == "boolean"`).assign(coerced, (0, codegen_1$s._)`"" + ${data}`).elseIf((0, codegen_1$s._)`${data} === null`).assign(coerced, (0, codegen_1$s._)`""`);
        return;
      case "number":
        gen.elseIf((0, codegen_1$s._)`${dataType2} == "boolean" || ${data} === null
              || (${dataType2} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1$s._)`+${data}`);
        return;
      case "integer":
        gen.elseIf((0, codegen_1$s._)`${dataType2} === "boolean" || ${data} === null
              || (${dataType2} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1$s._)`+${data}`);
        return;
      case "boolean":
        gen.elseIf((0, codegen_1$s._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1$s._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
        return;
      case "null":
        gen.elseIf((0, codegen_1$s._)`${data} === "" || ${data} === 0 || ${data} === false`);
        gen.assign(coerced, null);
        return;
      case "array":
        gen.elseIf((0, codegen_1$s._)`${dataType2} === "string" || ${dataType2} === "number"
              || ${dataType2} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1$s._)`[${data}]`);
    }
  }
}
function assignParentData({ gen, parentData, parentDataProperty }, expr) {
  gen.if((0, codegen_1$s._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1$s._)`${parentData}[${parentDataProperty}]`, expr));
}
function checkDataType(dataType2, data, strictNums, correct = DataType.Correct) {
  const EQ = correct === DataType.Correct ? codegen_1$s.operators.EQ : codegen_1$s.operators.NEQ;
  let cond;
  switch (dataType2) {
    case "null":
      return (0, codegen_1$s._)`${data} ${EQ} null`;
    case "array":
      cond = (0, codegen_1$s._)`Array.isArray(${data})`;
      break;
    case "object":
      cond = (0, codegen_1$s._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
      break;
    case "integer":
      cond = numCond((0, codegen_1$s._)`!(${data} % 1) && !isNaN(${data})`);
      break;
    case "number":
      cond = numCond();
      break;
    default:
      return (0, codegen_1$s._)`typeof ${data} ${EQ} ${dataType2}`;
  }
  return correct === DataType.Correct ? cond : (0, codegen_1$s.not)(cond);
  function numCond(_cond = codegen_1$s.nil) {
    return (0, codegen_1$s.and)((0, codegen_1$s._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1$s._)`isFinite(${data})` : codegen_1$s.nil);
  }
}
dataType.checkDataType = checkDataType;
function checkDataTypes(dataTypes, data, strictNums, correct) {
  if (dataTypes.length === 1) {
    return checkDataType(dataTypes[0], data, strictNums, correct);
  }
  let cond;
  const types2 = (0, util_1$q.toHash)(dataTypes);
  if (types2.array && types2.object) {
    const notObj = (0, codegen_1$s._)`typeof ${data} != "object"`;
    cond = types2.null ? notObj : (0, codegen_1$s._)`!${data} || ${notObj}`;
    delete types2.null;
    delete types2.array;
    delete types2.object;
  } else {
    cond = codegen_1$s.nil;
  }
  if (types2.number)
    delete types2.integer;
  for (const t in types2)
    cond = (0, codegen_1$s.and)(cond, checkDataType(t, data, strictNums, correct));
  return cond;
}
dataType.checkDataTypes = checkDataTypes;
const typeError = {
  message: ({ schema }) => `must be ${schema}`,
  params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1$s._)`{type: ${schema}}` : (0, codegen_1$s._)`{type: ${schemaValue}}`
};
function reportTypeError(it) {
  const cxt = getTypeErrorContext(it);
  (0, errors_1$2.reportError)(cxt, typeError);
}
dataType.reportTypeError = reportTypeError;
function getTypeErrorContext(it) {
  const { gen, data, schema } = it;
  const schemaCode = (0, util_1$q.schemaRefOrVal)(it, schema, "type");
  return {
    gen,
    keyword: "type",
    data,
    schema: schema.type,
    schemaCode,
    schemaValue: schemaCode,
    parentSchema: schema,
    params: {},
    it
  };
}
var defaults = {};
Object.defineProperty(defaults, "__esModule", { value: true });
defaults.assignDefaults = void 0;
const codegen_1$r = codegen;
const util_1$p = util;
function assignDefaults(it, ty) {
  const { properties: properties2, items: items2 } = it.schema;
  if (ty === "object" && properties2) {
    for (const key in properties2) {
      assignDefault(it, key, properties2[key].default);
    }
  } else if (ty === "array" && Array.isArray(items2)) {
    items2.forEach((sch, i) => assignDefault(it, i, sch.default));
  }
}
defaults.assignDefaults = assignDefaults;
function assignDefault(it, prop, defaultValue) {
  const { gen, compositeRule, data, opts } = it;
  if (defaultValue === void 0)
    return;
  const childData = (0, codegen_1$r._)`${data}${(0, codegen_1$r.getProperty)(prop)}`;
  if (compositeRule) {
    (0, util_1$p.checkStrictMode)(it, `default is ignored for: ${childData}`);
    return;
  }
  let condition = (0, codegen_1$r._)`${childData} === undefined`;
  if (opts.useDefaults === "empty") {
    condition = (0, codegen_1$r._)`${condition} || ${childData} === null || ${childData} === ""`;
  }
  gen.if(condition, (0, codegen_1$r._)`${childData} = ${(0, codegen_1$r.stringify)(defaultValue)}`);
}
var keyword = {};
var code = {};
Object.defineProperty(code, "__esModule", { value: true });
code.validateUnion = code.validateArray = code.usePattern = code.callValidateCode = code.schemaProperties = code.allSchemaProperties = code.noPropertyInData = code.propertyInData = code.isOwnProperty = code.hasPropFunc = code.reportMissingProp = code.checkMissingProp = code.checkReportMissingProp = void 0;
const codegen_1$q = codegen;
const util_1$o = util;
const names_1$5 = names$1;
const util_2$1 = util;
function checkReportMissingProp(cxt, prop) {
  const { gen, data, it } = cxt;
  gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
    cxt.setParams({ missingProperty: (0, codegen_1$q._)`${prop}` }, true);
    cxt.error();
  });
}
code.checkReportMissingProp = checkReportMissingProp;
function checkMissingProp({ gen, data, it: { opts } }, properties2, missing) {
  return (0, codegen_1$q.or)(...properties2.map((prop) => (0, codegen_1$q.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1$q._)`${missing} = ${prop}`)));
}
code.checkMissingProp = checkMissingProp;
function reportMissingProp(cxt, missing) {
  cxt.setParams({ missingProperty: missing }, true);
  cxt.error();
}
code.reportMissingProp = reportMissingProp;
function hasPropFunc(gen) {
  return gen.scopeValue("func", {
    // eslint-disable-next-line @typescript-eslint/unbound-method
    ref: Object.prototype.hasOwnProperty,
    code: (0, codegen_1$q._)`Object.prototype.hasOwnProperty`
  });
}
code.hasPropFunc = hasPropFunc;
function isOwnProperty(gen, data, property) {
  return (0, codegen_1$q._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
}
code.isOwnProperty = isOwnProperty;
function propertyInData(gen, data, property, ownProperties) {
  const cond = (0, codegen_1$q._)`${data}${(0, codegen_1$q.getProperty)(property)} !== undefined`;
  return ownProperties ? (0, codegen_1$q._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
}
code.propertyInData = propertyInData;
function noPropertyInData(gen, data, property, ownProperties) {
  const cond = (0, codegen_1$q._)`${data}${(0, codegen_1$q.getProperty)(property)} === undefined`;
  return ownProperties ? (0, codegen_1$q.or)(cond, (0, codegen_1$q.not)(isOwnProperty(gen, data, property))) : cond;
}
code.noPropertyInData = noPropertyInData;
function allSchemaProperties(schemaMap) {
  return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
}
code.allSchemaProperties = allSchemaProperties;
function schemaProperties(it, schemaMap) {
  return allSchemaProperties(schemaMap).filter((p) => !(0, util_1$o.alwaysValidSchema)(it, schemaMap[p]));
}
code.schemaProperties = schemaProperties;
function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
  const dataAndSchema = passSchema ? (0, codegen_1$q._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
  const valCxt = [
    [names_1$5.default.instancePath, (0, codegen_1$q.strConcat)(names_1$5.default.instancePath, errorPath)],
    [names_1$5.default.parentData, it.parentData],
    [names_1$5.default.parentDataProperty, it.parentDataProperty],
    [names_1$5.default.rootData, names_1$5.default.rootData]
  ];
  if (it.opts.dynamicRef)
    valCxt.push([names_1$5.default.dynamicAnchors, names_1$5.default.dynamicAnchors]);
  const args = (0, codegen_1$q._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
  return context !== codegen_1$q.nil ? (0, codegen_1$q._)`${func}.call(${context}, ${args})` : (0, codegen_1$q._)`${func}(${args})`;
}
code.callValidateCode = callValidateCode;
const newRegExp = (0, codegen_1$q._)`new RegExp`;
function usePattern({ gen, it: { opts } }, pattern2) {
  const u = opts.unicodeRegExp ? "u" : "";
  const { regExp } = opts.code;
  const rx = regExp(pattern2, u);
  return gen.scopeValue("pattern", {
    key: rx.toString(),
    ref: rx,
    code: (0, codegen_1$q._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2$1.useFunc)(gen, regExp)}(${pattern2}, ${u})`
  });
}
code.usePattern = usePattern;
function validateArray(cxt) {
  const { gen, data, keyword: keyword2, it } = cxt;
  const valid = gen.name("valid");
  if (it.allErrors) {
    const validArr = gen.let("valid", true);
    validateItems(() => gen.assign(validArr, false));
    return validArr;
  }
  gen.var(valid, true);
  validateItems(() => gen.break());
  return valid;
  function validateItems(notValid) {
    const len = gen.const("len", (0, codegen_1$q._)`${data}.length`);
    gen.forRange("i", 0, len, (i) => {
      cxt.subschema({
        keyword: keyword2,
        dataProp: i,
        dataPropType: util_1$o.Type.Num
      }, valid);
      gen.if((0, codegen_1$q.not)(valid), notValid);
    });
  }
}
code.validateArray = validateArray;
function validateUnion(cxt) {
  const { gen, schema, keyword: keyword2, it } = cxt;
  if (!Array.isArray(schema))
    throw new Error("ajv implementation error");
  const alwaysValid = schema.some((sch) => (0, util_1$o.alwaysValidSchema)(it, sch));
  if (alwaysValid && !it.opts.unevaluated)
    return;
  const valid = gen.let("valid", false);
  const schValid = gen.name("_valid");
  gen.block(() => schema.forEach((_sch, i) => {
    const schCxt = cxt.subschema({
      keyword: keyword2,
      schemaProp: i,
      compositeRule: true
    }, schValid);
    gen.assign(valid, (0, codegen_1$q._)`${valid} || ${schValid}`);
    const merged = cxt.mergeValidEvaluated(schCxt, schValid);
    if (!merged)
      gen.if((0, codegen_1$q.not)(valid));
  }));
  cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
}
code.validateUnion = validateUnion;
Object.defineProperty(keyword, "__esModule", { value: true });
keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = void 0;
const codegen_1$p = codegen;
const names_1$4 = names$1;
const code_1$9 = code;
const errors_1$1 = errors;
function macroKeywordCode(cxt, def2) {
  const { gen, keyword: keyword2, schema, parentSchema, it } = cxt;
  const macroSchema = def2.macro.call(it.self, schema, parentSchema, it);
  const schemaRef = useKeyword(gen, keyword2, macroSchema);
  if (it.opts.validateSchema !== false)
    it.self.validateSchema(macroSchema, true);
  const valid = gen.name("valid");
  cxt.subschema({
    schema: macroSchema,
    schemaPath: codegen_1$p.nil,
    errSchemaPath: `${it.errSchemaPath}/${keyword2}`,
    topSchemaRef: schemaRef,
    compositeRule: true
  }, valid);
  cxt.pass(valid, () => cxt.error(true));
}
keyword.macroKeywordCode = macroKeywordCode;
function funcKeywordCode(cxt, def2) {
  var _a;
  const { gen, keyword: keyword2, schema, parentSchema, $data, it } = cxt;
  checkAsyncKeyword(it, def2);
  const validate2 = !$data && def2.compile ? def2.compile.call(it.self, schema, parentSchema, it) : def2.validate;
  const validateRef = useKeyword(gen, keyword2, validate2);
  const valid = gen.let("valid");
  cxt.block$data(valid, validateKeyword);
  cxt.ok((_a = def2.valid) !== null && _a !== void 0 ? _a : valid);
  function validateKeyword() {
    if (def2.errors === false) {
      assignValid();
      if (def2.modifying)
        modifyData(cxt);
      reportErrs(() => cxt.error());
    } else {
      const ruleErrs = def2.async ? validateAsync() : validateSync();
      if (def2.modifying)
        modifyData(cxt);
      reportErrs(() => addErrs(cxt, ruleErrs));
    }
  }
  function validateAsync() {
    const ruleErrs = gen.let("ruleErrs", null);
    gen.try(() => assignValid((0, codegen_1$p._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1$p._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1$p._)`${e}.errors`), () => gen.throw(e)));
    return ruleErrs;
  }
  function validateSync() {
    const validateErrs = (0, codegen_1$p._)`${validateRef}.errors`;
    gen.assign(validateErrs, null);
    assignValid(codegen_1$p.nil);
    return validateErrs;
  }
  function assignValid(_await = def2.async ? (0, codegen_1$p._)`await ` : codegen_1$p.nil) {
    const passCxt = it.opts.passContext ? names_1$4.default.this : names_1$4.default.self;
    const passSchema = !("compile" in def2 && !$data || def2.schema === false);
    gen.assign(valid, (0, codegen_1$p._)`${_await}${(0, code_1$9.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def2.modifying);
  }
  function reportErrs(errors2) {
    var _a2;
    gen.if((0, codegen_1$p.not)((_a2 = def2.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors2);
  }
}
keyword.funcKeywordCode = funcKeywordCode;
function modifyData(cxt) {
  const { gen, data, it } = cxt;
  gen.if(it.parentData, () => gen.assign(data, (0, codegen_1$p._)`${it.parentData}[${it.parentDataProperty}]`));
}
function addErrs(cxt, errs) {
  const { gen } = cxt;
  gen.if((0, codegen_1$p._)`Array.isArray(${errs})`, () => {
    gen.assign(names_1$4.default.vErrors, (0, codegen_1$p._)`${names_1$4.default.vErrors} === null ? ${errs} : ${names_1$4.default.vErrors}.concat(${errs})`).assign(names_1$4.default.errors, (0, codegen_1$p._)`${names_1$4.default.vErrors}.length`);
    (0, errors_1$1.extendErrors)(cxt);
  }, () => cxt.error());
}
function checkAsyncKeyword({ schemaEnv }, def2) {
  if (def2.async && !schemaEnv.$async)
    throw new Error("async keyword in sync schema");
}
function useKeyword(gen, keyword2, result) {
  if (result === void 0)
    throw new Error(`keyword "${keyword2}" failed to compile`);
  return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1$p.stringify)(result) });
}
function validSchemaType(schema, schemaType, allowUndefined = false) {
  return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
}
keyword.validSchemaType = validSchemaType;
function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def2, keyword2) {
  if (Array.isArray(def2.keyword) ? !def2.keyword.includes(keyword2) : def2.keyword !== keyword2) {
    throw new Error("ajv implementation error");
  }
  const deps = def2.dependencies;
  if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
    throw new Error(`parent schema must have dependencies of ${keyword2}: ${deps.join(",")}`);
  }
  if (def2.validateSchema) {
    const valid = def2.validateSchema(schema[keyword2]);
    if (!valid) {
      const msg = `keyword "${keyword2}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def2.validateSchema.errors);
      if (opts.validateSchema === "log")
        self2.logger.error(msg);
      else
        throw new Error(msg);
    }
  }
}
keyword.validateKeywordUsage = validateKeywordUsage;
var subschema = {};
Object.defineProperty(subschema, "__esModule", { value: true });
subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0;
const codegen_1$o = codegen;
const util_1$n = util;
function getSubschema(it, { keyword: keyword2, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
  if (keyword2 !== void 0 && schema !== void 0) {
    throw new Error('both "keyword" and "schema" passed, only one allowed');
  }
  if (keyword2 !== void 0) {
    const sch = it.schema[keyword2];
    return schemaProp === void 0 ? {
      schema: sch,
      schemaPath: (0, codegen_1$o._)`${it.schemaPath}${(0, codegen_1$o.getProperty)(keyword2)}`,
      errSchemaPath: `${it.errSchemaPath}/${keyword2}`
    } : {
      schema: sch[schemaProp],
      schemaPath: (0, codegen_1$o._)`${it.schemaPath}${(0, codegen_1$o.getProperty)(keyword2)}${(0, codegen_1$o.getProperty)(schemaProp)}`,
      errSchemaPath: `${it.errSchemaPath}/${keyword2}/${(0, util_1$n.escapeFragment)(schemaProp)}`
    };
  }
  if (schema !== void 0) {
    if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
      throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
    }
    return {
      schema,
      schemaPath,
      topSchemaRef,
      errSchemaPath
    };
  }
  throw new Error('either "keyword" or "schema" must be passed');
}
subschema.getSubschema = getSubschema;
function extendSubschemaData(subschema2, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
  if (data !== void 0 && dataProp !== void 0) {
    throw new Error('both "data" and "dataProp" passed, only one allowed');
  }
  const { gen } = it;
  if (dataProp !== void 0) {
    const { errorPath, dataPathArr, opts } = it;
    const nextData = gen.let("data", (0, codegen_1$o._)`${it.data}${(0, codegen_1$o.getProperty)(dataProp)}`, true);
    dataContextProps(nextData);
    subschema2.errorPath = (0, codegen_1$o.str)`${errorPath}${(0, util_1$n.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
    subschema2.parentDataProperty = (0, codegen_1$o._)`${dataProp}`;
    subschema2.dataPathArr = [...dataPathArr, subschema2.parentDataProperty];
  }
  if (data !== void 0) {
    const nextData = data instanceof codegen_1$o.Name ? data : gen.let("data", data, true);
    dataContextProps(nextData);
    if (propertyName !== void 0)
      subschema2.propertyName = propertyName;
  }
  if (dataTypes)
    subschema2.dataTypes = dataTypes;
  function dataContextProps(_nextData) {
    subschema2.data = _nextData;
    subschema2.dataLevel = it.dataLevel + 1;
    subschema2.dataTypes = [];
    it.definedProperties = /* @__PURE__ */ new Set();
    subschema2.parentData = it.data;
    subschema2.dataNames = [...it.dataNames, _nextData];
  }
}
subschema.extendSubschemaData = extendSubschemaData;
function extendSubschemaMode(subschema2, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
  if (compositeRule !== void 0)
    subschema2.compositeRule = compositeRule;
  if (createErrors !== void 0)
    subschema2.createErrors = createErrors;
  if (allErrors !== void 0)
    subschema2.allErrors = allErrors;
  subschema2.jtdDiscriminator = jtdDiscriminator;
  subschema2.jtdMetadata = jtdMetadata;
}
subschema.extendSubschemaMode = extendSubschemaMode;
var resolve$1 = {};
var fastDeepEqual = function equal(a, b) {
  if (a === b)
    return true;
  if (a && b && typeof a == "object" && typeof b == "object") {
    if (a.constructor !== b.constructor)
      return false;
    var length, i, keys;
    if (Array.isArray(a)) {
      length = a.length;
      if (length != b.length)
        return false;
      for (i = length; i-- !== 0; )
        if (!equal(a[i], b[i]))
          return false;
      return true;
    }
    if (a.constructor === RegExp)
      return a.source === b.source && a.flags === b.flags;
    if (a.valueOf !== Object.prototype.valueOf)
      return a.valueOf() === b.valueOf();
    if (a.toString !== Object.prototype.toString)
      return a.toString() === b.toString();
    keys = Object.keys(a);
    length = keys.length;
    if (length !== Object.keys(b).length)
      return false;
    for (i = length; i-- !== 0; )
      if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
        return false;
    for (i = length; i-- !== 0; ) {
      var key = keys[i];
      if (!equal(a[key], b[key]))
        return false;
    }
    return true;
  }
  return a !== a && b !== b;
};
var jsonSchemaTraverse = { exports: {} };
var traverse$1 = jsonSchemaTraverse.exports = function(schema, opts, cb) {
  if (typeof opts == "function") {
    cb = opts;
    opts = {};
  }
  cb = opts.cb || cb;
  var pre = typeof cb == "function" ? cb : cb.pre || function() {
  };
  var post = cb.post || function() {
  };
  _traverse(opts, pre, post, schema, "", schema);
};
traverse$1.keywords = {
  additionalItems: true,
  items: true,
  contains: true,
  additionalProperties: true,
  propertyNames: true,
  not: true,
  if: true,
  then: true,
  else: true
};
traverse$1.arrayKeywords = {
  items: true,
  allOf: true,
  anyOf: true,
  oneOf: true
};
traverse$1.propsKeywords = {
  $defs: true,
  definitions: true,
  properties: true,
  patternProperties: true,
  dependencies: true
};
traverse$1.skipKeywords = {
  default: true,
  enum: true,
  const: true,
  required: true,
  maximum: true,
  minimum: true,
  exclusiveMaximum: true,
  exclusiveMinimum: true,
  multipleOf: true,
  maxLength: true,
  minLength: true,
  pattern: true,
  format: true,
  maxItems: true,
  minItems: true,
  uniqueItems: true,
  maxProperties: true,
  minProperties: true
};
function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
  if (schema && typeof schema == "object" && !Array.isArray(schema)) {
    pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
    for (var key in schema) {
      var sch = schema[key];
      if (Array.isArray(sch)) {
        if (key in traverse$1.arrayKeywords) {
          for (var i = 0; i < sch.length; i++)
            _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
        }
      } else if (key in traverse$1.propsKeywords) {
        if (sch && typeof sch == "object") {
          for (var prop in sch)
            _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
        }
      } else if (key in traverse$1.keywords || opts.allKeys && !(key in traverse$1.skipKeywords)) {
        _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
      }
    }
    post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
  }
}
function escapeJsonPtr(str) {
  return str.replace(/~/g, "~0").replace(/\//g, "~1");
}
var jsonSchemaTraverseExports = jsonSchemaTraverse.exports;
Object.defineProperty(resolve$1, "__esModule", { value: true });
resolve$1.getSchemaRefs = resolve$1.resolveUrl = resolve$1.normalizeId = resolve$1._getFullPath = resolve$1.getFullPath = resolve$1.inlineRef = void 0;
const util_1$m = util;
const equal$2 = fastDeepEqual;
const traverse = jsonSchemaTraverseExports;
const SIMPLE_INLINED = /* @__PURE__ */ new Set([
  "type",
  "format",
  "pattern",
  "maxLength",
  "minLength",
  "maxProperties",
  "minProperties",
  "maxItems",
  "minItems",
  "maximum",
  "minimum",
  "uniqueItems",
  "multipleOf",
  "required",
  "enum",
  "const"
]);
function inlineRef(schema, limit = true) {
  if (typeof schema == "boolean")
    return true;
  if (limit === true)
    return !hasRef(schema);
  if (!limit)
    return false;
  return countKeys(schema) <= limit;
}
resolve$1.inlineRef = inlineRef;
const REF_KEYWORDS = /* @__PURE__ */ new Set([
  "$ref",
  "$recursiveRef",
  "$recursiveAnchor",
  "$dynamicRef",
  "$dynamicAnchor"
]);
function hasRef(schema) {
  for (const key in schema) {
    if (REF_KEYWORDS.has(key))
      return true;
    const sch = schema[key];
    if (Array.isArray(sch) && sch.some(hasRef))
      return true;
    if (typeof sch == "object" && hasRef(sch))
      return true;
  }
  return false;
}
function countKeys(schema) {
  let count = 0;
  for (const key in schema) {
    if (key === "$ref")
      return Infinity;
    count++;
    if (SIMPLE_INLINED.has(key))
      continue;
    if (typeof schema[key] == "object") {
      (0, util_1$m.eachItem)(schema[key], (sch) => count += countKeys(sch));
    }
    if (count === Infinity)
      return Infinity;
  }
  return count;
}
function getFullPath(resolver, id2 = "", normalize) {
  if (normalize !== false)
    id2 = normalizeId(id2);
  const p = resolver.parse(id2);
  return _getFullPath(resolver, p);
}
resolve$1.getFullPath = getFullPath;
function _getFullPath(resolver, p) {
  const serialized = resolver.serialize(p);
  return serialized.split("#")[0] + "#";
}
resolve$1._getFullPath = _getFullPath;
const TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id2) {
  return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
}
resolve$1.normalizeId = normalizeId;
function resolveUrl(resolver, baseId, id2) {
  id2 = normalizeId(id2);
  return resolver.resolve(baseId, id2);
}
resolve$1.resolveUrl = resolveUrl;
const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
function getSchemaRefs(schema, baseId) {
  if (typeof schema == "boolean")
    return {};
  const { schemaId, uriResolver } = this.opts;
  const schId = normalizeId(schema[schemaId] || baseId);
  const baseIds = { "": schId };
  const pathPrefix = getFullPath(uriResolver, schId, false);
  const localRefs = {};
  const schemaRefs = /* @__PURE__ */ new Set();
  traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
    if (parentJsonPtr === void 0)
      return;
    const fullPath = pathPrefix + jsonPtr;
    let innerBaseId = baseIds[parentJsonPtr];
    if (typeof sch[schemaId] == "string")
      innerBaseId = addRef.call(this, sch[schemaId]);
    addAnchor.call(this, sch.$anchor);
    addAnchor.call(this, sch.$dynamicAnchor);
    baseIds[jsonPtr] = innerBaseId;
    function addRef(ref2) {
      const _resolve = this.opts.uriResolver.resolve;
      ref2 = normalizeId(innerBaseId ? _resolve(innerBaseId, ref2) : ref2);
      if (schemaRefs.has(ref2))
        throw ambiguos(ref2);
      schemaRefs.add(ref2);
      let schOrRef = this.refs[ref2];
      if (typeof schOrRef == "string")
        schOrRef = this.refs[schOrRef];
      if (typeof schOrRef == "object") {
        checkAmbiguosRef(sch, schOrRef.schema, ref2);
      } else if (ref2 !== normalizeId(fullPath)) {
        if (ref2[0] === "#") {
          checkAmbiguosRef(sch, localRefs[ref2], ref2);
          localRefs[ref2] = sch;
        } else {
          this.refs[ref2] = fullPath;
        }
      }
      return ref2;
    }
    function addAnchor(anchor) {
      if (typeof anchor == "string") {
        if (!ANCHOR.test(anchor))
          throw new Error(`invalid anchor "${anchor}"`);
        addRef.call(this, `#${anchor}`);
      }
    }
  });
  return localRefs;
  function checkAmbiguosRef(sch1, sch2, ref2) {
    if (sch2 !== void 0 && !equal$2(sch1, sch2))
      throw ambiguos(ref2);
  }
  function ambiguos(ref2) {
    return new Error(`reference "${ref2}" resolves to more than one schema`);
  }
}
resolve$1.getSchemaRefs = getSchemaRefs;
Object.defineProperty(validate, "__esModule", { value: true });
validate.getData = validate.KeywordCxt = validate.validateFunctionCode = void 0;
const boolSchema_1 = boolSchema;
const dataType_1$1 = dataType;
const applicability_1 = applicability;
const dataType_2 = dataType;
const defaults_1 = defaults;
const keyword_1 = keyword;
const subschema_1 = subschema;
const codegen_1$n = codegen;
const names_1$3 = names$1;
const resolve_1$2 = resolve$1;
const util_1$l = util;
const errors_1 = errors;
function validateFunctionCode(it) {
  if (isSchemaObj(it)) {
    checkKeywords(it);
    if (schemaCxtHasRules(it)) {
      topSchemaObjCode(it);
      return;
    }
  }
  validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
}
validate.validateFunctionCode = validateFunctionCode;
function validateFunction({ gen, validateName: validateName2, schema, schemaEnv, opts }, body) {
  if (opts.code.es5) {
    gen.func(validateName2, (0, codegen_1$n._)`${names_1$3.default.data}, ${names_1$3.default.valCxt}`, schemaEnv.$async, () => {
      gen.code((0, codegen_1$n._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
      destructureValCxtES5(gen, opts);
      gen.code(body);
    });
  } else {
    gen.func(validateName2, (0, codegen_1$n._)`${names_1$3.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
  }
}
function destructureValCxt(opts) {
  return (0, codegen_1$n._)`{${names_1$3.default.instancePath}="", ${names_1$3.default.parentData}, ${names_1$3.default.parentDataProperty}, ${names_1$3.default.rootData}=${names_1$3.default.data}${opts.dynamicRef ? (0, codegen_1$n._)`, ${names_1$3.default.dynamicAnchors}={}` : codegen_1$n.nil}}={}`;
}
function destructureValCxtES5(gen, opts) {
  gen.if(names_1$3.default.valCxt, () => {
    gen.var(names_1$3.default.instancePath, (0, codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.instancePath}`);
    gen.var(names_1$3.default.parentData, (0, codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.parentData}`);
    gen.var(names_1$3.default.parentDataProperty, (0, codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.parentDataProperty}`);
    gen.var(names_1$3.default.rootData, (0, codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.rootData}`);
    if (opts.dynamicRef)
      gen.var(names_1$3.default.dynamicAnchors, (0, codegen_1$n._)`${names_1$3.default.valCxt}.${names_1$3.default.dynamicAnchors}`);
  }, () => {
    gen.var(names_1$3.default.instancePath, (0, codegen_1$n._)`""`);
    gen.var(names_1$3.default.parentData, (0, codegen_1$n._)`undefined`);
    gen.var(names_1$3.default.parentDataProperty, (0, codegen_1$n._)`undefined`);
    gen.var(names_1$3.default.rootData, names_1$3.default.data);
    if (opts.dynamicRef)
      gen.var(names_1$3.default.dynamicAnchors, (0, codegen_1$n._)`{}`);
  });
}
function topSchemaObjCode(it) {
  const { schema, opts, gen } = it;
  validateFunction(it, () => {
    if (opts.$comment && schema.$comment)
      commentKeyword(it);
    checkNoDefault(it);
    gen.let(names_1$3.default.vErrors, null);
    gen.let(names_1$3.default.errors, 0);
    if (opts.unevaluated)
      resetEvaluated(it);
    typeAndKeywords(it);
    returnResults(it);
  });
  return;
}
function resetEvaluated(it) {
  const { gen, validateName: validateName2 } = it;
  it.evaluated = gen.const("evaluated", (0, codegen_1$n._)`${validateName2}.evaluated`);
  gen.if((0, codegen_1$n._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1$n._)`${it.evaluated}.props`, (0, codegen_1$n._)`undefined`));
  gen.if((0, codegen_1$n._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1$n._)`${it.evaluated}.items`, (0, codegen_1$n._)`undefined`));
}
function funcSourceUrl(schema, opts) {
  const schId = typeof schema == "object" && schema[opts.schemaId];
  return schId && (opts.code.source || opts.code.process) ? (0, codegen_1$n._)`/*# sourceURL=${schId} */` : codegen_1$n.nil;
}
function subschemaCode(it, valid) {
  if (isSchemaObj(it)) {
    checkKeywords(it);
    if (schemaCxtHasRules(it)) {
      subSchemaObjCode(it, valid);
      return;
    }
  }
  (0, boolSchema_1.boolOrEmptySchema)(it, valid);
}
function schemaCxtHasRules({ schema, self: self2 }) {
  if (typeof schema == "boolean")
    return !schema;
  for (const key in schema)
    if (self2.RULES.all[key])
      return true;
  return false;
}
function isSchemaObj(it) {
  return typeof it.schema != "boolean";
}
function subSchemaObjCode(it, valid) {
  const { schema, gen, opts } = it;
  if (opts.$comment && schema.$comment)
    commentKeyword(it);
  updateContext(it);
  checkAsyncSchema(it);
  const errsCount = gen.const("_errs", names_1$3.default.errors);
  typeAndKeywords(it, errsCount);
  gen.var(valid, (0, codegen_1$n._)`${errsCount} === ${names_1$3.default.errors}`);
}
function checkKeywords(it) {
  (0, util_1$l.checkUnknownRules)(it);
  checkRefsAndKeywords(it);
}
function typeAndKeywords(it, errsCount) {
  if (it.opts.jtd)
    return schemaKeywords(it, [], false, errsCount);
  const types2 = (0, dataType_1$1.getSchemaTypes)(it.schema);
  const checkedTypes = (0, dataType_1$1.coerceAndCheckDataType)(it, types2);
  schemaKeywords(it, types2, !checkedTypes, errsCount);
}
function checkRefsAndKeywords(it) {
  const { schema, errSchemaPath, opts, self: self2 } = it;
  if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1$l.schemaHasRulesButRef)(schema, self2.RULES)) {
    self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
  }
}
function checkNoDefault(it) {
  const { schema, opts } = it;
  if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
    (0, util_1$l.checkStrictMode)(it, "default is ignored in the schema root");
  }
}
function updateContext(it) {
  const schId = it.schema[it.opts.schemaId];
  if (schId)
    it.baseId = (0, resolve_1$2.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
}
function checkAsyncSchema(it) {
  if (it.schema.$async && !it.schemaEnv.$async)
    throw new Error("async schema in sync schema");
}
function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
  const msg = schema.$comment;
  if (opts.$comment === true) {
    gen.code((0, codegen_1$n._)`${names_1$3.default.self}.logger.log(${msg})`);
  } else if (typeof opts.$comment == "function") {
    const schemaPath = (0, codegen_1$n.str)`${errSchemaPath}/$comment`;
    const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
    gen.code((0, codegen_1$n._)`${names_1$3.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
  }
}
function returnResults(it) {
  const { gen, schemaEnv, validateName: validateName2, ValidationError: ValidationError2, opts } = it;
  if (schemaEnv.$async) {
    gen.if((0, codegen_1$n._)`${names_1$3.default.errors} === 0`, () => gen.return(names_1$3.default.data), () => gen.throw((0, codegen_1$n._)`new ${ValidationError2}(${names_1$3.default.vErrors})`));
  } else {
    gen.assign((0, codegen_1$n._)`${validateName2}.errors`, names_1$3.default.vErrors);
    if (opts.unevaluated)
      assignEvaluated(it);
    gen.return((0, codegen_1$n._)`${names_1$3.default.errors} === 0`);
  }
}
function assignEvaluated({ gen, evaluated, props, items: items2 }) {
  if (props instanceof codegen_1$n.Name)
    gen.assign((0, codegen_1$n._)`${evaluated}.props`, props);
  if (items2 instanceof codegen_1$n.Name)
    gen.assign((0, codegen_1$n._)`${evaluated}.items`, items2);
}
function schemaKeywords(it, types2, typeErrors, errsCount) {
  const { gen, schema, data, allErrors, opts, self: self2 } = it;
  const { RULES } = self2;
  if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1$l.schemaHasRulesButRef)(schema, RULES))) {
    gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
    return;
  }
  if (!opts.jtd)
    checkStrictTypes(it, types2);
  gen.block(() => {
    for (const group of RULES.rules)
      groupKeywords(group);
    groupKeywords(RULES.post);
  });
  function groupKeywords(group) {
    if (!(0, applicability_1.shouldUseGroup)(schema, group))
      return;
    if (group.type) {
      gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
      iterateKeywords(it, group);
      if (types2.length === 1 && types2[0] === group.type && typeErrors) {
        gen.else();
        (0, dataType_2.reportTypeError)(it);
      }
      gen.endIf();
    } else {
      iterateKeywords(it, group);
    }
    if (!allErrors)
      gen.if((0, codegen_1$n._)`${names_1$3.default.errors} === ${errsCount || 0}`);
  }
}
function iterateKeywords(it, group) {
  const { gen, schema, opts: { useDefaults } } = it;
  if (useDefaults)
    (0, defaults_1.assignDefaults)(it, group.type);
  gen.block(() => {
    for (const rule of group.rules) {
      if ((0, applicability_1.shouldUseRule)(schema, rule)) {
        keywordCode(it, rule.keyword, rule.definition, group.type);
      }
    }
  });
}
function checkStrictTypes(it, types2) {
  if (it.schemaEnv.meta || !it.opts.strictTypes)
    return;
  checkContextTypes(it, types2);
  if (!it.opts.allowUnionTypes)
    checkMultipleTypes(it, types2);
  checkKeywordTypes(it, it.dataTypes);
}
function checkContextTypes(it, types2) {
  if (!types2.length)
    return;
  if (!it.dataTypes.length) {
    it.dataTypes = types2;
    return;
  }
  types2.forEach((t) => {
    if (!includesType(it.dataTypes, t)) {
      strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`);
    }
  });
  narrowSchemaTypes(it, types2);
}
function checkMultipleTypes(it, ts) {
  if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
    strictTypesError(it, "use allowUnionTypes to allow union type keyword");
  }
}
function checkKeywordTypes(it, ts) {
  const rules2 = it.self.RULES.all;
  for (const keyword2 in rules2) {
    const rule = rules2[keyword2];
    if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
      const { type: type2 } = rule.definition;
      if (type2.length && !type2.some((t) => hasApplicableType(ts, t))) {
        strictTypesError(it, `missing type "${type2.join(",")}" for keyword "${keyword2}"`);
      }
    }
  }
}
function hasApplicableType(schTs, kwdT) {
  return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
}
function includesType(ts, t) {
  return ts.includes(t) || t === "integer" && ts.includes("number");
}
function narrowSchemaTypes(it, withTypes) {
  const ts = [];
  for (const t of it.dataTypes) {
    if (includesType(withTypes, t))
      ts.push(t);
    else if (withTypes.includes("integer") && t === "number")
      ts.push("integer");
  }
  it.dataTypes = ts;
}
function strictTypesError(it, msg) {
  const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
  msg += ` at "${schemaPath}" (strictTypes)`;
  (0, util_1$l.checkStrictMode)(it, msg, it.opts.strictTypes);
}
class KeywordCxt {
  constructor(it, def2, keyword2) {
    (0, keyword_1.validateKeywordUsage)(it, def2, keyword2);
    this.gen = it.gen;
    this.allErrors = it.allErrors;
    this.keyword = keyword2;
    this.data = it.data;
    this.schema = it.schema[keyword2];
    this.$data = def2.$data && it.opts.$data && this.schema && this.schema.$data;
    this.schemaValue = (0, util_1$l.schemaRefOrVal)(it, this.schema, keyword2, this.$data);
    this.schemaType = def2.schemaType;
    this.parentSchema = it.schema;
    this.params = {};
    this.it = it;
    this.def = def2;
    if (this.$data) {
      this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
    } else {
      this.schemaCode = this.schemaValue;
      if (!(0, keyword_1.validSchemaType)(this.schema, def2.schemaType, def2.allowUndefined)) {
        throw new Error(`${keyword2} value must be ${JSON.stringify(def2.schemaType)}`);
      }
    }
    if ("code" in def2 ? def2.trackErrors : def2.errors !== false) {
      this.errsCount = it.gen.const("_errs", names_1$3.default.errors);
    }
  }
  result(condition, successAction, failAction) {
    this.failResult((0, codegen_1$n.not)(condition), successAction, failAction);
  }
  failResult(condition, successAction, failAction) {
    this.gen.if(condition);
    if (failAction)
      failAction();
    else
      this.error();
    if (successAction) {
      this.gen.else();
      successAction();
      if (this.allErrors)
        this.gen.endIf();
    } else {
      if (this.allErrors)
        this.gen.endIf();
      else
        this.gen.else();
    }
  }
  pass(condition, failAction) {
    this.failResult((0, codegen_1$n.not)(condition), void 0, failAction);
  }
  fail(condition) {
    if (condition === void 0) {
      this.error();
      if (!this.allErrors)
        this.gen.if(false);
      return;
    }
    this.gen.if(condition);
    this.error();
    if (this.allErrors)
      this.gen.endIf();
    else
      this.gen.else();
  }
  fail$data(condition) {
    if (!this.$data)
      return this.fail(condition);
    const { schemaCode } = this;
    this.fail((0, codegen_1$n._)`${schemaCode} !== undefined && (${(0, codegen_1$n.or)(this.invalid$data(), condition)})`);
  }
  error(append, errorParams, errorPaths) {
    if (errorParams) {
      this.setParams(errorParams);
      this._error(append, errorPaths);
      this.setParams({});
      return;
    }
    this._error(append, errorPaths);
  }
  _error(append, errorPaths) {
    (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
  }
  $dataError() {
    (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
  }
  reset() {
    if (this.errsCount === void 0)
      throw new Error('add "trackErrors" to keyword definition');
    (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
  }
  ok(cond) {
    if (!this.allErrors)
      this.gen.if(cond);
  }
  setParams(obj, assign) {
    if (assign)
      Object.assign(this.params, obj);
    else
      this.params = obj;
  }
  block$data(valid, codeBlock, $dataValid = codegen_1$n.nil) {
    this.gen.block(() => {
      this.check$data(valid, $dataValid);
      codeBlock();
    });
  }
  check$data(valid = codegen_1$n.nil, $dataValid = codegen_1$n.nil) {
    if (!this.$data)
      return;
    const { gen, schemaCode, schemaType, def: def2 } = this;
    gen.if((0, codegen_1$n.or)((0, codegen_1$n._)`${schemaCode} === undefined`, $dataValid));
    if (valid !== codegen_1$n.nil)
      gen.assign(valid, true);
    if (schemaType.length || def2.validateSchema) {
      gen.elseIf(this.invalid$data());
      this.$dataError();
      if (valid !== codegen_1$n.nil)
        gen.assign(valid, false);
    }
    gen.else();
  }
  invalid$data() {
    const { gen, schemaCode, schemaType, def: def2, it } = this;
    return (0, codegen_1$n.or)(wrong$DataType(), invalid$DataSchema());
    function wrong$DataType() {
      if (schemaType.length) {
        if (!(schemaCode instanceof codegen_1$n.Name))
          throw new Error("ajv implementation error");
        const st = Array.isArray(schemaType) ? schemaType : [schemaType];
        return (0, codegen_1$n._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
      }
      return codegen_1$n.nil;
    }
    function invalid$DataSchema() {
      if (def2.validateSchema) {
        const validateSchemaRef = gen.scopeValue("validate$data", { ref: def2.validateSchema });
        return (0, codegen_1$n._)`!${validateSchemaRef}(${schemaCode})`;
      }
      return codegen_1$n.nil;
    }
  }
  subschema(appl, valid) {
    const subschema2 = (0, subschema_1.getSubschema)(this.it, appl);
    (0, subschema_1.extendSubschemaData)(subschema2, this.it, appl);
    (0, subschema_1.extendSubschemaMode)(subschema2, appl);
    const nextContext = { ...this.it, ...subschema2, items: void 0, props: void 0 };
    subschemaCode(nextContext, valid);
    return nextContext;
  }
  mergeEvaluated(schemaCxt, toName) {
    const { it, gen } = this;
    if (!it.opts.unevaluated)
      return;
    if (it.props !== true && schemaCxt.props !== void 0) {
      it.props = util_1$l.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
    }
    if (it.items !== true && schemaCxt.items !== void 0) {
      it.items = util_1$l.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
    }
  }
  mergeValidEvaluated(schemaCxt, valid) {
    const { it, gen } = this;
    if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
      gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1$n.Name));
      return true;
    }
  }
}
validate.KeywordCxt = KeywordCxt;
function keywordCode(it, keyword2, def2, ruleType) {
  const cxt = new KeywordCxt(it, def2, keyword2);
  if ("code" in def2) {
    def2.code(cxt, ruleType);
  } else if (cxt.$data && def2.validate) {
    (0, keyword_1.funcKeywordCode)(cxt, def2);
  } else if ("macro" in def2) {
    (0, keyword_1.macroKeywordCode)(cxt, def2);
  } else if (def2.compile || def2.validate) {
    (0, keyword_1.funcKeywordCode)(cxt, def2);
  }
}
const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, { dataLevel, dataNames, dataPathArr }) {
  let jsonPointer;
  let data;
  if ($data === "")
    return names_1$3.default.rootData;
  if ($data[0] === "/") {
    if (!JSON_POINTER.test($data))
      throw new Error(`Invalid JSON-pointer: ${$data}`);
    jsonPointer = $data;
    data = names_1$3.default.rootData;
  } else {
    const matches = RELATIVE_JSON_POINTER.exec($data);
    if (!matches)
      throw new Error(`Invalid JSON-pointer: ${$data}`);
    const up = +matches[1];
    jsonPointer = matches[2];
    if (jsonPointer === "#") {
      if (up >= dataLevel)
        throw new Error(errorMsg("property/index", up));
      return dataPathArr[dataLevel - up];
    }
    if (up > dataLevel)
      throw new Error(errorMsg("data", up));
    data = dataNames[dataLevel - up];
    if (!jsonPointer)
      return data;
  }
  let expr = data;
  const segments = jsonPointer.split("/");
  for (const segment of segments) {
    if (segment) {
      data = (0, codegen_1$n._)`${data}${(0, codegen_1$n.getProperty)((0, util_1$l.unescapeJsonPointer)(segment))}`;
      expr = (0, codegen_1$n._)`${expr} && ${data}`;
    }
  }
  return expr;
  function errorMsg(pointerType, up) {
    return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
  }
}
validate.getData = getData;
var validation_error = {};
Object.defineProperty(validation_error, "__esModule", { value: true });
class ValidationError extends Error {
  constructor(errors2) {
    super("validation failed");
    this.errors = errors2;
    this.ajv = this.validation = true;
  }
}
validation_error.default = ValidationError;
var ref_error = {};
Object.defineProperty(ref_error, "__esModule", { value: true });
const resolve_1$1 = resolve$1;
class MissingRefError extends Error {
  constructor(resolver, baseId, ref2, msg) {
    super(msg || `can't resolve reference ${ref2} from id ${baseId}`);
    this.missingRef = (0, resolve_1$1.resolveUrl)(resolver, baseId, ref2);
    this.missingSchema = (0, resolve_1$1.normalizeId)((0, resolve_1$1.getFullPath)(resolver, this.missingRef));
  }
}
ref_error.default = MissingRefError;
var compile = {};
Object.defineProperty(compile, "__esModule", { value: true });
compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = void 0;
const codegen_1$m = codegen;
const validation_error_1 = validation_error;
const names_1$2 = names$1;
const resolve_1 = resolve$1;
const util_1$k = util;
const validate_1$1 = validate;
class SchemaEnv {
  constructor(env) {
    var _a;
    this.refs = {};
    this.dynamicAnchors = {};
    let schema;
    if (typeof env.schema == "object")
      schema = env.schema;
    this.schema = env.schema;
    this.schemaId = env.schemaId;
    this.root = env.root || this;
    this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
    this.schemaPath = env.schemaPath;
    this.localRefs = env.localRefs;
    this.meta = env.meta;
    this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
    this.refs = {};
  }
}
compile.SchemaEnv = SchemaEnv;
function compileSchema(sch) {
  const _sch = getCompilingSchema.call(this, sch);
  if (_sch)
    return _sch;
  const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
  const { es5, lines } = this.opts.code;
  const { ownProperties } = this.opts;
  const gen = new codegen_1$m.CodeGen(this.scope, { es5, lines, ownProperties });
  let _ValidationError;
  if (sch.$async) {
    _ValidationError = gen.scopeValue("Error", {
      ref: validation_error_1.default,
      code: (0, codegen_1$m._)`require("ajv/dist/runtime/validation_error").default`
    });
  }
  const validateName2 = gen.scopeName("validate");
  sch.validateName = validateName2;
  const schemaCxt = {
    gen,
    allErrors: this.opts.allErrors,
    data: names_1$2.default.data,
    parentData: names_1$2.default.parentData,
    parentDataProperty: names_1$2.default.parentDataProperty,
    dataNames: [names_1$2.default.data],
    dataPathArr: [codegen_1$m.nil],
    // TODO can its length be used as dataLevel if nil is removed?
    dataLevel: 0,
    dataTypes: [],
    definedProperties: /* @__PURE__ */ new Set(),
    topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1$m.stringify)(sch.schema) } : { ref: sch.schema }),
    validateName: validateName2,
    ValidationError: _ValidationError,
    schema: sch.schema,
    schemaEnv: sch,
    rootId,
    baseId: sch.baseId || rootId,
    schemaPath: codegen_1$m.nil,
    errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
    errorPath: (0, codegen_1$m._)`""`,
    opts: this.opts,
    self: this
  };
  let sourceCode;
  try {
    this._compilations.add(sch);
    (0, validate_1$1.validateFunctionCode)(schemaCxt);
    gen.optimize(this.opts.code.optimize);
    const validateCode = gen.toString();
    sourceCode = `${gen.scopeRefs(names_1$2.default.scope)}return ${validateCode}`;
    if (this.opts.code.process)
      sourceCode = this.opts.code.process(sourceCode, sch);
    const makeValidate = new Function(`${names_1$2.default.self}`, `${names_1$2.default.scope}`, sourceCode);
    const validate2 = makeValidate(this, this.scope.get());
    this.scope.value(validateName2, { ref: validate2 });
    validate2.errors = null;
    validate2.schema = sch.schema;
    validate2.schemaEnv = sch;
    if (sch.$async)
      validate2.$async = true;
    if (this.opts.code.source === true) {
      validate2.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
    }
    if (this.opts.unevaluated) {
      const { props, items: items2 } = schemaCxt;
      validate2.evaluated = {
        props: props instanceof codegen_1$m.Name ? void 0 : props,
        items: items2 instanceof codegen_1$m.Name ? void 0 : items2,
        dynamicProps: props instanceof codegen_1$m.Name,
        dynamicItems: items2 instanceof codegen_1$m.Name
      };
      if (validate2.source)
        validate2.source.evaluated = (0, codegen_1$m.stringify)(validate2.evaluated);
    }
    sch.validate = validate2;
    return sch;
  } catch (e) {
    delete sch.validate;
    delete sch.validateName;
    if (sourceCode)
      this.logger.error("Error compiling schema, function code:", sourceCode);
    throw e;
  } finally {
    this._compilations.delete(sch);
  }
}
compile.compileSchema = compileSchema;
function resolveRef(root, baseId, ref2) {
  var _a;
  ref2 = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref2);
  const schOrFunc = root.refs[ref2];
  if (schOrFunc)
    return schOrFunc;
  let _sch = resolve.call(this, root, ref2);
  if (_sch === void 0) {
    const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref2];
    const { schemaId } = this.opts;
    if (schema)
      _sch = new SchemaEnv({ schema, schemaId, root, baseId });
  }
  if (_sch === void 0)
    return;
  return root.refs[ref2] = inlineOrCompile.call(this, _sch);
}
compile.resolveRef = resolveRef;
function inlineOrCompile(sch) {
  if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
    return sch.schema;
  return sch.validate ? sch : compileSchema.call(this, sch);
}
function getCompilingSchema(schEnv) {
  for (const sch of this._compilations) {
    if (sameSchemaEnv(sch, schEnv))
      return sch;
  }
}
compile.getCompilingSchema = getCompilingSchema;
function sameSchemaEnv(s1, s2) {
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
}
function resolve(root, ref2) {
  let sch;
  while (typeof (sch = this.refs[ref2]) == "string")
    ref2 = sch;
  return sch || this.schemas[ref2] || resolveSchema.call(this, root, ref2);
}
function resolveSchema(root, ref2) {
  const p = this.opts.uriResolver.parse(ref2);
  const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
  let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
  if (Object.keys(root.schema).length > 0 && refPath === baseId) {
    return getJsonPointer.call(this, p, root);
  }
  const id2 = (0, resolve_1.normalizeId)(refPath);
  const schOrRef = this.refs[id2] || this.schemas[id2];
  if (typeof schOrRef == "string") {
    const sch = resolveSchema.call(this, root, schOrRef);
    if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
      return;
    return getJsonPointer.call(this, p, sch);
  }
  if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
    return;
  if (!schOrRef.validate)
    compileSchema.call(this, schOrRef);
  if (id2 === (0, resolve_1.normalizeId)(ref2)) {
    const { schema } = schOrRef;
    const { schemaId } = this.opts;
    const schId = schema[schemaId];
    if (schId)
      baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
    return new SchemaEnv({ schema, schemaId, root, baseId });
  }
  return getJsonPointer.call(this, p, schOrRef);
}
compile.resolveSchema = resolveSchema;
const PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
  "properties",
  "patternProperties",
  "enum",
  "dependencies",
  "definitions"
]);
function getJsonPointer(parsedRef, { baseId, schema, root }) {
  var _a;
  if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/")
    return;
  for (const part of parsedRef.fragment.slice(1).split("/")) {
    if (typeof schema === "boolean")
      return;
    const partSchema = schema[(0, util_1$k.unescapeFragment)(part)];
    if (partSchema === void 0)
      return;
    schema = partSchema;
    const schId = typeof schema === "object" && schema[this.opts.schemaId];
    if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
      baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
    }
  }
  let env;
  if (typeof schema != "boolean" && schema.$ref && !(0, util_1$k.schemaHasRulesButRef)(schema, this.RULES)) {
    const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
    env = resolveSchema.call(this, root, $ref);
  }
  const { schemaId } = this.opts;
  env = env || new SchemaEnv({ schema, schemaId, root, baseId });
  if (env.schema !== env.root.schema)
    return env;
  return void 0;
}
const $id$E = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
const description$g = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
const type$F = "object";
const required$e = [
  "$data"
];
const properties$y = {
  $data: {
    type: "string",
    anyOf: [
      {
        format: "relative-json-pointer"
      },
      {
        format: "json-pointer"
      }
    ]
  }
};
const additionalProperties$f = false;
const require$$9$1 = {
  $id: $id$E,
  description: description$g,
  type: type$F,
  required: required$e,
  properties: properties$y,
  additionalProperties: additionalProperties$f
};
var uri$1 = {};
var uri_all = { exports: {} };
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
(function(module2, exports2) {
  (function(global2, factory) {
    factory(exports2);
  })(commonjsGlobal, function(exports3) {
    function merge() {
      for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
        sets[_key] = arguments[_key];
      }
      if (sets.length > 1) {
        sets[0] = sets[0].slice(0, -1);
        var xl = sets.length - 1;
        for (var x = 1; x < xl; ++x) {
          sets[x] = sets[x].slice(1, -1);
        }
        sets[xl] = sets[xl].slice(1);
        return sets.join("");
      } else {
        return sets[0];
      }
    }
    function subexp(str) {
      return "(?:" + str + ")";
    }
    function typeOf(o) {
      return o === void 0 ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
    }
    function toUpperCase(str) {
      return str.toUpperCase();
    }
    function toArray(obj) {
      return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
    }
    function assign(target, source) {
      var obj = target;
      if (source) {
        for (var key in source) {
          obj[key] = source[key];
        }
      }
      return obj;
    }
    function buildExps(isIRI) {
      var ALPHA$$ = "[A-Za-z]", DIGIT$$ = "[0-9]", HEXDIG$$2 = merge(DIGIT$$, "[A-Fa-f]"), PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$);
      subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*");
      subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*");
      var DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$2 + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$2 + "|" + PCT_ENCODED$2) + "+");
      subexp("[vV]" + HEXDIG$$2 + "+\\." + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+");
      subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$)) + "*");
      var PCHAR$ = subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]"));
      subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\@]")) + "+");
      subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*");
      return {
        NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
        NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
        NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
        ESCAPE: new RegExp(merge("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
        UNRESERVED: new RegExp(UNRESERVED$$2, "g"),
        OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"),
        PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"),
        IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
        IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$")
        //RFC 6874, with relaxed parsing rules
      };
    }
    var URI_PROTOCOL = buildExps(false);
    var IRI_PROTOCOL = buildExps(true);
    var slicedToArray = function() {
      function sliceIterator(arr, i) {
        var _arr = [];
        var _n = true;
        var _d = false;
        var _e = void 0;
        try {
          for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
            _arr.push(_s.value);
            if (i && _arr.length === i)
              break;
          }
        } catch (err) {
          _d = true;
          _e = err;
        } finally {
          try {
            if (!_n && _i["return"])
              _i["return"]();
          } finally {
            if (_d)
              throw _e;
          }
        }
        return _arr;
      }
      return function(arr, i) {
        if (Array.isArray(arr)) {
          return arr;
        } else if (Symbol.iterator in Object(arr)) {
          return sliceIterator(arr, i);
        } else {
          throw new TypeError("Invalid attempt to destructure non-iterable instance");
        }
      };
    }();
    var toConsumableArray = function(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++)
          arr2[i] = arr[i];
        return arr2;
      } else {
        return Array.from(arr);
      }
    };
    var maxInt = 2147483647;
    var base = 36;
    var tMin = 1;
    var tMax = 26;
    var skew = 38;
    var damp = 700;
    var initialBias = 72;
    var initialN = 128;
    var delimiter = "-";
    var regexPunycode = /^xn--/;
    var regexNonASCII = /[^\0-\x7E]/;
    var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
    var errors2 = {
      "overflow": "Overflow: input needs wider integers to process",
      "not-basic": "Illegal input >= 0x80 (not a basic code point)",
      "invalid-input": "Invalid input"
    };
    var baseMinusTMin = base - tMin;
    var floor = Math.floor;
    var stringFromCharCode = String.fromCharCode;
    function error$12(type2) {
      throw new RangeError(errors2[type2]);
    }
    function map(array, fn) {
      var result = [];
      var length = array.length;
      while (length--) {
        result[length] = fn(array[length]);
      }
      return result;
    }
    function mapDomain(string, fn) {
      var parts = string.split("@");
      var result = "";
      if (parts.length > 1) {
        result = parts[0] + "@";
        string = parts[1];
      }
      string = string.replace(regexSeparators, ".");
      var labels = string.split(".");
      var encoded = map(labels, fn).join(".");
      return result + encoded;
    }
    function ucs2decode(string) {
      var output = [];
      var counter = 0;
      var length = string.length;
      while (counter < length) {
        var value = string.charCodeAt(counter++);
        if (value >= 55296 && value <= 56319 && counter < length) {
          var extra = string.charCodeAt(counter++);
          if ((extra & 64512) == 56320) {
            output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
          } else {
            output.push(value);
            counter--;
          }
        } else {
          output.push(value);
        }
      }
      return output;
    }
    var ucs2encode = function ucs2encode2(array) {
      return String.fromCodePoint.apply(String, toConsumableArray(array));
    };
    var basicToDigit = function basicToDigit2(codePoint) {
      if (codePoint - 48 < 10) {
        return codePoint - 22;
      }
      if (codePoint - 65 < 26) {
        return codePoint - 65;
      }
      if (codePoint - 97 < 26) {
        return codePoint - 97;
      }
      return base;
    };
    var digitToBasic = function digitToBasic2(digit, flag) {
      return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
    };
    var adapt = function adapt2(delta, numPoints, firstTime) {
      var k = 0;
      delta = firstTime ? floor(delta / damp) : delta >> 1;
      delta += floor(delta / numPoints);
      for (
        ;
        /* no initialization */
        delta > baseMinusTMin * tMax >> 1;
        k += base
      ) {
        delta = floor(delta / baseMinusTMin);
      }
      return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
    };
    var decode = function decode2(input) {
      var output = [];
      var inputLength = input.length;
      var i = 0;
      var n = initialN;
      var bias = initialBias;
      var basic = input.lastIndexOf(delimiter);
      if (basic < 0) {
        basic = 0;
      }
      for (var j = 0; j < basic; ++j) {
        if (input.charCodeAt(j) >= 128) {
          error$12("not-basic");
        }
        output.push(input.charCodeAt(j));
      }
      for (var index = basic > 0 ? basic + 1 : 0; index < inputLength; ) {
        var oldi = i;
        for (
          var w = 1, k = base;
          ;
          /* no condition */
          k += base
        ) {
          if (index >= inputLength) {
            error$12("invalid-input");
          }
          var digit = basicToDigit(input.charCodeAt(index++));
          if (digit >= base || digit > floor((maxInt - i) / w)) {
            error$12("overflow");
          }
          i += digit * w;
          var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
          if (digit < t) {
            break;
          }
          var baseMinusT = base - t;
          if (w > floor(maxInt / baseMinusT)) {
            error$12("overflow");
          }
          w *= baseMinusT;
        }
        var out = output.length + 1;
        bias = adapt(i - oldi, out, oldi == 0);
        if (floor(i / out) > maxInt - n) {
          error$12("overflow");
        }
        n += floor(i / out);
        i %= out;
        output.splice(i++, 0, n);
      }
      return String.fromCodePoint.apply(String, output);
    };
    var encode = function encode2(input) {
      var output = [];
      input = ucs2decode(input);
      var inputLength = input.length;
      var n = initialN;
      var delta = 0;
      var bias = initialBias;
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = void 0;
      try {
        for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var _currentValue2 = _step.value;
          if (_currentValue2 < 128) {
            output.push(stringFromCharCode(_currentValue2));
          }
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
      var basicLength = output.length;
      var handledCPCount = basicLength;
      if (basicLength) {
        output.push(delimiter);
      }
      while (handledCPCount < inputLength) {
        var m = maxInt;
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = void 0;
        try {
          for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var currentValue = _step2.value;
            if (currentValue >= n && currentValue < m) {
              m = currentValue;
            }
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2.return) {
              _iterator2.return();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }
        var handledCPCountPlusOne = handledCPCount + 1;
        if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
          error$12("overflow");
        }
        delta += (m - n) * handledCPCountPlusOne;
        n = m;
        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = void 0;
        try {
          for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
            var _currentValue = _step3.value;
            if (_currentValue < n && ++delta > maxInt) {
              error$12("overflow");
            }
            if (_currentValue == n) {
              var q = delta;
              for (
                var k = base;
                ;
                /* no condition */
                k += base
              ) {
                var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
                if (q < t) {
                  break;
                }
                var qMinusT = q - t;
                var baseMinusT = base - t;
                output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
                q = floor(qMinusT / baseMinusT);
              }
              output.push(stringFromCharCode(digitToBasic(q, 0)));
              bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
              delta = 0;
              ++handledCPCount;
            }
          }
        } catch (err) {
          _didIteratorError3 = true;
          _iteratorError3 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion3 && _iterator3.return) {
              _iterator3.return();
            }
          } finally {
            if (_didIteratorError3) {
              throw _iteratorError3;
            }
          }
        }
        ++delta;
        ++n;
      }
      return output.join("");
    };
    var toUnicode = function toUnicode2(input) {
      return mapDomain(input, function(string) {
        return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
      });
    };
    var toASCII = function toASCII2(input) {
      return mapDomain(input, function(string) {
        return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
      });
    };
    var punycode = {
      /**
       * A string representing the current Punycode.js version number.
       * @memberOf punycode
       * @type String
       */
      "version": "2.1.0",
      /**
       * An object of methods to convert from JavaScript's internal character
       * representation (UCS-2) to Unicode code points, and back.
       * @see <https://mathiasbynens.be/notes/javascript-encoding>
       * @memberOf punycode
       * @type Object
       */
      "ucs2": {
        "decode": ucs2decode,
        "encode": ucs2encode
      },
      "decode": decode,
      "encode": encode,
      "toASCII": toASCII,
      "toUnicode": toUnicode
    };
    var SCHEMES = {};
    function pctEncChar(chr) {
      var c = chr.charCodeAt(0);
      var e = void 0;
      if (c < 16)
        e = "%0" + c.toString(16).toUpperCase();
      else if (c < 128)
        e = "%" + c.toString(16).toUpperCase();
      else if (c < 2048)
        e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
      else
        e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
      return e;
    }
    function pctDecChars(str) {
      var newStr = "";
      var i = 0;
      var il = str.length;
      while (i < il) {
        var c = parseInt(str.substr(i + 1, 2), 16);
        if (c < 128) {
          newStr += String.fromCharCode(c);
          i += 3;
        } else if (c >= 194 && c < 224) {
          if (il - i >= 6) {
            var c2 = parseInt(str.substr(i + 4, 2), 16);
            newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
          } else {
            newStr += str.substr(i, 6);
          }
          i += 6;
        } else if (c >= 224) {
          if (il - i >= 9) {
            var _c = parseInt(str.substr(i + 4, 2), 16);
            var c3 = parseInt(str.substr(i + 7, 2), 16);
            newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
          } else {
            newStr += str.substr(i, 9);
          }
          i += 9;
        } else {
          newStr += str.substr(i, 3);
          i += 3;
        }
      }
      return newStr;
    }
    function _normalizeComponentEncoding(components, protocol) {
      function decodeUnreserved2(str) {
        var decStr = pctDecChars(str);
        return !decStr.match(protocol.UNRESERVED) ? str : decStr;
      }
      if (components.scheme)
        components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, "");
      if (components.userinfo !== void 0)
        components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.host !== void 0)
        components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.path !== void 0)
        components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.query !== void 0)
        components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      if (components.fragment !== void 0)
        components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
      return components;
    }
    function _stripLeadingZeros(str) {
      return str.replace(/^0*(.*)/, "$1") || "0";
    }
    function _normalizeIPv4(host, protocol) {
      var matches = host.match(protocol.IPV4ADDRESS) || [];
      var _matches = slicedToArray(matches, 2), address = _matches[1];
      if (address) {
        return address.split(".").map(_stripLeadingZeros).join(".");
      } else {
        return host;
      }
    }
    function _normalizeIPv6(host, protocol) {
      var matches = host.match(protocol.IPV6ADDRESS) || [];
      var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2];
      if (address) {
        var _address$toLowerCase$ = address.toLowerCase().split("::").reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last = _address$toLowerCase$2[0], first = _address$toLowerCase$2[1];
        var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
        var lastFields = last.split(":").map(_stripLeadingZeros);
        var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
        var fieldCount = isLastFieldIPv4Address ? 7 : 8;
        var lastFieldsStart = lastFields.length - fieldCount;
        var fields = Array(fieldCount);
        for (var x = 0; x < fieldCount; ++x) {
          fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || "";
        }
        if (isLastFieldIPv4Address) {
          fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
        }
        var allZeroFields = fields.reduce(function(acc, field, index) {
          if (!field || field === "0") {
            var lastLongest = acc[acc.length - 1];
            if (lastLongest && lastLongest.index + lastLongest.length === index) {
              lastLongest.length++;
            } else {
              acc.push({ index, length: 1 });
            }
          }
          return acc;
        }, []);
        var longestZeroFields = allZeroFields.sort(function(a, b) {
          return b.length - a.length;
        })[0];
        var newHost = void 0;
        if (longestZeroFields && longestZeroFields.length > 1) {
          var newFirst = fields.slice(0, longestZeroFields.index);
          var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
          newHost = newFirst.join(":") + "::" + newLast.join(":");
        } else {
          newHost = fields.join(":");
        }
        if (zone) {
          newHost += "%" + zone;
        }
        return newHost;
      } else {
        return host;
      }
    }
    var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
    var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0;
    function parse2(uriString) {
      var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var components = {};
      var protocol = options2.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
      if (options2.reference === "suffix")
        uriString = (options2.scheme ? options2.scheme + ":" : "") + "//" + uriString;
      var matches = uriString.match(URI_PARSE);
      if (matches) {
        if (NO_MATCH_IS_UNDEFINED) {
          components.scheme = matches[1];
          components.userinfo = matches[3];
          components.host = matches[4];
          components.port = parseInt(matches[5], 10);
          components.path = matches[6] || "";
          components.query = matches[7];
          components.fragment = matches[8];
          if (isNaN(components.port)) {
            components.port = matches[5];
          }
        } else {
          components.scheme = matches[1] || void 0;
          components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : void 0;
          components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0;
          components.port = parseInt(matches[5], 10);
          components.path = matches[6] || "";
          components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0;
          components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : void 0;
          if (isNaN(components.port)) {
            components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0;
          }
        }
        if (components.host) {
          components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
        }
        if (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) {
          components.reference = "same-document";
        } else if (components.scheme === void 0) {
          components.reference = "relative";
        } else if (components.fragment === void 0) {
          components.reference = "absolute";
        } else {
          components.reference = "uri";
        }
        if (options2.reference && options2.reference !== "suffix" && options2.reference !== components.reference) {
          components.error = components.error || "URI is not a " + options2.reference + " reference.";
        }
        var schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
        if (!options2.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (components.host && (options2.domainHost || schemeHandler && schemeHandler.domainHost)) {
            try {
              components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
            } catch (e) {
              components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
            }
          }
          _normalizeComponentEncoding(components, URI_PROTOCOL);
        } else {
          _normalizeComponentEncoding(components, protocol);
        }
        if (schemeHandler && schemeHandler.parse) {
          schemeHandler.parse(components, options2);
        }
      } else {
        components.error = components.error || "URI can not be parsed.";
      }
      return components;
    }
    function _recomposeAuthority(components, options2) {
      var protocol = options2.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
      var uriTokens = [];
      if (components.userinfo !== void 0) {
        uriTokens.push(components.userinfo);
        uriTokens.push("@");
      }
      if (components.host !== void 0) {
        uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_, $1, $2) {
          return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
        }));
      }
      if (typeof components.port === "number" || typeof components.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(components.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    var RDS1 = /^\.\.?\//;
    var RDS2 = /^\/\.(\/|$)/;
    var RDS3 = /^\/\.\.(\/|$)/;
    var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
    function removeDotSegments(input) {
      var output = [];
      while (input.length) {
        if (input.match(RDS1)) {
          input = input.replace(RDS1, "");
        } else if (input.match(RDS2)) {
          input = input.replace(RDS2, "/");
        } else if (input.match(RDS3)) {
          input = input.replace(RDS3, "/");
          output.pop();
        } else if (input === "." || input === "..") {
          input = "";
        } else {
          var im = input.match(RDS5);
          if (im) {
            var s = im[0];
            input = input.slice(s.length);
            output.push(s);
          } else {
            throw new Error("Unexpected dot segment condition");
          }
        }
      }
      return output.join("");
    }
    function serialize(components) {
      var options2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      var protocol = options2.iri ? IRI_PROTOCOL : URI_PROTOCOL;
      var uriTokens = [];
      var schemeHandler = SCHEMES[(options2.scheme || components.scheme || "").toLowerCase()];
      if (schemeHandler && schemeHandler.serialize)
        schemeHandler.serialize(components, options2);
      if (components.host) {
        if (protocol.IPV6ADDRESS.test(components.host))
          ;
        else if (options2.domainHost || schemeHandler && schemeHandler.domainHost) {
          try {
            components.host = !options2.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
          } catch (e) {
            components.error = components.error || "Host's domain name can not be converted to " + (!options2.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
          }
        }
      }
      _normalizeComponentEncoding(components, protocol);
      if (options2.reference !== "suffix" && components.scheme) {
        uriTokens.push(components.scheme);
        uriTokens.push(":");
      }
      var authority = _recomposeAuthority(components, options2);
      if (authority !== void 0) {
        if (options2.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (components.path && components.path.charAt(0) !== "/") {
          uriTokens.push("/");
        }
      }
      if (components.path !== void 0) {
        var s = components.path;
        if (!options2.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s = removeDotSegments(s);
        }
        if (authority === void 0) {
          s = s.replace(/^\/\//, "/%2F");
        }
        uriTokens.push(s);
      }
      if (components.query !== void 0) {
        uriTokens.push("?");
        uriTokens.push(components.query);
      }
      if (components.fragment !== void 0) {
        uriTokens.push("#");
        uriTokens.push(components.fragment);
      }
      return uriTokens.join("");
    }
    function resolveComponents(base2, relative) {
      var options2 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      var skipNormalization = arguments[3];
      var target = {};
      if (!skipNormalization) {
        base2 = parse2(serialize(base2, options2), options2);
        relative = parse2(serialize(relative, options2), options2);
      }
      options2 = options2 || {};
      if (!options2.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
      } else {
        if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
          target.userinfo = relative.userinfo;
          target.host = relative.host;
          target.port = relative.port;
          target.path = removeDotSegments(relative.path || "");
          target.query = relative.query;
        } else {
          if (!relative.path) {
            target.path = base2.path;
            if (relative.query !== void 0) {
              target.query = relative.query;
            } else {
              target.query = base2.query;
            }
          } else {
            if (relative.path.charAt(0) === "/") {
              target.path = removeDotSegments(relative.path);
            } else {
              if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) {
                target.path = "/" + relative.path;
              } else if (!base2.path) {
                target.path = relative.path;
              } else {
                target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative.query;
          }
          target.userinfo = base2.userinfo;
          target.host = base2.host;
          target.port = base2.port;
        }
        target.scheme = base2.scheme;
      }
      target.fragment = relative.fragment;
      return target;
    }
    function resolve2(baseURI, relativeURI, options2) {
      var schemelessOptions = assign({ scheme: "null" }, options2);
      return serialize(resolveComponents(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
    }
    function normalize(uri2, options2) {
      if (typeof uri2 === "string") {
        uri2 = serialize(parse2(uri2, options2), options2);
      } else if (typeOf(uri2) === "object") {
        uri2 = parse2(serialize(uri2, options2), options2);
      }
      return uri2;
    }
    function equal3(uriA, uriB, options2) {
      if (typeof uriA === "string") {
        uriA = serialize(parse2(uriA, options2), options2);
      } else if (typeOf(uriA) === "object") {
        uriA = serialize(uriA, options2);
      }
      if (typeof uriB === "string") {
        uriB = serialize(parse2(uriB, options2), options2);
      } else if (typeOf(uriB) === "object") {
        uriB = serialize(uriB, options2);
      }
      return uriA === uriB;
    }
    function escapeComponent(str, options2) {
      return str && str.toString().replace(!options2 || !options2.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
    }
    function unescapeComponent(str, options2) {
      return str && str.toString().replace(!options2 || !options2.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
    }
    var handler = {
      scheme: "http",
      domainHost: true,
      parse: function parse3(components, options2) {
        if (!components.host) {
          components.error = components.error || "HTTP URIs must have a host.";
        }
        return components;
      },
      serialize: function serialize2(components, options2) {
        var secure = String(components.scheme).toLowerCase() === "https";
        if (components.port === (secure ? 443 : 80) || components.port === "") {
          components.port = void 0;
        }
        if (!components.path) {
          components.path = "/";
        }
        return components;
      }
    };
    var handler$1 = {
      scheme: "https",
      domainHost: handler.domainHost,
      parse: handler.parse,
      serialize: handler.serialize
    };
    function isSecure(wsComponents) {
      return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
    }
    var handler$2 = {
      scheme: "ws",
      domainHost: true,
      parse: function parse3(components, options2) {
        var wsComponents = components;
        wsComponents.secure = isSecure(wsComponents);
        wsComponents.resourceName = (wsComponents.path || "/") + (wsComponents.query ? "?" + wsComponents.query : "");
        wsComponents.path = void 0;
        wsComponents.query = void 0;
        return wsComponents;
      },
      serialize: function serialize2(wsComponents, options2) {
        if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
          wsComponents.port = void 0;
        }
        if (typeof wsComponents.secure === "boolean") {
          wsComponents.scheme = wsComponents.secure ? "wss" : "ws";
          wsComponents.secure = void 0;
        }
        if (wsComponents.resourceName) {
          var _wsComponents$resourc = wsComponents.resourceName.split("?"), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
          wsComponents.path = path && path !== "/" ? path : void 0;
          wsComponents.query = query;
          wsComponents.resourceName = void 0;
        }
        wsComponents.fragment = void 0;
        return wsComponents;
      }
    };
    var handler$3 = {
      scheme: "wss",
      domainHost: handler$2.domainHost,
      parse: handler$2.parse,
      serialize: handler$2.serialize
    };
    var O = {};
    var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]";
    var HEXDIG$$ = "[0-9A-Fa-f]";
    var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$));
    var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
    var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
    var VCHAR$$ = merge(QTEXT$$, '[\\"\\\\]');
    var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
    var UNRESERVED = new RegExp(UNRESERVED$$, "g");
    var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
    var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
    var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
    var NOT_HFVALUE = NOT_HFNAME;
    function decodeUnreserved(str) {
      var decStr = pctDecChars(str);
      return !decStr.match(UNRESERVED) ? str : decStr;
    }
    var handler$4 = {
      scheme: "mailto",
      parse: function parse$$1(components, options2) {
        var mailtoComponents = components;
        var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
        mailtoComponents.path = void 0;
        if (mailtoComponents.query) {
          var unknownHeaders = false;
          var headers = {};
          var hfields = mailtoComponents.query.split("&");
          for (var x = 0, xl = hfields.length; x < xl; ++x) {
            var hfield = hfields[x].split("=");
            switch (hfield[0]) {
              case "to":
                var toAddrs = hfield[1].split(",");
                for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
                  to.push(toAddrs[_x]);
                }
                break;
              case "subject":
                mailtoComponents.subject = unescapeComponent(hfield[1], options2);
                break;
              case "body":
                mailtoComponents.body = unescapeComponent(hfield[1], options2);
                break;
              default:
                unknownHeaders = true;
                headers[unescapeComponent(hfield[0], options2)] = unescapeComponent(hfield[1], options2);
                break;
            }
          }
          if (unknownHeaders)
            mailtoComponents.headers = headers;
        }
        mailtoComponents.query = void 0;
        for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
          var addr = to[_x2].split("@");
          addr[0] = unescapeComponent(addr[0]);
          if (!options2.unicodeSupport) {
            try {
              addr[1] = punycode.toASCII(unescapeComponent(addr[1], options2).toLowerCase());
            } catch (e) {
              mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
            }
          } else {
            addr[1] = unescapeComponent(addr[1], options2).toLowerCase();
          }
          to[_x2] = addr.join("@");
        }
        return mailtoComponents;
      },
      serialize: function serialize$$1(mailtoComponents, options2) {
        var components = mailtoComponents;
        var to = toArray(mailtoComponents.to);
        if (to) {
          for (var x = 0, xl = to.length; x < xl; ++x) {
            var toAddr = String(to[x]);
            var atIdx = toAddr.lastIndexOf("@");
            var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
            var domain = toAddr.slice(atIdx + 1);
            try {
              domain = !options2.iri ? punycode.toASCII(unescapeComponent(domain, options2).toLowerCase()) : punycode.toUnicode(domain);
            } catch (e) {
              components.error = components.error || "Email address's domain name can not be converted to " + (!options2.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
            }
            to[x] = localPart + "@" + domain;
          }
          components.path = to.join(",");
        }
        var headers = mailtoComponents.headers = mailtoComponents.headers || {};
        if (mailtoComponents.subject)
          headers["subject"] = mailtoComponents.subject;
        if (mailtoComponents.body)
          headers["body"] = mailtoComponents.body;
        var fields = [];
        for (var name2 in headers) {
          if (headers[name2] !== O[name2]) {
            fields.push(name2.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name2].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
          }
        }
        if (fields.length) {
          components.query = fields.join("&");
        }
        return components;
      }
    };
    var URN_PARSE = /^([^\:]+)\:(.*)/;
    var handler$5 = {
      scheme: "urn",
      parse: function parse$$1(components, options2) {
        var matches = components.path && components.path.match(URN_PARSE);
        var urnComponents = components;
        if (matches) {
          var scheme = options2.scheme || urnComponents.scheme || "urn";
          var nid = matches[1].toLowerCase();
          var nss = matches[2];
          var urnScheme = scheme + ":" + (options2.nid || nid);
          var schemeHandler = SCHEMES[urnScheme];
          urnComponents.nid = nid;
          urnComponents.nss = nss;
          urnComponents.path = void 0;
          if (schemeHandler) {
            urnComponents = schemeHandler.parse(urnComponents, options2);
          }
        } else {
          urnComponents.error = urnComponents.error || "URN can not be parsed.";
        }
        return urnComponents;
      },
      serialize: function serialize$$1(urnComponents, options2) {
        var scheme = options2.scheme || urnComponents.scheme || "urn";
        var nid = urnComponents.nid;
        var urnScheme = scheme + ":" + (options2.nid || nid);
        var schemeHandler = SCHEMES[urnScheme];
        if (schemeHandler) {
          urnComponents = schemeHandler.serialize(urnComponents, options2);
        }
        var uriComponents = urnComponents;
        var nss = urnComponents.nss;
        uriComponents.path = (nid || options2.nid) + ":" + nss;
        return uriComponents;
      }
    };
    var UUID2 = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
    var handler$6 = {
      scheme: "urn:uuid",
      parse: function parse3(urnComponents, options2) {
        var uuidComponents = urnComponents;
        uuidComponents.uuid = uuidComponents.nss;
        uuidComponents.nss = void 0;
        if (!options2.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID2))) {
          uuidComponents.error = uuidComponents.error || "UUID is not valid.";
        }
        return uuidComponents;
      },
      serialize: function serialize2(uuidComponents, options2) {
        var urnComponents = uuidComponents;
        urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
        return urnComponents;
      }
    };
    SCHEMES[handler.scheme] = handler;
    SCHEMES[handler$1.scheme] = handler$1;
    SCHEMES[handler$2.scheme] = handler$2;
    SCHEMES[handler$3.scheme] = handler$3;
    SCHEMES[handler$4.scheme] = handler$4;
    SCHEMES[handler$5.scheme] = handler$5;
    SCHEMES[handler$6.scheme] = handler$6;
    exports3.SCHEMES = SCHEMES;
    exports3.pctEncChar = pctEncChar;
    exports3.pctDecChars = pctDecChars;
    exports3.parse = parse2;
    exports3.removeDotSegments = removeDotSegments;
    exports3.serialize = serialize;
    exports3.resolveComponents = resolveComponents;
    exports3.resolve = resolve2;
    exports3.normalize = normalize;
    exports3.equal = equal3;
    exports3.escapeComponent = escapeComponent;
    exports3.unescapeComponent = unescapeComponent;
    Object.defineProperty(exports3, "__esModule", { value: true });
  });
})(uri_all, uri_all.exports);
var uri_allExports = uri_all.exports;
Object.defineProperty(uri$1, "__esModule", { value: true });
const uri = uri_allExports;
uri.code = 'require("ajv/dist/runtime/uri").default';
uri$1.default = uri;
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = void 0;
  var validate_12 = validate;
  Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() {
    return validate_12.KeywordCxt;
  } });
  var codegen_12 = codegen;
  Object.defineProperty(exports2, "_", { enumerable: true, get: function() {
    return codegen_12._;
  } });
  Object.defineProperty(exports2, "str", { enumerable: true, get: function() {
    return codegen_12.str;
  } });
  Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
    return codegen_12.stringify;
  } });
  Object.defineProperty(exports2, "nil", { enumerable: true, get: function() {
    return codegen_12.nil;
  } });
  Object.defineProperty(exports2, "Name", { enumerable: true, get: function() {
    return codegen_12.Name;
  } });
  Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() {
    return codegen_12.CodeGen;
  } });
  const validation_error_12 = validation_error;
  const ref_error_12 = ref_error;
  const rules_12 = rules;
  const compile_12 = compile;
  const codegen_2 = codegen;
  const resolve_12 = resolve$1;
  const dataType_12 = dataType;
  const util_12 = util;
  const $dataRefSchema = require$$9$1;
  const uri_1 = uri$1;
  const defaultRegExp = (str, flags) => new RegExp(str, flags);
  defaultRegExp.code = "new RegExp";
  const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
  const EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
    "validate",
    "serialize",
    "parse",
    "wrapper",
    "root",
    "schema",
    "keyword",
    "pattern",
    "formats",
    "validate$data",
    "func",
    "obj",
    "Error"
  ]);
  const removedOptions = {
    errorDataPath: "",
    format: "`validateFormats: false` can be used instead.",
    nullable: '"nullable" keyword is supported by default.',
    jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
    extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
    missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
    processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
    sourceCode: "Use option `code: {source: true}`",
    strictDefaults: "It is default now, see option `strict`.",
    strictKeywords: "It is default now, see option `strict`.",
    uniqueItems: '"uniqueItems" keyword is always validated.',
    unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
    cache: "Map is used as cache, schema object as key.",
    serialize: "Map is used as cache, schema object as key.",
    ajvErrors: "It is default now."
  };
  const deprecatedOptions = {
    ignoreKeywordsWithRef: "",
    jsPropertySyntax: "",
    unicode: '"minLength"/"maxLength" account for unicode characters by default.'
  };
  const MAX_EXPRESSION = 200;
  function requiredOptions(o) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
    const s = o.strict;
    const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize;
    const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
    const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
    const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
    return {
      strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
      strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
      strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
      strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
      strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
      code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
      loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
      loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
      meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
      messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
      inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
      schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
      addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
      validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
      validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
      unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
      int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
      uriResolver
    };
  }
  class Ajv2 {
    constructor(opts = {}) {
      this.schemas = {};
      this.refs = {};
      this.formats = {};
      this._compilations = /* @__PURE__ */ new Set();
      this._loading = {};
      this._cache = /* @__PURE__ */ new Map();
      opts = this.opts = { ...opts, ...requiredOptions(opts) };
      const { es5, lines } = this.opts.code;
      this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
      this.logger = getLogger(opts.logger);
      const formatOpt = opts.validateFormats;
      opts.validateFormats = false;
      this.RULES = (0, rules_12.getRules)();
      checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
      checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
      this._metaOpts = getMetaSchemaOptions.call(this);
      if (opts.formats)
        addInitialFormats.call(this);
      this._addVocabularies();
      this._addDefaultMetaSchema();
      if (opts.keywords)
        addInitialKeywords.call(this, opts.keywords);
      if (typeof opts.meta == "object")
        this.addMetaSchema(opts.meta);
      addInitialSchemas.call(this);
      opts.validateFormats = formatOpt;
    }
    _addVocabularies() {
      this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
      const { $data, meta, schemaId } = this.opts;
      let _dataRefSchema = $dataRefSchema;
      if (schemaId === "id") {
        _dataRefSchema = { ...$dataRefSchema };
        _dataRefSchema.id = _dataRefSchema.$id;
        delete _dataRefSchema.$id;
      }
      if (meta && $data)
        this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
    }
    defaultMeta() {
      const { meta, schemaId } = this.opts;
      return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
    }
    validate(schemaKeyRef, data) {
      let v;
      if (typeof schemaKeyRef == "string") {
        v = this.getSchema(schemaKeyRef);
        if (!v)
          throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
      } else {
        v = this.compile(schemaKeyRef);
      }
      const valid = v(data);
      if (!("$async" in v))
        this.errors = v.errors;
      return valid;
    }
    compile(schema, _meta) {
      const sch = this._addSchema(schema, _meta);
      return sch.validate || this._compileSchemaEnv(sch);
    }
    compileAsync(schema, meta) {
      if (typeof this.opts.loadSchema != "function") {
        throw new Error("options.loadSchema should be a function");
      }
      const { loadSchema } = this.opts;
      return runCompileAsync.call(this, schema, meta);
      async function runCompileAsync(_schema, _meta) {
        await loadMetaSchema.call(this, _schema.$schema);
        const sch = this._addSchema(_schema, _meta);
        return sch.validate || _compileAsync.call(this, sch);
      }
      async function loadMetaSchema($ref) {
        if ($ref && !this.getSchema($ref)) {
          await runCompileAsync.call(this, { $ref }, true);
        }
      }
      async function _compileAsync(sch) {
        try {
          return this._compileSchemaEnv(sch);
        } catch (e) {
          if (!(e instanceof ref_error_12.default))
            throw e;
          checkLoaded.call(this, e);
          await loadMissingSchema.call(this, e.missingSchema);
          return _compileAsync.call(this, sch);
        }
      }
      function checkLoaded({ missingSchema: ref2, missingRef }) {
        if (this.refs[ref2]) {
          throw new Error(`AnySchema ${ref2} is loaded but ${missingRef} cannot be resolved`);
        }
      }
      async function loadMissingSchema(ref2) {
        const _schema = await _loadSchema.call(this, ref2);
        if (!this.refs[ref2])
          await loadMetaSchema.call(this, _schema.$schema);
        if (!this.refs[ref2])
          this.addSchema(_schema, ref2, meta);
      }
      async function _loadSchema(ref2) {
        const p = this._loading[ref2];
        if (p)
          return p;
        try {
          return await (this._loading[ref2] = loadSchema(ref2));
        } finally {
          delete this._loading[ref2];
        }
      }
    }
    // Adds schema to the instance
    addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
      if (Array.isArray(schema)) {
        for (const sch of schema)
          this.addSchema(sch, void 0, _meta, _validateSchema);
        return this;
      }
      let id2;
      if (typeof schema === "object") {
        const { schemaId } = this.opts;
        id2 = schema[schemaId];
        if (id2 !== void 0 && typeof id2 != "string") {
          throw new Error(`schema ${schemaId} must be string`);
        }
      }
      key = (0, resolve_12.normalizeId)(key || id2);
      this._checkUnique(key);
      this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
      return this;
    }
    // Add schema that will be used to validate other schemas
    // options in META_IGNORE_OPTIONS are alway set to false
    addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
      this.addSchema(schema, key, true, _validateSchema);
      return this;
    }
    //  Validate schema against its meta-schema
    validateSchema(schema, throwOrLogError) {
      if (typeof schema == "boolean")
        return true;
      let $schema2;
      $schema2 = schema.$schema;
      if ($schema2 !== void 0 && typeof $schema2 != "string") {
        throw new Error("$schema must be a string");
      }
      $schema2 = $schema2 || this.opts.defaultMeta || this.defaultMeta();
      if (!$schema2) {
        this.logger.warn("meta-schema not available");
        this.errors = null;
        return true;
      }
      const valid = this.validate($schema2, schema);
      if (!valid && throwOrLogError) {
        const message = "schema is invalid: " + this.errorsText();
        if (this.opts.validateSchema === "log")
          this.logger.error(message);
        else
          throw new Error(message);
      }
      return valid;
    }
    // Get compiled schema by `key` or `ref`.
    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
    getSchema(keyRef) {
      let sch;
      while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
        keyRef = sch;
      if (sch === void 0) {
        const { schemaId } = this.opts;
        const root = new compile_12.SchemaEnv({ schema: {}, schemaId });
        sch = compile_12.resolveSchema.call(this, root, keyRef);
        if (!sch)
          return;
        this.refs[keyRef] = sch;
      }
      return sch.validate || this._compileSchemaEnv(sch);
    }
    // Remove cached schema(s).
    // If no parameter is passed all schemas but meta-schemas are removed.
    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
    removeSchema(schemaKeyRef) {
      if (schemaKeyRef instanceof RegExp) {
        this._removeAllSchemas(this.schemas, schemaKeyRef);
        this._removeAllSchemas(this.refs, schemaKeyRef);
        return this;
      }
      switch (typeof schemaKeyRef) {
        case "undefined":
          this._removeAllSchemas(this.schemas);
          this._removeAllSchemas(this.refs);
          this._cache.clear();
          return this;
        case "string": {
          const sch = getSchEnv.call(this, schemaKeyRef);
          if (typeof sch == "object")
            this._cache.delete(sch.schema);
          delete this.schemas[schemaKeyRef];
          delete this.refs[schemaKeyRef];
          return this;
        }
        case "object": {
          const cacheKey = schemaKeyRef;
          this._cache.delete(cacheKey);
          let id2 = schemaKeyRef[this.opts.schemaId];
          if (id2) {
            id2 = (0, resolve_12.normalizeId)(id2);
            delete this.schemas[id2];
            delete this.refs[id2];
          }
          return this;
        }
        default:
          throw new Error("ajv.removeSchema: invalid parameter");
      }
    }
    // add "vocabulary" - a collection of keywords
    addVocabulary(definitions2) {
      for (const def2 of definitions2)
        this.addKeyword(def2);
      return this;
    }
    addKeyword(kwdOrDef, def2) {
      let keyword2;
      if (typeof kwdOrDef == "string") {
        keyword2 = kwdOrDef;
        if (typeof def2 == "object") {
          this.logger.warn("these parameters are deprecated, see docs for addKeyword");
          def2.keyword = keyword2;
        }
      } else if (typeof kwdOrDef == "object" && def2 === void 0) {
        def2 = kwdOrDef;
        keyword2 = def2.keyword;
        if (Array.isArray(keyword2) && !keyword2.length) {
          throw new Error("addKeywords: keyword must be string or non-empty array");
        }
      } else {
        throw new Error("invalid addKeywords parameters");
      }
      checkKeyword.call(this, keyword2, def2);
      if (!def2) {
        (0, util_12.eachItem)(keyword2, (kwd) => addRule.call(this, kwd));
        return this;
      }
      keywordMetaschema.call(this, def2);
      const definition = {
        ...def2,
        type: (0, dataType_12.getJSONTypes)(def2.type),
        schemaType: (0, dataType_12.getJSONTypes)(def2.schemaType)
      };
      (0, util_12.eachItem)(keyword2, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
      return this;
    }
    getKeyword(keyword2) {
      const rule = this.RULES.all[keyword2];
      return typeof rule == "object" ? rule.definition : !!rule;
    }
    // Remove keyword
    removeKeyword(keyword2) {
      const { RULES } = this;
      delete RULES.keywords[keyword2];
      delete RULES.all[keyword2];
      for (const group of RULES.rules) {
        const i = group.rules.findIndex((rule) => rule.keyword === keyword2);
        if (i >= 0)
          group.rules.splice(i, 1);
      }
      return this;
    }
    // Add format
    addFormat(name2, format2) {
      if (typeof format2 == "string")
        format2 = new RegExp(format2);
      this.formats[name2] = format2;
      return this;
    }
    errorsText(errors2 = this.errors, { separator = ", ", dataVar = "data" } = {}) {
      if (!errors2 || errors2.length === 0)
        return "No errors";
      return errors2.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
    }
    $dataMetaSchema(metaSchema, keywordsJsonPointers) {
      const rules2 = this.RULES.all;
      metaSchema = JSON.parse(JSON.stringify(metaSchema));
      for (const jsonPointer of keywordsJsonPointers) {
        const segments = jsonPointer.split("/").slice(1);
        let keywords2 = metaSchema;
        for (const seg of segments)
          keywords2 = keywords2[seg];
        for (const key in rules2) {
          const rule = rules2[key];
          if (typeof rule != "object")
            continue;
          const { $data } = rule.definition;
          const schema = keywords2[key];
          if ($data && schema)
            keywords2[key] = schemaOrData(schema);
        }
      }
      return metaSchema;
    }
    _removeAllSchemas(schemas, regex) {
      for (const keyRef in schemas) {
        const sch = schemas[keyRef];
        if (!regex || regex.test(keyRef)) {
          if (typeof sch == "string") {
            delete schemas[keyRef];
          } else if (sch && !sch.meta) {
            this._cache.delete(sch.schema);
            delete schemas[keyRef];
          }
        }
      }
    }
    _addSchema(schema, meta, baseId, validateSchema2 = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
      let id2;
      const { schemaId } = this.opts;
      if (typeof schema == "object") {
        id2 = schema[schemaId];
      } else {
        if (this.opts.jtd)
          throw new Error("schema must be object");
        else if (typeof schema != "boolean")
          throw new Error("schema must be object or boolean");
      }
      let sch = this._cache.get(schema);
      if (sch !== void 0)
        return sch;
      baseId = (0, resolve_12.normalizeId)(id2 || baseId);
      const localRefs = resolve_12.getSchemaRefs.call(this, schema, baseId);
      sch = new compile_12.SchemaEnv({ schema, schemaId, meta, baseId, localRefs });
      this._cache.set(sch.schema, sch);
      if (addSchema && !baseId.startsWith("#")) {
        if (baseId)
          this._checkUnique(baseId);
        this.refs[baseId] = sch;
      }
      if (validateSchema2)
        this.validateSchema(schema, true);
      return sch;
    }
    _checkUnique(id2) {
      if (this.schemas[id2] || this.refs[id2]) {
        throw new Error(`schema with key or id "${id2}" already exists`);
      }
    }
    _compileSchemaEnv(sch) {
      if (sch.meta)
        this._compileMetaSchema(sch);
      else
        compile_12.compileSchema.call(this, sch);
      if (!sch.validate)
        throw new Error("ajv implementation error");
      return sch.validate;
    }
    _compileMetaSchema(sch) {
      const currentOpts = this.opts;
      this.opts = this._metaOpts;
      try {
        compile_12.compileSchema.call(this, sch);
      } finally {
        this.opts = currentOpts;
      }
    }
  }
  Ajv2.ValidationError = validation_error_12.default;
  Ajv2.MissingRefError = ref_error_12.default;
  exports2.default = Ajv2;
  function checkOptions(checkOpts, options2, msg, log = "error") {
    for (const key in checkOpts) {
      const opt = key;
      if (opt in options2)
        this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
    }
  }
  function getSchEnv(keyRef) {
    keyRef = (0, resolve_12.normalizeId)(keyRef);
    return this.schemas[keyRef] || this.refs[keyRef];
  }
  function addInitialSchemas() {
    const optsSchemas = this.opts.schemas;
    if (!optsSchemas)
      return;
    if (Array.isArray(optsSchemas))
      this.addSchema(optsSchemas);
    else
      for (const key in optsSchemas)
        this.addSchema(optsSchemas[key], key);
  }
  function addInitialFormats() {
    for (const name2 in this.opts.formats) {
      const format2 = this.opts.formats[name2];
      if (format2)
        this.addFormat(name2, format2);
    }
  }
  function addInitialKeywords(defs) {
    if (Array.isArray(defs)) {
      this.addVocabulary(defs);
      return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (const keyword2 in defs) {
      const def2 = defs[keyword2];
      if (!def2.keyword)
        def2.keyword = keyword2;
      this.addKeyword(def2);
    }
  }
  function getMetaSchemaOptions() {
    const metaOpts = { ...this.opts };
    for (const opt of META_IGNORE_OPTIONS)
      delete metaOpts[opt];
    return metaOpts;
  }
  const noLogs = { log() {
  }, warn() {
  }, error() {
  } };
  function getLogger(logger) {
    if (logger === false)
      return noLogs;
    if (logger === void 0)
      return console;
    if (logger.log && logger.warn && logger.error)
      return logger;
    throw new Error("logger must implement log, warn and error methods");
  }
  const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
  function checkKeyword(keyword2, def2) {
    const { RULES } = this;
    (0, util_12.eachItem)(keyword2, (kwd) => {
      if (RULES.keywords[kwd])
        throw new Error(`Keyword ${kwd} is already defined`);
      if (!KEYWORD_NAME.test(kwd))
        throw new Error(`Keyword ${kwd} has invalid name`);
    });
    if (!def2)
      return;
    if (def2.$data && !("code" in def2 || "validate" in def2)) {
      throw new Error('$data keyword must have "code" or "validate" function');
    }
  }
  function addRule(keyword2, definition, dataType2) {
    var _a;
    const post = definition === null || definition === void 0 ? void 0 : definition.post;
    if (dataType2 && post)
      throw new Error('keyword with "post" flag cannot have "type"');
    const { RULES } = this;
    let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType2);
    if (!ruleGroup) {
      ruleGroup = { type: dataType2, rules: [] };
      RULES.rules.push(ruleGroup);
    }
    RULES.keywords[keyword2] = true;
    if (!definition)
      return;
    const rule = {
      keyword: keyword2,
      definition: {
        ...definition,
        type: (0, dataType_12.getJSONTypes)(definition.type),
        schemaType: (0, dataType_12.getJSONTypes)(definition.schemaType)
      }
    };
    if (definition.before)
      addBeforeRule.call(this, ruleGroup, rule, definition.before);
    else
      ruleGroup.rules.push(rule);
    RULES.all[keyword2] = rule;
    (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd));
  }
  function addBeforeRule(ruleGroup, rule, before) {
    const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
    if (i >= 0) {
      ruleGroup.rules.splice(i, 0, rule);
    } else {
      ruleGroup.rules.push(rule);
      this.logger.warn(`rule ${before} is not defined`);
    }
  }
  function keywordMetaschema(def2) {
    let { metaSchema } = def2;
    if (metaSchema === void 0)
      return;
    if (def2.$data && this.opts.$data)
      metaSchema = schemaOrData(metaSchema);
    def2.validateSchema = this.compile(metaSchema, true);
  }
  const $dataRef = {
    $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
  };
  function schemaOrData(schema) {
    return { anyOf: [schema, $dataRef] };
  }
})(core$2);
var draft7 = {};
var core$1 = {};
var id = {};
Object.defineProperty(id, "__esModule", { value: true });
const def$s = {
  keyword: "id",
  code() {
    throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
  }
};
id.default = def$s;
var ref = {};
Object.defineProperty(ref, "__esModule", { value: true });
ref.callRef = ref.getValidate = void 0;
const ref_error_1 = ref_error;
const code_1$8 = code;
const codegen_1$l = codegen;
const names_1$1 = names$1;
const compile_1$1 = compile;
const util_1$j = util;
const def$r = {
  keyword: "$ref",
  schemaType: "string",
  code(cxt) {
    const { gen, schema: $ref, it } = cxt;
    const { baseId, schemaEnv: env, validateName: validateName2, opts, self: self2 } = it;
    const { root } = env;
    if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
      return callRootRef();
    const schOrEnv = compile_1$1.resolveRef.call(self2, root, baseId, $ref);
    if (schOrEnv === void 0)
      throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
    if (schOrEnv instanceof compile_1$1.SchemaEnv)
      return callValidate(schOrEnv);
    return inlineRefSchema(schOrEnv);
    function callRootRef() {
      if (env === root)
        return callRef(cxt, validateName2, env, env.$async);
      const rootName = gen.scopeValue("root", { ref: root });
      return callRef(cxt, (0, codegen_1$l._)`${rootName}.validate`, root, root.$async);
    }
    function callValidate(sch) {
      const v = getValidate(cxt, sch);
      callRef(cxt, v, sch, sch.$async);
    }
    function inlineRefSchema(sch) {
      const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1$l.stringify)(sch) } : { ref: sch });
      const valid = gen.name("valid");
      const schCxt = cxt.subschema({
        schema: sch,
        dataTypes: [],
        schemaPath: codegen_1$l.nil,
        topSchemaRef: schName,
        errSchemaPath: $ref
      }, valid);
      cxt.mergeEvaluated(schCxt);
      cxt.ok(valid);
    }
  }
};
function getValidate(cxt, sch) {
  const { gen } = cxt;
  return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1$l._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
}
ref.getValidate = getValidate;
function callRef(cxt, v, sch, $async) {
  const { gen, it } = cxt;
  const { allErrors, schemaEnv: env, opts } = it;
  const passCxt = opts.passContext ? names_1$1.default.this : codegen_1$l.nil;
  if ($async)
    callAsyncRef();
  else
    callSyncRef();
  function callAsyncRef() {
    if (!env.$async)
      throw new Error("async schema referenced by sync schema");
    const valid = gen.let("valid");
    gen.try(() => {
      gen.code((0, codegen_1$l._)`await ${(0, code_1$8.callValidateCode)(cxt, v, passCxt)}`);
      addEvaluatedFrom(v);
      if (!allErrors)
        gen.assign(valid, true);
    }, (e) => {
      gen.if((0, codegen_1$l._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
      addErrorsFrom(e);
      if (!allErrors)
        gen.assign(valid, false);
    });
    cxt.ok(valid);
  }
  function callSyncRef() {
    cxt.result((0, code_1$8.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
  }
  function addErrorsFrom(source) {
    const errs = (0, codegen_1$l._)`${source}.errors`;
    gen.assign(names_1$1.default.vErrors, (0, codegen_1$l._)`${names_1$1.default.vErrors} === null ? ${errs} : ${names_1$1.default.vErrors}.concat(${errs})`);
    gen.assign(names_1$1.default.errors, (0, codegen_1$l._)`${names_1$1.default.vErrors}.length`);
  }
  function addEvaluatedFrom(source) {
    var _a;
    if (!it.opts.unevaluated)
      return;
    const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated;
    if (it.props !== true) {
      if (schEvaluated && !schEvaluated.dynamicProps) {
        if (schEvaluated.props !== void 0) {
          it.props = util_1$j.mergeEvaluated.props(gen, schEvaluated.props, it.props);
        }
      } else {
        const props = gen.var("props", (0, codegen_1$l._)`${source}.evaluated.props`);
        it.props = util_1$j.mergeEvaluated.props(gen, props, it.props, codegen_1$l.Name);
      }
    }
    if (it.items !== true) {
      if (schEvaluated && !schEvaluated.dynamicItems) {
        if (schEvaluated.items !== void 0) {
          it.items = util_1$j.mergeEvaluated.items(gen, schEvaluated.items, it.items);
        }
      } else {
        const items2 = gen.var("items", (0, codegen_1$l._)`${source}.evaluated.items`);
        it.items = util_1$j.mergeEvaluated.items(gen, items2, it.items, codegen_1$l.Name);
      }
    }
  }
}
ref.callRef = callRef;
ref.default = def$r;
Object.defineProperty(core$1, "__esModule", { value: true });
const id_1 = id;
const ref_1 = ref;
const core = [
  "$schema",
  "$id",
  "$defs",
  "$vocabulary",
  { keyword: "$comment" },
  "definitions",
  id_1.default,
  ref_1.default
];
core$1.default = core;
var validation$1 = {};
var limitNumber = {};
Object.defineProperty(limitNumber, "__esModule", { value: true });
const codegen_1$k = codegen;
const ops = codegen_1$k.operators;
const KWDs = {
  maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
  minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
  exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
  exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
};
const error$i = {
  message: ({ keyword: keyword2, schemaCode }) => (0, codegen_1$k.str)`must be ${KWDs[keyword2].okStr} ${schemaCode}`,
  params: ({ keyword: keyword2, schemaCode }) => (0, codegen_1$k._)`{comparison: ${KWDs[keyword2].okStr}, limit: ${schemaCode}}`
};
const def$q = {
  keyword: Object.keys(KWDs),
  type: "number",
  schemaType: "number",
  $data: true,
  error: error$i,
  code(cxt) {
    const { keyword: keyword2, data, schemaCode } = cxt;
    cxt.fail$data((0, codegen_1$k._)`${data} ${KWDs[keyword2].fail} ${schemaCode} || isNaN(${data})`);
  }
};
limitNumber.default = def$q;
var multipleOf = {};
Object.defineProperty(multipleOf, "__esModule", { value: true });
const codegen_1$j = codegen;
const error$h = {
  message: ({ schemaCode }) => (0, codegen_1$j.str)`must be multiple of ${schemaCode}`,
  params: ({ schemaCode }) => (0, codegen_1$j._)`{multipleOf: ${schemaCode}}`
};
const def$p = {
  keyword: "multipleOf",
  type: "number",
  schemaType: "number",
  $data: true,
  error: error$h,
  code(cxt) {
    const { gen, data, schemaCode, it } = cxt;
    const prec = it.opts.multipleOfPrecision;
    const res = gen.let("res");
    const invalid = prec ? (0, codegen_1$j._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1$j._)`${res} !== parseInt(${res})`;
    cxt.fail$data((0, codegen_1$j._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
  }
};
multipleOf.default = def$p;
var limitLength = {};
var ucs2length$1 = {};
Object.defineProperty(ucs2length$1, "__esModule", { value: true });
function ucs2length(str) {
  const len = str.length;
  let length = 0;
  let pos = 0;
  let value;
  while (pos < len) {
    length++;
    value = str.charCodeAt(pos++);
    if (value >= 55296 && value <= 56319 && pos < len) {
      value = str.charCodeAt(pos);
      if ((value & 64512) === 56320)
        pos++;
    }
  }
  return length;
}
ucs2length$1.default = ucs2length;
ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
Object.defineProperty(limitLength, "__esModule", { value: true });
const codegen_1$i = codegen;
const util_1$i = util;
const ucs2length_1 = ucs2length$1;
const error$g = {
  message({ keyword: keyword2, schemaCode }) {
    const comp = keyword2 === "maxLength" ? "more" : "fewer";
    return (0, codegen_1$i.str)`must NOT have ${comp} than ${schemaCode} characters`;
  },
  params: ({ schemaCode }) => (0, codegen_1$i._)`{limit: ${schemaCode}}`
};
const def$o = {
  keyword: ["maxLength", "minLength"],
  type: "string",
  schemaType: "number",
  $data: true,
  error: error$g,
  code(cxt) {
    const { keyword: keyword2, data, schemaCode, it } = cxt;
    const op = keyword2 === "maxLength" ? codegen_1$i.operators.GT : codegen_1$i.operators.LT;
    const len = it.opts.unicode === false ? (0, codegen_1$i._)`${data}.length` : (0, codegen_1$i._)`${(0, util_1$i.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
    cxt.fail$data((0, codegen_1$i._)`${len} ${op} ${schemaCode}`);
  }
};
limitLength.default = def$o;
var pattern = {};
Object.defineProperty(pattern, "__esModule", { value: true });
const code_1$7 = code;
const codegen_1$h = codegen;
const error$f = {
  message: ({ schemaCode }) => (0, codegen_1$h.str)`must match pattern "${schemaCode}"`,
  params: ({ schemaCode }) => (0, codegen_1$h._)`{pattern: ${schemaCode}}`
};
const def$n = {
  keyword: "pattern",
  type: "string",
  schemaType: "string",
  $data: true,
  error: error$f,
  code(cxt) {
    const { data, $data, schema, schemaCode, it } = cxt;
    const u = it.opts.unicodeRegExp ? "u" : "";
    const regExp = $data ? (0, codegen_1$h._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1$7.usePattern)(cxt, schema);
    cxt.fail$data((0, codegen_1$h._)`!${regExp}.test(${data})`);
  }
};
pattern.default = def$n;
var limitProperties = {};
Object.defineProperty(limitProperties, "__esModule", { value: true });
const codegen_1$g = codegen;
const error$e = {
  message({ keyword: keyword2, schemaCode }) {
    const comp = keyword2 === "maxProperties" ? "more" : "fewer";
    return (0, codegen_1$g.str)`must NOT have ${comp} than ${schemaCode} properties`;
  },
  params: ({ schemaCode }) => (0, codegen_1$g._)`{limit: ${schemaCode}}`
};
const def$m = {
  keyword: ["maxProperties", "minProperties"],
  type: "object",
  schemaType: "number",
  $data: true,
  error: error$e,
  code(cxt) {
    const { keyword: keyword2, data, schemaCode } = cxt;
    const op = keyword2 === "maxProperties" ? codegen_1$g.operators.GT : codegen_1$g.operators.LT;
    cxt.fail$data((0, codegen_1$g._)`Object.keys(${data}).length ${op} ${schemaCode}`);
  }
};
limitProperties.default = def$m;
var required$d = {};
Object.defineProperty(required$d, "__esModule", { value: true });
const code_1$6 = code;
const codegen_1$f = codegen;
const util_1$h = util;
const error$d = {
  message: ({ params: { missingProperty } }) => (0, codegen_1$f.str)`must have required property '${missingProperty}'`,
  params: ({ params: { missingProperty } }) => (0, codegen_1$f._)`{missingProperty: ${missingProperty}}`
};
const def$l = {
  keyword: "required",
  type: "object",
  schemaType: "array",
  $data: true,
  error: error$d,
  code(cxt) {
    const { gen, schema, schemaCode, data, $data, it } = cxt;
    const { opts } = it;
    if (!$data && schema.length === 0)
      return;
    const useLoop = schema.length >= opts.loopRequired;
    if (it.allErrors)
      allErrorsMode();
    else
      exitOnErrorMode();
    if (opts.strictRequired) {
      const props = cxt.parentSchema.properties;
      const { definedProperties } = cxt.it;
      for (const requiredKey of schema) {
        if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
          const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
          const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
          (0, util_1$h.checkStrictMode)(it, msg, it.opts.strictRequired);
        }
      }
    }
    function allErrorsMode() {
      if (useLoop || $data) {
        cxt.block$data(codegen_1$f.nil, loopAllRequired);
      } else {
        for (const prop of schema) {
          (0, code_1$6.checkReportMissingProp)(cxt, prop);
        }
      }
    }
    function exitOnErrorMode() {
      const missing = gen.let("missing");
      if (useLoop || $data) {
        const valid = gen.let("valid", true);
        cxt.block$data(valid, () => loopUntilMissing(missing, valid));
        cxt.ok(valid);
      } else {
        gen.if((0, code_1$6.checkMissingProp)(cxt, schema, missing));
        (0, code_1$6.reportMissingProp)(cxt, missing);
        gen.else();
      }
    }
    function loopAllRequired() {
      gen.forOf("prop", schemaCode, (prop) => {
        cxt.setParams({ missingProperty: prop });
        gen.if((0, code_1$6.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
      });
    }
    function loopUntilMissing(missing, valid) {
      cxt.setParams({ missingProperty: missing });
      gen.forOf(missing, schemaCode, () => {
        gen.assign(valid, (0, code_1$6.propertyInData)(gen, data, missing, opts.ownProperties));
        gen.if((0, codegen_1$f.not)(valid), () => {
          cxt.error();
          gen.break();
        });
      }, codegen_1$f.nil);
    }
  }
};
required$d.default = def$l;
var limitItems = {};
Object.defineProperty(limitItems, "__esModule", { value: true });
const codegen_1$e = codegen;
const error$c = {
  message({ keyword: keyword2, schemaCode }) {
    const comp = keyword2 === "maxItems" ? "more" : "fewer";
    return (0, codegen_1$e.str)`must NOT have ${comp} than ${schemaCode} items`;
  },
  params: ({ schemaCode }) => (0, codegen_1$e._)`{limit: ${schemaCode}}`
};
const def$k = {
  keyword: ["maxItems", "minItems"],
  type: "array",
  schemaType: "number",
  $data: true,
  error: error$c,
  code(cxt) {
    const { keyword: keyword2, data, schemaCode } = cxt;
    const op = keyword2 === "maxItems" ? codegen_1$e.operators.GT : codegen_1$e.operators.LT;
    cxt.fail$data((0, codegen_1$e._)`${data}.length ${op} ${schemaCode}`);
  }
};
limitItems.default = def$k;
var uniqueItems = {};
var equal$1 = {};
Object.defineProperty(equal$1, "__esModule", { value: true });
const equal2 = fastDeepEqual;
equal2.code = 'require("ajv/dist/runtime/equal").default';
equal$1.default = equal2;
Object.defineProperty(uniqueItems, "__esModule", { value: true });
const dataType_1 = dataType;
const codegen_1$d = codegen;
const util_1$g = util;
const equal_1$2 = equal$1;
const error$b = {
  message: ({ params: { i, j } }) => (0, codegen_1$d.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
  params: ({ params: { i, j } }) => (0, codegen_1$d._)`{i: ${i}, j: ${j}}`
};
const def$j = {
  keyword: "uniqueItems",
  type: "array",
  schemaType: "boolean",
  $data: true,
  error: error$b,
  code(cxt) {
    const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
    if (!$data && !schema)
      return;
    const valid = gen.let("valid");
    const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
    cxt.block$data(valid, validateUniqueItems, (0, codegen_1$d._)`${schemaCode} === false`);
    cxt.ok(valid);
    function validateUniqueItems() {
      const i = gen.let("i", (0, codegen_1$d._)`${data}.length`);
      const j = gen.let("j");
      cxt.setParams({ i, j });
      gen.assign(valid, true);
      gen.if((0, codegen_1$d._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
    }
    function canOptimize() {
      return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
    }
    function loopN(i, j) {
      const item = gen.name("item");
      const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
      const indices = gen.const("indices", (0, codegen_1$d._)`{}`);
      gen.for((0, codegen_1$d._)`;${i}--;`, () => {
        gen.let(item, (0, codegen_1$d._)`${data}[${i}]`);
        gen.if(wrongType, (0, codegen_1$d._)`continue`);
        if (itemTypes.length > 1)
          gen.if((0, codegen_1$d._)`typeof ${item} == "string"`, (0, codegen_1$d._)`${item} += "_"`);
        gen.if((0, codegen_1$d._)`typeof ${indices}[${item}] == "number"`, () => {
          gen.assign(j, (0, codegen_1$d._)`${indices}[${item}]`);
          cxt.error();
          gen.assign(valid, false).break();
        }).code((0, codegen_1$d._)`${indices}[${item}] = ${i}`);
      });
    }
    function loopN2(i, j) {
      const eql = (0, util_1$g.useFunc)(gen, equal_1$2.default);
      const outer = gen.name("outer");
      gen.label(outer).for((0, codegen_1$d._)`;${i}--;`, () => gen.for((0, codegen_1$d._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1$d._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
        cxt.error();
        gen.assign(valid, false).break(outer);
      })));
    }
  }
};
uniqueItems.default = def$j;
var _const = {};
Object.defineProperty(_const, "__esModule", { value: true });
const codegen_1$c = codegen;
const util_1$f = util;
const equal_1$1 = equal$1;
const error$a = {
  message: "must be equal to constant",
  params: ({ schemaCode }) => (0, codegen_1$c._)`{allowedValue: ${schemaCode}}`
};
const def$i = {
  keyword: "const",
  $data: true,
  error: error$a,
  code(cxt) {
    const { gen, data, $data, schemaCode, schema } = cxt;
    if ($data || schema && typeof schema == "object") {
      cxt.fail$data((0, codegen_1$c._)`!${(0, util_1$f.useFunc)(gen, equal_1$1.default)}(${data}, ${schemaCode})`);
    } else {
      cxt.fail((0, codegen_1$c._)`${schema} !== ${data}`);
    }
  }
};
_const.default = def$i;
var _enum = {};
Object.defineProperty(_enum, "__esModule", { value: true });
const codegen_1$b = codegen;
const util_1$e = util;
const equal_1 = equal$1;
const error$9 = {
  message: "must be equal to one of the allowed values",
  params: ({ schemaCode }) => (0, codegen_1$b._)`{allowedValues: ${schemaCode}}`
};
const def$h = {
  keyword: "enum",
  schemaType: "array",
  $data: true,
  error: error$9,
  code(cxt) {
    const { gen, data, $data, schema, schemaCode, it } = cxt;
    if (!$data && schema.length === 0)
      throw new Error("enum must have non-empty array");
    const useLoop = schema.length >= it.opts.loopEnum;
    let eql;
    const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1$e.useFunc)(gen, equal_1.default);
    let valid;
    if (useLoop || $data) {
      valid = gen.let("valid");
      cxt.block$data(valid, loopEnum);
    } else {
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const vSchema = gen.const("vSchema", schemaCode);
      valid = (0, codegen_1$b.or)(...schema.map((_x, i) => equalCode(vSchema, i)));
    }
    cxt.pass(valid);
    function loopEnum() {
      gen.assign(valid, false);
      gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1$b._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
    }
    function equalCode(vSchema, i) {
      const sch = schema[i];
      return typeof sch === "object" && sch !== null ? (0, codegen_1$b._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1$b._)`${data} === ${sch}`;
    }
  }
};
_enum.default = def$h;
Object.defineProperty(validation$1, "__esModule", { value: true });
const limitNumber_1 = limitNumber;
const multipleOf_1 = multipleOf;
const limitLength_1 = limitLength;
const pattern_1 = pattern;
const limitProperties_1 = limitProperties;
const required_1 = required$d;
const limitItems_1 = limitItems;
const uniqueItems_1 = uniqueItems;
const const_1 = _const;
const enum_1 = _enum;
const validation = [
  // number
  limitNumber_1.default,
  multipleOf_1.default,
  // string
  limitLength_1.default,
  pattern_1.default,
  // object
  limitProperties_1.default,
  required_1.default,
  // array
  limitItems_1.default,
  uniqueItems_1.default,
  // any
  { keyword: "type", schemaType: ["string", "array"] },
  { keyword: "nullable", schemaType: "boolean" },
  const_1.default,
  enum_1.default
];
validation$1.default = validation;
var applicator = {};
var additionalItems = {};
Object.defineProperty(additionalItems, "__esModule", { value: true });
additionalItems.validateAdditionalItems = void 0;
const codegen_1$a = codegen;
const util_1$d = util;
const error$8 = {
  message: ({ params: { len } }) => (0, codegen_1$a.str)`must NOT have more than ${len} items`,
  params: ({ params: { len } }) => (0, codegen_1$a._)`{limit: ${len}}`
};
const def$g = {
  keyword: "additionalItems",
  type: "array",
  schemaType: ["boolean", "object"],
  before: "uniqueItems",
  error: error$8,
  code(cxt) {
    const { parentSchema, it } = cxt;
    const { items: items2 } = parentSchema;
    if (!Array.isArray(items2)) {
      (0, util_1$d.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
      return;
    }
    validateAdditionalItems(cxt, items2);
  }
};
function validateAdditionalItems(cxt, items2) {
  const { gen, schema, data, keyword: keyword2, it } = cxt;
  it.items = true;
  const len = gen.const("len", (0, codegen_1$a._)`${data}.length`);
  if (schema === false) {
    cxt.setParams({ len: items2.length });
    cxt.pass((0, codegen_1$a._)`${len} <= ${items2.length}`);
  } else if (typeof schema == "object" && !(0, util_1$d.alwaysValidSchema)(it, schema)) {
    const valid = gen.var("valid", (0, codegen_1$a._)`${len} <= ${items2.length}`);
    gen.if((0, codegen_1$a.not)(valid), () => validateItems(valid));
    cxt.ok(valid);
  }
  function validateItems(valid) {
    gen.forRange("i", items2.length, len, (i) => {
      cxt.subschema({ keyword: keyword2, dataProp: i, dataPropType: util_1$d.Type.Num }, valid);
      if (!it.allErrors)
        gen.if((0, codegen_1$a.not)(valid), () => gen.break());
    });
  }
}
additionalItems.validateAdditionalItems = validateAdditionalItems;
additionalItems.default = def$g;
var prefixItems = {};
var items$2 = {};
Object.defineProperty(items$2, "__esModule", { value: true });
items$2.validateTuple = void 0;
const codegen_1$9 = codegen;
const util_1$c = util;
const code_1$5 = code;
const def$f = {
  keyword: "items",
  type: "array",
  schemaType: ["object", "array", "boolean"],
  before: "uniqueItems",
  code(cxt) {
    const { schema, it } = cxt;
    if (Array.isArray(schema))
      return validateTuple(cxt, "additionalItems", schema);
    it.items = true;
    if ((0, util_1$c.alwaysValidSchema)(it, schema))
      return;
    cxt.ok((0, code_1$5.validateArray)(cxt));
  }
};
function validateTuple(cxt, extraItems, schArr = cxt.schema) {
  const { gen, parentSchema, data, keyword: keyword2, it } = cxt;
  checkStrictTuple(parentSchema);
  if (it.opts.unevaluated && schArr.length && it.items !== true) {
    it.items = util_1$c.mergeEvaluated.items(gen, schArr.length, it.items);
  }
  const valid = gen.name("valid");
  const len = gen.const("len", (0, codegen_1$9._)`${data}.length`);
  schArr.forEach((sch, i) => {
    if ((0, util_1$c.alwaysValidSchema)(it, sch))
      return;
    gen.if((0, codegen_1$9._)`${len} > ${i}`, () => cxt.subschema({
      keyword: keyword2,
      schemaProp: i,
      dataProp: i
    }, valid));
    cxt.ok(valid);
  });
  function checkStrictTuple(sch) {
    const { opts, errSchemaPath } = it;
    const l = schArr.length;
    const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
    if (opts.strictTuples && !fullTuple) {
      const msg = `"${keyword2}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
      (0, util_1$c.checkStrictMode)(it, msg, opts.strictTuples);
    }
  }
}
items$2.validateTuple = validateTuple;
items$2.default = def$f;
Object.defineProperty(prefixItems, "__esModule", { value: true });
const items_1$1 = items$2;
const def$e = {
  keyword: "prefixItems",
  type: "array",
  schemaType: ["array"],
  before: "uniqueItems",
  code: (cxt) => (0, items_1$1.validateTuple)(cxt, "items")
};
prefixItems.default = def$e;
var items2020 = {};
Object.defineProperty(items2020, "__esModule", { value: true });
const codegen_1$8 = codegen;
const util_1$b = util;
const code_1$4 = code;
const additionalItems_1$1 = additionalItems;
const error$7 = {
  message: ({ params: { len } }) => (0, codegen_1$8.str)`must NOT have more than ${len} items`,
  params: ({ params: { len } }) => (0, codegen_1$8._)`{limit: ${len}}`
};
const def$d = {
  keyword: "items",
  type: "array",
  schemaType: ["object", "boolean"],
  before: "uniqueItems",
  error: error$7,
  code(cxt) {
    const { schema, parentSchema, it } = cxt;
    const { prefixItems: prefixItems2 } = parentSchema;
    it.items = true;
    if ((0, util_1$b.alwaysValidSchema)(it, schema))
      return;
    if (prefixItems2)
      (0, additionalItems_1$1.validateAdditionalItems)(cxt, prefixItems2);
    else
      cxt.ok((0, code_1$4.validateArray)(cxt));
  }
};
items2020.default = def$d;
var contains = {};
Object.defineProperty(contains, "__esModule", { value: true });
const codegen_1$7 = codegen;
const util_1$a = util;
const error$6 = {
  message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1$7.str)`must contain at least ${min} valid item(s)` : (0, codegen_1$7.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
  params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1$7._)`{minContains: ${min}}` : (0, codegen_1$7._)`{minContains: ${min}, maxContains: ${max}}`
};
const def$c = {
  keyword: "contains",
  type: "array",
  schemaType: ["object", "boolean"],
  before: "uniqueItems",
  trackErrors: true,
  error: error$6,
  code(cxt) {
    const { gen, schema, parentSchema, data, it } = cxt;
    let min;
    let max;
    const { minContains, maxContains } = parentSchema;
    if (it.opts.next) {
      min = minContains === void 0 ? 1 : minContains;
      max = maxContains;
    } else {
      min = 1;
    }
    const len = gen.const("len", (0, codegen_1$7._)`${data}.length`);
    cxt.setParams({ min, max });
    if (max === void 0 && min === 0) {
      (0, util_1$a.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
      return;
    }
    if (max !== void 0 && min > max) {
      (0, util_1$a.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
      cxt.fail();
      return;
    }
    if ((0, util_1$a.alwaysValidSchema)(it, schema)) {
      let cond = (0, codegen_1$7._)`${len} >= ${min}`;
      if (max !== void 0)
        cond = (0, codegen_1$7._)`${cond} && ${len} <= ${max}`;
      cxt.pass(cond);
      return;
    }
    it.items = true;
    const valid = gen.name("valid");
    if (max === void 0 && min === 1) {
      validateItems(valid, () => gen.if(valid, () => gen.break()));
    } else if (min === 0) {
      gen.let(valid, true);
      if (max !== void 0)
        gen.if((0, codegen_1$7._)`${data}.length > 0`, validateItemsWithCount);
    } else {
      gen.let(valid, false);
      validateItemsWithCount();
    }
    cxt.result(valid, () => cxt.reset());
    function validateItemsWithCount() {
      const schValid = gen.name("_valid");
      const count = gen.let("count", 0);
      validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
    }
    function validateItems(_valid, block2) {
      gen.forRange("i", 0, len, (i) => {
        cxt.subschema({
          keyword: "contains",
          dataProp: i,
          dataPropType: util_1$a.Type.Num,
          compositeRule: true
        }, _valid);
        block2();
      });
    }
    function checkLimits(count) {
      gen.code((0, codegen_1$7._)`${count}++`);
      if (max === void 0) {
        gen.if((0, codegen_1$7._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
      } else {
        gen.if((0, codegen_1$7._)`${count} > ${max}`, () => gen.assign(valid, false).break());
        if (min === 1)
          gen.assign(valid, true);
        else
          gen.if((0, codegen_1$7._)`${count} >= ${min}`, () => gen.assign(valid, true));
      }
    }
  }
};
contains.default = def$c;
var dependencies = {};
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.validateSchemaDeps = exports2.validatePropertyDeps = exports2.error = void 0;
  const codegen_12 = codegen;
  const util_12 = util;
  const code_12 = code;
  exports2.error = {
    message: ({ params: { property, depsCount, deps } }) => {
      const property_ies = depsCount === 1 ? "property" : "properties";
      return (0, codegen_12.str)`must have ${property_ies} ${deps} when property ${property} is present`;
    },
    params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_12._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
    // TODO change to reference
  };
  const def2 = {
    keyword: "dependencies",
    type: "object",
    schemaType: "object",
    error: exports2.error,
    code(cxt) {
      const [propDeps, schDeps] = splitDependencies(cxt);
      validatePropertyDeps(cxt, propDeps);
      validateSchemaDeps(cxt, schDeps);
    }
  };
  function splitDependencies({ schema }) {
    const propertyDeps = {};
    const schemaDeps = {};
    for (const key in schema) {
      if (key === "__proto__")
        continue;
      const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
      deps[key] = schema[key];
    }
    return [propertyDeps, schemaDeps];
  }
  function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
    const { gen, data, it } = cxt;
    if (Object.keys(propertyDeps).length === 0)
      return;
    const missing = gen.let("missing");
    for (const prop in propertyDeps) {
      const deps = propertyDeps[prop];
      if (deps.length === 0)
        continue;
      const hasProperty = (0, code_12.propertyInData)(gen, data, prop, it.opts.ownProperties);
      cxt.setParams({
        property: prop,
        depsCount: deps.length,
        deps: deps.join(", ")
      });
      if (it.allErrors) {
        gen.if(hasProperty, () => {
          for (const depProp of deps) {
            (0, code_12.checkReportMissingProp)(cxt, depProp);
          }
        });
      } else {
        gen.if((0, codegen_12._)`${hasProperty} && (${(0, code_12.checkMissingProp)(cxt, deps, missing)})`);
        (0, code_12.reportMissingProp)(cxt, missing);
        gen.else();
      }
    }
  }
  exports2.validatePropertyDeps = validatePropertyDeps;
  function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
    const { gen, data, keyword: keyword2, it } = cxt;
    const valid = gen.name("valid");
    for (const prop in schemaDeps) {
      if ((0, util_12.alwaysValidSchema)(it, schemaDeps[prop]))
        continue;
      gen.if(
        (0, code_12.propertyInData)(gen, data, prop, it.opts.ownProperties),
        () => {
          const schCxt = cxt.subschema({ keyword: keyword2, schemaProp: prop }, valid);
          cxt.mergeValidEvaluated(schCxt, valid);
        },
        () => gen.var(valid, true)
        // TODO var
      );
      cxt.ok(valid);
    }
  }
  exports2.validateSchemaDeps = validateSchemaDeps;
  exports2.default = def2;
})(dependencies);
var propertyNames = {};
Object.defineProperty(propertyNames, "__esModule", { value: true });
const codegen_1$6 = codegen;
const util_1$9 = util;
const error$5 = {
  message: "property name must be valid",
  params: ({ params }) => (0, codegen_1$6._)`{propertyName: ${params.propertyName}}`
};
const def$b = {
  keyword: "propertyNames",
  type: "object",
  schemaType: ["object", "boolean"],
  error: error$5,
  code(cxt) {
    const { gen, schema, data, it } = cxt;
    if ((0, util_1$9.alwaysValidSchema)(it, schema))
      return;
    const valid = gen.name("valid");
    gen.forIn("key", data, (key) => {
      cxt.setParams({ propertyName: key });
      cxt.subschema({
        keyword: "propertyNames",
        data: key,
        dataTypes: ["string"],
        propertyName: key,
        compositeRule: true
      }, valid);
      gen.if((0, codegen_1$6.not)(valid), () => {
        cxt.error(true);
        if (!it.allErrors)
          gen.break();
      });
    });
    cxt.ok(valid);
  }
};
propertyNames.default = def$b;
var additionalProperties$e = {};
Object.defineProperty(additionalProperties$e, "__esModule", { value: true });
const code_1$3 = code;
const codegen_1$5 = codegen;
const names_1 = names$1;
const util_1$8 = util;
const error$4 = {
  message: "must NOT have additional properties",
  params: ({ params }) => (0, codegen_1$5._)`{additionalProperty: ${params.additionalProperty}}`
};
const def$a = {
  keyword: "additionalProperties",
  type: ["object"],
  schemaType: ["boolean", "object"],
  allowUndefined: true,
  trackErrors: true,
  error: error$4,
  code(cxt) {
    const { gen, schema, parentSchema, data, errsCount, it } = cxt;
    if (!errsCount)
      throw new Error("ajv implementation error");
    const { allErrors, opts } = it;
    it.props = true;
    if (opts.removeAdditional !== "all" && (0, util_1$8.alwaysValidSchema)(it, schema))
      return;
    const props = (0, code_1$3.allSchemaProperties)(parentSchema.properties);
    const patProps = (0, code_1$3.allSchemaProperties)(parentSchema.patternProperties);
    checkAdditionalProperties();
    cxt.ok((0, codegen_1$5._)`${errsCount} === ${names_1.default.errors}`);
    function checkAdditionalProperties() {
      gen.forIn("key", data, (key) => {
        if (!props.length && !patProps.length)
          additionalPropertyCode(key);
        else
          gen.if(isAdditional(key), () => additionalPropertyCode(key));
      });
    }
    function isAdditional(key) {
      let definedProp;
      if (props.length > 8) {
        const propsSchema = (0, util_1$8.schemaRefOrVal)(it, parentSchema.properties, "properties");
        definedProp = (0, code_1$3.isOwnProperty)(gen, propsSchema, key);
      } else if (props.length) {
        definedProp = (0, codegen_1$5.or)(...props.map((p) => (0, codegen_1$5._)`${key} === ${p}`));
      } else {
        definedProp = codegen_1$5.nil;
      }
      if (patProps.length) {
        definedProp = (0, codegen_1$5.or)(definedProp, ...patProps.map((p) => (0, codegen_1$5._)`${(0, code_1$3.usePattern)(cxt, p)}.test(${key})`));
      }
      return (0, codegen_1$5.not)(definedProp);
    }
    function deleteAdditional(key) {
      gen.code((0, codegen_1$5._)`delete ${data}[${key}]`);
    }
    function additionalPropertyCode(key) {
      if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
        deleteAdditional(key);
        return;
      }
      if (schema === false) {
        cxt.setParams({ additionalProperty: key });
        cxt.error();
        if (!allErrors)
          gen.break();
        return;
      }
      if (typeof schema == "object" && !(0, util_1$8.alwaysValidSchema)(it, schema)) {
        const valid = gen.name("valid");
        if (opts.removeAdditional === "failing") {
          applyAdditionalSchema(key, valid, false);
          gen.if((0, codegen_1$5.not)(valid), () => {
            cxt.reset();
            deleteAdditional(key);
          });
        } else {
          applyAdditionalSchema(key, valid);
          if (!allErrors)
            gen.if((0, codegen_1$5.not)(valid), () => gen.break());
        }
      }
    }
    function applyAdditionalSchema(key, valid, errors2) {
      const subschema2 = {
        keyword: "additionalProperties",
        dataProp: key,
        dataPropType: util_1$8.Type.Str
      };
      if (errors2 === false) {
        Object.assign(subschema2, {
          compositeRule: true,
          createErrors: false,
          allErrors: false
        });
      }
      cxt.subschema(subschema2, valid);
    }
  }
};
additionalProperties$e.default = def$a;
var properties$x = {};
Object.defineProperty(properties$x, "__esModule", { value: true });
const validate_1 = validate;
const code_1$2 = code;
const util_1$7 = util;
const additionalProperties_1$1 = additionalProperties$e;
const def$9 = {
  keyword: "properties",
  type: "object",
  schemaType: "object",
  code(cxt) {
    const { gen, schema, parentSchema, data, it } = cxt;
    if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
      additionalProperties_1$1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1$1.default, "additionalProperties"));
    }
    const allProps = (0, code_1$2.allSchemaProperties)(schema);
    for (const prop of allProps) {
      it.definedProperties.add(prop);
    }
    if (it.opts.unevaluated && allProps.length && it.props !== true) {
      it.props = util_1$7.mergeEvaluated.props(gen, (0, util_1$7.toHash)(allProps), it.props);
    }
    const properties2 = allProps.filter((p) => !(0, util_1$7.alwaysValidSchema)(it, schema[p]));
    if (properties2.length === 0)
      return;
    const valid = gen.name("valid");
    for (const prop of properties2) {
      if (hasDefault(prop)) {
        applyPropertySchema(prop);
      } else {
        gen.if((0, code_1$2.propertyInData)(gen, data, prop, it.opts.ownProperties));
        applyPropertySchema(prop);
        if (!it.allErrors)
          gen.else().var(valid, true);
        gen.endIf();
      }
      cxt.it.definedProperties.add(prop);
      cxt.ok(valid);
    }
    function hasDefault(prop) {
      return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
    }
    function applyPropertySchema(prop) {
      cxt.subschema({
        keyword: "properties",
        schemaProp: prop,
        dataProp: prop
      }, valid);
    }
  }
};
properties$x.default = def$9;
var patternProperties = {};
Object.defineProperty(patternProperties, "__esModule", { value: true });
const code_1$1 = code;
const codegen_1$4 = codegen;
const util_1$6 = util;
const util_2 = util;
const def$8 = {
  keyword: "patternProperties",
  type: "object",
  schemaType: "object",
  code(cxt) {
    const { gen, schema, data, parentSchema, it } = cxt;
    const { opts } = it;
    const patterns = (0, code_1$1.allSchemaProperties)(schema);
    const alwaysValidPatterns = patterns.filter((p) => (0, util_1$6.alwaysValidSchema)(it, schema[p]));
    if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
      return;
    }
    const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
    const valid = gen.name("valid");
    if (it.props !== true && !(it.props instanceof codegen_1$4.Name)) {
      it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
    }
    const { props } = it;
    validatePatternProperties();
    function validatePatternProperties() {
      for (const pat of patterns) {
        if (checkProperties)
          checkMatchingProperties(pat);
        if (it.allErrors) {
          validateProperties(pat);
        } else {
          gen.var(valid, true);
          validateProperties(pat);
          gen.if(valid);
        }
      }
    }
    function checkMatchingProperties(pat) {
      for (const prop in checkProperties) {
        if (new RegExp(pat).test(prop)) {
          (0, util_1$6.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
        }
      }
    }
    function validateProperties(pat) {
      gen.forIn("key", data, (key) => {
        gen.if((0, codegen_1$4._)`${(0, code_1$1.usePattern)(cxt, pat)}.test(${key})`, () => {
          const alwaysValid = alwaysValidPatterns.includes(pat);
          if (!alwaysValid) {
            cxt.subschema({
              keyword: "patternProperties",
              schemaProp: pat,
              dataProp: key,
              dataPropType: util_2.Type.Str
            }, valid);
          }
          if (it.opts.unevaluated && props !== true) {
            gen.assign((0, codegen_1$4._)`${props}[${key}]`, true);
          } else if (!alwaysValid && !it.allErrors) {
            gen.if((0, codegen_1$4.not)(valid), () => gen.break());
          }
        });
      });
    }
  }
};
patternProperties.default = def$8;
var not = {};
Object.defineProperty(not, "__esModule", { value: true });
const util_1$5 = util;
const def$7 = {
  keyword: "not",
  schemaType: ["object", "boolean"],
  trackErrors: true,
  code(cxt) {
    const { gen, schema, it } = cxt;
    if ((0, util_1$5.alwaysValidSchema)(it, schema)) {
      cxt.fail();
      return;
    }
    const valid = gen.name("valid");
    cxt.subschema({
      keyword: "not",
      compositeRule: true,
      createErrors: false,
      allErrors: false
    }, valid);
    cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
  },
  error: { message: "must NOT be valid" }
};
not.default = def$7;
var anyOf = {};
Object.defineProperty(anyOf, "__esModule", { value: true });
const code_1 = code;
const def$6 = {
  keyword: "anyOf",
  schemaType: "array",
  trackErrors: true,
  code: code_1.validateUnion,
  error: { message: "must match a schema in anyOf" }
};
anyOf.default = def$6;
var oneOf = {};
Object.defineProperty(oneOf, "__esModule", { value: true });
const codegen_1$3 = codegen;
const util_1$4 = util;
const error$3 = {
  message: "must match exactly one schema in oneOf",
  params: ({ params }) => (0, codegen_1$3._)`{passingSchemas: ${params.passing}}`
};
const def$5 = {
  keyword: "oneOf",
  schemaType: "array",
  trackErrors: true,
  error: error$3,
  code(cxt) {
    const { gen, schema, parentSchema, it } = cxt;
    if (!Array.isArray(schema))
      throw new Error("ajv implementation error");
    if (it.opts.discriminator && parentSchema.discriminator)
      return;
    const schArr = schema;
    const valid = gen.let("valid", false);
    const passing = gen.let("passing", null);
    const schValid = gen.name("_valid");
    cxt.setParams({ passing });
    gen.block(validateOneOf);
    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
    function validateOneOf() {
      schArr.forEach((sch, i) => {
        let schCxt;
        if ((0, util_1$4.alwaysValidSchema)(it, sch)) {
          gen.var(schValid, true);
        } else {
          schCxt = cxt.subschema({
            keyword: "oneOf",
            schemaProp: i,
            compositeRule: true
          }, schValid);
        }
        if (i > 0) {
          gen.if((0, codegen_1$3._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1$3._)`[${passing}, ${i}]`).else();
        }
        gen.if(schValid, () => {
          gen.assign(valid, true);
          gen.assign(passing, i);
          if (schCxt)
            cxt.mergeEvaluated(schCxt, codegen_1$3.Name);
        });
      });
    }
  }
};
oneOf.default = def$5;
var allOf$6 = {};
Object.defineProperty(allOf$6, "__esModule", { value: true });
const util_1$3 = util;
const def$4 = {
  keyword: "allOf",
  schemaType: "array",
  code(cxt) {
    const { gen, schema, it } = cxt;
    if (!Array.isArray(schema))
      throw new Error("ajv implementation error");
    const valid = gen.name("valid");
    schema.forEach((sch, i) => {
      if ((0, util_1$3.alwaysValidSchema)(it, sch))
        return;
      const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
      cxt.ok(valid);
      cxt.mergeEvaluated(schCxt);
    });
  }
};
allOf$6.default = def$4;
var _if = {};
Object.defineProperty(_if, "__esModule", { value: true });
const codegen_1$2 = codegen;
const util_1$2 = util;
const error$2 = {
  message: ({ params }) => (0, codegen_1$2.str)`must match "${params.ifClause}" schema`,
  params: ({ params }) => (0, codegen_1$2._)`{failingKeyword: ${params.ifClause}}`
};
const def$3 = {
  keyword: "if",
  schemaType: ["object", "boolean"],
  trackErrors: true,
  error: error$2,
  code(cxt) {
    const { gen, parentSchema, it } = cxt;
    if (parentSchema.then === void 0 && parentSchema.else === void 0) {
      (0, util_1$2.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
    }
    const hasThen = hasSchema(it, "then");
    const hasElse = hasSchema(it, "else");
    if (!hasThen && !hasElse)
      return;
    const valid = gen.let("valid", true);
    const schValid = gen.name("_valid");
    validateIf();
    cxt.reset();
    if (hasThen && hasElse) {
      const ifClause = gen.let("ifClause");
      cxt.setParams({ ifClause });
      gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
    } else if (hasThen) {
      gen.if(schValid, validateClause("then"));
    } else {
      gen.if((0, codegen_1$2.not)(schValid), validateClause("else"));
    }
    cxt.pass(valid, () => cxt.error(true));
    function validateIf() {
      const schCxt = cxt.subschema({
        keyword: "if",
        compositeRule: true,
        createErrors: false,
        allErrors: false
      }, schValid);
      cxt.mergeEvaluated(schCxt);
    }
    function validateClause(keyword2, ifClause) {
      return () => {
        const schCxt = cxt.subschema({ keyword: keyword2 }, schValid);
        gen.assign(valid, schValid);
        cxt.mergeValidEvaluated(schCxt, valid);
        if (ifClause)
          gen.assign(ifClause, (0, codegen_1$2._)`${keyword2}`);
        else
          cxt.setParams({ ifClause: keyword2 });
      };
    }
  }
};
function hasSchema(it, keyword2) {
  const schema = it.schema[keyword2];
  return schema !== void 0 && !(0, util_1$2.alwaysValidSchema)(it, schema);
}
_if.default = def$3;
var thenElse = {};
Object.defineProperty(thenElse, "__esModule", { value: true });
const util_1$1 = util;
const def$2 = {
  keyword: ["then", "else"],
  schemaType: ["object", "boolean"],
  code({ keyword: keyword2, parentSchema, it }) {
    if (parentSchema.if === void 0)
      (0, util_1$1.checkStrictMode)(it, `"${keyword2}" without "if" is ignored`);
  }
};
thenElse.default = def$2;
Object.defineProperty(applicator, "__esModule", { value: true });
const additionalItems_1 = additionalItems;
const prefixItems_1 = prefixItems;
const items_1 = items$2;
const items2020_1 = items2020;
const contains_1 = contains;
const dependencies_1 = dependencies;
const propertyNames_1 = propertyNames;
const additionalProperties_1 = additionalProperties$e;
const properties_1 = properties$x;
const patternProperties_1 = patternProperties;
const not_1 = not;
const anyOf_1 = anyOf;
const oneOf_1 = oneOf;
const allOf_1 = allOf$6;
const if_1 = _if;
const thenElse_1 = thenElse;
function getApplicator(draft2020 = false) {
  const applicator2 = [
    // any
    not_1.default,
    anyOf_1.default,
    oneOf_1.default,
    allOf_1.default,
    if_1.default,
    thenElse_1.default,
    // object
    propertyNames_1.default,
    additionalProperties_1.default,
    dependencies_1.default,
    properties_1.default,
    patternProperties_1.default
  ];
  if (draft2020)
    applicator2.push(prefixItems_1.default, items2020_1.default);
  else
    applicator2.push(additionalItems_1.default, items_1.default);
  applicator2.push(contains_1.default);
  return applicator2;
}
applicator.default = getApplicator;
var format$2 = {};
var format$1 = {};
Object.defineProperty(format$1, "__esModule", { value: true });
const codegen_1$1 = codegen;
const error$1 = {
  message: ({ schemaCode }) => (0, codegen_1$1.str)`must match format "${schemaCode}"`,
  params: ({ schemaCode }) => (0, codegen_1$1._)`{format: ${schemaCode}}`
};
const def$1 = {
  keyword: "format",
  type: ["number", "string"],
  schemaType: "string",
  $data: true,
  error: error$1,
  code(cxt, ruleType) {
    const { gen, data, $data, schema, schemaCode, it } = cxt;
    const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
    if (!opts.validateFormats)
      return;
    if ($data)
      validate$DataFormat();
    else
      validateFormat();
    function validate$DataFormat() {
      const fmts = gen.scopeValue("formats", {
        ref: self2.formats,
        code: opts.code.formats
      });
      const fDef = gen.const("fDef", (0, codegen_1$1._)`${fmts}[${schemaCode}]`);
      const fType = gen.let("fType");
      const format2 = gen.let("format");
      gen.if((0, codegen_1$1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1$1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1$1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1$1._)`"string"`).assign(format2, fDef));
      cxt.fail$data((0, codegen_1$1.or)(unknownFmt(), invalidFmt()));
      function unknownFmt() {
        if (opts.strictSchema === false)
          return codegen_1$1.nil;
        return (0, codegen_1$1._)`${schemaCode} && !${format2}`;
      }
      function invalidFmt() {
        const callFormat = schemaEnv.$async ? (0, codegen_1$1._)`(${fDef}.async ? await ${format2}(${data}) : ${format2}(${data}))` : (0, codegen_1$1._)`${format2}(${data})`;
        const validData = (0, codegen_1$1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data}))`;
        return (0, codegen_1$1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`;
      }
    }
    function validateFormat() {
      const formatDef = self2.formats[schema];
      if (!formatDef) {
        unknownFormat();
        return;
      }
      if (formatDef === true)
        return;
      const [fmtType, format2, fmtRef] = getFormat(formatDef);
      if (fmtType === ruleType)
        cxt.pass(validCondition());
      function unknownFormat() {
        if (opts.strictSchema === false) {
          self2.logger.warn(unknownMsg());
          return;
        }
        throw new Error(unknownMsg());
        function unknownMsg() {
          return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
        }
      }
      function getFormat(fmtDef) {
        const code2 = fmtDef instanceof RegExp ? (0, codegen_1$1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1$1._)`${opts.code.formats}${(0, codegen_1$1.getProperty)(schema)}` : void 0;
        const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code: code2 });
        if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
          return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1$1._)`${fmt}.validate`];
        }
        return ["string", fmtDef, fmt];
      }
      function validCondition() {
        if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
          if (!schemaEnv.$async)
            throw new Error("async format in sync schema");
          return (0, codegen_1$1._)`await ${fmtRef}(${data})`;
        }
        return typeof format2 == "function" ? (0, codegen_1$1._)`${fmtRef}(${data})` : (0, codegen_1$1._)`${fmtRef}.test(${data})`;
      }
    }
  }
};
format$1.default = def$1;
Object.defineProperty(format$2, "__esModule", { value: true });
const format_1$1 = format$1;
const format = [format_1$1.default];
format$2.default = format;
var metadata = {};
Object.defineProperty(metadata, "__esModule", { value: true });
metadata.contentVocabulary = metadata.metadataVocabulary = void 0;
metadata.metadataVocabulary = [
  "title",
  "description",
  "default",
  "deprecated",
  "readOnly",
  "writeOnly",
  "examples"
];
metadata.contentVocabulary = [
  "contentMediaType",
  "contentEncoding",
  "contentSchema"
];
Object.defineProperty(draft7, "__esModule", { value: true });
const core_1 = core$1;
const validation_1 = validation$1;
const applicator_1 = applicator;
const format_1 = format$2;
const metadata_1 = metadata;
const draft7Vocabularies = [
  core_1.default,
  validation_1.default,
  (0, applicator_1.default)(),
  format_1.default,
  metadata_1.metadataVocabulary,
  metadata_1.contentVocabulary
];
draft7.default = draft7Vocabularies;
var discriminator = {};
var types = {};
Object.defineProperty(types, "__esModule", { value: true });
types.DiscrError = void 0;
var DiscrError;
(function(DiscrError2) {
  DiscrError2["Tag"] = "tag";
  DiscrError2["Mapping"] = "mapping";
})(DiscrError || (types.DiscrError = DiscrError = {}));
Object.defineProperty(discriminator, "__esModule", { value: true });
const codegen_1 = codegen;
const types_1 = types;
const compile_1 = compile;
const util_1 = util;
const error = {
  message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
  params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
};
const def = {
  keyword: "discriminator",
  type: "object",
  schemaType: "object",
  error,
  code(cxt) {
    const { gen, data, schema, parentSchema, it } = cxt;
    const { oneOf: oneOf2 } = parentSchema;
    if (!it.opts.discriminator) {
      throw new Error("discriminator: requires discriminator option");
    }
    const tagName = schema.propertyName;
    if (typeof tagName != "string")
      throw new Error("discriminator: requires propertyName");
    if (schema.mapping)
      throw new Error("discriminator: mapping is not supported");
    if (!oneOf2)
      throw new Error("discriminator: requires oneOf keyword");
    const valid = gen.let("valid", false);
    const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
    gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
    cxt.ok(valid);
    function validateMapping() {
      const mapping = getMapping();
      gen.if(false);
      for (const tagValue in mapping) {
        gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
        gen.assign(valid, applyTagSchema(mapping[tagValue]));
      }
      gen.else();
      cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
      gen.endIf();
    }
    function applyTagSchema(schemaProp) {
      const _valid = gen.name("valid");
      const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
      cxt.mergeEvaluated(schCxt, codegen_1.Name);
      return _valid;
    }
    function getMapping() {
      var _a;
      const oneOfMapping = {};
      const topRequired = hasRequired(parentSchema);
      let tagRequired = true;
      for (let i = 0; i < oneOf2.length; i++) {
        let sch = oneOf2[i];
        if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
          sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch === null || sch === void 0 ? void 0 : sch.$ref);
          if (sch instanceof compile_1.SchemaEnv)
            sch = sch.schema;
        }
        const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName];
        if (typeof propSch != "object") {
          throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
        }
        tagRequired = tagRequired && (topRequired || hasRequired(sch));
        addMappings(propSch, i);
      }
      if (!tagRequired)
        throw new Error(`discriminator: "${tagName}" must be required`);
      return oneOfMapping;
      function hasRequired({ required: required2 }) {
        return Array.isArray(required2) && required2.includes(tagName);
      }
      function addMappings(sch, i) {
        if (sch.const) {
          addMapping(sch.const, i);
        } else if (sch.enum) {
          for (const tagValue of sch.enum) {
            addMapping(tagValue, i);
          }
        } else {
          throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
        }
      }
      function addMapping(tagValue, i) {
        if (typeof tagValue != "string" || tagValue in oneOfMapping) {
          throw new Error(`discriminator: "${tagName}" values must be unique strings`);
        }
        oneOfMapping[tagValue] = i;
      }
    }
  }
};
discriminator.default = def;
const $schema = "http://json-schema.org/draft-07/schema#";
const $id$D = "http://json-schema.org/draft-07/schema#";
const title$g = "Core schema meta-schema";
const definitions$1 = {
  schemaArray: {
    type: "array",
    minItems: 1,
    items: {
      $ref: "#"
    }
  },
  nonNegativeInteger: {
    type: "integer",
    minimum: 0
  },
  nonNegativeIntegerDefault0: {
    allOf: [
      {
        $ref: "#/definitions/nonNegativeInteger"
      },
      {
        "default": 0
      }
    ]
  },
  simpleTypes: {
    "enum": [
      "array",
      "boolean",
      "integer",
      "null",
      "number",
      "object",
      "string"
    ]
  },
  stringArray: {
    type: "array",
    items: {
      type: "string"
    },
    uniqueItems: true,
    "default": []
  }
};
const type$E = [
  "object",
  "boolean"
];
const properties$w = {
  $id: {
    type: "string",
    format: "uri-reference"
  },
  $schema: {
    type: "string",
    format: "uri"
  },
  $ref: {
    type: "string",
    format: "uri-reference"
  },
  $comment: {
    type: "string"
  },
  title: {
    type: "string"
  },
  description: {
    type: "string"
  },
  "default": true,
  readOnly: {
    type: "boolean",
    "default": false
  },
  examples: {
    type: "array",
    items: true
  },
  multipleOf: {
    type: "number",
    exclusiveMinimum: 0
  },
  maximum: {
    type: "number"
  },
  exclusiveMaximum: {
    type: "number"
  },
  minimum: {
    type: "number"
  },
  exclusiveMinimum: {
    type: "number"
  },
  maxLength: {
    $ref: "#/definitions/nonNegativeInteger"
  },
  minLength: {
    $ref: "#/definitions/nonNegativeIntegerDefault0"
  },
  pattern: {
    type: "string",
    format: "regex"
  },
  additionalItems: {
    $ref: "#"
  },
  items: {
    anyOf: [
      {
        $ref: "#"
      },
      {
        $ref: "#/definitions/schemaArray"
      }
    ],
    "default": true
  },
  maxItems: {
    $ref: "#/definitions/nonNegativeInteger"
  },
  minItems: {
    $ref: "#/definitions/nonNegativeIntegerDefault0"
  },
  uniqueItems: {
    type: "boolean",
    "default": false
  },
  contains: {
    $ref: "#"
  },
  maxProperties: {
    $ref: "#/definitions/nonNegativeInteger"
  },
  minProperties: {
    $ref: "#/definitions/nonNegativeIntegerDefault0"
  },
  required: {
    $ref: "#/definitions/stringArray"
  },
  additionalProperties: {
    $ref: "#"
  },
  definitions: {
    type: "object",
    additionalProperties: {
      $ref: "#"
    },
    "default": {}
  },
  properties: {
    type: "object",
    additionalProperties: {
      $ref: "#"
    },
    "default": {}
  },
  patternProperties: {
    type: "object",
    additionalProperties: {
      $ref: "#"
    },
    propertyNames: {
      format: "regex"
    },
    "default": {}
  },
  dependencies: {
    type: "object",
    additionalProperties: {
      anyOf: [
        {
          $ref: "#"
        },
        {
          $ref: "#/definitions/stringArray"
        }
      ]
    }
  },
  propertyNames: {
    $ref: "#"
  },
  "const": true,
  "enum": {
    type: "array",
    items: true,
    minItems: 1,
    uniqueItems: true
  },
  type: {
    anyOf: [
      {
        $ref: "#/definitions/simpleTypes"
      },
      {
        type: "array",
        items: {
          $ref: "#/definitions/simpleTypes"
        },
        minItems: 1,
        uniqueItems: true
      }
    ]
  },
  format: {
    type: "string"
  },
  contentMediaType: {
    type: "string"
  },
  contentEncoding: {
    type: "string"
  },
  "if": {
    $ref: "#"
  },
  then: {
    $ref: "#"
  },
  "else": {
    $ref: "#"
  },
  allOf: {
    $ref: "#/definitions/schemaArray"
  },
  anyOf: {
    $ref: "#/definitions/schemaArray"
  },
  oneOf: {
    $ref: "#/definitions/schemaArray"
  },
  not: {
    $ref: "#"
  }
};
const require$$3$2 = {
  $schema,
  $id: $id$D,
  title: title$g,
  definitions: definitions$1,
  type: type$E,
  properties: properties$w,
  "default": true
};
(function(module2, exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.MissingRefError = exports2.ValidationError = exports2.CodeGen = exports2.Name = exports2.nil = exports2.stringify = exports2.str = exports2._ = exports2.KeywordCxt = exports2.Ajv = void 0;
  const core_12 = core$2;
  const draft7_1 = draft7;
  const discriminator_1 = discriminator;
  const draft7MetaSchema = require$$3$2;
  const META_SUPPORT_DATA = ["/properties"];
  const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
  class Ajv2 extends core_12.default {
    _addVocabularies() {
      super._addVocabularies();
      draft7_1.default.forEach((v) => this.addVocabulary(v));
      if (this.opts.discriminator)
        this.addKeyword(discriminator_1.default);
    }
    _addDefaultMetaSchema() {
      super._addDefaultMetaSchema();
      if (!this.opts.meta)
        return;
      const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
      this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
      this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
    }
    defaultMeta() {
      return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
    }
  }
  exports2.Ajv = Ajv2;
  module2.exports = exports2 = Ajv2;
  module2.exports.Ajv = Ajv2;
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.default = Ajv2;
  var validate_12 = validate;
  Object.defineProperty(exports2, "KeywordCxt", { enumerable: true, get: function() {
    return validate_12.KeywordCxt;
  } });
  var codegen_12 = codegen;
  Object.defineProperty(exports2, "_", { enumerable: true, get: function() {
    return codegen_12._;
  } });
  Object.defineProperty(exports2, "str", { enumerable: true, get: function() {
    return codegen_12.str;
  } });
  Object.defineProperty(exports2, "stringify", { enumerable: true, get: function() {
    return codegen_12.stringify;
  } });
  Object.defineProperty(exports2, "nil", { enumerable: true, get: function() {
    return codegen_12.nil;
  } });
  Object.defineProperty(exports2, "Name", { enumerable: true, get: function() {
    return codegen_12.Name;
  } });
  Object.defineProperty(exports2, "CodeGen", { enumerable: true, get: function() {
    return codegen_12.CodeGen;
  } });
  var validation_error_12 = validation_error;
  Object.defineProperty(exports2, "ValidationError", { enumerable: true, get: function() {
    return validation_error_12.default;
  } });
  var ref_error_12 = ref_error;
  Object.defineProperty(exports2, "MissingRefError", { enumerable: true, get: function() {
    return ref_error_12.default;
  } });
})(ajv, ajv.exports);
var ajvExports = ajv.exports;
const title$f = "Root";
const type$D = "object";
const description$f = "Root Element";
const definitions = {
  base64String: {
    type: "string",
    pattern: "^[A-Za-z0-9/+=]*$"
  },
  tagString: {
    type: "string",
    pattern: "^[a-z][a-z0-9]*(:.+)?$"
  }
};
const properties$v = {
  id: {
    type: "string"
  },
  metadata: {
    type: "object",
    properties: {
      selectors: {
        type: "object",
        additionalProperties: {
          type: "string"
        }
      }
    },
    required: [
      "selectors"
    ],
    additionalProperties: false
  },
  tags: {
    type: "array",
    items: {
      type: "string",
      $ref: "#/definitions/tagString"
    }
  },
  enums: {
    type: "object",
    properties: {
      ids: {
        $ref: "#/definitions/base64String"
      },
      wordLike: {
        $ref: "#/definitions/base64String"
      },
      notWordLike: {
        $ref: "#/definitions/base64String"
      },
      scopeBits: {
        $ref: "#/definitions/base64String"
      },
      graftTypes: {
        $ref: "#/definitions/base64String"
      }
    },
    required: [
      "ids",
      "wordLike",
      "notWordLike",
      "scopeBits",
      "graftTypes"
    ],
    additionalProperties: false
  },
  docs: {
    type: "object",
    propertyNames: {
      type: "string"
    },
    additionalProperties: {
      type: "object",
      properties: {
        sequences: {
          type: "object",
          additionalProperties: {
            type: "object",
            properties: {
              type: {
                type: "string"
              },
              blocks: {
                type: "array",
                items: {
                  type: "object",
                  properties: {
                    bs: {
                      type: "string"
                    },
                    bg: {
                      type: "string"
                    },
                    c: {
                      type: "string"
                    },
                    is: {
                      type: "string"
                    },
                    os: {
                      type: "string"
                    },
                    nt: {
                      type: "string"
                    }
                  },
                  required: [
                    "bs",
                    "bg",
                    "c",
                    "is",
                    "os",
                    "nt"
                  ],
                  additionalProperties: false
                }
              },
              tags: {
                type: "array",
                items: {
                  type: "string",
                  $ref: "#/definitions/tagString"
                }
              },
              chapters: {
                type: "object",
                additionalProperties: {
                  type: "string"
                }
              },
              chapterVerses: {
                type: "object",
                additionalProperties: {
                  type: "string"
                }
              },
              tokensPresent: {
                type: "string"
              }
            },
            required: [
              "blocks",
              "tags"
            ],
            additionalProperties: false
          }
        },
        headers: {
          type: "object",
          additionalProperties: {
            type: "string"
          }
        },
        mainId: {
          type: "string"
        },
        tags: {
          type: "array",
          items: {
            type: "string",
            $ref: "#/definitions/tagString"
          }
        }
      },
      required: [
        "sequences",
        "headers",
        "mainId",
        "tags"
      ],
      additionalProperties: false
    }
  },
  additionalProperties: false
};
const required$c = [
  "id",
  "enums",
  "docs",
  "tags"
];
const additionalProperties$d = false;
const require$$1$2 = {
  title: title$f,
  type: type$D,
  description: description$f,
  definitions,
  properties: properties$v,
  required: required$c,
  additionalProperties: additionalProperties$d
};
const $comment$8 = "version 0.1.0";
const $id$C = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_2_1/document_structure.json";
const title$e = "Document (Structure)";
const description$e = "A document, typically corresponding to a single USFM or USX book";
const type$C = "object";
const properties$u = {
  schema: {
    type: "object",
    properties: {
      structure: {
        description: "The basic 'shape' of the content",
        type: "string",
        "enum": [
          "flat",
          "nested"
        ]
      },
      structure_version: {
        description: "the semantic version of the structure schema",
        type: "string"
      },
      constraints: {
        type: "array",
        items: {
          type: "object",
          properties: {
            name: {
              type: "string",
              "enum": [
                "perf",
                "sofria"
              ]
            },
            version: {
              description: "the semantic version of the constraint schema",
              type: "string"
            }
          },
          additionalProperties: false,
          required: [
            "name",
            "version"
          ]
        }
      }
    },
    required: [
      "structure",
      "structure_version",
      "constraints"
    ],
    additionalProperties: false
  },
  metadata: {
    description: "Metadata describing the document and the translation it belongs to",
    type: "object",
    properties: {
      translation: {
        type: "object",
        description: "Metadata concerning the translation to which the document belongs",
        properties: {
          tags: {
            description: "Tags attached to the translation",
            type: "array",
            items: {
              type: "string"
            }
          },
          properties: {
            type: "object",
            description: "Key/value properties attached to the translation",
            additionalProperties: {
              type: "string"
            }
          },
          selectors: {
            type: "object",
            description: "Proskomma selectors for the translation that, together, provide a primary key in the translation store",
            additionalProperties: {
              type: "string"
            }
          }
        },
        additionalProperties: {
          type: "string"
        },
        required: [
          "id"
        ]
      },
      document: {
        type: "object",
        description: "Metadata concerning the document itself",
        properties: {
          tags: {
            type: "array",
            description: "Tags attached to the document",
            items: {
              type: "string"
            }
          },
          properties: {
            type: "object",
            description: "Key/value properties attached to the document",
            additionalProperties: {
              type: "string"
            }
          },
          chapters: {
            type: "string",
            pattern: "^[1-9][0-9]*(-[1-9][0-9]*)?$"
          }
        },
        additionalProperties: {
          type: "string"
        }
      }
    },
    additionalProperties: false
  },
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./sequence_structure.json"
    }
  },
  sequence: {
    $ref: "./sequence_structure.json"
  },
  main_sequence_id: {
    type: "string"
  }
};
const required$b = [
  "schema",
  "metadata"
];
const additionalProperties$c = false;
const then$b = {
  required: [
    "sequences",
    "main_sequence_id"
  ],
  not: {
    required: [
      "sequence"
    ]
  }
};
const require$$2$1 = {
  $comment: $comment$8,
  $id: $id$C,
  title: title$e,
  description: description$e,
  type: type$C,
  properties: properties$u,
  required: required$b,
  additionalProperties: additionalProperties$c,
  "if": {
    properties: {
      schema: {
        type: "object",
        properties: {
          structure: {
            "enum": [
              "flat"
            ]
          }
        }
      }
    }
  },
  then: then$b,
  "else": {
    required: [
      "sequence"
    ],
    allOf: [
      {
        not: {
          required: [
            "sequences"
          ]
        }
      },
      {
        not: {
          required: [
            "main_sequence_id"
          ]
        }
      }
    ]
  }
};
const $id$B = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_2_1/sequence_structure.json";
const title$d = "Sequence (Structure)";
const description$d = "A sequence contains a 'flow' of one or more blocks";
const type$B = "object";
const properties$t = {
  type: {
    description: "The type of sequence",
    type: "string"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label",
    type: "string"
  },
  blocks: {
    type: "array",
    description: "The blocks that, together, represent the 'flow' of the sequence",
    items: {
      $ref: "./block_structure.json"
    }
  }
};
const required$a = [
  "type"
];
const additionalProperties$b = false;
const require$$3$1 = {
  $id: $id$B,
  title: title$d,
  description: description$d,
  type: type$B,
  properties: properties$t,
  required: required$a,
  additionalProperties: additionalProperties$b
};
const $id$A = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_2_1/block_structure.json";
const title$c = "Block (Structure)";
const description$c = "A block, which represents either a paragraph of text or a graft";
const type$A = "object";
const properties$s = {
  type: {
    type: "string",
    description: "The type of block",
    "enum": [
      "paragraph",
      "graft"
    ]
  },
  subtype: {
    description: "A type-specific subtype",
    type: "string"
  },
  target: {
    description: "The id of the sequence containing graft content",
    type: "string"
  },
  sequence: {
    description: "The sequence containing graft content",
    $ref: "./sequence_structure.json"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label for a graft",
    type: "string"
  },
  "new": {
    description: "If present and true, is interpreted as a request for the server to create a new graft",
    type: "boolean"
  },
  atts: {
    type: "object",
    description: "An object containing USFM attributes or subtype-specific additional information (such as the number of a verse or chapter). The value may be a boolean, a string or an array of strings",
    additionalProperties: {
      oneOf: [
        {
          type: "array",
          items: {
            type: "string"
          }
        },
        {
          type: "string"
        },
        {
          type: "boolean"
        }
      ]
    }
  },
  content: {
    type: "array",
    description: "The content of the block",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  }
};
const required$9 = [
  "type"
];
const additionalProperties$a = false;
const then$a = {
  required: [
    "content"
  ],
  allOf: [
    {
      not: {
        required: [
          "new"
        ]
      }
    },
    {
      not: {
        required: [
          "preview_text"
        ]
      }
    },
    {
      not: {
        required: [
          "target"
        ]
      }
    }
  ]
};
const require$$4$1 = {
  $id: $id$A,
  title: title$c,
  description: description$c,
  type: type$A,
  properties: properties$s,
  required: required$9,
  additionalProperties: additionalProperties$a,
  "if": {
    properties: {
      type: {
        "enum": [
          "paragraph"
        ]
      }
    }
  },
  then: then$a,
  "else": {
    "if": {
      required: [
        "new"
      ],
      properties: {
        "new": {
          "enum": [
            true
          ]
        }
      }
    },
    then: {
      allOf: [
        {
          oneOf: [
            {
              required: [
                "subtype"
              ]
            },
            {
              required: [
                "sequence"
              ]
            }
          ]
        },
        {
          not: {
            required: [
              "target"
            ]
          }
        },
        {
          not: {
            required: [
              "preview_text"
            ]
          }
        },
        {
          not: {
            required: [
              "content"
            ]
          }
        }
      ]
    },
    "else": {
      oneOf: [
        {
          required: [
            "target"
          ]
        },
        {
          required: [
            "sequence"
          ]
        }
      ]
    }
  }
};
const $id$z = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_2_1/contentElement_structure.json";
const title$b = "Content Element (Structure)";
const description$b = "A content element, ie some form of (possibly nested) markup";
const type$z = "object";
const properties$r = {
  type: {
    type: "string",
    description: "The type of element",
    "enum": [
      "mark",
      "wrapper",
      "start_milestone",
      "end_milestone",
      "graft"
    ]
  },
  subtype: {
    description: "The subtype of the element, which is context-dependent",
    type: "string"
  },
  atts: {
    type: "object",
    description: "An object containing USFM attributes or subtype-specific additional information (such as the number of a verse or chapter). The value may be a boolean, a string or an array of strings",
    additionalProperties: {
      oneOf: [
        {
          type: "array",
          items: {
            type: "string"
          }
        },
        {
          type: "string"
        },
        {
          type: "boolean"
        }
      ]
    }
  },
  target: {
    type: "string",
    description: "The id of the sequence containing graft content"
  },
  sequence: {
    description: "The sequence containing graft content",
    $ref: "./sequence_structure.json"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label for a graft",
    type: "string"
  },
  "new": {
    type: "boolean",
    description: "If present and true, is interpreted as a request for the server to create a new graft"
  },
  content: {
    type: "array",
    description: "Nested content within the content element",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    description: "Non-Scripture content related to the content element, such as checking data or related resources",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  }
};
const required$8 = [
  "type"
];
const additionalProperties$9 = false;
const require$$5$1 = {
  $id: $id$z,
  title: title$b,
  description: description$b,
  type: type$z,
  properties: properties$r,
  required: required$8,
  additionalProperties: additionalProperties$9
};
const $comment$7 = "version 0.2.0";
const $id$y = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/perf_document_constraint.json";
const type$y = "object";
const properties$q = {
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./perf_sequence_constraint.json"
    }
  }
};
const require$$6$1 = {
  $comment: $comment$7,
  $id: $id$y,
  type: type$y,
  properties: properties$q
};
const $id$x = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/perf_sequence_constraint.json";
const type$x = "object";
const properties$p = {
  type: {
    type: "string",
    "enum": [
      "main",
      "introduction",
      "intro_title",
      "intro_end_title",
      "title",
      "end_title",
      "heading",
      "remark",
      "sidebar",
      "table",
      "tree",
      "kv",
      "footnote",
      "note_caller",
      "xref",
      "pub_number",
      "alt_number",
      "esb_cat",
      "fig",
      "temp"
    ]
  },
  blocks: {
    type: "array",
    items: {
      $ref: "./perf_block_constraint.json"
    }
  }
};
const require$$7$1 = {
  $id: $id$x,
  type: type$x,
  properties: properties$p
};
const $id$w = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/perf_block_constraint.json";
const type$w = "object";
const properties$o = {
  type: {
    type: "string",
    "enum": [
      "paragraph",
      "graft"
    ]
  },
  content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./perf_contentElement_constraint.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./perf_contentElement_constraint.json"
        }
      ]
    }
  }
};
const then$9 = {
  properties: {
    subtype: {
      "enum": [
        "introduction",
        "intro_title",
        "Intro_end_title",
        "title",
        "end_title",
        "heading",
        "remark",
        "sidebar",
        "table",
        "tree",
        "kv"
      ]
    }
  }
};
const require$$8 = {
  $id: $id$w,
  type: type$w,
  properties: properties$o,
  "if": {
    properties: {
      type: {
        "enum": [
          "graft"
        ]
      }
    }
  },
  then: then$9,
  "else": {
    properties: {
      subtype: {
        type: "string",
        pattern: "^usfm:"
      }
    }
  }
};
const $id$v = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/perf_contentElement_constraint.json";
const type$v = "object";
const allOf$5 = [
  {
    properties: {
      content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./perf_contentElement_constraint.json"
            }
          ]
        }
      },
      meta_content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./perf_contentElement_constraint.json"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "graft"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          "enum": [
            "footnote",
            "xref",
            "note_caller"
          ]
        }
      },
      allOf: [
        {
          not: {
            required: [
              "content"
            ]
          }
        },
        {
          not: {
            required: [
              "meta_content"
            ]
          }
        }
      ],
      "if": {
        required: [
          "new"
        ],
        properties: {
          "new": {
            "enum": [
              true
            ]
          }
        }
      },
      then: {
        not: {
          anyOf: [
            {
              required: [
                "target"
              ]
            },
            {
              required: [
                "preview_text"
              ]
            }
          ]
        }
      },
      "else": {
        required: [
          "target"
        ]
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "mark"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "chapter",
                "verses"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "chapter",
              "verses"
            ]
          }
        }
      },
      then: {
        type: "object",
        required: [
          "atts"
        ],
        properties: {
          atts: {
            type: "object",
            required: [
              "number"
            ],
            maxProperties: 1
          }
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "wrapper"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "meta_content"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "meta_content"
            ]
          }
        }
      },
      then: {
        not: {
          required: [
            "atts"
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "start_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "end_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      not: {
        required: [
          "atts"
        ]
      }
    }
  }
];
const require$$9 = {
  $id: $id$v,
  type: type$v,
  allOf: allOf$5
};
const $comment$6 = "version 0.2.0";
const $id$u = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/sofria_document_constraint.json";
const type$u = "object";
const properties$n = {
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./sofria_sequence_constraint.json"
    }
  }
};
const require$$10 = {
  $comment: $comment$6,
  $id: $id$u,
  type: type$u,
  properties: properties$n
};
const $id$t = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/sofria_sequence_constraint.json";
const type$t = "object";
const properties$m = {
  type: {
    type: "string",
    "enum": [
      "main",
      "introduction",
      "intro_title",
      "intro_end_title",
      "title",
      "end_title",
      "heading",
      "remark",
      "sidebar",
      "table",
      "tree",
      "kv",
      "footnote",
      "note_caller",
      "xref",
      "pub_number",
      "alt_number",
      "esb_cat",
      "fig",
      "temp"
    ]
  },
  blocks: {
    type: "array",
    items: {
      $ref: "./sofria_block_constraint.json"
    }
  }
};
const require$$11 = {
  $id: $id$t,
  type: type$t,
  properties: properties$m
};
const $id$s = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/sofria_block_constraint.json";
const type$s = "object";
const properties$l = {
  type: {
    type: "string",
    "enum": [
      "paragraph",
      "graft"
    ]
  },
  content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./sofria_contentElement_constraint.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./sofria_contentElement_constraint.json"
        }
      ]
    }
  }
};
const then$8 = {
  properties: {
    subtype: {
      "enum": [
        "introduction",
        "intro_title",
        "Intro_end_title",
        "title",
        "end_title",
        "heading",
        "remark",
        "sidebar",
        "table",
        "tree",
        "kv"
      ]
    }
  }
};
const require$$12 = {
  $id: $id$s,
  type: type$s,
  properties: properties$l,
  "if": {
    properties: {
      type: {
        "enum": [
          "graft"
        ]
      }
    }
  },
  then: then$8,
  "else": {
    properties: {
      subtype: {
        type: "string",
        pattern: "^usfm:"
      }
    }
  }
};
const $id$r = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_2_1/sofria_contentElement_constraint.json";
const type$r = "object";
const allOf$4 = [
  {
    properties: {
      content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./sofria_contentElement_constraint.json"
            }
          ]
        }
      },
      meta_content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./sofria_contentElement_constraint.json"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "graft"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          "enum": [
            "footnote",
            "xref",
            "note_caller"
          ]
        }
      },
      allOf: [
        {
          not: {
            required: [
              "content"
            ]
          }
        },
        {
          not: {
            required: [
              "meta_content"
            ]
          }
        }
      ],
      "if": {
        required: [
          "new"
        ],
        properties: {
          "new": {
            "enum": [
              true
            ]
          }
        }
      },
      then: {
        not: {
          anyOf: [
            {
              required: [
                "block"
              ]
            },
            {
              required: [
                "preview_text"
              ]
            }
          ]
        }
      },
      "else": {
        required: [
          "block"
        ]
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "mark"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "chapter_label",
                "verses_label"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "chapter",
              "verses"
            ]
          }
        }
      },
      then: {
        type: "object",
        required: [
          "atts"
        ],
        properties: {
          atts: {
            type: "object",
            required: [
              "number"
            ],
            maxProperties: 1
          }
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "wrapper"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "meta_content",
                "chapter",
                "verses"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "meta_content"
            ]
          }
        }
      },
      then: {
        not: {
          required: [
            "atts"
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "start_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "end_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      not: {
        required: [
          "atts"
        ]
      }
    }
  }
];
const require$$13 = {
  $id: $id$r,
  type: type$r,
  allOf: allOf$4
};
const $comment$5 = "version 0.1.0";
const $id$q = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_3_0/document_structure.json";
const title$a = "Document (Structure)";
const description$a = "A document, typically corresponding to a single USFM or USX book";
const type$q = "object";
const properties$k = {
  schema: {
    type: "object",
    properties: {
      structure: {
        description: "The basic 'shape' of the content",
        type: "string",
        "enum": [
          "flat",
          "nested"
        ]
      },
      structure_version: {
        description: "the semantic version of the structure schema",
        type: "string"
      },
      constraints: {
        type: "array",
        items: {
          type: "object",
          properties: {
            name: {
              type: "string",
              "enum": [
                "perf",
                "sofria"
              ]
            },
            version: {
              description: "the semantic version of the constraint schema",
              type: "string"
            }
          },
          additionalProperties: false,
          required: [
            "name",
            "version"
          ]
        }
      }
    },
    required: [
      "structure",
      "structure_version",
      "constraints"
    ],
    additionalProperties: false
  },
  metadata: {
    description: "Metadata describing the document and the translation it belongs to",
    type: "object",
    properties: {
      translation: {
        type: "object",
        description: "Metadata concerning the translation to which the document belongs",
        properties: {
          tags: {
            description: "Tags attached to the translation",
            type: "array",
            items: {
              type: "string"
            }
          },
          properties: {
            type: "object",
            description: "Key/value properties attached to the translation",
            additionalProperties: {
              type: "string"
            }
          },
          selectors: {
            type: "object",
            description: "Proskomma selectors for the translation that, together, provide a primary key in the translation store",
            additionalProperties: {
              type: "string"
            }
          }
        },
        additionalProperties: {
          type: "string"
        },
        required: [
          "id"
        ]
      },
      document: {
        type: "object",
        description: "Metadata concerning the document itself",
        properties: {
          tags: {
            type: "array",
            description: "Tags attached to the document",
            items: {
              type: "string"
            }
          },
          properties: {
            type: "object",
            description: "Key/value properties attached to the document",
            additionalProperties: {
              type: "string"
            }
          },
          chapters: {
            type: "string",
            pattern: "^[1-9][0-9]*(-[1-9][0-9]*)?$"
          }
        },
        additionalProperties: {
          type: "string"
        }
      }
    },
    additionalProperties: false
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  },
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./sequence_structure.json"
    }
  },
  sequence: {
    $ref: "./sequence_structure.json"
  },
  main_sequence_id: {
    type: "string"
  }
};
const required$7 = [
  "schema",
  "metadata"
];
const additionalProperties$8 = false;
const then$7 = {
  required: [
    "sequences",
    "main_sequence_id"
  ],
  not: {
    required: [
      "sequence"
    ]
  }
};
const require$$14 = {
  $comment: $comment$5,
  $id: $id$q,
  title: title$a,
  description: description$a,
  type: type$q,
  properties: properties$k,
  required: required$7,
  additionalProperties: additionalProperties$8,
  "if": {
    properties: {
      schema: {
        type: "object",
        properties: {
          structure: {
            "enum": [
              "flat"
            ]
          }
        }
      }
    }
  },
  then: then$7,
  "else": {
    required: [
      "sequence"
    ],
    allOf: [
      {
        not: {
          required: [
            "sequences"
          ]
        }
      },
      {
        not: {
          required: [
            "main_sequence_id"
          ]
        }
      }
    ]
  }
};
const $id$p = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_3_0/sequence_structure.json";
const title$9 = "Sequence (Structure)";
const description$9 = "A sequence contains a 'flow' of one or more blocks";
const type$p = "object";
const properties$j = {
  type: {
    description: "The type of sequence",
    type: "string"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label",
    type: "string"
  },
  blocks: {
    type: "array",
    description: "The blocks that, together, represent the 'flow' of the sequence",
    items: {
      $ref: "./block_structure.json"
    }
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  }
};
const required$6 = [
  "type"
];
const additionalProperties$7 = false;
const require$$15 = {
  $id: $id$p,
  title: title$9,
  description: description$9,
  type: type$p,
  properties: properties$j,
  required: required$6,
  additionalProperties: additionalProperties$7
};
const $id$o = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_3_0/block_structure.json";
const title$8 = "Block (Structure)";
const description$8 = "A block, which represents either a paragraph of text or a graft";
const type$o = "object";
const properties$i = {
  type: {
    type: "string",
    description: "The type of block",
    "enum": [
      "paragraph",
      "row",
      "node",
      "lookup",
      "graft"
    ]
  },
  subtype: {
    description: "A type-specific subtype",
    type: "string"
  },
  target: {
    description: "The id of the sequence containing graft content",
    type: "string"
  },
  sequence: {
    description: "The sequence containing graft content",
    $ref: "./sequence_structure.json"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label for a graft",
    type: "string"
  },
  "new": {
    description: "If present and true, is interpreted as a request for the server to create a new graft",
    type: "boolean"
  },
  atts: {
    type: "object",
    description: "An object containing USFM attributes or subtype-specific additional information (such as the number of a verse or chapter). The value may be a boolean, a string or an array of strings",
    additionalProperties: {
      oneOf: [
        {
          type: "array",
          items: {
            type: "string"
          }
        },
        {
          type: "string"
        },
        {
          type: "boolean"
        }
      ]
    }
  },
  content: {
    type: "array",
    description: "The content of the block",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  }
};
const required$5 = [
  "type"
];
const additionalProperties$6 = false;
const then$6 = {
  required: [
    "content"
  ],
  allOf: [
    {
      not: {
        required: [
          "new"
        ]
      }
    },
    {
      not: {
        required: [
          "preview_text"
        ]
      }
    },
    {
      not: {
        required: [
          "target"
        ]
      }
    }
  ]
};
const require$$16 = {
  $id: $id$o,
  title: title$8,
  description: description$8,
  type: type$o,
  properties: properties$i,
  required: required$5,
  additionalProperties: additionalProperties$6,
  "if": {
    properties: {
      type: {
        "enum": [
          "paragraph",
          "row",
          "node",
          "lookup"
        ]
      }
    }
  },
  then: then$6,
  "else": {
    "if": {
      required: [
        "new"
      ],
      properties: {
        "new": {
          "enum": [
            true
          ]
        }
      }
    },
    then: {
      allOf: [
        {
          oneOf: [
            {
              required: [
                "subtype"
              ]
            },
            {
              required: [
                "sequence"
              ]
            }
          ]
        },
        {
          not: {
            required: [
              "target"
            ]
          }
        },
        {
          not: {
            required: [
              "preview_text"
            ]
          }
        },
        {
          not: {
            required: [
              "content"
            ]
          }
        }
      ]
    },
    "else": {
      oneOf: [
        {
          required: [
            "target"
          ]
        },
        {
          required: [
            "sequence"
          ]
        }
      ]
    }
  }
};
const $id$n = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_3_0/contentElement_structure.json";
const title$7 = "Content Element (Structure)";
const description$7 = "A content element, ie some form of (possibly nested) markup";
const type$n = "object";
const properties$h = {
  type: {
    type: "string",
    description: "The type of element",
    "enum": [
      "mark",
      "wrapper",
      "start_milestone",
      "end_milestone",
      "graft"
    ]
  },
  subtype: {
    description: "The subtype of the element, which is context-dependent",
    type: "string"
  },
  atts: {
    type: "object",
    description: "An object containing USFM attributes or subtype-specific additional information (such as the number of a verse or chapter). The value may be a boolean, a string or an array of strings",
    additionalProperties: {
      oneOf: [
        {
          type: "array",
          items: {
            type: "string"
          }
        },
        {
          type: "string"
        },
        {
          type: "boolean"
        }
      ]
    }
  },
  target: {
    type: "string",
    description: "The id of the sequence containing graft content"
  },
  sequence: {
    description: "The sequence containing graft content",
    $ref: "./sequence_structure.json"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label for a graft",
    type: "string"
  },
  "new": {
    type: "boolean",
    description: "If present and true, is interpreted as a request for the server to create a new graft"
  },
  content: {
    type: "array",
    description: "Nested content within the content element",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    description: "Non-Scripture content related to the content element, such as checking data or related resources",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  }
};
const required$4 = [
  "type"
];
const additionalProperties$5 = false;
const require$$17 = {
  $id: $id$n,
  title: title$7,
  description: description$7,
  type: type$n,
  properties: properties$h,
  required: required$4,
  additionalProperties: additionalProperties$5
};
const $id$m = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_3_0/hook_structure.json";
const title$6 = "Hook (Structure)";
const description$6 = "Hooks, ie typed labels that may be used to link documents";
const type$m = "array";
const items$1 = {
  type: "array",
  items: [
    {
      type: "string",
      oneOf: [
        {
          "enum": [
            "bcv_ref",
            "book_ref"
          ]
        },
        {
          pattern: "^x-(app|publisher)-[a-z][a-z0-9]+-\\S{2,256}$"
        },
        {
          pattern: "^x-local-\\S{2,256}$"
        }
      ]
    },
    {
      type: "string",
      oneOf: [
        {
          "enum": [
            "label"
          ]
        },
        {
          pattern: "^\\w{1,255}$"
        }
      ]
    }
  ],
  minItems: 2,
  maxItems: 2
};
const require$$18 = {
  $id: $id$m,
  title: title$6,
  description: description$6,
  type: type$m,
  items: items$1
};
const $comment$4 = "version 0.3.0";
const $id$l = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/perf_document_constraint.json";
const type$l = "object";
const properties$g = {
  hooks: {
    type: "array"
  },
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./perf_sequence_constraint.json"
    }
  }
};
const require$$19 = {
  $comment: $comment$4,
  $id: $id$l,
  type: type$l,
  properties: properties$g
};
const $id$k = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/perf_sequence_constraint.json";
const type$k = "object";
const properties$f = {
  type: {
    type: "string",
    "enum": [
      "main",
      "introduction",
      "intro_title",
      "intro_end_title",
      "title",
      "end_title",
      "heading",
      "remark",
      "sidebar",
      "table",
      "tree",
      "kv",
      "footnote",
      "note_caller",
      "xref",
      "pub_number",
      "alt_number",
      "esb_cat",
      "fig",
      "temp"
    ]
  },
  blocks: {
    type: "array",
    items: {
      $ref: "./perf_block_constraint.json"
    }
  }
};
const require$$20 = {
  $id: $id$k,
  type: type$k,
  properties: properties$f
};
const $id$j = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/perf_block_constraint.json";
const type$j = "object";
const properties$e = {
  type: {
    type: "string",
    "enum": [
      "paragraph",
      "graft",
      "row",
      "node",
      "lookup"
    ]
  },
  content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./perf_contentElement_constraint.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./perf_contentElement_constraint.json"
        }
      ]
    }
  }
};
const then$5 = {
  properties: {
    subtype: {
      "enum": [
        "introduction",
        "intro_title",
        "Intro_end_title",
        "title",
        "end_title",
        "heading",
        "remark",
        "sidebar",
        "table",
        "tree",
        "kv"
      ]
    }
  }
};
const require$$21 = {
  $id: $id$j,
  type: type$j,
  properties: properties$e,
  "if": {
    properties: {
      type: {
        "enum": [
          "graft"
        ]
      }
    }
  },
  then: then$5,
  "else": {
    "if": {
      properties: {
        type: {
          "enum": [
            "row"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "row:heading",
                "row:body"
              ]
            }
          ]
        }
      }
    },
    "else": {
      "if": {
        properties: {
          type: {
            "enum": [
              "node"
            ]
          }
        }
      },
      then: {
        properties: {
          subtype: {
            type: "string",
            oneOf: [
              {
                "enum": [
                  "node"
                ]
              },
              {
                pattern: "^x-\\S{1,256}$"
              }
            ]
          },
          atts: {
            type: "object",
            properties: {
              id: {
                type: "string"
              },
              parent: {
                type: "string"
              },
              children: {
                type: "array",
                items: {
                  type: "string"
                }
              }
            },
            required: [
              "id"
            ],
            additionalProperties: false
          }
        }
      },
      "else": {
        "if": {
          properties: {
            type: {
              "enum": [
                "lookup"
              ]
            }
          }
        },
        then: {
          properties: {
            subtype: {
              type: "string",
              oneOf: [
                {
                  "enum": [
                    "lookup"
                  ]
                },
                {
                  pattern: "^x-\\S{1,256}$"
                }
              ]
            },
            atts: {
              type: "object",
              properties: {
                primary: {
                  type: "string"
                },
                secondary: {
                  type: "array",
                  items: {
                    type: "string"
                  }
                }
              },
              required: [
                "primary"
              ],
              additionalProperties: false
            }
          }
        },
        "else": {
          properties: {
            subtype: {
              type: "string",
              oneOf: [
                {
                  pattern: "^usfm:"
                },
                {
                  pattern: "^x-\\S{1,256}$"
                }
              ]
            }
          }
        }
      }
    }
  }
};
const $id$i = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/perf_contentElement_constraint.json";
const type$i = "object";
const allOf$3 = [
  {
    properties: {
      content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./perf_contentElement_constraint.json"
            }
          ]
        }
      },
      meta_content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./perf_contentElement_constraint.json"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "graft"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          "enum": [
            "footnote",
            "xref",
            "note_caller"
          ]
        }
      },
      allOf: [
        {
          not: {
            required: [
              "content"
            ]
          }
        },
        {
          not: {
            required: [
              "meta_content"
            ]
          }
        }
      ],
      "if": {
        required: [
          "new"
        ],
        properties: {
          "new": {
            "enum": [
              true
            ]
          }
        }
      },
      then: {
        not: {
          anyOf: [
            {
              required: [
                "target"
              ]
            },
            {
              required: [
                "preview_text"
              ]
            }
          ]
        }
      },
      "else": {
        required: [
          "target"
        ]
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "mark"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "chapter",
                "verses",
                "alt_chapter",
                "alt_verse",
                "pub_chapter",
                "pub_verse"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "chapter",
              "verses"
            ]
          }
        }
      },
      then: {
        type: "object",
        required: [
          "atts"
        ],
        properties: {
          atts: {
            type: "object",
            required: [
              "number"
            ],
            maxProperties: 1
          }
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "wrapper"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "meta_content"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "meta_content"
            ]
          }
        }
      },
      then: {
        not: {
          required: [
            "atts"
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "start_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "end_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      not: {
        required: [
          "atts"
        ]
      }
    }
  }
];
const require$$22 = {
  $id: $id$i,
  type: type$i,
  allOf: allOf$3
};
const $comment$3 = "version 0.3.0";
const $id$h = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/sofria_document_constraint.json";
const type$h = "object";
const properties$d = {
  sequence: {
    $ref: "./sofria_sequence_constraint.json"
  }
};
const require$$23 = {
  $comment: $comment$3,
  $id: $id$h,
  type: type$h,
  properties: properties$d
};
const $id$g = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/sofria_sequence_constraint.json";
const type$g = "object";
const properties$c = {
  type: {
    type: "string",
    "enum": [
      "main",
      "introduction",
      "intro_title",
      "intro_end_title",
      "title",
      "end_title",
      "heading",
      "remark",
      "sidebar",
      "table",
      "tree",
      "kv",
      "footnote",
      "note_caller",
      "xref",
      "pub_number",
      "alt_number",
      "esb_cat",
      "fig",
      "temp"
    ]
  },
  blocks: {
    type: "array",
    items: {
      $ref: "./sofria_block_constraint.json"
    }
  }
};
const require$$24 = {
  $id: $id$g,
  type: type$g,
  properties: properties$c
};
const $id$f = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/sofria_block_constraint.json";
const type$f = "object";
const properties$b = {
  type: {
    type: "string",
    "enum": [
      "paragraph",
      "graft"
    ]
  },
  content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./sofria_contentElement_constraint.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./sofria_contentElement_constraint.json"
        }
      ]
    }
  }
};
const then$4 = {
  properties: {
    subtype: {
      "enum": [
        "introduction",
        "intro_title",
        "Intro_end_title",
        "title",
        "end_title",
        "heading",
        "remark",
        "sidebar",
        "table",
        "tree",
        "kv"
      ]
    }
  }
};
const require$$25 = {
  $id: $id$f,
  type: type$f,
  properties: properties$b,
  "if": {
    properties: {
      type: {
        "enum": [
          "graft"
        ]
      }
    }
  },
  then: then$4,
  "else": {
    properties: {
      subtype: {
        type: "string",
        pattern: "^usfm:"
      }
    }
  }
};
const $id$e = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_3_0/sofria_contentElement_constraint.json";
const type$e = "object";
const allOf$2 = [
  {
    properties: {
      content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./sofria_contentElement_constraint.json"
            }
          ]
        }
      },
      meta_content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./sofria_contentElement_constraint.json"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "graft"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          "enum": [
            "footnote",
            "xref",
            "note_caller"
          ]
        }
      },
      allOf: [
        {
          not: {
            required: [
              "content"
            ]
          }
        },
        {
          not: {
            required: [
              "meta_content"
            ]
          }
        }
      ],
      "if": {
        required: [
          "new"
        ],
        properties: {
          "new": {
            "enum": [
              true
            ]
          }
        }
      },
      then: {
        not: {
          anyOf: [
            {
              required: [
                "blocks"
              ]
            },
            {
              required: [
                "preview_text"
              ]
            }
          ]
        }
      },
      "else": {
        required: [
          "sequence"
        ]
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "mark"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "chapter_label",
                "verses_label",
                "alt_chapter",
                "alt_verse",
                "pub_chapter",
                "pub_verse"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "chapter",
              "verses"
            ]
          }
        }
      },
      then: {
        type: "object",
        required: [
          "atts"
        ],
        properties: {
          atts: {
            type: "object",
            required: [
              "number"
            ],
            maxProperties: 1
          }
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "wrapper"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "meta_content",
                "chapter",
                "verses"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "meta_content"
            ]
          }
        }
      },
      then: {
        not: {
          required: [
            "atts"
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "start_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "end_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      not: {
        required: [
          "atts"
        ]
      }
    }
  }
];
const require$$26 = {
  $id: $id$e,
  type: type$e,
  allOf: allOf$2
};
const $comment$2 = "version 0.1.0";
const $id$d = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_4_0/document_structure.json";
const title$5 = "Document (Structure)";
const description$5 = "A document, typically corresponding to a single USFM or USX book";
const type$d = "object";
const properties$a = {
  schema: {
    type: "object",
    properties: {
      structure: {
        description: "The basic 'shape' of the content",
        type: "string",
        "enum": [
          "flat",
          "nested"
        ]
      },
      structure_version: {
        description: "the semantic version of the structure schema",
        type: "string"
      },
      constraints: {
        type: "array",
        items: {
          type: "object",
          properties: {
            name: {
              type: "string",
              "enum": [
                "perf",
                "sofria"
              ]
            },
            version: {
              description: "the semantic version of the constraint schema",
              type: "string"
            }
          },
          additionalProperties: false,
          required: [
            "name",
            "version"
          ]
        }
      }
    },
    required: [
      "structure",
      "structure_version",
      "constraints"
    ],
    additionalProperties: false
  },
  metadata: {
    description: "Metadata describing the document and the translation it belongs to",
    type: "object",
    properties: {
      translation: {
        type: "object",
        description: "Metadata concerning the translation to which the document belongs",
        properties: {
          tags: {
            description: "Tags attached to the translation",
            type: "array",
            items: {
              type: "string"
            }
          },
          properties: {
            type: "object",
            description: "Key/value properties attached to the translation",
            additionalProperties: {
              type: "string"
            }
          },
          selectors: {
            type: "object",
            description: "Proskomma selectors for the translation that, together, provide a primary key in the translation store",
            additionalProperties: {
              type: "string"
            }
          }
        },
        additionalProperties: {
          type: "string"
        },
        required: [
          "id"
        ]
      },
      document: {
        type: "object",
        description: "Metadata concerning the document itself",
        properties: {
          tags: {
            type: "array",
            description: "Tags attached to the document",
            items: {
              type: "string"
            }
          },
          properties: {
            type: "object",
            description: "Key/value properties attached to the document",
            additionalProperties: {
              type: "string"
            }
          },
          chapters: {
            type: "string",
            pattern: "^[1-9][0-9]*(-[1-9][0-9]*)?$"
          }
        },
        additionalProperties: {
          type: "string"
        }
      }
    },
    additionalProperties: false
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  },
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./sequence_structure.json"
    }
  },
  sequence: {
    $ref: "./sequence_structure.json"
  },
  main_sequence_id: {
    type: "string"
  }
};
const required$3 = [
  "schema",
  "metadata"
];
const additionalProperties$4 = false;
const then$3 = {
  required: [
    "sequences",
    "main_sequence_id"
  ],
  not: {
    required: [
      "sequence"
    ]
  }
};
const require$$27 = {
  $comment: $comment$2,
  $id: $id$d,
  title: title$5,
  description: description$5,
  type: type$d,
  properties: properties$a,
  required: required$3,
  additionalProperties: additionalProperties$4,
  "if": {
    properties: {
      schema: {
        type: "object",
        properties: {
          structure: {
            "enum": [
              "flat"
            ]
          }
        }
      }
    }
  },
  then: then$3,
  "else": {
    required: [
      "sequence"
    ],
    allOf: [
      {
        not: {
          required: [
            "sequences"
          ]
        }
      },
      {
        not: {
          required: [
            "main_sequence_id"
          ]
        }
      }
    ]
  }
};
const $id$c = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_4_0/sequence_structure.json";
const title$4 = "Sequence (Structure)";
const description$4 = "A sequence contains a 'flow' of one or more blocks";
const type$c = "object";
const properties$9 = {
  type: {
    description: "The type of sequence",
    type: "string"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label",
    type: "string"
  },
  blocks: {
    type: "array",
    description: "The blocks that, together, represent the 'flow' of the sequence",
    items: {
      $ref: "./block_structure.json"
    }
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  }
};
const required$2 = [
  "type"
];
const additionalProperties$3 = false;
const require$$28 = {
  $id: $id$c,
  title: title$4,
  description: description$4,
  type: type$c,
  properties: properties$9,
  required: required$2,
  additionalProperties: additionalProperties$3
};
const $id$b = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_4_0/block_structure.json";
const title$3 = "Block (Structure)";
const description$3 = "A block, which represents either a paragraph of text or a graft";
const type$b = "object";
const properties$8 = {
  type: {
    type: "string",
    description: "The type of block",
    "enum": [
      "paragraph",
      "row",
      "graft"
    ]
  },
  subtype: {
    description: "A type-specific subtype",
    type: "string"
  },
  target: {
    description: "The id of the sequence containing graft content",
    type: "string"
  },
  sequence: {
    description: "The sequence containing graft content",
    $ref: "./sequence_structure.json"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label for a graft",
    type: "string"
  },
  "new": {
    description: "If present and true, is interpreted as a request for the server to create a new graft",
    type: "boolean"
  },
  atts: {
    type: "object",
    description: "An object containing USFM attributes or subtype-specific additional information (such as the number of a verse or chapter). The value may be a boolean, a string or an array of strings",
    additionalProperties: {
      oneOf: [
        {
          type: "array",
          items: {
            type: "string"
          }
        },
        {
          type: "string"
        },
        {
          type: "boolean"
        }
      ]
    }
  },
  content: {
    type: "array",
    description: "The content of the block",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  }
};
const required$1 = [
  "type"
];
const additionalProperties$2 = false;
const then$2 = {
  required: [
    "content"
  ],
  allOf: [
    {
      not: {
        required: [
          "new"
        ]
      }
    },
    {
      not: {
        required: [
          "preview_text"
        ]
      }
    },
    {
      not: {
        required: [
          "target"
        ]
      }
    }
  ]
};
const require$$29 = {
  $id: $id$b,
  title: title$3,
  description: description$3,
  type: type$b,
  properties: properties$8,
  required: required$1,
  additionalProperties: additionalProperties$2,
  "if": {
    properties: {
      type: {
        "enum": [
          "paragraph",
          "row"
        ]
      }
    }
  },
  then: then$2,
  "else": {
    "if": {
      required: [
        "new"
      ],
      properties: {
        "new": {
          "enum": [
            true
          ]
        }
      }
    },
    then: {
      allOf: [
        {
          oneOf: [
            {
              required: [
                "subtype"
              ]
            },
            {
              required: [
                "sequence"
              ]
            }
          ]
        },
        {
          not: {
            required: [
              "target"
            ]
          }
        },
        {
          not: {
            required: [
              "preview_text"
            ]
          }
        },
        {
          not: {
            required: [
              "content"
            ]
          }
        }
      ]
    },
    "else": {
      oneOf: [
        {
          required: [
            "target"
          ]
        },
        {
          required: [
            "sequence"
          ]
        }
      ]
    }
  }
};
const $id$a = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_4_0/contentElement_structure.json";
const title$2 = "Content Element (Structure)";
const description$2 = "A content element, ie some form of (possibly nested) markup";
const type$a = "object";
const properties$7 = {
  type: {
    type: "string",
    description: "The type of element",
    "enum": [
      "mark",
      "wrapper",
      "start_milestone",
      "end_milestone",
      "graft"
    ]
  },
  subtype: {
    description: "The subtype of the element, which is context-dependent",
    type: "string"
  },
  atts: {
    type: "object",
    description: "An object containing USFM attributes or subtype-specific additional information (such as the number of a verse or chapter). The value may be a boolean, a string or an array of strings",
    additionalProperties: {
      oneOf: [
        {
          type: "array",
          items: {
            type: "string"
          }
        },
        {
          type: "string"
        },
        {
          type: "boolean"
        },
        {
          type: "number"
        }
      ]
    }
  },
  target: {
    type: "string",
    description: "The id of the sequence containing graft content"
  },
  sequence: {
    description: "The sequence containing graft content",
    $ref: "./sequence_structure.json"
  },
  preview_text: {
    description: "An optional field to provide some kind of printable label for a graft",
    type: "string"
  },
  "new": {
    type: "boolean",
    description: "If present and true, is interpreted as a request for the server to create a new graft"
  },
  content: {
    type: "array",
    description: "Nested content within the content element",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    description: "Non-Scripture content related to the content element, such as checking data or related resources",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./contentElement_structure.json"
        }
      ]
    }
  },
  hooks: {
    type: "array",
    $ref: "./hook_structure.json"
  }
};
const required = [
  "type"
];
const additionalProperties$1 = false;
const require$$30 = {
  $id: $id$a,
  title: title$2,
  description: description$2,
  type: type$a,
  properties: properties$7,
  required,
  additionalProperties: additionalProperties$1
};
const $id$9 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/structure/0_4_0/hook_structure.json";
const title$1 = "Hook (Structure)";
const description$1 = "Hooks, ie typed labels that may be used to link documents";
const type$9 = "array";
const items = {
  type: "array",
  items: [
    {
      type: "string",
      oneOf: [
        {
          "enum": [
            "bcv_ref",
            "book_ref"
          ]
        },
        {
          pattern: "^x-(app|publisher)-[a-z][a-z0-9]+-\\S{2,256}$"
        },
        {
          pattern: "^x-local-\\S{2,256}$"
        }
      ]
    },
    {
      type: "string",
      oneOf: [
        {
          "enum": [
            "label"
          ]
        },
        {
          pattern: "^\\w{1,255}$"
        }
      ]
    }
  ],
  minItems: 2,
  maxItems: 2
};
const require$$31 = {
  $id: $id$9,
  title: title$1,
  description: description$1,
  type: type$9,
  items
};
const $comment$1 = "version 0.3.0";
const $id$8 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/perf_document_constraint.json";
const type$8 = "object";
const properties$6 = {
  hooks: {
    type: "array"
  },
  sequences: {
    type: "object",
    propertyNames: {
      pattern: "^\\S+$"
    },
    additionalProperties: {
      $ref: "./perf_sequence_constraint.json"
    }
  }
};
const require$$32 = {
  $comment: $comment$1,
  $id: $id$8,
  type: type$8,
  properties: properties$6
};
const $id$7 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/perf_sequence_constraint.json";
const type$7 = "object";
const properties$5 = {
  type: {
    type: "string",
    "enum": [
      "main",
      "introduction",
      "intro_title",
      "intro_end_title",
      "title",
      "end_title",
      "heading",
      "remark",
      "sidebar",
      "table",
      "tree",
      "kv",
      "footnote",
      "note_caller",
      "xref",
      "pub_number",
      "alt_number",
      "esb_cat",
      "fig",
      "temp"
    ]
  },
  blocks: {
    type: "array",
    items: {
      $ref: "./perf_block_constraint.json"
    }
  }
};
const require$$33 = {
  $id: $id$7,
  type: type$7,
  properties: properties$5
};
const $id$6 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/perf_block_constraint.json";
const type$6 = "object";
const properties$4 = {
  type: {
    type: "string",
    "enum": [
      "paragraph",
      "graft",
      "row",
      "node",
      "lookup"
    ]
  },
  content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./perf_contentElement_constraint.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./perf_contentElement_constraint.json"
        }
      ]
    }
  }
};
const then$1 = {
  properties: {
    subtype: {
      "enum": [
        "introduction",
        "intro_title",
        "Intro_end_title",
        "title",
        "end_title",
        "heading",
        "remark",
        "sidebar",
        "table",
        "tree",
        "kv"
      ]
    }
  }
};
const require$$34 = {
  $id: $id$6,
  type: type$6,
  properties: properties$4,
  "if": {
    properties: {
      type: {
        "enum": [
          "graft"
        ]
      }
    }
  },
  then: then$1,
  "else": {
    "if": {
      properties: {
        type: {
          "enum": [
            "row"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "row:heading",
                "row:body"
              ]
            }
          ]
        }
      }
    },
    "else": {
      "if": {
        properties: {
          type: {
            "enum": [
              "node"
            ]
          }
        }
      },
      then: {
        properties: {
          subtype: {
            type: "string",
            oneOf: [
              {
                "enum": [
                  "node"
                ]
              },
              {
                pattern: "^x-\\S{1,256}$"
              }
            ]
          },
          atts: {
            type: "object",
            properties: {
              id: {
                type: "string"
              },
              parent: {
                type: "string"
              },
              children: {
                type: "array",
                items: {
                  type: "string"
                }
              }
            },
            required: [
              "id"
            ],
            additionalProperties: false
          }
        }
      },
      "else": {
        "if": {
          properties: {
            type: {
              "enum": [
                "lookup"
              ]
            }
          }
        },
        then: {
          properties: {
            subtype: {
              type: "string",
              oneOf: [
                {
                  "enum": [
                    "lookup"
                  ]
                },
                {
                  pattern: "^x-\\S{1,256}$"
                }
              ]
            },
            atts: {
              type: "object",
              properties: {
                primary: {
                  type: "string"
                },
                secondary: {
                  type: "array",
                  items: {
                    type: "string"
                  }
                }
              },
              required: [
                "primary"
              ],
              additionalProperties: false
            }
          }
        },
        "else": {
          properties: {
            subtype: {
              type: "string",
              oneOf: [
                {
                  pattern: "^usfm:"
                },
                {
                  pattern: "^x-\\S{1,256}$"
                }
              ]
            }
          }
        }
      }
    }
  }
};
const $id$5 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/perf_contentElement_constraint.json";
const type$5 = "object";
const allOf$1 = [
  {
    properties: {
      content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./perf_contentElement_constraint.json"
            }
          ]
        }
      },
      meta_content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./perf_contentElement_constraint.json"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "graft"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          "enum": [
            "footnote",
            "xref",
            "note_caller"
          ]
        }
      },
      allOf: [
        {
          not: {
            required: [
              "content"
            ]
          }
        },
        {
          not: {
            required: [
              "meta_content"
            ]
          }
        }
      ],
      "if": {
        required: [
          "new"
        ],
        properties: {
          "new": {
            "enum": [
              true
            ]
          }
        }
      },
      then: {
        not: {
          anyOf: [
            {
              required: [
                "target"
              ]
            },
            {
              required: [
                "preview_text"
              ]
            }
          ]
        }
      },
      "else": {
        required: [
          "target"
        ]
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "mark"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "chapter",
                "verses",
                "alt_chapter",
                "alt_verse",
                "pub_chapter",
                "pub_verse"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "chapter",
              "verses"
            ]
          }
        }
      },
      then: {
        type: "object",
        required: [
          "atts"
        ],
        properties: {
          atts: {
            type: "object",
            required: [
              "number"
            ],
            maxProperties: 1
          }
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "wrapper"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "meta_content"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "meta_content"
            ]
          }
        }
      },
      then: {
        not: {
          required: [
            "atts"
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "start_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "end_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      not: {
        required: [
          "atts"
        ]
      }
    }
  }
];
const require$$35 = {
  $id: $id$5,
  type: type$5,
  allOf: allOf$1
};
const $comment = "version 0.3.0";
const $id$4 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/sofria_document_constraint.json";
const type$4 = "object";
const properties$3 = {
  sequence: {
    $ref: "./sofria_sequence_constraint.json"
  }
};
const require$$36 = {
  $comment,
  $id: $id$4,
  type: type$4,
  properties: properties$3
};
const $id$3 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/sofria_sequence_constraint.json";
const type$3 = "object";
const properties$2 = {
  type: {
    type: "string",
    "enum": [
      "main",
      "introduction",
      "intro_title",
      "intro_end_title",
      "title",
      "end_title",
      "heading",
      "remark",
      "sidebar",
      "table",
      "tree",
      "kv",
      "footnote",
      "note_caller",
      "xref",
      "pub_number",
      "alt_number",
      "esb_cat",
      "fig",
      "temp"
    ]
  },
  blocks: {
    type: "array",
    items: {
      $ref: "./sofria_block_constraint.json"
    }
  }
};
const require$$37 = {
  $id: $id$3,
  type: type$3,
  properties: properties$2
};
const $id$2 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/sofria_block_constraint.json";
const type$2 = "object";
const properties$1 = {
  type: {
    type: "string",
    "enum": [
      "paragraph",
      "graft",
      "row"
    ]
  },
  content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./sofria_contentElement_constraint.json"
        }
      ]
    }
  },
  meta_content: {
    type: "array",
    items: {
      oneOf: [
        {
          type: "string"
        },
        {
          $ref: "./sofria_contentElement_constraint.json"
        }
      ]
    }
  }
};
const then = {
  properties: {
    subtype: {
      "enum": [
        "introduction",
        "intro_title",
        "Intro_end_title",
        "title",
        "end_title",
        "heading",
        "remark",
        "sidebar",
        "table",
        "tree",
        "kv"
      ]
    }
  }
};
const require$$38 = {
  $id: $id$2,
  type: type$2,
  properties: properties$1,
  "if": {
    properties: {
      type: {
        "enum": [
          "graft"
        ]
      }
    }
  },
  then,
  "else": {
    "if": {
      properties: {
        type: {
          "enum": [
            "row"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          "enum": [
            "usfm:tr",
            "pk"
          ]
        }
      }
    },
    "else": {
      properties: {
        subtype: {
          type: "string",
          pattern: "^usfm:"
        }
      }
    }
  }
};
const $id$1 = "https://github.com/Proskomma/proskomma-json-tools/tree/main/src/schema/constraint/0_4_0/sofria_contentElement_constraint.json";
const type$1 = "object";
const allOf = [
  {
    properties: {
      content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./sofria_contentElement_constraint.json"
            }
          ]
        }
      },
      meta_content: {
        type: "array",
        items: {
          oneOf: [
            {
              type: "string"
            },
            {
              $ref: "./sofria_contentElement_constraint.json"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "graft"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          "enum": [
            "footnote",
            "xref",
            "note_caller"
          ]
        }
      },
      allOf: [
        {
          not: {
            required: [
              "content"
            ]
          }
        },
        {
          not: {
            required: [
              "meta_content"
            ]
          }
        }
      ],
      "if": {
        required: [
          "new"
        ],
        properties: {
          "new": {
            "enum": [
              true
            ]
          }
        }
      },
      then: {
        not: {
          anyOf: [
            {
              required: [
                "blocks"
              ]
            },
            {
              required: [
                "preview_text"
              ]
            }
          ]
        }
      },
      "else": {
        required: [
          "sequence"
        ]
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "mark"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "chapter_label",
                "verses_label",
                "alt_chapter",
                "alt_verse",
                "pub_chapter",
                "pub_verse"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "chapter",
              "verses"
            ]
          }
        }
      },
      then: {
        type: "object",
        required: [
          "atts"
        ],
        properties: {
          atts: {
            type: "object",
            required: [
              "number"
            ],
            maxProperties: 1
          }
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "wrapper"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              "enum": [
                "meta_content",
                "chapter",
                "verses",
                "cell"
              ]
            },
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      "if": {
        properties: {
          subtype: {
            "enum": [
              "meta_content"
            ]
          }
        }
      },
      then: {
        not: {
          required: [
            "atts"
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "start_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      }
    }
  },
  {
    "if": {
      properties: {
        type: {
          "enum": [
            "end_milestone"
          ]
        }
      }
    },
    then: {
      properties: {
        subtype: {
          type: "string",
          oneOf: [
            {
              pattern: "^[A-Za-z][A-Za-z0-9]*:\\S+$"
            },
            {
              pattern: "^x-\\S+$"
            }
          ]
        }
      },
      not: {
        required: [
          "atts"
        ]
      }
    }
  }
];
const require$$39 = {
  $id: $id$1,
  type: type$1,
  allOf
};
const $id = "https://usfm-committee/usj.schema.json";
const title = "Unified Scripture JSON";
const description = "The JSON variant of USFM and USX data models";
const type = "object";
const $defs = {
  paraMarkerObject: {
    description: "Para-like content",
    type: "object",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "para"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          $ref: "#/$defs/inParaObject"
        }
      },
      sid: {
        description: "Indicates the Book-Chapter-Verse-like value",
        type: "string",
        pattern: "^[0-6A-Z]{3}( [1-9][0-9]{0,2}(:[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?)?)?$"
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  bookObject: {
    description: "Book object",
    type: "object",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "book"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        "const": "id"
      },
      code: {
        description: "The 3-letter book code in id element",
        pattern: "^[0-6A-Z]{3}$",
        type: "string"
      },
      content: {
        type: "array",
        items: {
          type: "string"
        }
      }
    },
    required: [
      "type",
      "marker",
      "code"
    ],
    additionalProperties: false
  },
  chapterObject: {
    description: "Chapter object",
    type: "object",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "chapter"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        "const": "c"
      },
      sid: {
        description: "Indicates the Book-Chapter-Verse-like value",
        type: "string",
        pattern: "^[0-6A-Z]{3}( [1-9][0-9]{0,2}(:[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?)?)?$"
      },
      number: {
        description: "Chapter number",
        type: "string",
        pattern: "^[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?$"
      },
      altnumber: {
        description: "Alternative chapter number",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      },
      pubnumber: {
        description: "Published characters as non-orthogonal attribute for USFM-incompatibility (mad and wrong)",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      }
    },
    required: [
      "type",
      "marker",
      "number"
    ],
    additionalProperties: false
  },
  sidebarObject: {
    type: "object",
    description: "Sidebar, which contains para-like content",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "sidebar"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        "const": "esb"
      },
      content: {
        type: "array",
        items: {
          $ref: "#/$defs/paraMarkerObject"
        }
      },
      category: {
        description: "Category of extended study bible sections",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  inParaObject: {
    description: "The set of thingeys that can appear inside a paragraph-like thingeys",
    anyOf: [
      {
        type: "string"
      },
      {
        $ref: "#/$defs/charMarkerObject"
      },
      {
        $ref: "#/$defs/verseObject"
      },
      {
        $ref: "#/$defs/milestoneObject"
      },
      {
        $ref: "#/$defs/figureObject"
      },
      {
        $ref: "#/$defs/noteObject"
      }
    ]
  },
  charMarkerObject: {
    type: "object",
    description: "Character-type content",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "enum": [
          "char",
          "whitespace",
          "row",
          "cell"
        ]
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          $ref: "#/$defs/inParaObject"
        }
      },
      "link-id": {
        description: "ID for link",
        type: "string"
      },
      "link-href": {
        description: "ID for link",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  noteObject: {
    type: "object",
    description: "A note",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "note"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          $ref: "#/$defs/inParaObject"
        }
      },
      caller: {
        description: "Caller character for footnotes and cross-refs",
        type: "string",
        pattern: "^[^ 	\n]$"
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  figureObject: {
    type: "object",
    description: "a figure object",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "figure"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          type: "string"
        }
      },
      file: {
        description: "The filename",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      },
      size: {
        description: "The file size",
        type: "string"
      },
      ref: {
        description: "The file ref",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  verseObject: {
    type: "object",
    description: "A verse number",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "verse"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      sid: {
        description: "Indicates the Book-Chapter-Verse-like value",
        type: "string",
        pattern: "^[0-6A-Z]{3}( [1-9][0-9]{0,2}(:[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?)?)?$"
      },
      number: {
        description: "Verse number",
        type: "string",
        pattern: "^[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?$"
      },
      altnumber: {
        description: "Alternative verse number",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      },
      pubnumber: {
        description: "Published characters as non-orthogonal attribute for USFM-incompatibility (mad and wrong)",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      }
    },
    required: [
      "type",
      "marker",
      "number"
    ],
    additionalProperties: false
  },
  milestoneObject: {
    type: "object",
    description: "Milestone (start or end marker)",
    properties: {
      type: {
        description: "The kind/category of node or element",
        type: "string",
        "const": "ms"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      sid: {
        description: "An id to distinguish milestones when using mad and wrong technology to process XML",
        type: "string",
        pattern: "^[^ 	\n](.*[^ 	\n])?$"
      },
      who: {
        description: "The speaker in an sp tag",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      },
      eid: {
        description: "The end milestone id",
        type: "string",
        pattern: "^[^ 	\r\n](.*[^ 	\r\n])?$"
      }
    },
    required: [
      "type",
      "marker"
    ],
    patternProperties: {
      "^x-": {
        type: "string"
      }
    },
    additionalProperties: false
  },
  tableObject: {
    type: "object",
    description: "A table, which contains rows",
    properties: {
      type: {
        description: "The kind/category of node or element this is, corresponding the USFM marker and USX node",
        type: "string",
        "const": "table"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          $ref: "#/$defs/rowObject"
        }
      },
      sid: {
        description: "Indicates the Book-Chapter-Verse value in the paragraph-based structure",
        type: "string",
        pattern: "(^[0-6A-Z]{3}( [1-9][0-9]{0,2}(:[1-9][0-9]{0,2}(-[1-9][0-9]{0,2})?)?)?$)|.*"
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  rowObject: {
    type: "object",
    description: "A table row which contains cells",
    properties: {
      type: {
        description: "The kind/category of node or element this is, corresponding the USFM marker and USX node",
        type: "string",
        "const": "row"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          anyOf: [
            {
              $ref: "#/$defs/cellObject"
            }
          ]
        }
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  },
  cellObject: {
    type: "object",
    description: "A table cell",
    properties: {
      type: {
        description: "The kind/category of node or element this is, corresponding the USFM marker and USX node",
        type: "string",
        "const": "cell"
      },
      marker: {
        description: "The corresponding marker in USFM or style in USX",
        type: "string",
        pattern: "^[^ 	\r\n]+$"
      },
      content: {
        type: "array",
        items: {
          $ref: "#/$defs/inParaObject"
        }
      },
      align: {
        description: "Alignment of table cells",
        type: "string",
        "enum": [
          "start",
          "end",
          "center"
        ]
      },
      colspan: {
        description: "Number of columns spanned by the cell",
        type: "integer",
        minimum: 1
      }
    },
    required: [
      "type",
      "marker"
    ],
    additionalProperties: false
  }
};
const properties = {
  type: {
    description: "The kind of node/element/marker this is",
    type: "string"
  },
  version: {
    description: "The USJ spec version",
    type: "string"
  },
  content: {
    description: "The JSON representation of scripture contents from USFM/USX",
    type: "array",
    items: {
      anyOf: [
        {
          $ref: "#/$defs/bookObject"
        },
        {
          $ref: "#/$defs/chapterObject"
        },
        {
          $ref: "#/$defs/paraMarkerObject"
        },
        {
          $ref: "#/$defs/tableObject"
        },
        {
          $ref: "#/$defs/sidebarObject"
        }
      ]
    }
  }
};
const additionalProperties = false;
const require$$40 = {
  $id,
  title,
  description,
  type,
  $defs,
  properties,
  additionalProperties
};
var Ajv = ajvExports;
var succinctSchema_0_2_0 = require$$1$2;
var documentStructureSchema_0_2_1 = require$$2$1;
var sequenceStructureSchema_0_2_1 = require$$3$1;
var blockStructureSchema_0_2_1 = require$$4$1;
var contentElementStructureSchema_0_2_1 = require$$5$1;
var perfDocumentConstraintSchema_0_2_1 = require$$6$1;
var perfSequenceConstraintSchema_0_2_1 = require$$7$1;
var perfBlockConstraintSchema_0_2_1 = require$$8;
var perfContentElementConstraintSchema_0_2_1 = require$$9;
var sofriaDocumentConstraintSchema_0_2_1 = require$$10;
var sofriaSequenceConstraintSchema_0_2_1 = require$$11;
var sofriaBlockConstraintSchema_0_2_1 = require$$12;
var sofriaContentElementConstraintSchema_0_2_1 = require$$13;
var documentStructureSchema_0_3_0 = require$$14;
var sequenceStructureSchema_0_3_0 = require$$15;
var blockStructureSchema_0_3_0 = require$$16;
var contentElementStructureSchema_0_3_0 = require$$17;
var hookStructureSchema_0_3_0 = require$$18;
var perfDocumentConstraintSchema_0_3_0 = require$$19;
var perfSequenceConstraintSchema_0_3_0 = require$$20;
var perfBlockConstraintSchema_0_3_0 = require$$21;
var perfContentElementConstraintSchema_0_3_0 = require$$22;
var sofriaDocumentConstraintSchema_0_3_0 = require$$23;
var sofriaSequenceConstraintSchema_0_3_0 = require$$24;
var sofriaBlockConstraintSchema_0_3_0 = require$$25;
var sofriaContentElementConstraintSchema_0_3_0 = require$$26;
var documentStructureSchema_0_4_0 = require$$27;
var sequenceStructureSchema_0_4_0 = require$$28;
var blockStructureSchema_0_4_0 = require$$29;
var contentElementStructureSchema_0_4_0 = require$$30;
var hookStructureSchema_0_4_0 = require$$31;
var perfDocumentConstraintSchema_0_4_0 = require$$32;
var perfSequenceConstraintSchema_0_4_0 = require$$33;
var perfBlockConstraintSchema_0_4_0 = require$$34;
var perfContentElementConstraintSchema_0_4_0 = require$$35;
var sofriaDocumentConstraintSchema_0_4_0 = require$$36;
var sofriaSequenceConstraintSchema_0_4_0 = require$$37;
var sofriaBlockConstraintSchema_0_4_0 = require$$38;
var sofriaContentElementConstraintSchema_0_4_0 = require$$39;
var usjSchema_0_2_4 = require$$40;
let Validator$1 = class Validator {
  constructor() {
    this.schema = {
      structure: {},
      constraint: {},
      proskomma: {},
      usj: {}
    };
    for (var [key, schemaOb] of [["succinct", {
      "0.2.0": [{
        "name": "Proskomma Serialized Succinct",
        "validator": new Ajv().compile(succinctSchema_0_2_0)
      }]
    }]]) {
      this.schema.proskomma[key] = schemaOb;
    }
    for (var [_key, _schemaOb] of [["document", {
      "0.2.1": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(contentElementStructureSchema_0_2_1).addSchema(blockStructureSchema_0_2_1).addSchema(sequenceStructureSchema_0_2_1).compile(documentStructureSchema_0_2_1)
      }],
      "0.3.0": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(contentElementStructureSchema_0_3_0).addSchema(blockStructureSchema_0_3_0).addSchema(sequenceStructureSchema_0_3_0).compile(documentStructureSchema_0_3_0)
      }],
      "0.4.0": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(contentElementStructureSchema_0_4_0).addSchema(blockStructureSchema_0_4_0).addSchema(sequenceStructureSchema_0_4_0).compile(documentStructureSchema_0_4_0)
      }]
    }], ["sequence", {
      "0.2.1": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(contentElementStructureSchema_0_2_1).addSchema(blockStructureSchema_0_2_1).compile(sequenceStructureSchema_0_2_1)
      }],
      "0.3.0": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(contentElementStructureSchema_0_3_0).addSchema(blockStructureSchema_0_3_0).compile(sequenceStructureSchema_0_3_0)
      }],
      "0.4.0": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(contentElementStructureSchema_0_4_0).addSchema(blockStructureSchema_0_4_0).compile(sequenceStructureSchema_0_4_0)
      }]
    }]]) {
      this.schema.structure[_key] = _schemaOb;
    }
    for (var [_key2, _schemaOb2] of [["perfDocument", {
      "0.2.1": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(contentElementStructureSchema_0_2_1).addSchema(blockStructureSchema_0_2_1).addSchema(sequenceStructureSchema_0_2_1).compile(documentStructureSchema_0_2_1)
      }, {
        "name": "PERF Document",
        "validator": new Ajv().addSchema(perfContentElementConstraintSchema_0_2_1).addSchema(perfBlockConstraintSchema_0_2_1).addSchema(perfSequenceConstraintSchema_0_2_1).compile(perfDocumentConstraintSchema_0_2_1)
      }],
      "0.3.0": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(contentElementStructureSchema_0_3_0).addSchema(blockStructureSchema_0_3_0).addSchema(sequenceStructureSchema_0_3_0).compile(documentStructureSchema_0_3_0)
      }, {
        "name": "PERF Document",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(perfContentElementConstraintSchema_0_3_0).addSchema(perfBlockConstraintSchema_0_3_0).addSchema(perfSequenceConstraintSchema_0_3_0).compile(perfDocumentConstraintSchema_0_3_0)
      }],
      "0.4.0": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(contentElementStructureSchema_0_4_0).addSchema(blockStructureSchema_0_4_0).addSchema(sequenceStructureSchema_0_4_0).compile(documentStructureSchema_0_4_0)
      }, {
        "name": "PERF Document",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(perfContentElementConstraintSchema_0_4_0).addSchema(perfBlockConstraintSchema_0_4_0).addSchema(perfSequenceConstraintSchema_0_4_0).compile(perfDocumentConstraintSchema_0_4_0)
      }]
    }], ["perfSequence", {
      "0.2.1": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(contentElementStructureSchema_0_2_1).addSchema(blockStructureSchema_0_2_1).compile(sequenceStructureSchema_0_2_1)
      }, {
        "name": "PERF Sequence",
        "validator": new Ajv().addSchema(perfContentElementConstraintSchema_0_2_1).addSchema(perfBlockConstraintSchema_0_2_1).compile(perfSequenceConstraintSchema_0_2_1)
      }],
      "0.3.0": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(contentElementStructureSchema_0_3_0).addSchema(blockStructureSchema_0_3_0).compile(sequenceStructureSchema_0_3_0)
      }, {
        "name": "PERF Sequence",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(perfContentElementConstraintSchema_0_3_0).addSchema(perfBlockConstraintSchema_0_3_0).compile(perfSequenceConstraintSchema_0_3_0)
      }],
      "0.4.0": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(contentElementStructureSchema_0_4_0).addSchema(blockStructureSchema_0_4_0).compile(sequenceStructureSchema_0_4_0)
      }, {
        "name": "PERF Sequence",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(perfContentElementConstraintSchema_0_4_0).addSchema(perfBlockConstraintSchema_0_4_0).compile(perfSequenceConstraintSchema_0_4_0)
      }]
    }], ["sofriaDocument", {
      "0.2.1": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(contentElementStructureSchema_0_2_1).addSchema(blockStructureSchema_0_2_1).addSchema(sequenceStructureSchema_0_2_1).compile(documentStructureSchema_0_2_1)
      }, {
        "name": "SOFRIA Document",
        "validator": new Ajv().addSchema(sofriaContentElementConstraintSchema_0_2_1).addSchema(sofriaBlockConstraintSchema_0_2_1).addSchema(sofriaSequenceConstraintSchema_0_2_1).compile(sofriaDocumentConstraintSchema_0_2_1)
      }],
      "0.3.0": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(contentElementStructureSchema_0_3_0).addSchema(blockStructureSchema_0_3_0).addSchema(sequenceStructureSchema_0_3_0).compile(documentStructureSchema_0_3_0)
      }, {
        "name": "SOFRIA Document",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(sofriaContentElementConstraintSchema_0_3_0).addSchema(sofriaBlockConstraintSchema_0_3_0).addSchema(sofriaSequenceConstraintSchema_0_3_0).compile(sofriaDocumentConstraintSchema_0_3_0)
      }],
      "0.4.0": [{
        "name": "Document Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(contentElementStructureSchema_0_4_0).addSchema(blockStructureSchema_0_4_0).addSchema(sequenceStructureSchema_0_4_0).compile(documentStructureSchema_0_4_0)
      }, {
        "name": "SOFRIA Document",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(sofriaContentElementConstraintSchema_0_4_0).addSchema(sofriaBlockConstraintSchema_0_4_0).addSchema(sofriaSequenceConstraintSchema_0_4_0).compile(sofriaDocumentConstraintSchema_0_4_0)
      }]
    }], ["sofriaSequence", {
      "0.2.1": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(contentElementStructureSchema_0_2_1).addSchema(blockStructureSchema_0_2_1).compile(sequenceStructureSchema_0_2_1)
      }, {
        "name": "SOFRIA Sequence",
        "validator": new Ajv().addSchema(sofriaContentElementConstraintSchema_0_2_1).addSchema(sofriaBlockConstraintSchema_0_2_1).compile(sofriaSequenceConstraintSchema_0_2_1)
      }],
      "0.3.0": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(contentElementStructureSchema_0_3_0).addSchema(blockStructureSchema_0_3_0).compile(sequenceStructureSchema_0_3_0)
      }, {
        "name": "SOFRIA Sequence",
        "validator": new Ajv().addSchema(hookStructureSchema_0_3_0).addSchema(sofriaContentElementConstraintSchema_0_3_0).addSchema(sofriaBlockConstraintSchema_0_3_0).compile(sofriaSequenceConstraintSchema_0_3_0)
      }],
      "0.4.0": [{
        "name": "Sequence Structure",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(contentElementStructureSchema_0_4_0).addSchema(blockStructureSchema_0_4_0).compile(sequenceStructureSchema_0_4_0)
      }, {
        "name": "SOFRIA Sequence",
        "validator": new Ajv().addSchema(hookStructureSchema_0_4_0).addSchema(sofriaContentElementConstraintSchema_0_4_0).addSchema(sofriaBlockConstraintSchema_0_4_0).compile(sofriaSequenceConstraintSchema_0_4_0)
      }]
    }]]) {
      this.schema.constraint[_key2] = _schemaOb2;
    }
    for (var [_key3, _schemaOb3] of [["structure", {
      "0.2.4": [{
        "name": "Unified Scripture JSON",
        "validator": new Ajv().compile(usjSchema_0_2_4)
      }]
    }]]) {
      this.schema.usj[_key3] = _schemaOb3;
    }
  }
  schemaInfo() {
    var ret = {};
    for (var [schemaType, schemas] of Object.entries(this.schema)) {
      ret[schemaType] = {};
      for (var [schemaLabel, schemaVersions] of Object.entries(schemas)) {
        ret[schemaType][schemaLabel] = {};
        for (var [version2, versionSteps] of Object.entries(schemaVersions)) {
          ret[schemaType][schemaLabel][version2] = versionSteps.map((vs) => vs.name);
        }
      }
    }
    return ret;
  }
  validate(schemaType, schemaKey, schemaVersion, data) {
    if (data === void 0) {
      throw new Error("data argument is missing. Usage: validate(schemaType, schemaKey, schemaVersion, data)");
    }
    if (data === null) {
      throw new Error("Data argument is null");
    }
    var knownSchemaTypes = Object.keys(this.schema);
    if (!knownSchemaTypes.includes(schemaType)) {
      throw new Error("Schema type must be one of ".concat(knownSchemaTypes.map((s) => "'".concat(s, "'")).join(", "), ", not '").concat(schemaType, "'"));
    }
    if (!this.schema[schemaType][schemaKey]) {
      throw new Error("Unknown ".concat(schemaType, " schema key ").concat(schemaKey));
    }
    if (!this.schema[schemaType][schemaKey][schemaVersion]) {
      throw new Error("Unknown version ".concat(schemaVersion, " for ").concat(schemaType, " schema key ").concat(schemaKey));
    }
    var validators = this.schema[schemaType][schemaKey][schemaVersion];
    var result;
    for (var {
      name: validatorName,
      validator: validator2
    } of validators) {
      result = {
        validatorName,
        isValid: validator2(data),
        errors: validator2.errors
      };
      if (!result.isValid) {
        break;
      }
    }
    return {
      requested: {
        schemaType,
        schemaKey,
        schemaVersion
      },
      lastSchema: result.validatorName,
      isValid: result.isValid,
      errors: result.errors
    };
  }
};
var validator = Validator$1;
var characterTags = ["qs", "qac", "litl", "lik", "liv", "fr", "fq", "fqa", "fk", "fl", "fw", "fp", "fv", "ft", "fdc", "fm", "xo", "xk", "xq", "xt", "xta", "xop", "xot", "xnt", "xdc", "rq", "add", "bk", "dc", "k", "nd", "ord", "pn", "png", "qt", "sig", "sls", "tl", "wj", "em", "bd", "it", "bdit", "no", "sc", "sup", "ior", "iqt", "th", "thr", "tc", "tcr"];
var headingTags = ["ms", "mr", "s", "sr", "r", "qa", "sp", "sd"];
var bodyTags = ["cd", "p", "m", "po", "pr", "cls", "pmo", "pm", "pmc", "pmr", "pi", "mi", "nb", "pc", "ph", "b", "q", "qr", "qc", "qa", "qm", "qd", "lh", "li", "lf", "lim", "d"];
var introHeadingTags = ["imt", "is", "imte"];
var introBodyTags = ["ip", "ipi", "im", "imi", "ipq", "imq", "ipr", "iq", "ib", "ili", "iot", "io", "iex"];
var usfmHelps$1 = {
  characterTags,
  bodyTags,
  headingTags,
  introHeadingTags,
  introBodyTags
};
const require$$1$1 = /* @__PURE__ */ getAugmentedNamespace(src);
var xre$2 = require$$1$1;
var flattenZalns = (vos) => {
  var ret = [];
  for (var vo of vos) {
    if (vo.tag && vo.tag === "zaln") {
      if (vo.children[0].tag === "w") {
        ret.push(vo);
      } else {
        var childZalns = flattenZalns(vo.children);
        var payload = childZalns[childZalns.length - 1].children;
        for (var childZaln of [vo, ...childZalns]) {
          childZaln.children = payload;
          ret.push(childZaln);
        }
      }
    }
  }
  return ret;
};
var wordsFromString = (s) => {
  var wordlikeRE = xre$2("([\\p{Letter}\\p{Number}\\p{Mark}\\u2060]{1,127})");
  return xre$2.match(s, wordlikeRE, "all");
};
var firstWordFromString = (s) => {
  var words = wordsFromString(s);
  return words[0];
};
var lastWordFromString = (s) => {
  var words = wordsFromString(s);
  return words[words.length - 1];
};
var alignmentLookupFromUsfmJs = (usfmJs) => {
  var ret = {};
  for (var [chapterN, chapter] of Object.entries(usfmJs.chapters)) {
    ret[chapterN] = {};
    for (var [verseN, verse] of Object.entries(chapter)) {
      ret[chapterN][verseN] = {
        "before": {},
        "after": {}
      };
      for (var verseObject of flattenZalns(verse.verseObjects)) {
        var startAlignmentKey = "".concat(firstWordFromString(verseObject.children[0].text), "_").concat(verseObject.children[0].occurrence);
        if (!(startAlignmentKey in ret[chapterN][verseN]["before"])) {
          ret[chapterN][verseN]["before"][startAlignmentKey] = [];
        }
        var vo = {
          strong: verseObject.strong,
          lemma: verseObject.lemma,
          morph: verseObject.morph,
          occurrence: verseObject.occurrence,
          occurrences: verseObject.occurrences,
          content: verseObject.content
        };
        ret[chapterN][verseN]["before"][startAlignmentKey].push(vo);
        var endAlignmentKey = "".concat(lastWordFromString(verseObject.children[verseObject.children.length - 1].text), "_").concat(verseObject.children[verseObject.children.length - 1].occurrence);
        if (!(endAlignmentKey in ret[chapterN][verseN]["after"])) {
          ret[chapterN][verseN]["after"][endAlignmentKey] = [];
        }
        vo = {
          strong: verseObject.strong,
          lemma: verseObject.lemma,
          morph: verseObject.morph,
          occurrence: verseObject.occurrence,
          occurrences: verseObject.occurrences,
          content: verseObject.content
        };
        ret[chapterN][verseN]["after"][endAlignmentKey].unshift(vo);
      }
    }
  }
  return ret;
};
var usfmJsHelps$2 = {
  alignmentLookupFromUsfmJs
};
var _xregexp$2 = _interopRequireDefault$f(require$$1$1);
function _interopRequireDefault$f(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var verseWordsActions$2 = {
  startDocument: [{
    description: "Set up storage",
    test: () => true,
    action: (_ref) => {
      var {
        workspace,
        output
      } = _ref;
      workspace.verseContent = [];
      workspace.chapter = null;
      workspace.verses = null;
      output.cv = {};
    }
  }],
  mark: [{
    description: "Update CV state",
    test: () => true,
    action: (_ref2) => {
      var {
        context,
        workspace,
        output
      } = _ref2;
      var {
        element
      } = context.sequences[0];
      if (element.subType === "chapter") {
        workspace.chapter = element.atts["number"];
        workspace.verses = 0;
        if (output.cv[workspace.chapter]) {
          throw new Error("Duplicate chapter ".concat(workspace.chapter, " in verseWords"));
        }
        output.cv[workspace.chapter] = {};
        output.cv[workspace.chapter][workspace.verses] = {};
      } else if (element.subType === "verses") {
        workspace.verses = element.atts["number"];
        if (output.cv[workspace.chapter][workspace.verses]) {
          throw new Error("Duplicate verse ".concat(workspace.chapter, ":").concat(workspace.verses, " in verseWords"));
        }
        output.cv[workspace.chapter][workspace.verses] = {};
      }
    }
  }],
  text: [{
    description: "Log occurrences",
    test: () => true,
    action: (_ref3) => {
      var {
        context,
        workspace,
        output
      } = _ref3;
      var {
        chapter,
        verses
      } = workspace;
      var {
        text
      } = context.sequences[0].element;
      var re2 = (0, _xregexp$2.default)("([\\p{Letter}\\p{Number}\\p{Mark}\\u2060]{1,127})");
      var words = _xregexp$2.default.match(text, re2, "all");
      for (var word of words) {
        var _output$cv$chapter$ve, _output$cv$chapter$ve2;
        (_output$cv$chapter$ve2 = (_output$cv$chapter$ve = output.cv[chapter][verses])[word]) !== null && _output$cv$chapter$ve2 !== void 0 ? _output$cv$chapter$ve2 : _output$cv$chapter$ve[word] = 0;
        output.cv[chapter][verses][word] += 1;
      }
    }
  }]
};
var verseWords$2 = {
  verseWordsActions: verseWordsActions$2
};
var _xregexp$1 = _interopRequireDefault$e(require$$1$1);
function _interopRequireDefault$e(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
function ownKeys$5(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$5(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys$5(Object(t), true).forEach(function(r2) {
      _defineProperty$5(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$5(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty$5(obj, key, value) {
  key = _toPropertyKey$5(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey$5(arg) {
  var key = _toPrimitive$5(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive$5(input, hint) {
  if (typeof input !== "object" || input === null)
    return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object")
      return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var stripMarkupActions$2 = {
  startDocument: [{
    description: "Set up",
    test: () => true,
    action: (_ref) => {
      var {
        workspace,
        output
      } = _ref;
      workspace.chapter = null;
      workspace.verses = null;
      workspace.lastWord = "";
      workspace.waitingMarkup = [];
      workspace.currentOccurrences = {};
      workspace.PendingStartMilestones = [];
      output.stripped = {};
      output.unalignedWords = {};
      return true;
    }
  }],
  startMilestone: [{
    description: "Ignore zaln startMilestone events",
    test: (_ref2) => {
      var {
        context
      } = _ref2;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: (_ref3) => {
      var {
        context,
        workspace
      } = _ref3;
      var payload = context.sequences[0].element;
      payload.subtype = payload.subType;
      delete payload.subType;
      workspace.waitingMarkup.push(payload);
      workspace.PendingStartMilestones.push(payload);
    }
  }],
  endMilestone: [{
    description: "Ignore zaln endMilestone events",
    test: (_ref4) => {
      var {
        context
      } = _ref4;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: (_ref5) => {
      var {
        context,
        workspace,
        output,
        config
      } = _ref5;
      var {
        chapter,
        verses,
        lastWord: word
      } = workspace;
      var {
        verseWords: totalOccurrences
      } = config;
      var strippedKey = ["after", word, workspace.currentOccurrences[word], totalOccurrences[chapter][verses][word]].join("--");
      var payload = _objectSpread$5({}, context.sequences[0].element);
      payload.subtype = payload.subType;
      delete payload.subType;
      var record = {
        chapter,
        verses,
        occurrence: workspace.currentOccurrences[word],
        occurrences: totalOccurrences[chapter][verses][word],
        position: "after",
        word,
        payload,
        startMilestone: workspace.PendingStartMilestones.shift()
      };
      if (!output.stripped[workspace.chapter][workspace.verses][strippedKey]) {
        output.stripped[workspace.chapter][workspace.verses][strippedKey] = [record];
      } else {
        output.stripped[workspace.chapter][workspace.verses][strippedKey].push(record);
      }
      return false;
    }
  }],
  startWrapper: [{
    description: "Ignore w startWrapper events",
    test: (_ref6) => {
      var {
        context
      } = _ref6;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: (_ref7) => {
      var {
        context,
        workspace
      } = _ref7;
      var payload = _objectSpread$5({}, context.sequences[0].element);
      payload.subtype = payload.subType;
      delete payload.subType;
      workspace.waitingMarkup.push(payload);
    }
  }],
  endWrapper: [{
    description: "Ignore w endWrapper events",
    test: (_ref8) => {
      var {
        context
      } = _ref8;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: (_ref9) => {
    }
  }],
  text: [{
    description: "Log occurrences",
    test: () => true,
    action: (_ref10) => {
      var {
        context,
        workspace,
        output,
        config
      } = _ref10;
      try {
        var sequence = context.sequences[0];
        if (sequence.type !== "main")
          return true;
        var text = sequence.element.text;
        var re2 = (0, _xregexp$1.default)("([\\p{Letter}\\p{Number}\\p{Mark}\\u2060]{1,127})");
        var words = _xregexp$1.default.match(text, re2, "all");
        var {
          chapter,
          verses
        } = workspace;
        var {
          verseWords: totalOccurrences
        } = config;
        for (var word of words) {
          var _workspace$currentOcc, _workspace$currentOcc2;
          (_workspace$currentOcc2 = (_workspace$currentOcc = workspace.currentOccurrences)[word]) !== null && _workspace$currentOcc2 !== void 0 ? _workspace$currentOcc2 : _workspace$currentOcc[word] = 0;
          workspace.currentOccurrences[word]++;
          if (!workspace.PendingStartMilestones.length && workspace.waitingMarkup.length) {
            var _output$unalignedWord, _output$unalignedWord2, _output$unalignedWord3, _output$unalignedWord4;
            (_output$unalignedWord2 = (_output$unalignedWord = output.unalignedWords)[chapter]) !== null && _output$unalignedWord2 !== void 0 ? _output$unalignedWord2 : _output$unalignedWord[chapter] = {};
            (_output$unalignedWord4 = (_output$unalignedWord3 = output.unalignedWords[chapter])[verses]) !== null && _output$unalignedWord4 !== void 0 ? _output$unalignedWord4 : _output$unalignedWord3[verses] = [];
            output.unalignedWords[chapter][verses].push({
              word,
              occurrence: workspace.currentOccurrences[word],
              totalOccurrences: totalOccurrences[chapter][verses][word]
            });
          }
          while (workspace.waitingMarkup.length) {
            var payload = workspace.waitingMarkup.shift();
            var strippedKey = ["before", word, workspace.currentOccurrences[word], totalOccurrences[chapter][verses][word]].join("--");
            var record = {
              chapter,
              verses,
              occurrence: workspace.currentOccurrences[word],
              occurrences: totalOccurrences[chapter][verses][word],
              position: "before",
              word,
              payload: _objectSpread$5(_objectSpread$5({}, payload), payload.subtype === "usfm:w" && {
                content: [word]
              })
            };
            if (!output.stripped[workspace.chapter][workspace.verses][strippedKey]) {
              output.stripped[workspace.chapter][workspace.verses][strippedKey] = [record];
            } else {
              output.stripped[workspace.chapter][workspace.verses][strippedKey].push(record);
            }
          }
          workspace.lastWord = word;
        }
      } catch (err) {
        console.error(err);
        throw err;
      }
      return true;
    }
  }],
  mark: [{
    description: "Update CV state",
    test: () => true,
    action: (_ref11) => {
      var {
        context,
        workspace,
        output
      } = _ref11;
      try {
        var element = context.sequences[0].element;
        if (element.subType === "chapter") {
          workspace.chapter = element.atts["number"];
          workspace.verses = 0;
          workspace.lastWord = "";
          workspace.currentOccurrences = {};
          output.stripped[workspace.chapter] = {};
          output.stripped[workspace.chapter][workspace.verses] = {};
        } else if (element.subType === "verses") {
          workspace.verses = element.atts["number"];
          workspace.lastWord = "";
          workspace.currentOccurrences = {};
          output.stripped[workspace.chapter][workspace.verses] = {};
        }
      } catch (err) {
        console.error(err);
        throw err;
      }
      return true;
    }
  }]
};
var stripAlignment$2 = {
  stripMarkupActions: stripMarkupActions$2
};
var _xregexp = _interopRequireDefault$d(require$$1$1);
function _interopRequireDefault$d(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var lexingRegexes$1 = [["printable", "wordLike", (0, _xregexp.default)("([\\p{Letter}\\p{Number}\\p{Mark}\\u2060]{1,127})")], ["printable", "lineSpace", (0, _xregexp.default)("([\\p{Separator}	]{1,127})")], ["printable", "punctuation", (0, _xregexp.default)("([\\p{Punctuation}\\p{Math_Symbol}\\p{Currency_Symbol}\\p{Modifier_Symbol}\\p{Other_Symbol}])")], ["bad", "unknown", (0, _xregexp.default)("(.)")]];
var re = _xregexp.default.union(lexingRegexes$1.map((x) => x[2]));
var endMilestone = {
  type: "end_milestone",
  subtype: "usfm:zaln"
};
var mergeAlignmentActions$2 = {
  startDocument: [{
    description: "setup",
    test: () => true,
    action: (_ref) => {
      var {
        workspace,
        output
      } = _ref;
      workspace.chapter = null;
      workspace.verses = null;
      workspace.currentOccurrences = {};
      output.unalignedWords = {};
      return true;
    }
  }],
  text: [{
    description: "add-to-text",
    test: () => true,
    action: (_ref2) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref2;
      try {
        let pushOnHoldChars = function() {
          while (onHoldChars.length) {
            workspace.outputContentStack[0].push(onHoldChars.shift());
          }
        };
        var sequence = context.sequences[0];
        if (sequence.type !== "main")
          return true;
        var text = context.sequences[0].element.text;
        var words = _xregexp.default.match(text, re, "all");
        var {
          chapter,
          verses
        } = workspace;
        if (!verses)
          return true;
        var {
          totalOccurrences,
          strippedAlignment
        } = config;
        var alignments = {
          opened: null
        };
        var addWrappers = (_ref3) => {
          var {
            subtype,
            content = [],
            atts = {}
          } = _ref3;
          if (Object.keys(atts).length > 0) {
            return {
              type: "wrapper",
              subtype,
              content,
              atts
            };
          }
          return {
            type: "wrapper",
            subtype,
            content
          };
        };
        var onHoldChars = [];
        var _loop = function _loop2(word2) {
          var _xre$match, _workspace$currentOcc, _workspace$currentOcc2;
          var isWord = (_xre$match = _xregexp.default.match(word2, lexingRegexes$1[0][2], "all")) === null || _xre$match === void 0 ? void 0 : _xre$match.length;
          if (!isWord) {
            onHoldChars.push(word2);
            return 1;
          }
          (_workspace$currentOcc2 = (_workspace$currentOcc = workspace.currentOccurrences)[word2]) !== null && _workspace$currentOcc2 !== void 0 ? _workspace$currentOcc2 : _workspace$currentOcc[word2] = 0;
          workspace.currentOccurrences[word2]++;
          var strippedKey = (position) => {
            return [position, word2, workspace.currentOccurrences[word2], totalOccurrences[chapter][verses][word2]].join("--");
          };
          var markupChapter = strippedAlignment[chapter];
          var markup = markupChapter ? markupChapter[verses] || {} : {};
          var skipStartMilestone = false;
          var afterWord = markup[strippedKey("after")];
          var beforeWord = markup[strippedKey("before")];
          if (beforeWord !== null && beforeWord !== void 0 && beforeWord.length)
            pushOnHoldChars();
          if (afterWord !== null && afterWord !== void 0 && afterWord.length && !alignments.opened) {
            afterWord.map((_ref4) => {
              var {
                startMilestone
              } = _ref4;
              return workspace.outputContentStack[0].push(startMilestone);
            });
            skipStartMilestone = true;
          }
          beforeWord === null || beforeWord === void 0 || beforeWord.forEach((_ref5) => {
            var {
              payload
            } = _ref5;
            if (payload.type !== "start_milestone") {
              workspace.outputContentStack[0].push(payload);
            }
            if (payload.type === "start_milestone" && !skipStartMilestone) {
              workspace.outputContentStack[0].push(payload);
              alignments.opened = true;
            }
          });
          afterWord === null || afterWord === void 0 || afterWord.forEach((_ref6) => {
            var {
              payload
            } = _ref6;
            alignments.opened = false;
            workspace.outputContentStack[0].push(payload);
          });
          if (!(beforeWord !== null && beforeWord !== void 0 && beforeWord.length)) {
            var _output$unalignedWord, _output$unalignedWord2, _output$unalignedWord3, _output$unalignedWord4;
            if (alignments.opened) {
              workspace.outputContentStack[0].push(endMilestone);
              alignments.opened = false;
            }
            pushOnHoldChars();
            (_output$unalignedWord2 = (_output$unalignedWord = output.unalignedWords)[chapter]) !== null && _output$unalignedWord2 !== void 0 ? _output$unalignedWord2 : _output$unalignedWord[chapter] = {};
            (_output$unalignedWord4 = (_output$unalignedWord3 = output.unalignedWords[chapter])[verses]) !== null && _output$unalignedWord4 !== void 0 ? _output$unalignedWord4 : _output$unalignedWord3[verses] = [];
            output.unalignedWords[workspace.chapter][workspace.verses].push({
              word: word2,
              occurrence: workspace.currentOccurrences[word2],
              totalOccurrences: totalOccurrences[chapter][verses][word2]
            });
            var wrappedWord = addWrappers({
              subtype: "usfm:w",
              content: [word2]
            });
            workspace.outputContentStack[0].push(wrappedWord);
          }
        };
        for (var word of words) {
          if (_loop(word))
            continue;
        }
        pushOnHoldChars();
        return false;
      } catch (err) {
        console.error(err);
        throw err;
      }
    }
  }],
  mark: [{
    description: "mark-chapters",
    test: (_ref7) => {
      var {
        context
      } = _ref7;
      return context.sequences[0].element.subType === "chapter";
    },
    action: (_ref8) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref8;
      var element = context.sequences[0].element;
      workspace.chapter = element.atts["number"];
      workspace.verses = 0;
      return true;
    }
  }, {
    description: "mark-verses",
    test: (_ref9) => {
      var {
        context
      } = _ref9;
      return context.sequences[0].element.subType === "verses";
    },
    action: (_ref10) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref10;
      var element = context.sequences[0].element;
      workspace.verses = element.atts["number"];
      workspace.currentOccurrences = {};
      return true;
    }
  }]
};
var mergeAlignement = {
  mergeAlignmentActions: mergeAlignmentActions$2
};
var {
  verseWordsActions: verseWordsActions$1
} = verseWords$2;
var {
  stripMarkupActions: stripMarkupActions$1
} = stripAlignment$2;
var {
  mergeAlignmentActions: mergeAlignmentActions$1
} = mergeAlignement;
var renderActions$b = {
  verseWordsActions: verseWordsActions$1,
  stripMarkupActions: stripMarkupActions$1,
  mergeAlignmentActions: mergeAlignmentActions$1
};
let ProskommaRenderAction$1 = class ProskommaRenderAction {
  constructor(ob) {
    if (!ob) {
      throw new Error("Must provide a constructor object to constructor");
    }
    this.description = ob.description ? ob.description : (() => {
      throw new Error("Must provide a description in constructor object");
    })();
    this.test = ob.test || (() => true);
    this.action = ob.action || (() => null);
  }
};
var ProskommaRenderAction_1 = ProskommaRenderAction$1;
var ProskommaRenderAction2 = ProskommaRenderAction_1;
let ProskommaRender$5 = class ProskommaRender {
  constructor(spec) {
    if (this.constructor === ProskommaRender) {
      throw new Error("Abstract class ProskommaRender cannot be instantiated - make as subclass!");
    }
    var actions2 = spec.actions || {};
    this.debugLevel = spec.debugLevel || 0;
    this.actions = {};
    for (var event of ["startDocument", "endDocument", "startSequence", "startTable", "endTable", "endSequence", "unresolvedBlockGraft", "blockGraft", "startParagraph", "endParagraph", "startRow", "endRow", "startCell", "endCell", "metaContent", "mark", "unresolvedInlineGraft", "inlineGraft", "startWrapper", "endWrapper", "startMilestone", "endMilestone", "startVerses", "endVerses", "startChapter", "endChapter", "text"]) {
      if (actions2[event]) {
        this.actions[event] = actions2[event].map((a) => new ProskommaRenderAction2(a));
      } else {
        this.actions[event] = [];
      }
    }
  }
  addRenderActionObject(event, actionOb) {
    if (!this.actions[event]) {
      throw new Error("Unknown event '".concat(event));
    }
    this.actions[event].push(actionOb);
  }
  addRenderAction(event, actionSpec) {
    this.addRenderActionObject(event, new ProskommaRenderAction2(actionSpec));
  }
  describeRenderActions(event) {
    if (!this.actions[event]) {
      throw new Error("Unknown event '".concat(event));
    }
    var ret = ["**Actions for ".concat(event, "**\n")];
    for (var actionOb of this.actions[event]) {
      ret.push("IF ".concat(actionOb.test.toString(), ":"));
      ret.push("    DO ".concat(actionOb.description));
    }
    return ret.join("\n");
  }
  renderDocument(_ref) {
    var {
      docId,
      config,
      output
    } = _ref;
    var context = {};
    var workspace = {};
    this.renderDocument1({
      docId,
      config,
      context,
      workspace,
      output
    });
    return output;
  }
  renderDocument1(_ref2) {
    throw new Error("Define renderDocument1() in subclass");
  }
  // renderEnvironment => {config, context, workspace, output}
  renderEvent(event, renderEnvironment) {
    var context = renderEnvironment.context;
    if (this.debugLevel > 1) {
      console.log("".concat("    ".repeat(context.sequences.length), "EVENT ").concat(event));
    }
    if (!this.actions[event]) {
      throw new Error("Unknown event '".concat(event));
    }
    var found = false;
    for (var actionOb of this.actions[event]) {
      var testResult = false;
      try {
        testResult = actionOb.test(renderEnvironment);
      } catch (err) {
        var msg = "Exception from test of action '".concat(actionOb.description, "' for event ").concat(event, " in ").concat(context.sequences.length > 0 ? context.sequences[0].type : "no", " sequence: ").concat(err);
        throw new Error(msg);
      }
      if (testResult) {
        found = true;
        if (this.debugLevel > 0) {
          console.log("".concat("    ".repeat(context.sequences.length), "    ").concat(event, " action: ").concat(actionOb.description));
        }
        var actionResult = false;
        try {
          actionResult = actionOb.action(renderEnvironment);
        } catch (err) {
          throw new Error("Exception from action '".concat(actionOb.description, "' for event ").concat(event, " in ").concat(context.sequences.length > 0 ? context.sequences[0].type : "no", " sequence: ").concat(err));
        }
        if (!actionResult) {
          break;
        }
      }
    }
    if (["unresolvedBlockGraft", "unresolvedInlineGraft"].includes(event) && this.actions[event].length === 0) {
      throw new Error("No action for ".concat(event, " graft event in ").concat(context.sequences.length > 0 ? context.sequences[0].type : "no", " sequence: add an action or fix your data!"));
    }
    if (!found && this.debugLevel > 1) {
      console.log("".concat("    ".repeat(context.sequences.length), "    No matching action"));
    }
  }
};
var ProskommaRender_1 = ProskommaRender$5;
var ProskommaRender$4 = ProskommaRender_1;
let PerfRenderFromJson$2 = class PerfRenderFromJson2 extends ProskommaRender$4 {
  constructor(spec) {
    super(spec);
    if (!spec.srcJson) {
      throw new Error("Must provide srcJson");
    }
    this.srcJson = spec.srcJson;
  }
  renderDocument1(_ref) {
    var {
      docId,
      config,
      context,
      workspace,
      output
    } = _ref;
    var environment = {
      config,
      context,
      workspace,
      output
    };
    context.renderer = this;
    context.document = {
      id: docId,
      schema: this.srcJson.schema,
      metadata: this.srcJson.metadata,
      mainSequenceId: this.srcJson.main_sequence_id,
      nSequences: Object.keys(this.srcJson.sequences).length
    };
    context.sequences = [];
    this.renderEvent("startDocument", environment);
    this.renderSequenceId(environment, this.srcJson.main_sequence_id);
    this.renderEvent("endDocument", environment);
  }
  sequenceContext(sequence, sequenceId) {
    return {
      id: sequenceId,
      type: sequence.type,
      nBlocks: sequence.blocks.length,
      milestones: /* @__PURE__ */ new Set([])
    };
  }
  renderSequenceId(environment, sequenceId) {
    var context = environment.context;
    var sequence = this.srcJson.sequences[sequenceId];
    if (!sequence) {
      throw new Error("Sequence '".concat(sequenceId, "' not found in renderSequenceId()"));
    }
    context.sequences.unshift(this.sequenceContext(sequence, sequenceId));
    this.renderEvent("startSequence", environment);
    for (var [blockN, block2] of sequence.blocks.entries()) {
      context.sequences[0].block = {
        type: block2.type,
        subType: block2.subtype,
        blockN,
        wrappers: []
      };
      if (block2.type === "graft") {
        if (block2.target && !this.srcJson.sequences[block2.target]) {
          context.sequences[0].block.target = block2.target;
          this.renderEvent("unresolvedBlockGraft", environment);
        } else {
          context.sequences[0].block.target = block2.target;
          context.sequences[0].block.isNew = block2.new || false;
          this.renderEvent("blockGraft", environment);
        }
      } else if (block2.type === "row") {
        this.renderEvent("startRow", environment);
        this.renderContent(block2.content, environment);
        this.renderEvent("endRow", environment);
      } else {
        this.renderEvent("startParagraph", environment);
        this.renderContent(block2.content, environment);
        this.renderEvent("endParagraph", environment);
      }
      delete context.sequences[0].block;
    }
    this.renderEvent("endSequence", environment);
    context.sequences.shift();
  }
  renderContent(content, environment) {
    for (var element of content) {
      this.renderElement(element, environment);
    }
  }
  renderElement(element, environment) {
    var maybeRenderMetaContent = (elementContext2) => {
      if (element.meta_content) {
        elementContext2.metaContent = element.meta_content;
        this.renderEvent("metaContent", environment);
      }
    };
    var context = environment.context;
    var elementContext = {
      type: element.type || "text"
    };
    if (element.subtype) {
      elementContext.subType = element.subtype;
    }
    if (element.atts) {
      elementContext.atts = element.atts;
    } else if (elementContext.type !== "end_milestone" && elementContext.type !== "meta_content") {
      elementContext.atts = {};
    }
    if (element.target) {
      elementContext.target = element.target;
    }
    if (element.type === "graft") {
      elementContext.isNew = element.new || false;
    }
    if (elementContext.type === "text") {
      elementContext.text = element;
    }
    context.sequences[0].element = elementContext;
    if (elementContext.type === "text") {
      this.renderEvent("text", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "mark") {
      this.renderEvent("mark", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "start_milestone") {
      this.renderEvent("startMilestone", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "end_milestone") {
      this.renderEvent("endMilestone", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "graft") {
      if (element.target) {
        if (element.target && !this.srcJson.sequences[element.target]) {
          this.renderEvent("unresolvedInlineGraft", environment);
          return;
        }
      }
      this.renderEvent("inlineGraft", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "wrapper") {
      context.sequences[0].block.wrappers.unshift(elementContext.subType);
      this.renderEvent("startWrapper", environment);
      this.renderContent(element.content, environment);
      context.sequences[0].element = elementContext;
      maybeRenderMetaContent(elementContext);
      this.renderEvent("endWrapper", environment);
      context.sequences[0].block.wrappers.shift();
    } else {
      throw new Error("Unexpected element type '".concat(elementContext.type));
    }
    delete context.sequences[0].element;
  }
};
var PerfRenderFromJson_1 = PerfRenderFromJson$2;
var _PerfRenderFromJson$a = _interopRequireDefault$c(PerfRenderFromJson_1);
function _interopRequireDefault$c(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  verseWordsActions
} = verseWords$2;
var verseWordsCode = function verseWordsCode2(_ref) {
  var {
    perf
  } = _ref;
  var cl = new _PerfRenderFromJson$a.default({
    srcJson: perf,
    actions: verseWordsActions
  });
  var output = {};
  try {
    cl.renderDocument({
      docId: "",
      config: {},
      output
    });
  } catch (err) {
    throw new Error("Error from renderDocument in verseWords: ".concat(err.message));
  }
  return {
    verseWords: output.cv
  };
};
var verseWords$1 = {
  name: "verseWords",
  type: "Transform",
  description: "PERF=>JSON: Counts words occurrences",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "verseWords",
    type: "json"
  }],
  code: verseWordsCode
};
var verseWords_1 = {
  verseWords: verseWords$1
};
var mergeActions$1 = (actionList) => {
  var ret = {};
  for (var action of actionList) {
    for (var key of Object.keys(action)) {
      if (ret[key]) {
        ret[key].push(...action[key]);
      } else {
        ret[key] = action[key];
      }
    }
  }
  return ret;
};
var mergeActions_1 = mergeActions$1;
var identityActions$b = {
  startDocument: [{
    description: "identity",
    test: () => true,
    action: (_ref) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref;
      output.perf = {};
      output.perf.schema = context.document.schema;
      output.perf.metadata = context.document.metadata;
      output.perf.sequences = {};
    }
  }],
  endDocument: [{
    description: "identity",
    test: () => true,
    action: (_ref2) => {
    }
  }],
  startSequence: [{
    description: "identity",
    test: () => true,
    action: (_ref3) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref3;
      output.perf.sequences[context.sequences[0].id] = {
        type: context.sequences[0].type,
        blocks: []
      };
      workspace.outputSequence = output.perf.sequences[context.sequences[0].id];
      if (context.sequences[0].type === "main") {
        output.perf.main_sequence_id = context.sequences[0].id;
      }
    }
  }],
  endSequence: [{
    description: "identity",
    test: () => true,
    action: (_ref4) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref4;
      if (context.sequences.length > 1) {
        workspace.outputSequence = output.perf.sequences[context.sequences[1].id];
      }
    }
  }],
  blockGraft: [{
    description: "identity",
    test: () => true,
    action: (environment) => {
      var currentBlock = environment.context.sequences[0].block;
      var graftRecord = {
        type: currentBlock.type,
        subtype: currentBlock.subType
      };
      if (currentBlock.target) {
        graftRecord.target = currentBlock.target;
        environment.context.renderer.renderSequenceId(environment, graftRecord.target);
      }
      if (currentBlock.isNew) {
        graftRecord.new = currentBlock.isNew;
      }
      environment.workspace.outputSequence.blocks.push(graftRecord);
    }
  }],
  startParagraph: [{
    description: "identity",
    test: () => true,
    action: (_ref5) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref5;
      var currentBlock = context.sequences[0].block;
      var paraRecord = {
        type: currentBlock.type,
        subtype: currentBlock.subType,
        content: []
      };
      workspace.outputSequence.blocks.push(paraRecord);
      workspace.currentContent = paraRecord.content;
      workspace.outputBlock = workspace.outputSequence.blocks[workspace.outputSequence.blocks.length - 1];
      workspace.outputContentStack = [workspace.outputBlock.content];
    }
  }],
  endParagraph: [{
    description: "identity",
    test: () => true,
    action: (_ref6) => {
    }
  }],
  metaContent: [{
    description: "identity",
    test: () => true,
    action: (environment) => {
      var {
        config,
        context,
        workspace,
        output
      } = environment;
      var element = context.sequences[0].element;
      workspace.currentContent = element.metaContent;
      var lastOutputItem = workspace.outputContentStack[1][workspace.outputContentStack[1].length - 1];
      lastOutputItem.meta_content = [];
      workspace.outputContentStack.unshift(lastOutputItem.meta_content);
      context.renderer.renderContent(workspace.currentContent, environment);
      workspace.outputContentStack.shift();
    }
  }],
  mark: [{
    description: "identity",
    test: () => true,
    action: (_ref7) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref7;
      var element = context.sequences[0].element;
      var markRecord = {
        type: element.type,
        subtype: element.subType
      };
      if (element.atts && typeof element.atts === "object" && Object.keys(element.atts).length !== 0) {
        markRecord.atts = element.atts;
      }
      workspace.outputContentStack[0].push(markRecord);
    }
  }],
  inlineGraft: [{
    description: "identity",
    test: () => true,
    action: (environment) => {
      var element = environment.context.sequences[0].element;
      var graftRecord = {
        type: element.type,
        subtype: element.subType
      };
      if (element.target) {
        graftRecord.target = element.target;
        var currentContent = environment.workspace.outputContentStack[0];
        environment.context.renderer.renderSequenceId(environment, element.target);
        environment.workspace.outputContentStack[0] = currentContent;
      }
      if (element.isNew) {
        graftRecord.new = element.isNew;
      }
      environment.workspace.outputContentStack[0].push(graftRecord);
    }
  }],
  startRow: [{
    description: "identity",
    test: () => true,
    action: (_ref8) => {
      var {
        context,
        workspace
      } = _ref8;
      var currentBlock = context.sequences[0].block;
      var paraRecord = {
        type: currentBlock.type,
        subtype: currentBlock.subType,
        content: []
      };
      workspace.outputSequence.blocks.push(paraRecord);
      workspace.currentContent = paraRecord.content;
      workspace.outputBlock = workspace.outputSequence.blocks[workspace.outputSequence.blocks.length - 1];
      workspace.outputContentStack = [workspace.outputBlock.content];
    }
  }],
  endRow: [{
    description: "identity",
    test: () => true,
    action: (_ref9) => {
    }
  }],
  startWrapper: [{
    description: "identity",
    test: () => true,
    action: (_ref10) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref10;
      var element = context.sequences[0].element;
      var wrapperRecord = {
        type: element.type,
        subtype: element.subType,
        content: []
      };
      if ("atts" in element && typeof element.atts === "object" && Object.keys(element.atts).length !== 0) {
        wrapperRecord.atts = element.atts;
      }
      workspace.outputContentStack[0].push(wrapperRecord);
      workspace.outputContentStack.unshift(wrapperRecord.content);
    }
  }],
  endWrapper: [{
    description: "identity",
    test: () => true,
    action: (_ref11) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref11;
      workspace.outputContentStack.shift();
    }
  }],
  startMilestone: [{
    description: "identity",
    test: () => true,
    action: (_ref12) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref12;
      var element = context.sequences[0].element;
      var milestoneRecord = {
        type: element.type,
        subtype: element.subType
      };
      if (element.atts && typeof element.atts === "object" && Object.keys(element.atts).length !== 0) {
        milestoneRecord.atts = element.atts;
      }
      workspace.outputContentStack[0].push(milestoneRecord);
    }
  }],
  endMilestone: [{
    description: "identity",
    test: () => true,
    action: (_ref13) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref13;
      var element = context.sequences[0].element;
      var milestoneRecord = {
        type: element.type,
        subtype: element.subType
      };
      workspace.outputContentStack[0].push(milestoneRecord);
    }
  }],
  text: [{
    description: "identity",
    test: () => true,
    action: (_ref14) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref14;
      var element = context.sequences[0].element;
      workspace.outputContentStack[0].push(element.text);
    }
  }]
};
var identity$5 = {
  identityActions: identityActions$b
};
var _PerfRenderFromJson$9 = _interopRequireDefault$b(PerfRenderFromJson_1);
var _mergeActions$5 = _interopRequireDefault$b(mergeActions_1);
function _interopRequireDefault$b(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  identityActions: identityActions$a
} = identity$5;
var {
  stripMarkupActions
} = stripAlignment$2;
var stripMarkupCode = function stripMarkupCode2(_ref) {
  var {
    perf,
    verseWords: verseWords2
  } = _ref;
  var cl = new _PerfRenderFromJson$9.default({
    srcJson: perf,
    actions: (0, _mergeActions$5.default)([stripMarkupActions, identityActions$a])
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      verseWords: verseWords2
    },
    output
  });
  return {
    perf: output.perf,
    strippedAlignment: output.stripped,
    unalignedWords: output.unalignedWords
  };
};
var stripAlignment$1 = {
  name: "stripAlignment",
  type: "Transform",
  description: "PERF=>PERF: Strips alignment markup",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }, {
    name: "verseWords",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }, {
    name: "strippedAlignment",
    type: "json"
  }, {
    name: "unalignedWords",
    type: "json"
  }],
  code: stripMarkupCode
};
var stripAlignment_1 = {
  stripAlignment: stripAlignment$1
};
var _PerfRenderFromJson$8 = _interopRequireDefault$a(PerfRenderFromJson_1);
var _mergeActions$4 = _interopRequireDefault$a(mergeActions_1);
function _interopRequireDefault$a(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  identityActions: identityActions$9
} = identity$5;
var {
  mergeAlignmentActions
} = mergeAlignement;
var mergeAlignmentCode = function mergeAlignmentCode2(_ref) {
  var {
    perf,
    verseWords: totalOccurrences,
    strippedAlignment
  } = _ref;
  var cl = new _PerfRenderFromJson$8.default({
    srcJson: perf,
    actions: (0, _mergeActions$4.default)([mergeAlignmentActions, identityActions$9])
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      totalOccurrences,
      strippedAlignment
    },
    output
  });
  return {
    perf: output.perf,
    unalignedWords: output.unalignedWords
  };
};
var mergeAlignment$1 = {
  name: "mergeAlignment",
  type: "Transform",
  description: "PERF=>PERF adds report to verses",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }, {
    name: "strippedAlignment",
    type: "json",
    source: ""
  }, {
    name: "verseWords",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }, {
    name: "unalignedWords",
    type: "json"
  }],
  code: mergeAlignmentCode
};
var mergeAlignment_1 = {
  mergeAlignment: mergeAlignment$1
};
var {
  verseWords
} = verseWords_1;
var {
  stripAlignment
} = stripAlignment_1;
var {
  mergeAlignment
} = mergeAlignment_1;
var transforms$9 = {
  verseWords,
  stripAlignment,
  mergeAlignment
};
var renderActions$a = renderActions$b;
var transforms$8 = transforms$9;
var alignment$1 = {
  transforms: transforms$8,
  renderActions: renderActions$a
};
var renderActions$9 = {};
var usfmToPerfCode$1 = function usfmToPerfCode(_ref) {
  var {
    usfm,
    selectors,
    proskomma
  } = _ref;
  proskomma.importDocuments(selectors, "usfm", [usfm]);
  var perfResultDocument = proskomma.gqlQuerySync("{documents {id docSetId perf} }").data.documents[0];
  var docId = perfResultDocument.id;
  var docSetId = perfResultDocument.docSetId;
  proskomma.gqlQuerySync('mutation { deleteDocument(docSetId: "'.concat(docSetId, '", documentId: "').concat(docId, '") }'));
  var perf = JSON.parse(perfResultDocument.perf);
  return {
    perf
  };
};
var usfmToPerf$1 = {
  name: "usfmToPerf",
  type: "Transform",
  description: "USFM=>PERF: Conversion via Proskomma",
  inputs: [{
    name: "usfm",
    type: "text",
    source: ""
  }, {
    name: "selectors",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: usfmToPerfCode$1
};
var usfmToPerf_1 = {
  usfmToPerf: usfmToPerf$1,
  usfmToPerfCode: usfmToPerfCode$1
};
var {
  usfmToPerf,
  usfmToPerfCode: usfmToPerfCode2
} = usfmToPerf_1;
var transforms$7 = {
  usfmToPerf,
  usfmToPerfCode: usfmToPerfCode2
};
var renderActions$8 = renderActions$9;
var transforms$6 = transforms$7;
var xToPerf$1 = {
  transforms: transforms$6,
  renderActions: renderActions$8
};
function ownKeys$4(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$4(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys$4(Object(t), true).forEach(function(r2) {
      _defineProperty$4(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$4(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty$4(obj, key, value) {
  key = _toPropertyKey$4(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey$4(arg) {
  var key = _toPrimitive$4(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive$4(input, hint) {
  if (typeof input !== "object" || input === null)
    return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object")
      return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var identityActions$8 = {
  startDocument: [{
    description: "identity",
    test: () => true,
    action: (_ref) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref;
      output.sofria = {};
      output.paras = [];
      output.sofria.schema = context.document.schema;
      output.sofria.metadata = context.document.metadata;
      output.sofria.sequence = {};
      workspace.currentSequence = output.sofria.sequence;
      workspace.chapter = null;
      workspace.verses = null;
      workspace.cachedChapter = null;
      workspace.cachedVerses = null;
    }
  }],
  endDocument: [{
    description: "identity",
    test: () => true,
    action: (_ref2) => {
    }
  }],
  startSequence: [{
    description: "identity",
    test: () => true,
    action: (_ref3) => {
      var {
        context,
        workspace
      } = _ref3;
      if (workspace.currentSequence == null) {
        workspace.currentSequence = {};
      }
      workspace.currentSequence.type = context.sequences[0].type;
      workspace.currentSequence.blocks = [];
    }
  }],
  endSequence: [{
    description: "identity",
    test: () => true,
    action: (_ref4) => {
      var {
        workspace,
        output
      } = _ref4;
      if (workspace.currentSequence.type === "main") {
        workspace.chapter = null;
        workspace.verses = null;
      }
      if (output.paras == null) {
        output.paras = workspace.currentSequence.blocks;
      } else {
        if (workspace.currentSequence.type === "main") {
          output.paras = output.paras.concat(workspace.currentSequence.blocks);
        }
      }
      workspace.currentSequence = null;
    }
  }],
  blockGraft: [{
    description: "identity",
    test: () => true,
    action: (environment) => {
      var currentBlock = environment.context.sequences[0].block;
      var graftRecord = {
        type: currentBlock.type
      };
      if (currentBlock.sequence) {
        graftRecord.sequence = {};
        var cachedSequencePointer = environment.workspace.currentSequence;
        environment.workspace.currentSequence = graftRecord.sequence;
        environment.context.renderer.renderSequence(environment);
        environment.workspace.currentSequence = cachedSequencePointer;
      }
      environment.workspace.currentSequence.blocks.push(graftRecord);
    }
  }],
  startParagraph: [{
    description: "identity",
    test: () => true,
    action: (_ref5) => {
      var {
        context,
        workspace
      } = _ref5;
      var currentBlock = context.sequences[0].block;
      var paraRecord = {
        type: currentBlock.type,
        subtype: currentBlock.subType,
        content: []
      };
      workspace.currentSequence.blocks.push(paraRecord);
      workspace.currentContent = paraRecord.content;
      workspace.outputBlock = workspace.currentSequence.blocks[workspace.currentSequence.blocks.length - 1];
      workspace.outputContentStack = [workspace.outputBlock.content];
      if (workspace.currentSequence.type === "main") {
        for (var cv of ["chapter", "verses"]) {
          if (workspace[cv]) {
            var wrapperRecord = {
              type: "wrapper",
              subtype: cv,
              content: [],
              atts: {
                number: workspace[cv]
              }
            };
            workspace.outputContentStack[0].push(wrapperRecord);
            workspace.outputContentStack.unshift(wrapperRecord.content);
          }
        }
      }
    }
  }],
  endParagraph: [{
    description: "identity",
    test: () => true,
    action: (_ref6) => {
    }
  }],
  startRow: [{
    description: "identity",
    test: () => true,
    action: (_ref7) => {
      var {
        context,
        workspace
      } = _ref7;
      var currentBlock = context.sequences[0].block;
      var paraRecord = {
        type: currentBlock.type,
        subtype: currentBlock.subType,
        content: []
      };
      workspace.currentSequence.blocks.push(paraRecord);
      workspace.currentContent = paraRecord.content;
      workspace.outputBlock = workspace.currentSequence.blocks[workspace.currentSequence.blocks.length - 1];
      workspace.outputContentStack = [workspace.outputBlock.content];
      if (workspace.currentSequence.type === "main") {
        for (var cv of ["chapter", "verses"]) {
          if (workspace[cv]) {
            var wrapperRecord = {
              type: "wrapper",
              subtype: cv,
              content: [],
              atts: {
                number: workspace[cv]
              }
            };
            workspace.outputContentStack[0].push(wrapperRecord);
            workspace.outputContentStack.unshift(wrapperRecord.content);
          }
        }
      }
    }
  }],
  endRow: [{
    description: "identity",
    test: () => true,
    action: (_ref8) => {
    }
  }],
  metaContent: [{
    description: "identity",
    test: () => true,
    action: (environment) => {
      var {
        context,
        workspace
      } = environment;
      var element = context.sequences[0].element;
      workspace.currentContent = element.metaContent;
      var lastOutputItem = workspace.outputContentStack[1][workspace.outputContentStack[1].length - 1];
      lastOutputItem.meta_content = [];
      workspace.outputContentStack.unshift(lastOutputItem.meta_content);
      context.renderer.renderContent(workspace.currentContent, environment);
      workspace.outputContentStack.shift();
    }
  }],
  mark: [{
    description: "identity",
    test: () => true,
    action: (_ref9) => {
      var {
        context,
        workspace
      } = _ref9;
      var element = context.sequences[0].element;
      var markRecord = {
        type: element.type,
        subtype: element.subType
      };
      if (element.atts) {
        markRecord.atts = element.atts;
      }
      workspace.outputContentStack[0].push(markRecord);
    }
  }],
  inlineGraft: [{
    description: "identity",
    test: () => true,
    action: (environment) => {
      var element = environment.context.sequences[0].element;
      var graftRecord = {
        type: element.type,
        subtype: element.subType,
        sequence: {}
      };
      var cachedSequencePointer = environment.workspace.currentSequence;
      var cachedOutputContentStack = [...environment.workspace.outputContentStack];
      environment.workspace.currentSequence = graftRecord.sequence;
      environment.context.renderer.renderSequence(environment);
      environment.workspace.outputContentStack = cachedOutputContentStack;
      environment.workspace.currentSequence = cachedSequencePointer;
      environment.workspace.outputContentStack[0].push(graftRecord);
    }
  }],
  startWrapper: [{
    description: "identity",
    test: () => true,
    action: (_ref10) => {
      var {
        context,
        workspace
      } = _ref10;
      var element = context.sequences[0].element;
      if (element.subType === "chapter") {
        workspace.chapter = element.atts.number;
        workspace.cachedChapter = workspace.chapter;
      } else if (element.subType === "verses") {
        workspace.verses = element.atts.number;
        workspace.cachedVerses = workspace.verses;
      }
      var wrapperRecord = {
        type: element.type,
        subtype: element.subType,
        content: []
      };
      if ("atts" in element) {
        wrapperRecord.atts = _objectSpread$4({}, element.atts);
      }
      if (workspace.outputContentStack.length === 0) {
        throw new Error("outputContentStack is empty before pushing to its first element, near ".concat(context.document.metadata.document.bookCode, " ").concat(workspace.cachedChapter, ":").concat(workspace.cachedVerses));
      }
      workspace.outputContentStack[0].push(wrapperRecord);
      workspace.outputContentStack.unshift(wrapperRecord.content);
    }
  }],
  endWrapper: [{
    description: "identity",
    test: () => true,
    action: (_ref11) => {
      var {
        context,
        workspace
      } = _ref11;
      var element = context.sequences[0].element;
      if (element.subType === "chapter") {
        workspace.chapter = null;
      } else if (element.subType === "verses") {
        workspace.verses = null;
      }
      workspace.outputContentStack.shift();
    }
  }],
  startMilestone: [{
    description: "identity",
    test: () => true,
    action: (_ref12) => {
      var {
        context,
        workspace
      } = _ref12;
      var element = context.sequences[0].element;
      var milestoneRecord = {
        type: element.type,
        subtype: element.subType
      };
      if (element.atts) {
        milestoneRecord.atts = element.atts;
      }
      workspace.outputContentStack[0].push(milestoneRecord);
    }
  }],
  endMilestone: [{
    description: "identity",
    test: () => true,
    action: (_ref13) => {
      var {
        context,
        workspace
      } = _ref13;
      var element = context.sequences[0].element;
      var milestoneRecord = {
        type: element.type,
        subtype: element.subType
      };
      workspace.outputContentStack[0].push(milestoneRecord);
    }
  }],
  text: [{
    description: "identity",
    test: () => true,
    action: (_ref14) => {
      var {
        context,
        workspace
      } = _ref14;
      var element = context.sequences[0].element;
      if (workspace.outputContentStack) {
        workspace.outputContentStack[0].push(element.text);
      }
    }
  }]
};
var identity$4 = {
  identityActions: identityActions$8
};
var {
  identityActions: identityActions$7
} = identity$4;
var renderActions$7 = {
  identityActions: identityActions$7
};
var {
  identityActions: identityActions$6
} = identity$4;
var identityActionsCode$1 = function identityActionsCode(_ref) {
  var {
    perf
  } = _ref;
  var cl = new PerfRenderFromJson({
    srcJson: perf,
    actions: identityActions$6
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {},
    output
  });
  return {
    verseWords: output.cv
  };
};
var identity$3 = {
  name: "identity",
  type: "Transform",
  description: "identity operation",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: identityActionsCode$1
};
var identity_1$1 = {
  identity: identity$3
};
var {
  identity: identity$2
} = identity_1$1;
var transforms$5 = {
  identity: identity$2
};
var renderActions$6 = renderActions$7;
var transforms$4 = transforms$5;
var sofriaToSofria$1 = {
  transforms: transforms$4,
  renderActions: renderActions$6
};
var wordCountActions$2 = {
  startDocument: [{
    description: "Set up word object",
    test: () => true,
    action: (_ref) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref;
      workspace.words = {};
    }
  }],
  text: [{
    description: "Split strings and add words to word object",
    test: () => true,
    action: (_ref2) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref2;
      for (var word of context.sequences[0].element.text.split(/[\s:;,.]+/).filter((w) => w.length > 0)) {
        word = word.toLowerCase();
        if (word in workspace.words) {
          workspace.words[word] += 1;
        } else {
          workspace.words[word] = 1;
        }
      }
    }
  }],
  endDocument: [{
    description: "Sort words",
    test: () => true,
    action: (_ref3) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref3;
      output.words = [...Object.entries(workspace.words)].sort((a, b) => b[1] - a[1]);
    }
  }]
};
var wordCount$2 = {
  wordCountActions: wordCountActions$2
};
var initialBlockRecord$1 = (ct) => ({
  type: ct.sequences[0].block.type,
  subType: ct.sequences[0].block.subType,
  pos: ct.sequences[0].block.blockN,
  perfChapter: null
});
var calculateUsfmChapterPositionsActions$4 = {
  startDocument: [{
    description: "Set up storage",
    test: () => true,
    action: (_ref) => {
      var {
        workspace,
        output
      } = _ref;
      workspace.blockRecords = [];
      output.report = {};
    }
  }],
  startParagraph: [{
    description: "Set up block record",
    test: () => true,
    action: (_ref2) => {
      var {
        context,
        workspace,
        output
      } = _ref2;
      workspace.blockRecords.push(initialBlockRecord$1(context));
    }
  }],
  blockGraft: [{
    description: "Set up block record",
    test: () => true,
    action: (_ref3) => {
      var {
        context,
        workspace,
        output
      } = _ref3;
      workspace.blockRecords.push(initialBlockRecord$1(context));
    }
  }],
  mark: [{
    description: "Add chapter number to block record",
    test: (_ref4) => {
      var {
        context
      } = _ref4;
      return context.sequences[0].element.subType === "chapter";
    },
    action: (_ref5) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref5;
      workspace.blockRecords[workspace.blockRecords.length - 1].perfChapter = context.sequences[0].element.atts["number"];
    }
  }],
  endDocument: [{
    description: "Populate report",
    test: () => true,
    action: (_ref6) => {
      var {
        workspace,
        output
      } = _ref6;
      for (var [recordN, record] of Object.entries(workspace.blockRecords)) {
        if (!record.perfChapter) {
          continue;
        }
        var usfmChapterPos = recordN;
        var found = false;
        while (usfmChapterPos > 0 && !found) {
          if (workspace.blockRecords[usfmChapterPos - 1].type === "paragraph" || workspace.blockRecords[usfmChapterPos - 1].subType === "title") {
            found = true;
          } else {
            usfmChapterPos--;
          }
        }
        output.report[usfmChapterPos.toString()] = record.perfChapter;
      }
    }
  }]
};
var calculateUsfmChapterPositions$3 = {
  calculateUsfmChapterPositionsActions: calculateUsfmChapterPositionsActions$4
};
var oneifyTag$3 = (t) => {
  if (["toc", "toca", "mt", "imt", "s", "ms", "mte", "sd"].includes(t)) {
    return t + "1";
  }
  return t;
};
var buildMilestone$1 = function buildMilestone(type2) {
  var atts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
  if (atts == null)
    atts = {};
  var str = "\\".concat(type2, "-s |");
  for (var [key, value] of Object.entries(atts)) {
    if (key === "x-morph" && typeof value !== "string") {
      str = str + oneifyTag$3(key) + '="' + value.join(",") + '" ';
    } else {
      str = str + oneifyTag$3(key) + '="' + value + '" ';
    }
  }
  return str + "\\*";
};
var buildEndWrapper$1 = function buildEndWrapper(type2, atts) {
  var isnested = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
  var str = "|";
  for (var [key, value] of Object.entries(atts || {})) {
    str = str + oneifyTag$3(key) + '="' + value + '" ';
  }
  str = str + "\\";
  if (isnested) {
    str = str + "+";
  }
  return str + type2 + "*";
};
var perfToUsfmActions$2 = {
  startDocument: [{
    description: "Set up environment",
    test: () => true,
    action: (_ref) => {
      var {
        context,
        workspace
      } = _ref;
      workspace.usfmBits = [""];
      workspace.nestedWrapper = 0;
      for (var [key, value] of Object.entries(context.document.metadata.document).filter((kv) => !["tags", "properties", "bookCode", "cl"].includes(kv[0]))) {
        workspace.usfmBits.push("\\".concat(oneifyTag$3(key), " ").concat(value, "\n"));
      }
    }
  }],
  blockGraft: [{
    description: "Follow block grafts",
    test: (_ref2) => {
      var {
        context
      } = _ref2;
      return ["title", "heading", "introduction"].includes(context.sequences[0].block.subType);
    },
    action: (environment) => {
      var contextSequence = environment.context.sequences[0];
      var chapterValue = environment.config.report[contextSequence.block.blockN.toString()];
      var target = contextSequence.block.target;
      if (chapterValue && contextSequence.type === "main") {
        environment.workspace.usfmBits.push("\n\\c ".concat(chapterValue, "\n"));
      }
      if (target) {
        environment.context.renderer.renderSequenceId(environment, target);
      }
    }
  }],
  inlineGraft: [{
    description: "Follow inline grafts",
    test: () => true,
    action: (environment) => {
      var target = environment.context.sequences[0].element.target;
      if (target) {
        environment.context.renderer.renderSequenceId(environment, target);
      }
    }
  }],
  startParagraph: [{
    description: "Output footnote paragraph tag (footnote)",
    test: (_ref3) => {
      var {
        context
      } = _ref3;
      return context.sequences[0].block.subType === "usfm:f" && context.sequences[0].type === "footnote" || context.sequences[0].block.subType === "usfm:x" && context.sequences[0].type === "xref";
    },
    action: (_ref4) => {
      var {
        context,
        workspace,
        config
      } = _ref4;
      workspace.nestedWrapper = 0;
      var contextSequence = context.sequences[0];
      workspace.usfmBits.push("\\".concat(oneifyTag$3(contextSequence.block.subType.split(":")[1]), " "));
    }
  }, {
    description: "Output footnote note_caller tag (footnote)",
    test: (_ref5) => {
      var {
        context
      } = _ref5;
      return context.sequences[0].block.subType === "usfm:f" || context.sequences[0].block.subType === "usfm:x";
    },
    action: (_ref6) => {
      var {
        context,
        workspace,
        config
      } = _ref6;
      workspace.nestedWrapper = 0;
    }
  }, {
    description: "Output paragraph tag (main)",
    test: () => true,
    action: (_ref7) => {
      var {
        context,
        workspace,
        config
      } = _ref7;
      workspace.nestedWrapper = 0;
      var contextSequence = context.sequences[0];
      var chapterValue = config.report[contextSequence.block.blockN.toString()];
      if (chapterValue && contextSequence.type === "main") {
        workspace.usfmBits.push("\n\\c ".concat(chapterValue, "\n"));
      }
      workspace.usfmBits.push("\n\\".concat(oneifyTag$3(contextSequence.block.subType.split(":")[1]), "\n"));
    }
  }],
  endParagraph: [{
    description: "Output footnote paragraph tag (footnote)",
    test: (_ref8) => {
      var {
        context
      } = _ref8;
      return context.sequences[0].block.subType === "usfm:f" && context.sequences[0].type === "footnote" || context.sequences[0].block.subType === "usfm:x" && context.sequences[0].type === "xref";
    },
    action: (_ref9) => {
      var {
        context,
        workspace,
        config
      } = _ref9;
      var contextSequence = context.sequences[0];
      workspace.usfmBits.push("\\".concat(oneifyTag$3(contextSequence.block.subType.split(":")[1]), "*"));
    }
  }, {
    description: "Output footnote note_caller tag (footnote)",
    test: (_ref10) => {
      var {
        context
      } = _ref10;
      return context.sequences[0].block.subType === "usfm:f" || context.sequences[0].block.subType === "usfm:x";
    },
    action: (_ref11) => {
    }
  }, {
    description: "Output nl",
    test: () => true,
    action: (_ref12) => {
      var {
        workspace
      } = _ref12;
      workspace.usfmBits.push("\n");
    }
  }],
  startMilestone: [{
    description: "Output start milestone",
    test: () => true,
    action: (_ref13) => {
      var {
        context,
        workspace
      } = _ref13;
      var contextSequenceElement = context.sequences[0].element;
      var newStartMileStone = buildMilestone$1(oneifyTag$3(contextSequenceElement.subType.split(":")[1]), contextSequenceElement.atts);
      workspace.usfmBits.push(newStartMileStone);
    }
  }],
  endMilestone: [{
    description: "Output end milestone",
    test: () => true,
    action: (_ref14) => {
      var {
        context,
        workspace
      } = _ref14;
      workspace.usfmBits.push("\\".concat(oneifyTag$3(context.sequences[0].element.subType.split(":")[1]), "-e\\*"));
    }
  }],
  text: [{
    description: "Output text",
    test: () => true,
    action: (_ref15) => {
      var {
        context,
        workspace
      } = _ref15;
      var text = context.sequences[0].element.text;
      workspace.usfmBits.push(text);
    }
  }],
  mark: [{
    description: "Output chapter or verses",
    test: () => true,
    action: (_ref16) => {
      var {
        context,
        workspace
      } = _ref16;
      var element = context.sequences[0].element;
      if (element.subType === "verses") {
        workspace.usfmBits.push("\n\\v ".concat(element.atts["number"], "\n"));
      }
    }
  }],
  endSequence: [{
    description: "Output \\cl",
    test: (_ref17) => {
      var {
        context
      } = _ref17;
      return context.document.metadata.document.cl && context.sequences[0].type === "title";
    },
    action: (_ref18) => {
      var {
        context,
        workspace
      } = _ref18;
      workspace.usfmBits.push("\n\\cl ".concat(context.document.metadata.document.cl, "\n"));
    }
  }],
  startWrapper: [{
    description: "Output start tag",
    test: () => true,
    action: (_ref19) => {
      var {
        workspace,
        context
      } = _ref19;
      var contextSequence = context.sequences[0];
      if (workspace.nestedWrapper > 0) {
        workspace.usfmBits.push("\\+".concat(oneifyTag$3(contextSequence.element.subType.split(":")[1]), " "));
      } else {
        workspace.usfmBits.push("\\".concat(oneifyTag$3(contextSequence.element.subType.split(":")[1]), " "));
      }
      workspace.nestedWrapper += 1;
    }
  }],
  endWrapper: [{
    description: "Output end tag",
    test: (_ref20) => {
      var {
        context
      } = _ref20;
      return !["fr", "fq", "fqa", "fk", "fl", "fw", "fp", "ft", "xo", "xk", "xq", "xt", "xta"].includes(context.sequences[0].element.subType.split(":")[1]);
    },
    action: (_ref21) => {
      var {
        workspace,
        context
      } = _ref21;
      workspace.nestedWrapper -= 1;
      var contextSequence = context.sequences[0];
      var subType = contextSequence.element.subType.split(":")[1];
      var isNested = workspace.nestedWrapper > 0;
      if (subType === "w") {
        var newEndW = buildEndWrapper$1(oneifyTag$3(subType), contextSequence.element.atts, isNested);
        workspace.usfmBits.push(newEndW);
      } else {
        if (isNested) {
          workspace.usfmBits.push("\\+".concat(oneifyTag$3(contextSequence.element.subType.split(":")[1]), "*"));
        } else {
          workspace.usfmBits.push("\\".concat(oneifyTag$3(contextSequence.element.subType.split(":")[1]), "*"));
        }
      }
    }
  }, {
    description: "Do NOT output end tag",
    test: () => true,
    action: (_ref22) => {
      var {
        workspace
      } = _ref22;
      workspace.nestedWrapper -= 1;
    }
  }],
  endDocument: [{
    description: "Build output",
    test: () => true,
    action: (_ref23) => {
      var {
        workspace,
        output
      } = _ref23;
      output.usfm = workspace.usfmBits.join("").replace(/(\s*)\n(\s*)/gm, "\n");
    }
  }]
};
var perfToUsfm$2 = {
  perfToUsfmActions: perfToUsfmActions$2
};
var {
  wordCountActions: wordCountActions$1
} = wordCount$2;
var {
  calculateUsfmChapterPositionsActions: calculateUsfmChapterPositionsActions$3
} = calculateUsfmChapterPositions$3;
var {
  perfToUsfmActions: perfToUsfmActions$1
} = perfToUsfm$2;
var renderActions$5 = {
  wordCountActions: wordCountActions$1,
  perfToUsfmActions: perfToUsfmActions$1,
  calculateUsfmChapterPositionsActions: calculateUsfmChapterPositionsActions$3
};
var _PerfRenderFromJson$7 = _interopRequireDefault$9(PerfRenderFromJson_1);
function _interopRequireDefault$9(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  wordCountActions
} = wordCount$2;
var wordCountCode = function wordCountCode2(_ref) {
  var {
    perf
  } = _ref;
  var cl = new _PerfRenderFromJson$7.default({
    srcJson: perf,
    actions: wordCountActions
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {},
    output
  });
  return {
    report: output.report
  };
};
var wordCount$1 = {
  name: "wordCount",
  type: "Transform",
  description: "PERF=>JSON: Generates positions for inserting chapter numbers into USFM",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "report",
    type: "json"
  }],
  code: wordCountCode
};
var wordCount_1 = {
  wordCount: wordCount$1
};
var _PerfRenderFromJson$6 = _interopRequireDefault$8(PerfRenderFromJson_1);
function _interopRequireDefault$8(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  calculateUsfmChapterPositionsActions: calculateUsfmChapterPositionsActions$2
} = calculateUsfmChapterPositions$3;
var calculateUsfmChapterPositionsCode$1 = function calculateUsfmChapterPositionsCode(_ref) {
  var {
    perf
  } = _ref;
  var cl = new _PerfRenderFromJson$6.default({
    srcJson: perf,
    actions: calculateUsfmChapterPositionsActions$2
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      maxLength: 60
    },
    output
  });
  return {
    report: output.report
  };
};
var calculateUsfmChapterPositions$2 = {
  name: "calculateUsfmChapterPositions",
  type: "Transform",
  description: "PERF=>JSON: Generates positions for inserting chapter numbers into USFM",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "report",
    type: "json"
  }],
  code: calculateUsfmChapterPositionsCode$1
};
var calculateUsfmChapterPositions_1 = {
  calculateUsfmChapterPositions: calculateUsfmChapterPositions$2
};
var _PerfRenderFromJson$5 = _interopRequireDefault$7(PerfRenderFromJson_1);
function _interopRequireDefault$7(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  perfToUsfmActions
} = perfToUsfm$2;
var perfToUsfmCode = function perfToUsfmCode2(_ref) {
  var {
    perf,
    report
  } = _ref;
  var cl = new _PerfRenderFromJson$5.default({
    srcJson: perf,
    actions: perfToUsfmActions
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      report
    },
    output
  });
  return {
    usfm: output.usfm
  };
};
var perfToUsfm$1 = {
  name: "perfToUsfm",
  type: "Transform",
  description: "PERF=>USFM",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }, {
    name: "report",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "usfm",
    type: "text"
  }],
  code: perfToUsfmCode
};
var perfToUsfm_1 = {
  perfToUsfm: perfToUsfm$1
};
var xre$1 = require$$1$1;
var oneifyTag$2 = (t) => {
  if (["toc", "toca", "mt", "imt", "s", "ms", "mte", "sd"].includes(t)) {
    return t + "1";
  }
  return t;
};
var perfToUsfmJsActions$1 = {
  startDocument: [{
    description: "Setup",
    test: () => true,
    action: (_ref) => {
      var {
        context,
        workspace,
        output
      } = _ref;
      workspace.chapter = "front";
      workspace.verses = "front";
      workspace.zalns = [];
      workspace.inW = false;
      output.usfmJs = {
        headers: [],
        chapters: {}
      };
      for (var [k, v] of Object.entries(context.document.metadata.document)) {
        if (["bookCode", "properties", "tags"].includes(k)) {
          continue;
        }
        output.usfmJs.headers.push({
          tag: k === "toc" ? "toc1" : k,
          content: v
        });
      }
    }
  }],
  startParagraph: [{
    description: "Output paragraph tag (main), currently always to front",
    test: (_ref2) => {
      var {
        context,
        workspace,
        output
      } = _ref2;
      return context.sequences[0].type === "main" && output.usfmJs.chapters[workspace.chapter];
    },
    action: (_ref3) => {
      var {
        context,
        workspace,
        output
      } = _ref3;
      if (!output.usfmJs.chapters[workspace.chapter]["front"]) {
        output.usfmJs.chapters[workspace.chapter]["front"] = {
          verseObjects: []
        };
      }
      output.usfmJs.chapters[workspace.chapter]["front"].verseObjects.push({
        tag: oneifyTag$2(context.sequences[0].block.subType.split(":")[1]),
        type: "paragraph",
        nextChar: "\n"
      });
    }
  }, {
    description: "mt (title)",
    test: (_ref4) => {
      var {
        context,
        workspace,
        output
      } = _ref4;
      return context.sequences[0].type === "title";
    },
    action: (_ref5) => {
      var {
        context,
        output
      } = _ref5;
      output.usfmJs.headers.push({
        tag: oneifyTag$2(context.sequences[0].block.subType.split(":")[1]),
        content: ""
      });
    }
  }],
  mark: [{
    description: "Update chapter number",
    test: (_ref6) => {
      var {
        context
      } = _ref6;
      return context.sequences[0].element.subType === "chapter";
    },
    action: (_ref7) => {
      var {
        context,
        workspace,
        output
      } = _ref7;
      workspace.chapter = context.sequences[0].element.atts["number"];
      workspace.verses = "front";
      output.usfmJs.chapters[workspace.chapter] = {};
    }
  }, {
    description: "Update verses number",
    test: (_ref8) => {
      var {
        context
      } = _ref8;
      return context.sequences[0].element.subType === "verses";
    },
    action: (_ref9) => {
      var {
        context,
        workspace,
        output
      } = _ref9;
      workspace.verses = context.sequences[0].element.atts["number"];
      output.usfmJs.chapters[workspace.chapter][workspace.verses] = {
        verseObjects: []
      };
    }
  }],
  startMilestone: [{
    description: "Start zaln: make milestone and add to stack",
    test: (_ref10) => {
      var {
        context
      } = _ref10;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: (_ref11) => {
      var {
        context,
        workspace,
        output
      } = _ref11;
      var element = context.sequences[0].element;
      var milestoneOb = {
        tag: "zaln",
        type: "milestone"
      };
      for (var attKey of ["strong", "lemma", "morph", "occurrence", "occurrences", "content"]) {
        if (element.atts["x-".concat(attKey)]) {
          milestoneOb[attKey] = element.atts["x-".concat(attKey)].join(",");
        }
      }
      milestoneOb["children"] = [];
      milestoneOb["endTag"] = null;
      if (workspace.zalns.length === 0) {
        output.usfmJs.chapters[workspace.chapter][workspace.verses].verseObjects.push(milestoneOb);
      } else {
        workspace.zalns[0].children.push(milestoneOb);
      }
      workspace.zalns.unshift(milestoneOb);
    }
  }],
  endMilestone: [{
    description: "End zaln: pop stack",
    test: (_ref12) => {
      var {
        context
      } = _ref12;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: (_ref13) => {
      var {
        workspace
      } = _ref13;
      workspace.zalns[0].endTag = "zaln-e\\*";
      workspace.zalns.shift();
    }
  }],
  startWrapper: [{
    description: "start of w wrapper: make a new object with empty text",
    test: (_ref14) => {
      var {
        context,
        workspace
      } = _ref14;
      return context.sequences[0].element.subType === "usfm:w" && workspace.zalns.length > 0;
    },
    action: (_ref15) => {
      var {
        context,
        workspace
      } = _ref15;
      var wObject = {
        tag: "w",
        type: "word",
        text: ""
      };
      var element = context.sequences[0].element;
      for (var attKey of ["occurrence", "occurrences", "content"]) {
        if (element.atts["x-".concat(attKey)]) {
          wObject[attKey] = element.atts["x-".concat(attKey)].join(",");
        }
      }
      workspace.zalns[0].children.push(wObject);
      workspace.inW = true;
    }
  }],
  endWrapper: [{
    description: "end of w wrapper: clear flag",
    test: (_ref16) => {
      var {
        context,
        workspace
      } = _ref16;
      return context.sequences[0].element.subType === "usfm:w" && workspace.zalns.length > 0;
    },
    action: (_ref17) => {
      var {
        context,
        workspace
      } = _ref17;
      workspace.inW = false;
    }
  }],
  text: [{
    description: "Main sequence: add text either as text object or to existing word object in milestone",
    test: (_ref18) => {
      var {
        context
      } = _ref18;
      return context.sequences[0].type === "main";
    },
    action: (_ref19) => {
      var {
        context,
        workspace,
        output
      } = _ref19;
      var text = context.sequences[0].element.text;
      var target = output.usfmJs.chapters[workspace.chapter][workspace.verses].verseObjects.slice(-1)[0];
      if (workspace.zalns[0]) {
        target = workspace.zalns[0];
      } else if (target.type === "milestone") {
        target = {
          type: "text",
          text: ""
        };
        output.usfmJs.chapters[workspace.chapter][workspace.verses].verseObjects.push(target);
      }
      if (!target)
        ;
      else if (target.type === "text") {
        if ("text" in target) {
          target.text = "";
        }
        target.text += text;
      } else if (target.type === "milestone") {
        var children = target.children;
        var isWord = xre$1.test(text, xre$1("^[\\p{Letter}\\p{Number}\\p{Mark}\\u2060]{1,127}$"), 0);
        if (children.length === 0 || !("text" in children[children.length - 1]) || !isWord) {
          children.push({
            type: "text",
            text: ""
          });
        }
        children[children.length - 1].text += text;
      } else {
        throw new Error("Child is either text nor milestone");
      }
    }
  }, {
    description: "Title sequence: add text to mt in header",
    test: (_ref20) => {
      var {
        context
      } = _ref20;
      return context.sequences[0].type === "title";
    },
    action: (_ref21) => {
      var {
        context,
        output
      } = _ref21;
      var text = context.sequences[0].element.text;
      var headers = output.usfmJs.headers;
      headers[headers.length - 1].content += text;
    }
  }],
  blockGraft: [{
    description: "Process title grafts",
    test: (environment) => environment.context.sequences[0].block.subType === "title",
    action: (environment) => {
      var currentBlock = environment.context.sequences[0].block;
      var graftRecord = {
        type: currentBlock.type,
        subtype: currentBlock.subType
      };
      if (currentBlock.target) {
        graftRecord.target = currentBlock.target;
        environment.context.renderer.renderSequenceId(environment, graftRecord.target);
      }
      if (currentBlock.isNew) {
        graftRecord.new = currentBlock.isNew;
      }
    }
  }]
};
var perfToUsfmJs$2 = {
  perfToUsfmJsActions: perfToUsfmJsActions$1
};
var _PerfRenderFromJson$4 = _interopRequireDefault$6(PerfRenderFromJson_1);
function _interopRequireDefault$6(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  perfToUsfmJsActions
} = perfToUsfmJs$2;
var perfToUsfmJsCode = function perfToUsfmJsCode2(_ref) {
  var {
    perf,
    report
  } = _ref;
  var cl = new _PerfRenderFromJson$4.default({
    srcJson: perf,
    actions: perfToUsfmJsActions
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      report
    },
    output
  });
  return {
    usfmJs: output.usfmJs
  };
};
var perfToUsfmJs$1 = {
  name: "perfToUsfmJs",
  type: "Transform",
  description: "PERF=>USFMJS",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "usfmJs",
    type: "json"
  }],
  code: perfToUsfmJsCode
};
var perfToUsfmJs_1 = {
  perfToUsfmJs: perfToUsfmJs$1
};
var {
  wordCount
} = wordCount_1;
var {
  calculateUsfmChapterPositions: calculateUsfmChapterPositions$1
} = calculateUsfmChapterPositions_1;
var {
  perfToUsfm
} = perfToUsfm_1;
var {
  perfToUsfmJs
} = perfToUsfmJs_1;
var transforms$3 = {
  wordCount,
  perfToUsfm,
  perfToUsfmJs,
  calculateUsfmChapterPositions: calculateUsfmChapterPositions$1
};
var renderActions$4 = renderActions$5;
var transforms$2 = transforms$3;
var perfToX$1 = {
  transforms: transforms$2,
  renderActions: renderActions$4
};
var justTheBibleActions$2 = {
  startMilestone: [{
    description: "Ignore startMilestone events",
    test: () => true,
    action: () => {
    }
  }],
  endMilestone: [{
    description: "Ignore endMilestone events",
    test: () => true,
    action: () => {
    }
  }],
  startWrapper: [{
    description: "Ignore startWrapper events",
    test: () => true,
    action: () => {
    }
  }],
  endWrapper: [{
    description: "Ignore endWrapper events",
    test: () => true,
    action: () => {
    }
  }],
  blockGraft: [{
    description: "Ignore blockGraft events, except for title (\\mt)",
    test: (environment) => environment.context.sequences[0].block.subType !== "title",
    action: (environment) => {
    }
  }],
  inlineGraft: [{
    description: "Ignore inlineGraft events",
    test: () => true,
    action: () => {
    }
  }],
  mark: [{
    description: "Ignore mark events, except for chapter and verses",
    test: (_ref) => {
      var {
        context
      } = _ref;
      return !["chapter", "verses"].includes(context.sequences[0].element.subType);
    },
    action: () => {
    }
  }]
};
var justTheBible$2 = {
  justTheBibleActions: justTheBibleActions$2
};
var stripUwAlignmentActions$2 = {
  startMilestone: [{
    description: "Ignore zaln startMilestone events",
    test: (_ref) => {
      var {
        context
      } = _ref;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: () => {
    }
  }],
  endMilestone: [{
    description: "Ignore zaln endMilestone events",
    test: (_ref2) => {
      var {
        context
      } = _ref2;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: () => {
    }
  }],
  startWrapper: [{
    description: "Ignore w startWrapper events",
    test: (_ref3) => {
      var {
        context
      } = _ref3;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: () => {
    }
  }],
  endWrapper: [{
    description: "Ignore w endWrapper events",
    test: (_ref4) => {
      var {
        context
      } = _ref4;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: () => {
    }
  }]
};
var stripUwAlignment$2 = {
  stripUwAlignmentActions: stripUwAlignmentActions$2
};
var usfmJsHelps$1 = usfmJsHelps$2;
var xre = require$$1$1;
var mergeUwAlignmentActions$2 = {
  startDocument: [{
    description: "Make alignment lookup",
    test: () => true,
    action: (_ref) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref;
      workspace.chapter = null;
      workspace.verses = null;
      workspace.verseWordOccurrences = {};
      workspace.alignmentLookup = usfmJsHelps$1.alignmentLookupFromUsfmJs(config.usfmJs);
      workspace.zalnNesting = 0;
      output.perf = {};
      output.occurrences = {};
      return true;
    }
  }],
  mark: [{
    description: "Update CV state",
    test: () => true,
    action: (_ref2) => {
      var {
        context,
        workspace,
        output
      } = _ref2;
      try {
        var element = context.sequences[0].element;
        if (element.subType === "chapter") {
          workspace.chapter = element.atts["number"];
          workspace.verses = null;
          output.occurrences[workspace.chapter] = {};
        } else if (element.subType === "verses") {
          workspace.verses = element.atts["number"];
          workspace.verseWordOccurrences = {};
          output.occurrences[workspace.chapter][workspace.verses] = [];
        }
      } catch (err) {
        console.error(err);
        throw err;
      }
      return true;
    }
  }],
  text: [{
    description: "Maintain occurrences, add alignment when match found",
    test: (_ref3) => {
      var {
        context
      } = _ref3;
      return context.sequences[0].type === "main";
    },
    action: (_ref4) => {
      var {
        context,
        workspace,
        output
      } = _ref4;
      var regexes = {
        wordlike: xre("([\\p{Letter}\\p{Number}\\p{Mark}\\u2060]{1,127})"),
        unwordlike: xre("(([\\p{Separator}	]{1,127})|([\\p{Punctuation}\\p{Math_Symbol}\\p{Currency_Symbol}\\p{Modifier_Symbol}\\p{Other_Symbol}]))+")
      };
      regexes.all = xre.union([regexes.wordlike, regexes.unwordlike]);
      var texts = context.sequences[0].element.text;
      var textBits = xre.match(texts, regexes.all, "all");
      for (var text of textBits) {
        var _text = texts;
        if (xre.test(_text, regexes.wordlike)) {
          if (!workspace.verseWordOccurrences[_text]) {
            workspace.verseWordOccurrences[_text] = 0;
          }
          workspace.verseWordOccurrences[_text]++;
          output.occurrences[workspace.chapter][workspace.verses].push(workspace.verseWordOccurrences[_text]);
          var alignmentKey = "".concat(_text, "_").concat(workspace.verseWordOccurrences[_text]);
          var alignmentStartRecord = workspace.alignmentLookup[workspace.chapter][workspace.verses].before[alignmentKey];
          if (alignmentStartRecord) {
            for (var alignment2 of alignmentStartRecord) {
              var milestone = {
                "type": "start_milestone",
                "subtype": "usfm:zaln",
                "atts": {
                  "x-strong": [alignment2.strong],
                  "x-lemma": [alignment2.lemma],
                  "x-morph": [alignment2.morph.split(",")],
                  "x-occurrence": ["".concat(alignment2.occurrence)],
                  "x-occurrences": ["".concat(alignment2.occurrences)],
                  "x-content": [alignment2.content]
                }
              };
              workspace.outputContentStack[0].push(milestone);
              workspace.zalnNesting++;
            }
            if (workspace.zalnNesting > 0) {
              var wrapper = {
                "type": "wrapper",
                "subtype": "usfm:w",
                "content": [_text],
                "atts": {
                  "x-occurrence": ["".concat(workspace.verseWordOccurrences[_text])],
                  "x-occurrences": ["0"]
                }
              };
              workspace.outputContentStack[0].push(wrapper);
            } else {
              workspace.outputContentStack[0].push(_text);
            }
            var alignmentEndRecord = workspace.alignmentLookup[workspace.chapter][workspace.verses].after[alignmentKey];
            if (alignmentEndRecord) {
              for (var _alignment of alignmentEndRecord) {
                var _milestone = {
                  "type": "end_milestone",
                  "subtype": "usfm:zaln",
                  "atts": {
                    "x-strong": [_alignment.strong],
                    "x-lemma": [_alignment.lemma],
                    "x-morph": [_alignment.morph.split(",")],
                    "x-occurrence": ["".concat(_alignment.occurrence)],
                    "x-occurrences": ["".concat(_alignment.occurrences)],
                    "x-content": [_alignment.content]
                  }
                };
                workspace.outputContentStack[0].push(_milestone);
                workspace.zalnNesting--;
              }
            }
          }
        } else {
          workspace.outputContentStack[0].push(_text);
        }
      }
      return false;
    }
  }]
};
var mergeUwAlignment$2 = {
  mergeUwAlignmentActions: mergeUwAlignmentActions$2
};
var addUwAlignmentOccurrencesActions$1 = {
  startDocument: [{
    description: "Set up w counter",
    test: (_ref) => {
      return true;
    },
    action: (_ref2) => {
      var {
        workspace
      } = _ref2;
      workspace.wInVerse = 0;
      return true;
    }
  }],
  mark: [{
    description: "Update CV state",
    test: () => true,
    action: (_ref3) => {
      var {
        context,
        workspace,
        output
      } = _ref3;
      try {
        var element = context.sequences[0].element;
        if (element.subType === "chapter") {
          workspace.chapter = element.atts["number"];
          workspace.verses = null;
        } else if (element.subType === "verses") {
          workspace.verses = element.atts["number"];
          workspace.verseWordOccurrences = {};
          workspace.wInVerse = 0;
        }
      } catch (err) {
        console.error(err);
        throw err;
      }
      return true;
    }
  }],
  startWrapper: [{
    description: "Add occurrences to w wrapper",
    test: (_ref4) => {
      var {
        context
      } = _ref4;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: (_ref5) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref5;
      var element = context.sequences[0].element;
      var wrapperRecord = {
        type: element.type,
        subtype: element.subType,
        content: []
      };
      if ("atts" in element && typeof element.atts === "object" && Object.keys(element.atts).length !== 0) {
        wrapperRecord.atts = element.atts;
      }
      var occurrences = config.occurrences[workspace.chapter][workspace.verses][workspace.wInVerse];
      if (!occurrences) {
        throw new Error("No occurrences data for ".concat(workspace.chapter, ":").concat(workspace.verses, "#").concat(workspace.wInVerse));
      }
      wrapperRecord.atts["x-occurrences"] = [occurrences];
      workspace.wInVerse++;
      workspace.outputContentStack[0].push(wrapperRecord);
      workspace.outputContentStack.unshift(wrapperRecord.content);
      return false;
    }
  }]
};
var addUwAlignmentOccurrences$3 = {
  addUwAlignmentOccurrencesActions: addUwAlignmentOccurrencesActions$1
};
var {
  identityActions: identityActions$5
} = identity$5;
var {
  justTheBibleActions: justTheBibleActions$1
} = justTheBible$2;
var {
  stripUwAlignmentActions: stripUwAlignmentActions$1
} = stripUwAlignment$2;
var {
  mergeUwAlignmentActions: mergeUwAlignmentActions$1
} = mergeUwAlignment$2;
var {
  addUwAlignmentOccurrences: addUwAlignmentOccurrences$2
} = addUwAlignmentOccurrences$3;
var renderActions$3 = {
  identityActions: identityActions$5,
  justTheBibleActions: justTheBibleActions$1,
  stripUwAlignmentActions: stripUwAlignmentActions$1,
  mergeUwAlignmentActions: mergeUwAlignmentActions$1,
  addUwAlignmentOccurrences: addUwAlignmentOccurrences$2
};
var {
  identityActions: identityActions$4
} = identity$5;
var identityActionsCode2 = function identityActionsCode3(_ref) {
  var {
    perf
  } = _ref;
  var cl = new PerfRenderFromJson({
    srcJson: perf,
    actions: identityActions$4
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {},
    output
  });
  return {
    verseWords: output.cv
  };
};
var identity$1 = {
  name: "identityTransform",
  type: "Transform",
  description: "identity operation",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: identityActionsCode2
};
var identity_1 = {
  identity: identity$1
};
var _PerfRenderFromJson$3 = _interopRequireDefault$5(PerfRenderFromJson_1);
var _mergeActions$3 = _interopRequireDefault$5(mergeActions_1);
function _interopRequireDefault$5(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  identityActions: identityActions$3
} = identity$5;
var {
  justTheBibleActions
} = justTheBible$2;
var justTheBibleCode = function justTheBibleCode2(_ref) {
  var {
    perf
  } = _ref;
  var cl = new _PerfRenderFromJson$3.default({
    srcJson: perf,
    actions: (0, _mergeActions$3.default)([justTheBibleActions, identityActions$3])
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {},
    output
  });
  return {
    perf: output.perf
  };
};
var justTheBible$1 = {
  name: "justTheBible",
  type: "Transform",
  description: "PERF=>PERF: Strips most markup",
  documentation: "This transform removes milestones, wrappers and most marks. It has been used in several pipelines. It may also be stripping metaContent.",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: justTheBibleCode
};
var justTheBible_1 = {
  justTheBible: justTheBible$1
};
var _PerfRenderFromJson$2 = _interopRequireDefault$4(PerfRenderFromJson_1);
var _mergeActions$2 = _interopRequireDefault$4(mergeActions_1);
function _interopRequireDefault$4(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  identityActions: identityActions$2
} = identity$5;
var {
  stripUwAlignmentActions
} = stripUwAlignment$2;
var stripUwAlignmentCode = function stripUwAlignmentCode2(_ref) {
  var {
    perf
  } = _ref;
  var cl = new _PerfRenderFromJson$2.default({
    srcJson: perf,
    actions: (0, _mergeActions$2.default)([stripUwAlignmentActions, identityActions$2])
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {},
    output
  });
  return {
    perf: output.perf
  };
};
var stripUwAlignment$1 = {
  name: "stripUwAlignment",
  type: "Transform",
  description: "PERF=>PERF: Strips uW alignment markup",
  documentation: "This transform removes zaln milestones and w wrappers and most marks.",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: stripUwAlignmentCode
};
var stripUwAlignment_1 = {
  stripUwAlignment: stripUwAlignment$1
};
var _PerfRenderFromJson$1 = _interopRequireDefault$3(PerfRenderFromJson_1);
var _mergeActions$1 = _interopRequireDefault$3(mergeActions_1);
function _interopRequireDefault$3(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  identityActions: identityActions$1
} = identity$5;
var {
  mergeUwAlignmentActions
} = mergeUwAlignment$2;
var mergeUwAlignmentCode = function mergeUwAlignmentCode2(_ref) {
  var {
    perf,
    usfmJs
  } = _ref;
  var cl = new _PerfRenderFromJson$1.default({
    srcJson: perf,
    actions: (0, _mergeActions$1.default)([mergeUwAlignmentActions, identityActions$1])
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      usfmJs
    },
    output
  });
  return {
    perf: output.perf,
    occurrences: output.occurrences
  };
};
var mergeUwAlignment$1 = {
  name: "mergeUwAlignment",
  type: "Transform",
  description: "PERF=>PERF: Adds uW alignment markup from usfmJs",
  documentation: "This transform adds uW alignment from an equivalent usfmJs document.",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }, {
    name: "usfmJs",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }, {
    name: "occurrences",
    type: "json"
  }],
  code: mergeUwAlignmentCode
};
var mergeUwAlignment_1 = {
  mergeUwAlignment: mergeUwAlignment$1
};
var _PerfRenderFromJson = _interopRequireDefault$2(PerfRenderFromJson_1);
var _mergeActions = _interopRequireDefault$2(mergeActions_1);
function _interopRequireDefault$2(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var {
  identityActions
} = identity$5;
var {
  addUwAlignmentOccurrencesActions
} = addUwAlignmentOccurrences$3;
var addUwAlignmentOccurrencesCode = function addUwAlignmentOccurrencesCode2(_ref) {
  var {
    perf,
    occurrences
  } = _ref;
  var cl = new _PerfRenderFromJson.default({
    srcJson: perf,
    actions: (0, _mergeActions.default)([addUwAlignmentOccurrencesActions, identityActions])
  });
  var output = {};
  cl.renderDocument({
    docId: "",
    config: {
      occurrences
    },
    output
  });
  return {
    perf: output.perf
  };
};
var addUwAlignmentOccurrences$1 = {
  name: "addUwAlignmentOccurrences",
  type: "Transform",
  description: "PERF=>PERF: Adds uW alignment markup from usfmJs",
  documentation: "This transform adds uW alignment from an equivalent usfmJs document.",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }, {
    name: "occurrences",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: addUwAlignmentOccurrencesCode
};
var addUwAlignmentOccurrences_1 = {
  addUwAlignmentOccurrences: addUwAlignmentOccurrences$1
};
const objectBehaviors = {};
const isPrimitive$1 = (item) => {
  let type2 = typeof item;
  return type2 === "number" || type2 === "string" || type2 === "boolean" || type2 === "undefined" || type2 === "bigint" || type2 === "symbol" || item === null;
};
const objectType$1 = (obj) => {
  if (isPrimitive$1(obj) || !(obj instanceof Object)) {
    return "primitive";
  }
  const consName = obj.constructor && obj.constructor.name && obj.constructor.name.toLowerCase();
  if (typeof consName === "string" && consName.length && objectBehaviors[consName]) {
    return consName;
  }
  let typeTry;
  for (const name2 in objectBehaviors) {
    typeTry = objectBehaviors[name2].type;
    if (!typeTry || obj instanceof typeTry) {
      return name2;
    }
  }
  return "unknown";
};
const arrayAddElement = (array, key, value) => Array.prototype.push.call(array, value);
const arrayMakeEmpty = (source) => {
  const newArray = [];
  Object.setPrototypeOf(newArray, Object.getPrototypeOf(source));
  return newArray;
};
const arrayMakeShallow = (source) => {
  const dest = [...source];
  Object.setPrototypeOf(dest, Object.getPrototypeOf(source));
  return dest;
};
const arrayIterate = (array, copyNonEnumerables, callback) => {
  const len = array.length;
  for (let i = 0; i < len; i++) {
    const val = array[i];
    const elInfo = {
      key: i,
      value: val,
      type: objectType$1(val)
    };
    callback(elInfo);
  }
};
const addArrayBehavior = () => {
  Object.assign(objectBehaviors, {
    "array": {
      type: Array,
      mayDeepCopy: true,
      addElement: arrayAddElement,
      makeEmpty: arrayMakeEmpty,
      makeShallow: arrayMakeShallow,
      iterate: arrayIterate
    }
  });
};
const addDateBehavior = () => {
  Object.assign(objectBehaviors, {
    "date": {
      type: Date,
      makeShallow: (date) => new Date(date.getTime())
    }
  });
};
const addRegExpBehavior = () => {
  Object.assign(objectBehaviors, {
    "regexp": {
      type: RegExp,
      makeShallow: (src2) => new RegExp(src2)
    }
  });
};
const addFunctionBehavior = () => {
  Object.assign(objectBehaviors, {
    "function": {
      type: Function,
      makeShallow: (fn) => fn
    }
  });
};
const addErrorBehavior = () => {
  Object.assign(objectBehaviors, {
    "error": {
      type: Error,
      makeShallow: (err) => {
        const errCopy = new Error(err.message);
        errCopy.stack = err.stack;
        return errCopy;
      }
    }
  });
};
const addTypedArrayBehavior = (name2) => {
  let type2 = typeof commonjsGlobal !== "undefined" && commonjsGlobal[name2] || typeof window !== "undefined" && window[name2] || typeof WorkerGlobalScope !== "undefined" && WorkerGlobalScope[name2];
  if (typeof type2 !== "undefined") {
    objectBehaviors[name2.toLowerCase()] = {
      type: type2,
      makeShallow: (source) => type2.from(source)
    };
  }
};
const addAllTypedArrayBehaviors = () => {
  const typedArrayNames = [
    "Int8Array",
    "Uint8Array",
    "Uint8ClampedArray",
    "Int16Array",
    "Uint16Array",
    "Int32Array",
    "Uint32Array",
    "Float32Array",
    "Float32Array",
    "Float64Array",
    "BigInt64Array",
    "BigUint64Array"
  ];
  typedArrayNames.forEach((name2) => addTypedArrayBehavior(name2));
};
const addArrayBufferBehavior = () => {
  if (typeof ArrayBuffer !== "undefined") {
    Object.assign(objectBehaviors, {
      "arraybuffer": {
        type: ArrayBuffer,
        makeShallow: (buffer2) => buffer2.slice(0)
      }
    });
  }
};
const addMapBehavior = () => {
  if (typeof Map === "undefined") {
    return;
  }
  Object.assign(objectBehaviors, {
    "map": {
      type: Map,
      mayDeepCopy: true,
      addElement: (map, key, value) => map.set(key, value),
      makeEmpty: () => /* @__PURE__ */ new Map(),
      makeShallow: (sourceMap) => new Map(sourceMap),
      iterate: (map, copyNonEnumerables, callback) => {
        map.forEach((val, key) => {
          const elInfo = {
            key,
            value: val,
            type: objectType$1(val)
          };
          callback(elInfo);
        });
      }
    }
  });
};
const addSetBehavior = () => {
  if (typeof Set === "undefined") {
    return;
  }
  Object.assign(objectBehaviors, {
    "set": {
      type: Set,
      mayDeepCopy: true,
      addElement: (set, key, value) => set.add(value),
      makeEmpty: () => /* @__PURE__ */ new Set(),
      makeShallow: (set) => new Set(set),
      iterate: (set, copyNonEnumerables, callback) => {
        set.forEach((val) => {
          const elInfo = {
            key: null,
            value: val,
            type: objectType$1(val)
          };
          callback(elInfo);
        });
      }
    }
  });
};
const addWeakSetBehavior = () => {
  if (typeof WeakSet === "undefined") {
    return;
  }
  Object.assign(objectBehaviors, {
    "weakset": {
      type: WeakSet,
      makeShallow: (wset) => wset
    }
  });
};
const addWeakMapBehavior = () => {
  if (typeof WeakMap === "undefined") {
    return;
  }
  Object.assign(objectBehaviors, {
    "weakmap": {
      type: WeakMap,
      makeShallow: (wmap) => wmap
    }
  });
};
const addBufferBehavior = () => {
  if (typeof Buffer === "undefined") {
    return;
  }
  Object.assign(objectBehaviors, {
    "buffer": {
      type: Buffer,
      makeShallow: (buf) => Buffer.from(buf)
    }
  });
};
const objectAddElement = (obj, key, value, descriptor = void 0) => {
  if (!descriptor) {
    obj[key] = value;
  } else {
    Object.defineProperty(obj, key, descriptor);
  }
};
const objectMakeEmpty = (source) => {
  const newObj = {};
  Object.setPrototypeOf(newObj, Object.getPrototypeOf(source));
  return newObj;
};
const objectMakeShallow = (source) => {
  const dest = Object.assign({}, source);
  Object.setPrototypeOf(dest, Object.getPrototypeOf(source));
  return dest;
};
const objectIterate = (obj, copyNonEnumerables, callback) => {
  const keys = copyNonEnumerables ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
  const len = keys.length;
  for (let i = 0; i < len; i++) {
    const key = keys[i], value = obj[key], elInfo = {
      key,
      value,
      type: objectType$1(value)
    };
    if (copyNonEnumerables && !obj.propertyIsEnumerable(key)) {
      elInfo.descriptor = Object.getOwnPropertyDescriptor(obj, key);
    }
    callback(elInfo);
  }
};
const addObjectBehavior = () => {
  Object.assign(objectBehaviors, {
    "object": {
      type: Object,
      mayDeepCopy: true,
      addElement: objectAddElement,
      makeEmpty: objectMakeEmpty,
      makeShallow: objectMakeShallow,
      iterate: objectIterate
    }
  });
};
const addUnknownAndPrimitive = () => {
  Object.assign(objectBehaviors, {
    "unknown": {
      makeShallow: (source) => source
    },
    "primitive": {
      makeShallow: (source) => source
    }
  });
};
addArrayBehavior();
addDateBehavior();
addRegExpBehavior();
addFunctionBehavior();
addErrorBehavior();
addAllTypedArrayBehaviors();
addArrayBufferBehavior();
addMapBehavior();
addSetBehavior();
addWeakSetBehavior();
addWeakMapBehavior();
addBufferBehavior();
addObjectBehavior();
addUnknownAndPrimitive();
function objectActions$1(typeName) {
  return objectBehaviors[typeName];
}
var dcaLibrary = [
  isPrimitive$1,
  objectType$1,
  objectActions$1
];
const [isPrimitive, objectType, objectActions] = dcaLibrary, defaultOpts = { goDeep: true, includeNonEnumerable: false, detectCircular: true, maxDepth: 20 };
function setMissingOptions(e) {
  Object.keys(defaultOpts).forEach((t) => {
    void 0 === e[t] && (e[t] = defaultOpts[t]);
  });
}
class Watcher {
  constructor() {
    this._seenMap = /* @__PURE__ */ new WeakMap();
  }
  setAsCopied(e, t) {
    e instanceof Object && this._seenMap.set(e, t);
  }
  wasCopied(e) {
    return e instanceof Object && this._seenMap.has(e);
  }
  getCopy(e) {
    return this._seenMap.get(e);
  }
}
function copyElement(e, t, c) {
  const { options: o, watcher: s } = c;
  let n;
  return t.mayDeepCopy ? (n = t.makeEmpty(e), o.detectCircular && s.setAsCopied(e, n)) : n = t.makeShallow(e), n;
}
function checkForExceededDepth(e, t) {
  if (e >= t)
    throw `Error max depth of ${t} levels exceeded, possible circular reference`;
}
const copyObjectContents = (e, t, c) => {
  const { destObject: o, srcType: s, watcher: n, options: r } = t, p = r.detectCircular;
  checkForExceededDepth(++c, r.maxDepth);
  const i = objectActions(s);
  if (!i.mayDeepCopy)
    return;
  const a = i.addElement;
  i.iterate(e, r.includeNonEnumerable, (e2) => {
    const t2 = e2.value, s2 = e2.type, i2 = objectActions(s2);
    let d, l = false;
    p && n.wasCopied(t2) ? (d = n.getCopy(t2), l = true) : d = copyElement(t2, i2, { options: r, watcher: n }), a(o, e2.key, d, e2.descriptor), i2.mayDeepCopy && !l && copyObjectContents(t2, { destObject: d, srcType: s2, watcher: n, options: r }, c);
  });
};
function deepCopy(e, t = defaultOpts) {
  if (setMissingOptions(t), isPrimitive(e))
    return e;
  const c = objectType(e), o = objectActions(c);
  if (!t.goDeep || !o.mayDeepCopy)
    return o.makeShallow(e);
  const s = t.detectCircular ? new Watcher() : null;
  let n = o.makeEmpty(e);
  return t.detectCircular && s.setAsCopied(e, n), copyObjectContents(e, { destObject: n, srcType: c, watcher: s, options: t }, 0), n;
}
var deepCopyAll_min = deepCopy;
const deepCopy$1 = /* @__PURE__ */ getDefaultExportFromCjs(deepCopyAll_min);
var _deepCopyAll = _interopRequireDefault$1(deepCopyAll_min);
function _interopRequireDefault$1(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var doMerge1 = (content) => {
  var ret = [];
  for (var element of content) {
    if (typeof element === "string") {
      if (ret.length > 0 && typeof ret[ret.length - 1] === "string") {
        ret[ret.length - 1] += element;
      } else {
        ret.push(element);
      }
    } else {
      if (element.content) {
        element.content = doMerge1(element.content);
      }
      if (element.metaContent) {
        element.metaContent = doMerge1(element.content);
      }
      ret.push(element);
    }
  }
  return ret;
};
var doMerge = (perf) => {
  var newPerf = (0, _deepCopyAll.default)(perf);
  for (var seq of Object.values(newPerf.sequences)) {
    for (var block2 of seq.blocks) {
      if (block2.content) {
        block2.content = doMerge1(block2.content);
      }
      if (block2.metaContent) {
        block2.metaContent = doMerge1(block2.metaContent);
      }
    }
  }
  return newPerf;
};
var mergePerfTextCode$1 = function mergePerfTextCode(_ref) {
  var {
    perf
  } = _ref;
  return {
    perf: doMerge(perf)
  };
};
var mergePerfText$1 = {
  name: "mergePerfText",
  type: "Transform",
  description: "PERF=>PERF: Merge consecutive text strings",
  inputs: [{
    name: "perf",
    type: "json",
    source: ""
  }],
  outputs: [{
    name: "perf",
    type: "json"
  }],
  code: mergePerfTextCode$1
};
var mergePerfText_1 = {
  mergePerfText: mergePerfText$1,
  mergePerfTextCode: mergePerfTextCode$1
};
var {
  identity
} = identity_1;
var {
  justTheBible
} = justTheBible_1;
var {
  stripUwAlignment
} = stripUwAlignment_1;
var {
  mergeUwAlignment
} = mergeUwAlignment_1;
var {
  addUwAlignmentOccurrences
} = addUwAlignmentOccurrences_1;
var {
  mergePerfText,
  mergePerfTextCode: mergePerfTextCode2
} = mergePerfText_1;
var transforms$1 = {
  identity,
  justTheBible,
  mergePerfText,
  stripUwAlignment,
  mergeUwAlignment,
  addUwAlignmentOccurrences,
  mergePerfTextCode: mergePerfTextCode2
};
var renderActions$2 = renderActions$3;
var transforms = transforms$1;
var perfToPerf$1 = {
  transforms,
  renderActions: renderActions$2
};
function ownKeys$3(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$3(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys$3(Object(t), true).forEach(function(r2) {
      _defineProperty$3(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty$3(obj, key, value) {
  key = _toPropertyKey$3(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey$3(arg) {
  var key = _toPrimitive$3(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive$3(input, hint) {
  if (typeof input !== "object" || input === null)
    return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object")
      return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var defaultSettings = {
  showWordAtts: false,
  showTitles: true,
  showHeadings: true,
  showFootnotes: true,
  showXrefs: true,
  showChapterLabels: true,
  showVersesLabels: true,
  showFirstVerseLabel: false,
  showCharacterMarkup: true,
  showParaStyles: true,
  selectedBcvNotes: []
};
var sofria2WebActions$1 = {
  startDocument: [{
    description: "Set up",
    test: () => true,
    action: (_ref) => {
      var {
        config,
        context,
        workspace,
        output
      } = _ref;
      if (config.displayPartOfText != null) {
        if (!["begin", "continue"].includes(config.displayPartOfText.state)) {
          throw new Error("state must be typeof string and one of begin or continue");
        }
      }
      workspace.settings = _objectSpread$3(_objectSpread$3({}, defaultSettings), config);
      workspace.webParas = [];
      workspace.currentIndex = 0;
      output.sofria = {};
      output.sofria.sequence = {};
      workspace.currentSequence = output.sofria.sequence;
      workspace.paraContentStack = [];
      workspace.footnoteNo = 1;
      workspace.bookCode = context.document.metadata.document.bookCode;
      workspace.chapter = 0;
      workspace.foundPara = false;
    }
  }],
  startSequence: [{
    description: "startSequence",
    test: () => true,
    action: (_ref2) => {
      var {
        context,
        workspace
      } = _ref2;
      workspace.currentIndex += 1;
      workspace.currentSequence.type = context.sequences[0].type;
      workspace.currentSequence.blocks = [];
    }
  }],
  endSequence: [{
    description: "endSequence",
    test: () => true,
    action: (_ref3) => {
      var {
        config,
        context,
        workspace
      } = _ref3;
      if (workspace.currentSequence.type === "footnote") {
        workspace.footnoteNo++;
      }
      workspace.currentSequence = {};
    }
  }],
  startTable: [{
    description: "Initialise table",
    test: () => true,
    action: (_ref4) => {
      var {
        context,
        workspace
      } = _ref4;
      workspace.currentIndex += 1;
      workspace.paraContentStack.unshift({
        subType: "table",
        content: []
      });
    }
  }],
  endTable: [{
    description: "Add completed table to webParas",
    test: () => true,
    action: (_ref5) => {
      var {
        config,
        context,
        workspace
      } = _ref5;
      workspace.webParas.push(config.renderers.table(workspace.paraContentStack[0].content));
      workspace.paraContentStack.shift();
    }
  }],
  startRow: [{
    description: "Initialise content stack",
    test: () => true,
    action: (_ref6) => {
      var {
        context,
        workspace
      } = _ref6;
      var block2 = context.sequences[0].block;
      workspace.currentIndex += 1;
      workspace.paraContentStack.unshift({
        subType: block2.subType,
        content: []
      });
    }
  }],
  endRow: [{
    description: "Add completed table to webParas",
    test: () => true,
    action: (_ref7) => {
      var {
        config,
        context,
        workspace
      } = _ref7;
      var popped = workspace.paraContentStack.shift();
      workspace.paraContentStack[0].content.push(config.renderers.row(popped.content, workspace.currentIndex));
    }
  }],
  blockGraft: [{
    description: "Process block grafts",
    test: () => true,
    action: (environment) => {
      var currentBlock = environment.context.sequences[0].block;
      if (currentBlock.subType !== "remark" && !(["title", "endTitle"].includes(currentBlock.subType) && !environment.workspace.settings.showTitles) && !(["heading"].includes(currentBlock.subType) && !environment.workspace.settings.showHeadings) && !(["introduction"].includes(currentBlock.subType) && !environment.workspace.settings.showIntroductions)) {
        var graftRecord = {
          type: currentBlock.type
        };
        if (currentBlock.sequence) {
          graftRecord.sequence = {};
          var cachedSequencePointer = environment.workspace.currentSequence;
          environment.workspace.currentSequence = graftRecord.sequence;
          var cachedParaContentStack = environment.workspace.paraContentStack;
          environment.context.renderer.renderSequence(environment);
          environment.workspace.paraContentStack = cachedParaContentStack;
          environment.workspace.currentSequence = cachedSequencePointer;
        }
        environment.workspace.currentSequence.blocks.push(graftRecord);
      }
    }
  }],
  inlineGraft: [{
    description: "inlineGraft",
    test: (_ref8) => {
      var {
        context,
        workspace
      } = _ref8;
      return context.sequences[0].element.subType !== "note_caller" && !(["footnote"].includes(context.sequences[0].element.subType) && !workspace.settings.showFootnotes) && !(["xref"].includes(context.sequences[0].element.subType) && !workspace.settings.showXrefs);
    },
    action: (environment) => {
      var element = environment.context.sequences[0].element;
      var graftRecord = {
        type: element.type
      };
      if (element.sequence) {
        graftRecord.sequence = {};
        var cachedSequencePointer = environment.workspace.currentSequence;
        var cachedParaContentStack = [...environment.workspace.paraContentStack];
        var cachedWebParas = environment.workspace.webParas;
        environment.workspace.webParas = [];
        environment.workspace.currentSequence = graftRecord.sequence;
        environment.context.renderer.renderSequence(environment);
        var sequencePseudoParas = environment.workspace.webParas;
        environment.workspace.webParas = cachedWebParas;
        environment.workspace.paraContentStack = cachedParaContentStack;
        environment.workspace.paraContentStack[0].content.push(sequencePseudoParas);
        environment.workspace.currentSequence = cachedSequencePointer;
      }
    }
  }],
  startParagraph: [{
    description: "Initialise content stack",
    test: () => true,
    action: (_ref9) => {
      var {
        config,
        context,
        workspace
      } = _ref9;
      if (context.sequences[0].type !== "title" && !workspace.foundPara) {
        workspace.webParas.push(config.renderers.startChapters(workspace.settings.nColumns));
        workspace.foundPara = true;
      }
      workspace.currentIndex += 1;
      var block2 = context.sequences[0].block;
      workspace.paraContentStack.unshift({
        subType: block2.subType,
        content: []
      });
    }
  }],
  endParagraph: [{
    description: "Add completed para to webParas",
    test: () => true,
    action: (_ref10) => {
      var {
        config,
        context,
        workspace
      } = _ref10;
      workspace.webParas.push(config.renderers.paragraph(workspace.settings.showParaStyles || ["footnote", "xref"].includes(context.sequences[0].type) ? workspace.paraContentStack[0].subType : "usfm:m", workspace.paraContentStack[0].content, workspace.footnoteNo, workspace.currentIndex));
      workspace.paraContentStack.shift();
    }
  }],
  startWrapper: [{
    description: "Skip usfm:w outside main sequence",
    test: (_ref11) => {
      var {
        context
      } = _ref11;
      return context.sequences[0].element.subType === "usfm:w" && context.sequences[0].type !== "main";
    },
    action: () => {
    }
  }, {
    description: "Handle standard w attributes",
    test: (_ref12) => {
      var {
        context
      } = _ref12;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: (_ref13) => {
      var {
        context,
        workspace
      } = _ref13;
      workspace.currentIndex += 1;
      var atts = context.sequences[0].element.atts;
      var standardAtts = {};
      for (var [key, value] of Object.entries(atts)) {
        if (["strong", "lemma", "gloss"].includes(key)) {
          standardAtts[key] = value;
        }
      }
      workspace.paraContentStack.unshift({
        subType: context.sequences[0].element.subType,
        atts: standardAtts,
        content: []
      });
      return false;
    }
  }, {
    description: "Push to paraContent Stack",
    test: (_ref14) => {
      var {
        context,
        workspace
      } = _ref14;
      return !["chapter", "verses"].includes(context.sequences[0].element.subType) && workspace.settings.showCharacterMarkup;
    },
    action: (_ref15) => {
      var {
        context,
        workspace
      } = _ref15;
      var pushed = {
        subType: context.sequences[0].element.subType,
        content: []
      };
      if (context.sequences[0].element.subType === "cell") {
        pushed.atts = context.sequences[0].element.atts;
      }
      workspace.currentIndex += 1;
      workspace.paraContentStack.unshift(pushed);
    }
  }],
  endWrapper: [{
    description: "Skip usfm:w outside main sequence",
    test: (_ref16) => {
      var {
        context
      } = _ref16;
      return context.sequences[0].element.subType === "usfm:w" && context.sequences[0].type !== "main";
    },
    action: () => {
    }
  }, {
    description: "Handle standard w attributes",
    test: (_ref17) => {
      var {
        context
      } = _ref17;
      return context.sequences[0].element.subType === "usfm:w";
    },
    action: (_ref18) => {
      var {
        config,
        workspace
      } = _ref18;
      var popped = workspace.paraContentStack.shift();
      var toPush = config.renderers.wWrapper(workspace.settings.showWordAtts ? popped.atts : {}, popped.content.join(""), workspace.currentIndex);
      workspace.paraContentStack[0].content.push(toPush);
      if (workspace.settings.showGlossaryStar) {
        workspace.paraContentStack[0].content.push('<span class="glossary_star">*</span>');
      }
      return false;
    }
  }, {
    description: "Collapse one level of paraContent Stack",
    test: (_ref19) => {
      var {
        context,
        workspace
      } = _ref19;
      return !["chapter", "verses"].includes(context.sequences[0].element.subType) && workspace.settings.showCharacterMarkup;
    },
    action: (_ref20) => {
      var {
        config,
        workspace
      } = _ref20;
      var popped = workspace.paraContentStack.shift();
      workspace.paraContentStack[0].content.push(config.renderers.wrapper(popped.subType === "cell" ? popped.atts : {}, popped.subType, popped.content, workspace.currentIndex));
    }
  }],
  startMilestone: [{
    description: "Handle zaln word-like atts",
    test: (_ref21) => {
      var {
        context
      } = _ref21;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: (_ref22) => {
      var {
        config,
        context,
        workspace
      } = _ref22;
      var atts = context.sequences[0].element.atts;
      var standardAtts = {};
      for (var [key, value] of Object.entries(atts)) {
        if (["x-strong", "x-lemma", "x-morph", "x-content"].includes(key)) {
          standardAtts[key.split("-")[1]] = value;
        }
      }
      workspace.currentIndex += 1;
      workspace.paraContentStack[0].content.push(config.renderers.milestone("usfm:zaln", standardAtts));
      return false;
    }
  }],
  endMilestone: [{
    description: "Handle zaln word-like atts",
    test: (_ref23) => {
      var {
        context
      } = _ref23;
      return context.sequences[0].element.subType === "usfm:zaln";
    },
    action: (_ref24) => {
      var {
        config,
        context,
        workspace
      } = _ref24;
      var atts = context.sequences[0].element.atts;
      var standardAtts = {};
      for (var [key, value] of Object.entries(atts)) {
        if (["x-strong", "x-lemma", "x-morph", "x-content"].includes(key)) {
          standardAtts[key.split("-")[1]] = value;
        }
      }
      workspace.paraContentStack[0].content.push(config.renderers.milestone("usfm:zaln", standardAtts));
      return false;
    }
  }],
  text: [{
    description: "Push text to para",
    test: () => true,
    action: (_ref25) => {
      var {
        config,
        context,
        workspace
      } = _ref25;
      var element = context.sequences[0].element;
      element.text.split(" ").map((w, id2) => {
        workspace.currentIndex += 1;
        var renderedText = config.renderers.text(id2 === element.text.split(" ").length - 1 ? w : w + " ", workspace.currentIndex);
        workspace.paraContentStack[0].content.push(renderedText);
      });
    }
  }],
  mark: [{
    description: "Show chapter/verse markers",
    test: () => true,
    action: (_ref26) => {
      var {
        config,
        context,
        workspace
      } = _ref26;
      workspace.currentIndex += 1;
      var element = context.sequences[0].element;
      if (element.subType === "chapter_label" && workspace.settings.showChapterLabels) {
        workspace.chapter = element.atts.number;
        workspace.paraContentStack[0].content.push(config.renderers.chapter_label(element.atts.number, workspace.currentIndex));
      } else if (element.subType === "verses_label" && workspace.settings.showVersesLabels) {
        if (element.atts.number === "1" && !workspace.settings.showFirstVerseLabel) {
          return false;
        }
        var bcv = [];
        if (config.selectedBcvNotes.length > 0) {
          bcv = [workspace.bookCode, workspace.chapter, element.atts.number];
        }
        workspace.paraContentStack[0].content.push(config.renderers.verses_label(element.atts.number, bcv, config.bcvNotesCallback, workspace.currentIndex));
      }
    }
  }],
  endDocument: [{
    description: "Build output",
    test: () => true,
    action: (_ref27) => {
      var {
        config,
        workspace,
        output
      } = _ref27;
      if (workspace.foundPara) {
        workspace.webParas.push(config.renderers.endChapters());
        workspace.foundPara = true;
      }
      output.paras = config.renderers.mergeParas(workspace.webParas);
    }
  }]
};
var sofria2web$2 = {
  sofria2WebActions: sofria2WebActions$1
};
var {
  sofria2WebActions
} = sofria2web$2;
var renderActions$1 = {
  sofria2WebActions
};
var styles = {
  paras: {
    default: {
      fontSize: "medium",
      marginTop: "0.5ex",
      marginBottom: "0.5ex"
    },
    "usfm:b": {
      height: "1em"
    },
    "usfm:d": {
      fontStyle: "italic"
    },
    "usfm:f": {
      fontSize: "small"
    },
    "usfm:hangingGraft": {},
    "usfm:imt": {
      fontWeight: "bold",
      fontStyle: "italic",
      fontSize: "xx-large",
      textAlign: "center"
    },
    "usfm:imt2": {
      fontWeight: "bold",
      fontStyle: "italic",
      fontSize: "x-large",
      textAlign: "center"
    },
    "usfm:imt3": {
      fontWeight: "bold",
      fontStyle: "italic",
      fontSize: "large",
      textAlign: "center"
    },
    "usfm:ip": {
      textIndent: "1.5em"
    },
    "usfm:ipi": {
      paddingLeft: "1.5em",
      textIndent: "1.5em"
    },
    "usfm:io": {
      paddingLeft: "1.5em"
    },
    "usfm:iot": {
      fontWeight: "bold",
      fontSize: "large"
    },
    "usfm:is": {
      fontStyle: "italic",
      fontSize: "xx-large"
    },
    "usfm:is2": {
      fontStyle: "italic",
      fontSize: "x-large"
    },
    "usfm:is3": {
      fontStyle: "italic",
      fontSize: "large"
    },
    "usfm:li": {
      listStyleType: "disc",
      paddingLeft: "3em",
      textIndent: "-1.5em"
    },
    "usfm:li2": {
      listStyleType: "disc",
      paddingLeft: "4.5em",
      textIndent: "-1.5em"
    },
    "usfm:li3": {
      listStyleType: "disc",
      paddingLeft: "6em",
      textIndent: "-1.5em"
    },
    "usfm:m": {},
    "usfm:mi": {
      paddingLeft: "1.5em"
    },
    "usfm:mr": {
      fontSize: "large",
      fontStyle: "italic"
    },
    "usfm:ms": {
      fontSize: "large",
      fontWeight: "bold"
    },
    "usfm:ms2": {
      fontWeight: "bold"
    },
    "usfm:mt": {
      fontWeight: "bold",
      fontStyle: "italic",
      fontSize: "xx-large",
      textAlign: "center"
    },
    "usfm:mt2": {
      fontWeight: "bold",
      fontStyle: "italic",
      fontSize: "x-large",
      textAlign: "center"
    },
    "usfm:mt3": {
      fontWeight: "bold",
      fontStyle: "italic",
      fontSize: "large",
      textAlign: "center"
    },
    "usfm:nb": {},
    "usfm:p": {
      textIndent: "1.5em"
    },
    "usfm:pc": {
      textAlign: "center"
    },
    "usfm:pi": {
      paddingLeft: "1.5em",
      textIndent: "1.5em"
    },
    "usfm:pi2": {
      paddingLeft: "3em",
      textIndent: "1.5em"
    },
    "usfm:pi3": {
      paddingLeft: "4.5em",
      textIndent: "1.5em"
    },
    "usfm:q": {
      paddingLeft: "1.5em",
      marginTop: "0.5ex",
      marginBottom: "0.5ex"
    },
    "usfm:q2": {
      paddingLeft: "3em",
      marginTop: "0.5ex",
      marginBottom: "0.5ex"
    },
    "usfm:q3": {
      paddingLeft: "4.5em",
      marginTop: "0.5ex",
      marginBottom: "0.5ex"
    },
    "usfm:q4": {
      paddingLeft: "6em",
      marginTop: "0.5ex",
      marginBottom: "0.5ex"
    },
    "usfm:qa": {
      fontWeight: "bold",
      fontSize: "x-large"
    },
    "usfm:qr": {
      textAlign: "right"
    },
    "usfm:r": {
      fontWeight: "bold"
    },
    "usfm:s": {
      fontStyle: "italic",
      fontSize: "xx-large"
    },
    "usfm:s2": {
      fontStyle: "italic",
      fontSize: "x-large"
    },
    "usfm:s3": {
      fontStyle: "italic",
      fontSize: "large"
    },
    "usfm:sr": {
      fontSize: "large"
    },
    "usfm:tr": {},
    "usfm:x": {
      fontSize: "small"
    }
  },
  marks: {
    default: {},
    chapter_label: {
      float: "left",
      fontSize: "xx-large",
      marginRight: "0.5em"
    },
    verses_label: {
      fontWeight: "bold",
      fontSize: "small",
      verticalAlign: "super",
      marginRight: "0.5em"
    }
  },
  wrappers: {
    default: {},
    "usfm:add": {
      fontStyle: "italic"
    },
    "usfm:bd": {
      fontWeight: "bold"
    },
    "usfm:bdit": {
      fontWeight: "bold",
      fontStyle: "italic"
    },
    "usfm:bk": {
      fontWeight: "bold"
    },
    chapter: {},
    "usfm:fl": {},
    "usfm:fm": {},
    "usfm:fq": {
      fontStyle: "italic"
    },
    "usfm:fqa": {
      fontStyle: "italic"
    },
    "usfm:fr": {
      fontWeight: "bold"
    },
    "usfm:ft": {},
    "usfm:it": {
      fontStyle: "italic"
    },
    "usfm:nd": {
      fontWeight: "bold",
      fontSize: "smaller",
      textTransform: "uppercase"
    },
    "usfm:qs": {
      float: "right",
      fontStyle: "italic"
    },
    "usfm:sc": {
      fontSize: "smaller",
      textTransform: "uppercase"
    },
    "usfm:tl": {
      fontStyle: "italic"
    },
    verses: {},
    "usfm:wj": {
      color: "#D00"
    },
    "usfm:xk": {},
    "usfm:xo": {
      fontWeight: "bold"
    },
    "usfm:xt": {}
  }
};
var styleAsCSS = (options2) => {
  var cssResult = [];
  for (var option in options2) {
    cssResult.push("/* ".concat(option, " CSS format : */\n"));
    for (var op in options2[option]) {
      if (op.includes(":")) {
        var newOp = op.replace(":", "_");
        cssResult.push("  .".concat(option, "_").concat(newOp.replace(/([A-Z])/g, "_$1").toLowerCase(), " {\n"));
      } else {
        cssResult.push("  .".concat(option, "_").concat(op.replace(/([A-Z])/g, "_$1").toLowerCase(), " {\n"));
      }
      var _styles = options2[option][op];
      for (var prop in _styles) {
        for (var p in prop) {
          if (prop[p] === prop[p].toUpperCase()) {
            var newProp = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
            cssResult.push("      ".concat(newProp, ": ").concat(_styles[prop], ";\n"));
          }
        }
      }
      cssResult.push("  }\n");
    }
  }
  return cssResult.join("");
};
function convertCssToReactNativeStyle(styleSheet) {
  var copyStyleSheet = styleSheet;
  var keyFirstLayerArray = Object.keys(copyStyleSheet);
  keyFirstLayerArray.map((firstLayerKeys) => {
    var secondLayerKeysArray = Object.keys(copyStyleSheet[firstLayerKeys]);
    secondLayerKeysArray.map((secondLayerKey) => {
      var thirdLayerKeysArray = Object.keys(copyStyleSheet[firstLayerKeys][secondLayerKey]);
      thirdLayerKeysArray.map((thirdLayerKey) => {
        if (thirdLayerKey === "float") {
          if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "left") {
            copyStyleSheet[firstLayerKeys][secondLayerKey]["textAlign"] = "left";
            delete copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey];
          }
        }
        if (thirdLayerKey === "verticalAlign") {
          if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "super") {
            copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = "top";
          }
        }
        if (thirdLayerKey === "textIndent") {
          if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey].includes("em")) {
            var stringToChange = copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey];
            stringToChange.replace("em", "");
            copyStyleSheet[firstLayerKeys][secondLayerKey]["marginLeft"] = parseFloat(stringToChange) * 16;
            delete copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey];
          }
          delete copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey];
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "medium") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 16;
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "x-small") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 10;
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "xx-small") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 9;
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "small") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 13.333;
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "large") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 18;
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "x-large") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 24;
        }
        if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "xx-large") {
          copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = 32;
        }
        if (typeof copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] === "string") {
          if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey].includes("em")) {
            var _stringToChange = copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey];
            _stringToChange.replace("em", "");
            copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = parseFloat(_stringToChange) * 16;
            return;
          }
          if (copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey].includes("ex")) {
            var _stringToChange2 = copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey];
            _stringToChange2.replace("ex", "");
            copyStyleSheet[firstLayerKeys][secondLayerKey][thirdLayerKey] = parseFloat(_stringToChange2);
            return;
          }
        }
      });
    });
  });
  return copyStyleSheet;
}
var renderStyles$1 = {
  styles,
  styleAsCSS,
  convertCssToReactNativeStyle
};
var renderers = {
  text: (_text) => _text.replace(/{/g, "<i>").replace(/}/g, "</i>"),
  chapter_label: (number) => '<span class="marks_chapter_label">'.concat(number, "</span>"),
  verses_label: (number) => '<span class="marks_verses_label">'.concat(number, "</span>"),
  paragraph: (subType, content, footnoteNo) => {
    var paraClass = subType.split(":")[1];
    var paraHtmlTag = "p";
    if (["f", "x"].includes(paraClass)) {
      paraHtmlTag = "span";
    } else if (["s", "ms", "imt", "imte", "mt"].includes(paraClass)) {
      paraHtmlTag = "h1";
    } else if (["s2", "ms2", "imt2", "imte2", "mt2", "mr", "sr"].includes(paraClass)) {
      paraHtmlTag = "h2";
    } else if (["s3", "ms3", "imt3", "imte3", "mt3", "r", "d"].includes(paraClass)) {
      paraHtmlTag = "h3";
    } else if (["s4", "ms4", "imt4", "imte4", "mt4"].includes(paraClass)) {
      paraHtmlTag = "h4";
    }
    return "<".concat(paraHtmlTag, ' class="', "paras_usfm_".concat(paraClass), '">').concat(content.join(""), "</").concat(paraHtmlTag, ">");
  },
  wrapper: (atts, subType, content) => subType === "cell" ? atts.role === "body" ? "<td colspan=".concat(atts.nCols, ' style="text-align:').concat(atts.alignment, '">').concat(content.join(""), "</td>") : "<th colspan=".concat(atts.nCols, ' style="text-align:').concat(atts.alignment, '">').concat(content.join(""), "</th>") : '<span class="'.concat("wrappers_usfm_".concat(subType.split(":")[1]), '">', content.join(""), "</span>"),
  wWrapper: (atts, content) => Object.keys(atts).length === 0 ? content : '<span\n            style={{\n                display: "inline-block",\n                verticalAlign: "top",\n                textAlign: "center"\n            }}\n        >\n        <div>'.concat(content, "</div>").concat(Object.entries(atts).map((a) => '<div\n                            style={{\n                                fontSize: "xx-small",\n                                fontWeight: "bold"\n                            }}\n                        >\n                        {'.concat(a[0], " = ").concat(a[1], "} \n                        </div>")).join(""), "</span>"),
  milestone: (tags2, atts) => "",
  // Do not write milestones in HTML for now.
  startChapters: (nCols) => '<section class="chapters" style="columns: '.concat(nCols, '">'),
  endChapters: () => "</section>",
  mergeParas: (paras) => paras.join("\n"),
  row: (content) => {
    return "<tr>".concat(content.join(""), "</tr>");
  },
  table: (content) => {
    return "<table border>".concat(content.join(" "), "</table>");
  }
};
var sofria2html$1 = {
  renderers
};
var renderActions = renderActions$1;
var renderStyles = renderStyles$1;
var sofria2html = sofria2html$1;
var sofria2web$1 = {
  renderStyles,
  renderActions,
  sofria2html
};
var alignment = alignment$1;
var xToPerf = xToPerf$1;
var sofriaToSofria = sofriaToSofria$1;
var perfToX = perfToX$1;
var perfToPerf = perfToPerf$1;
var sofria2web = sofria2web$1;
var render$1 = {
  xToPerf,
  perfToX,
  sofriaToSofria,
  alignment,
  perfToPerf,
  sofria2web
};
const require$$0 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      usfm: "text",
      selectors: "json"
    }
  },
  {
    id: 2,
    title: "USFM to PERF",
    name: "usfmToPerf",
    type: "Transform",
    inputs: [
      {
        name: "usfm",
        type: "text",
        source: "Input usfm"
      },
      {
        name: "selectors",
        type: "json",
        source: "Input selectors"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ],
    description: "USFM=>PERF: Conversion via Proskomma"
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 2 perf"
      }
    ]
  }
];
const require$$1 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json",
      strippedAlignment: "json"
    }
  },
  {
    id: 1,
    title: "Count stripped perf words",
    name: "verseWords",
    transformName: "verseWords",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "verseWords",
        type: "json"
      }
    ],
    description: "PERF=>JSON: Counts words occurrences"
  },
  {
    id: 2,
    title: "Merge Back Into Stripped (roundtrip)",
    name: "mergeAlignment",
    transformName: "mergeAlignment",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      },
      {
        name: "strippedAlignment",
        type: "json",
        source: "Input strippedAlignment"
      },
      {
        name: "verseWords",
        type: "json",
        source: "Transform 1 verseWords"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      },
      {
        name: "unalignedWords",
        type: "json"
      }
    ],
    description: "PERF=>PERF adds report to verses"
  },
  {
    id: 3,
    title: "Merge Merged PERF Text",
    name: "mergePerfText",
    transformName: "mergePerfText",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 2 perf"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ],
    description: "PERF=>PERF: Merge consecutive text strings"
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 3 perf"
      },
      {
        name: "unalignedWords",
        type: "json",
        source: "Transform 2 unalignedWords"
      }
    ]
  }
];
const require$$2 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json"
    }
  },
  {
    id: 1,
    title: "Count stripped perf words",
    name: "verseWords",
    type: "Transform",
    transformName: "verseWords",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "verseWords",
        type: "json"
      }
    ],
    description: "PERF=>JSON: Counts words occurrences"
  },
  {
    id: 2,
    title: "Strip Alignment",
    name: "stripAlignment",
    type: "Transform",
    transformName: "stripAlignment",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      },
      {
        name: "verseWords",
        type: "json",
        source: "Transform 1 verseWords"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      },
      {
        name: "strippedAlignment",
        type: "json"
      },
      {
        name: "unalignedWords",
        type: "json"
      }
    ],
    description: "PERF=>PERF: Strips alignment markup"
  },
  {
    id: 3,
    title: "Merge stripped perf",
    name: "mergePerfText",
    type: "Transform",
    transformName: "mergePerfText",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 2 perf"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ],
    description: "PERF=>PERF: Merge consecutive text strings"
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 3 perf"
      },
      {
        name: "strippedAlignment",
        type: "json",
        source: "Transform 2 strippedAlignment"
      },
      {
        name: "unalignedWords",
        type: "json",
        source: "Transform 2 unalignedWords"
      }
    ]
  }
];
const require$$3 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json"
    }
  },
  {
    id: 1,
    title: "Strip uW alignment",
    name: "stripUwAlignment",
    transformName: "stripUwAlignment",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ]
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 1 perf"
      }
    ]
  }
];
const require$$4 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json",
      usfmJs: "json"
    }
  },
  {
    id: 1,
    title: "Strip uW alignment",
    name: "stripUwAlignment",
    transformName: "stripUwAlignment",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ]
  },
  {
    id: 2,
    title: "Merge uW alignment",
    name: "mergeUwAlignment",
    transformName: "mergeUwAlignment",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 1 perf"
      },
      {
        name: "usfmJs",
        type: "json",
        source: "Input usfmJs"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      },
      {
        name: "occurrences",
        type: "json"
      }
    ]
  },
  {
    id: 3,
    title: "Add occurrences",
    name: "addUwAlignmentOccurrences",
    transformName: "addUwAlignmentOccurrences",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 2 perf"
      },
      {
        name: "occurrences",
        type: "json",
        source: "Transform 2 occurrences"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ]
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 3 perf"
      },
      {
        name: "occurrences",
        type: "json",
        source: "Transform 2 perf"
      }
    ]
  }
];
const require$$5 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json"
    }
  },
  {
    id: 1,
    title: "Generate report",
    name: "calculateUsfmChapterPositions",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "report",
        type: "json"
      }
    ],
    description: "Generate report from perf to calculate the position of the chapters"
  },
  {
    id: 2,
    title: "PERF to USFM",
    name: "perfToUsfm",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      },
      {
        name: "report",
        type: "json",
        source: "Transform 1 report"
      }
    ],
    outputs: [
      {
        name: "usfm",
        type: "text"
      }
    ],
    description: "PERF=>USFM: Conversion via Proskomma"
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "usfm",
        type: "text",
        source: "Transform 2 usfm"
      }
    ]
  }
];
const require$$6 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json"
    }
  },
  {
    id: 1,
    title: "PERF to USFMJS",
    name: "perfToUsfmJs",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "usfmJs",
        type: "json"
      }
    ],
    description: "USFM=>PERF: Conversion via Proskomma"
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "usfmJs",
        type: "json",
        source: "Transform 1 usfmJs"
      }
    ]
  }
];
const require$$7 = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json"
    }
  },
  {
    id: 1,
    title: "Simplify Input PERF",
    name: "justTheBible",
    transformName: "justTheBible",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "perf",
        type: "json"
      }
    ]
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "perf",
        type: "json",
        source: "Transform 1 perf"
      }
    ]
  }
];
var _usfmToPerfPipeline = _interopRequireDefault(require$$0);
var _mergeAlignmentPipeline = _interopRequireDefault(require$$1);
var _stripAlignmentPipeline = _interopRequireDefault(require$$2);
var _stripUwAlignmentPipeline = _interopRequireDefault(require$$3);
var _mergeUwAlignmentPipeline = _interopRequireDefault(require$$4);
var _perfToUsfmPipeline = _interopRequireDefault(require$$5);
var _perfToUsfmJsPipeline = _interopRequireDefault(require$$6);
var _justTheBiblePipeline = _interopRequireDefault(require$$7);
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
var pipelines$2 = {
  usfmToPerfPipeline: _usfmToPerfPipeline.default,
  mergeAlignmentPipeline: _mergeAlignmentPipeline.default,
  stripAlignmentPipeline: _stripAlignmentPipeline.default,
  stripUwAlignmentPipeline: _stripUwAlignmentPipeline.default,
  mergeUwAlignmentPipeline: _mergeUwAlignmentPipeline.default,
  perfToUsfmPipeline: _perfToUsfmPipeline.default,
  perfToUsfmJsPipeline: _perfToUsfmJsPipeline.default,
  justTheBiblePipeline: _justTheBiblePipeline.default
};
function ownKeys$2(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$2(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys$2(Object(t), true).forEach(function(r2) {
      _defineProperty$2(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty$2(obj, key, value) {
  key = _toPropertyKey$2(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey$2(arg) {
  var key = _toPrimitive$2(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive$2(input, hint) {
  if (typeof input !== "object" || input === null)
    return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object")
      return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var namespaceTransforms = render$1;
var officialPipelines = pipelines$2;
let PipelineHandler$1 = class PipelineHandler {
  /**
   *
   * @param {Proskomma} proskomma - a proskomma instance
   * @param {JSON[]} pipelines - a list of the pipelines
   * @param {JSON[]} transforms - a list of the transforms
   * @param {boolean} verbose - print pipeline reading step by step
   */
  constructor(_ref) {
    var {
      pipelines: pipelines2 = null,
      transforms: transforms2 = null,
      proskomma = null,
      verbose = false
    } = _ref;
    if (proskomma !== null) {
      this.proskomma = proskomma;
      var query = "{ id }";
      var content = proskomma.gqlQuerySync(query) || {};
      if (!content || !content.data.id) {
        throw new Error("Provided Proskomma instance does not have any ID");
      }
    }
    this.pipelines = officialPipelines;
    this.namespaces = namespaceTransforms;
    this.transforms = {};
    if (pipelines2 != null) {
      for (var key of Object.keys(pipelines2)) {
        this.pipelines[key] = pipelines2[key];
      }
    }
    if (transforms2 != null) {
      for (var _key of Object.keys(transforms2)) {
        this.transforms[_key] = transforms2[_key];
      }
    }
    this.verbose = verbose;
  }
  getProskomma() {
    return this.proskomma;
  }
  setProskomma(proskomma) {
    this.proskomma = proskomma;
  }
  listPipelinesNames() {
    return Object.keys(this.pipelines).join("\n");
  }
  listTransformsNames() {
    return Object.keys(this.transforms).join("\n");
  }
  listNamespacesNames() {
    return Object.keys(this.namespaces).join("\n");
  }
  /**
   * Gets pipeline by given name
   * @param {string} pipelineName - the pipeline name
   * @param {object} data input data
   * @return {pipeline} pipeline transforms
   * @private
   */
  getPipeline(pipelineName, data) {
    if (!this.pipelines[pipelineName]) {
      throw new Error("Unknown pipeline name '".concat(pipelineName, "'"));
    }
    var pipeline = this.pipelines[pipelineName];
    var inputSpecs = pipeline[0].inputs;
    if (Object.keys(inputSpecs).length !== Object.keys(data).length) {
      throw new Error("".concat(Object.keys(inputSpecs).length, " input(s) expected by ").concat(pipelineName, " but ").concat(Object.keys(data).length, " provided (").concat(Object.keys(data).join(", "), ")"));
    }
    for (var [inputSpecName, inputSpecType] of Object.entries(inputSpecs)) {
      if (!data[inputSpecName]) {
        throw new Error("Input ".concat(inputSpecName, " not provided as input to ").concat(pipelineName));
      }
      if (typeof data[inputSpecName] === "string" !== (inputSpecType === "text")) {
        throw new Error("Input ".concat(inputSpecName, " must be ").concat(inputSpecType, " but ").concat(typeof data[inputSpecName] === "string" ? "text" : "json", " was provided"));
      }
    }
    return pipeline;
  }
  /**
   * Generates and returns a report via a transform pipeline
   * @async
   * @param {string} pipelineName
   * @param {object} data
   * @return {Promise<array>} A report
   */
  runPipeline(pipelineName, data) {
    var pipeline = this.getPipeline(pipelineName, data);
    this.loadTransforms(pipeline, "perf");
    try {
      return this.evaluateSteps({
        specSteps: pipeline,
        inputValues: data
      });
    } catch (err) {
      throw new Error("Error from runPipeline while running ".concat(pipelineName, ": ").concat(err.message));
    }
  }
  loadTransforms(pipeline) {
    var namespace = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "perf";
    var transformSteps = pipeline.filter((s) => s.type === "Transform");
    if (transformSteps.length === 0) {
      throw new Error("No Transform steps found in report steps");
    }
    var names2 = Object.keys(transformSteps).map((val) => transformSteps[val]["name"]);
    if (namespace === "sofria") {
      var entries = null;
      for (var [key, tr] of Object.entries(this.namespaces)) {
        if (key === "sofriaToSofria") {
          if (tr.transforms) {
            entries = Object.entries(tr.transforms);
          } else {
            entries = Object.entries(tr);
          }
          for (var [k, t] of entries) {
            if (names2.includes(k)) {
              this.transforms[k] = t;
            }
          }
        }
      }
    } else {
      var _entries = null;
      for (var [_key2, _tr] of Object.entries(this.namespaces)) {
        if (_key2 !== "sofriaToSofria") {
          if (_tr.transforms) {
            _entries = Object.entries(_tr.transforms);
          } else {
            _entries = Object.entries(_tr);
          }
          for (var [_k, _t] of _entries) {
            if (names2.includes(_k)) {
              this.transforms[_k] = _t;
            }
          }
        }
      }
    }
  }
  evaluateSteps(_ref2) {
    var {
      specSteps,
      inputValues
    } = _ref2;
    this.verbose && console.log("** Evaluate **");
    var inputStep = specSteps.filter((s) => s.type === "Inputs")[0];
    if (!inputStep) {
      throw new Error("No Inputs step found in report steps");
    }
    var outputStep = specSteps.filter((s) => s.type === "Outputs")[0];
    if (!outputStep) {
      throw new Error("No Outputs step found in report steps");
    }
    var transformSteps = specSteps.filter((s) => s.type === "Transform");
    if (transformSteps.length === 0) {
      throw new Error("No Transform steps found in report steps");
    }
    var transformInputs = {};
    var transformOutputs = {};
    for (var transformStep of Object.values(transformSteps)) {
      transformInputs[transformStep.id] = {};
      for (var input of transformStep.inputs) {
        transformInputs[transformStep.id][input.name] = null;
      }
      transformOutputs[transformStep.id] = {};
      for (var output of transformStep.outputs) {
        transformOutputs[transformStep.id][output] = null;
      }
    }
    for (var [inputKey, inputValue] of Object.entries(inputValues)) {
      for (var _transformStep of transformSteps) {
        for (var _input of _transformStep.inputs) {
          if (_input.source === "Input ".concat(inputKey)) {
            this.verbose && console.log("Copying Input ".concat(inputKey, " to Transform ").concat(_transformStep.id, " ").concat(_input.name, " input"));
            transformInputs[_transformStep.id][_input.name] = inputValue;
          }
        }
      }
    }
    var seenTransforms = /* @__PURE__ */ new Set([]);
    var changed = true;
    while (changed) {
      changed = false;
      for (var _transformStep2 of transformSteps) {
        if (Object.values(transformInputs[_transformStep2.id]).filter((i) => !i).length === 0 && Object.values(transformOutputs[_transformStep2.id]).filter((i) => !i).length > 0) {
          if (!this.transforms[_transformStep2.name]) {
            throw new Error("Could not find transform called ".concat(_transformStep2.name));
          }
          if (seenTransforms.has(_transformStep2.id)) {
            throw new Error("Transform ".concat(_transformStep2.id, " called more than once"));
          }
          seenTransforms.add(_transformStep2.id);
          this.verbose && console.log("Evaluating Transform ".concat(_transformStep2.id));
          try {
            transformOutputs[_transformStep2.id] = this.transforms[_transformStep2.name].code(_objectSpread$2(_objectSpread$2({}, transformInputs[_transformStep2.id]), {}, {
              proskomma: this.getProskomma()
            }));
            if (Object.values(transformOutputs[_transformStep2.id]).filter((v) => !v).length > 0) {
              throw new Error("Transform ".concat(_transformStep2.id, " returned at least one false/undefined value: ").concat(JSON.stringify(transformOutputs[_transformStep2.id])));
            }
          } catch (err) {
            var errMsg = "Error evaluating Transform ".concat(_transformStep2.id, " (name=").concat(_transformStep2.name, ", type=").concat(typeof _transformStep2.code, "): ").concat(err);
            throw new Error(errMsg);
          }
          for (var consumingTransform of transformSteps) {
            for (var consumingInput of consumingTransform.inputs) {
              for (var resolvedOutput of Object.keys(transformOutputs[_transformStep2.id])) {
                if (consumingInput.source === "Transform ".concat(_transformStep2.id, " ").concat(resolvedOutput)) {
                  this.verbose && console.log("Copying Transform ".concat(_transformStep2.id, " ").concat(resolvedOutput, " output to Transform ").concat(consumingTransform.id, " ").concat(consumingInput.name, " input"));
                  transformInputs[consumingTransform.id][consumingInput.name] = transformOutputs[_transformStep2.id][resolvedOutput];
                }
              }
            }
          }
          changed = true;
        }
      }
    }
    var outputValues = {};
    for (var _output of outputStep.outputs) {
      var transformN = _output.source.split(" ")[1];
      this.verbose && console.log("Copying Transform ".concat(transformN, " ").concat(_output.name, " to Output ").concat(_output.name));
      outputValues[_output.name] = transformOutputs[transformN][_output.name];
    }
    this.verbose && console.log("****");
    return outputValues;
  }
};
var PipelineHandler_1 = PipelineHandler$1;
function ownKeys$1(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread$1(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys$1(Object(t), true).forEach(function(r2) {
      _defineProperty$1(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty$1(obj, key, value) {
  key = _toPropertyKey$1(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey$1(arg) {
  var key = _toPrimitive$1(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive$1(input, hint) {
  if (typeof input !== "object" || input === null)
    return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object")
      return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var ProskommaRender$3 = ProskommaRender_1;
var camelCaseToSnakeCase$1 = (s) => {
  var ret = [];
  for (var c of s.split("")) {
    if (c.toUpperCase() === c && c.toLowerCase() !== c) {
      ret.push("_".concat(c.toLowerCase()));
    } else {
      ret.push(c);
    }
  }
  return ret.join("");
};
let PerfRenderFromProskomma$1 = class PerfRenderFromProskomma extends ProskommaRender$3 {
  constructor(spec) {
    super(spec);
    if (!spec.proskomma) {
      throw new Error("No Proskomma");
    }
    this.pk = spec.proskomma;
    this._tokens = [];
    this._container = null;
  }
  renderDocument1(_ref) {
    var {
      docId,
      config,
      context,
      workspace,
      output
    } = _ref;
    var environment = {
      config,
      context,
      workspace,
      output
    };
    context.renderer = this;
    var documentResult = this.pk.gqlQuerySync('{document(id: "'.concat(docId, '") {docSetId mainSequence { id } nSequences sequences {id} headers { key value } } }'));
    var docSetId = documentResult.data.document.docSetId;
    var mainId = documentResult.data.document.mainSequence.id;
    var nSequences = documentResult.data.document.nSequences;
    documentResult.data.document.sequences.map((s) => s.id);
    var headers = {};
    for (var header of documentResult.data.document.headers) {
      headers[header.key] = header.value;
    }
    var docSetResult = this.pk.gqlQuerySync('{docSet(id: "'.concat(docSetId, '") {selectors {key value}}}'));
    var selectors = {};
    for (var selector of docSetResult.data.docSet.selectors) {
      selectors[selector.key] = selector.value;
    }
    context.document = {
      id: docId,
      schema: {
        "structure": "flat",
        "structure_version": "0.2.1",
        "constraints": [{
          "name": "perf",
          "version": "0.2.1"
        }]
      },
      metadata: {
        translation: {
          id: docSetId,
          selectors,
          properties: {},
          tags: []
        },
        document: _objectSpread$1(_objectSpread$1({}, headers), {}, {
          properties: {},
          tags: []
        })
      },
      mainSequenceId: mainId,
      nSequences
    };
    context.sequences = [];
    this.renderEvent("startDocument", environment);
    this.renderSequenceId(environment, mainId);
    this.renderEvent("endDocument", environment);
  }
  sequenceContext(sequence, sequenceId) {
    return {
      id: sequenceId,
      type: camelCaseToSnakeCase$1(sequence.type),
      nBlocks: sequence.nBlocks,
      milestones: /* @__PURE__ */ new Set([])
    };
  }
  renderSequenceId(environment, sequenceId) {
    var context = environment.context;
    var documentResult = this.pk.gqlQuerySync('{document(id: "'.concat(context.document.id, '") {sequence(id:"').concat(sequenceId, '") {id type nBlocks } } }'));
    var sequence = documentResult.data.document.sequence;
    if (!sequence) {
      throw new Error("Sequence '".concat(sequenceId, "' not found in renderSequenceId()"));
    }
    context.sequences.unshift(this.sequenceContext(sequence, sequenceId));
    this.renderEvent("startSequence", environment);
    var outputBlockN = 0;
    for (var inputBlockN = 0; inputBlockN < sequence.nBlocks; inputBlockN++) {
      var blocksResult = this.pk.gqlQuerySync('{\n               document(id: "'.concat(context.document.id, '") {\n                 sequence(id:"').concat(sequenceId, '") {\n                   blocks(positions:').concat(inputBlockN, ") {\n                     bg {subType payload}\n                     bs {payload}\n                     items {type subType payload}\n                   }\n                 }\n               }\n             }"));
      var blockResult = blocksResult.data.document.sequence.blocks[0];
      for (var blockGraft of blockResult.bg) {
        context.sequences[0].block = {
          type: "graft",
          subType: camelCaseToSnakeCase$1(blockGraft.subType),
          blockN: outputBlockN
        };
        context.sequences[0].block.target = blockGraft.payload;
        context.sequences[0].block.isNew = false;
        this.renderEvent("blockGraft", environment);
        outputBlockN++;
      }
      var subTypeValues = blockResult.bs.payload.split("/");
      var subTypeValue = void 0;
      if (subTypeValues[1] && ["tr", "zrow"].includes(subTypeValues[1])) {
        subTypeValue = subTypeValues[1] === "tr" ? "usfm:tr" : "pk";
      } else if (subTypeValues[1]) {
        subTypeValue = "usfm:".concat(subTypeValues[1]);
      } else {
        subTypeValue = subTypeValues[0];
      }
      context.sequences[0].block = {
        type: ["usfm:tr", "pk"].includes(subTypeValue) ? "row" : "paragraph",
        subType: subTypeValue,
        blockN: outputBlockN,
        wrappers: []
      };
      if (subTypeValue === "row") {
        this.renderEvent("startRow", environment);
      } else {
        this.renderEvent("startParagraph", environment);
      }
      this._tokens = [];
      this.renderContent(blockResult.items, environment);
      this._tokens = [];
      if (subTypeValue === "row") {
        this.renderEvent("endRow", environment);
      } else {
        this.renderEvent("endParagraph", environment);
      }
      delete context.sequences[0].block;
      outputBlockN++;
    }
    this.renderEvent("endSequence", environment);
    context.sequences.shift();
  }
  renderContent(items2, environment) {
    for (var item of items2) {
      this.renderItem(item, environment);
    }
    this.maybeRenderText(environment);
  }
  renderItem(item, environment) {
    if (item.type === "scope" && item.payload.startsWith("attribute")) {
      var scopeBits = item.payload.split("/");
      if (item.subType === "start") {
        if (!this._container) {
          this._container = {
            direction: "start",
            subType: "usfm:w",
            type: "wrapper",
            atts: {}
          };
        }
        if (scopeBits[3] in this._container.atts) {
          this._container.atts[scopeBits[3]].push(scopeBits[5]);
        } else {
          this._container.atts[scopeBits[3]] = [scopeBits[5]];
        }
      } else {
        if (!this._container) {
          this._container = {
            direction: "end",
            subType: "usfm:".concat(camelCaseToSnakeCase$1(scopeBits[2])),
            atts: {}
          };
          if (scopeBits[1] === "milestone") {
            this._container.type = "end_milestone";
          } else {
            this._container.type = "wrapper";
            if (scopeBits[3] in this._container.atts) {
              this._container.atts[scopeBits[3]].push(scopeBits[5]);
            } else {
              this._container.atts[scopeBits[3]] = [scopeBits[5]];
            }
          }
        }
      }
    } else {
      if (this._container) {
        this.maybeRenderText(environment);
        this.renderContainer(environment);
      }
      if (item.type === "token") {
        this._tokens.push(item.payload.replace(/\s+/g, " "));
      } else {
        if (item.type === "graft") {
          this.maybeRenderText(environment);
          var graft = {
            type: "graft",
            subType: camelCaseToSnakeCase$1(item.subType),
            target: item.payload,
            isNew: false
          };
          environment.context.sequences[0].element = graft;
          this.renderEvent("inlineGraft", environment);
          delete environment.context.sequences[0].element;
        } else {
          this.maybeRenderText(environment);
          var _scopeBits = item.payload.split("/");
          if (["chapter", "verses", "pubChapter", "pubVerse", "altChapter", "altVerse"].includes(_scopeBits[0])) {
            if (item.subType === "start") {
              var mark = {
                type: "mark",
                subType: camelCaseToSnakeCase$1(_scopeBits[0]),
                atts: {
                  number: _scopeBits[1]
                }
              };
              environment.context.sequences[0].element = mark;
              this.renderEvent("mark", environment);
              delete environment.context.sequences[0].element;
            }
          } else if (_scopeBits[0] === "span") {
            var wrapper = {
              type: "wrapper",
              subType: "usfm:".concat(_scopeBits[1]),
              atts: {}
            };
            environment.context.sequences[0].element = wrapper;
            if (item.subType === "start") {
              environment.context.sequences[0].block.wrappers.unshift(wrapper.subType);
              this.renderEvent("startWrapper", environment);
            } else {
              this.renderEvent("endWrapper", environment);
              environment.context.sequences[0].block.wrappers.shift();
            }
            delete environment.context.sequences[0].element;
          } else if (_scopeBits[0] === "spanWithAtts") {
            if (item.subType === "start") {
              this._container = {
                direction: "start",
                type: "wrapper",
                subType: "usfm:".concat(_scopeBits[1]),
                atts: {}
              };
            }
          } else if (_scopeBits[0] === "cell") {
            var _wrapper = {
              direction: "start",
              type: "wrapper",
              subType: _scopeBits[0],
              atts: {
                role: _scopeBits[1],
                alignment: _scopeBits[2],
                nCols: parseInt(_scopeBits[3])
              }
            };
            environment.context.sequences[0].element = _wrapper;
            if (item.subType === "start") {
              environment.context.sequences[0].block.wrappers.unshift(_wrapper.subType);
              this.renderEvent("startWrapper", environment);
            } else {
              this.renderEvent("endWrapper", environment);
              environment.context.sequences[0].block.wrappers.shift();
            }
            delete environment.context.sequences[0].element;
          } else if (_scopeBits[0] === "milestone" && item.subType === "start") {
            if (_scopeBits[1] === "ts") {
              var _mark = {
                type: "mark",
                subType: "usfm:".concat(camelCaseToSnakeCase$1(_scopeBits[1])),
                atts: {}
              };
              environment.context.sequences[0].element = _mark;
              this.renderEvent("mark", environment);
              delete environment.context.sequences[0].element;
            } else {
              this._container = {
                type: "start_milestone",
                subType: "usfm:".concat(camelCaseToSnakeCase$1(_scopeBits[1])),
                atts: {}
              };
            }
          }
        }
      }
    }
  }
  maybeRenderText(environment) {
    if (this._tokens.length === 0) {
      return;
    }
    var elementContext = {
      type: "text",
      text: this._tokens.join("")
    };
    environment.context.sequences[0].element = elementContext;
    this._tokens = [];
    this.renderEvent("text", environment);
    delete environment.context.sequences[0].element;
  }
  renderContainer(environment) {
    if (this._container.type === "wrapper") {
      var direction = this._container.direction;
      delete this._container.direction;
      if (direction === "start") {
        environment.context.sequences[0].element = this._container;
        environment.context.sequences[0].block.wrappers.unshift(this._container.subType);
        this.renderEvent("startWrapper", environment);
        delete environment.context.sequences[0].element;
      } else {
        environment.context.sequences[0].element = this._container;
        this.renderEvent("endWrapper", environment);
        environment.context.sequences[0].block.wrappers.shift();
        delete environment.context.sequences[0].element;
      }
    } else if (this._container.type === "start_milestone") {
      environment.context.sequences[0].element = this._container;
      this.renderEvent("startMilestone", environment);
      delete environment.context.sequences[0].element;
    } else if (this._container.type === "end_milestone") {
      environment.context.sequences[0].element = this._container;
      this.renderEvent("endMilestone", environment);
      delete environment.context.sequences[0].element;
    }
    this._container = null;
  }
};
var PerfRenderFromProskomma_1 = PerfRenderFromProskomma$1;
var ProskommaRender$2 = ProskommaRender_1;
let SofriaRenderFromJson$1 = class SofriaRenderFromJson extends ProskommaRender$2 {
  constructor(spec) {
    super(spec);
    if (!spec.srcJson) {
      throw new Error("Must provide srcJson");
    }
    this.srcJson = spec.srcJson;
    this.cachedSequences = [];
  }
  renderDocument1(_ref) {
    var {
      docId,
      config,
      context,
      workspace,
      output
    } = _ref;
    var environment = {
      config,
      context,
      workspace,
      output
    };
    context.renderer = this;
    context.document = {
      id: docId,
      schema: this.srcJson.schema,
      metadata: this.srcJson.metadata
    };
    context.sequences = [];
    this.renderEvent("startDocument", environment);
    this.renderSequence(environment, this.srcJson.sequence);
    this.renderEvent("endDocument", environment);
  }
  sequenceContext(sequence) {
    return {
      type: sequence.type,
      nBlocks: sequence.blocks.length,
      milestones: /* @__PURE__ */ new Set([])
    };
  }
  renderSequence(environment, providedSequence) {
    var sequence;
    if (!providedSequence) {
      if (this.cachedSequences.length === 0) {
        throw new Error("No sequence provided and no sequences cached");
      }
      sequence = this.cachedSequences[0];
    } else {
      sequence = providedSequence;
    }
    var context = environment.context;
    context.sequences.unshift(sequence);
    this.renderEvent("startSequence", environment);
    for (var [blockN, block2] of sequence.blocks.entries()) {
      context.sequences[0].block = {
        type: block2.type,
        subType: block2.subtype,
        blockN,
        wrappers: []
      };
      if (block2.type === "graft") {
        context.sequences[0].block.sequence = this.sequenceContext(block2.sequence);
        this.cachedSequences.unshift(block2.sequence);
        this.renderEvent("blockGraft", environment);
        this.cachedSequences.shift();
      } else if (block2.type === "row") {
        if (!environment.workspace.inTable) {
          this.renderEvent("startTable", environment);
          environment.workspace.inTable = true;
        }
        this.renderEvent("startRow", environment);
        this.renderContent(block2.content, environment);
        if (environment.workspace.skipEndRow) {
          environment.workspace.skipEndRow = false;
        } else {
          this.renderEvent("endRow", environment);
        }
      } else {
        if (environment.workspace.inTable && context.sequences[0].type.includes("main")) {
          this.renderEvent("endTable", environment);
          environment.workspace.inTable = false;
        }
        this.renderEvent("startParagraph", environment);
        this.renderContent(block2.content, environment);
        this.renderEvent("endParagraph", environment);
      }
      delete context.sequences[0].block;
    }
    if (environment.workspace.inTable && context.sequences[0].type.includes("main")) {
      this.renderEvent("endTable", environment);
      environment.workspace.inTable = false;
      environment.workspace.tableHasContent = false;
      environment.workspace.skipEndRow = false;
      environment.workspace.changingChapter = false;
    }
    this.renderEvent("endSequence", environment);
    this.cachedSequence = null;
    context.sequences.shift();
  }
  renderContent(content, environment) {
    for (var element of content) {
      this.renderElement(element, environment);
    }
  }
  renderElement(element, environment) {
    var maybeRenderMetaContent = (elementContext2) => {
      if (element.meta_content) {
        elementContext2.metaContent = element.meta_content;
        this.renderEvent("metaContent", environment);
      }
    };
    var context = environment.context;
    var elementContext = {
      type: element.type || "text"
    };
    if (element.subtype) {
      elementContext.subType = element.subtype;
    }
    if (element.atts) {
      elementContext.atts = element.atts;
    } else if (elementContext.type !== "end_milestone" && elementContext.type !== "meta_content") {
      elementContext.atts = {};
    }
    if (element.sequence) {
      elementContext.sequence = this.sequenceContext(element.sequence);
    }
    if (elementContext.type === "text") {
      elementContext.text = element;
    }
    context.sequences[0].element = elementContext;
    if (elementContext.type === "text") {
      if (environment.workspace.inTable) {
        environment.workspace.tableHasContent = true;
      }
      this.renderEvent("text", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "mark") {
      this.renderEvent("mark", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "start_milestone") {
      this.renderEvent("startMilestone", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "end_milestone") {
      this.renderEvent("endMilestone", environment);
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "graft") {
      this.cachedSequences.unshift(element.sequence);
      this.renderEvent("inlineGraft", environment);
      this.cachedSequences.shift();
      maybeRenderMetaContent(elementContext);
    } else if (elementContext.type === "wrapper") {
      if (elementContext.subType === "chapter") {
        if (environment.workspace.chapterCurent) {
          if (environment.workspace.chapterCurent != elementContext.atts.number) {
            environment.workspace.changingChapter = true;
          }
        } else {
          environment.workspace.chapterCurent = elementContext.atts.number;
        }
      }
      if (environment.workspace.changingChapter && environment.workspace.inTable && environment.workspace.tableHasContent && elementContext.subType === "chapter") {
        this.renderEvent("endRow", environment);
        this.renderEvent("endTable", environment);
        environment.workspace.inTable = false;
        environment.workspace.tableHasContent = false;
        environment.workspace.skipEndRow = true;
        environment.workspace.changingChapter = false;
      }
      context.sequences[0].block.wrappers.unshift(elementContext.subType);
      this.renderEvent("startWrapper", environment);
      this.renderContent(element.content, environment);
      context.sequences[0].element = elementContext;
      maybeRenderMetaContent(elementContext);
      this.renderEvent("endWrapper", environment);
      context.sequences[0].block.wrappers.shift();
    } else {
      throw new Error("Unexpected element type '".concat(elementContext.type));
    }
    delete context.sequences[0].element;
  }
};
var SofriaRenderFromJson_1 = SofriaRenderFromJson$1;
function ownKeys(e, r) {
  var t = Object.keys(e);
  if (Object.getOwnPropertySymbols) {
    var o = Object.getOwnPropertySymbols(e);
    r && (o = o.filter(function(r2) {
      return Object.getOwnPropertyDescriptor(e, r2).enumerable;
    })), t.push.apply(t, o);
  }
  return t;
}
function _objectSpread(e) {
  for (var r = 1; r < arguments.length; r++) {
    var t = null != arguments[r] ? arguments[r] : {};
    r % 2 ? ownKeys(Object(t), true).forEach(function(r2) {
      _defineProperty(e, r2, t[r2]);
    }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) {
      Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2));
    });
  }
  return e;
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, "string");
  return typeof key === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
  if (typeof input !== "object" || input === null)
    return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== void 0) {
    var res = prim.call(input, hint || "default");
    if (typeof res !== "object")
      return res;
    throw new TypeError("@@toPrimitive must return a primitive value.");
  }
  return (hint === "string" ? String : Number)(input);
}
var ProskommaRender$1 = ProskommaRender_1;
var camelCaseToSnakeCase = (s) => {
  var ret = [];
  for (var c of s.split("")) {
    if (c.toUpperCase() === c && c.toLowerCase() !== c) {
      ret.push("_".concat(c.toLowerCase()));
    } else {
      ret.push(c);
    }
  }
  return ret.join("");
};
let SofriaRenderFromProskomma$1 = class SofriaRenderFromProskomma extends ProskommaRender$1 {
  constructor(spec) {
    super(spec);
    if (!spec.proskomma) {
      throw new Error("No Proskomma");
    }
    this.pk = spec.proskomma;
    this._tokens = [];
    this._container = null;
    this.cachedSequenceIds = [];
    this.sequences = null;
    this.currentCV = {
      chapter: null,
      verses: null
    };
  }
  renderDocument1(_ref) {
    var {
      docId,
      config,
      context,
      workspace,
      output
    } = _ref;
    var environment = {
      config,
      context,
      workspace,
      output
    };
    context.renderer = this;
    var documentResult = this.pk.gqlQuerySync('{\n          document(id: "'.concat(docId, '") {\n            docSetId\n            mainSequence { id }\n            nSequences\n            sequences {\n              id\n              type\n              nBlocks\n            }\n            headers {\n              key\n              value\n            }\n          } \n        }'));
    var docSetId = documentResult.data.document.docSetId;
    var mainId = documentResult.data.document.mainSequence.id;
    var nSequences = documentResult.data.document.nSequences;
    this.sequences = {};
    for (var seq of documentResult.data.document.sequences) {
      this.sequences[seq.id] = seq;
    }
    var headers = {};
    for (var header of documentResult.data.document.headers) {
      headers[header.key] = header.value;
    }
    var docSetResult = this.pk.gqlQuerySync('{docSet(id: "'.concat(docSetId, '") {selectors {key value}}}'));
    var selectors = {};
    for (var selector of docSetResult.data.docSet.selectors) {
      selectors[selector.key] = selector.value;
    }
    context.document = {
      id: docId,
      schema: {
        structure: "nested",
        structure_version: "0.2.1",
        constraints: [{
          name: "sofria",
          version: "0.2.1"
        }]
      },
      metadata: {
        translation: {
          id: docSetId,
          selectors,
          properties: {},
          tags: []
        },
        document: _objectSpread(_objectSpread({}, headers), {}, {
          properties: {},
          tags: []
        })
      },
      mainSequenceId: mainId,
      nSequences
    };
    context.sequences = [{}];
    this.renderEvent("startDocument", environment);
    this.cachedSequenceIds.unshift(mainId);
    if (environment.config.nbBlock) {
      environment.workspace.nbBlock = environment.config.nbBlock;
    }
    if (config.chapters) {
      if (workspace.chapters) {
        if (workspace.chapters.length === 0) {
          workspace.chapters = [...config.chapters];
        }
      } else {
        workspace.chapters = [...config.chapters];
      }
    }
    if (workspace.chapters) {
      context.document.metadata.document.properties.chapters = workspace.chapters[0];
    }
    this.renderSequence(environment);
    this.cachedSequenceIds.shift();
    this.renderEvent("endDocument", environment);
  }
  sequenceContext(sequence, sequenceId) {
    return {
      id: sequenceId,
      type: camelCaseToSnakeCase(sequence.type),
      nBlocks: sequence.nBlocks,
      milestones: /* @__PURE__ */ new Set([])
    };
  }
  renderSequence(environment) {
    var _environment$workspac, _environment$config2;
    var context = environment.context;
    var sequenceId = this.cachedSequenceIds[0];
    var sequenceType = this.pk.gqlQuerySync('{document(id: "'.concat(context.document.id, '") {sequence(id:"').concat(sequenceId, '") {type} } }')).data.document.sequence.type;
    var documentResult = {};
    var currentChapter = null;
    var currentChapterContext = null;
    var blocksIdsToRender = [];
    if (sequenceType === "main") {
      if (environment.workspace.blockId) {
        blocksIdsToRender = environment.workspace.blockId;
      }
    }
    var numberBlockTorender = 0;
    if (sequenceType === "main") {
      var _environment$config;
      if (environment.workspace.chapters && !((_environment$config = environment.config) !== null && _environment$config !== void 0 && _environment$config.byVerseExperimental)) {
        while (environment.workspace.chapters.length > 0) {
          currentChapter = environment.workspace.chapters.shift();
          if (currentChapter) {
            currentChapterContext = this.pk.gqlQuerySync('{document(id: "'.concat(context.document.id, '") {cIndex(chapter: ').concat(currentChapter, ") {\n                          startBlock\n                          endBlock\n                        }}}"));
          }
          if (currentChapter && currentChapterContext) {
            if (typeof currentChapterContext.data.document.cIndex.startBlock === "number" && typeof currentChapterContext.data.document.cIndex.endBlock === "number") {
              for (var i = currentChapterContext.data.document.cIndex.startBlock; i < currentChapterContext.data.document.cIndex.endBlock + 1; i++) {
                blocksIdsToRender.push(i);
              }
            } else {
              throw new Error("Chapter '".concat(currentChapter, "' not found in document"));
            }
          }
          environment.workspace.blockId = blocksIdsToRender;
        }
      } else {
        var nb = this.pk.gqlQuerySync('{document(id: "'.concat(context.document.id, '") {sequence(id:"').concat(sequenceId, '") {nBlocks} }}')).data.document.sequence.nBlocks;
        for (var _i = 0; _i < nb; _i++) {
          blocksIdsToRender.push(_i);
        }
      }
      blocksIdsToRender.sort((a, b) => b - a);
      if (!environment.workspace.nbBlock) {
        environment.workspace.nbBlock = blocksIdsToRender.length;
      }
    } else {
      var _nb = this.pk.gqlQuerySync('{document(id: "'.concat(context.document.id, '") {sequence(id:"').concat(sequenceId, '") {nBlocks} }}')).data.document.sequence.nBlocks;
      for (var _i2 = 0; _i2 < _nb; _i2++) {
        blocksIdsToRender.push(_i2);
      }
    }
    if (sequenceType === "main") {
      numberBlockTorender = environment.workspace.nbBlock;
    } else {
      numberBlockTorender = blocksIdsToRender.length;
    }
    documentResult = this.pk.gqlQuerySync('{document(id: "'.concat(context.document.id, '") {id sequence(id:"').concat(sequenceId, '") {id type nBlocks  } } }'));
    var sequence = documentResult.data.document.sequence;
    if (!sequence) {
      throw new Error("Sequence '".concat(sequenceId, "' not found in renderSequenceId()"));
    }
    context.sequences.unshift(this.sequenceContext(sequence, sequenceId));
    this.renderEvent("startSequence", environment);
    var outputBlockN = 0;
    if (((_environment$workspac = environment.workspace) === null || _environment$workspac === void 0 || (_environment$workspac = _environment$workspac.chapters) === null || _environment$workspac === void 0 ? void 0 : _environment$workspac.length) > 0 && (_environment$config2 = environment.config) !== null && _environment$config2 !== void 0 && _environment$config2.byVerseExperimental) {
      this.blockForCv(environment, sequenceId, sequenceType);
    } else {
      for (var _i3 = 0; _i3 < numberBlockTorender; _i3++) {
        if (blocksIdsToRender.length !== 0) {
          var inputBlockN = {};
          if (sequenceType === "main") {
            inputBlockN = blocksIdsToRender.pop();
          } else {
            inputBlockN = blocksIdsToRender.shift();
          }
          var blocksResult = void 0;
          if (environment.config.excludeScopeTypes) {
            if (environment.config.excludeScopeTypes.length > 0) {
              var scopeTypes = environment.config.excludeScopeTypes.map((elem) => '"'.concat(elem, '"'));
              blocksResult = this.pk.gqlQuerySync('{\n                   document(id: "'.concat(context.document.id, '") {\n                     sequence(id:"').concat(sequenceId, '") {\n                       blocks(positions:').concat(inputBlockN, ") {\n                         bg {subType payload}\n                         bs {payload}\n                         items (excludeScopeTypes : [").concat(scopeTypes, "] ) {type subType payload}\n                       }        \n                     }\n                   }\n                 }"));
            } else {
              blocksResult = this.pk.gqlQuerySync('{\n                   document(id: "'.concat(context.document.id, '") {\n                     sequence(id:"').concat(sequenceId, '") {\n                       blocks(positions:').concat(inputBlockN, ") {\n                         bg {subType payload}\n                         bs {payload}\n                         items{type subType payload}\n                       }\n                     }\n                   }\n                 }"));
            }
          } else {
            blocksResult = this.pk.gqlQuerySync('{\n                   document(id: "'.concat(context.document.id, '") {\n                     sequence(id:"').concat(sequenceId, '") {\n                       blocks(positions:').concat(inputBlockN, ") {\n                         bg {subType payload}\n                         bs {payload}\n                         items {type subType payload}\n                       }\n                     }\n                   }\n                 }"));
          }
          var blockResult = blocksResult.data.document.sequence.blocks[0];
          for (var blockGraft of blockResult.bg) {
            context.sequences[0].block = {
              type: "graft",
              subType: camelCaseToSnakeCase(blockGraft.subType),
              blockN: outputBlockN,
              sequence: this.sequences[blockGraft.payload]
            };
            this.cachedSequenceIds.unshift(blockGraft.payload);
            this.renderEvent("blockGraft", environment);
            this.cachedSequenceIds.shift();
            outputBlockN++;
          }
          var subTypeValues = blockResult.bs.payload.split("/");
          var subTypeValue = void 0;
          if (subTypeValues[1] && ["tr", "zrow"].includes(subTypeValues[1])) {
            subTypeValue = subTypeValues[1] === "tr" ? "usfm:tr" : "pk";
          } else if (subTypeValues[1]) {
            subTypeValue = "usfm:".concat(subTypeValues[1]);
          } else {
            subTypeValue = subTypeValues[0];
          }
          context.sequences[0].block = {
            type: ["usfm:tr", "pk"].includes(subTypeValue) ? "row" : "paragraph",
            subType: subTypeValue,
            blockN: outputBlockN,
            wrappers: []
          };
          if (context.sequences[0].block.type === "row") {
            if (!environment.workspace.inTable) {
              this.renderEvent("startTable", environment);
              environment.workspace.inTable = true;
            }
            this.renderEvent("startRow", environment);
          } else {
            if (environment.workspace.inTable && context.sequences[0].type.includes("main")) {
              this.renderEvent("endTable", environment);
              environment.workspace.tableHasContent = false;
              environment.workspace.inTable = false;
              environment.workspace.skipEndRow = false;
            }
            this.renderEvent("startParagraph", environment);
          }
          this._tokens = [];
          if (sequenceType === "main" && this.currentCV.chapter) {
            var wrapper = {
              type: "wrapper",
              subType: "chapter",
              atts: {
                number: this.currentCV.chapter
              }
            };
            environment.context.sequences[0].element = wrapper;
            environment.context.sequences[0].block.wrappers.unshift(wrapper.subType);
            this.renderEvent("startWrapper", environment);
          }
          if (sequenceType === "main" && this.currentCV.verses) {
            var _wrapper = {
              type: "wrapper",
              subType: "verses",
              atts: {
                number: this.currentCV.verses
              }
            };
            environment.context.sequences[0].element = _wrapper;
            environment.context.sequences[0].block.wrappers.unshift(_wrapper.subType);
            this.renderEvent("startWrapper", environment);
          }
          this.renderContent(blockResult.items, environment);
          this._tokens = [];
          if (sequenceType === "main" && this.currentCV.verses) {
            var _wrapper2 = {
              type: "wrapper",
              subType: "verses",
              atts: {
                number: this.currentCV.verses
              }
            };
            environment.context.sequences[0].element = _wrapper2;
            environment.context.sequences[0].block.wrappers.shift();
            this.renderEvent("endWrapper", environment);
          }
          if (sequenceType === "main" && this.currentCV.chapter) {
            var _wrapper3 = {
              type: "wrapper",
              subType: "chapter",
              atts: {
                number: this.currentCV.chapter
              }
            };
            environment.context.sequences[0].element = _wrapper3;
            environment.context.sequences[0].block.wrappers.shift();
            this.renderEvent("endWrapper", environment);
          }
          if (context.sequences[0].block.type === "row" && !environment.workspace.skipEndRow) {
            this.renderEvent("endRow", environment);
          } else if (environment.workspace.skipEndRow && context.sequences[0].block.type === "row") {
            environment.workspace.skipEndRow = false;
          } else {
            this.renderEvent("endParagraph", environment);
          }
          delete context.sequences[0].block;
          outputBlockN++;
        }
      }
      if (environment.workspace.inTable && context.sequences[0].type.includes("main")) {
        this.renderEvent("endTable", environment);
        environment.workspace.tableHasContent = false;
        environment.workspace.inTable = false;
        environment.workspace.skipEndRow = false;
      }
      this.renderEvent("endSequence", environment);
      if (sequenceType === "main") {
        environment.workspace.blockId = blocksIdsToRender;
      }
      context.sequences.shift();
    }
  }
  renderContent(items2, environment) {
    for (var i = 0; i < items2.length; i++) {
      this.renderItem(items2[i], environment);
    }
    this.maybeRenderText(environment);
  }
  renderItem(item, environment) {
    if (item.type === "scope" && item.payload.startsWith("attribute")) {
      var scopeBits = item.payload.split("/");
      if (item.subType === "start") {
        if (!this._container) {
          this._container = {
            direction: "start",
            subType: "usfm:w",
            type: "wrapper",
            atts: {}
          };
        }
        if (scopeBits[3] in this._container.atts) {
          this._container.atts[scopeBits[3]].push(scopeBits[5]);
        } else {
          this._container.atts[scopeBits[3]] = [scopeBits[5]];
        }
      } else {
        if (!this._container) {
          this._container = {
            direction: "end",
            subType: "usfm:".concat(camelCaseToSnakeCase(scopeBits[2]))
          };
          if (scopeBits[1] !== "milestone") {
            this._container.type = "wrapper";
            this._container.atts = {};
          }
        }
      }
    } else {
      if (this._container) {
        this.maybeRenderText(environment);
        this.renderContainer(environment);
        if (item.payload.includes("spanWith")) {
          this.maybeRenderText(environment);
          return;
        }
      }
      if (item.type === "token") {
        this._tokens.push(item.payload.replace(/[\r\n\t ]+/g, " "));
      } else if (item.type === "graft") {
        this.maybeRenderText(environment);
        var graft = {
          type: "graft",
          subType: camelCaseToSnakeCase(item.subType),
          sequence: this.sequences[item.payload]
        };
        environment.context.sequences[0].element = graft;
        this.cachedSequenceIds.unshift(item.payload);
        this.renderEvent("inlineGraft", environment);
        this.cachedSequenceIds.shift();
        delete environment.context.sequences[0].element;
      } else {
        this.maybeRenderText(environment);
        var _scopeBits = item.payload.split("/");
        if (["chapter", "verses"].includes(_scopeBits[0])) {
          var wrapper = {
            type: "wrapper",
            subType: camelCaseToSnakeCase(_scopeBits[0]),
            atts: {
              number: _scopeBits[1]
            }
          };
          environment.context.sequences[0].element = wrapper;
          if (item.subType === "start") {
            if (environment.workspace.tableHasContent && environment.workspace.inTable) {
              this.renderEvent("endRow", environment);
              this.renderEvent("endTable", environment);
              environment.workspace.tableHasContent = false;
              environment.workspace.inTable = false;
              environment.workspace.skipEndRow = true;
            }
            this.currentCV[_scopeBits[0]] = _scopeBits[1];
            environment.context.sequences[0].block.wrappers.unshift(wrapper.subType);
            this.renderEvent("start".concat(_scopeBits[0] === "chapter" ? "Chapter" : "Verses"), environment);
            this.renderEvent("startWrapper", environment);
            var cvMark = {
              type: "mark",
              subType: "".concat(_scopeBits[0], "_label"),
              atts: {
                number: _scopeBits[1]
              }
            };
            environment.context.sequences[0].element = cvMark;
            this.renderEvent("mark", environment);
            environment.context.sequences[0].element = wrapper;
          } else {
            this.renderEvent("endWrapper", environment);
            this.renderEvent("end".concat(_scopeBits[0] === "chapter" ? "Chapter" : "Verses"), environment);
            environment.context.sequences[0].block.wrappers.shift();
            delete environment.context.sequences[0].element;
            this.currentCV[_scopeBits[0]] = null;
          }
        } else if (["pubChapter", "pubVerse", "altChapter", "altVerse"].includes(_scopeBits[0])) {
          if (item.subType === "start") {
            var mark = {
              type: "mark",
              subType: camelCaseToSnakeCase(_scopeBits[0]),
              atts: {
                number: _scopeBits[1]
              }
            };
            environment.context.sequences[0].element = mark;
            this.renderEvent("mark", environment);
            delete environment.context.sequences[0].element;
          }
        } else if (_scopeBits[0] === "span") {
          var _wrapper4 = {
            type: "wrapper",
            subType: "usfm:".concat(_scopeBits[1]),
            atts: {}
          };
          environment.context.sequences[0].element = _wrapper4;
          if (item.subType === "start") {
            environment.context.sequences[0].block.wrappers.unshift(_wrapper4.subType);
            this.renderEvent("startWrapper", environment);
          } else {
            this.renderEvent("endWrapper", environment);
            environment.context.sequences[0].block.wrappers.shift();
          }
          delete environment.context.sequences[0].element;
        } else if (_scopeBits[0] === "spanWithAtts") {
          if (item.subType === "start") {
            this._container = {
              direction: "start",
              type: "wrapper",
              subType: "usfm:".concat(_scopeBits[1]),
              atts: {}
            };
          } else {
            var _wrapper5 = {
              type: "wrapper",
              subType: "usfm:".concat(_scopeBits[1]),
              atts: {}
            };
            if (item.payload.includes("spanWith"))
              ;
            environment.context.sequences[0].element = _wrapper5;
            this.renderEvent("endWrapper", environment);
            environment.context.sequences[0].block.wrappers.shift();
          }
        } else if (_scopeBits[0] === "cell") {
          var _wrapper6 = {
            direction: "start",
            type: "wrapper",
            subType: _scopeBits[0],
            atts: {
              role: _scopeBits[1],
              alignment: _scopeBits[2],
              nCols: parseInt(_scopeBits[3])
            }
          };
          environment.context.sequences[0].element = _wrapper6;
          if (item.subType === "start") {
            environment.context.sequences[0].block.wrappers.unshift(_wrapper6.subType);
            this.renderEvent("startWrapper", environment);
          } else {
            this.renderEvent("endWrapper", environment);
            environment.context.sequences[0].block.wrappers.shift();
          }
          delete environment.context.sequences[0].element;
        } else if (_scopeBits[0] === "milestone" && item.subType === "start") {
          if (_scopeBits[1] === "ts") {
            var _mark = {
              type: "mark",
              subType: "usfm:".concat(camelCaseToSnakeCase(_scopeBits[1])),
              atts: {}
            };
            environment.context.sequences[0].element = _mark;
            this.renderEvent("mark", environment);
            delete environment.context.sequences[0].element;
          } else {
            this._container = {
              type: "start_milestone",
              subType: "usfm:".concat(camelCaseToSnakeCase(_scopeBits[1])),
              atts: {}
            };
          }
        } else if (_scopeBits[0] === "milestone") {
          this._container = {
            type: "end_milestone",
            subType: "usfm:".concat(camelCaseToSnakeCase(_scopeBits[1])),
            atts: {}
          };
          this.renderContainer(environment);
        }
      }
    }
  }
  maybeRenderText(environment, sequenceId) {
    if (this._tokens.length === 0) {
      return;
    }
    var elementContext = {
      type: "text",
      text: this._tokens.join("")
    };
    environment.context.sequences[0].element = elementContext;
    this._tokens = [];
    this.renderEvent("text", environment);
    if (environment.workspace.inTable) {
      environment.workspace.tableHasContent = true;
    }
    delete environment.context.sequences[0].element;
  }
  blockForCv(environment, sequenceId, sequenceType) {
    var blocksResult1 = [];
    while (environment.workspace.chapters.length > 0) {
      var currentChapter = environment.workspace.chapters.shift();
      blocksResult1.push(this.pk.gqlQuerySync('{\n                 document(id: "'.concat(environment.context.document.id, '") {\n                      cvIndex(chapter: ').concat(currentChapter, ") {\n                        verses {\n                          verse {\n                            items(includeContext: true) {\n                              payload\n                              type\n                              subType\n                            }\n                          }\n                        }\n                      \n                   }\n                 }\n               }")).data.document.cvIndex.verses.map((e) => e.verse));
    }
    blocksResult1 = blocksResult1.flat().filter((e) => e.length > 0).map((e) => e[0]);
    for (var i = 0; i < blocksResult1.length; i++) {
      var _environment$config3, _blockResult, _blockResult2;
      if (((_environment$config3 = environment.config) === null || _environment$config3 === void 0 || (_environment$config3 = _environment$config3.excludeScopeTypes) === null || _environment$config3 === void 0 ? void 0 : _environment$config3.length) > 0) {
        var blockResult = {
          items: blocksResult1[i].items.filter((e) => e.subType != "heading" && e.subType != "title" && !environment.config.excludeScopeTypes.some((scopeType) => e.payload.includes(scopeType)))
        };
      } else {
        var blockResult = {
          items: blocksResult1[i].items.filter((e) => e.subType != "heading" && e.subType != "title")
        };
      }
      blockResult["bs"] = {
        payload: "blockTag/m"
      };
      if (((_blockResult = blockResult) === null || _blockResult === void 0 || (_blockResult = _blockResult.bg) === null || _blockResult === void 0 ? void 0 : _blockResult.length) > 0) {
        for (var blockGraft of blockResult.bg) {
          environment.context.sequences[0].block = {
            type: "graft",
            subType: camelCaseToSnakeCase(blockGraft.subType),
            sequence: environment.context.sequences[sequenceId]
          };
          this.cachedSequenceIds.unshift(blockGraft.payload);
          this.renderEvent("blockGraft", environment);
          this.cachedSequenceIds.shift();
        }
      }
      var subTypeValues = (_blockResult2 = blockResult) === null || _blockResult2 === void 0 || (_blockResult2 = _blockResult2.bs) === null || _blockResult2 === void 0 ? void 0 : _blockResult2.payload.split("/");
      var subTypeValue = void 0;
      if (subTypeValues) {
        if (subTypeValues[1] && ["tr", "zrow"].includes(subTypeValues[1])) {
          subTypeValue = subTypeValues[1] === "tr" ? "usfm:tr" : "pk";
        } else if (subTypeValues[1]) {
          subTypeValue = "usfm:".concat(subTypeValues[1]);
        } else {
          subTypeValue = subTypeValues[0];
        }
      }
      environment.context.sequences[0].block = {
        type: ["usfm:tr", "pk"].includes(subTypeValue) ? "row" : "paragraph",
        subType: subTypeValue,
        wrappers: []
      };
      if (environment.context.sequences[0].block.type === "row") {
        if (!environment.workspace.inTable) {
          this.renderEvent("startTable", environment);
          environment.workspace.inTable = true;
        }
        this.renderEvent("startRow", environment);
      } else {
        if (environment.workspace.inTable && environment.context.sequences[0].type.includes("main")) {
          this.renderEvent("endTable", environment);
          environment.workspace.tableHasContent = false;
          environment.workspace.inTable = false;
          environment.workspace.skipEndRow = false;
        }
        this.renderEvent("startParagraph", environment);
      }
      this._tokens = [];
      if (sequenceType === "main" && this.currentCV.chapter) {
        var wrapper = {
          type: "wrapper",
          subType: "chapter",
          atts: {
            number: this.currentCV.chapter
          }
        };
        environment.context.sequences[0].element = wrapper;
        environment.context.sequences[0].block.wrappers.unshift(wrapper.subType);
        this.renderEvent("startWrapper", environment);
      }
      if (sequenceType === "main" && this.currentCV.verses) {
        var _wrapper7 = {
          type: "wrapper",
          subType: "verses",
          atts: {
            number: this.currentCV.verses
          }
        };
        environment.context.sequences[0].element = _wrapper7;
        environment.context.sequences[0].block.wrappers.unshift(_wrapper7.subType);
        this.renderEvent("startWrapper", environment);
      }
      this.renderContent(blockResult.items, environment);
      this._tokens = [];
      if (sequenceType === "main" && this.currentCV.verses) {
        var _wrapper8 = {
          type: "wrapper",
          subType: "verses",
          atts: {
            number: this.currentCV.verses
          }
        };
        environment.context.sequences[0].element = _wrapper8;
        environment.context.sequences[0].block.wrappers.shift();
        this.renderEvent("endWrapper", environment);
      }
      if (sequenceType === "main" && this.currentCV.chapter) {
        var _wrapper9 = {
          type: "wrapper",
          subType: "chapter",
          atts: {
            number: this.currentCV.chapter
          }
        };
        environment.context.sequences[0].element = _wrapper9;
        environment.context.sequences[0].block.wrappers.shift();
        this.renderEvent("endWrapper", environment);
      }
      if (environment.context.sequences[0].block.type === "row" && !environment.workspace.skipEndRow) {
        this.renderEvent("endRow", environment);
      } else if (environment.workspace.skipEndRow && environment.context.sequences[0].block.type === "row") {
        environment.workspace.skipEndRow = false;
      } else {
        this.renderEvent("endParagraph", environment);
      }
      delete environment.context.sequences[0].block;
    }
    if (environment.workspace.inTable && environment.context.sequences[0].type.includes("main")) {
      this.renderEvent("endTable", environment);
      environment.workspace.tableHasContent = false;
      environment.workspace.inTable = false;
      environment.workspace.skipEndRow = false;
    }
    this.renderEvent("endSequence", environment);
    environment.context.sequences.shift();
  }
  renderContainer(environment) {
    if (this._container.type === "wrapper") {
      var direction = this._container.direction;
      delete this._container.direction;
      if (direction === "start") {
        environment.context.sequences[0].element = this._container;
        environment.context.sequences[0].block.wrappers.unshift(this._container.subType);
        this.renderEvent("startWrapper", environment);
        delete environment.context.sequences[0].element;
      } else {
        environment.context.sequences[0].element = this._container;
        this.renderEvent("endWrapper", environment);
        environment.context.sequences[0].block.wrappers.shift();
        delete environment.context.sequences[0].element;
      }
    } else if (this._container.type === "start_milestone") {
      environment.context.sequences[0].element = this._container;
      this.renderEvent("startMilestone", environment);
      delete environment.context.sequences[0].element;
    } else if (this._container.type === "end_milestone") {
      environment.context.sequences[0].element = this._container;
      this.renderEvent("endMilestone", environment);
      delete environment.context.sequences[0].element;
      this._container = null;
    }
    this._container = null;
  }
};
var SofriaRenderFromProskomma_1 = SofriaRenderFromProskomma$1;
var Validator2 = validator;
var usfmHelps = usfmHelps$1;
var usfmJsHelps = usfmJsHelps$2;
var PipelineHandler2 = PipelineHandler_1;
var ProskommaRender2 = ProskommaRender_1;
var PerfRenderFromJson$1 = PerfRenderFromJson_1;
var PerfRenderFromProskomma2 = PerfRenderFromProskomma_1;
var SofriaRenderFromJson2 = SofriaRenderFromJson_1;
var SofriaRenderFromProskomma2 = SofriaRenderFromProskomma_1;
var mergeActions = mergeActions_1;
var pipelines$1 = pipelines$2;
var render = render$1;
var dist = {
  Validator: Validator2,
  usfmHelps,
  usfmJsHelps,
  ProskommaRender: ProskommaRender2,
  PerfRenderFromJson: PerfRenderFromJson$1,
  SofriaRenderFromJson: SofriaRenderFromJson2,
  SofriaRenderFromProskomma: SofriaRenderFromProskomma2,
  PerfRenderFromProskomma: PerfRenderFromProskomma2,
  mergeActions,
  PipelineHandler: PipelineHandler2,
  pipelines: pipelines$1,
  render
};
const lexingRegexes = [
  ["chapter", "chapter", XRegExp("([\\r\\n]*\\\\c[ \\t]+(\\d+)[ \\t\\r\\n]*)")],
  [
    "pubchapter",
    "pubchapter",
    XRegExp("([\\r\\n]*\\\\cp[ \\t]+([^\\r\\n]+)[ \\t\\r\\n]*)")
  ],
  ["verses", "verses", XRegExp("(\\\\v[ \\t]+([\\d\\-]+)[ \\t\\r\\n]*)")],
  [
    "attribute",
    "attribute",
    XRegExp('([ \\t]*\\|?[ \\t]*([A-Za-z0-9\\-]+)="([^"]*)"[ \\t]?)')
  ],
  ["attribute", "defaultAttribute", XRegExp("([ \\t]*\\|[ \\t]*([^\\|\\\\]*))")],
  ["milestone", "emptyMilestone", XRegExp('(\\\\([a-z1-9]+)([ \\t]*\\|[ \\t]*[a-z1-9]+="[^\\|\\\\"]*")*\\\\[*])')],
  ["milestone", "startMilestoneTag", XRegExp("(\\\\([a-z1-9]+)-([se]))")],
  ["milestone", "endMilestoneMarker", XRegExp("(\\\\([*]))")],
  ["tag", "endTag", XRegExp("(\\\\([+]?[a-z\\-]+)([1-9]?(-([1-9]))?)[*])")],
  ["tag", "startTag", XRegExp("(\\\\([+]?[a-z\\-]+)([1-9]?(-([1-9]))?)[ \\t]?)")],
  ["bad", "bareSlash", XRegExp("(\\\\)")],
  ["printable", "eol", XRegExp("([ \\t]*[\\r\\n]+[ \\t]*)")],
  // ['break', 'noBreakSpace', xre('~')],
  ["break", "softLineBreak", XRegExp("//")],
  [
    "printable",
    "wordLike",
    XRegExp("([\\p{Letter}\\p{Number}\\p{Mark}\\u2060~]{1,127})")
  ],
  ["printable", "lineSpace", XRegExp("([\\p{Separator}	]{1,127})")],
  [
    "printable",
    "punctuation",
    XRegExp(
      "([\\p{Punctuation}\\p{Math_Symbol}\\p{Currency_Symbol}\\p{Modifier_Symbol}\\p{Other_Symbol}])"
    )
  ],
  ["bad", "unknown", XRegExp("(.)")]
];
const mainRegex = XRegExp.union(lexingRegexes.map((x) => x[2]));
const makePrintable = (subclass, matchedBits) => ({
  subclass,
  printValue: matchedBits[0].replace(/~/g, " ")
});
const makeChapter = (subclass, matchedBits) => ({
  subclass,
  numberString: matchedBits[2],
  number: parseInt(matchedBits[2]),
  printValue: `\\c ${matchedBits[2]}
`
});
const makeVerses = (subclass, matchedBits) => {
  const ret = {
    subclass,
    numberString: matchedBits[2],
    printValue: `\\v ${matchedBits[2]}
`
  };
  if (ret.numberString.includes("-")) {
    let [fromV, toV] = ret.numberString.split("-").map((v) => parseInt(v));
    if (!toV) {
      toV = fromV;
    }
    ret.numbers = Array.from(Array(toV - fromV + 1).keys()).map(
      (v) => v + fromV
    );
  } else {
    ret.numbers = [parseInt(ret.numberString)];
  }
  return ret;
};
const makeAttribute = (subclass, matchedBits) => {
  let ret;
  if (subclass === "defaultAttribute") {
    ret = {
      subclass,
      key: "default",
      valueString: matchedBits[2].trim().replace(/\//g, "÷")
    };
  } else {
    ret = {
      subclass,
      key: matchedBits[2],
      valueString: matchedBits[3].trim().replace(/\//g, "÷")
    };
  }
  ret.values = ret.valueString.split(",").map((vb) => vb.trim());
  ret.printValue = `| ${ret.key}="${ret.valueString}"`;
  return ret;
};
const makePubChapter = (subclass, matchedBits) => ({
  subclass,
  numberString: matchedBits[2],
  printValue: `\\cp ${matchedBits[2]}
`
});
const makeMilestone = (subclass, matchedBits) => {
  const ret = {
    subclass,
    sOrE: null
  };
  if (subclass === "endMilestoneMarker") {
    ret.printValue = "\\*";
  } else {
    ret.tagName = matchedBits[2];
    if (subclass === "emptyMilestone") {
      ret.printValue = `\\${ret.tagName}\\*`;
      ret.attributes = matchedBits[1] ? matchedBits[1].split("|").slice(1).map((a) => a.split("=")).map(
        (aa) => [
          aa[0],
          aa[1].replace(/"/g, "").replace(/[\\*]/g, "")
        ]
      ) : [];
    } else {
      ret.printValue = `\\${ret.tagName}`;
      ret.sOrE = matchedBits[3];
    }
  }
  return ret;
};
const makeTag = (subclass, matchedBits) => {
  const ret = {
    subclass,
    tagName: matchedBits[2],
    isNested: false
  };
  if (ret.tagName.startsWith("+")) {
    ret.isNested = true;
    ret.tagName = ret.tagName.substring(1);
  }
  ret.tagLevel = matchedBits[3] !== "" ? parseInt(matchedBits[3]) : 1;
  ret.fullTagName = `${ret.tagName}${matchedBits[3] === "1" ? "" : matchedBits[3]}`;
  ret.printValue = subclass === "startTag" ? `\\${ret.fullTagName} ` : `\\${ret.fullTagName}*`;
  return ret;
};
const constructorForFragment = {
  printable: makePrintable,
  chapter: makeChapter,
  pubchapter: makePubChapter,
  verses: makeVerses,
  tag: makeTag,
  break: makePrintable,
  milestone: makeMilestone,
  attribute: makeAttribute,
  bad: makePrintable
};
const preTokenObjectForFragment = (fragment, lexingRegexes2) => {
  for (let n = 0; n < lexingRegexes2.length; n++) {
    let [tClass, tSubclass, tRE] = lexingRegexes2[n];
    let matchedBits = XRegExp.exec(fragment, tRE, 0, "sticky");
    if (matchedBits) {
      return constructorForFragment[tClass](tSubclass, matchedBits);
    }
  }
  throw new Error(`Could not match preToken fragment '${fragment}'`);
};
const parseUsfm = (str, parser) => {
  const matches = XRegExp.match(str, mainRegex, "all");
  for (let n = 0; n < matches.length; n++) {
    parser.parseItem(preTokenObjectForFragment(matches[n], lexingRegexes));
  }
};
var sax$1 = {};
var emitterComponent;
var hasRequiredEmitterComponent;
function requireEmitterComponent() {
  if (hasRequiredEmitterComponent)
    return emitterComponent;
  hasRequiredEmitterComponent = 1;
  emitterComponent = Emitter;
  function Emitter(obj) {
    if (obj)
      return mixin(obj);
  }
  function mixin(obj) {
    for (var key in Emitter.prototype) {
      obj[key] = Emitter.prototype[key];
    }
    return obj;
  }
  Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
    this._callbacks = this._callbacks || {};
    (this._callbacks[event] = this._callbacks[event] || []).push(fn);
    return this;
  };
  Emitter.prototype.once = function(event, fn) {
    var self2 = this;
    this._callbacks = this._callbacks || {};
    function on() {
      self2.off(event, on);
      fn.apply(this, arguments);
    }
    on.fn = fn;
    this.on(event, on);
    return this;
  };
  Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
    this._callbacks = this._callbacks || {};
    if (0 == arguments.length) {
      this._callbacks = {};
      return this;
    }
    var callbacks = this._callbacks[event];
    if (!callbacks)
      return this;
    if (1 == arguments.length) {
      delete this._callbacks[event];
      return this;
    }
    var cb;
    for (var i = 0; i < callbacks.length; i++) {
      cb = callbacks[i];
      if (cb === fn || cb.fn === fn) {
        callbacks.splice(i, 1);
        break;
      }
    }
    return this;
  };
  Emitter.prototype.emit = function(event) {
    this._callbacks = this._callbacks || {};
    var args = [].slice.call(arguments, 1), callbacks = this._callbacks[event];
    if (callbacks) {
      callbacks = callbacks.slice(0);
      for (var i = 0, len = callbacks.length; i < len; ++i) {
        callbacks[i].apply(this, args);
      }
    }
    return this;
  };
  Emitter.prototype.listeners = function(event) {
    this._callbacks = this._callbacks || {};
    return this._callbacks[event] || [];
  };
  Emitter.prototype.hasListeners = function(event) {
    return !!this.listeners(event).length;
  };
  return emitterComponent;
}
var stream;
var hasRequiredStream;
function requireStream() {
  if (hasRequiredStream)
    return stream;
  hasRequiredStream = 1;
  var Emitter = requireEmitterComponent();
  function Stream() {
    Emitter.call(this);
  }
  Stream.prototype = new Emitter();
  stream = Stream;
  Stream.Stream = Stream;
  Stream.prototype.pipe = function(dest, options2) {
    var source = this;
    function ondata(chunk) {
      if (dest.writable) {
        if (false === dest.write(chunk) && source.pause) {
          source.pause();
        }
      }
    }
    source.on("data", ondata);
    function ondrain() {
      if (source.readable && source.resume) {
        source.resume();
      }
    }
    dest.on("drain", ondrain);
    if (!dest._isStdio && (!options2 || options2.end !== false)) {
      source.on("end", onend);
      source.on("close", onclose);
    }
    var didOnEnd = false;
    function onend() {
      if (didOnEnd)
        return;
      didOnEnd = true;
      dest.end();
    }
    function onclose() {
      if (didOnEnd)
        return;
      didOnEnd = true;
      if (typeof dest.destroy === "function")
        dest.destroy();
    }
    function onerror(er) {
      cleanup();
      if (!this.hasListeners("error")) {
        throw er;
      }
    }
    source.on("error", onerror);
    dest.on("error", onerror);
    function cleanup() {
      source.off("data", ondata);
      dest.off("drain", ondrain);
      source.off("end", onend);
      source.off("close", onclose);
      source.off("error", onerror);
      dest.off("error", onerror);
      source.off("end", cleanup);
      source.off("close", cleanup);
      dest.off("end", cleanup);
      dest.off("close", cleanup);
    }
    source.on("end", cleanup);
    source.on("close", cleanup);
    dest.on("end", cleanup);
    dest.on("close", cleanup);
    dest.emit("pipe", source);
    return dest;
  };
  return stream;
}
var string_decoder = {};
var safeBuffer = { exports: {} };
var buffer = {};
var ieee754 = {};
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
var hasRequiredIeee754;
function requireIeee754() {
  if (hasRequiredIeee754)
    return ieee754;
  hasRequiredIeee754 = 1;
  ieee754.read = function(buffer2, offset, isLE, mLen, nBytes) {
    var e, m;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var nBits = -7;
    var i = isLE ? nBytes - 1 : 0;
    var d = isLE ? -1 : 1;
    var s = buffer2[offset + i];
    i += d;
    e = s & (1 << -nBits) - 1;
    s >>= -nBits;
    nBits += eLen;
    for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) {
    }
    m = e & (1 << -nBits) - 1;
    e >>= -nBits;
    nBits += mLen;
    for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) {
    }
    if (e === 0) {
      e = 1 - eBias;
    } else if (e === eMax) {
      return m ? NaN : (s ? -1 : 1) * Infinity;
    } else {
      m = m + Math.pow(2, mLen);
      e = e - eBias;
    }
    return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  };
  ieee754.write = function(buffer2, value, offset, isLE, mLen, nBytes) {
    var e, m, c;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
    var i = isLE ? 0 : nBytes - 1;
    var d = isLE ? 1 : -1;
    var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
    value = Math.abs(value);
    if (isNaN(value) || value === Infinity) {
      m = isNaN(value) ? 1 : 0;
      e = eMax;
    } else {
      e = Math.floor(Math.log(value) / Math.LN2);
      if (value * (c = Math.pow(2, -e)) < 1) {
        e--;
        c *= 2;
      }
      if (e + eBias >= 1) {
        value += rt / c;
      } else {
        value += rt * Math.pow(2, 1 - eBias);
      }
      if (value * c >= 2) {
        e++;
        c /= 2;
      }
      if (e + eBias >= eMax) {
        m = 0;
        e = eMax;
      } else if (e + eBias >= 1) {
        m = (value * c - 1) * Math.pow(2, mLen);
        e = e + eBias;
      } else {
        m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
        e = 0;
      }
    }
    for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
    }
    e = e << mLen | m;
    eLen += mLen;
    for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
    }
    buffer2[offset + i - d] |= s * 128;
  };
  return ieee754;
}
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */
var hasRequiredBuffer;
function requireBuffer() {
  if (hasRequiredBuffer)
    return buffer;
  hasRequiredBuffer = 1;
  (function(exports2) {
    const base642 = base64Js;
    const ieee7542 = requireIeee754();
    const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
    exports2.Buffer = Buffer2;
    exports2.SlowBuffer = SlowBuffer;
    exports2.INSPECT_MAX_BYTES = 50;
    const K_MAX_LENGTH = 2147483647;
    exports2.kMaxLength = K_MAX_LENGTH;
    Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
    if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
      console.error(
        "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
      );
    }
    function typedArraySupport() {
      try {
        const arr = new Uint8Array(1);
        const proto = { foo: function() {
          return 42;
        } };
        Object.setPrototypeOf(proto, Uint8Array.prototype);
        Object.setPrototypeOf(arr, proto);
        return arr.foo() === 42;
      } catch (e) {
        return false;
      }
    }
    Object.defineProperty(Buffer2.prototype, "parent", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this))
          return void 0;
        return this.buffer;
      }
    });
    Object.defineProperty(Buffer2.prototype, "offset", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this))
          return void 0;
        return this.byteOffset;
      }
    });
    function createBuffer(length) {
      if (length > K_MAX_LENGTH) {
        throw new RangeError('The value "' + length + '" is invalid for option "size"');
      }
      const buf = new Uint8Array(length);
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function Buffer2(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        if (typeof encodingOrOffset === "string") {
          throw new TypeError(
            'The "string" argument must be of type string. Received type number'
          );
        }
        return allocUnsafe(arg);
      }
      return from(arg, encodingOrOffset, length);
    }
    Buffer2.poolSize = 8192;
    function from(value, encodingOrOffset, length) {
      if (typeof value === "string") {
        return fromString(value, encodingOrOffset);
      }
      if (ArrayBuffer.isView(value)) {
        return fromArrayView(value);
      }
      if (value == null) {
        throw new TypeError(
          "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
        );
      }
      if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
        return fromArrayBuffer(value, encodingOrOffset, length);
      }
      if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
        return fromArrayBuffer(value, encodingOrOffset, length);
      }
      if (typeof value === "number") {
        throw new TypeError(
          'The "value" argument must not be of type number. Received type number'
        );
      }
      const valueOf = value.valueOf && value.valueOf();
      if (valueOf != null && valueOf !== value) {
        return Buffer2.from(valueOf, encodingOrOffset, length);
      }
      const b = fromObject(value);
      if (b)
        return b;
      if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
        return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
      }
      throw new TypeError(
        "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
      );
    }
    Buffer2.from = function(value, encodingOrOffset, length) {
      return from(value, encodingOrOffset, length);
    };
    Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
    Object.setPrototypeOf(Buffer2, Uint8Array);
    function assertSize(size) {
      if (typeof size !== "number") {
        throw new TypeError('"size" argument must be of type number');
      } else if (size < 0) {
        throw new RangeError('The value "' + size + '" is invalid for option "size"');
      }
    }
    function alloc(size, fill, encoding) {
      assertSize(size);
      if (size <= 0) {
        return createBuffer(size);
      }
      if (fill !== void 0) {
        return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
      }
      return createBuffer(size);
    }
    Buffer2.alloc = function(size, fill, encoding) {
      return alloc(size, fill, encoding);
    };
    function allocUnsafe(size) {
      assertSize(size);
      return createBuffer(size < 0 ? 0 : checked(size) | 0);
    }
    Buffer2.allocUnsafe = function(size) {
      return allocUnsafe(size);
    };
    Buffer2.allocUnsafeSlow = function(size) {
      return allocUnsafe(size);
    };
    function fromString(string, encoding) {
      if (typeof encoding !== "string" || encoding === "") {
        encoding = "utf8";
      }
      if (!Buffer2.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      const length = byteLength2(string, encoding) | 0;
      let buf = createBuffer(length);
      const actual = buf.write(string, encoding);
      if (actual !== length) {
        buf = buf.slice(0, actual);
      }
      return buf;
    }
    function fromArrayLike(array) {
      const length = array.length < 0 ? 0 : checked(array.length) | 0;
      const buf = createBuffer(length);
      for (let i = 0; i < length; i += 1) {
        buf[i] = array[i] & 255;
      }
      return buf;
    }
    function fromArrayView(arrayView) {
      if (isInstance(arrayView, Uint8Array)) {
        const copy = new Uint8Array(arrayView);
        return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
      }
      return fromArrayLike(arrayView);
    }
    function fromArrayBuffer(array, byteOffset, length) {
      if (byteOffset < 0 || array.byteLength < byteOffset) {
        throw new RangeError('"offset" is outside of buffer bounds');
      }
      if (array.byteLength < byteOffset + (length || 0)) {
        throw new RangeError('"length" is outside of buffer bounds');
      }
      let buf;
      if (byteOffset === void 0 && length === void 0) {
        buf = new Uint8Array(array);
      } else if (length === void 0) {
        buf = new Uint8Array(array, byteOffset);
      } else {
        buf = new Uint8Array(array, byteOffset, length);
      }
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function fromObject(obj) {
      if (Buffer2.isBuffer(obj)) {
        const len = checked(obj.length) | 0;
        const buf = createBuffer(len);
        if (buf.length === 0) {
          return buf;
        }
        obj.copy(buf, 0, 0, len);
        return buf;
      }
      if (obj.length !== void 0) {
        if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
          return createBuffer(0);
        }
        return fromArrayLike(obj);
      }
      if (obj.type === "Buffer" && Array.isArray(obj.data)) {
        return fromArrayLike(obj.data);
      }
    }
    function checked(length) {
      if (length >= K_MAX_LENGTH) {
        throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
      }
      return length | 0;
    }
    function SlowBuffer(length) {
      if (+length != length) {
        length = 0;
      }
      return Buffer2.alloc(+length);
    }
    Buffer2.isBuffer = function isBuffer(b) {
      return b != null && b._isBuffer === true && b !== Buffer2.prototype;
    };
    Buffer2.compare = function compare(a, b) {
      if (isInstance(a, Uint8Array))
        a = Buffer2.from(a, a.offset, a.byteLength);
      if (isInstance(b, Uint8Array))
        b = Buffer2.from(b, b.offset, b.byteLength);
      if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {
        throw new TypeError(
          'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
        );
      }
      if (a === b)
        return 0;
      let x = a.length;
      let y = b.length;
      for (let i = 0, len = Math.min(x, y); i < len; ++i) {
        if (a[i] !== b[i]) {
          x = a[i];
          y = b[i];
          break;
        }
      }
      if (x < y)
        return -1;
      if (y < x)
        return 1;
      return 0;
    };
    Buffer2.isEncoding = function isEncoding(encoding) {
      switch (String(encoding).toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "latin1":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return true;
        default:
          return false;
      }
    };
    Buffer2.concat = function concat(list, length) {
      if (!Array.isArray(list)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      }
      if (list.length === 0) {
        return Buffer2.alloc(0);
      }
      let i;
      if (length === void 0) {
        length = 0;
        for (i = 0; i < list.length; ++i) {
          length += list[i].length;
        }
      }
      const buffer2 = Buffer2.allocUnsafe(length);
      let pos = 0;
      for (i = 0; i < list.length; ++i) {
        let buf = list[i];
        if (isInstance(buf, Uint8Array)) {
          if (pos + buf.length > buffer2.length) {
            if (!Buffer2.isBuffer(buf))
              buf = Buffer2.from(buf);
            buf.copy(buffer2, pos);
          } else {
            Uint8Array.prototype.set.call(
              buffer2,
              buf,
              pos
            );
          }
        } else if (!Buffer2.isBuffer(buf)) {
          throw new TypeError('"list" argument must be an Array of Buffers');
        } else {
          buf.copy(buffer2, pos);
        }
        pos += buf.length;
      }
      return buffer2;
    };
    function byteLength2(string, encoding) {
      if (Buffer2.isBuffer(string)) {
        return string.length;
      }
      if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
        return string.byteLength;
      }
      if (typeof string !== "string") {
        throw new TypeError(
          'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
        );
      }
      const len = string.length;
      const mustMatch = arguments.length > 2 && arguments[2] === true;
      if (!mustMatch && len === 0)
        return 0;
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "ascii":
          case "latin1":
          case "binary":
            return len;
          case "utf8":
          case "utf-8":
            return utf8ToBytes(string).length;
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return len * 2;
          case "hex":
            return len >>> 1;
          case "base64":
            return base64ToBytes(string).length;
          default:
            if (loweredCase) {
              return mustMatch ? -1 : utf8ToBytes(string).length;
            }
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.byteLength = byteLength2;
    function slowToString(encoding, start, end) {
      let loweredCase = false;
      if (start === void 0 || start < 0) {
        start = 0;
      }
      if (start > this.length) {
        return "";
      }
      if (end === void 0 || end > this.length) {
        end = this.length;
      }
      if (end <= 0) {
        return "";
      }
      end >>>= 0;
      start >>>= 0;
      if (end <= start) {
        return "";
      }
      if (!encoding)
        encoding = "utf8";
      while (true) {
        switch (encoding) {
          case "hex":
            return hexSlice(this, start, end);
          case "utf8":
          case "utf-8":
            return utf8Slice(this, start, end);
          case "ascii":
            return asciiSlice(this, start, end);
          case "latin1":
          case "binary":
            return latin1Slice(this, start, end);
          case "base64":
            return base64Slice(this, start, end);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return utf16leSlice(this, start, end);
          default:
            if (loweredCase)
              throw new TypeError("Unknown encoding: " + encoding);
            encoding = (encoding + "").toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.prototype._isBuffer = true;
    function swap(b, n, m) {
      const i = b[n];
      b[n] = b[m];
      b[m] = i;
    }
    Buffer2.prototype.swap16 = function swap16() {
      const len = this.length;
      if (len % 2 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 16-bits");
      }
      for (let i = 0; i < len; i += 2) {
        swap(this, i, i + 1);
      }
      return this;
    };
    Buffer2.prototype.swap32 = function swap32() {
      const len = this.length;
      if (len % 4 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 32-bits");
      }
      for (let i = 0; i < len; i += 4) {
        swap(this, i, i + 3);
        swap(this, i + 1, i + 2);
      }
      return this;
    };
    Buffer2.prototype.swap64 = function swap64() {
      const len = this.length;
      if (len % 8 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 64-bits");
      }
      for (let i = 0; i < len; i += 8) {
        swap(this, i, i + 7);
        swap(this, i + 1, i + 6);
        swap(this, i + 2, i + 5);
        swap(this, i + 3, i + 4);
      }
      return this;
    };
    Buffer2.prototype.toString = function toString() {
      const length = this.length;
      if (length === 0)
        return "";
      if (arguments.length === 0)
        return utf8Slice(this, 0, length);
      return slowToString.apply(this, arguments);
    };
    Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
    Buffer2.prototype.equals = function equals(b) {
      if (!Buffer2.isBuffer(b))
        throw new TypeError("Argument must be a Buffer");
      if (this === b)
        return true;
      return Buffer2.compare(this, b) === 0;
    };
    Buffer2.prototype.inspect = function inspect2() {
      let str = "";
      const max = exports2.INSPECT_MAX_BYTES;
      str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
      if (this.length > max)
        str += " ... ";
      return "<Buffer " + str + ">";
    };
    if (customInspectSymbol) {
      Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
    }
    Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
      if (isInstance(target, Uint8Array)) {
        target = Buffer2.from(target, target.offset, target.byteLength);
      }
      if (!Buffer2.isBuffer(target)) {
        throw new TypeError(
          'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
        );
      }
      if (start === void 0) {
        start = 0;
      }
      if (end === void 0) {
        end = target ? target.length : 0;
      }
      if (thisStart === void 0) {
        thisStart = 0;
      }
      if (thisEnd === void 0) {
        thisEnd = this.length;
      }
      if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
        throw new RangeError("out of range index");
      }
      if (thisStart >= thisEnd && start >= end) {
        return 0;
      }
      if (thisStart >= thisEnd) {
        return -1;
      }
      if (start >= end) {
        return 1;
      }
      start >>>= 0;
      end >>>= 0;
      thisStart >>>= 0;
      thisEnd >>>= 0;
      if (this === target)
        return 0;
      let x = thisEnd - thisStart;
      let y = end - start;
      const len = Math.min(x, y);
      const thisCopy = this.slice(thisStart, thisEnd);
      const targetCopy = target.slice(start, end);
      for (let i = 0; i < len; ++i) {
        if (thisCopy[i] !== targetCopy[i]) {
          x = thisCopy[i];
          y = targetCopy[i];
          break;
        }
      }
      if (x < y)
        return -1;
      if (y < x)
        return 1;
      return 0;
    };
    function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) {
      if (buffer2.length === 0)
        return -1;
      if (typeof byteOffset === "string") {
        encoding = byteOffset;
        byteOffset = 0;
      } else if (byteOffset > 2147483647) {
        byteOffset = 2147483647;
      } else if (byteOffset < -2147483648) {
        byteOffset = -2147483648;
      }
      byteOffset = +byteOffset;
      if (numberIsNaN(byteOffset)) {
        byteOffset = dir ? 0 : buffer2.length - 1;
      }
      if (byteOffset < 0)
        byteOffset = buffer2.length + byteOffset;
      if (byteOffset >= buffer2.length) {
        if (dir)
          return -1;
        else
          byteOffset = buffer2.length - 1;
      } else if (byteOffset < 0) {
        if (dir)
          byteOffset = 0;
        else
          return -1;
      }
      if (typeof val === "string") {
        val = Buffer2.from(val, encoding);
      }
      if (Buffer2.isBuffer(val)) {
        if (val.length === 0) {
          return -1;
        }
        return arrayIndexOf(buffer2, val, byteOffset, encoding, dir);
      } else if (typeof val === "number") {
        val = val & 255;
        if (typeof Uint8Array.prototype.indexOf === "function") {
          if (dir) {
            return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
          } else {
            return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
          }
        }
        return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir);
      }
      throw new TypeError("val must be string, number or Buffer");
    }
    function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
      let indexSize = 1;
      let arrLength = arr.length;
      let valLength = val.length;
      if (encoding !== void 0) {
        encoding = String(encoding).toLowerCase();
        if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
          if (arr.length < 2 || val.length < 2) {
            return -1;
          }
          indexSize = 2;
          arrLength /= 2;
          valLength /= 2;
          byteOffset /= 2;
        }
      }
      function read(buf, i2) {
        if (indexSize === 1) {
          return buf[i2];
        } else {
          return buf.readUInt16BE(i2 * indexSize);
        }
      }
      let i;
      if (dir) {
        let foundIndex = -1;
        for (i = byteOffset; i < arrLength; i++) {
          if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
            if (foundIndex === -1)
              foundIndex = i;
            if (i - foundIndex + 1 === valLength)
              return foundIndex * indexSize;
          } else {
            if (foundIndex !== -1)
              i -= i - foundIndex;
            foundIndex = -1;
          }
        }
      } else {
        if (byteOffset + valLength > arrLength)
          byteOffset = arrLength - valLength;
        for (i = byteOffset; i >= 0; i--) {
          let found = true;
          for (let j = 0; j < valLength; j++) {
            if (read(arr, i + j) !== read(val, j)) {
              found = false;
              break;
            }
          }
          if (found)
            return i;
        }
      }
      return -1;
    }
    Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
      return this.indexOf(val, byteOffset, encoding) !== -1;
    };
    Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
    };
    Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
    };
    function hexWrite(buf, string, offset, length) {
      offset = Number(offset) || 0;
      const remaining = buf.length - offset;
      if (!length) {
        length = remaining;
      } else {
        length = Number(length);
        if (length > remaining) {
          length = remaining;
        }
      }
      const strLen = string.length;
      if (length > strLen / 2) {
        length = strLen / 2;
      }
      let i;
      for (i = 0; i < length; ++i) {
        const parsed = parseInt(string.substr(i * 2, 2), 16);
        if (numberIsNaN(parsed))
          return i;
        buf[offset + i] = parsed;
      }
      return i;
    }
    function utf8Write(buf, string, offset, length) {
      return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
    }
    function asciiWrite(buf, string, offset, length) {
      return blitBuffer(asciiToBytes(string), buf, offset, length);
    }
    function base64Write(buf, string, offset, length) {
      return blitBuffer(base64ToBytes(string), buf, offset, length);
    }
    function ucs2Write(buf, string, offset, length) {
      return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
    }
    Buffer2.prototype.write = function write(string, offset, length, encoding) {
      if (offset === void 0) {
        encoding = "utf8";
        length = this.length;
        offset = 0;
      } else if (length === void 0 && typeof offset === "string") {
        encoding = offset;
        length = this.length;
        offset = 0;
      } else if (isFinite(offset)) {
        offset = offset >>> 0;
        if (isFinite(length)) {
          length = length >>> 0;
          if (encoding === void 0)
            encoding = "utf8";
        } else {
          encoding = length;
          length = void 0;
        }
      } else {
        throw new Error(
          "Buffer.write(string, encoding, offset[, length]) is no longer supported"
        );
      }
      const remaining = this.length - offset;
      if (length === void 0 || length > remaining)
        length = remaining;
      if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
        throw new RangeError("Attempt to write outside buffer bounds");
      }
      if (!encoding)
        encoding = "utf8";
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "hex":
            return hexWrite(this, string, offset, length);
          case "utf8":
          case "utf-8":
            return utf8Write(this, string, offset, length);
          case "ascii":
          case "latin1":
          case "binary":
            return asciiWrite(this, string, offset, length);
          case "base64":
            return base64Write(this, string, offset, length);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return ucs2Write(this, string, offset, length);
          default:
            if (loweredCase)
              throw new TypeError("Unknown encoding: " + encoding);
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    };
    Buffer2.prototype.toJSON = function toJSON() {
      return {
        type: "Buffer",
        data: Array.prototype.slice.call(this._arr || this, 0)
      };
    };
    function base64Slice(buf, start, end) {
      if (start === 0 && end === buf.length) {
        return base642.fromByteArray(buf);
      } else {
        return base642.fromByteArray(buf.slice(start, end));
      }
    }
    function utf8Slice(buf, start, end) {
      end = Math.min(buf.length, end);
      const res = [];
      let i = start;
      while (i < end) {
        const firstByte = buf[i];
        let codePoint = null;
        let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
        if (i + bytesPerSequence <= end) {
          let secondByte, thirdByte, fourthByte, tempCodePoint;
          switch (bytesPerSequence) {
            case 1:
              if (firstByte < 128) {
                codePoint = firstByte;
              }
              break;
            case 2:
              secondByte = buf[i + 1];
              if ((secondByte & 192) === 128) {
                tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
                if (tempCodePoint > 127) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 3:
              secondByte = buf[i + 1];
              thirdByte = buf[i + 2];
              if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
                tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
                if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 4:
              secondByte = buf[i + 1];
              thirdByte = buf[i + 2];
              fourthByte = buf[i + 3];
              if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
                tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
                if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                  codePoint = tempCodePoint;
                }
              }
          }
        }
        if (codePoint === null) {
          codePoint = 65533;
          bytesPerSequence = 1;
        } else if (codePoint > 65535) {
          codePoint -= 65536;
          res.push(codePoint >>> 10 & 1023 | 55296);
          codePoint = 56320 | codePoint & 1023;
        }
        res.push(codePoint);
        i += bytesPerSequence;
      }
      return decodeCodePointsArray(res);
    }
    const MAX_ARGUMENTS_LENGTH = 4096;
    function decodeCodePointsArray(codePoints) {
      const len = codePoints.length;
      if (len <= MAX_ARGUMENTS_LENGTH) {
        return String.fromCharCode.apply(String, codePoints);
      }
      let res = "";
      let i = 0;
      while (i < len) {
        res += String.fromCharCode.apply(
          String,
          codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
        );
      }
      return res;
    }
    function asciiSlice(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i = start; i < end; ++i) {
        ret += String.fromCharCode(buf[i] & 127);
      }
      return ret;
    }
    function latin1Slice(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i = start; i < end; ++i) {
        ret += String.fromCharCode(buf[i]);
      }
      return ret;
    }
    function hexSlice(buf, start, end) {
      const len = buf.length;
      if (!start || start < 0)
        start = 0;
      if (!end || end < 0 || end > len)
        end = len;
      let out = "";
      for (let i = start; i < end; ++i) {
        out += hexSliceLookupTable[buf[i]];
      }
      return out;
    }
    function utf16leSlice(buf, start, end) {
      const bytes = buf.slice(start, end);
      let res = "";
      for (let i = 0; i < bytes.length - 1; i += 2) {
        res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
      }
      return res;
    }
    Buffer2.prototype.slice = function slice(start, end) {
      const len = this.length;
      start = ~~start;
      end = end === void 0 ? len : ~~end;
      if (start < 0) {
        start += len;
        if (start < 0)
          start = 0;
      } else if (start > len) {
        start = len;
      }
      if (end < 0) {
        end += len;
        if (end < 0)
          end = 0;
      } else if (end > len) {
        end = len;
      }
      if (end < start)
        end = start;
      const newBuf = this.subarray(start, end);
      Object.setPrototypeOf(newBuf, Buffer2.prototype);
      return newBuf;
    };
    function checkOffset(offset, ext, length) {
      if (offset % 1 !== 0 || offset < 0)
        throw new RangeError("offset is not uint");
      if (offset + ext > length)
        throw new RangeError("Trying to access beyond buffer length");
    }
    Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert)
        checkOffset(offset, byteLength3, this.length);
      let val = this[offset];
      let mul = 1;
      let i = 0;
      while (++i < byteLength3 && (mul *= 256)) {
        val += this[offset + i] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        checkOffset(offset, byteLength3, this.length);
      }
      let val = this[offset + --byteLength3];
      let mul = 1;
      while (byteLength3 > 0 && (mul *= 256)) {
        val += this[offset + --byteLength3] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 1, this.length);
      return this[offset];
    };
    Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 2, this.length);
      return this[offset] | this[offset + 1] << 8;
    };
    Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 2, this.length);
      return this[offset] << 8 | this[offset + 1];
    };
    Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 4, this.length);
      return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
    };
    Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 4, this.length);
      return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
    };
    Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
      const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
      return BigInt(lo) + (BigInt(hi) << BigInt(32));
    });
    Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
      const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
      return (BigInt(hi) << BigInt(32)) + BigInt(lo);
    });
    Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert)
        checkOffset(offset, byteLength3, this.length);
      let val = this[offset];
      let mul = 1;
      let i = 0;
      while (++i < byteLength3 && (mul *= 256)) {
        val += this[offset + i] * mul;
      }
      mul *= 128;
      if (val >= mul)
        val -= Math.pow(2, 8 * byteLength3);
      return val;
    };
    Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert)
        checkOffset(offset, byteLength3, this.length);
      let i = byteLength3;
      let mul = 1;
      let val = this[offset + --i];
      while (i > 0 && (mul *= 256)) {
        val += this[offset + --i] * mul;
      }
      mul *= 128;
      if (val >= mul)
        val -= Math.pow(2, 8 * byteLength3);
      return val;
    };
    Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 1, this.length);
      if (!(this[offset] & 128))
        return this[offset];
      return (255 - this[offset] + 1) * -1;
    };
    Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 2, this.length);
      const val = this[offset] | this[offset + 1] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 2, this.length);
      const val = this[offset + 1] | this[offset] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 4, this.length);
      return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
    };
    Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 4, this.length);
      return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
    };
    Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
      return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
    });
    Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const val = (first << 24) + // Overflow
      this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
      return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
    });
    Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 4, this.length);
      return ieee7542.read(this, offset, true, 23, 4);
    };
    Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 4, this.length);
      return ieee7542.read(this, offset, false, 23, 4);
    };
    Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 8, this.length);
      return ieee7542.read(this, offset, true, 52, 8);
    };
    Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert)
        checkOffset(offset, 8, this.length);
      return ieee7542.read(this, offset, false, 52, 8);
    };
    function checkInt(buf, value, offset, ext, max, min) {
      if (!Buffer2.isBuffer(buf))
        throw new TypeError('"buffer" argument must be a Buffer instance');
      if (value > max || value < min)
        throw new RangeError('"value" argument is out of bounds');
      if (offset + ext > buf.length)
        throw new RangeError("Index out of range");
    }
    Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
        checkInt(this, value, offset, byteLength3, maxBytes, 0);
      }
      let mul = 1;
      let i = 0;
      this[offset] = value & 255;
      while (++i < byteLength3 && (mul *= 256)) {
        this[offset + i] = value / mul & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
        checkInt(this, value, offset, byteLength3, maxBytes, 0);
      }
      let i = byteLength3 - 1;
      let mul = 1;
      this[offset + i] = value & 255;
      while (--i >= 0 && (mul *= 256)) {
        this[offset + i] = value / mul & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 1, 255, 0);
      this[offset] = value & 255;
      return offset + 1;
    };
    Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 2, 65535, 0);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      return offset + 2;
    };
    Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 2, 65535, 0);
      this[offset] = value >>> 8;
      this[offset + 1] = value & 255;
      return offset + 2;
    };
    Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 4, 4294967295, 0);
      this[offset + 3] = value >>> 24;
      this[offset + 2] = value >>> 16;
      this[offset + 1] = value >>> 8;
      this[offset] = value & 255;
      return offset + 4;
    };
    Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 4, 4294967295, 0);
      this[offset] = value >>> 24;
      this[offset + 1] = value >>> 16;
      this[offset + 2] = value >>> 8;
      this[offset + 3] = value & 255;
      return offset + 4;
    };
    function wrtBigUInt64LE(buf, value, offset, min, max) {
      checkIntBI(value, min, max, buf, offset, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      return offset;
    }
    function wrtBigUInt64BE(buf, value, offset, min, max) {
      checkIntBI(value, min, max, buf, offset, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset + 7] = lo;
      lo = lo >> 8;
      buf[offset + 6] = lo;
      lo = lo >> 8;
      buf[offset + 5] = lo;
      lo = lo >> 8;
      buf[offset + 4] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset + 3] = hi;
      hi = hi >> 8;
      buf[offset + 2] = hi;
      hi = hi >> 8;
      buf[offset + 1] = hi;
      hi = hi >> 8;
      buf[offset] = hi;
      return offset + 8;
    }
    Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
      return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
      return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        const limit = Math.pow(2, 8 * byteLength3 - 1);
        checkInt(this, value, offset, byteLength3, limit - 1, -limit);
      }
      let i = 0;
      let mul = 1;
      let sub = 0;
      this[offset] = value & 255;
      while (++i < byteLength3 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
          sub = 1;
        }
        this[offset + i] = (value / mul >> 0) - sub & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        const limit = Math.pow(2, 8 * byteLength3 - 1);
        checkInt(this, value, offset, byteLength3, limit - 1, -limit);
      }
      let i = byteLength3 - 1;
      let mul = 1;
      let sub = 0;
      this[offset + i] = value & 255;
      while (--i >= 0 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
          sub = 1;
        }
        this[offset + i] = (value / mul >> 0) - sub & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 1, 127, -128);
      if (value < 0)
        value = 255 + value + 1;
      this[offset] = value & 255;
      return offset + 1;
    };
    Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 2, 32767, -32768);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      return offset + 2;
    };
    Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 2, 32767, -32768);
      this[offset] = value >>> 8;
      this[offset + 1] = value & 255;
      return offset + 2;
    };
    Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 4, 2147483647, -2147483648);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      this[offset + 2] = value >>> 16;
      this[offset + 3] = value >>> 24;
      return offset + 4;
    };
    Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert)
        checkInt(this, value, offset, 4, 2147483647, -2147483648);
      if (value < 0)
        value = 4294967295 + value + 1;
      this[offset] = value >>> 24;
      this[offset + 1] = value >>> 16;
      this[offset + 2] = value >>> 8;
      this[offset + 3] = value & 255;
      return offset + 4;
    };
    Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
      return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
      return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    function checkIEEE754(buf, value, offset, ext, max, min) {
      if (offset + ext > buf.length)
        throw new RangeError("Index out of range");
      if (offset < 0)
        throw new RangeError("Index out of range");
    }
    function writeFloat(buf, value, offset, littleEndian, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        checkIEEE754(buf, value, offset, 4);
      }
      ieee7542.write(buf, value, offset, littleEndian, 23, 4);
      return offset + 4;
    }
    Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
      return writeFloat(this, value, offset, true, noAssert);
    };
    Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
      return writeFloat(this, value, offset, false, noAssert);
    };
    function writeDouble(buf, value, offset, littleEndian, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        checkIEEE754(buf, value, offset, 8);
      }
      ieee7542.write(buf, value, offset, littleEndian, 52, 8);
      return offset + 8;
    }
    Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
      return writeDouble(this, value, offset, true, noAssert);
    };
    Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
      return writeDouble(this, value, offset, false, noAssert);
    };
    Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
      if (!Buffer2.isBuffer(target))
        throw new TypeError("argument should be a Buffer");
      if (!start)
        start = 0;
      if (!end && end !== 0)
        end = this.length;
      if (targetStart >= target.length)
        targetStart = target.length;
      if (!targetStart)
        targetStart = 0;
      if (end > 0 && end < start)
        end = start;
      if (end === start)
        return 0;
      if (target.length === 0 || this.length === 0)
        return 0;
      if (targetStart < 0) {
        throw new RangeError("targetStart out of bounds");
      }
      if (start < 0 || start >= this.length)
        throw new RangeError("Index out of range");
      if (end < 0)
        throw new RangeError("sourceEnd out of bounds");
      if (end > this.length)
        end = this.length;
      if (target.length - targetStart < end - start) {
        end = target.length - targetStart + start;
      }
      const len = end - start;
      if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
        this.copyWithin(targetStart, start, end);
      } else {
        Uint8Array.prototype.set.call(
          target,
          this.subarray(start, end),
          targetStart
        );
      }
      return len;
    };
    Buffer2.prototype.fill = function fill(val, start, end, encoding) {
      if (typeof val === "string") {
        if (typeof start === "string") {
          encoding = start;
          start = 0;
          end = this.length;
        } else if (typeof end === "string") {
          encoding = end;
          end = this.length;
        }
        if (encoding !== void 0 && typeof encoding !== "string") {
          throw new TypeError("encoding must be a string");
        }
        if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        if (val.length === 1) {
          const code2 = val.charCodeAt(0);
          if (encoding === "utf8" && code2 < 128 || encoding === "latin1") {
            val = code2;
          }
        }
      } else if (typeof val === "number") {
        val = val & 255;
      } else if (typeof val === "boolean") {
        val = Number(val);
      }
      if (start < 0 || this.length < start || this.length < end) {
        throw new RangeError("Out of range index");
      }
      if (end <= start) {
        return this;
      }
      start = start >>> 0;
      end = end === void 0 ? this.length : end >>> 0;
      if (!val)
        val = 0;
      let i;
      if (typeof val === "number") {
        for (i = start; i < end; ++i) {
          this[i] = val;
        }
      } else {
        const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
        const len = bytes.length;
        if (len === 0) {
          throw new TypeError('The value "' + val + '" is invalid for argument "value"');
        }
        for (i = 0; i < end - start; ++i) {
          this[i + start] = bytes[i % len];
        }
      }
      return this;
    };
    const errors2 = {};
    function E(sym, getMessage, Base) {
      errors2[sym] = class NodeError extends Base {
        constructor() {
          super();
          Object.defineProperty(this, "message", {
            value: getMessage.apply(this, arguments),
            writable: true,
            configurable: true
          });
          this.name = `${this.name} [${sym}]`;
          this.stack;
          delete this.name;
        }
        get code() {
          return sym;
        }
        set code(value) {
          Object.defineProperty(this, "code", {
            configurable: true,
            enumerable: true,
            value,
            writable: true
          });
        }
        toString() {
          return `${this.name} [${sym}]: ${this.message}`;
        }
      };
    }
    E(
      "ERR_BUFFER_OUT_OF_BOUNDS",
      function(name2) {
        if (name2) {
          return `${name2} is outside of buffer bounds`;
        }
        return "Attempt to access memory outside buffer bounds";
      },
      RangeError
    );
    E(
      "ERR_INVALID_ARG_TYPE",
      function(name2, actual) {
        return `The "${name2}" argument must be of type number. Received type ${typeof actual}`;
      },
      TypeError
    );
    E(
      "ERR_OUT_OF_RANGE",
      function(str, range, input) {
        let msg = `The value of "${str}" is out of range.`;
        let received = input;
        if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
          received = addNumericalSeparator(String(input));
        } else if (typeof input === "bigint") {
          received = String(input);
          if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
            received = addNumericalSeparator(received);
          }
          received += "n";
        }
        msg += ` It must be ${range}. Received ${received}`;
        return msg;
      },
      RangeError
    );
    function addNumericalSeparator(val) {
      let res = "";
      let i = val.length;
      const start = val[0] === "-" ? 1 : 0;
      for (; i >= start + 4; i -= 3) {
        res = `_${val.slice(i - 3, i)}${res}`;
      }
      return `${val.slice(0, i)}${res}`;
    }
    function checkBounds(buf, offset, byteLength3) {
      validateNumber(offset, "offset");
      if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) {
        boundsError(offset, buf.length - (byteLength3 + 1));
      }
    }
    function checkIntBI(value, min, max, buf, offset, byteLength3) {
      if (value > max || value < min) {
        const n = typeof min === "bigint" ? "n" : "";
        let range;
        if (byteLength3 > 3) {
          if (min === 0 || min === BigInt(0)) {
            range = `>= 0${n} and < 2${n} ** ${(byteLength3 + 1) * 8}${n}`;
          } else {
            range = `>= -(2${n} ** ${(byteLength3 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n}`;
          }
        } else {
          range = `>= ${min}${n} and <= ${max}${n}`;
        }
        throw new errors2.ERR_OUT_OF_RANGE("value", range, value);
      }
      checkBounds(buf, offset, byteLength3);
    }
    function validateNumber(value, name2) {
      if (typeof value !== "number") {
        throw new errors2.ERR_INVALID_ARG_TYPE(name2, "number", value);
      }
    }
    function boundsError(value, length, type2) {
      if (Math.floor(value) !== value) {
        validateNumber(value, type2);
        throw new errors2.ERR_OUT_OF_RANGE(type2 || "offset", "an integer", value);
      }
      if (length < 0) {
        throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS();
      }
      throw new errors2.ERR_OUT_OF_RANGE(
        type2 || "offset",
        `>= ${type2 ? 1 : 0} and <= ${length}`,
        value
      );
    }
    const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
    function base64clean(str) {
      str = str.split("=")[0];
      str = str.trim().replace(INVALID_BASE64_RE, "");
      if (str.length < 2)
        return "";
      while (str.length % 4 !== 0) {
        str = str + "=";
      }
      return str;
    }
    function utf8ToBytes(string, units) {
      units = units || Infinity;
      let codePoint;
      const length = string.length;
      let leadSurrogate = null;
      const bytes = [];
      for (let i = 0; i < length; ++i) {
        codePoint = string.charCodeAt(i);
        if (codePoint > 55295 && codePoint < 57344) {
          if (!leadSurrogate) {
            if (codePoint > 56319) {
              if ((units -= 3) > -1)
                bytes.push(239, 191, 189);
              continue;
            } else if (i + 1 === length) {
              if ((units -= 3) > -1)
                bytes.push(239, 191, 189);
              continue;
            }
            leadSurrogate = codePoint;
            continue;
          }
          if (codePoint < 56320) {
            if ((units -= 3) > -1)
              bytes.push(239, 191, 189);
            leadSurrogate = codePoint;
            continue;
          }
          codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
        } else if (leadSurrogate) {
          if ((units -= 3) > -1)
            bytes.push(239, 191, 189);
        }
        leadSurrogate = null;
        if (codePoint < 128) {
          if ((units -= 1) < 0)
            break;
          bytes.push(codePoint);
        } else if (codePoint < 2048) {
          if ((units -= 2) < 0)
            break;
          bytes.push(
            codePoint >> 6 | 192,
            codePoint & 63 | 128
          );
        } else if (codePoint < 65536) {
          if ((units -= 3) < 0)
            break;
          bytes.push(
            codePoint >> 12 | 224,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else if (codePoint < 1114112) {
          if ((units -= 4) < 0)
            break;
          bytes.push(
            codePoint >> 18 | 240,
            codePoint >> 12 & 63 | 128,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else {
          throw new Error("Invalid code point");
        }
      }
      return bytes;
    }
    function asciiToBytes(str) {
      const byteArray = [];
      for (let i = 0; i < str.length; ++i) {
        byteArray.push(str.charCodeAt(i) & 255);
      }
      return byteArray;
    }
    function utf16leToBytes(str, units) {
      let c, hi, lo;
      const byteArray = [];
      for (let i = 0; i < str.length; ++i) {
        if ((units -= 2) < 0)
          break;
        c = str.charCodeAt(i);
        hi = c >> 8;
        lo = c % 256;
        byteArray.push(lo);
        byteArray.push(hi);
      }
      return byteArray;
    }
    function base64ToBytes(str) {
      return base642.toByteArray(base64clean(str));
    }
    function blitBuffer(src2, dst, offset, length) {
      let i;
      for (i = 0; i < length; ++i) {
        if (i + offset >= dst.length || i >= src2.length)
          break;
        dst[i + offset] = src2[i];
      }
      return i;
    }
    function isInstance(obj, type2) {
      return obj instanceof type2 || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type2.name;
    }
    function numberIsNaN(obj) {
      return obj !== obj;
    }
    const hexSliceLookupTable = function() {
      const alphabet = "0123456789abcdef";
      const table = new Array(256);
      for (let i = 0; i < 16; ++i) {
        const i16 = i * 16;
        for (let j = 0; j < 16; ++j) {
          table[i16 + j] = alphabet[i] + alphabet[j];
        }
      }
      return table;
    }();
    function defineBigIntMethod(fn) {
      return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
    }
    function BufferBigIntNotDefined() {
      throw new Error("BigInt not supported");
    }
  })(buffer);
  return buffer;
}
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
var hasRequiredSafeBuffer;
function requireSafeBuffer() {
  if (hasRequiredSafeBuffer)
    return safeBuffer.exports;
  hasRequiredSafeBuffer = 1;
  (function(module2, exports2) {
    var buffer2 = requireBuffer();
    var Buffer2 = buffer2.Buffer;
    function copyProps(src2, dst) {
      for (var key in src2) {
        dst[key] = src2[key];
      }
    }
    if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {
      module2.exports = buffer2;
    } else {
      copyProps(buffer2, exports2);
      exports2.Buffer = SafeBuffer;
    }
    function SafeBuffer(arg, encodingOrOffset, length) {
      return Buffer2(arg, encodingOrOffset, length);
    }
    SafeBuffer.prototype = Object.create(Buffer2.prototype);
    copyProps(Buffer2, SafeBuffer);
    SafeBuffer.from = function(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        throw new TypeError("Argument must not be a number");
      }
      return Buffer2(arg, encodingOrOffset, length);
    };
    SafeBuffer.alloc = function(size, fill, encoding) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      var buf = Buffer2(size);
      if (fill !== void 0) {
        if (typeof encoding === "string") {
          buf.fill(fill, encoding);
        } else {
          buf.fill(fill);
        }
      } else {
        buf.fill(0);
      }
      return buf;
    };
    SafeBuffer.allocUnsafe = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return Buffer2(size);
    };
    SafeBuffer.allocUnsafeSlow = function(size) {
      if (typeof size !== "number") {
        throw new TypeError("Argument must be a number");
      }
      return buffer2.SlowBuffer(size);
    };
  })(safeBuffer, safeBuffer.exports);
  return safeBuffer.exports;
}
var hasRequiredString_decoder;
function requireString_decoder() {
  if (hasRequiredString_decoder)
    return string_decoder;
  hasRequiredString_decoder = 1;
  var Buffer2 = requireSafeBuffer().Buffer;
  var isEncoding = Buffer2.isEncoding || function(encoding) {
    encoding = "" + encoding;
    switch (encoding && encoding.toLowerCase()) {
      case "hex":
      case "utf8":
      case "utf-8":
      case "ascii":
      case "binary":
      case "base64":
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
      case "raw":
        return true;
      default:
        return false;
    }
  };
  function _normalizeEncoding(enc) {
    if (!enc)
      return "utf8";
    var retried;
    while (true) {
      switch (enc) {
        case "utf8":
        case "utf-8":
          return "utf8";
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return "utf16le";
        case "latin1":
        case "binary":
          return "latin1";
        case "base64":
        case "ascii":
        case "hex":
          return enc;
        default:
          if (retried)
            return;
          enc = ("" + enc).toLowerCase();
          retried = true;
      }
    }
  }
  function normalizeEncoding(enc) {
    var nenc = _normalizeEncoding(enc);
    if (typeof nenc !== "string" && (Buffer2.isEncoding === isEncoding || !isEncoding(enc)))
      throw new Error("Unknown encoding: " + enc);
    return nenc || enc;
  }
  string_decoder.StringDecoder = StringDecoder;
  function StringDecoder(encoding) {
    this.encoding = normalizeEncoding(encoding);
    var nb;
    switch (this.encoding) {
      case "utf16le":
        this.text = utf16Text;
        this.end = utf16End;
        nb = 4;
        break;
      case "utf8":
        this.fillLast = utf8FillLast;
        nb = 4;
        break;
      case "base64":
        this.text = base64Text;
        this.end = base64End;
        nb = 3;
        break;
      default:
        this.write = simpleWrite;
        this.end = simpleEnd;
        return;
    }
    this.lastNeed = 0;
    this.lastTotal = 0;
    this.lastChar = Buffer2.allocUnsafe(nb);
  }
  StringDecoder.prototype.write = function(buf) {
    if (buf.length === 0)
      return "";
    var r;
    var i;
    if (this.lastNeed) {
      r = this.fillLast(buf);
      if (r === void 0)
        return "";
      i = this.lastNeed;
      this.lastNeed = 0;
    } else {
      i = 0;
    }
    if (i < buf.length)
      return r ? r + this.text(buf, i) : this.text(buf, i);
    return r || "";
  };
  StringDecoder.prototype.end = utf8End;
  StringDecoder.prototype.text = utf8Text;
  StringDecoder.prototype.fillLast = function(buf) {
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
    this.lastNeed -= buf.length;
  };
  function utf8CheckByte(byte) {
    if (byte <= 127)
      return 0;
    else if (byte >> 5 === 6)
      return 2;
    else if (byte >> 4 === 14)
      return 3;
    else if (byte >> 3 === 30)
      return 4;
    return byte >> 6 === 2 ? -1 : -2;
  }
  function utf8CheckIncomplete(self2, buf, i) {
    var j = buf.length - 1;
    if (j < i)
      return 0;
    var nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0)
        self2.lastNeed = nb - 1;
      return nb;
    }
    if (--j < i || nb === -2)
      return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0)
        self2.lastNeed = nb - 2;
      return nb;
    }
    if (--j < i || nb === -2)
      return 0;
    nb = utf8CheckByte(buf[j]);
    if (nb >= 0) {
      if (nb > 0) {
        if (nb === 2)
          nb = 0;
        else
          self2.lastNeed = nb - 3;
      }
      return nb;
    }
    return 0;
  }
  function utf8CheckExtraBytes(self2, buf, p) {
    if ((buf[0] & 192) !== 128) {
      self2.lastNeed = 0;
      return "�";
    }
    if (self2.lastNeed > 1 && buf.length > 1) {
      if ((buf[1] & 192) !== 128) {
        self2.lastNeed = 1;
        return "�";
      }
      if (self2.lastNeed > 2 && buf.length > 2) {
        if ((buf[2] & 192) !== 128) {
          self2.lastNeed = 2;
          return "�";
        }
      }
    }
  }
  function utf8FillLast(buf) {
    var p = this.lastTotal - this.lastNeed;
    var r = utf8CheckExtraBytes(this, buf);
    if (r !== void 0)
      return r;
    if (this.lastNeed <= buf.length) {
      buf.copy(this.lastChar, p, 0, this.lastNeed);
      return this.lastChar.toString(this.encoding, 0, this.lastTotal);
    }
    buf.copy(this.lastChar, p, 0, buf.length);
    this.lastNeed -= buf.length;
  }
  function utf8Text(buf, i) {
    var total = utf8CheckIncomplete(this, buf, i);
    if (!this.lastNeed)
      return buf.toString("utf8", i);
    this.lastTotal = total;
    var end = buf.length - (total - this.lastNeed);
    buf.copy(this.lastChar, 0, end);
    return buf.toString("utf8", i, end);
  }
  function utf8End(buf) {
    var r = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed)
      return r + "�";
    return r;
  }
  function utf16Text(buf, i) {
    if ((buf.length - i) % 2 === 0) {
      var r = buf.toString("utf16le", i);
      if (r) {
        var c = r.charCodeAt(r.length - 1);
        if (c >= 55296 && c <= 56319) {
          this.lastNeed = 2;
          this.lastTotal = 4;
          this.lastChar[0] = buf[buf.length - 2];
          this.lastChar[1] = buf[buf.length - 1];
          return r.slice(0, -1);
        }
      }
      return r;
    }
    this.lastNeed = 1;
    this.lastTotal = 2;
    this.lastChar[0] = buf[buf.length - 1];
    return buf.toString("utf16le", i, buf.length - 1);
  }
  function utf16End(buf) {
    var r = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed) {
      var end = this.lastTotal - this.lastNeed;
      return r + this.lastChar.toString("utf16le", 0, end);
    }
    return r;
  }
  function base64Text(buf, i) {
    var n = (buf.length - i) % 3;
    if (n === 0)
      return buf.toString("base64", i);
    this.lastNeed = 3 - n;
    this.lastTotal = 3;
    if (n === 1) {
      this.lastChar[0] = buf[buf.length - 1];
    } else {
      this.lastChar[0] = buf[buf.length - 2];
      this.lastChar[1] = buf[buf.length - 1];
    }
    return buf.toString("base64", i, buf.length - n);
  }
  function base64End(buf) {
    var r = buf && buf.length ? this.write(buf) : "";
    if (this.lastNeed)
      return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed);
    return r;
  }
  function simpleWrite(buf) {
    return buf.toString(this.encoding);
  }
  function simpleEnd(buf) {
    return buf && buf.length ? this.write(buf) : "";
  }
  return string_decoder;
}
(function(exports2) {
  (function(sax2) {
    sax2.parser = function(strict, opt) {
      return new SAXParser(strict, opt);
    };
    sax2.SAXParser = SAXParser;
    sax2.SAXStream = SAXStream;
    sax2.createStream = createStream;
    sax2.MAX_BUFFER_LENGTH = 64 * 1024;
    var buffers = [
      "comment",
      "sgmlDecl",
      "textNode",
      "tagName",
      "doctype",
      "procInstName",
      "procInstBody",
      "entity",
      "attribName",
      "attribValue",
      "cdata",
      "script"
    ];
    sax2.EVENTS = [
      "text",
      "processinginstruction",
      "sgmldeclaration",
      "doctype",
      "comment",
      "opentagstart",
      "attribute",
      "opentag",
      "closetag",
      "opencdata",
      "cdata",
      "closecdata",
      "error",
      "end",
      "ready",
      "script",
      "opennamespace",
      "closenamespace"
    ];
    function SAXParser(strict, opt) {
      if (!(this instanceof SAXParser)) {
        return new SAXParser(strict, opt);
      }
      var parser = this;
      clearBuffers(parser);
      parser.q = parser.c = "";
      parser.bufferCheckPosition = sax2.MAX_BUFFER_LENGTH;
      parser.opt = opt || {};
      parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags;
      parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase";
      parser.tags = [];
      parser.closed = parser.closedRoot = parser.sawRoot = false;
      parser.tag = parser.error = null;
      parser.strict = !!strict;
      parser.noscript = !!(strict || parser.opt.noscript);
      parser.state = S.BEGIN;
      parser.strictEntities = parser.opt.strictEntities;
      parser.ENTITIES = parser.strictEntities ? Object.create(sax2.XML_ENTITIES) : Object.create(sax2.ENTITIES);
      parser.attribList = [];
      if (parser.opt.xmlns) {
        parser.ns = Object.create(rootNS);
      }
      parser.trackPosition = parser.opt.position !== false;
      if (parser.trackPosition) {
        parser.position = parser.line = parser.column = 0;
      }
      emit(parser, "onready");
    }
    if (!Object.create) {
      Object.create = function(o) {
        function F() {
        }
        F.prototype = o;
        var newf = new F();
        return newf;
      };
    }
    if (!Object.keys) {
      Object.keys = function(o) {
        var a = [];
        for (var i in o)
          if (o.hasOwnProperty(i))
            a.push(i);
        return a;
      };
    }
    function checkBufferLength(parser) {
      var maxAllowed = Math.max(sax2.MAX_BUFFER_LENGTH, 10);
      var maxActual = 0;
      for (var i = 0, l = buffers.length; i < l; i++) {
        var len = parser[buffers[i]].length;
        if (len > maxAllowed) {
          switch (buffers[i]) {
            case "textNode":
              closeText(parser);
              break;
            case "cdata":
              emitNode(parser, "oncdata", parser.cdata);
              parser.cdata = "";
              break;
            case "script":
              emitNode(parser, "onscript", parser.script);
              parser.script = "";
              break;
            default:
              error2(parser, "Max buffer length exceeded: " + buffers[i]);
          }
        }
        maxActual = Math.max(maxActual, len);
      }
      var m = sax2.MAX_BUFFER_LENGTH - maxActual;
      parser.bufferCheckPosition = m + parser.position;
    }
    function clearBuffers(parser) {
      for (var i = 0, l = buffers.length; i < l; i++) {
        parser[buffers[i]] = "";
      }
    }
    function flushBuffers(parser) {
      closeText(parser);
      if (parser.cdata !== "") {
        emitNode(parser, "oncdata", parser.cdata);
        parser.cdata = "";
      }
      if (parser.script !== "") {
        emitNode(parser, "onscript", parser.script);
        parser.script = "";
      }
    }
    SAXParser.prototype = {
      end: function() {
        end(this);
      },
      write,
      resume: function() {
        this.error = null;
        return this;
      },
      close: function() {
        return this.write(null);
      },
      flush: function() {
        flushBuffers(this);
      }
    };
    var Stream;
    try {
      Stream = requireStream().Stream;
    } catch (ex) {
      Stream = function() {
      };
    }
    if (!Stream)
      Stream = function() {
      };
    var streamWraps = sax2.EVENTS.filter(function(ev) {
      return ev !== "error" && ev !== "end";
    });
    function createStream(strict, opt) {
      return new SAXStream(strict, opt);
    }
    function SAXStream(strict, opt) {
      if (!(this instanceof SAXStream)) {
        return new SAXStream(strict, opt);
      }
      Stream.apply(this);
      this._parser = new SAXParser(strict, opt);
      this.writable = true;
      this.readable = true;
      var me = this;
      this._parser.onend = function() {
        me.emit("end");
      };
      this._parser.onerror = function(er) {
        me.emit("error", er);
        me._parser.error = null;
      };
      this._decoder = null;
      streamWraps.forEach(function(ev) {
        Object.defineProperty(me, "on" + ev, {
          get: function() {
            return me._parser["on" + ev];
          },
          set: function(h) {
            if (!h) {
              me.removeAllListeners(ev);
              me._parser["on" + ev] = h;
              return h;
            }
            me.on(ev, h);
          },
          enumerable: true,
          configurable: false
        });
      });
    }
    SAXStream.prototype = Object.create(Stream.prototype, {
      constructor: {
        value: SAXStream
      }
    });
    SAXStream.prototype.write = function(data) {
      if (typeof Buffer === "function" && typeof Buffer.isBuffer === "function" && Buffer.isBuffer(data)) {
        if (!this._decoder) {
          var SD = requireString_decoder().StringDecoder;
          this._decoder = new SD("utf8");
        }
        data = this._decoder.write(data);
      }
      this._parser.write(data.toString());
      this.emit("data", data);
      return true;
    };
    SAXStream.prototype.end = function(chunk) {
      if (chunk && chunk.length) {
        this.write(chunk);
      }
      this._parser.end();
      return true;
    };
    SAXStream.prototype.on = function(ev, handler) {
      var me = this;
      if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) {
        me._parser["on" + ev] = function() {
          var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments);
          args.splice(0, 0, ev);
          me.emit.apply(me, args);
        };
      }
      return Stream.prototype.on.call(me, ev, handler);
    };
    var CDATA = "[CDATA[";
    var DOCTYPE = "DOCTYPE";
    var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace";
    var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/";
    var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE };
    var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
    var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
    var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;
    var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;
    function isWhitespace(c) {
      return c === " " || c === "\n" || c === "\r" || c === "	";
    }
    function isQuote(c) {
      return c === '"' || c === "'";
    }
    function isAttribEnd(c) {
      return c === ">" || isWhitespace(c);
    }
    function isMatch(regex, c) {
      return regex.test(c);
    }
    function notMatch(regex, c) {
      return !isMatch(regex, c);
    }
    var S = 0;
    sax2.STATE = {
      BEGIN: S++,
      // leading byte order mark or whitespace
      BEGIN_WHITESPACE: S++,
      // leading whitespace
      TEXT: S++,
      // general stuff
      TEXT_ENTITY: S++,
      // &amp and such.
      OPEN_WAKA: S++,
      // <
      SGML_DECL: S++,
      // <!BLARG
      SGML_DECL_QUOTED: S++,
      // <!BLARG foo "bar
      DOCTYPE: S++,
      // <!DOCTYPE
      DOCTYPE_QUOTED: S++,
      // <!DOCTYPE "//blah
      DOCTYPE_DTD: S++,
      // <!DOCTYPE "//blah" [ ...
      DOCTYPE_DTD_QUOTED: S++,
      // <!DOCTYPE "//blah" [ "foo
      COMMENT_STARTING: S++,
      // <!-
      COMMENT: S++,
      // <!--
      COMMENT_ENDING: S++,
      // <!-- blah -
      COMMENT_ENDED: S++,
      // <!-- blah --
      CDATA: S++,
      // <![CDATA[ something
      CDATA_ENDING: S++,
      // ]
      CDATA_ENDING_2: S++,
      // ]]
      PROC_INST: S++,
      // <?hi
      PROC_INST_BODY: S++,
      // <?hi there
      PROC_INST_ENDING: S++,
      // <?hi "there" ?
      OPEN_TAG: S++,
      // <strong
      OPEN_TAG_SLASH: S++,
      // <strong /
      ATTRIB: S++,
      // <a
      ATTRIB_NAME: S++,
      // <a foo
      ATTRIB_NAME_SAW_WHITE: S++,
      // <a foo _
      ATTRIB_VALUE: S++,
      // <a foo=
      ATTRIB_VALUE_QUOTED: S++,
      // <a foo="bar
      ATTRIB_VALUE_CLOSED: S++,
      // <a foo="bar"
      ATTRIB_VALUE_UNQUOTED: S++,
      // <a foo=bar
      ATTRIB_VALUE_ENTITY_Q: S++,
      // <foo bar="&quot;"
      ATTRIB_VALUE_ENTITY_U: S++,
      // <foo bar=&quot
      CLOSE_TAG: S++,
      // </a
      CLOSE_TAG_SAW_WHITE: S++,
      // </a   >
      SCRIPT: S++,
      // <script> ...
      SCRIPT_ENDING: S++
      // <script> ... <
    };
    sax2.XML_ENTITIES = {
      "amp": "&",
      "gt": ">",
      "lt": "<",
      "quot": '"',
      "apos": "'"
    };
    sax2.ENTITIES = {
      "amp": "&",
      "gt": ">",
      "lt": "<",
      "quot": '"',
      "apos": "'",
      "AElig": 198,
      "Aacute": 193,
      "Acirc": 194,
      "Agrave": 192,
      "Aring": 197,
      "Atilde": 195,
      "Auml": 196,
      "Ccedil": 199,
      "ETH": 208,
      "Eacute": 201,
      "Ecirc": 202,
      "Egrave": 200,
      "Euml": 203,
      "Iacute": 205,
      "Icirc": 206,
      "Igrave": 204,
      "Iuml": 207,
      "Ntilde": 209,
      "Oacute": 211,
      "Ocirc": 212,
      "Ograve": 210,
      "Oslash": 216,
      "Otilde": 213,
      "Ouml": 214,
      "THORN": 222,
      "Uacute": 218,
      "Ucirc": 219,
      "Ugrave": 217,
      "Uuml": 220,
      "Yacute": 221,
      "aacute": 225,
      "acirc": 226,
      "aelig": 230,
      "agrave": 224,
      "aring": 229,
      "atilde": 227,
      "auml": 228,
      "ccedil": 231,
      "eacute": 233,
      "ecirc": 234,
      "egrave": 232,
      "eth": 240,
      "euml": 235,
      "iacute": 237,
      "icirc": 238,
      "igrave": 236,
      "iuml": 239,
      "ntilde": 241,
      "oacute": 243,
      "ocirc": 244,
      "ograve": 242,
      "oslash": 248,
      "otilde": 245,
      "ouml": 246,
      "szlig": 223,
      "thorn": 254,
      "uacute": 250,
      "ucirc": 251,
      "ugrave": 249,
      "uuml": 252,
      "yacute": 253,
      "yuml": 255,
      "copy": 169,
      "reg": 174,
      "nbsp": 160,
      "iexcl": 161,
      "cent": 162,
      "pound": 163,
      "curren": 164,
      "yen": 165,
      "brvbar": 166,
      "sect": 167,
      "uml": 168,
      "ordf": 170,
      "laquo": 171,
      "not": 172,
      "shy": 173,
      "macr": 175,
      "deg": 176,
      "plusmn": 177,
      "sup1": 185,
      "sup2": 178,
      "sup3": 179,
      "acute": 180,
      "micro": 181,
      "para": 182,
      "middot": 183,
      "cedil": 184,
      "ordm": 186,
      "raquo": 187,
      "frac14": 188,
      "frac12": 189,
      "frac34": 190,
      "iquest": 191,
      "times": 215,
      "divide": 247,
      "OElig": 338,
      "oelig": 339,
      "Scaron": 352,
      "scaron": 353,
      "Yuml": 376,
      "fnof": 402,
      "circ": 710,
      "tilde": 732,
      "Alpha": 913,
      "Beta": 914,
      "Gamma": 915,
      "Delta": 916,
      "Epsilon": 917,
      "Zeta": 918,
      "Eta": 919,
      "Theta": 920,
      "Iota": 921,
      "Kappa": 922,
      "Lambda": 923,
      "Mu": 924,
      "Nu": 925,
      "Xi": 926,
      "Omicron": 927,
      "Pi": 928,
      "Rho": 929,
      "Sigma": 931,
      "Tau": 932,
      "Upsilon": 933,
      "Phi": 934,
      "Chi": 935,
      "Psi": 936,
      "Omega": 937,
      "alpha": 945,
      "beta": 946,
      "gamma": 947,
      "delta": 948,
      "epsilon": 949,
      "zeta": 950,
      "eta": 951,
      "theta": 952,
      "iota": 953,
      "kappa": 954,
      "lambda": 955,
      "mu": 956,
      "nu": 957,
      "xi": 958,
      "omicron": 959,
      "pi": 960,
      "rho": 961,
      "sigmaf": 962,
      "sigma": 963,
      "tau": 964,
      "upsilon": 965,
      "phi": 966,
      "chi": 967,
      "psi": 968,
      "omega": 969,
      "thetasym": 977,
      "upsih": 978,
      "piv": 982,
      "ensp": 8194,
      "emsp": 8195,
      "thinsp": 8201,
      "zwnj": 8204,
      "zwj": 8205,
      "lrm": 8206,
      "rlm": 8207,
      "ndash": 8211,
      "mdash": 8212,
      "lsquo": 8216,
      "rsquo": 8217,
      "sbquo": 8218,
      "ldquo": 8220,
      "rdquo": 8221,
      "bdquo": 8222,
      "dagger": 8224,
      "Dagger": 8225,
      "bull": 8226,
      "hellip": 8230,
      "permil": 8240,
      "prime": 8242,
      "Prime": 8243,
      "lsaquo": 8249,
      "rsaquo": 8250,
      "oline": 8254,
      "frasl": 8260,
      "euro": 8364,
      "image": 8465,
      "weierp": 8472,
      "real": 8476,
      "trade": 8482,
      "alefsym": 8501,
      "larr": 8592,
      "uarr": 8593,
      "rarr": 8594,
      "darr": 8595,
      "harr": 8596,
      "crarr": 8629,
      "lArr": 8656,
      "uArr": 8657,
      "rArr": 8658,
      "dArr": 8659,
      "hArr": 8660,
      "forall": 8704,
      "part": 8706,
      "exist": 8707,
      "empty": 8709,
      "nabla": 8711,
      "isin": 8712,
      "notin": 8713,
      "ni": 8715,
      "prod": 8719,
      "sum": 8721,
      "minus": 8722,
      "lowast": 8727,
      "radic": 8730,
      "prop": 8733,
      "infin": 8734,
      "ang": 8736,
      "and": 8743,
      "or": 8744,
      "cap": 8745,
      "cup": 8746,
      "int": 8747,
      "there4": 8756,
      "sim": 8764,
      "cong": 8773,
      "asymp": 8776,
      "ne": 8800,
      "equiv": 8801,
      "le": 8804,
      "ge": 8805,
      "sub": 8834,
      "sup": 8835,
      "nsub": 8836,
      "sube": 8838,
      "supe": 8839,
      "oplus": 8853,
      "otimes": 8855,
      "perp": 8869,
      "sdot": 8901,
      "lceil": 8968,
      "rceil": 8969,
      "lfloor": 8970,
      "rfloor": 8971,
      "lang": 9001,
      "rang": 9002,
      "loz": 9674,
      "spades": 9824,
      "clubs": 9827,
      "hearts": 9829,
      "diams": 9830
    };
    Object.keys(sax2.ENTITIES).forEach(function(key) {
      var e = sax2.ENTITIES[key];
      var s2 = typeof e === "number" ? String.fromCharCode(e) : e;
      sax2.ENTITIES[key] = s2;
    });
    for (var s in sax2.STATE) {
      sax2.STATE[sax2.STATE[s]] = s;
    }
    S = sax2.STATE;
    function emit(parser, event, data) {
      parser[event] && parser[event](data);
    }
    function emitNode(parser, nodeType, data) {
      if (parser.textNode)
        closeText(parser);
      emit(parser, nodeType, data);
    }
    function closeText(parser) {
      parser.textNode = textopts(parser.opt, parser.textNode);
      if (parser.textNode)
        emit(parser, "ontext", parser.textNode);
      parser.textNode = "";
    }
    function textopts(opt, text) {
      if (opt.trim)
        text = text.trim();
      if (opt.normalize)
        text = text.replace(/\s+/g, " ");
      return text;
    }
    function error2(parser, er) {
      closeText(parser);
      if (parser.trackPosition) {
        er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c;
      }
      er = new Error(er);
      parser.error = er;
      emit(parser, "onerror", er);
      return parser;
    }
    function end(parser) {
      if (parser.sawRoot && !parser.closedRoot)
        strictFail(parser, "Unclosed root tag");
      if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) {
        error2(parser, "Unexpected end");
      }
      closeText(parser);
      parser.c = "";
      parser.closed = true;
      emit(parser, "onend");
      SAXParser.call(parser, parser.strict, parser.opt);
      return parser;
    }
    function strictFail(parser, message) {
      if (typeof parser !== "object" || !(parser instanceof SAXParser)) {
        throw new Error("bad call to strictFail");
      }
      if (parser.strict) {
        error2(parser, message);
      }
    }
    function newTag(parser) {
      if (!parser.strict)
        parser.tagName = parser.tagName[parser.looseCase]();
      var parent = parser.tags[parser.tags.length - 1] || parser;
      var tag = parser.tag = { name: parser.tagName, attributes: {} };
      if (parser.opt.xmlns) {
        tag.ns = parent.ns;
      }
      parser.attribList.length = 0;
      emitNode(parser, "onopentagstart", tag);
    }
    function qname(name2, attribute) {
      var i = name2.indexOf(":");
      var qualName = i < 0 ? ["", name2] : name2.split(":");
      var prefix = qualName[0];
      var local = qualName[1];
      if (attribute && name2 === "xmlns") {
        prefix = "xmlns";
        local = "";
      }
      return { prefix, local };
    }
    function attrib(parser) {
      if (!parser.strict) {
        parser.attribName = parser.attribName[parser.looseCase]();
      }
      if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) {
        parser.attribName = parser.attribValue = "";
        return;
      }
      if (parser.opt.xmlns) {
        var qn = qname(parser.attribName, true);
        var prefix = qn.prefix;
        var local = qn.local;
        if (prefix === "xmlns") {
          if (local === "xml" && parser.attribValue !== XML_NAMESPACE) {
            strictFail(
              parser,
              "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue
            );
          } else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) {
            strictFail(
              parser,
              "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue
            );
          } else {
            var tag = parser.tag;
            var parent = parser.tags[parser.tags.length - 1] || parser;
            if (tag.ns === parent.ns) {
              tag.ns = Object.create(parent.ns);
            }
            tag.ns[local] = parser.attribValue;
          }
        }
        parser.attribList.push([parser.attribName, parser.attribValue]);
      } else {
        parser.tag.attributes[parser.attribName] = parser.attribValue;
        emitNode(parser, "onattribute", {
          name: parser.attribName,
          value: parser.attribValue
        });
      }
      parser.attribName = parser.attribValue = "";
    }
    function openTag(parser, selfClosing) {
      if (parser.opt.xmlns) {
        var tag = parser.tag;
        var qn = qname(parser.tagName);
        tag.prefix = qn.prefix;
        tag.local = qn.local;
        tag.uri = tag.ns[qn.prefix] || "";
        if (tag.prefix && !tag.uri) {
          strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName));
          tag.uri = qn.prefix;
        }
        var parent = parser.tags[parser.tags.length - 1] || parser;
        if (tag.ns && parent.ns !== tag.ns) {
          Object.keys(tag.ns).forEach(function(p) {
            emitNode(parser, "onopennamespace", {
              prefix: p,
              uri: tag.ns[p]
            });
          });
        }
        for (var i = 0, l = parser.attribList.length; i < l; i++) {
          var nv2 = parser.attribList[i];
          var name2 = nv2[0];
          var value = nv2[1];
          var qualName = qname(name2, true);
          var prefix = qualName.prefix;
          var local = qualName.local;
          var uri2 = prefix === "" ? "" : tag.ns[prefix] || "";
          var a = {
            name: name2,
            value,
            prefix,
            local,
            uri: uri2
          };
          if (prefix && prefix !== "xmlns" && !uri2) {
            strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix));
            a.uri = prefix;
          }
          parser.tag.attributes[name2] = a;
          emitNode(parser, "onattribute", a);
        }
        parser.attribList.length = 0;
      }
      parser.tag.isSelfClosing = !!selfClosing;
      parser.sawRoot = true;
      parser.tags.push(parser.tag);
      emitNode(parser, "onopentag", parser.tag);
      if (!selfClosing) {
        if (!parser.noscript && parser.tagName.toLowerCase() === "script") {
          parser.state = S.SCRIPT;
        } else {
          parser.state = S.TEXT;
        }
        parser.tag = null;
        parser.tagName = "";
      }
      parser.attribName = parser.attribValue = "";
      parser.attribList.length = 0;
    }
    function closeTag(parser) {
      if (!parser.tagName) {
        strictFail(parser, "Weird empty close tag.");
        parser.textNode += "</>";
        parser.state = S.TEXT;
        return;
      }
      if (parser.script) {
        if (parser.tagName !== "script") {
          parser.script += "</" + parser.tagName + ">";
          parser.tagName = "";
          parser.state = S.SCRIPT;
          return;
        }
        emitNode(parser, "onscript", parser.script);
        parser.script = "";
      }
      var t = parser.tags.length;
      var tagName = parser.tagName;
      if (!parser.strict) {
        tagName = tagName[parser.looseCase]();
      }
      var closeTo = tagName;
      while (t--) {
        var close = parser.tags[t];
        if (close.name !== closeTo) {
          strictFail(parser, "Unexpected close tag");
        } else {
          break;
        }
      }
      if (t < 0) {
        strictFail(parser, "Unmatched closing tag: " + parser.tagName);
        parser.textNode += "</" + parser.tagName + ">";
        parser.state = S.TEXT;
        return;
      }
      parser.tagName = tagName;
      var s2 = parser.tags.length;
      while (s2-- > t) {
        var tag = parser.tag = parser.tags.pop();
        parser.tagName = parser.tag.name;
        emitNode(parser, "onclosetag", parser.tagName);
        var x = {};
        for (var i in tag.ns) {
          x[i] = tag.ns[i];
        }
        var parent = parser.tags[parser.tags.length - 1] || parser;
        if (parser.opt.xmlns && tag.ns !== parent.ns) {
          Object.keys(tag.ns).forEach(function(p) {
            var n = tag.ns[p];
            emitNode(parser, "onclosenamespace", { prefix: p, uri: n });
          });
        }
      }
      if (t === 0)
        parser.closedRoot = true;
      parser.tagName = parser.attribValue = parser.attribName = "";
      parser.attribList.length = 0;
      parser.state = S.TEXT;
    }
    function parseEntity(parser) {
      var entity = parser.entity;
      var entityLC = entity.toLowerCase();
      var num;
      var numStr = "";
      if (parser.ENTITIES[entity]) {
        return parser.ENTITIES[entity];
      }
      if (parser.ENTITIES[entityLC]) {
        return parser.ENTITIES[entityLC];
      }
      entity = entityLC;
      if (entity.charAt(0) === "#") {
        if (entity.charAt(1) === "x") {
          entity = entity.slice(2);
          num = parseInt(entity, 16);
          numStr = num.toString(16);
        } else {
          entity = entity.slice(1);
          num = parseInt(entity, 10);
          numStr = num.toString(10);
        }
      }
      entity = entity.replace(/^0+/, "");
      if (isNaN(num) || numStr.toLowerCase() !== entity) {
        strictFail(parser, "Invalid character entity");
        return "&" + parser.entity + ";";
      }
      return String.fromCodePoint(num);
    }
    function beginWhiteSpace(parser, c) {
      if (c === "<") {
        parser.state = S.OPEN_WAKA;
        parser.startTagPosition = parser.position;
      } else if (!isWhitespace(c)) {
        strictFail(parser, "Non-whitespace before first tag.");
        parser.textNode = c;
        parser.state = S.TEXT;
      }
    }
    function charAt(chunk, i) {
      var result = "";
      if (i < chunk.length) {
        result = chunk.charAt(i);
      }
      return result;
    }
    function write(chunk) {
      var parser = this;
      if (this.error) {
        throw this.error;
      }
      if (parser.closed) {
        return error2(
          parser,
          "Cannot write after close. Assign an onready handler."
        );
      }
      if (chunk === null) {
        return end(parser);
      }
      if (typeof chunk === "object") {
        chunk = chunk.toString();
      }
      var i = 0;
      var c = "";
      while (true) {
        c = charAt(chunk, i++);
        parser.c = c;
        if (!c) {
          break;
        }
        if (parser.trackPosition) {
          parser.position++;
          if (c === "\n") {
            parser.line++;
            parser.column = 0;
          } else {
            parser.column++;
          }
        }
        switch (parser.state) {
          case S.BEGIN:
            parser.state = S.BEGIN_WHITESPACE;
            if (c === "\uFEFF") {
              continue;
            }
            beginWhiteSpace(parser, c);
            continue;
          case S.BEGIN_WHITESPACE:
            beginWhiteSpace(parser, c);
            continue;
          case S.TEXT:
            if (parser.sawRoot && !parser.closedRoot) {
              var starti = i - 1;
              while (c && c !== "<" && c !== "&") {
                c = charAt(chunk, i++);
                if (c && parser.trackPosition) {
                  parser.position++;
                  if (c === "\n") {
                    parser.line++;
                    parser.column = 0;
                  } else {
                    parser.column++;
                  }
                }
              }
              parser.textNode += chunk.substring(starti, i - 1);
            }
            if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
              parser.state = S.OPEN_WAKA;
              parser.startTagPosition = parser.position;
            } else {
              if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) {
                strictFail(parser, "Text data outside of root node.");
              }
              if (c === "&") {
                parser.state = S.TEXT_ENTITY;
              } else {
                parser.textNode += c;
              }
            }
            continue;
          case S.SCRIPT:
            if (c === "<") {
              parser.state = S.SCRIPT_ENDING;
            } else {
              parser.script += c;
            }
            continue;
          case S.SCRIPT_ENDING:
            if (c === "/") {
              parser.state = S.CLOSE_TAG;
            } else {
              parser.script += "<" + c;
              parser.state = S.SCRIPT;
            }
            continue;
          case S.OPEN_WAKA:
            if (c === "!") {
              parser.state = S.SGML_DECL;
              parser.sgmlDecl = "";
            } else if (isWhitespace(c))
              ;
            else if (isMatch(nameStart, c)) {
              parser.state = S.OPEN_TAG;
              parser.tagName = c;
            } else if (c === "/") {
              parser.state = S.CLOSE_TAG;
              parser.tagName = "";
            } else if (c === "?") {
              parser.state = S.PROC_INST;
              parser.procInstName = parser.procInstBody = "";
            } else {
              strictFail(parser, "Unencoded <");
              if (parser.startTagPosition + 1 < parser.position) {
                var pad = parser.position - parser.startTagPosition;
                c = new Array(pad).join(" ") + c;
              }
              parser.textNode += "<" + c;
              parser.state = S.TEXT;
            }
            continue;
          case S.SGML_DECL:
            if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
              emitNode(parser, "onopencdata");
              parser.state = S.CDATA;
              parser.sgmlDecl = "";
              parser.cdata = "";
            } else if (parser.sgmlDecl + c === "--") {
              parser.state = S.COMMENT;
              parser.comment = "";
              parser.sgmlDecl = "";
            } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
              parser.state = S.DOCTYPE;
              if (parser.doctype || parser.sawRoot) {
                strictFail(
                  parser,
                  "Inappropriately located doctype declaration"
                );
              }
              parser.doctype = "";
              parser.sgmlDecl = "";
            } else if (c === ">") {
              emitNode(parser, "onsgmldeclaration", parser.sgmlDecl);
              parser.sgmlDecl = "";
              parser.state = S.TEXT;
            } else if (isQuote(c)) {
              parser.state = S.SGML_DECL_QUOTED;
              parser.sgmlDecl += c;
            } else {
              parser.sgmlDecl += c;
            }
            continue;
          case S.SGML_DECL_QUOTED:
            if (c === parser.q) {
              parser.state = S.SGML_DECL;
              parser.q = "";
            }
            parser.sgmlDecl += c;
            continue;
          case S.DOCTYPE:
            if (c === ">") {
              parser.state = S.TEXT;
              emitNode(parser, "ondoctype", parser.doctype);
              parser.doctype = true;
            } else {
              parser.doctype += c;
              if (c === "[") {
                parser.state = S.DOCTYPE_DTD;
              } else if (isQuote(c)) {
                parser.state = S.DOCTYPE_QUOTED;
                parser.q = c;
              }
            }
            continue;
          case S.DOCTYPE_QUOTED:
            parser.doctype += c;
            if (c === parser.q) {
              parser.q = "";
              parser.state = S.DOCTYPE;
            }
            continue;
          case S.DOCTYPE_DTD:
            parser.doctype += c;
            if (c === "]") {
              parser.state = S.DOCTYPE;
            } else if (isQuote(c)) {
              parser.state = S.DOCTYPE_DTD_QUOTED;
              parser.q = c;
            }
            continue;
          case S.DOCTYPE_DTD_QUOTED:
            parser.doctype += c;
            if (c === parser.q) {
              parser.state = S.DOCTYPE_DTD;
              parser.q = "";
            }
            continue;
          case S.COMMENT:
            if (c === "-") {
              parser.state = S.COMMENT_ENDING;
            } else {
              parser.comment += c;
            }
            continue;
          case S.COMMENT_ENDING:
            if (c === "-") {
              parser.state = S.COMMENT_ENDED;
              parser.comment = textopts(parser.opt, parser.comment);
              if (parser.comment) {
                emitNode(parser, "oncomment", parser.comment);
              }
              parser.comment = "";
            } else {
              parser.comment += "-" + c;
              parser.state = S.COMMENT;
            }
            continue;
          case S.COMMENT_ENDED:
            if (c !== ">") {
              strictFail(parser, "Malformed comment");
              parser.comment += "--" + c;
              parser.state = S.COMMENT;
            } else {
              parser.state = S.TEXT;
            }
            continue;
          case S.CDATA:
            if (c === "]") {
              parser.state = S.CDATA_ENDING;
            } else {
              parser.cdata += c;
            }
            continue;
          case S.CDATA_ENDING:
            if (c === "]") {
              parser.state = S.CDATA_ENDING_2;
            } else {
              parser.cdata += "]" + c;
              parser.state = S.CDATA;
            }
            continue;
          case S.CDATA_ENDING_2:
            if (c === ">") {
              if (parser.cdata) {
                emitNode(parser, "oncdata", parser.cdata);
              }
              emitNode(parser, "onclosecdata");
              parser.cdata = "";
              parser.state = S.TEXT;
            } else if (c === "]") {
              parser.cdata += "]";
            } else {
              parser.cdata += "]]" + c;
              parser.state = S.CDATA;
            }
            continue;
          case S.PROC_INST:
            if (c === "?") {
              parser.state = S.PROC_INST_ENDING;
            } else if (isWhitespace(c)) {
              parser.state = S.PROC_INST_BODY;
            } else {
              parser.procInstName += c;
            }
            continue;
          case S.PROC_INST_BODY:
            if (!parser.procInstBody && isWhitespace(c)) {
              continue;
            } else if (c === "?") {
              parser.state = S.PROC_INST_ENDING;
            } else {
              parser.procInstBody += c;
            }
            continue;
          case S.PROC_INST_ENDING:
            if (c === ">") {
              emitNode(parser, "onprocessinginstruction", {
                name: parser.procInstName,
                body: parser.procInstBody
              });
              parser.procInstName = parser.procInstBody = "";
              parser.state = S.TEXT;
            } else {
              parser.procInstBody += "?" + c;
              parser.state = S.PROC_INST_BODY;
            }
            continue;
          case S.OPEN_TAG:
            if (isMatch(nameBody, c)) {
              parser.tagName += c;
            } else {
              newTag(parser);
              if (c === ">") {
                openTag(parser);
              } else if (c === "/") {
                parser.state = S.OPEN_TAG_SLASH;
              } else {
                if (!isWhitespace(c)) {
                  strictFail(parser, "Invalid character in tag name");
                }
                parser.state = S.ATTRIB;
              }
            }
            continue;
          case S.OPEN_TAG_SLASH:
            if (c === ">") {
              openTag(parser, true);
              closeTag(parser);
            } else {
              strictFail(parser, "Forward-slash in opening tag not followed by >");
              parser.state = S.ATTRIB;
            }
            continue;
          case S.ATTRIB:
            if (isWhitespace(c)) {
              continue;
            } else if (c === ">") {
              openTag(parser);
            } else if (c === "/") {
              parser.state = S.OPEN_TAG_SLASH;
            } else if (isMatch(nameStart, c)) {
              parser.attribName = c;
              parser.attribValue = "";
              parser.state = S.ATTRIB_NAME;
            } else {
              strictFail(parser, "Invalid attribute name");
            }
            continue;
          case S.ATTRIB_NAME:
            if (c === "=") {
              parser.state = S.ATTRIB_VALUE;
            } else if (c === ">") {
              strictFail(parser, "Attribute without value");
              parser.attribValue = parser.attribName;
              attrib(parser);
              openTag(parser);
            } else if (isWhitespace(c)) {
              parser.state = S.ATTRIB_NAME_SAW_WHITE;
            } else if (isMatch(nameBody, c)) {
              parser.attribName += c;
            } else {
              strictFail(parser, "Invalid attribute name");
            }
            continue;
          case S.ATTRIB_NAME_SAW_WHITE:
            if (c === "=") {
              parser.state = S.ATTRIB_VALUE;
            } else if (isWhitespace(c)) {
              continue;
            } else {
              strictFail(parser, "Attribute without value");
              parser.tag.attributes[parser.attribName] = "";
              parser.attribValue = "";
              emitNode(parser, "onattribute", {
                name: parser.attribName,
                value: ""
              });
              parser.attribName = "";
              if (c === ">") {
                openTag(parser);
              } else if (isMatch(nameStart, c)) {
                parser.attribName = c;
                parser.state = S.ATTRIB_NAME;
              } else {
                strictFail(parser, "Invalid attribute name");
                parser.state = S.ATTRIB;
              }
            }
            continue;
          case S.ATTRIB_VALUE:
            if (isWhitespace(c)) {
              continue;
            } else if (isQuote(c)) {
              parser.q = c;
              parser.state = S.ATTRIB_VALUE_QUOTED;
            } else {
              strictFail(parser, "Unquoted attribute value");
              parser.state = S.ATTRIB_VALUE_UNQUOTED;
              parser.attribValue = c;
            }
            continue;
          case S.ATTRIB_VALUE_QUOTED:
            if (c !== parser.q) {
              if (c === "&") {
                parser.state = S.ATTRIB_VALUE_ENTITY_Q;
              } else {
                parser.attribValue += c;
              }
              continue;
            }
            attrib(parser);
            parser.q = "";
            parser.state = S.ATTRIB_VALUE_CLOSED;
            continue;
          case S.ATTRIB_VALUE_CLOSED:
            if (isWhitespace(c)) {
              parser.state = S.ATTRIB;
            } else if (c === ">") {
              openTag(parser);
            } else if (c === "/") {
              parser.state = S.OPEN_TAG_SLASH;
            } else if (isMatch(nameStart, c)) {
              strictFail(parser, "No whitespace between attributes");
              parser.attribName = c;
              parser.attribValue = "";
              parser.state = S.ATTRIB_NAME;
            } else {
              strictFail(parser, "Invalid attribute name");
            }
            continue;
          case S.ATTRIB_VALUE_UNQUOTED:
            if (!isAttribEnd(c)) {
              if (c === "&") {
                parser.state = S.ATTRIB_VALUE_ENTITY_U;
              } else {
                parser.attribValue += c;
              }
              continue;
            }
            attrib(parser);
            if (c === ">") {
              openTag(parser);
            } else {
              parser.state = S.ATTRIB;
            }
            continue;
          case S.CLOSE_TAG:
            if (!parser.tagName) {
              if (isWhitespace(c)) {
                continue;
              } else if (notMatch(nameStart, c)) {
                if (parser.script) {
                  parser.script += "</" + c;
                  parser.state = S.SCRIPT;
                } else {
                  strictFail(parser, "Invalid tagname in closing tag.");
                }
              } else {
                parser.tagName = c;
              }
            } else if (c === ">") {
              closeTag(parser);
            } else if (isMatch(nameBody, c)) {
              parser.tagName += c;
            } else if (parser.script) {
              parser.script += "</" + parser.tagName;
              parser.tagName = "";
              parser.state = S.SCRIPT;
            } else {
              if (!isWhitespace(c)) {
                strictFail(parser, "Invalid tagname in closing tag");
              }
              parser.state = S.CLOSE_TAG_SAW_WHITE;
            }
            continue;
          case S.CLOSE_TAG_SAW_WHITE:
            if (isWhitespace(c)) {
              continue;
            }
            if (c === ">") {
              closeTag(parser);
            } else {
              strictFail(parser, "Invalid characters in closing tag");
            }
            continue;
          case S.TEXT_ENTITY:
          case S.ATTRIB_VALUE_ENTITY_Q:
          case S.ATTRIB_VALUE_ENTITY_U:
            var returnState;
            var buffer2;
            switch (parser.state) {
              case S.TEXT_ENTITY:
                returnState = S.TEXT;
                buffer2 = "textNode";
                break;
              case S.ATTRIB_VALUE_ENTITY_Q:
                returnState = S.ATTRIB_VALUE_QUOTED;
                buffer2 = "attribValue";
                break;
              case S.ATTRIB_VALUE_ENTITY_U:
                returnState = S.ATTRIB_VALUE_UNQUOTED;
                buffer2 = "attribValue";
                break;
            }
            if (c === ";") {
              if (parser.opt.unparsedEntities) {
                var parsedEntity = parseEntity(parser);
                parser.entity = "";
                parser.state = returnState;
                parser.write(parsedEntity);
              } else {
                parser[buffer2] += parseEntity(parser);
                parser.entity = "";
                parser.state = returnState;
              }
            } else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) {
              parser.entity += c;
            } else {
              strictFail(parser, "Invalid character in entity name");
              parser[buffer2] += "&" + parser.entity + c;
              parser.entity = "";
              parser.state = returnState;
            }
            continue;
          default: {
            throw new Error(parser, "Unknown state: " + parser.state);
          }
        }
      }
      if (parser.position >= parser.bufferCheckPosition) {
        checkBufferLength(parser);
      }
      return parser;
    }
    /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
    if (!String.fromCodePoint) {
      (function() {
        var stringFromCharCode = String.fromCharCode;
        var floor = Math.floor;
        var fromCodePoint = function() {
          var MAX_SIZE = 16384;
          var codeUnits = [];
          var highSurrogate;
          var lowSurrogate;
          var index = -1;
          var length = arguments.length;
          if (!length) {
            return "";
          }
          var result = "";
          while (++index < length) {
            var codePoint = Number(arguments[index]);
            if (!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
            codePoint < 0 || // not a valid Unicode code point
            codePoint > 1114111 || // not a valid Unicode code point
            floor(codePoint) !== codePoint) {
              throw RangeError("Invalid code point: " + codePoint);
            }
            if (codePoint <= 65535) {
              codeUnits.push(codePoint);
            } else {
              codePoint -= 65536;
              highSurrogate = (codePoint >> 10) + 55296;
              lowSurrogate = codePoint % 1024 + 56320;
              codeUnits.push(highSurrogate, lowSurrogate);
            }
            if (index + 1 === length || codeUnits.length > MAX_SIZE) {
              result += stringFromCharCode.apply(null, codeUnits);
              codeUnits.length = 0;
            }
          }
          return result;
        };
        if (Object.defineProperty) {
          Object.defineProperty(String, "fromCodePoint", {
            value: fromCodePoint,
            configurable: true,
            writable: true
          });
        } else {
          String.fromCodePoint = fromCodePoint;
        }
      })();
    }
  })(exports2);
})(sax$1);
const sax = /* @__PURE__ */ getDefaultExportFromCjs(sax$1);
class UsxLexer {
  constructor() {
    this.sax = sax.parser(true);
    this.sax.ontext = (text) => this.handleSaxText(text);
    this.sax.onopentag = (ot) => this.handleSaxOpenTag(ot);
    this.sax.onclosetag = (ct) => this.handleSaxCloseTag(ct);
    this.elementStack = [];
    this.currentText = "";
    this.openTagHandlers = {
      usx: this.ignoreHandler,
      book: this.handleBookOpen,
      chapter: this.handleChapter,
      verse: this.handleVerses,
      para: this.handleParaOpen,
      table: this.ignoreHandler,
      row: this.handleRowOpen,
      cell: this.handleCellOpen,
      char: this.handleCharOpen,
      ms: this.handleMSOpen,
      note: this.handleNoteOpen,
      sidebar: this.handleSidebarOpen,
      periph: this.notHandledHandler,
      figure: this.handleFigureOpen,
      optbreak: this.handleOptBreakOpen,
      ref: this.ignoreHandler
      // this.handleRefOpen,
    };
    this.closeTagHandlers = {
      usx: this.ignoreHandler,
      book: this.handleBookClose,
      chapter: this.ignoreHandler,
      verse: this.ignoreHandler,
      para: this.handleParaClose,
      table: this.ignoreHandler,
      row: this.handleRowClose,
      cell: this.handleCellClose,
      char: this.handleCharClose,
      ms: this.handleMSClose,
      note: this.handleNoteClose,
      sidebar: this.handleSidebarClose,
      periph: this.notHandledHandler,
      figure: this.handleFigureClose,
      optbreak: this.handleOptBreakClose,
      ref: this.ignoreHandler
      // this.handleRefClose,
    };
  }
  lexAndParse(str, parser) {
    this.parser = parser;
    this.lexed = [];
    this.elementStack = [];
    this.sax.write(str).close();
  }
  handleSaxText(text) {
    this.currentText = this.replaceEntities(text);
    XRegExp.match(this.currentText, mainRegex, "all").map((f) => preTokenObjectForFragment(f, lexingRegexes)).forEach((t) => this.parser.parseItem(t));
  }
  replaceEntities(text) {
    return text.replace("&lt;", "<").replace("&gt;", ">").replace("&apos;", "'").replace("&quot;", '"').replace("&amp;", "&");
  }
  handleSaxOpenTag(tagOb) {
    const name2 = tagOb.name;
    const atts = tagOb.attributes;
    if (name2 in this.openTagHandlers) {
      this.openTagHandlers[name2](this, "open", name2, atts);
    } else {
      throw new Error(`Unexpected open element tag '${name2}' in UsxParser`);
    }
  }
  handleSaxCloseTag(name2) {
    this.closeTagHandlers[name2](this, "close", name2);
  }
  notHandledHandler(lexer, oOrC, tag) {
    console.error(
      `WARNING: ${oOrC} element tag '${tag}' is not handled by UsxParser`
    );
  }
  stackPush(name2, atts) {
    this.elementStack.push([name2, atts]);
  }
  stackPop() {
    return this.elementStack.pop();
  }
  splitTagNumber(fullTagName) {
    const tagBits = XRegExp.exec(fullTagName, XRegExp("([^1-9]+)(.*)"));
    const tagName = tagBits[1];
    const tagNo = tagBits[2].length > 0 ? tagBits[2] : "1";
    return [tagName, tagNo];
  }
  ignoreHandler(lexer, oOrC, tag) {
  }
  handleParaOpen(lexer, oOrC, name2, atts) {
    lexer.currentText = "";
    const [tagName, tagNo] = lexer.splitTagNumber(atts.style);
    if (!["cp"].includes(tagName)) {
      lexer.parser.parseItem(
        constructorForFragment.tag("startTag", [null, null, tagName, tagNo])
      );
    }
    lexer.stackPush(name2, atts);
  }
  handleParaClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.style);
    if (["cp"].includes(tagName)) {
      lexer.parser.parseItem(
        constructorForFragment.pubchapter("pubchapter", [
          null,
          null,
          lexer.currentText
        ])
      );
    } else {
      lexer.parser.parseItem(
        constructorForFragment.tag("endTag", [null, null, tagName, tagNo])
      );
    }
    lexer.currentText = "";
  }
  handleCharOpen(lexer, oOrC, name2, atts) {
    const [tagName, tagNo] = lexer.splitTagNumber(atts.style);
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, `+${tagName}`, tagNo])
    );
    const ignoredAtts = [
      "sid",
      "eid",
      "style",
      "srcloc",
      "link-href",
      "link-title",
      "link-id",
      "closed"
    ];
    for (const [attName, attValue] of Object.entries(atts)) {
      if (!ignoredAtts.includes(attName)) {
        lexer.parser.parseItem(
          constructorForFragment.attribute("attribute", [
            null,
            null,
            attName,
            attValue
          ])
        );
      }
    }
    lexer.stackPush(name2, atts);
  }
  handleCharClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.style);
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, `+${tagName}`, tagNo])
    );
  }
  handleRefOpen(lexer) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "xt", ""])
    );
  }
  handleRefClose(lexer) {
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, "xt", ""])
    );
  }
  handleRowOpen(lexer, oOrC, name2, atts) {
    const [tagName, tagNo] = lexer.splitTagNumber(atts.style);
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, tagName, tagNo])
    );
    lexer.stackPush(name2, atts);
  }
  handleRowClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.style);
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, tagName, tagNo])
    );
  }
  handleCellOpen(lexer, oOrC, name2, atts) {
    const [tagName, tagNo] = lexer.splitTagNumber(atts.style);
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, tagName, tagNo])
    );
    lexer.stackPush(name2, atts);
  }
  handleCellClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.style);
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, tagName, tagNo])
    );
  }
  handleBookOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "id", ""])
    );
    lexer.parser.parseItem(
      constructorForFragment.printable("wordLike", [atts.code])
    );
    lexer.parser.parseItem(
      constructorForFragment.printable("lineSpace", [" "])
    );
    lexer.stackPush(name2, atts);
  }
  handleBookClose(lexer) {
    lexer.stackPop();
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, "id", ""])
    );
  }
  handleChapter(lexer, oOrC, name2, atts) {
    if (atts.number) {
      lexer.parser.parseItem(
        constructorForFragment.chapter("chapter", [null, null, atts.number])
      );
      if (atts.pubnumber) {
        lexer.parser.parseItem(
          constructorForFragment.pubchapter("pubchapter", [
            null,
            null,
            atts.pubnumber
          ])
        );
      }
      if (atts.altnumber) {
        lexer.parser.parseItem(
          constructorForFragment.tag("startTag", [null, null, "+ca", ""])
        );
        lexer.parser.parseItem(
          constructorForFragment.printable("wordLike", [atts.altnumber])
        );
        lexer.parser.parseItem(
          constructorForFragment.tag("endTag", [null, null, "+ca", ""])
        );
      }
    }
  }
  handleVerses(lexer, oOrC, name2, atts) {
    if (atts.number) {
      lexer.parser.parseItem(
        constructorForFragment.verses("verses", [null, null, atts.number])
      );
      if (atts.pubnumber) {
        lexer.parser.parseItem(
          constructorForFragment.tag("startTag", [null, null, "+vp", ""])
        );
        lexer.parser.parseItem(
          constructorForFragment.printable("wordLike", [atts.pubnumber])
        );
        lexer.parser.parseItem(
          constructorForFragment.tag("endTag", [null, null, "+vp", ""])
        );
      }
      if (atts.altnumber) {
        lexer.parser.parseItem(
          constructorForFragment.tag("startTag", [null, null, "+va", ""])
        );
        lexer.parser.parseItem(
          constructorForFragment.printable("wordLike", [atts.altnumber])
        );
        lexer.parser.parseItem(
          constructorForFragment.tag("endTag", [null, null, "+va", ""])
        );
      }
    }
  }
  handleNoteOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, atts.style, ""])
    );
    lexer.parser.parseItem(
      constructorForFragment.printable("punctuation", [atts.caller])
    );
    lexer.stackPush(name2, atts);
  }
  handleNoteClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, sAtts.style, ""])
    );
  }
  handleSidebarOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "esb", ""])
    );
    if ("category" in atts) {
      lexer.parser.parseItem(
        constructorForFragment.tag("startTag", [null, null, "cat", ""])
      );
      lexer.parser.parseItem(
        constructorForFragment.printable("wordLike", [atts.category])
      );
      lexer.parser.parseItem(
        constructorForFragment.tag("endTag", [null, null, "cat", ""])
      );
    }
    lexer.stackPush(name2, atts);
  }
  handleSidebarClose(lexer) {
    lexer.stackPop();
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "esbe", ""])
    );
  }
  handleMSOpen(lexer, oOrC, name2, atts) {
    let matchBits = XRegExp.exec(atts.style, XRegExp("(([a-z1-9]+)-([se]))"));
    if (matchBits) {
      const startMS = constructorForFragment.milestone("startMilestoneTag", [
        null,
        null,
        matchBits[2],
        matchBits[3]
      ]);
      lexer.parser.parseItem(startMS);
      const ignoredAtts = [
        "sid",
        "eid",
        "style",
        "srcloc",
        "link-href",
        "link-title",
        "link-id"
      ];
      for (const [attName, attValue] of Object.entries(atts)) {
        if (!ignoredAtts.includes(attName)) {
          lexer.parser.parseItem(
            constructorForFragment.attribute("attribute", [
              null,
              null,
              attName,
              attValue
            ])
          );
        }
      }
      lexer.parser.parseItem(
        constructorForFragment.milestone("endMilestoneMarker")
      );
    } else {
      const emptyMS = constructorForFragment.milestone("emptyMilestone", [
        null,
        null,
        atts.style,
        ""
      ]);
      lexer.parser.parseItem(emptyMS);
    }
    lexer.stackPush(name2, atts);
  }
  handleMSClose(lexer) {
    lexer.stackPop();
  }
  handleFigureOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "+fig", ""])
    );
    for (const [attName, attValue] of Object.entries(atts)) {
      if (attName === "style") {
        continue;
      }
      const scopeAttName = attName === "file" ? "src" : attName;
      lexer.parser.parseItem(
        constructorForFragment.attribute("attribute", [
          null,
          null,
          scopeAttName,
          attValue
        ])
      );
    }
    lexer.stackPush(name2, atts);
  }
  handleFigureClose(lexer) {
    lexer.stackPop()[1];
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, `+fig`, ""])
    );
  }
  handleOptBreakOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.printable("softLineBreak", ["//"])
    );
    lexer.stackPush(name2, atts);
  }
  handleOptBreakClose(lexer) {
    lexer.stackPop();
  }
}
const parseUsx = (str, parser) => {
  new UsxLexer().lexAndParse(str, parser);
};
class UsjLexer {
  constructor() {
    this.elementStack = [];
    this.currentText = "";
    this.openTagHandlers = {
      USJ: this.ignoreHandler,
      book: this.handleBookOpen,
      chapter: this.handleChapter,
      verse: this.handleVerses,
      para: this.handleParaOpen,
      table: this.ignoreHandler,
      row: this.handleRowOpen,
      cell: this.handleCellOpen,
      char: this.handleCharOpen,
      ms: this.handleMSOpen,
      note: this.handleNoteOpen,
      sidebar: this.handleSidebarOpen,
      periph: this.notHandledHandler,
      figure: this.handleFigureOpen,
      optbreak: this.handleOptBreakOpen,
      ref: this.ignoreHandler
      // this.handleRefOpen,
    };
    this.closeTagHandlers = {
      USJ: this.ignoreHandler,
      book: this.handleBookClose,
      chapter: this.ignoreHandler,
      verse: this.ignoreHandler,
      para: this.handleParaClose,
      table: this.ignoreHandler,
      row: this.handleRowClose,
      cell: this.handleCellClose,
      char: this.handleCharClose,
      ms: this.handleMSClose,
      note: this.handleNoteClose,
      sidebar: this.handleSidebarClose,
      periph: this.notHandledHandler,
      figure: this.handleFigureClose,
      optbreak: this.handleOptBreakClose,
      ref: this.ignoreHandler
      // this.handleRefClose,
    };
  }
  lexAndParse(str, parser) {
    this.parser = parser;
    this.elementStack = [];
    let usjJson;
    try {
      usjJson = JSON.parse(str);
    } catch (err) {
      throw new Error(`Error parsing USJ: ${err}`);
    }
    this.walkUsj(usjJson, parser);
  }
  walkUsj(usj, parser, path = []) {
    const printPath = () => `/${path.join("/")}`;
    if (typeof usj !== "object" || Array.isArray(usj)) {
      throw new Error(`USJ walker expected object at ${printPath()} but found '${JSON.stringify(usj).substring(0, 40) + "..."}'`);
    }
    const nodeType = usj["type"];
    if (!nodeType) {
      throw new Error(`USJ walker did not find type attribute at ${printPath()} in '${JSON.stringify(usj).substring(0, 40) + "..."}'`);
    }
    if (!this.openTagHandlers[nodeType]) {
      throw new Error(`USJ walker found no openTag handler for ${nodeType} at ${printPath()}`);
    }
    if (!this.closeTagHandlers[nodeType]) {
      throw new Error(`USJ walker found no closeTag handler for ${nodeType} at ${printPath()}`);
    }
    let atts = { ...usj };
    delete atts["type"];
    delete atts["content"];
    for (const [k, v] of Object.entries(atts)) {
      if (typeof v === "object") {
        throw new Error(`usjWalker expected string or number but found object or array '${JSON.stringify(usj).substring(0, 40) + "..."}' for attribute ${k} at ${printPath()}`);
      }
    }
    this.openTagHandlers[nodeType](this, "open", nodeType, atts);
    for (const [n, child] of (usj["content"] || []).entries()) {
      if (typeof child === "string") {
        this.handleText(child);
      } else if (typeof child !== "object" || Array.isArray(child)) {
        throw new Error(`USJ walker expected child to be object at ${printPath()} but found '${JSON.stringify(child).substring(0, 40) + "..."}'`);
      } else {
        this.walkUsj(child, parser, [...path, nodeType, n]);
      }
    }
    this.closeTagHandlers[nodeType](this, "close", nodeType, atts);
  }
  handleText(text) {
    this.currentText = text;
    XRegExp.match(this.currentText, mainRegex, "all").map((f) => preTokenObjectForFragment(f, lexingRegexes)).forEach((t) => this.parser.parseItem(t));
  }
  notHandledHandler(lexer, oOrC, tag) {
    console.error(
      `WARNING: ${oOrC} element tag '${tag}' is not handled by UsjParser`
    );
  }
  stackPush(name2, atts) {
    this.elementStack.push([name2, atts]);
  }
  stackPop() {
    return this.elementStack.pop();
  }
  splitTagNumber(fullTagName) {
    const tagBits = XRegExp.exec(fullTagName, XRegExp("([^1-9]+)(.*)"));
    const tagName = tagBits[1];
    const tagNo = tagBits[2].length > 0 ? tagBits[2] : "1";
    return [tagName, tagNo];
  }
  ignoreHandler(lexer, oOrC, tag) {
  }
  handleParaOpen(lexer, oOrC, name2, atts) {
    lexer.currentText = "";
    const [tagName, tagNo] = lexer.splitTagNumber(atts.marker);
    if (!["cp"].includes(tagName)) {
      lexer.parser.parseItem(
        constructorForFragment.tag("startTag", [null, null, tagName, tagNo])
      );
    }
    lexer.stackPush(name2, atts);
  }
  handleParaClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.marker);
    if (["cp"].includes(tagName)) {
      lexer.parser.parseItem(
        constructorForFragment.pubchapter("pubchapter", [
          null,
          null,
          lexer.currentText
        ])
      );
    } else {
      lexer.parser.parseItem(
        constructorForFragment.tag("endTag", [null, null, tagName, tagNo])
      );
    }
    lexer.currentText = "";
  }
  handleCharOpen(lexer, oOrC, name2, atts) {
    const [tagName, tagNo] = lexer.splitTagNumber(atts.marker);
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, `+${tagName}`, tagNo])
    );
    const ignoredAtts = [
      "sid",
      "eid",
      "style",
      "srcloc",
      "link-href",
      "link-title",
      "link-id",
      "closed"
    ];
    for (const [attName, attValue] of Object.entries(atts)) {
      if (!ignoredAtts.includes(attName)) {
        lexer.parser.parseItem(
          constructorForFragment.attribute("attribute", [
            null,
            null,
            attName,
            attValue
          ])
        );
      }
    }
    lexer.stackPush(name2, atts);
  }
  handleCharClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.marker);
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, `+${tagName}`, tagNo])
    );
  }
  handleRefOpen(lexer) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "xt", ""])
    );
  }
  handleRefClose(lexer) {
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, "xt", ""])
    );
  }
  handleRowOpen(lexer, oOrC, name2, atts) {
    const [tagName, tagNo] = lexer.splitTagNumber(atts.marker);
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, tagName, tagNo])
    );
    lexer.stackPush(name2, atts);
  }
  handleRowClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.marker);
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, tagName, tagNo])
    );
  }
  handleCellOpen(lexer, oOrC, name2, atts) {
    const [tagName, tagNo] = lexer.splitTagNumber(atts.marker);
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, tagName, tagNo])
    );
    lexer.stackPush(name2, atts);
  }
  handleCellClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    const [tagName, tagNo] = lexer.splitTagNumber(sAtts.marker);
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, tagName, tagNo])
    );
  }
  handleBookOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "id", ""])
    );
    lexer.parser.parseItem(
      constructorForFragment.printable("wordLike", [atts.code])
    );
    lexer.parser.parseItem(
      constructorForFragment.printable("lineSpace", [" "])
    );
    lexer.stackPush(name2, atts);
  }
  handleBookClose(lexer) {
    lexer.stackPop();
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, "id", ""])
    );
  }
  handleChapter(lexer, oOrC, name2, atts) {
    if (atts.number) {
      lexer.parser.parseItem(
        constructorForFragment.chapter("chapter", [null, null, atts.number])
      );
      if (atts.pubnumber) {
        lexer.parser.parseItem(
          constructorForFragment.pubchapter("pubchapter", [
            null,
            null,
            atts.pubnumber
          ])
        );
      }
      if (atts.altnumber) {
        lexer.parser.parseItem(
          constructorForFragment.tag("startTag", [null, null, "+ca", ""])
        );
        lexer.parser.parseItem(
          constructorForFragment.printable("wordLike", [atts.altnumber])
        );
        lexer.parser.parseItem(
          constructorForFragment.tag("endTag", [null, null, "+ca", ""])
        );
      }
    }
  }
  handleVerses(lexer, oOrC, name2, atts) {
    if (atts.number) {
      lexer.parser.parseItem(
        constructorForFragment.verses("verses", [null, null, atts.number])
      );
      if (atts.pubnumber) {
        lexer.parser.parseItem(
          constructorForFragment.tag("startTag", [null, null, "+vp", ""])
        );
        lexer.parser.parseItem(
          constructorForFragment.printable("wordLike", [atts.pubnumber])
        );
        lexer.parser.parseItem(
          constructorForFragment.tag("endTag", [null, null, "+vp", ""])
        );
      }
      if (atts.altnumber) {
        lexer.parser.parseItem(
          constructorForFragment.tag("startTag", [null, null, "+va", ""])
        );
        lexer.parser.parseItem(
          constructorForFragment.printable("wordLike", [atts.altnumber])
        );
        lexer.parser.parseItem(
          constructorForFragment.tag("endTag", [null, null, "+va", ""])
        );
      }
    }
  }
  handleNoteOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, atts.marker, ""])
    );
    lexer.parser.parseItem(
      constructorForFragment.printable("punctuation", [atts.caller])
    );
    lexer.stackPush(name2, atts);
  }
  handleNoteClose(lexer) {
    const sAtts = lexer.stackPop()[1];
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, sAtts.marker, ""])
    );
  }
  handleSidebarOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "esb", ""])
    );
    if ("category" in atts) {
      lexer.parser.parseItem(
        constructorForFragment.tag("startTag", [null, null, "cat", ""])
      );
      lexer.parser.parseItem(
        constructorForFragment.printable("wordLike", [atts.category])
      );
      lexer.parser.parseItem(
        constructorForFragment.tag("endTag", [null, null, "cat", ""])
      );
    }
    lexer.stackPush(name2, atts);
  }
  handleSidebarClose(lexer) {
    lexer.stackPop();
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "esbe", ""])
    );
  }
  handleMSOpen(lexer, oOrC, name2, atts) {
    let matchBits = XRegExp.exec(atts.marker, XRegExp("(([a-z1-9]+)-([se]))"));
    if (matchBits) {
      const startMS = constructorForFragment.milestone("startMilestoneTag", [
        null,
        null,
        matchBits[2],
        matchBits[3]
      ]);
      lexer.parser.parseItem(startMS);
      const ignoredAtts = [
        "sid",
        "eid",
        "style",
        "srcloc",
        "link-href",
        "link-title",
        "link-id"
      ];
      for (const [attName, attValue] of Object.entries(atts)) {
        if (!ignoredAtts.includes(attName)) {
          lexer.parser.parseItem(
            constructorForFragment.attribute("attribute", [
              null,
              null,
              attName,
              attValue
            ])
          );
        }
      }
      lexer.parser.parseItem(
        constructorForFragment.milestone("endMilestoneMarker")
      );
    } else {
      const emptyMS = constructorForFragment.milestone("emptyMilestone", [
        null,
        null,
        atts.marker,
        ""
      ]);
      lexer.parser.parseItem(emptyMS);
    }
    lexer.stackPush(name2, atts);
  }
  handleMSClose(lexer) {
    lexer.stackPop();
  }
  handleFigureOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.tag("startTag", [null, null, "+fig", ""])
    );
    for (const [attName, attValue] of Object.entries(atts)) {
      if (attName === "marker") {
        continue;
      }
      const scopeAttName = attName === "file" ? "src" : attName;
      lexer.parser.parseItem(
        constructorForFragment.attribute("attribute", [
          null,
          null,
          scopeAttName,
          attValue
        ])
      );
    }
    lexer.stackPush(name2, atts);
  }
  handleFigureClose(lexer) {
    lexer.stackPop()[1];
    lexer.parser.parseItem(
      constructorForFragment.tag("endTag", [null, null, `+fig`, ""])
    );
  }
  handleOptBreakOpen(lexer, oOrC, name2, atts) {
    lexer.parser.parseItem(
      constructorForFragment.printable("softLineBreak", ["//"])
    );
    lexer.stackPush(name2, atts);
  }
  handleOptBreakClose(lexer) {
    lexer.stackPop();
  }
}
const parseUsj = (str, parser) => {
  new UsjLexer().lexAndParse(str, parser);
};
const ByteArray$3 = utils.ByteArray;
const {
  pushSuccinctGraftBytes: pushSuccinctGraftBytes$1,
  pushSuccinctScopeBytes: pushSuccinctScopeBytes$1,
  pushSuccinctTokenBytes: pushSuccinctTokenBytes$1
} = utils.succinct;
const { addTag: addTag$1 } = utils.tags;
const { labelForScope: labelForScope$5 } = utils.scopeDefs;
const { itemEnum: itemEnum$3 } = utils.itemDefs;
const { scopeEnum: scopeEnum$1 } = utils.scopeDefs;
const { tokenCategory: tokenCategory$1, tokenEnum: tokenEnum$2 } = utils.tokenDefs;
const Sequence = class {
  constructor(sType) {
    this.id = utils.generateId();
    this.type = sType;
    this.tags = /* @__PURE__ */ new Set([]);
    this.blocks = [];
    this.activeScopes = [];
  }
  addTag(tag) {
    addTag$1(this.tags, tag);
  }
  plainText() {
    return this.blocks.map((b) => b.plainText()).join("").trim();
  }
  addItem(i) {
    this.lastBlock().addItem(i);
  }
  addBlockGraft(g) {
    this.newBlock("hangingGraft");
    this.lastBlock().bg.push(g);
  }
  lastBlock() {
    if (this.blocks.length === 0) {
      this.newBlock("orphanTokens");
    }
    return this.blocks[this.blocks.length - 1];
  }
  newBlock(label) {
    if (this.blocks.length > 0 && ["orphanTokens", "hangingGraft"].includes(
      this.blocks[this.blocks.length - 1].bs.payload
    )) {
      this.lastBlock().bs = {
        type: "scope",
        subType: "start",
        payload: label
      };
    } else {
      this.blocks.push(new Block(label));
    }
  }
  trim() {
    this.blocks.forEach((b) => b.trim());
  }
  reorderSpanWithAtts() {
    this.blocks.forEach((b) => b.reorderSpanWithAtts());
  }
  makeNoteGrafts(parser) {
    this.blocks.forEach((b) => b.makeNoteGrafts(parser));
  }
  close(parser) {
    for (const activeScope of this.activeScopes.filter(() => true).reverse()) {
      this.closeActiveScope(parser, activeScope);
    }
    this.activeScopes = [];
  }
  closeActiveScope(parser, sc) {
    this.addItem({
      type: "scope",
      subType: "end",
      payload: sc.label
    });
    if (sc.onEnd) {
      sc.onEnd(parser, sc.label);
    }
  }
  filterGrafts(options2) {
    return this.blocks.map((b) => b.filterGrafts(options2)).reduce((acc, current) => acc.concat(current), []);
  }
  filterScopes(options2) {
    this.blocks.forEach((b) => b.filterScopes(options2));
  }
  text() {
    return this.blocks.map((b) => b.text()).join("");
  }
  addTableScopes() {
    let inTable = false;
    for (const [blockNo, block2] of this.blocks.entries()) {
      if (!inTable && block2.bs.payload === "blockTag/tr") {
        inTable = true;
        this.blocks[blockNo].items.unshift({
          type: "scope",
          subType: "start",
          payload: labelForScope$5("table", [])
        });
      } else if (inTable && block2.bs.payload !== "blockTag/tr") {
        inTable = false;
        this.blocks[blockNo - 1].items.push({
          type: "scope",
          subType: "end",
          payload: labelForScope$5("table", [])
        });
      }
    }
    if (inTable) {
      this.lastBlock().items.push({
        type: "scope",
        subType: "end",
        payload: labelForScope$5("table", [])
      });
    }
  }
  graftifyIntroductionHeadings(parser) {
    let blockEntries = [...this.blocks.entries()];
    blockEntries.reverse();
    const introHeadingTags2 = ["iot", "is"].concat(
      parser.customTags.introHeading
    );
    for (const [n, block2] of blockEntries) {
      const blockTag = block2.bs.payload.split("/")[1].replace(/[0-9]/g, "");
      if (introHeadingTags2.includes(blockTag)) {
        const headingSequence = new Sequence("heading");
        parser.sequences.heading.push(headingSequence);
        headingSequence.blocks.push(block2);
        const headingGraft = {
          type: "graft",
          subType: "heading",
          payload: headingSequence.id
        };
        if (this.blocks.length < n + 2) {
          this.newBlock("blockTag/hangingGraft");
        }
        this.blocks[n + 1].bg.unshift(headingGraft);
        this.blocks.splice(n, 1);
      } else if (blockTag.startsWith("imt")) {
        const titleType = blockTag.startsWith("imte") ? "introEndTitle" : "introTitle";
        let titleSequence;
        if (parser.sequences[titleType]) {
          titleSequence = parser.sequences[titleType];
        } else {
          const graftType = blockTag.startsWith("imte") ? "endTitle" : "title";
          titleSequence = new Sequence(graftType);
          parser.sequences[titleType] = titleSequence;
          const titleGraft = {
            type: "graft",
            subType: graftType,
            payload: titleSequence.id
          };
          if (this.blocks.length < n + 2) {
            this.newBlock("blockTag/hangingGraft");
          }
          this.blocks[n + 1].bg.unshift(titleGraft);
        }
        this.blocks.splice(n, 1);
        titleSequence.blocks.unshift(block2);
      }
    }
  }
  moveOrphanScopes() {
    if (this.blocks.length > 1) {
      this.moveOrphanStartScopes();
      this.moveOrphanEndScopes();
    }
  }
  moveOrphanStartScopes() {
    for (const [blockNo, block2] of this.blocks.entries()) {
      if (blockNo >= this.blocks.length - 1) {
        continue;
      }
      for (const item of [...block2.items].reverse()) {
        if (item.subType !== "start" || item.payload.startsWith("altChapter")) {
          break;
        }
        this.blocks[blockNo + 1].items.unshift(
          this.blocks[blockNo].items.pop()
        );
      }
    }
  }
  moveOrphanStartScopes2() {
    for (const [blockNo, block2] of this.blocks.entries()) {
      if (blockNo >= this.blocks.length - 1) {
        continue;
      }
      for (const item of [...block2.items].reverse()) {
        if (item.subType !== "start") {
          break;
        }
        this.blocks[blockNo + 1].items.unshift(
          this.blocks[blockNo].items.pop()
        );
      }
    }
  }
  moveOrphanEndScopes() {
    for (const [blockNo, block2] of this.blocks.entries()) {
      if (blockNo === 0) {
        continue;
      }
      for (const item of [...block2.items]) {
        if (item.subType !== "end") {
          break;
        }
        this.blocks[blockNo - 1].items.push(this.blocks[blockNo].items.shift());
      }
    }
  }
  removeEmptyBlocks(customCanBeEmpty) {
    const canBeEmpty = ["blockTag/b", "blockTag/ib"].concat(customCanBeEmpty);
    const emptyBlocks = [];
    let changed = false;
    const emptyMilestones = (blockItems) => {
      const milestoneScopes = blockItems.filter((i) => i.type === "scope" && i.payload.startsWith("milestone"));
      const startMilestones = /* @__PURE__ */ new Set([]);
      for (const milestoneScope of milestoneScopes) {
        if (milestoneScope.subType === "start") {
          startMilestones.add(milestoneScope.payload);
        } else if (startMilestones.has(milestoneScope.payload)) {
          return true;
        }
      }
      return false;
    };
    const blockGrafts = (blockItems) => {
      const grafts = blockItems.filter((i) => i.type === "graft" && i.subType === "fig");
      return grafts.length > 0;
    };
    for (const blockRecord of this.blocks.entries()) {
      if (blockRecord[1].tokens().length === 0 && !emptyMilestones(blockRecord[1].items) && !blockGrafts(blockRecord[1].items) && !canBeEmpty.includes(blockRecord[1].bs.payload)) {
        emptyBlocks.push(blockRecord);
      }
    }
    for (const [n, block2] of emptyBlocks.reverse()) {
      if (n < this.blocks.length - 1) {
        for (const bg of [...block2.bg].reverse()) {
          this.blocks[n + 1].bg.unshift(bg);
        }
        for (const i of block2.items.reverse()) {
          this.blocks[n + 1].items.unshift(i);
        }
        this.blocks.splice(n, 1);
        changed = true;
      } else if (block2.bg.length === 0 && block2.items.length === 0) {
        this.blocks.splice(n, 1);
        changed = true;
      }
    }
    if (changed) {
      this.removeEmptyBlocks(customCanBeEmpty);
    }
  }
  removeGraftsToEmptySequences(emptySequences) {
    this.blocks.forEach((b) => b.removeGraftsToEmptySequences(emptySequences));
  }
  succinctifyBlocks(docSet) {
    const ret = [];
    let openScopes = [];
    const updateOpenScopes2 = (item) => {
      if (item.subType === "start") {
        const existingScopes = openScopes.filter(
          (s) => s.payload === item.payload
        );
        if (existingScopes.length === 0) {
          openScopes.push(item);
        }
      } else {
        openScopes = openScopes.filter((s) => s.payload !== item.payload);
      }
    };
    let nextToken = 0;
    for (const block2 of this.blocks) {
      const contentBA = new ByteArray$3(block2.length);
      const blockGraftsBA = new ByteArray$3(1);
      const openScopesBA = new ByteArray$3(1);
      const includedScopesBA = new ByteArray$3(1);
      const nextTokenBA = new ByteArray$3(1);
      nextTokenBA.pushNByte(nextToken);
      for (const bg of block2.bg) {
        this.pushSuccinctGraft(blockGraftsBA, docSet, bg);
      }
      for (const os of openScopes) {
        this.pushSuccinctScope(openScopesBA, docSet, os);
      }
      const includedScopes = [];
      for (const item of block2.items) {
        switch (item.type) {
          case "token":
            this.pushSuccinctToken(contentBA, docSet, item);
            if (item.subType === "wordLike") {
              nextToken++;
            }
            break;
          case "graft":
            this.pushSuccinctGraft(contentBA, docSet, item);
            break;
          case "scope":
            this.pushSuccinctScope(contentBA, docSet, item);
            updateOpenScopes2(item);
            if (item.subType === "start") {
              includedScopes.push(item);
            }
            break;
          default:
            throw new Error(
              `Item type ${item.type} is not handled in succinctifyBlocks`
            );
        }
      }
      const blockScopeBA = new ByteArray$3(10);
      this.pushSuccinctScope(blockScopeBA, docSet, block2.bs);
      for (const is of includedScopes) {
        this.pushSuccinctScope(includedScopesBA, docSet, is);
      }
      contentBA.trim();
      blockGraftsBA.trim();
      blockScopeBA.trim();
      openScopesBA.trim();
      includedScopesBA.trim();
      ret.push({
        c: contentBA,
        bs: blockScopeBA,
        bg: blockGraftsBA,
        os: openScopesBA,
        is: includedScopesBA,
        nt: nextTokenBA
      });
    }
    return ret;
  }
  pushSuccinctToken(bA, docSet, item) {
    const charsEnumIndex = docSet.enumForCategoryValue(
      tokenCategory$1[item.subType],
      item.payload
    );
    pushSuccinctTokenBytes$1(bA, tokenEnum$2[item.subType], charsEnumIndex);
  }
  pushSuccinctGraft(bA, docSet, item) {
    const graftTypeEnumIndex = docSet.enumForCategoryValue(
      "graftTypes",
      item.subType
    );
    const seqEnumIndex = docSet.enumForCategoryValue("ids", item.payload);
    pushSuccinctGraftBytes$1(bA, graftTypeEnumIndex, seqEnumIndex);
  }
  pushSuccinctScope(bA, docSet, item) {
    const scopeBits = item.payload.split("/");
    const scopeTypeByte = scopeEnum$1[scopeBits[0]];
    const scopeBitBytes = scopeBits.slice(1).map((b) => docSet.enumForCategoryValue("scopeBits", b));
    pushSuccinctScopeBytes$1(
      bA,
      itemEnum$3[`${item.subType}Scope`],
      scopeTypeByte,
      scopeBitBytes
    );
  }
};
const Block = class {
  constructor(blockScope) {
    this.id = utils.generateId();
    this.items = [];
    this.bg = [];
    this.bs = {
      type: "scope",
      subType: "start",
      payload: blockScope
    };
    this.os = [];
  }
  addItem(i) {
    this.items.push(i);
  }
  plainText() {
    return this.items.filter((i) => i.type === "token").map((i) => i.payload).join("");
  }
  trim() {
    this.items = this.trimEnd(this.trimStart(this.items));
  }
  reorderSpanWithAtts() {
    const swaStarts = [];
    for (const [pos, item] of this.items.entries()) {
      if (item.subType === "start" && item.payload.startsWith("spanWithAtts")) {
        swaStarts.push(pos + 1);
      }
    }
    for (const swaStart of swaStarts) {
      let pos = swaStart;
      let tokens2 = [];
      let scopes = [];
      while (true) {
        if (pos >= this.items.length) {
          break;
        }
        const item = this.items[pos];
        if (item.type === "token") {
          tokens2.push(item);
        } else if (item.subType === "start" && item.payload.startsWith("attribute/spanWithAtts")) {
          scopes.push(item);
        } else {
          break;
        }
        pos++;
      }
      if (tokens2.length !== 0 && scopes.length !== 0) {
        let pos2 = swaStart;
        for (const s of scopes) {
          this.items[pos2] = s;
          pos2++;
        }
        for (const t of tokens2) {
          this.items[pos2] = t;
          pos2++;
        }
      }
    }
  }
  inlineToEnd() {
    let toAppend = null;
    for (const [pos, item] of this.items.entries()) {
      if (item.subType === "end" && ["inline/f", "inline/fe", "inline/x"].includes(item.payload)) {
        toAppend = item;
        this.items.splice(pos, 1);
        break;
      }
    }
    if (toAppend) {
      this.addItem(toAppend);
    }
  }
  makeNoteGrafts(parser) {
    const noteStarts = [];
    for (const [pos, item] of this.items.entries()) {
      if (item.subType === "start" && (item.payload.startsWith("inline/f") || item.payload.startsWith("inline/x"))) {
        noteStarts.push(pos);
      }
    }
    for (const noteStart of noteStarts) {
      const noteLabel = this.items[noteStart].payload;
      const callerToken = this.items[noteStart + 1];
      if (callerToken.type === "token" && callerToken.payload.length === 1) {
        const callerSequence = new Sequence("noteCaller");
        callerSequence.newBlock(noteLabel);
        callerSequence.addItem(callerToken);
        parser.sequences.noteCaller.push(callerSequence);
        this.items[noteStart + 1] = {
          type: "graft",
          subType: "noteCaller",
          payload: callerSequence.id
        };
      }
    }
  }
  trimStart(items2) {
    if (items2.length === 0) {
      return items2;
    }
    const firstItem = items2[0];
    if (["lineSpace", "eol"].includes(firstItem.subType)) {
      return this.trimStart(items2.slice(1));
    }
    if (firstItem.type === "token") {
      return items2;
    }
    return [firstItem, ...this.trimStart(items2.slice(1))];
  }
  trimEnd(items2) {
    if (items2.length === 0) {
      return items2;
    }
    const lastItem = items2[items2.length - 1];
    if (["lineSpace", "eol"].includes(lastItem.subType)) {
      return this.trimEnd(items2.slice(0, items2.length - 1));
    }
    if (lastItem.type === "token") {
      return items2;
    }
    return [...this.trimEnd(items2.slice(0, items2.length - 1)), lastItem];
  }
  filterGrafts(options2) {
    const ret = [];
    let toRemove = [];
    for (const [pos, item] of this.grafts()) {
      if (this.graftPassesOptions(item, options2)) {
        ret.push(item.payload);
      } else {
        toRemove.push(pos);
      }
    }
    for (const [count, pos] of Array.from(toRemove.entries())) {
      this.items.splice(pos - count, 1);
    }
    toRemove = [];
    for (const [pos, item] of this.bg.entries()) {
      if (this.graftPassesOptions(item, options2)) {
        ret.push(item.payload);
      } else {
        toRemove.push(pos);
      }
    }
    for (const [count, pos] of Array.from(toRemove.entries())) {
      this.bg.splice(pos - count, 1);
    }
    return ret;
  }
  filterScopes(options2) {
    const toRemove = [];
    for (const [pos, item] of this.scopes()) {
      if (!this.scopePassesOptions(item, options2)) {
        toRemove.push(pos);
      }
    }
    for (const [count, pos] of Array.from(toRemove.entries())) {
      this.items.splice(pos - count, 1);
    }
  }
  graftPassesOptions(item, options2) {
    return (!("includeGrafts" in options2) || options2.includeGrafts.includes(item.subType)) && (!("excludeGrafts" in options2) || !options2.excludeGrafts.includes(item.subType));
  }
  scopePassesOptions(item, options2) {
    return (!("includeScopes" in options2) || this.scopeMatchesOptionArray(item.payload, options2.includeScopes)) && (!("excludeScopes" in options2) || !this.scopeMatchesOptionArray(item.payload, options2.excludeScopes));
  }
  scopeMatchesOptionArray(itemString, optionArray) {
    for (const optionString of optionArray) {
      if (itemString.startsWith(optionString)) {
        return true;
      }
    }
    return false;
  }
  removeGraftsToEmptySequences(emptySequences) {
    const ret = [];
    let toRemove = [];
    for (const [pos, item] of this.grafts()) {
      if (emptySequences.includes(item.payload)) {
        toRemove.push(pos);
      }
    }
    for (const [count, pos] of Array.from(toRemove.entries())) {
      this.items.splice(pos - count, 1);
    }
    toRemove = [];
    for (const [pos, item] of this.bg.entries()) {
      if (emptySequences.includes(item.payload)) {
        toRemove.push(pos);
      }
    }
    for (const [count, pos] of Array.from(toRemove.entries())) {
      this.bg.splice(pos - count, 1);
    }
    return ret;
  }
  grafts() {
    return Array.from(this.items.entries()).filter(
      (ip) => ip[1].type === "graft"
    );
  }
  scopes() {
    return Array.from(this.items.entries()).filter(
      (ip) => ip[1].type === "scope"
    );
  }
  tokens() {
    return Array.from(this.items.entries()).filter(
      (ip) => !["scope", "graft"].includes(ip[1].type)
    );
  }
  text() {
    return this.tokens().map((t) => t[1].payload).join("");
  }
};
const tokenTypes = {};
const unionComponents = [];
for (const lr of lexingRegexes) {
  if (["wordLike", "eol", "lineSpace", "punctuation", "unknown"].includes(lr[1])) {
    tokenTypes[lr[1]] = XRegExp(`^${lr[2].xregexp.source}$`);
    unionComponents.push(lr[2]);
  }
}
const tokenizeString = (str) => {
  const unionRegex = XRegExp.union(unionComponents);
  const ret = [];
  for (const token of XRegExp.match(str, unionRegex, "all")) {
    let tokenType;
    if (XRegExp.test(token, tokenTypes["wordLike"])) {
      tokenType = "wordLike";
    } else if (XRegExp.test(token, tokenTypes["punctuation"])) {
      tokenType = "punctuation";
    } else if (XRegExp.test(token, tokenTypes["lineSpace"])) {
      tokenType = "lineSpace";
    } else if (XRegExp.test(token, tokenTypes["eol"])) {
      tokenType = "eol";
    } else {
      tokenType = "unknown";
    }
    ret.push([token, tokenType]);
  }
  return ret;
};
const { labelForScope: labelForScope$4 } = utils.scopeDefs;
const parseTableToDocument = (str, parser, bookCode) => {
  const { rows } = JSON.parse(str);
  parser.headers.id = bookCode;
  parser.headers.bookCode = bookCode;
  const tableSequence = new Sequence("table");
  for (const [rowN, row] of rows.entries()) {
    for (const [cellN, cell] of row.entries()) {
      tableSequence.newBlock(labelForScope$4("tTableRow", [`${rowN}`]));
      const lastBlock = tableSequence.lastBlock();
      lastBlock.addItem({
        type: "scope",
        subType: "start",
        payload: `tTableCol/${cellN}`
      });
      for (const [token, tokenType] of tokenizeString(cell)) {
        lastBlock.addItem({
          type: "token",
          subType: tokenType,
          payload: token
        });
      }
      lastBlock.addItem({
        type: "scope",
        subType: "end",
        payload: `tTableCol/${cellN}`
      });
    }
  }
  parser.sequences.table.push(tableSequence);
  parser.sequences.main.addBlockGraft({
    type: "graft",
    subType: "table",
    payload: tableSequence.id
  });
};
const { labelForScope: labelForScope$3 } = utils.scopeDefs;
let nextNodeId = 0;
const numberNodes = (node, parentId) => {
  if (typeof parentId !== "number") {
    nextNodeId = 0;
  }
  const ret = {
    ...node,
    id: nextNodeId,
    parentId: typeof parentId === "number" ? parentId : "none"
  };
  nextNodeId++;
  if (node.children) {
    ret.children = node.children.map((cn) => numberNodes(cn, ret.id));
  }
  return ret;
};
const flattenNodes = (node) => {
  const ret = [{}];
  ret[0].id = node.id;
  ret[0].parentId = node.parentId;
  if (node.content) {
    ret[0].content = node.content;
  }
  if (node.children) {
    ret[0].children = [];
    for (const cn of node.children) {
      ret[0].children.push(cn.id);
      flattenNodes(cn).forEach((n) => ret.push(n));
    }
  }
  return ret;
};
const parseNodes = (str, parser, bookCode) => {
  parser.headers.id = bookCode;
  parser.headers.bookCode = bookCode;
  const treeSequence = new Sequence("tree");
  for (const node of flattenNodes(numberNodes(JSON.parse(str)))) {
    treeSequence.newBlock(labelForScope$3("tTreeNode", [`${node.id}`]));
    const scopePayload = labelForScope$3("tTreeParent", [`${node.parentId}`]);
    treeSequence.lastBlock().items.push({
      type: "scope",
      subType: "start",
      payload: scopePayload
    });
    if (node.content) {
      for (const [name2, content] of Object.entries(node.content)) {
        const treeContentStart = treeSequence.lastBlock().items.length;
        const tokenized = tokenizeString(content);
        const scopePayload2 = labelForScope$3("tTreeContent", [
          name2,
          node.id,
          `${treeContentStart}`,
          `${tokenized.length}`
        ]);
        treeSequence.lastBlock().items.push({
          type: "scope",
          subType: "start",
          payload: scopePayload2
        });
        for (const [payload, subType] of tokenized) {
          treeSequence.lastBlock().items.push({
            type: "token",
            subType,
            payload
          });
        }
        treeSequence.lastBlock().items.push({
          type: "scope",
          subType: "end",
          payload: scopePayload2
        });
      }
    }
    if (node.children) {
      for (const [childN, childNodeN] of node.children.entries()) {
        const scopePayload2 = labelForScope$3("tTreeChild", [childN, childNodeN]);
        treeSequence.lastBlock().items.push({
          type: "scope",
          subType: "start",
          payload: scopePayload2
        });
        treeSequence.lastBlock().items.push({
          type: "scope",
          subType: "end",
          payload: scopePayload2
        });
      }
    }
    treeSequence.lastBlock().items.push({
      type: "scope",
      subType: "end",
      payload: scopePayload
    });
  }
  parser.sequences.tree.push(treeSequence);
  parser.sequences.main.addBlockGraft({
    type: "graft",
    subType: "tree",
    payload: treeSequence.id
  });
};
const { labelForScope: labelForScope$2 } = utils.scopeDefs;
const idTest = new RegExp(/^[A-Z0-9_]+$/);
const buildSpecLookup = (specs2) => {
  const ret = {};
  for (const spec of specs2) {
    for (const context of spec.contexts) {
      if (!(context[0] in ret)) {
        ret[context[0]] = {};
      }
      const accessor = context[1];
      if (!accessor) {
        ret[context[0]]._noAccessor = spec.parser;
      } else {
        if (!(accessor in ret[context[0]])) {
          ret[context[0]][accessor] = {};
        }
        for (const accessorValue of context[2]) {
          ret[context[0]][accessor][accessorValue] = spec.parser;
        }
      }
    }
  }
  return ret;
};
const specs = (pt) => [
  {
    // HEADERS - make temp sequence, then add to headers object
    contexts: [
      [
        "startTag",
        "tagName",
        ["id", "usfm", "ide", "sts", "h", "toc", "toca", "cl"]
      ]
    ],
    parser: {
      baseSequenceType: "header",
      forceNewSequence: true,
      newBlock: true,
      useTempSequence: true,
      newScopes: [
        {
          label: (pt2) => pt2.fullTagName,
          endedBy: ["baseSequenceChange"],
          onEnd: (parser, label) => {
            parser.headers[label] = parser.current.sequence.plainText();
            if (label === "id") {
              const idBits = parser.headers[label].split(" ", 2);
              if (idBits[0].length >= 2 && idBits[0].length <= 32 && idTest.test(idBits[0])) {
                parser.headers["bookCode"] = idBits[0];
              }
            }
          }
        }
      ]
    }
  },
  {
    // HEADINGS - Start new sequence
    contexts: [
      [
        "startTag",
        "tagName",
        ["ms", "mr", "s", "sr", "r", "qa", "sp", "sd"].concat(
          pt.customTags.heading
        )
      ]
    ],
    parser: {
      baseSequenceType: "heading",
      forceNewSequence: true,
      newBlock: true,
      newScopes: []
    }
  },
  {
    // TITLE - make a sequence or add to existing one
    contexts: [["startTag", "tagName", ["mt"]]],
    parser: {
      baseSequenceType: "title",
      newBlock: true,
      newScopes: []
    }
  },
  {
    // END TITLE - make a sequence or add to existing one
    contexts: [["startTag", "tagName", ["mte"]]],
    parser: {
      baseSequenceType: "endTitle",
      newBlock: true,
      newScopes: []
    }
  },
  {
    // INTRODUCTION - make a sequence or add to existing one
    contexts: [
      [
        "startTag",
        "tagName",
        [
          "imt",
          "is",
          "ip",
          "ipi",
          "im",
          "imi",
          "ipq",
          "imq",
          "ipr",
          "iq",
          "ib",
          "ili",
          "iot",
          "io",
          "iex",
          "imte"
        ].concat(pt.customTags.intro)
      ]
    ],
    parser: {
      baseSequenceType: "introduction",
      newBlock: true,
      newScopes: []
    }
  },
  {
    // START SIDEBAR - make a new sequence
    contexts: [["startTag", "tagName", ["esb"]]],
    parser: {
      baseSequenceType: "sidebar",
      newBlock: true,
      newScopes: [],
      after: (parser) => {
        parser.mainLike = parser.current.sequence;
      }
    }
  },
  {
    // END SIDEBAR - return to main
    contexts: [["startTag", "tagName", ["esbe"]]],
    parser: {
      baseSequenceType: "main",
      newBlock: true,
      newScopes: [],
      after: (parser) => {
        parser.mainLike = parser.sequences.main;
      }
    }
  },
  {
    // CAT - graft label and add stub scope, then remove graft and modify scope at tidy stage
    contexts: [["startTag", "tagName", ["cat"]]],
    parser: {
      inlineSequenceType: "esbCat",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("inline", [pt2.fullTagName]),
          endedBy: ["endTag/cat", "endBlock", "implicitEnd"],
          onEnd: (parser) => parser.returnToBaseSequence()
        }
      ],
      during: (parser, pt2) => {
        const scopeId = utils.generateId();
        const esbScope = {
          label: () => labelForScope$2("esbCat", [scopeId]),
          endedBy: ["startTag/esbe"]
        };
        parser.openNewScope(pt2, esbScope, true, parser.mainLike);
      }
    }
  },
  {
    // REMARK - make new sequence
    contexts: [["startTag", "tagName", ["rem"]]],
    parser: {
      baseSequenceType: "remark",
      forceNewSequence: true,
      newScopes: []
    }
  },
  {
    // PARAGRAPH STYLES - Make new block on main
    contexts: [
      [
        "startTag",
        "tagName",
        [
          "cd",
          "p",
          "m",
          "po",
          "pr",
          "cls",
          "pmo",
          "pm",
          "pmc",
          "pmr",
          "pi",
          "mi",
          "nb",
          "pc",
          "ph",
          "b",
          "q",
          "qr",
          "qc",
          "qa",
          "qm",
          "qd",
          "lh",
          "li",
          "lf",
          "lim",
          "d"
        ].concat(pt.customTags.paragraph)
      ]
    ],
    parser: {
      baseSequenceType: "mainLike",
      newBlock: true,
      newScopes: []
    }
  },
  {
    // ROW - Make new block
    contexts: [["startTag", "tagName", ["tr"]]],
    parser: {
      newBlock: true,
      newScopes: []
    }
  },
  {
    // FOOTNOTE/ENDNOTE - new inline sequence
    contexts: [["startTag", "tagName", ["f", "fe"]]],
    parser: {
      inlineSequenceType: "footnote",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("inline", [pt2.fullTagName]),
          endedBy: ["endTag/f", "endTag/fe", "endBlock"],
          onEnd: (parser) => parser.returnToBaseSequence()
        }
      ]
    }
  },
  {
    // CROSS REFERENCE - make new inline sequence
    contexts: [["startTag", "tagName", ["x"]]],
    parser: {
      inlineSequenceType: "xref",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("inline", [pt2.fullTagName]),
          endedBy: ["endTag/x", "endBlock"],
          onEnd: (parser) => parser.returnToBaseSequence()
        }
      ]
    }
  },
  {
    // FIGURE - new inline sequence
    contexts: [["startTag", "tagName", ["fig"]]],
    parser: {
      inlineSequenceType: "fig",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("spanWithAtts", [pt2.tagName]),
          endedBy: ["endBlock", "endTag/$tagName$"],
          onEnd: (parser) => parser.clearAttributeContext()
        }
      ],
      during: (parser, pt2) => {
        parser.setAttributeContext(labelForScope$2("spanWithAtts", [pt2.tagName]));
      }
    }
  },
  {
    // CHAPTER - chapter scope
    contexts: [["chapter"]],
    parser: {
      mainSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("chapter", [pt2.number]),
          endedBy: ["chapter"]
        }
      ]
    }
  },
  {
    // CP - graft label and add stub scope, then remove graft and modify scope at tidy stage
    contexts: [["pubchapter"]],
    parser: {
      mainSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("pubChapter", [pt2.numberString]),
          endedBy: ["pubchapter", "chapter"]
        }
      ]
    }
  },
  {
    // CA - graft label and add stub scope, then remove graft and modify scope at tidy stage
    contexts: [["startTag", "tagName", ["ca"]]],
    parser: {
      inlineSequenceType: "altNumber",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("inline", [pt2.fullTagName]),
          endedBy: ["endTag/ca", "endBlock", "implicitEnd"],
          onEnd: (parser) => parser.returnToBaseSequence()
        }
      ],
      during: (parser, pt2) => {
        const scopeId = utils.generateId();
        const caScope = {
          label: () => labelForScope$2("altChapter", [scopeId]),
          endedBy: ["startTag/ca", "chapter"]
        };
        parser.openNewScope(pt2, caScope, true, parser.sequences.main);
      }
    }
  },
  {
    // VERSES - verse and verses scopes
    contexts: [["verses"]],
    parser: {
      mainSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("verses", [pt2.numberString]),
          endedBy: ["verses", "chapter", "pubchapter"]
        }
      ],
      during: (parser, pt2) => {
        pt2.numbers.forEach((n) => {
          const verseScope = {
            label: () => labelForScope$2("verse", [n]),
            endedBy: ["verses", "chapter", "pubchapter"]
          };
          parser.openNewScope(pt2, verseScope, true, parser.sequences.main);
        });
      }
    }
  },
  {
    // VP - graft label and add stub scope, then remove graft and modify scope at tidy stage
    contexts: [["startTag", "tagName", ["vp"]]],
    parser: {
      inlineSequenceType: "pubNumber",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("inline", [pt2.fullTagName]),
          endedBy: ["endTag/vp", "endBlock", "implicitEnd"],
          onEnd: (parser) => parser.returnToBaseSequence()
        }
      ],
      during: (parser, pt2) => {
        const scopeId = utils.generateId();
        const vpScope = {
          label: () => labelForScope$2("pubVerse", [scopeId]),
          endedBy: ["startTag/vp", "verses", "chapter", "pubchapter"]
        };
        parser.openNewScope(pt2, vpScope, true, parser.sequences.main);
      }
    }
  },
  {
    // VA - graft label and add stub scope, then remove graft and modify scope at tidy stage
    contexts: [["startTag", "tagName", ["va"]]],
    parser: {
      inlineSequenceType: "altNumber",
      forceNewSequence: true,
      newScopes: [
        {
          label: (pt2) => labelForScope$2("inline", [pt2.fullTagName]),
          endedBy: ["endTag/va", "endBlock", "implicitEnd"],
          onEnd: (parser) => parser.returnToBaseSequence()
        }
      ],
      during: (parser, pt2) => {
        const scopeId = utils.generateId();
        const vpScope = {
          label: () => labelForScope$2("altVerse", [scopeId]),
          endedBy: ["startTag/va", "verses", "chapter", "pubchapter"]
        };
        parser.openNewScope(pt2, vpScope, true, parser.sequences.main);
      }
    }
  },
  {
    // CHARACTER MARKUP - add scope
    contexts: [
      [
        "startTag",
        "tagName",
        [
          "qs",
          "qac",
          "litl",
          "lik",
          "liv",
          "fr",
          "fq",
          "fqa",
          "fk",
          "fl",
          "fw",
          "fp",
          "fv",
          "ft",
          "fdc",
          "fm",
          "xo",
          "xk",
          "xq",
          "xt",
          "xta",
          "xop",
          "xot",
          "xnt",
          "xdc",
          "rq",
          "add",
          "bk",
          "dc",
          "k",
          "nd",
          "ord",
          "pn",
          "png",
          "qt",
          "sig",
          "sls",
          "tl",
          "wj",
          "em",
          "bd",
          "it",
          "bdit",
          "no",
          "sc",
          "sup",
          "ior",
          "iqt"
        ].concat(pt.customTags.char)
      ]
    ],
    parser: {
      newScopes: [
        {
          label: (pt2) => labelForScope$2("span", [pt2.fullTagName]),
          endedBy: ["endBlock", "endTag/$fullTagName$", "implicitEnd"]
        }
      ]
    }
  },
  {
    // CELL - unpick tagName, add scope
    contexts: [["startTag", "tagName", ["th", "thr", "tc", "tcr"]]],
    parser: {
      newScopes: [
        {
          label: (pt2) => labelForScope$2("cell", [pt2.fullTagName]),
          endedBy: [
            "startTag/th",
            "startTag/thr",
            "startTag/tc",
            "startTag/tcr",
            "startTag/th2",
            "startTag/thr2",
            "startTag/tc2",
            "startTag/tcr2",
            "startTag/th3",
            "startTag/thr3",
            "startTag/tc3",
            "startTag/tcr3",
            "endBlock",
            "endTag/$fullTagName$"
          ]
        }
      ]
    }
  },
  {
    // EMPTY MILESTONE - add open and close scope
    contexts: [["emptyMilestone"]],
    parser: {
      during: (parser, pt2) => {
        parser.addEmptyMilestone(labelForScope$2("milestone", [pt2.tagName]), pt2);
      }
    }
  },
  {
    // START MILESTONE - open scope, set attribute context
    contexts: [["startMilestoneTag", "sOrE", "s"]],
    parser: {
      newScopes: [
        {
          label: (pt2) => labelForScope$2("milestone", [pt2.tagName]),
          endedBy: ["endMilestone/$tagName$"]
        }
      ],
      during: (parser, pt2) => {
        parser.setAttributeContext(labelForScope$2("milestone", [pt2.tagName]));
      }
    }
  },
  {
    // END MILESTONE - close scope, clear attribute context
    contexts: [["endMilestoneMarker"]],
    parser: { during: (parser) => parser.clearAttributeContext() }
  },
  {
    // ATTRIBUTE - open scope based on attribute context
    contexts: [["attribute"], ["defaultAttribute"]],
    parser: {
      during: (parser, pt2) => {
        const defaults2 = {
          w: "lemma",
          rb: "gloss",
          xt: "link-href"
        };
        if (parser.current.attributeContext) {
          const contextParts = parser.current.attributeContext.split("/");
          if (pt2.key === "default" && contextParts.length === 2) {
            pt2.key = defaults2[contextParts[1]] || `unknownDefault_${contextParts[1]}`;
            pt2.printValue = pt2.printValue.replace(/default/, pt2.key);
          }
          [...pt2.values.entries()].forEach((na) => {
            const attScope = {
              label: (pt3) => labelForScope$2("attribute", [
                parser.current.attributeContext,
                pt3.key,
                na[0],
                na[1]
              ]),
              endedBy: [`$attributeContext$`]
            };
            parser.openNewScope(pt2, attScope);
          });
        } else {
          parser.addToken(
            constructorForFragment.printable("unknown", [pt2.printValue])
          );
        }
      }
    }
  },
  {
    // WORD-LEVEL MARKUP - open scope and set attribute context
    contexts: [
      [
        "startTag",
        "tagName",
        [
          "w",
          "rb",
          "jmp"
          // 'xt',
        ].concat(pt.customTags.word)
      ]
    ],
    parser: {
      newScopes: [
        {
          label: (pt2) => labelForScope$2("spanWithAtts", [pt2.tagName]),
          endedBy: ["endBlock", "endTag/$tagName$"],
          onEnd: (parser) => parser.clearAttributeContext()
        }
      ],
      during: (parser, pt2) => {
        parser.setAttributeContext(labelForScope$2("spanWithAtts", [pt2.tagName]));
      }
    }
  },
  {
    // TOKEN - add a token!
    contexts: [["wordLike"], ["lineSpace"], ["punctuation"], ["eol"]],
    parser: { during: (parser, pt2) => parser.addToken(pt2) }
  },
  {
    // NO BREAK SPACE - make a token!
    contexts: [["noBreakSpace"]],
    parser: {
      during: (parser) => {
        parser.addToken(
          constructorForFragment.printable("lineSpace", [" "])
        );
      }
    }
  },
  {
    // SOFT LINE BREAK - make a token!
    contexts: [["softLineBreak"]],
    parser: {
      during: (parser) => {
        parser.addToken(
          constructorForFragment.printable("softLineBreak", ["//"])
        );
      }
    }
  },
  {
    // BARESLASH - make a token!
    contexts: [["bareSlash"]],
    parser: {
      during: (parser) => {
        parser.addToken(constructorForFragment.printable("bareSlash", ["\\"]));
      }
    }
  },
  {
    // UNKNOWN - make a token!
    contexts: [["unknown"]],
    parser: {
      during: (parser, pt2) => {
        parser.addToken(
          constructorForFragment.printable("unknown", [pt2.printValue])
        );
      }
    }
  }
];
const { labelForScope: labelForScope$1 } = utils.scopeDefs;
const parserConstantDef$1 = utils.parserConstants;
const Parser2 = class {
  constructor(filterOptions, customTags, emptyBlocks) {
    this.filterOptions = filterOptions;
    this.customTags = customTags;
    this.emptyBlocks = emptyBlocks;
    this.specs = specs(this);
    this.specLookup = buildSpecLookup(this.specs);
    this.headers = {};
    this.baseSequenceTypes = parserConstantDef$1.usfm.baseSequenceTypes;
    this.inlineSequenceTypes = parserConstantDef$1.usfm.inlineSequenceTypes;
    this.setSequences();
    this.setCurrent();
  }
  setSequences() {
    this.sequences = {};
    for (const [sType, sArity] of Object.entries({
      ...this.baseSequenceTypes,
      ...this.inlineSequenceTypes
    })) {
      switch (sArity) {
        case "1":
          this.sequences[sType] = new Sequence(sType);
          break;
        case "?":
          this.sequences[sType] = null;
          break;
        case "*":
          this.sequences[sType] = [];
          break;
        default:
          throw new Error(
            `Unexpected sequence arity '${sArity}' for '${sType}'`
          );
      }
    }
    this.mainLike = this.sequences.main;
  }
  setCurrent() {
    this.current = {
      sequence: this.sequences.main,
      parentSequence: null,
      baseSequenceType: "main",
      inlineSequenceType: null,
      attributeContext: null
    };
  }
  parseItem(lexedItem) {
    let changeBaseSequence = false;
    if (["startTag"].includes(lexedItem.subclass)) {
      this.closeActiveScopes(`startTag/${lexedItem.fullTagName}`);
      if (!lexedItem.isNested) {
        this.closeActiveScopes(`implicitEnd`);
      }
    }
    if (["endTag"].includes(lexedItem.subclass)) {
      this.closeActiveScopes(`endTag/${lexedItem.fullTagName}`);
    }
    if (["startMilestoneTag"].includes(lexedItem.subclass) && lexedItem.sOrE === "e") {
      this.closeActiveScopes(`endMilestone/${lexedItem.tagName}`);
    }
    if (["chapter", "pubchapter", "verses"].includes(lexedItem.subclass)) {
      this.closeActiveScopes(lexedItem.subclass, this.sequences.main);
    }
    const spec = this.specForItem(lexedItem);
    if (spec) {
      if ("before" in spec.parser) {
        spec.parser.before(this, lexedItem);
      }
      changeBaseSequence = false;
      if (spec.parser.baseSequenceType) {
        const returnSequenceType = spec.parser.baseSequenceType === "mainLike" ? this.mainLike.type : spec.parser.baseSequenceType;
        changeBaseSequence = returnSequenceType !== this.current.baseSequenceType || spec.parser.forceNewSequence;
      }
      if (changeBaseSequence) {
        this.closeActiveScopes("baseSequenceChange");
        this.changeBaseSequence(spec.parser);
        if ("newBlock" in spec.parser && spec.parser.newBlock) {
          this.closeActiveScopes("endBlock");
          this.current.sequence.newBlock(
            labelForScope$1("blockTag", [lexedItem.fullTagName])
          );
        }
      } else if (spec.parser.inlineSequenceType) {
        this.current.inlineSequenceType = spec.parser.inlineSequenceType;
        this.current.parentSequence = this.current.sequence;
        if (this.current.parentSequence.type === "header") {
          this.current.parentSequence = this.sequences.main;
        }
        this.current.sequence = new Sequence(this.current.inlineSequenceType);
        this.current.sequence.newBlock(
          labelForScope$1("inline", spec.parser.inlineSequenceType)
        );
        this.sequences[this.current.inlineSequenceType].push(
          this.current.sequence
        );
        this.current.parentSequence.addItem({
          type: "graft",
          subType: this.current.inlineSequenceType,
          payload: this.current.sequence.id
        });
      } else if ("newBlock" in spec.parser && spec.parser.newBlock) {
        this.current.sequence.newBlock(
          labelForScope$1("blockTag", [lexedItem.fullTagName])
        );
      }
      if ("during" in spec.parser) {
        spec.parser.during(this, lexedItem);
      }
      this.openNewScopes(spec.parser, lexedItem);
      if ("after" in spec.parser) {
        spec.parser.after(this, lexedItem);
      }
    }
  }
  tidy() {
    for (const introduction of this.sequences.introduction) {
      introduction.graftifyIntroductionHeadings(this);
    }
    const allSequences = this.allSequences();
    for (const seq of allSequences) {
      seq.trim();
      seq.reorderSpanWithAtts();
      seq.makeNoteGrafts(this);
      seq.moveOrphanScopes();
      seq.removeEmptyBlocks(this.emptyBlocks);
    }
    const emptySequences = this.emptySequences(allSequences);
    for (const seq of allSequences) {
      if (emptySequences) {
        seq.removeGraftsToEmptySequences(emptySequences);
      }
      seq.addTableScopes();
      seq.close(this);
      this.substitutePubNumberScopes(seq);
      seq.moveOrphanStartScopes2();
      if (seq.type === "sidebar") {
        this.substituteEsbCatScopes(seq);
      }
      if (["footnote", "xref", "fig"].includes(seq.type)) {
        seq.lastBlock().inlineToEnd();
      }
    }
  }
  emptySequences(sequences) {
    return sequences.filter((s) => s.blocks.length === 0).map((s) => s.id);
  }
  substitutePubNumberScopes(seq) {
    const scopeToGraftContent = {};
    const sequenceById = this.sequenceById();
    for (const block2 of seq.blocks) {
      let spliceCount = 0;
      const itItems = [...block2.items];
      for (const [n, item] of itItems.entries()) {
        if (item.type === "graft" && ["pubNumber", "altNumber"].includes(item.subType)) {
          const graftContent = sequenceById[item.payload].text().trim();
          const scopeId = itItems[n + 1].payload.split("/")[1];
          scopeToGraftContent[scopeId] = graftContent;
          block2.items.splice(n - spliceCount, 1);
          spliceCount++;
        }
      }
    }
    if (Object.keys(scopeToGraftContent).length > 0) {
      for (const block2 of seq.blocks) {
        for (const scope2 of block2.items.filter((i) => i.type === "scope")) {
          const scopeParts = scope2.payload.split("/");
          if (["altChapter", "pubVerse", "altVerse"].includes(scopeParts[0])) {
            scope2.payload = `${scopeParts[0]}/${scopeToGraftContent[scopeParts[1]]}`;
          }
        }
      }
    }
  }
  substituteEsbCatScopes(seq) {
    const scopeToGraftContent = {};
    const sequenceById = this.sequenceById();
    for (const block2 of seq.blocks) {
      let spliceCount = 0;
      const itItems = [...block2.items];
      for (const [n, item] of itItems.entries()) {
        if (item.type === "graft" && item.subType === "esbCat") {
          const catContent = sequenceById[item.payload].text().trim();
          const scopeId = itItems[1].payload.split("/")[1];
          scopeToGraftContent[scopeId] = catContent;
          block2.items.splice(n - spliceCount, 1);
          spliceCount++;
        }
      }
    }
    if (Object.keys(scopeToGraftContent).length > 0) {
      for (const block2 of seq.blocks) {
        for (const scope2 of block2.items.filter((i) => i.type === "scope")) {
          const scopeParts = scope2.payload.split("/");
          if (scopeParts[0] === "esbCat") {
            scope2.payload = `${scopeParts[0]}/${scopeToGraftContent[scopeParts[1]]}`;
          }
        }
      }
    }
  }
  allSequences() {
    const ret = [];
    for (const [seqName, seqArity] of Object.entries({
      ...this.baseSequenceTypes,
      ...this.inlineSequenceTypes
    })) {
      switch (seqArity) {
        case "1":
        case "?":
          if (this.sequences[seqName]) {
            ret.push(this.sequences[seqName]);
          }
          break;
        case "*":
          this.sequences[seqName].forEach((s) => {
            ret.push(s);
          });
          break;
        default:
          throw new Error(
            `Unexpected sequence arity '${seqArity}' for '${seqName}'`
          );
      }
    }
    return ret;
  }
  sequenceById() {
    const ret = {};
    this.allSequences().forEach((s) => {
      ret[s.id] = s;
    });
    return ret;
  }
  filter() {
    const usedSequences = [];
    const sequenceById = this.sequenceById();
    this.filterGrafts(
      this.sequences.main.id,
      sequenceById,
      usedSequences,
      this.filterOptions
    );
    this.removeUnusedSequences(usedSequences);
    this.filterScopes(Object.values(sequenceById), this.filterOptions);
  }
  filterGrafts(seqId, seqById, used, options2) {
    used.push(seqId);
    const childSequences = seqById[seqId].filterGrafts(options2);
    for (const si of childSequences) {
      if (seqById[si].type === "main") {
        throw new Error(
          "MAIN is child!",
          JSON.stringify(seqById[seqId], null, 2)
        );
      }
      this.filterGrafts(si, seqById, used, options2);
    }
  }
  removeUnusedSequences(usedSequences) {
    for (const seq of this.allSequences()) {
      if (!usedSequences.includes(seq.id)) {
        const seqArity = {
          ...this.baseSequenceTypes,
          ...this.inlineSequenceTypes
        }[seq.type];
        switch (seqArity) {
          case "1":
            throw new Error("Attempting to remove sequence with arity of 1");
          case "?":
            this.sequences[seq.type] = null;
            break;
          case "*":
            this.sequences[seq.type] = this.sequences[seq.type].filter(
              (s) => s.id !== seq.id
            );
            break;
          default:
            throw new Error(
              `Unexpected sequence arity '${seqArity}' for '${seq.type}'`
            );
        }
      }
    }
  }
  filterScopes(sequences, options2) {
    sequences.forEach((s) => s.filterScopes(options2));
  }
  specForItem(item) {
    const context = item.subclass;
    if (!(context in this.specLookup)) {
      return null;
    }
    for (const accessor of ["tagName", "sOrE"]) {
      if (accessor in item && accessor in this.specLookup[context] && item[accessor] in this.specLookup[context][accessor]) {
        return { parser: this.specLookup[context][accessor][item[accessor]] };
      }
    }
    if ("_noAccessor" in this.specLookup[context]) {
      return { parser: this.specLookup[context]["_noAccessor"] };
    }
    return null;
  }
  closeActiveScopes(closeLabel, targetSequence) {
    if (targetSequence === void 0) {
      targetSequence = this.current.sequence;
    }
    const matchedScopes = targetSequence.activeScopes.filter((sc) => sc.endedBy.includes(closeLabel)).reverse();
    targetSequence.activeScopes = targetSequence.activeScopes.filter(
      (sc) => !sc.endedBy.includes(closeLabel)
    );
    matchedScopes.forEach((ms) => this.closeActiveScope(ms, targetSequence));
  }
  closeActiveScope(sc, targetSequence) {
    this.addScope("end", sc.label, targetSequence);
    if (sc.onEnd) {
      sc.onEnd(this, sc.label);
    }
  }
  changeBaseSequence(parserSpec) {
    const newType = parserSpec.baseSequenceType;
    if (newType === "mainLike") {
      this.current.sequence = this.mainLike;
      return;
    }
    this.current.baseSequenceType = newType;
    const arity = this.baseSequenceTypes[newType];
    switch (arity) {
      case "1":
        this.current.sequence = this.sequences[newType];
        break;
      case "?":
        if (!this.sequences[newType]) {
          this.sequences[newType] = new Sequence(newType);
        }
        this.current.sequence = this.sequences[newType];
        break;
      case "*":
        this.current.sequence = new Sequence(newType);
        if (!parserSpec.useTempSequence) {
          this.sequences[newType].push(this.current.sequence);
        }
        break;
      default:
        throw new Error(
          `Unexpected base sequence arity '${arity}' for '${newType}'`
        );
    }
    if (!parserSpec.useTempSequence && this.current.sequence.type !== "main") {
      this.mainLike.addBlockGraft({
        type: "graft",
        subType: this.current.baseSequenceType,
        payload: this.current.sequence.id
      });
    }
  }
  returnToBaseSequence() {
    this.current.inlineSequenceType = null;
    this.current.sequence = this.current.parentSequence;
    this.current.parentSequence = null;
  }
  openNewScopes(parserSpec, pt) {
    if (parserSpec.newScopes) {
      let targetSequence = this.current.sequence;
      if ("mainSequence" in parserSpec && parserSpec.mainSequence) {
        targetSequence = this.sequences.main;
      }
      parserSpec.newScopes.forEach(
        (sc) => this.openNewScope(pt, sc, true, targetSequence)
      );
    }
  }
  openNewScope(pt, sc, addItem, targetSequence) {
    if (addItem === void 0) {
      addItem = true;
    }
    if (targetSequence === void 0) {
      targetSequence = this.current.sequence;
    }
    if (addItem) {
      targetSequence.addItem({
        type: "scope",
        subType: "start",
        payload: sc.label(pt)
      });
    }
    const newScope = {
      label: sc.label(pt),
      endedBy: this.substituteEndedBys(sc.endedBy, pt)
    };
    if ("onEnd" in sc) {
      newScope.onEnd = sc.onEnd;
    }
    targetSequence.activeScopes.push(newScope);
  }
  substituteEndedBys(endedBy, pt) {
    return endedBy.map((eb) => {
      let ret = eb.replace("$fullTagName$", pt.fullTagName).replace("$tagName$", pt.tagName);
      if (this.current.attributeContext) {
        ret = ret.replace(
          "$attributeContext$",
          this.current.attributeContext.replace("milestone", "endMilestone").replace("spanWithAtts", "endTag")
        );
      }
      return ret;
    });
  }
  addToken(pt) {
    this.current.sequence.addItem({
      type: "token",
      subType: pt.subclass,
      payload: pt.printValue
    });
  }
  addScope(sOrE, label, targetSequence) {
    if (targetSequence === void 0) {
      targetSequence = this.current.sequence;
    }
    targetSequence.addItem({
      type: "scope",
      subType: sOrE,
      payload: label
    });
  }
  addEmptyMilestone(label, pt) {
    this.mainLike.addItem({
      type: "scope",
      subType: "start",
      payload: label
    });
    const startAttributeStrings = pt.attributes.map(
      (kv) => `attribute/${label}/${kv[0]}/0/${kv[1]}`
    );
    for (const aString of startAttributeStrings) {
      this.mainLike.addItem({
        type: "scope",
        subType: "start",
        payload: aString
      });
    }
    for (const aString of startAttributeStrings.reverse()) {
      this.mainLike.addItem({
        type: "scope",
        subType: "end",
        payload: aString
      });
    }
    this.mainLike.addItem({
      type: "scope",
      subType: "end",
      payload: label
    });
  }
  setAttributeContext(label) {
    this.current.attributeContext = label;
  }
  clearAttributeContext() {
    this.current.attributeContext = null;
  }
};
const ByteArray$2 = utils.ByteArray;
const { itemEnum: itemEnum$2 } = utils.itemDefs;
const { tokenEnum: tokenEnum$1 } = utils.tokenDefs;
const emptyCVIndexType = 0;
const shortCVIndexType = 2;
const longCVIndexType = 3;
const buildChapterVerseIndex = (document) => {
  const mainSequence = document.sequences[document.mainId];
  const docSet = document.processor.docSets[document.docSetId];
  docSet.buildPreEnums();
  docSet.buildEnumIndexes();
  const chapterVerseIndexes = {};
  const chapterIndexes = {};
  let chapterN = "0";
  let verseN = "0";
  let verses = "1";
  let nextTokenN = 0;
  mainSequence.chapterVerses = {};
  if (docSet.enums.wordLike.length === 0) {
    throw new Error(
      "No wordLike content in docSet - probably a USFM issue, maybe missing \\mt?"
    );
  }
  mainSequence.tokensPresent = new BitSet(
    new Array(docSet.enums.wordLike.length).fill(0).map((b) => b.toString()).join("")
  );
  for (const [blockN, block2] of mainSequence.blocks.entries()) {
    let pos = 0;
    let succinct2 = block2.c;
    let itemN = -1;
    while (pos < succinct2.length) {
      itemN++;
      const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
        succinct2,
        pos
      );
      if (itemType === itemEnum$2["startScope"]) {
        let scopeLabel = docSet.succinctScopeLabel(succinct2, itemSubtype, pos);
        if (scopeLabel.startsWith("chapter/")) {
          chapterN = scopeLabel.split("/")[1];
          chapterVerseIndexes[chapterN] = {};
          chapterIndexes[chapterN] = {
            startBlock: blockN,
            startItem: itemN,
            nextToken: nextTokenN
          };
        } else if (scopeLabel.startsWith("verse/")) {
          verseN = scopeLabel.split("/")[1];
          if (verseN === "1" && !("0" in chapterVerseIndexes[chapterN])) {
            if (chapterIndexes[chapterN].nextToken < nextTokenN) {
              chapterVerseIndexes[chapterN]["0"] = [
                {
                  startBlock: chapterIndexes[chapterN].startBlock,
                  startItem: chapterIndexes[chapterN].startItem,
                  endBlock: blockN,
                  endItem: Math.max(itemN - 1, 0),
                  nextToken: chapterIndexes[chapterN].nextToken,
                  verses: "0"
                }
              ];
            }
          }
          if (!(verseN in chapterVerseIndexes[chapterN])) {
            chapterVerseIndexes[chapterN][verseN] = [];
          }
          chapterVerseIndexes[chapterN][verseN].push({
            startBlock: blockN,
            startItem: itemN,
            nextToken: nextTokenN
          });
        } else if (scopeLabel.startsWith("verses/")) {
          verses = scopeLabel.split("/")[1];
        }
      } else if (itemType === itemEnum$2["endScope"]) {
        let scopeLabel = docSet.succinctScopeLabel(succinct2, itemSubtype, pos);
        if (scopeLabel.startsWith("chapter/")) {
          chapterN = scopeLabel.split("/")[1];
          let chapterRecord = chapterIndexes[chapterN];
          if (chapterRecord) {
            chapterRecord.endBlock = blockN;
            chapterRecord.endItem = itemN;
          }
        } else if (scopeLabel.startsWith("verse/")) {
          verseN = scopeLabel.split("/")[1];
          let versesRecord = chapterVerseIndexes[chapterN][verseN];
          if (versesRecord) {
            const verseRecord = chapterVerseIndexes[chapterN][verseN][chapterVerseIndexes[chapterN][verseN].length - 1];
            verseRecord.endBlock = blockN;
            verseRecord.endItem = itemN;
            verseRecord.verses = verses;
          }
        }
      } else if (itemType === itemEnum$2["token"] && itemSubtype === tokenEnum$1["wordLike"]) {
        mainSequence.tokensPresent.set(succinct2.nByte(pos + 2), 1);
        nextTokenN++;
      }
      pos += itemLength;
    }
  }
  for (const [chapterN2, chapterVerses] of Object.entries(chapterVerseIndexes)) {
    const ba = new ByteArray$2();
    mainSequence.chapterVerses[chapterN2] = ba;
    const sortedVerses = Object.keys(chapterVerses).map((n) => parseInt(n)).sort((a, b) => a - b);
    if (sortedVerses.length === 0) {
      continue;
    }
    const maxVerse = sortedVerses[sortedVerses.length - 1];
    const verseSlots = Array.from(Array(maxVerse + 1).keys());
    let pos = 0;
    for (const verseSlot of verseSlots) {
      const verseKey = `${verseSlot}`;
      if (verseKey in chapterVerses) {
        const verseElements = chapterVerses[verseKey];
        const nVerseElements = verseElements.length;
        for (const [verseElementN, verseElement] of verseElements.entries()) {
          if (!verseElement.verses) {
            console.log(
              `** VerseElement without verses for ${verseSlot} in buildChapterVerseIndex`
            );
            continue;
          }
          const versesEnumIndex = docSet.enumForCategoryValue(
            "scopeBits",
            verseElement.verses
          );
          const recordType = verseElement.startBlock === verseElement.endBlock ? shortCVIndexType : longCVIndexType;
          ba.pushByte(0);
          if (recordType === shortCVIndexType) {
            ba.pushNBytes([
              verseElement.startBlock,
              verseElement.startItem,
              verseElement.endItem,
              verseElement.nextToken,
              versesEnumIndex
            ]);
          } else {
            ba.pushNBytes([
              verseElement.startBlock,
              verseElement.endBlock,
              verseElement.startItem,
              verseElement.endItem,
              verseElement.nextToken,
              versesEnumIndex
            ]);
          }
          ba.setByte(
            pos,
            makeVerseLengthByte(
              recordType,
              verseElementN === nVerseElements - 1,
              ba.length - pos
            )
          );
          pos = ba.length;
        }
      } else {
        ba.pushByte(makeVerseLengthByte(emptyCVIndexType, true, 1));
        pos++;
      }
    }
    ba.trim();
  }
  mainSequence.chapters = {};
  for (const [chapterN2, chapterElement] of Object.entries(chapterIndexes)) {
    if (!("startBlock" in chapterElement) || !("endBlock" in chapterElement)) {
      continue;
    }
    const ba = new ByteArray$2();
    mainSequence.chapters[chapterN2] = ba;
    const recordType = chapterElement.startBlock === chapterElement.endBlock ? shortCVIndexType : longCVIndexType;
    ba.pushByte(0);
    if (recordType === shortCVIndexType) {
      ba.pushNBytes([
        chapterElement.startBlock,
        chapterElement.startItem,
        chapterElement.endItem,
        chapterElement.nextToken
      ]);
    } else {
      ba.pushNBytes([
        chapterElement.startBlock,
        chapterElement.endBlock,
        chapterElement.startItem,
        chapterElement.endItem,
        chapterElement.nextToken
      ]);
    }
    ba.setByte(0, makeVerseLengthByte(recordType, true, ba.length));
    ba.trim();
  }
};
const chapterVerseIndex = (document, chapN) => {
  const docSet = document.processor.docSets[document.docSetId];
  docSet.buildEnumIndexes();
  const ret = [];
  const succinct2 = document.sequences[document.mainId].chapterVerses[chapN];
  if (succinct2) {
    let pos = 0;
    let currentVerseRecord = [];
    while (pos < succinct2.length) {
      const [recordType, isLast, recordLength] = verseLengthByte(succinct2, pos);
      if (recordType === shortCVIndexType) {
        const nBytes = succinct2.nBytes(pos + 1, 5);
        currentVerseRecord.push({
          startBlock: nBytes[0],
          endBlock: nBytes[0],
          startItem: nBytes[1],
          endItem: nBytes[2],
          nextToken: nBytes[3],
          verses: docSet.enums.scopeBits.countedString(
            docSet.enumIndexes.scopeBits[nBytes[4]]
          )
        });
      } else if (recordType === longCVIndexType) {
        const nBytes = succinct2.nBytes(pos + 1, 6);
        currentVerseRecord.push({
          startBlock: nBytes[0],
          endBlock: nBytes[1],
          startItem: nBytes[2],
          endItem: nBytes[3],
          nextToken: nBytes[4],
          verses: docSet.enums.scopeBits.countedString(
            docSet.enumIndexes.scopeBits[nBytes[5]]
          )
        });
      }
      if (isLast) {
        ret.push(currentVerseRecord);
        currentVerseRecord = [];
      }
      pos += recordLength;
    }
  }
  return ret;
};
const chapterIndex = (document, chapN) => {
  const succinct2 = document.sequences[document.mainId].chapters[chapN];
  if (succinct2) {
    const recordType = verseLengthByte(succinct2, 0)[0];
    if (recordType === shortCVIndexType) {
      const nBytes = succinct2.nBytes(1, 4);
      return {
        startBlock: nBytes[0],
        endBlock: nBytes[0],
        startItem: nBytes[1],
        endItem: nBytes[2],
        nextToken: nBytes[3]
      };
    } else if (recordType === longCVIndexType) {
      const nBytes = succinct2.nBytes(1, 5);
      return {
        startBlock: nBytes[0],
        endBlock: nBytes[1],
        startItem: nBytes[2],
        endItem: nBytes[3],
        nextToken: nBytes[4]
      };
    }
  }
};
const makeVerseLengthByte = (recordType, isLast, length) => length + (isLast ? 32 : 0) + recordType * 64;
const verseLengthByte = (succinct2, pos) => {
  const sByte = succinct2.byte(pos);
  return [sByte >> 6, (sByte >> 5) % 2 === 1, sByte % 32];
};
const gcSequences = (document) => {
  const usedSequences = /* @__PURE__ */ new Set();
  const docSet = document.processor.docSets[document.docSetId];
  docSet.maybeBuildEnumIndexes();
  const followGrafts = (document2, sequence, used) => {
    used.add(sequence.id);
    for (const block2 of sequence.blocks) {
      for (const blockGraft of docSet.unsuccinctifyGrafts(block2.bg)) {
        if (!used.has(blockGraft[2])) {
          followGrafts(document2, document2.sequences[blockGraft[2]], used);
        }
      }
      for (const inlineGraft of docSet.unsuccinctifyItems(
        block2.c,
        { grafts: true },
        0
      )) {
        if (!used.has(inlineGraft[2])) {
          followGrafts(document2, document2.sequences[inlineGraft[2]], used);
        }
      }
    }
  };
  followGrafts(document, document.sequences[document.mainId], usedSequences);
  let changed = false;
  for (const sequenceId of Object.keys(document.sequences)) {
    if (!usedSequences.has(sequenceId)) {
      delete document.sequences[sequenceId];
      changed = true;
    }
  }
  return changed;
};
const newSequence = (document, seqType, tags2) => {
  const seqId = utils.generateId();
  document.sequences[seqId] = {
    id: seqId,
    type: seqType,
    tags: new Set(tags2 || []),
    isBaseType: seqType in document.baseSequenceTypes,
    blocks: []
  };
  return seqId;
};
const deleteSequence = (document, seqId) => {
  if (!(seqId in document.sequences)) {
    return false;
  }
  if (document.sequences[seqId].type === "main") {
    throw new Error("Cannot delete main sequence");
  }
  if (document.sequences[seqId].type in document.baseSequenceTypes) {
    gcSequenceReferences(document, "block", seqId);
  } else {
    gcSequenceReferences(document, "inline", seqId);
  }
  delete document.sequences[seqId];
  document.buildChapterVerseIndex(globalThis);
  document.gcSequences();
  return true;
};
const gcSequenceReferences = (document, seqContext, seqId) => {
  const docSet = document.processor.docSets[document.docSetId];
  for (const sequence of Object.values(document.sequences)) {
    for (const block2 of sequence.blocks) {
      const succinct2 = seqContext === "block" ? block2.bg : block2.c;
      let pos = 0;
      while (pos < succinct2.length) {
        const [itemLength, itemType] = utils.succinct.headerBytes(
          succinct2,
          pos
        );
        if (itemType !== utils.itemDefs.itemEnum.graft) {
          pos += itemLength;
        } else {
          const graftSeqId = utils.succinct.succinctGraftSeqId(
            docSet.enums,
            docSet.enumIndexes,
            succinct2,
            pos
          );
          if (graftSeqId === seqId) {
            succinct2.deleteItem(pos);
          } else {
            pos += itemLength;
          }
        }
      }
    }
  }
};
const modifySequence = (document, seqId, sequenceRewriteFunc, blockFilterFunc, itemFilterFunc, blockRewriteFunc, itemRewriteFunc) => {
  const docSet = document.processor.docSets[document.docSetId];
  docSet.maybeBuildEnumIndexes();
  sequenceRewriteFunc = sequenceRewriteFunc || ((s) => s);
  const oldSequence = document.sequences[seqId];
  const newSequence2 = sequenceRewriteFunc({
    id: seqId,
    type: oldSequence.type,
    tags: oldSequence.tags,
    isBaseType: oldSequence.isBaseType,
    verseMapping: oldSequence.verseMapping
  });
  pushModifiedBlocks(
    oldSequence,
    newSequence2,
    blockFilterFunc,
    itemFilterFunc,
    blockRewriteFunc,
    itemRewriteFunc
  );
  document.sequences[seqId] = newSequence2;
  if (newSequence2.type === "main") {
    document.buildChapterVerseIndex();
  }
  return newSequence2;
};
const pushModifiedBlocks = (oldSequence, newSequence2, blockFilterFunc, itemFilterFunc, blockRewriteFunc, itemRewriteFunc) => {
  blockFilterFunc = blockFilterFunc || ((oldSequence2, blockN, block2) => !!block2);
  itemFilterFunc = itemFilterFunc || ((oldSequence2, oldBlockN, block2, itemN, itemType, itemSubType, pos) => !!block2 || pos);
  blockRewriteFunc = blockRewriteFunc || ((oldSequence2, blockN, block2) => block2);
  itemRewriteFunc = itemRewriteFunc || ((oldSequence2, oldBlockN, oldBlock, newBlock2, itemN, itemLength, itemType, itemSubType, pos) => {
    for (let n = 0; n < itemLength; n++) {
      newBlock2.c.pushByte(oldBlock.c.byte(pos + n));
    }
  });
  newSequence2.blocks = [];
  for (const [blockN, block2] of oldSequence.blocks.entries()) {
    if (blockFilterFunc(oldSequence, blockN, block2)) {
      const newBlock2 = blockRewriteFunc(oldSequence, blockN, deepCopy$1(block2));
      newBlock2.c.clear();
      modifyBlockItems(
        oldSequence,
        blockN,
        block2,
        newBlock2,
        itemFilterFunc,
        itemRewriteFunc
      );
      newSequence2.blocks.push(newBlock2);
    }
  }
};
const modifyBlockItems = (oldSequence, oldBlockN, oldBlock, newBlock2, itemFilterFunc, itemRewriteFunc) => {
  let pos = 0;
  let itemN = -1;
  while (pos < oldBlock.c.length) {
    itemN++;
    const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
      oldBlock.c,
      pos
    );
    if (itemFilterFunc(
      oldSequence,
      oldBlockN,
      oldBlock,
      itemN,
      itemType,
      itemSubtype,
      pos
    )) {
      itemRewriteFunc(
        oldSequence,
        oldBlockN,
        oldBlock,
        newBlock2,
        itemN,
        itemLength,
        itemType,
        itemSubtype,
        pos
      );
    }
    pos += itemLength;
  }
};
const ByteArray$1 = utils.ByteArray;
const {
  pushSuccinctGraftBytes,
  pushSuccinctScopeBytes,
  pushSuccinctTokenBytes
} = utils.succinct;
const { itemEnum: itemEnum$1 } = utils.itemDefs;
const { scopeEnum, scopeEnumLabels, nComponentsForScope } = utils.scopeDefs;
const { tokenCategory, tokenEnum } = utils.tokenDefs;
const { headerBytes } = utils.succinct;
const deleteBlock = (document, seqId, blockN, buildCV) => {
  if (buildCV !== false) {
    buildCV = true;
  }
  if (!(seqId in document.sequences)) {
    return false;
  }
  const sequence = document.sequences[seqId];
  if (blockN < 0 || blockN >= sequence.blocks.length) {
    return false;
  }
  sequence.blocks.splice(blockN, 1);
  if (buildCV) {
    document.buildChapterVerseIndex(globalThis);
  }
  return true;
};
const newBlock = (document, seqId, blockN, blockScope, blockGrafts, buildCV) => {
  if (buildCV !== false) {
    buildCV = true;
  }
  if (!(seqId in document.sequences)) {
    return false;
  }
  const sequence = document.sequences[seqId];
  if (blockN < 0 || blockN > sequence.blocks.length) {
    return false;
  }
  const docSet = document.processor.docSets[document.docSetId];
  docSet.maybeBuildPreEnums();
  const newBlock2 = {
    bs: new ByteArray$1(0),
    bg: new ByteArray$1(0),
    c: new ByteArray$1(0),
    os: new ByteArray$1(0),
    is: new ByteArray$1(0),
    nt: new ByteArray$1(0)
  };
  const scopeBits = blockScope.split("/");
  const scopeTypeByte = scopeEnum[scopeBits[0]];
  const expectedNScopeBits = nComponentsForScope(scopeBits[0]);
  if (scopeBits.length !== expectedNScopeBits) {
    throw new Error(
      `Scope ${blockScope} has ${scopeBits.length} component(s) (expected ${expectedNScopeBits}`
    );
  }
  const scopeBitBytes = scopeBits.slice(1).map((b) => docSet.enumForCategoryValue("scopeBits", b, true));
  pushSuccinctScopeBytes(
    newBlock2.bs,
    itemEnum$1[`startScope`],
    scopeTypeByte,
    scopeBitBytes
  );
  newBlock2.bs.trim();
  if (blockGrafts) {
    updateBlockGrafts(docSet, document.id, seqId, blockN, blockGrafts);
  }
  sequence.blocks.splice(blockN, 0, newBlock2);
  if (buildCV) {
    document.buildChapterVerseIndex();
  }
  return true;
};
const rewriteBlock = (block2, oldToNew) => {
  for (const blockKey of ["bs", "bg", "c", "is", "os"]) {
    const oldBa = block2[blockKey];
    const newBa = new ByteArray$1(oldBa.length);
    let pos = 0;
    while (pos < oldBa.length) {
      const [itemLength, itemType, itemSubtype] = headerBytes(oldBa, pos);
      if (itemType === itemEnum$1["token"]) {
        if (itemSubtype === tokenEnum.wordLike) {
          pushSuccinctTokenBytes(
            newBa,
            itemSubtype,
            oldToNew.wordLike[oldBa.nByte(pos + 2)]
          );
        } else {
          pushSuccinctTokenBytes(
            newBa,
            itemSubtype,
            oldToNew.notWordLike[oldBa.nByte(pos + 2)]
          );
        }
      } else if (itemType === itemEnum$1["graft"]) {
        pushSuccinctGraftBytes(
          newBa,
          oldToNew.graftTypes[itemSubtype],
          oldToNew.ids[oldBa.nByte(pos + 2)]
        );
      } else {
        let nScopeBitBytes = nComponentsForScope(scopeEnumLabels[itemSubtype]);
        const scopeBitBytes = [];
        let offset = 2;
        while (nScopeBitBytes > 1) {
          const scopeBitByte = oldToNew.scopeBits[oldBa.nByte(pos + offset)];
          scopeBitBytes.push(scopeBitByte);
          offset += oldBa.nByteLength(scopeBitByte);
          nScopeBitBytes--;
        }
        pushSuccinctScopeBytes(newBa, itemType, itemSubtype, scopeBitBytes);
      }
      pos += itemLength;
    }
    newBa.trim();
    block2[blockKey] = newBa;
  }
};
const ByteArray2 = utils.ByteArray;
const { itemEnum } = utils.itemDefs;
const succinctFilter = (document, filterOptions) => {
  if (!filterOptions || Object.keys(filterOptions).length === 0) {
    return;
  }
  const docSet = document.processor.docSets[document.docSetId];
  const filterItem = (oldSequence, oldBlockN, block2, itemN, itemType, itemSubType, pos) => {
    if (itemType === itemEnum.token) {
      return true;
    } else if (itemType === itemEnum.startScope || itemType === itemEnum.endScope) {
      if (!filterOptions.includeScopes && !filterOptions.excludeScopes) {
        return true;
      } else {
        const scopeOb = docSet.unsuccinctifyScope(
          block2.c,
          itemType,
          itemSubType,
          pos
        );
        return (!filterOptions.includeScopes || filterOptions.includeScopes.filter(
          (op) => scopeOb[2].startsWith(op)
        ).length > 0) && (!filterOptions.excludeScopes || filterOptions.excludeScopes.filter(
          (op) => scopeOb[2].startsWith(op)
        ).length === 0);
      }
    } else {
      if (!filterOptions.includeGrafts && !filterOptions.excludeGrafts) {
        return true;
      }
      const graftOb = docSet.unsuccinctifyGraft(block2.c, itemSubType, pos);
      return (!filterOptions.includeGrafts || filterOptions.includeGrafts.filter((op) => graftOb[1].startsWith(op)).length > 0) && (!filterOptions.excludeGrafts || filterOptions.excludeGrafts.filter((op) => graftOb[1].startsWith(op)).length === 0);
    }
  };
  const rewriteBlock2 = (oldSequence, blockN, block2) => {
    const newBA = new ByteArray2(block2.bg.length);
    let pos = 0;
    while (pos < block2.bg.length) {
      const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
        block2.bg,
        pos
      );
      const graftOb = docSet.unsuccinctifyGraft(block2.bg, itemSubtype, pos);
      if ((!filterOptions.includeGrafts || filterOptions.includeGrafts.filter((op) => graftOb[1].startsWith(op)).length > 0) && (!filterOptions.excludeGrafts || filterOptions.excludeGrafts.filter((op) => graftOb[1].startsWith(op)).length === 0)) {
        for (let n = 0; n < itemLength; n++) {
          newBA.pushByte(block2.bg.byte(pos + n));
        }
      }
      pos += itemLength;
    }
    newBA.trim();
    block2.bg = newBA;
    return block2;
  };
  Object.keys(document.sequences).forEach((seqId) => {
    document.modifySequence(seqId, null, null, filterItem, rewriteBlock2, null);
  });
  Object.values(document.sequences).forEach(
    (seq) => docSet.updateBlockIndexesAfterFilter(seq)
  );
  document.gcSequences();
};
const serializeSuccinct = (document) => {
  const ret = { sequences: {} };
  ret.headers = document.headers;
  ret.mainId = document.mainId;
  ret.tags = Array.from(document.tags);
  for (const [seqId, seqOb] of Object.entries(document.sequences)) {
    ret.sequences[seqId] = serializeSuccinctSequence(seqOb);
  }
  return ret;
};
const serializeSuccinctSequence = (seqOb) => {
  const ret = {
    type: seqOb.type,
    blocks: seqOb.blocks.map((b) => serializeSuccinctBlock(b)),
    tags: Array.from(seqOb.tags)
  };
  if (seqOb.type === "main") {
    ret.chapters = {};
    for (const [chK, chV] of Object.entries(seqOb.chapters || {})) {
      chV.trim();
      ret.chapters[chK] = chV.base64();
    }
    ret.chapterVerses = {};
    for (const [chvK, chvV] of Object.entries(seqOb.chapterVerses || {})) {
      chvV.trim();
      ret.chapterVerses[chvK] = chvV.base64();
    }
    if ("tokensPresent" in seqOb) {
      ret.tokensPresent = "0x" + seqOb.tokensPresent.toString(16);
    }
  }
  return ret;
};
const serializeSuccinctBlock = (blockOb) => {
  for (const succName of ["bs", "bg", "c", "is", "os", "nt"]) {
    blockOb[succName].trim();
  }
  return {
    bs: blockOb.bs.base64(),
    bg: blockOb.bg.base64(),
    c: blockOb.c.base64(),
    is: blockOb.is.base64(),
    os: blockOb.os.base64(),
    nt: blockOb.nt.base64()
  };
};
const recordPreEnums = (docSet, seq) => {
  docSet.recordPreEnum("scopeBits", "0");
  for (const [blockN, block2] of seq.blocks.entries()) {
    for (const [itemN, item] of [
      ...block2.items,
      block2.bs,
      ...block2.bg
    ].entries()) {
      if (item.subType === "wordLike") {
        docSet.recordPreEnum("wordLike", item.payload);
      } else if ([
        "lineSpace",
        "eol",
        "punctuation",
        "softLineBreak",
        "bareSlash",
        "unknown"
      ].includes(item.subType)) {
        docSet.recordPreEnum("notWordLike", item.payload);
      } else if (item.type === "graft") {
        docSet.recordPreEnum("graftTypes", item.subType);
      } else if (item.subType === "start") {
        const labelBits = item.payload.split("/");
        if (labelBits.length !== utils.scopeDefs.nComponentsForScope(labelBits[0])) {
          throw new Error(
            `Scope ${item.payload} has unexpected number of components`
          );
        }
        for (const labelBit of labelBits.slice(1)) {
          docSet.recordPreEnum("scopeBits", labelBit);
        }
      }
    }
  }
};
const rerecordPreEnums = (docSet, seq) => {
  docSet.recordPreEnum("scopeBits", "0");
  docSet.recordPreEnum("ids", seq.id);
  for (const block2 of seq.blocks) {
    for (const blockKey of ["bs", "bg", "c", "is", "os"]) {
      rerecordBlockPreEnums(docSet, block2[blockKey]);
    }
  }
};
const rerecordBlockPreEnums = (docSet, ba) => {
  for (const item of docSet.unsuccinctifyItems(ba, {}, 0)) {
    if (item[0] === "token") {
      if (item[1] === "wordLike") {
        docSet.recordPreEnum("wordLike", item[2]);
      } else {
        docSet.recordPreEnum("notWordLike", item[2]);
      }
    } else if (item[0] === "graft") {
      docSet.recordPreEnum("graftTypes", item[1]);
    } else if (item[0] === "scope" && item[1] === "start") {
      const labelBits = item[2].split("/");
      if (labelBits.length !== utils.scopeDefs.nComponentsForScope(labelBits[0])) {
        throw new Error(`Scope ${item[2]} has unexpected number of components`);
      }
      for (const labelBit of labelBits.slice(1)) {
        docSet.recordPreEnum("scopeBits", labelBit);
      }
    }
  }
};
const oneifyTag$1 = (t) => {
  if (["toc", "toca", "mt", "imt", "s", "ms", "mte", "sd"].includes(t)) {
    return t + "1";
  }
  return t;
};
const actions = {
  startDocument: [
    {
      description: "Set up environment",
      test: () => true,
      action: ({ context, workspace, output }) => {
        workspace.paraStack = [];
        workspace.wrapperStack = [];
        const docContext = context.document.metadata.document;
        output.usj = {
          type: "USJ",
          version: "3.1",
          content: [
            {
              "type": "book",
              "marker": "id",
              "code": docContext.bookCode
            }
          ]
        };
        const idContent = docContext.id.split(" ").slice(1).join(" ");
        if (idContent.length > 0) {
          output.usj.content[0].content = [idContent];
        }
        for (let [key, value] of Object.entries(
          context.document.metadata.document
        ).filter(
          (kv) => !["id", "tags", "properties", "bookCode", "cl"].includes(kv[0])
        )) {
          let headerObject = {
            type: "para",
            marker: oneifyTag$1(key)
          };
          if (value) {
            headerObject.content = [value];
          }
          output.usj.content.push(headerObject);
        }
      }
    }
  ],
  blockGraft: [
    {
      description: "Follow block grafts",
      test: () => true,
      action: (environment) => {
        let contextSequence = environment.context.sequences[0];
        const target = contextSequence.block.target;
        if (target) {
          environment.context.renderer.renderSequenceId(environment, target);
        }
      }
    }
  ],
  startParagraph: [
    {
      description: "Push to paraStack",
      test: ({ context }) => !["f"].includes(context.sequences[0].block.subType.split(":")[1]),
      action: ({ context, workspace }) => {
        let tag = context.sequences[0].block.subType.split(":")[1];
        let paraOb = {
          type: "para",
          marker: oneifyTag$1(tag),
          content: []
        };
        workspace.paraStack.push(paraOb);
      }
    }
  ],
  endParagraph: [
    {
      description: "Merge paraStack one level down",
      test: ({ context }) => !["f"].includes(context.sequences[0].block.subType.split(":")[1]),
      action: ({ workspace, output }) => {
        let topPara = workspace.paraStack.pop();
        if (topPara.content.length === 0) {
          delete topPara.content;
        }
        if (workspace.paraStack.length === 0) {
          output.usj.content.push(topPara);
        } else {
          workspace.paraStack[workspace.paraStack.length - 1].content.push(topPara);
        }
      }
    }
  ],
  inlineGraft: [
    {
      description: "Treat footnotes and xrefs as paras",
      test: () => true,
      action: (environment) => {
        const element = environment.context.sequences[0].element;
        if (["footnote", "xref", "note_caller"].includes(element.subType)) {
          let paraOb = {
            type: "note",
            marker: element.subType === "footnote" ? "f" : "x",
            content: []
          };
          const target = element.target;
          if (target) {
            environment.workspace.paraStack.push(paraOb);
            environment.context.renderer.renderSequenceId(environment, target);
            let topPara = environment.workspace.paraStack.pop();
            if (element.subType === "note_caller") {
              environment.workspace.paraStack[environment.workspace.paraStack.length - 1].caller = topPara.content[0];
            } else {
              environment.workspace.paraStack[environment.workspace.paraStack.length - 1].content.push(topPara);
            }
          }
        }
      }
    }
  ],
  mark: [
    {
      description: "Output chapter or verses",
      test: () => true,
      action: ({ context, workspace, output }) => {
        const element = context.sequences[0].element;
        if (element.subType === "verses") {
          workspace.paraStack[workspace.paraStack.length - 1].content.push(
            {
              "type": "verse",
              "marker": "v",
              "number": element.atts["number"]
            }
          );
        } else if (element.subType === "chapter") {
          output.usj.content.push(
            {
              "type": "chapter",
              "marker": "c",
              "number": element.atts["number"]
            }
          );
        }
      }
    }
  ],
  startMilestone: [
    {
      description: "Output start milestone",
      test: () => true,
      action: ({ context, workspace }) => {
        let element = context.sequences[0].element;
        const milestoneOb = {
          type: "ms",
          marker: oneifyTag$1(element.subType.split(":")[1]) + "-s"
        };
        if (element.atts) {
          for (const [k, v] of Object.entries(element.atts)) {
            milestoneOb[k] = v.join(",");
          }
        }
        if (workspace.wrapperStack.length > 0) {
          workspace.wrapperStack[workspace.wrapperStack.length - 1].content.push(milestoneOb);
        } else {
          workspace.paraStack[workspace.paraStack.length - 1].content.push(milestoneOb);
        }
      }
    }
  ],
  endMilestone: [
    {
      description: "Output end milestone",
      test: () => true,
      action: ({ context, workspace }) => {
        let element = context.sequences[0].element;
        const milestoneOb = {
          type: "ms",
          marker: oneifyTag$1(element.subType.split(":")[1]) + "-e",
          content: []
        };
        if (workspace.wrapperStack.length > 0) {
          workspace.wrapperStack[workspace.wrapperStack.length - 1].content.push(milestoneOb);
        } else {
          workspace.paraStack[workspace.paraStack.length - 1].content.push(milestoneOb);
        }
      }
    }
  ],
  startWrapper: [
    {
      description: "Push to wrapperStack",
      test: () => true,
      action: ({ workspace, context }) => {
        let element = context.sequences[0].element;
        const wrapperOb = {
          type: "char",
          marker: oneifyTag$1(element.subType.split(":")[1]),
          content: []
        };
        if (element.atts) {
          for (const [k, v] of Object.entries(element.atts)) {
            wrapperOb[k] = v.join(",");
          }
        }
        workspace.wrapperStack.push(wrapperOb);
      }
    }
  ],
  endWrapper: [
    {
      description: "Merge wrapperStack one level down",
      test: () => true,
      action: ({ workspace }) => {
        let topWrapper = workspace.wrapperStack.pop();
        if (workspace.wrapperStack.length === 0) {
          workspace.paraStack[workspace.paraStack.length - 1].content.push(topWrapper);
        } else {
          workspace.wrapperStack[workspace.wrapperStack.length - 1].content.push(topWrapper);
        }
      }
    }
  ],
  text: [
    {
      description: "Output text",
      test: () => true,
      action: ({ context, workspace }) => {
        const text = context.sequences[0].element.text;
        if (workspace.wrapperStack.length > 0) {
          workspace.wrapperStack[workspace.wrapperStack.length - 1].content.push(text);
        } else {
          workspace.paraStack[workspace.paraStack.length - 1].content.push(text);
        }
      }
    }
  ]
};
const initialBlockRecord = (ct) => ({
  type: ct.sequences[0].block.type,
  subType: ct.sequences[0].block.subType,
  pos: ct.sequences[0].block.blockN,
  perfChapter: null
});
const calculateUsfmChapterPositionsActions$1 = {
  startDocument: [
    {
      description: "Set up storage",
      test: () => true,
      action: ({ workspace, output }) => {
        workspace.blockRecords = [];
        output.report = {};
      }
    }
  ],
  startParagraph: [
    {
      description: "Set up block record",
      test: () => true,
      action: ({ context, workspace }) => {
        workspace.blockRecords.push(initialBlockRecord(context));
      }
    }
  ],
  blockGraft: [
    {
      description: "Set up block record",
      test: () => true,
      action: ({ context, workspace }) => {
        workspace.blockRecords.push(initialBlockRecord(context));
      }
    }
  ],
  mark: [
    {
      description: "Add chapter number to block record",
      test: ({ context }) => context.sequences[0].element.subType === "chapter",
      action: ({ context, workspace }) => {
        workspace.blockRecords[workspace.blockRecords.length - 1].perfChapter = context.sequences[0].element.atts["number"];
      }
    }
  ],
  endDocument: [
    {
      description: "Populate report",
      test: () => true,
      action: ({ workspace, output }) => {
        for (const [recordN, record] of Object.entries(
          workspace.blockRecords
        )) {
          if (!record.perfChapter) {
            continue;
          }
          let usfmChapterPos = recordN;
          let found = false;
          while (usfmChapterPos > 0 && !found) {
            if (workspace.blockRecords[usfmChapterPos - 1].type === "paragraph" || workspace.blockRecords[usfmChapterPos - 1].subType === "title") {
              found = true;
            } else {
              usfmChapterPos--;
            }
          }
          output.report[usfmChapterPos.toString()] = record.perfChapter;
        }
      }
    }
  ]
};
const oneifyTag = (t) => {
  if (["toc", "toca", "mt", "imt", "s", "ms", "mte", "sd"].includes(t)) {
    return t + "1";
  }
  return t;
};
const buildMilestone2 = (atts, type2) => {
  let str = `\\${type2}-s |`;
  for (let [key, value] of Object.entries(atts)) {
    if (key === "x-morph") {
      str = str + oneifyTag(key) + '="' + value.join(",") + '" ';
    } else {
      str = str + oneifyTag(key) + '="' + value + '" ';
    }
  }
  return str + "\\*";
};
const buildEndWrapper2 = (atts, type2, isnested = false) => {
  let str = "|";
  for (let [key, value] of Object.entries(atts)) {
    str = str + oneifyTag(key) + '="' + value + '" ';
  }
  str = str + "\\";
  if (isnested) {
    str = str + "+";
  }
  return str + type2 + "*";
};
const perf2UsfmActions = {
  startDocument: [
    {
      description: "Set up environment",
      test: () => true,
      action: ({ context, workspace }) => {
        workspace.usfmBits = [""];
        workspace.nestedWrapper = 0;
        for (let [key, value] of Object.entries(
          context.document.metadata.document
        ).filter(
          (kv) => !["tags", "properties", "bookCode", "cl"].includes(kv[0])
        )) {
          workspace.usfmBits.push(`\\${oneifyTag(key)} ${value}
`);
        }
      }
    }
  ],
  blockGraft: [
    {
      description: "Follow block grafts",
      test: ({ context }) => ["title", "heading", "introduction"].includes(
        context.sequences[0].block.subType
      ),
      action: (environment) => {
        let contextSequence = environment.context.sequences[0];
        let chapterValue = environment.config.report[contextSequence.block.blockN.toString()];
        const target = contextSequence.block.target;
        if (chapterValue && contextSequence.type === "main") {
          environment.workspace.usfmBits.push(`
\\c ${chapterValue}
`);
        }
        if (target) {
          environment.context.renderer.renderSequenceId(environment, target);
        }
      }
    }
  ],
  inlineGraft: [
    {
      description: "Follow inline grafts",
      test: () => true,
      action: (environment) => {
        const target = environment.context.sequences[0].element.target;
        if (target) {
          environment.context.renderer.renderSequenceId(environment, target);
        }
      }
    }
  ],
  startParagraph: [
    {
      description: "Output footnote paragraph tag (footnote)",
      test: ({ context }) => context.sequences[0].block.subType === "usfm:f" && context.sequences[0].type === "footnote" || context.sequences[0].block.subType === "usfm:x" && context.sequences[0].type === "xref",
      action: ({ context, workspace }) => {
        workspace.nestedWrapper = 0;
        let contextSequence = context.sequences[0];
        workspace.usfmBits.push(
          `\\${oneifyTag(contextSequence.block.subType.split(":")[1])} `
        );
      }
    },
    {
      description: "Output footnote note_caller tag (footnote)",
      test: ({ context }) => context.sequences[0].block.subType === "usfm:f" || context.sequences[0].block.subType === "usfm:x",
      action: ({ workspace }) => {
        workspace.nestedWrapper = 0;
      }
    },
    {
      description: "Output paragraph tag (main)",
      test: () => true,
      action: ({ context, workspace, config }) => {
        workspace.nestedWrapper = 0;
        let contextSequence = context.sequences[0];
        let chapterValue = config.report[contextSequence.block.blockN.toString()];
        if (chapterValue && contextSequence.type === "main") {
          workspace.usfmBits.push(`
\\c ${chapterValue}
`);
        }
        workspace.usfmBits.push(
          `
\\${oneifyTag(contextSequence.block.subType.split(":")[1])}
`
        );
      }
    }
  ],
  endParagraph: [
    {
      description: "Output footnote paragraph tag (footnote)",
      test: ({ context }) => context.sequences[0].block.subType === "usfm:f" && context.sequences[0].type === "footnote" || context.sequences[0].block.subType === "usfm:x" && context.sequences[0].type === "xref",
      action: ({ context, workspace }) => {
        let contextSequence = context.sequences[0];
        workspace.usfmBits.push(
          `\\${oneifyTag(contextSequence.block.subType.split(":")[1])}*`
        );
      }
    },
    {
      description: "Output footnote note_caller tag (footnote)",
      test: ({ context }) => context.sequences[0].block.subType === "usfm:f" || context.sequences[0].block.subType === "usfm:x",
      action: () => {
      }
    },
    {
      description: "Output nl",
      test: () => true,
      action: ({ workspace }) => {
        workspace.usfmBits.push(`
`);
      }
    }
  ],
  startMilestone: [
    {
      description: "Output start milestone",
      test: () => true,
      action: ({ context, workspace }) => {
        let contextSequenceElement = context.sequences[0].element;
        let newStartMileStone = buildMilestone2(
          contextSequenceElement.atts,
          oneifyTag(contextSequenceElement.subType.split(":")[1])
        );
        workspace.usfmBits.push(newStartMileStone);
      }
    }
  ],
  endMilestone: [
    {
      description: "Output end milestone",
      test: () => true,
      action: ({ context, workspace }) => {
        workspace.usfmBits.push(
          `\\${oneifyTag(
            context.sequences[0].element.subType.split(":")[1]
          )}-e\\*`
        );
      }
    }
  ],
  text: [
    {
      description: "Output text",
      test: () => true,
      action: ({ context, workspace }) => {
        const text = context.sequences[0].element.text;
        workspace.usfmBits.push(text);
      }
    }
  ],
  mark: [
    {
      description: "Output chapter or verses",
      test: () => true,
      action: ({ context, workspace }) => {
        const element = context.sequences[0].element;
        if (element.subType === "verses") {
          workspace.usfmBits.push(`
\\v ${element.atts["number"]}
`);
        }
      }
    }
  ],
  endSequence: [
    {
      description: "Output \\cl",
      test: ({ context }) => context.document.metadata.document.cl && context.sequences[0].type === "title",
      action: ({ context, workspace }) => {
        workspace.usfmBits.push(
          `
\\cl ${context.document.metadata.document.cl}
`
        );
      }
    }
  ],
  startWrapper: [
    {
      description: "Output start tag",
      test: () => true,
      action: ({ workspace, context }) => {
        let contextSequence = context.sequences[0];
        if (workspace.nestedWrapper > 0) {
          workspace.usfmBits.push(
            `\\+${oneifyTag(contextSequence.element.subType.split(":")[1])} `
          );
        } else {
          workspace.usfmBits.push(
            `\\${oneifyTag(contextSequence.element.subType.split(":")[1])} `
          );
        }
        workspace.nestedWrapper += 1;
      }
    }
  ],
  endWrapper: [
    {
      description: "Output end tag",
      test: ({ context }) => ![
        "fr",
        "fq",
        "fqa",
        "fk",
        "fl",
        "fw",
        "fp",
        "ft",
        "xo",
        "xk",
        "xq",
        "xt",
        "xta"
      ].includes(context.sequences[0].element.subType.split(":")[1]),
      action: ({ workspace, context }) => {
        workspace.nestedWrapper -= 1;
        let contextSequence = context.sequences[0];
        let subType = contextSequence.element.subType.split(":")[1];
        let isNested = workspace.nestedWrapper > 0;
        if (subType === "w") {
          let newEndW = buildEndWrapper2(
            contextSequence.element.atts,
            oneifyTag(subType),
            isNested
          );
          workspace.usfmBits.push(newEndW);
        } else {
          if (isNested) {
            workspace.usfmBits.push(
              `\\+${oneifyTag(contextSequence.element.subType.split(":")[1])}*`
            );
          } else {
            workspace.usfmBits.push(
              `\\${oneifyTag(contextSequence.element.subType.split(":")[1])}*`
            );
          }
        }
      }
    },
    {
      description: "Do NOT output end tag",
      test: () => true,
      action: ({ workspace }) => {
        workspace.nestedWrapper -= 1;
      }
    }
  ],
  endDocument: [
    {
      description: "Build output",
      test: () => true,
      action: ({ workspace, output }) => {
        output.usfm = workspace.usfmBits.join("").replace(/(\s*)\n(\s*)/gm, "\n");
      }
    }
  ]
};
const { addTag, removeTag, validateTags } = utils.tags;
const parserConstantDef = utils.parserConstants;
class Document {
  constructor(processor, docSetId, contentType, contentString, filterOptions, customTags, emptyBlocks, tags2) {
    this.processor = processor;
    this.docSetId = docSetId;
    this.baseSequenceTypes = parserConstantDef.usfm.baseSequenceTypes;
    if (contentType) {
      this.id = utils.generateId();
      this.filterOptions = filterOptions;
      this.customTags = customTags;
      this.emptyBlocks = emptyBlocks;
      this.tags = new Set(tags2 || []);
      validateTags(this.tags);
      this.headers = {};
      this.mainId = null;
      this.sequences = {};
      switch (contentType.toLowerCase()) {
        case "usfm":
        case "sfm":
          this.processUsfm(contentString);
          break;
        case "usx":
          this.processUsx(contentString);
          break;
        case "usj":
          this.processUsj(contentString);
          break;
        case "tsv":
          this.processTSV(contentString);
          break;
        case "nodes":
          this.processNodes(contentString);
          break;
        default:
          throw new Error(`Unknown document contentType '${contentType}'`);
      }
    }
  }
  addTag(tag) {
    addTag(this.tags, tag);
  }
  removeTag(tag) {
    removeTag(this.tags, tag);
  }
  makeParser() {
    return new Parser2(this.filterOptions, this.customTags, this.emptyBlocks);
  }
  processUsfm(usfmString) {
    const parser = this.makeParser();
    parseUsfm(usfmString, parser);
    this.postParseScripture(parser);
  }
  processUsx(usxString) {
    const parser = this.makeParser();
    parseUsx(usxString, parser);
    this.postParseScripture(parser);
  }
  processUsj(usjString) {
    const parser = this.makeParser();
    parseUsj(usjString, parser);
    this.postParseScripture(parser);
  }
  processTSV(tsvString) {
    const parser = this.makeParser();
    const bookCode = `T${this.processor.nextTable > 9 ? this.processor.nextTable : "0" + this.processor.nextTable}`;
    this.processor.nextTable++;
    parseTableToDocument(tsvString, parser, bookCode);
    this.headers = parser.headers;
    this.succinctPass1(parser);
    this.succinctPass2(parser);
    buildChapterVerseIndex(this);
    const tableSequence = Object.values(this.sequences).filter(
      (s) => s.type === "table"
    )[0];
    for (const [colN, colHead] of JSON.parse(tsvString).headings.entries()) {
      tableSequence.tags.add(`col${colN}:${colHead}`);
    }
  }
  processNodes(nodesString) {
    const parser = this.makeParser();
    const bookCode = `N${this.processor.nextNodes > 9 ? this.processor.nextNodes : "0" + this.processor.nextNodes}`;
    this.processor.nextNodes++;
    parseNodes(nodesString, parser, bookCode);
    this.headers = parser.headers;
    this.succinctPass1(parser);
    this.succinctPass2(parser);
    buildChapterVerseIndex(this);
  }
  postParseScripture(parser) {
    parser.tidy();
    const fo = parser.filterOptions;
    this.headers = parser.headers;
    this.succinctPass1(parser);
    this.succinctPass2(parser);
    this.succinctFilter(fo);
    buildChapterVerseIndex(this);
  }
  succinctFilter(filterOptions) {
    succinctFilter(this, filterOptions);
  }
  succinctPass1(parser) {
    const docSet = this.processor.docSets[this.docSetId];
    for (const seq of parser.allSequences()) {
      docSet.recordPreEnum("ids", seq.id);
      this.recordPreEnums(docSet, seq);
    }
    if (docSet.enums.wordLike.length === 0) {
      docSet.sortPreEnums();
    }
    docSet.buildEnums();
  }
  recordPreEnums(docSet, seq) {
    recordPreEnums(docSet, seq);
  }
  rerecordPreEnums(docSet, seq) {
    rerecordPreEnums(docSet, seq);
  }
  succinctPass2(parser) {
    const docSet = this.processor.docSets[this.docSetId];
    this.mainId = parser.sequences.main.id;
    for (const seq of parser.allSequences()) {
      this.sequences[seq.id] = {
        id: seq.id,
        type: seq.type,
        tags: new Set(seq.tags),
        isBaseType: seq.type in parser.baseSequenceTypes,
        blocks: seq.succinctifyBlocks(docSet)
      };
    }
    this.sequences[this.mainId].verseMapping = {};
  }
  modifySequence(seqId, sequenceRewriteFunc, blockFilterFunc, itemFilterFunc, blockRewriteFunc, itemRewriteFunc) {
    modifySequence(
      this,
      seqId,
      sequenceRewriteFunc,
      blockFilterFunc,
      itemFilterFunc,
      blockRewriteFunc,
      itemRewriteFunc
    );
  }
  buildChapterVerseIndex() {
    buildChapterVerseIndex(this);
  }
  chapterVerseIndexes() {
    const ret = {};
    for (const chapN of Object.keys(
      this.sequences[this.mainId].chapterVerses
    )) {
      ret[chapN] = chapterVerseIndex(this, chapN);
    }
    return ret;
  }
  chapterVerseIndex(chapN) {
    return chapterVerseIndex(this, chapN);
  }
  chapterIndexes() {
    const ret = {};
    for (const chapN of Object.keys(this.sequences[this.mainId].chapters)) {
      ret[chapN] = chapterIndex(this, chapN);
    }
    return ret;
  }
  chapterIndex(chapN) {
    return chapterIndex(this, chapN);
  }
  rewriteSequenceBlocks(sequenceId, oldToNew) {
    const sequence = this.sequences[sequenceId];
    for (const block2 of sequence.blocks) {
      this.rewriteSequenceBlock(block2, oldToNew);
    }
  }
  rewriteSequenceBlock(block2, oldToNew) {
    rewriteBlock(block2, oldToNew);
  }
  serializeSuccinct() {
    return serializeSuccinct(this);
  }
  gcSequences() {
    return gcSequences(this);
  }
  newSequence(seqType, tags2) {
    return newSequence(this, seqType, tags2);
  }
  deleteSequence(seqId) {
    return deleteSequence(this, seqId);
  }
  deleteBlock(seqId, blockN, buildCV) {
    return deleteBlock(this, seqId, blockN, buildCV);
  }
  newBlock(seqId, blockN, blockScope, blockGrafts, buildCV) {
    return newBlock(this, seqId, blockN, blockScope, blockGrafts, buildCV);
  }
  perf(indent2) {
    const cl = new dist.PerfRenderFromProskomma({
      proskomma: this.processor,
      actions: dist.render.perfToPerf.renderActions.identityActions
    });
    const output = {};
    cl.renderDocument({
      docId: this.id,
      config: {},
      output
    });
    return indent2 ? JSON.stringify(output.perf, null, indent2) : JSON.stringify(output.perf);
  }
  usfm() {
    const cl = new dist.PerfRenderFromProskomma({
      proskomma: this.processor,
      actions: calculateUsfmChapterPositionsActions$1
    });
    const output = {};
    cl.renderDocument({
      docId: this.id,
      config: {},
      output
    });
    const cl2 = new dist.PerfRenderFromProskomma({
      proskomma: this.processor,
      actions: perf2UsfmActions
    });
    const output2 = {};
    const config2 = { report: output.report };
    try {
      cl2.renderDocument({
        docId: this.id,
        config: config2,
        output: output2
      });
    } catch (err) {
      console.log(err);
      throw err;
    }
    return output2.usfm;
  }
  sofria(indent2, chapter) {
    const cl = new dist.SofriaRenderFromProskomma({
      proskomma: this.processor,
      actions: dist.render.sofriaToSofria.renderActions.identityActions
    });
    const output = {};
    const config = {};
    if (chapter) {
      config.chapters = [`${chapter}`];
    }
    try {
      cl.renderDocument({
        docId: this.id,
        config,
        output
      });
    } catch (err) {
      console.log(err);
      throw err;
    }
    return indent2 ? JSON.stringify(output.sofria, null, indent2) : JSON.stringify(output.sofria);
  }
  usj(indent2) {
    const cl = new dist.PerfRenderFromProskomma({
      proskomma: this.processor,
      actions
    });
    const output = {};
    const config = {};
    try {
      cl.renderDocument({
        docId: this.id,
        config,
        output
      });
    } catch (err) {
      console.log(err);
      throw err;
    }
    return indent2 ? JSON.stringify(output.usj, null, indent2) : JSON.stringify(output.usj);
  }
}
const keyValueSchemaString = `
"""Key/Value tuple"""
type KeyValue {
    """The key"""
    key: String!
    """The value"""
    value: String!
}`;
const keyValueResolvers = {
  key: (root) => root[0],
  value: (root) => root[1]
};
const keyCountSchemaString = `
"""Key/Count tuple"""
type KeyCount {
    """The key"""
    key: String!
    """The number of occurrences"""
    count: Int!
}`;
const keyCountResolvers = {
  key: (root) => root[0],
  count: (root) => root[1]
};
const keyCountCategorySchemaString = `
"""Key/Count/Category tuple"""
type KeyCountCategory {
    """The key"""
    key: String!
    """The number of occurrences"""
    count: Int!
    """The category"""
    category: String!
}`;
const keyCountCategoryResolvers = {
  key: (root) => root[0],
  count: (root) => root[1],
  category: (root) => root[2]
};
const cvSchemaString = `
"""A chapter-verse reference"""
type cv {
  """The chapter number"""
  chapter: Int
  """The verse number"""
  verse: Int
}
`;
const cvResolvers = {
  chapter: (root) => root[0],
  verse: (root) => root[1]
};
const idPartsSchemaString = `
"""Type-dependent parts of the ID header"""
type idParts {
  """The type of the ID"""
  type: String
  """An array of parts of the ID"""
  parts: [String]
  """A part of the ID, by index"""
  part(
    """The numeric index of the part"""
    index: Int!
  ): String
}
`;
const idPartsResolvers = {
  type: (root) => root[0],
  parts: (root) => root[1],
  part: (root, args) => {
    if (!root[1] || args.index < 0 || args.index >= root[1].length) {
      return null;
    }
    return root[1][args.index];
  }
};
const inputAttSpecSchemaString = `
"""Attribute Specification"""
input AttSpec {
"""The type of attribute, ie what type of thing it's connected to"""
attType: String!
"""The name of the USFM tag to which the attribute is connected"""
tagName: String!
"""The attribute key (ie the bit to the left of the equals sign in USX)"""
attKey: String!
"""The position of the value (which is 0 except for attributes with multiple values)"""
valueN: Int!
}`;
const keyMatchesSchemaString = `
"""Key/Regex tuple"""
input KeyMatches {
  """The key"""
  key: String!
  """The regex to match"""
  matches: String!
}
`;
const inputKeyValueSchemaString = `
"""Input Key/Value Object"""
input InputKeyValue {
    """The key"""
    key: String!
    """The value"""
    value: String!
}
`;
const keyValuesSchemaString = `
"""Input Key/Values Object"""
input KeyValues {
    """The key"""
    key: String!
    """The values"""
    values: [String!]!
}
`;
const inputItemObjectSchemaString = `
"""Item for arguments"""
input InputItemObject {
    """The basic item type (token, scope or graft)'"""
    type: String!
    """The type-dependent subtype of the item"""
    subType: String!
    """The content of the item (the text for tokens, the label for scopes and the sequence id for grafts)"""
    payload: String!
}`;
const scopeMatchesStartsWith$2 = (sw, s) => {
  if (sw.length === 0) {
    return true;
  }
  for (const swv of sw) {
    if (s.startsWith(swv)) {
      return true;
    }
  }
  return false;
};
const itemSchemaString = `
"""Item"""
type Item {
  """The basic item type (token, scope or graft)"""
  type: String!
  """The type-dependent subtype of the item"""
  subType: String!
  """The content of the item (the text for tokens, the label for scopes and the sequence id for grafts)"""
  payload(
    """If true, turn all whitespace into a normal space"""
    normalizeSpace: Boolean
    """A whitelist of characters to include"""
    includeChars: [String!]
    """A blacklist of characters to exclude"""
    excludeChars: [String!],
  ): String!
  """If 'includeContext' was selected, and for tokens, the index of the token from the start of the sequence"""
  position(
    """Only include scopes that begin with this value"""
    startsWith: [String!]
  ): Int
  """If 'includeContext' was selected, a list of scopes that are open around the item"""
  scopes(
    """Only include scopes that begin with this value"""
    startsWith: [String!]
  ): [String!]
}
`;
const itemResolvers = {
  type: (root) => root[0],
  subType: (root) => root[1],
  payload: (root, args) => {
    let ret = root[2];
    if (root[0] === "token") {
      if (args.normalizeSpace) {
        ret = root[2].replace(/[ \t\n\r]+/g, " ");
      }
      if (args.includeChars || args.excludeChars) {
        let retArray = ret.split("");
        retArray = retArray.filter(
          (c) => !args.includeChars || args.includeChars.includes(c)
        );
        retArray = retArray.filter(
          (c) => !args.excludeChars || !args.excludeChars.includes(c)
        );
        ret = retArray.join("");
      }
    }
    return ret;
  },
  position: (root) => root[3],
  scopes: (root, args) => root[4] ? root[4].filter(
    (s) => !args.startsWith || scopeMatchesStartsWith$2(args.startsWith, s)
  ) : []
};
const dumpItem = (i) => {
  let wrapper;
  switch (i[0]) {
    case "token":
      return `|${i[2]}`;
    case "scope":
      wrapper = i[1] === "start" ? "+" : "-";
      return `${wrapper}${i[2]}${wrapper}`;
    case "graft":
      return `>${i[1]}<`;
  }
};
const dumpItems = (il) => il.map((bci) => dumpItem(bci)).join("");
const dumpItemGroup = (ig) => {
  const ret = ["ItemGroup:"];
  ret.push(`   Open Scopes ${ig[0].join(", ")}`);
  ret.push(`   ${dumpItems(ig[1])}`);
  return ret.join("\n");
};
const dumpBlock = (b) => {
  const ret = ["Block:"];
  if (b.bg.length > 0) {
    b.bg.forEach((bbg) => ret.push(`   ${bbg[1]} graft to ${bbg[2]}`));
  }
  ret.push(`   Scope ${b.bs[2]}`);
  ret.push(`   ${dumpItems(b.c)}`);
  return ret.join("\n");
};
const scopeMatchesStartsWith$1 = (sw, s) => {
  if (sw.length === 0) {
    return true;
  }
  for (const swv of sw) {
    if (s.startsWith(swv)) {
      return true;
    }
  }
  return false;
};
const itemGroupSchemaString = `
"""A collection of items, with scope context"""
type ItemGroup {
  """Items for this itemGroup"""
  items: [Item!]!
  """Tokens for this itemGroup"""
  tokens(
    """Return tokens whose payload is an exact match to one of the specified strings"""
    withChars: [String!]
    """Return tokens with one of the specified subTypes"""
    withSubTypes: [String!]
  ): [Item!]!
  """The text of the itemGroup as a single string"""
  text(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): String!
  """The labels of scopes that were open at the beginning of the itemGroup"""
  scopeLabels(
    """Only include scopes that begin with this value"""
    startsWith: [String!]
  ): [String!]!
  """The itemGroup content as a string in a compact eyeballable format"""
  dump: String!
  """A list of scopes from the items of the itemGroup"""
  includedScopes: [String!]!
} 
`;
const itemGroupResolvers = {
  items: (root) => root[1],
  tokens: (root, args) => root[1].filter(
    (i) => i[0] === "token" && (!args.withChars || args.withChars.includes(i[2])) && (!args.withSubTypes || args.withSubTypes.includes(i[1]))
  ),
  text: (root, args) => {
    const tokensText = root[1].filter((i) => i[0] === "token").map((t) => t[2]).join("");
    return args.normalizeSpace ? tokensText.replace(/[ \t\n\r]+/g, " ") : tokensText;
  },
  scopeLabels: (root, args) => root[0].filter(
    (s) => !args.startsWith || scopeMatchesStartsWith$1(args.startsWith, s)
  ),
  dump: (root) => dumpItemGroup(root),
  includedScopes: (root) => Array.from(
    new Set(
      root[1].filter((i) => i[0] === "scope" && i[1] === "start").map((t) => t[2])
    )
  )
};
const kvEntrySchemaString = `
"""Key/Items tuple"""
type kvEntry {
    """The key"""
    key: String!
    """The secondary keys"""
    secondaryKeys: [KeyValue!]
    """The fields as itemGroups"""
    itemGroups: [ItemGroup]!
}`;
const kvEntryResolvers = {
  key: (root) => root[0],
  secondaryKeys: (root) => root[1],
  itemGroups: (root) => root[2]
};
const regexIndexSchemaString = `
"""Information about a regex match on an enum"""
type regexIndex {
    """The index in the enum"""
    index: String!
    """The string in the enum that matched"""
    matched: String!
}`;
const regexIndexResolvers = {
  index: (root) => root[0],
  matched: (root) => root[1]
};
const rowEqualsSpecSchemaString = `
"""Row Equals Specification"""
input rowEqualsSpec {
  """The position of the column in which to search a match"""
  colN: Int!
  """The values to match"""
  values: [String!]!
}
`;
const rowMatchSpecSchemaString = `
"""Row Match Specification"""
input rowMatchSpec {
  """The position of the column in which to search a match"""
  colN: Int!
  """The regex to match"""
  matching: String!
}
`;
const verseRangeSchemaString = `
"""Information about a verse range (which may only cover one verse)"""
type verseRange {
  """The range, as it would be printed in a Bible"""
  range: String!
  """A list of verse numbers for this range"""
  numbers: [Int!]!
}
`;
const origSchemaString = `
"""Mapped verse information"""
type orig {
  """The book code"""
  book: String
  """A list of chapter-verse references"""
  cvs: [cv!]!
}
`;
const verseNumberSchemaString = `
"""Information about a verse number (which may be part of a verse range)"""
type verseNumber {
  """The verse number"""
  number: Int!
  """The verse range to which the verse number belongs"""
  range: String!
  """The reference for this verse when mapped to 'original' versification"""
  orig: orig!
}
`;
const verseNumberResolvers = {
  orig: (root, args, context) => {
    const localBook = context.doc.headers.bookCode;
    const localChapter = context.cvIndex[0];
    const localVerse = root.number;
    const mainSequence = context.doc.sequences[context.doc.mainId];
    if (mainSequence.verseMapping && "forward" in mainSequence.verseMapping && `${localChapter}` in mainSequence.verseMapping.forward) {
      const mapping = utils.versification.mapVerse(
        mainSequence.verseMapping.forward[`${localChapter}`],
        localBook,
        localChapter,
        localVerse
      );
      return {
        book: mapping[0],
        cvs: mapping[1]
      };
    } else {
      return {
        book: localBook,
        cvs: [[localChapter, localVerse]]
      };
    }
  }
};
const cellSchemaString = `
"""A table cell"""
type cell {
  """The row numbers"""
  rows: [Int!]!
  """The column numbers"""
  columns: [Int!]!
  """A list of items from the c (content) field of the cell"""
  items: [Item!]!
  """A list of tokens from the c (content) field of the cell"""
  tokens: [Item!]!
  """The text of the cell as a single string"""
  text(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): String!
}
`;
const cellResolvers = {
  rows: (root) => root[0],
  columns: (root) => root[1],
  items: (root) => root[2],
  tokens: (root) => root[2].filter((i) => i[0] === "token"),
  text: (root, args) => {
    let ret = root[2].filter((i) => i[0] === "token").map((t) => t[2]).join("").trim();
    if (args.normalizeSpace) {
      ret = ret.replace(/[ \t\n\r]+/g, " ");
    }
    return ret;
  }
};
const cIndexSchemaString = `
"""A chapter index entry"""
type cIndex {
  """The chapter number"""
  chapter: Int!
  """The zero-indexed number of the block where the chapter starts"""
  startBlock: Int
  """The zero-indexed number of the block where the chapter ends"""
  endBlock: Int
  """The zero-indexed position of the item where the chapter starts"""
  startItem: Int
  """The zero-indexed position of the item where the chapter ends"""
  endItem: Int
  """The value of nextToken at the beginning of the chapter"""
  nextToken: Int
  """A list of items for this chapter"""
  items(
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
  ): [Item]!
  """The items as a string in a compact eyeballable format"""
  dumpItems: String
  """A list of tokens for this chapter"""
  tokens(
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
    """Return tokens whose payload is an exact match to one of the specified strings"""
    withChars: [String!]
    """Return tokens with one of the specified subTypes"""
    withSubTypes: [String!]
  ): [Item]!
  """The text of the chapter as a single string"""
  text(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): String!
}
`;
const cIndexResolvers = {
  chapter: (root) => root[0],
  startBlock: (root) => root[1].startBlock,
  endBlock: (root) => root[1].endBlock,
  startItem: (root) => root[1].startItem,
  endItem: (root) => root[1].endItem,
  nextToken: (root) => root[1].nextToken,
  items: (root, args, context) => context.docSet.itemsByIndex(
    context.doc.sequences[context.doc.mainId],
    root[1],
    args.includeContext
  ).reduce((a, b) => a.concat([["token", "lineSpace", " "]].concat(b)), []),
  dumpItems: (root, args, context) => {
    const items2 = context.docSet.itemsByIndex(
      context.doc.sequences[context.doc.mainId],
      root[1],
      false
    );
    if (items2.length > 0) {
      return dumpItems(
        items2.reduce(
          (a, b) => a.concat([["token", "lineSpace", " ", null]].concat(b))
        )
      );
    } else {
      return "";
    }
  },
  tokens: (root, args, context) => context.docSet.itemsByIndex(
    context.doc.sequences[context.doc.mainId],
    root[1],
    args.includeContext
  ).reduce((a, b) => a.concat([["token", "lineSpace", " "]].concat(b)), []).filter(
    (i) => i[0] === "token" && (!args.withChars || args.withChars.includes(i[2])) && (!args.withSubTypes || args.withSubTypes.includes(i[1]))
  ),
  text: (root, args, context) => {
    let ret = context.docSet.itemsByIndex(context.doc.sequences[context.doc.mainId], root[1]).reduce((a, b) => a.concat([["token", "lineSpace", " "]].concat(b)), []).filter((i) => i[0] === "token").map((t) => t[1] === "lineSpace" ? " " : t[2]).join("").trim();
    if (args.normalizeSpace) {
      ret = ret.replace(/[ \t\n\r]+/g, " ");
    }
    return ret;
  }
};
const cvVerseElementSchemaString = `
""""""
type cvVerseElement {
  """The zero-indexed number of the block where the verse starts"""
  startBlock: Int
  """The zero-indexed number of the block where the verse ends"""
  endBlock: Int
  """The zero-indexed position of the item where the verse starts"""
  startItem: Int
  """The zero-indexed position of the item where the verse ends"""
  endItem: Int
  """The value of nextToken at the beginning of the verse"""
  nextToken: Int
  """The verse range for this verse as it would be printed in a Bible"""
  verseRange: String
  """A list of items for this verse"""
  items(
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
  ): [Item]!
  """The items as a string in a compact eyeballable format"""
  dumpItems: String
  """A list of tokens for this verse"""
  tokens(
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
    """Return tokens whose payload is an exact match to one of the specified strings"""
    withChars: [String!]
    """Return tokens with one of the specified subTypes"""
    withSubTypes: [String!]
  ): [Item]!
  """The text of the verse as a single string"""
  text(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): String!
}
`;
const cvVerseElementResolvers = {
  startBlock: (root) => root.startBlock,
  endBlock: (root) => root.endBlock,
  startItem: (root) => root.startItem,
  endItem: (root) => root.endItem,
  nextToken: (root) => root.nextToken,
  verseRange: (root) => root.verses,
  items: (root, args, context) => context.docSet.itemsByIndex(
    context.doc.sequences[context.doc.mainId],
    root,
    args.includeContext
  ).reduce(
    (a, b) => a.concat([["token", "lineSpace", " ", null]].concat(b))
  ),
  dumpItems: (root, args, context) => dumpItems(
    context.docSet.itemsByIndex(
      context.doc.sequences[context.doc.mainId],
      root,
      args.includeContext
    ).reduce(
      (a, b) => a.concat([["token", "lineSpace", " ", null]].concat(b))
    )
  ),
  tokens: (root, args, context) => context.docSet.itemsByIndex(
    context.doc.sequences[context.doc.mainId],
    root,
    args.includeContext
  ).reduce((a, b) => a.concat([["token", "lineSpace", " ", null]].concat(b))).filter(
    (i) => i[0] === "token" && (!args.withChars || args.withChars.includes(i[2])) && (!args.withSubTypes || args.withSubTypes.includes(i[1]))
  ),
  text: (root, args, context) => {
    let ret = context.docSet.itemsByIndex(context.doc.sequences[context.doc.mainId], root).reduce((a, b) => a.concat([["token", "lineSpace", " ", null]].concat(b))).filter((i) => i[0] === "token").map((t) => t[1] === "lineSpace" ? " " : t[2]).join("").trim();
    if (args.normalizeSpace) {
      ret = ret.replace(/[ \t\n\r]+/g, " ");
    }
    return ret;
  }
};
const cvVersesSchemaString = `
"""Information about a verse in the chapter, which may be split into several pieces"""
type cvVerses {
  """The pieces of verse"""
  verse: [cvVerseElement]
}
`;
const cvVersesResolvers = { verse: (root) => root };
const cvIndexSchemaString = `
"""A chapterVerse index entry"""
type cvIndex {
  """The chapter number"""
  chapter: Int!
  """Information about the verses in the chapter"""
  verses: [cvVerses]
  """A list of verse number and range information, organized by verse number"""
  verseNumbers: [verseNumber!]
  """A list of verse number and range information, organized by verse range"""
  verseRanges: [verseRange!]
}
`;
const cvIndexResolvers = {
  chapter: (root) => root[0],
  verses: (root) => root[1],
  verseNumbers: (root, args, context) => {
    context.cvIndex = root;
    return [...root[1].entries()].filter((v) => v[1].length > 0).map((v) => ({
      number: v[0],
      range: v[1][v[1].length - 1].verses
    }));
  },
  verseRanges: (root) => {
    const ret = [];
    for (const [vn, vo] of [...root[1].entries()].filter(
      (v) => v[1].length > 0
    )) {
      if (ret.length === 0 || ret[ret.length - 1].range !== vo[vo.length - 1].verses) {
        ret.push({
          range: vo[vo.length - 1].verses,
          numbers: [vn]
        });
      } else {
        ret[ret.length - 1].numbers.push(vn);
      }
    }
    return ret;
  }
};
const nv = (root, newVerseRange) => {
  const chapterN = parseInt(root[0]);
  const verseN = parseInt(root[1]);
  if (root[3].length <= verseN || root[3][verseN].length === 0) {
    return null;
  }
  let ret = null;
  let nc = chapterN;
  let nv2 = verseN;
  let index = root[3];
  let startVerseRange = index[verseN][0].verses;
  let onNextChapter = false;
  while (!ret) {
    nv2 += 1;
    if (nv2 >= index.length) {
      if (onNextChapter || !root[4]) {
        break;
      }
      nv2 = -1;
      nc += 1;
      index = root[4];
      onNextChapter = true;
    } else if (index[nv2].length > 0 && (!newVerseRange || onNextChapter || index[nv2][0].verses !== startVerseRange)) {
      ret = [nc, nv2];
    }
  }
  return ret;
};
const pv = (root, newVerseRange) => {
  const chapterN = parseInt(root[0]);
  const verseN = parseInt(root[1]);
  if (root[3].length <= verseN || root[3][verseN].length === 0) {
    return null;
  }
  let ret = null;
  let nc = chapterN;
  let nv2 = verseN;
  let index = root[3];
  let startVerseRange = index[verseN][0].verses;
  let onPreviousChapter = false;
  while (!ret) {
    nv2 -= 1;
    if (nv2 < 0) {
      if (onPreviousChapter || !root[2]) {
        break;
      }
      nv2 = root[2].length;
      nc -= 1;
      index = root[2];
      onPreviousChapter = true;
    } else if (index[nv2].length > 0 && (!newVerseRange || onPreviousChapter || index[nv2][0].verses !== startVerseRange)) {
      ret = [nc, nv2];
    }
  }
  return ret;
};
const cvNavigationSchemaString = `
"""Various answers to 'previous' and 'next' with respect to a verse"""
type cvNavigation {
  """The verse number for the next verse"""
  nextVerse: cv
  """The verse number for the previous verse"""
  previousVerse: cv
  """The verse number for the next verse range"""
  nextVerseRangeVerse: cv
  """The verse number for the previous verse range"""
  previousVerseRangeVerse: cv
  """The next chapter number (as a string)"""
  nextChapter: String
  """The previous chapter number (as a string)"""
  previousChapter: String
}
`;
const cvNavigationResolvers = {
  nextVerse: (root) => nv(root, false),
  previousVerse: (root) => pv(root, false),
  nextVerseRangeVerse: (root) => nv(root, true),
  previousVerseRangeVerse: (root) => pv(root, true),
  nextChapter: (root) => {
    if (root[3].length > 0 && root[4].length > 0) {
      return (parseInt(root[0]) + 1).toString();
    } else {
      return null;
    }
  },
  previousChapter: (root) => {
    if (root[2].length > 0 && root[3].length > 0) {
      return (parseInt(root[0]) - 1).toString();
    } else {
      return null;
    }
  }
};
const inputBlockSpecSchemaString = `
"""A specification to create or update a block"""
input inputBlockSpec {
  """The block scope as an item"""
  bs: InputItemObject!
  """The block grafts as items"""
  bg: [InputItemObject!]!
  """The open scopes as items"""
  os: [InputItemObject!]!
  """The included scopes as items"""
  is: [InputItemObject!]!
  """The items"""
  items: [InputItemObject!]!
}
`;
const nodeSchemaString = `
"""A tree node"""
type node {
  """The node id"""
  id: String!
  """The node parent id"""
  parentId: String
  """The keys for content"""
  keys: [String!]!
  """The content as itemGroups"""
  itemGroups(
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
  ): [ItemGroup!]!
  """The node children ids"""
  childIds: [String!]!
}
`;
const nodeResolvers = {
  id: (root, args, context) => {
    const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
      root.bs,
      0
    );
    return context.docSet.unsuccinctifyScope(root.bs, itemType, itemSubtype, 0)[2].split("/")[1];
  },
  parentId: (root, args, context) => {
    const parentId = context.docSet.unsuccinctifyScopes(root.is).filter((s) => s[2].startsWith("tTreeParent"))[0][2].split("/")[1];
    return parentId === "none" ? null : parentId;
  },
  keys: (root, args, context) => context.docSet.unsuccinctifyScopes(root.is).filter((s) => s[2].startsWith("tTreeContent")).map((s) => s[2].split("/")[1]),
  itemGroups: (root, args, context) => context.docSet.sequenceItemsByScopes(
    [root],
    ["tTreeContent/"],
    args.includeContext || false
  ),
  childIds: (root, args, context) => context.docSet.unsuccinctifyScopes(root.is).filter((s) => s[2].startsWith("tTreeChild")).map((s) => s[2].split("/")[2])
};
const kvSequenceSchemaString = `
"""A contiguous flow of content for key-values"""
type kvSequence {
  """The id of the sequence"""
  id: String!
  """The number of entries in the key-value sequence"""
  nEntries: Int!
  """The entries in the key-value sequence"""
  entries(
    """Only return entries whose key matches the specification"""
    keyMatches: String
    """Only return entries whose key equals one of the values in the specification"""
    keyEquals: [String!]
    """Only return entries whose secondary keys match the specification"""
    secondaryMatches: [KeyMatches!]
    """Only return entries whose secondary keys equal one of the values in the specification"""
    secondaryEquals: [KeyValues!]
    """Only return entries whose content matches the specification"""
    contentMatches: [KeyMatches!]
    """Only return entries whose content equals one of the values in the specification"""
    contentEquals: [KeyValues!]
  ): [kvEntry!]
  """A list of the tags of this sequence"""
  tags: [String!]!
  """A list of the tags of this sequence as key/value tuples"""
  tagsKv: [KeyValue!]!
  """Whether or not the sequence has the specified tag"""
  hasTag(
    """The tag name"""
    tagName: String
  ): Boolean!
}
`;
const kvSequenceResolvers = {
  nEntries: (root) => root.blocks.length,
  entries: (root, args, context) => {
    let ret = root.blocks.map((b) => [
      context.docSet.unsuccinctifyScopes(b.bs).map((s) => s[2].split("/")[1])[0],
      context.docSet.unsuccinctifyScopes(b.is).filter((s) => s[2].startsWith("kvSecondary/")).map((s) => [s[2].split("/")[1], s[2].split("/")[2]]),
      context.docSet.sequenceItemsByScopes([b], ["kvField/"], false)
    ]);
    if (args.keyMatches) {
      ret = ret.filter((e) => XRegExp.test(e[0], XRegExp(args.keyMatches)));
    }
    if (args.keyEquals) {
      ret = ret.filter((e) => args.keyEquals.includes(e[0]));
    }
    if (args.secondaryMatches) {
      const matchesOb = {};
      args.secondaryMatches.forEach((sm) => matchesOb[sm.key] = sm.matches);
      ret = ret.filter((e) => {
        const secondaryOb = {};
        e[1].forEach((st) => secondaryOb[st[0]] = st[1]);
        for (const mo of Object.entries(matchesOb)) {
          const secondaryString = secondaryOb[mo[0]];
          if (!secondaryString || !XRegExp.test(secondaryString, XRegExp(mo[1]))) {
            return false;
          }
        }
        return true;
      });
    }
    if (args.secondaryEquals) {
      const equalsOb = {};
      args.secondaryEquals.forEach((sm) => equalsOb[sm.key] = sm.values);
      ret = ret.filter((e) => {
        const secondaryOb = {};
        e[1].forEach((st) => secondaryOb[st[0]] = st[1]);
        for (const mo of Object.entries(equalsOb)) {
          const secondaryString = secondaryOb[mo[0]];
          if (!secondaryString || !mo[1].includes(secondaryString)) {
            return false;
          }
        }
        return true;
      });
    }
    if (args.contentMatches) {
      const matchesOb = {};
      args.contentMatches.forEach((sm) => matchesOb[sm.key] = sm.matches);
      ret = ret.filter((e) => {
        const contentOb = {};
        e[2].forEach(
          (st) => contentOb[st[0].filter((s) => s.startsWith("kvField"))[0].split("/")[1]] = st[1].filter((i) => i[0] === "token").map((t) => t[2]).join("")
        );
        for (const mo of Object.entries(matchesOb)) {
          const contentString = contentOb[mo[0]];
          if (!contentString || !XRegExp.test(contentString, XRegExp(mo[1]))) {
            return false;
          }
        }
        return true;
      });
    }
    if (args.contentEquals) {
      const equalsOb = {};
      args.contentEquals.forEach((sm) => equalsOb[sm.key] = sm.values);
      ret = ret.filter((e) => {
        const contentOb = {};
        e[2].forEach(
          (st) => contentOb[st[0].filter((s) => s.startsWith("kvField"))[0].split("/")[1]] = st[1].filter((i) => i[0] === "token").map((t) => t[2]).join("")
        );
        for (const mo of Object.entries(equalsOb)) {
          const contentString = contentOb[mo[0]];
          if (!contentString || !contentString.includes(mo[1])) {
            return false;
          }
        }
        return true;
      });
    }
    return ret;
  },
  tags: (root) => Array.from(root.tags),
  tagsKv: (root) => Array.from(root.tags).map((t) => {
    if (t.includes(":")) {
      return [
        t.substring(0, t.indexOf(":")),
        t.substring(t.indexOf(":") + 1)
      ];
    } else {
      return [t, ""];
    }
  }),
  hasTag: (root, args) => root.tags.has(args.tagName)
};
const tableSequenceSchemaString = `
"""A contiguous flow of content for a table"""
type tableSequence {
  """The id of the sequence"""
  id: String!
  """The number of cells in the table sequence"""
  nCells: Int!
  """The number of rows in the table sequence"""
  nRows: Int!
  """The number of columns in the table sequence"""
  nColumns: Int!
  """The cells in the table sequence"""
  cells: [cell!]!
  """The rows in the table sequence"""
  rows(
    """Only return rows whose zero-indexed position is in the list"""
    positions: [Int!]
    """Only return columns whose zero-indexed position is in the list"""
    columns: [Int!]
    """Only return rows whose cells match the specification"""
    matches: [rowMatchSpec!]
    """'Only return rows whose cells contain one of the values in the specification"""
    equals: [rowEqualsSpec!]
  ): [[cell!]!]!
  """A list of the tags of this sequence"""
  tags: [String!]!
  """A list of the tags of this sequence as key/value tuples"""
  tagsKv: [KeyValue!]!
  """Whether or not the sequence has the specified tag"""
  hasTag(
    """The tag name"""
    tagName: String
  ): Boolean!
  """A list of column headings for this tableSequence, derived from the sequence tags"""
  headings: [String!]!
}
`;
const tableSequenceResolvers = {
  nCells: (root) => root.blocks.length,
  nRows: (root, args, context) => {
    const rowNs = /* @__PURE__ */ new Set([]);
    for (const block2 of root.blocks) {
      const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
        block2.bs,
        0
      );
      const bsPayload = context.docSet.unsuccinctifyScope(
        block2.bs,
        itemType,
        itemSubtype,
        0
      )[2];
      rowNs.add(bsPayload.split("/")[1]);
    }
    return rowNs.size;
  },
  nColumns: (root, args, context) => {
    const columnNs = /* @__PURE__ */ new Set([]);
    for (const block2 of root.blocks) {
      for (const scope2 of context.docSet.unsuccinctifyScopes(block2.is).map((s) => s[2])) {
        if (scope2.startsWith("tTableCol")) {
          columnNs.add(scope2.split("/")[1]);
        }
      }
    }
    return columnNs.size;
  },
  cells: (root, args, context) => {
    const ret = [];
    for (const block2 of root.blocks) {
      ret.push([
        context.docSet.unsuccinctifyScopes(block2.bs).map((s) => parseInt(s[2].split("/")[1])),
        Array.from(
          new Set(
            context.docSet.unsuccinctifyScopes(block2.is).filter((s) => s[2].startsWith("tTableCol")).map((s) => parseInt(s[2].split("/")[1]))
          )
        ),
        context.docSet.unsuccinctifyItems(block2.c, {}, 0)
      ]);
    }
    return ret;
  },
  rows: (root, args, context) => {
    const rowMatches1 = (row2, matchSpec) => {
      if (row2[matchSpec.colN] === void 0) {
        return false;
      }
      const matchCellText = row2[matchSpec.colN][2].filter((i) => i[0] === "token").map((i) => i[2]).join("");
      return XRegExp.test(matchCellText, XRegExp(matchSpec.matching));
    };
    const rowMatches = (row2, matchSpecs) => {
      if (matchSpecs.length === 0) {
        return true;
      }
      if (rowMatches1(row2, matchSpecs[0])) {
        return rowMatches(row2, matchSpecs.slice(1));
      }
      return false;
    };
    const rowEquals1 = (row2, matchSpec) => {
      if (row2[matchSpec.colN] === void 0) {
        return false;
      }
      const matchCellText = row2[matchSpec.colN][2].filter((i) => i[0] === "token").map((i) => i[2]).join("");
      return matchSpec.values.includes(matchCellText);
    };
    const rowEquals = (row2, matchSpecs) => {
      if (matchSpecs.length === 0) {
        return true;
      }
      if (rowEquals1(row2, matchSpecs[0])) {
        return rowEquals(row2, matchSpecs.slice(1));
      }
      return false;
    };
    let ret = [];
    let row = -1;
    for (const block2 of root.blocks) {
      const rows = context.docSet.unsuccinctifyScopes(block2.bs).map((s) => parseInt(s[2].split("/")[1]));
      if (args.positions && !args.positions.includes(rows[0])) {
        continue;
      }
      if (rows[0] !== row) {
        ret.push([]);
        row = rows[0];
      }
      ret[ret.length - 1].push([
        rows,
        Array.from(
          new Set(
            context.docSet.unsuccinctifyScopes(block2.is).filter((s) => s[2].startsWith("tTableCol")).map((s) => parseInt(s[2].split("/")[1]))
          )
        ),
        context.docSet.unsuccinctifyItems(block2.c, {}, 0)
      ]);
    }
    if (args.matches) {
      ret = ret.filter((row2) => rowMatches(row2, args.matches));
    }
    if (args.equals) {
      ret = ret.filter((row2) => rowEquals(row2, args.equals));
    }
    if (args.columns) {
      ret = ret.map(
        (row2) => [...row2.entries()].filter((re2) => args.columns.includes(re2[0])).map((re2) => re2[1])
      );
    }
    return ret;
  },
  tags: (root) => Array.from(root.tags),
  tagsKv: (root) => Array.from(root.tags).map((t) => {
    if (t.includes(":")) {
      return [
        t.substring(0, t.indexOf(":")),
        t.substring(t.indexOf(":") + 1)
      ];
    } else {
      return [t, ""];
    }
  }),
  hasTag: (root, args) => root.tags.has(args.tagName),
  headings: (root) => Array.from(root.tags).filter((t) => t.startsWith("col")).sort(
    (a, b) => parseInt(a.split(":")[0].substring(3)) - parseInt(b.split(":")[0].substring(3))
  ).map((t) => t.split(":")[1])
};
const aggregateFunctions = {
  equals: (docSet, node, a, b) => a === b,
  notEqual: (docSet, node, a, b) => a !== b,
  and: (docSet, node, ...args) => args.filter((a) => !a).length === 0,
  or: (docSet, node, ...args) => args.filter((a) => a).length > 0,
  not: (docSet, node, a) => !a,
  idRef: (docSet, node) => docSet.unsuccinctifyScopes(node.bs)[0][2].split("/")[1],
  parentIdRef: (docSet, node) => docSet.unsuccinctifyScopes(node.is).filter((s) => s[2].startsWith("tTreeParent"))[0][2].split("/")[1],
  nChildren: (docSet, node) => docSet.unsuccinctifyScopes(node.is).filter((s) => s[2].startsWith("tTreeChild")).length,
  contentRef: (docSet, node, label) => {
    const labelIG = docSet.sequenceItemsByScopes([node], ["tTreeContent/"], false).filter((ig) => {
      const key = ig[0].filter((s) => s.startsWith("tTreeContent"))[0].split("/")[1];
      return key === label;
    });
    return labelIG[0] ? labelIG[0][1].filter((i) => i[0] === "token").map((t) => t[2]).join("") : "";
  },
  hasContent: (docSet, node, label) => {
    const labelIG = docSet.sequenceItemsByScopes([node], ["tTreeContent/"], false).filter((ig) => {
      const key = ig[0].filter((s) => s.startsWith("tTreeContent"))[0].split("/")[1];
      return key === label;
    });
    return labelIG.length > 0;
  },
  concat: (docSet, node, ...args) => args.join(""),
  startsWith: (docSet, node, a, b) => a.startsWith(b),
  endsWith: (docSet, node, a, b) => a.endsWith(b),
  contains: (docSet, node, a, b) => a.includes(b),
  matches: (docSet, node, a, b) => XRegExp.test(a, XRegExp(b)),
  int: (docSet, node, str) => parseInt(str),
  string: (docSet, node, int) => `${int}`,
  left: (docSet, node, str, int) => str.substring(0, int),
  right: (docSet, node, str, int) => str.substring(str.length - int),
  length: (docSet, node, str) => str.length,
  indexOf: (docSet, node, a, b) => a.indexOf(b),
  add: (docSet, node, ...args) => args.reduce((x, y) => x + y),
  mul: (docSet, node, ...args) => args.reduce((x, y) => x * y),
  sub: (docSet, node, a, b) => a - b,
  div: (docSet, node, a, b) => Math.floor(a / b),
  mod: (docSet, node, a, b) => a % b,
  gt: (docSet, node, a, b) => a > b,
  lt: (docSet, node, a, b) => a < b,
  ge: (docSet, node, a, b) => a >= b,
  le: (docSet, node, a, b) => a <= b
};
const parseFunctions = {
  quotedString: (str) => str.substring(1, str.length - 1),
  int: (str) => parseInt(str),
  true: () => true,
  false: () => false
};
const splitArgs = (str) => {
  const ret = [[]];
  let pos = 0;
  let nParen = 0;
  let inQuote = false;
  while (str && pos < str.length) {
    switch (str[pos]) {
      case "\\":
        ret[ret.length - 1].push(str[pos]);
        if (str[pos + 1] === "'") {
          ret[ret.length - 1].push(str[pos + 1]);
          pos++;
        }
        break;
      case "'":
        ret[ret.length - 1].push(str[pos]);
        inQuote = !inQuote;
        break;
      case "(":
        if (inQuote) {
          ret[ret.length - 1].push(str[pos]);
        } else {
          ret[ret.length - 1].push(str[pos]);
          nParen++;
        }
        break;
      case ")":
        if (inQuote) {
          ret[ret.length - 1].push(str[pos]);
        } else {
          ret[ret.length - 1].push(str[pos]);
          nParen--;
        }
        break;
      case ",":
        if (!inQuote && nParen === 0) {
          ret.push([]);
          while (str[pos + 1] === " ") {
            pos++;
          }
        } else {
          ret[ret.length - 1].push(str[pos]);
        }
        break;
      default:
        ret[ret.length - 1].push(str[pos]);
    }
    pos++;
  }
  return ret.map((e) => e.join(""));
};
const expressions = {
  expression: {
    oneOf: ["stringExpression", "intExpression", "booleanExpression"]
  },
  booleanExpression: {
    oneOf: [
      "booleanPrimitive",
      "equals",
      "notEqual",
      "and",
      "or",
      "not",
      "contains",
      "startsWith",
      "endsWith",
      "matches",
      "gt",
      "lt",
      "ge",
      "le",
      "hasContent"
    ]
  },
  stringExpression: {
    oneOf: [
      "concat",
      "left",
      "right",
      "string",
      "idRef",
      "parentIdRef",
      "contentRef",
      "stringPrimitive"
    ]
  },
  intExpression: {
    oneOf: [
      "length",
      "indexOf",
      "int",
      "nChildren",
      "intPrimitive",
      "add",
      "sub",
      "mul",
      "div",
      "mod"
    ]
  },
  equals: {
    regex: XRegExp("^==\\((.+)\\)$"),
    doc: {
      operator: "==",
      args: ["expression", "expression"],
      result: "boolean",
      description: "Are the arguments strictly equal?"
    },
    argStructure: [["expression", [2, 2]]]
  },
  notEqual: {
    regex: XRegExp("^!=\\((.+)\\)$"),
    doc: {
      operator: "!=",
      args: ["expression", "expression"],
      result: "boolean",
      description: "Are the arguments not strictly equal?"
    },
    argStructure: [["expression", [2, 2]]]
  },
  and: {
    regex: XRegExp("^and\\((.+)\\)$"),
    doc: {
      operator: "and",
      args: ["boolean", "boolean", "..."],
      result: "boolean",
      description: "Are all the arguments true?"
    },
    breakOn: false,
    argStructure: [["booleanExpression", [2, null]]]
  },
  or: {
    regex: XRegExp("^or\\((.+)\\)$"),
    doc: {
      operator: "or",
      args: ["boolean", "boolean"],
      result: "boolean",
      description: "Are any arguments true?"
    },
    breakOn: true,
    argStructure: [["booleanExpression", [2, null]]]
  },
  concat: {
    regex: XRegExp("^concat\\((.+)\\)$"),
    doc: {
      operator: "concat",
      args: ["string", "string", "..."],
      result: "string",
      description: "Concatenates string arguments"
    },
    argStructure: [["stringExpression", [2, null]]]
  },
  contentRef: {
    regex: XRegExp("^content\\((.+)\\)$"),
    doc: {
      operator: "content",
      args: ["string"],
      result: "string",
      description: "String value of the specified content for the node"
    },
    argStructure: [["stringExpression", [1, 1]]]
  },
  hasContent: {
    regex: XRegExp("^hasContent\\((.+)\\)$"),
    doc: {
      operator: "hasContent",
      args: ["string"],
      result: "boolean",
      description: "Does the node have this content?"
    },
    argStructure: [["stringExpression", [1, 1]]]
  },
  contains: {
    regex: XRegExp("^contains\\((.+)\\)$"),
    doc: {
      operator: "contains",
      args: ["string", "string"],
      result: "boolean",
      description: "Does the first string contain the second string?"
    },
    argStructure: [["stringExpression", [2, 2]]]
  },
  startsWith: {
    regex: XRegExp("^startsWith\\((.+)\\)$"),
    doc: {
      operator: "startsWith",
      args: ["string", "string"],
      result: "boolean",
      description: "Does the first string start with the second string?"
    },
    argStructure: [["stringExpression", [2, 2]]]
  },
  endsWith: {
    regex: XRegExp("^endsWith\\((.+)\\)$"),
    doc: {
      operator: "endsWith",
      args: ["string", "string"],
      result: "boolean",
      description: "Does the first string end with the second string?"
    },
    argStructure: [["stringExpression", [2, 2]]]
  },
  matches: {
    regex: XRegExp("^matches\\((.+)\\)$"),
    doc: {
      operator: "matches",
      args: ["string", "regex"],
      result: "boolean",
      description: "Does the first string match the regex in the second string?"
    },
    argStructure: [["stringExpression", [2, 2]]]
  },
  left: {
    regex: XRegExp("^left\\((.+)\\)$"),
    doc: {
      operator: "left",
      args: ["string", "integer"],
      result: "string",
      description: "The first n characters of the string"
    },
    argStructure: [
      ["stringExpression", [1, 1]],
      ["intExpression", [1, 1]]
    ]
  },
  right: {
    regex: XRegExp("^right\\((.+)\\)$"),
    doc: {
      operator: "right",
      args: ["string", "integer"],
      result: "string",
      description: "The last n characters of the string"
    },
    argStructure: [
      ["stringExpression", [1, 1]],
      ["intExpression", [1, 1]]
    ]
  },
  length: {
    regex: XRegExp("^length\\((.+)\\)$"),
    doc: {
      operator: "length",
      args: ["string"],
      result: "integer",
      description: "The number of characters in the string"
    },
    argStructure: [["stringExpression", [1, 1]]]
  },
  indexOf: {
    regex: XRegExp("^indexOf\\((.+)\\)$"),
    doc: {
      operator: "indexOf",
      args: ["string", "string"],
      result: "number",
      description: "The integer position at which the second string starts in the first string"
    },
    argStructure: [["stringExpression", [2, 2]]]
  },
  not: {
    regex: XRegExp("^not\\((.+)\\)$"),
    doc: {
      operator: "not",
      args: ["boolean"],
      result: "boolean",
      description: "The inverse boolean value of the argument"
    },
    argStructure: [["booleanExpression", [1, 1]]]
  },
  int: {
    regex: XRegExp("^int\\((.+)\\)$"),
    doc: {
      operator: "int",
      args: ["string"],
      result: "integer",
      description: "The integer value of the string"
    },
    argStructure: [["stringExpression", [1, 1]]]
  },
  string: {
    regex: XRegExp("^string\\((.+)\\)$"),
    doc: {
      operator: "string",
      args: ["integer"],
      result: "string",
      description: "The string value of the integer"
    },
    argStructure: [["intExpression", [1, 1]]]
  },
  idRef: {
    regex: XRegExp("^id$"),
    doc: {
      operator: "id",
      args: [],
      result: "string",
      description: "The node ID"
    },
    argStructure: []
  },
  parentIdRef: {
    regex: XRegExp("^parentId$"),
    doc: {
      operator: "parentId",
      args: [],
      result: "string",
      description: "The node's parent ID"
    },
    argStructure: []
  },
  nChildren: {
    regex: XRegExp("^nChildren$"),
    doc: {
      operator: "nChildren",
      args: [],
      result: "int",
      description: "The number of children of the node"
    },
    argStructure: []
  },
  add: {
    regex: XRegExp("^add\\((.+)\\)$"),
    doc: {
      operator: "add",
      args: ["integer", "..."],
      result: "integer",
      description: "The numeric sum of the arguments"
    },
    argStructure: [["intExpression", [2, null]]]
  },
  mul: {
    regex: XRegExp("^mul\\((.+)\\)$"),
    doc: {
      operator: "mul",
      args: ["integer", "..."],
      result: "integer",
      description: "The numeric product of the arguments"
    },
    argStructure: [["intExpression", [2, null]]]
  },
  sub: {
    regex: XRegExp("^sub\\((.+)\\)$"),
    doc: {
      operator: "sub",
      args: ["integer", "integer"],
      result: "integer",
      description: "The first integer minus the second"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  div: {
    regex: XRegExp("^div\\((.+)\\)$"),
    doc: {
      operator: "div",
      args: ["integer", "integer"],
      result: "integer",
      description: "The first integer divided by the second"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  mod: {
    regex: XRegExp("^mod\\((.+)\\)$"),
    doc: {
      operator: "mod",
      args: ["integer", "integer"],
      result: "integer",
      description: "The modulus of the first integer when divided by the second"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  gt: {
    regex: XRegExp("^>\\((.+)\\)$"),
    doc: {
      operator: ">",
      args: ["integer", "integer"],
      result: "boolean",
      description: "Is the first integer numerically greater than the second?"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  lt: {
    regex: XRegExp("^<\\((.+)\\)$"),
    doc: {
      operator: "<",
      args: ["integer", "integer"],
      result: "boolean",
      description: "Is the first integer numerically less than the second?"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  ge: {
    regex: XRegExp("^>=\\((.+)\\)$"),
    doc: {
      operator: ">=",
      args: ["integer", "integer"],
      result: "boolean",
      description: "Is the first integer numerically greater than or equal to the second?"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  le: {
    regex: XRegExp("^<=\\((.+)\\)$"),
    doc: {
      operator: "<=",
      args: ["integer", "integer"],
      result: "boolean",
      description: "Is the first integer numerically less than or equal to the second?"
    },
    argStructure: [["intExpression", [2, 2]]]
  },
  stringPrimitive: {
    regex: XRegExp("^('([^']|\\\\')*')$"),
    parseFunctions: [null, "quotedString"]
  },
  intPrimitive: {
    regex: XRegExp("^(-?[0-9]+)$"),
    parseFunctions: [null, "int"]
  },
  booleanPrimitive: {
    regex: XRegExp("^(true)|(false)$"),
    parseFunctions: [null, "true", "false"]
  }
};
const parseRegexExpression = (docSet, node, predicateString, expressionId, matches) => {
  const expressionRecord = expressions[expressionId];
  if (!expressionRecord) {
    throw new Error(
      `Unknown expression ${expressionId} for predicate ${predicateString}`
    );
  }
  const nExpectedArgs = (structure) => [
    structure.map((a) => a[1][0]).reduce((a, b) => a + b),
    structure.filter((a) => a[1][1] === null).length > 0
  ];
  if (expressionRecord.parseFunctions) {
    let found = false;
    for (const [
      n,
      parseFunction
    ] of expressionRecord.parseFunctions.entries()) {
      if (!parseFunction || !matches[n]) {
        continue;
      }
      found = true;
      return { data: parseFunctions[parseFunction](matches[n]) };
    }
    if (!found) {
      return { errors: `Could not parse predicate ${predicateString}` };
    }
  } else {
    const argRecords = splitArgs(matches[1]);
    const argStructure = expressionRecord.argStructure;
    const argResults = [];
    if (argStructure.length > 0) {
      const nExpected = nExpectedArgs(argStructure);
      if (argRecords.length < nExpected[0]) {
        return {
          errors: `Expected at least ${nExpected[0]} args for '${expressionId}', found ${argRecords.length}`
        };
      }
      if (!nExpected[1] && argRecords.length > nExpected[0]) {
        return {
          errors: `Expected at most ${nExpected[0]} args for '${expressionId}', found ${argRecords.length}`
        };
      }
      let argRecordN = 0;
      let argStructureN = 0;
      let nOccs = 0;
      while (argRecordN < argRecords.length) {
        const argRecord = argRecords[argRecordN];
        const argResult = parseExpression(
          docSet,
          node,
          argRecord,
          argStructure[argStructureN][0]
        );
        if ("breakOn" in expressionRecord && !argRecord.errors && argResult.data === expressionRecord.breakOn) {
          return argResult;
        }
        argResults.push(argResult);
        argRecordN++;
        nOccs++;
        if (argStructure[argStructureN][1][1] && nOccs >= argStructure[argStructureN][1][1]) {
          argStructureN++;
          nOccs = 0;
        }
      }
    }
    if (argResults.filter((ar) => ar.errors).length === 0) {
      const args = argResults.map((ar) => ar.data);
      const aggregated = aggregateFunctions[expressionId](
        docSet,
        node,
        ...args
      );
      return { data: aggregated };
    }
    return {
      errors: `Could not parse arguments to ${expressionId}: ${argRecords.filter((ar) => ar.errors).map((ar) => ar.errors).join("; ")}`
    };
  }
};
const parseExpression = (docSet, node, predicate, expressionId) => {
  const expressionRecord = expressions[expressionId];
  if (!expressionRecord) {
    throw new Error(
      `Unknown expression ${expressionId} for predicate ${predicate}`
    );
  }
  if (expressionRecord.oneOf) {
    let errors2 = null;
    for (const option of expressionRecord.oneOf) {
      const optionResult = parseExpression(docSet, node, predicate, option);
      if (!optionResult.errors) {
        return optionResult;
      } else if (!errors2 || optionResult.errors.length < errors2.length) {
        errors2 = optionResult.errors;
      }
    }
    return { errors: errors2 };
  } else {
    const matches = XRegExp.exec(predicate, expressionRecord.regex);
    if (matches) {
      const reResult = parseRegexExpression(
        docSet,
        node,
        predicate,
        expressionId,
        matches
      );
      return reResult;
    } else {
      return { errors: `Could not match ${predicate}` };
    }
  }
};
const doPredicate = (docSet, result, predicateString) => ({
  data: result.data.filter((node) => {
    const nodeResult = parseExpression(
      docSet,
      node,
      predicateString,
      "booleanExpression"
    );
    if (nodeResult.errors) {
      throw new Error(`Predicate - ${nodeResult.errors}`);
    }
    return nodeResult.data;
  })
});
const predicateRegex = "(\\[(([^\\]']|'([^']|\\\\')*')+)\\])*";
const doAbsoluteIdStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  const values = matches[1].split(",").map((v) => v.trim());
  return {
    data: Array.from(values).map((nid) => allNodes[nodeLookup.get(nid)])
  };
};
const doAbsoluteRootStep = (docSet, allNodes) => ({ data: [allNodes[0]] });
const doAbsoluteNodesStep = (docSet, allNodes) => ({ data: allNodes });
const doChildrenStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  const childNo = matches[2];
  const childNodeIds = /* @__PURE__ */ new Set([]);
  for (const parentNode of result.data) {
    const children = docSet.unsuccinctifyScopes(parentNode.is).map((s) => s[2].split("/")).filter((s) => s[0] === "tTreeChild").filter((s) => !childNo || s[1] === childNo).map((s) => s[2]);
    for (const child of children) {
      childNodeIds.add(child);
    }
  }
  return {
    data: Array.from(childNodeIds).map((nid) => allNodes[nodeLookup.get(nid)])
  };
};
const doParentStep = (docSet, allNodes, nodeLookup, result) => {
  const parentNodeIds = /* @__PURE__ */ new Set([]);
  for (const childNode of result.data) {
    const parentId = docSet.unsuccinctifyScopes(childNode.is).filter((s) => s[2].startsWith("tTreeParent")).map((s) => s[2].split("/")[1])[0];
    parentNodeIds.add(parentId);
  }
  return {
    data: Array.from(parentNodeIds).map((nid) => allNodes[nodeLookup.get(nid)])
  };
};
const doAncestorStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  let ancestorNo = parseInt(matches[2]);
  if (ancestorNo < 1) {
    return {
      errors: `Expected a positive integer argument for ancestor, found ${queryStep}`
    };
  }
  let nodes = result.data;
  while (ancestorNo > 0) {
    const parentNodeIds = /* @__PURE__ */ new Set([]);
    for (const childNode of nodes) {
      const parentId = docSet.unsuccinctifyScopes(childNode.is).filter((s) => s[2].startsWith("tTreeParent")).map((s) => s[2].split("/")[1])[0];
      parentNodeIds.add(parentId);
    }
    nodes = Array.from(parentNodeIds).map(
      (nid) => allNodes[nodeLookup.get(nid)]
    );
    ancestorNo--;
  }
  return { data: nodes };
};
const doDescendantsStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  const descendantIds = /* @__PURE__ */ new Set([]);
  const getDescendants = (node, depth) => {
    const childIds = docSet.unsuccinctifyScopes(node.is).filter((s) => s[2].startsWith("tTreeChild")).map((s) => s[2].split("/")[2]);
    if (depth <= 1 || depth === null) {
      childIds.forEach((n) => descendantIds.add(n));
    }
    if (depth === null || depth > 1) {
      childIds.map((nid) => allNodes[nodeLookup.get(nid)]).forEach((n) => getDescendants(n, depth - 1));
    }
  };
  let descendantGen = null;
  if (matches[3]) {
    descendantGen = parseInt(matches[3]);
  }
  let descendantNo = -1;
  if (matches[5]) {
    descendantNo = parseInt(matches[5]);
  }
  for (const node of result.data) {
    getDescendants(node, descendantGen);
  }
  return {
    data: [...Array.from(descendantIds).entries()].filter((n) => descendantNo < 0 || n[0] === descendantNo).map((n) => n[1]).map((nid) => allNodes[nodeLookup.get(nid)])
  };
};
const doLeavesStep = (docSet, allNodes, nodeLookup, result) => {
  const leafIds = /* @__PURE__ */ new Set([]);
  const getLeaves = (node) => {
    const childIds = docSet.unsuccinctifyScopes(node.is).filter((s) => s[2].startsWith("tTreeChild")).map((s) => s[2].split("/")[2]);
    if (childIds.length === 0) {
      leafIds.add(docSet.unsuccinctifyScopes(node.bs)[0][2].split("/")[1]);
    } else {
      childIds.map((nid) => allNodes[nodeLookup.get(nid)]).forEach((n) => getLeaves(n));
    }
  };
  for (const node of result.data) {
    getLeaves(node);
  }
  return {
    data: Array.from(leafIds).map((nid) => allNodes[nodeLookup.get(nid)])
  };
};
const doSiblingsStep = (docSet, allNodes, nodeLookup, result) => {
  const parentNodeIds = /* @__PURE__ */ new Set([]);
  for (const childNode of result.data) {
    const parentId = docSet.unsuccinctifyScopes(childNode.is).filter((s) => s[2].startsWith("tTreeParent")).map((s) => s[2].split("/")[1])[0];
    parentNodeIds.add(parentId);
  }
  const parentNodes = allNodes.filter(
    (n) => parentNodeIds.has(docSet.unsuccinctifyScopes(n.bs)[0][2].split("/")[1])
  );
  const childNodeIds = /* @__PURE__ */ new Set([]);
  for (const parentNode of parentNodes) {
    const children = docSet.unsuccinctifyScopes(parentNode.is).filter((s) => s[2].startsWith("tTreeChild")).map((s) => s[2].split("/")[2]);
    for (const child of children) {
      childNodeIds.add(child);
    }
  }
  return {
    data: Array.from(childNodeIds).map((nid) => allNodes[nodeLookup.get(nid)])
  };
};
const nodeDetails = (docSet, node, allNodes, nodeLookup, fields, isBranch) => {
  const record = {};
  if (fields.size === 0 || fields.has("id")) {
    record.id = docSet.unsuccinctifyScopes(node.bs)[0][2].split("/")[1];
  }
  if (fields.size === 0 || fields.has("parentId")) {
    record.parentId = docSet.unsuccinctifyScopes(node.is).filter((s) => s[2].startsWith("tTreeParent")).map((s) => s[2].split("/")[1])[0];
  }
  const content = {};
  for (const [scopeLabels, items2] of docSet.sequenceItemsByScopes(
    [node],
    ["tTreeContent/"],
    false
  )) {
    const key = scopeLabels.filter((s) => s.startsWith("tTreeContent"))[0].split("/")[1];
    if (fields.size === 0 || fields.has("content") || fields.has(`@${key}`)) {
      content[key] = items2.filter((i) => i[0] === "token").map((t) => t[2]).join("");
    }
  }
  if (Object.keys(content).length > 0) {
    record.content = content;
  }
  const children = [];
  if (fields.has("children")) {
    for (const childScope of docSet.unsuccinctifyScopes(node.is).filter((s) => s[2].startsWith("tTreeChild")).map((s) => s[2].split("/")[2])) {
      children.push(childScope);
    }
  }
  if (children.length > 0) {
    if (isBranch) {
      record.children = children.map((nid) => allNodes[nodeLookup.get(nid)]).map((n) => nodeDetails(docSet, n, allNodes, nodeLookup, fields, true));
    } else {
      record.children = children;
    }
  }
  return record;
};
const doBranchStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  const ret = [];
  let fields = /* @__PURE__ */ new Set([]);
  if (matches[2]) {
    fields = new Set(matches[2].split(",").map((f) => f.trim()));
  }
  for (const node of result.data) {
    ret.push(nodeDetails(docSet, node, allNodes, nodeLookup, fields, true));
  }
  return { data: ret };
};
const doValuesStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  const nodeFields = [];
  let fields = /* @__PURE__ */ new Set([]);
  if (matches[2]) {
    fields = new Set(
      matches[2].split(",").map((f) => f.trim()).filter((f) => f.startsWith("@"))
    );
  }
  for (const node of result.data) {
    nodeFields.push(
      nodeDetails(docSet, node, allNodes, nodeLookup, fields, true)
    );
  }
  const values = {};
  for (const field of Array.from(fields).map((f) => f.substring(1))) {
    values[field] = Array.from(
      new Set(
        nodeFields.filter((nd) => nd.content).map((nd) => nd.content).filter((nd) => field in nd).map((nd) => nd[field]).sort()
      )
    );
  }
  return { data: values };
};
const doNodeStep = (docSet, allNodes, nodeLookup, result, queryStep, matches) => {
  const ret = [];
  let fields = /* @__PURE__ */ new Set([]);
  if (matches[2]) {
    fields = new Set(matches[2].split(",").map((f) => f.trim()));
  }
  for (const node of result.data) {
    ret.push(nodeDetails(docSet, node, allNodes, nodeLookup, fields, false));
  }
  return { data: ret };
};
const stepActions = [
  {
    regex: XRegExp(`^#\\{([^}]+)\\}${predicateRegex}$`),
    doc: {
      title: "Nodes by Id",
      syntax: "#(id, id, ...)",
      description: "Returns nodes whose id is listed"
    },
    predicateCapture: 3,
    inputType: null,
    outputType: "nodes",
    function: doAbsoluteIdStep
  },
  {
    regex: XRegExp(`^root${predicateRegex}$`),
    doc: {
      title: "Root Node",
      syntax: "root",
      description: "Returns the root node"
    },
    predicateCapture: 2,
    inputType: null,
    outputType: "nodes",
    function: doAbsoluteRootStep
  },
  {
    regex: XRegExp(`^nodes${predicateRegex}$`),
    doc: {
      title: "Nodes",
      syntax: "nodes",
      description: "Returns all the nodes"
    },
    predicateCapture: 2,
    function: doAbsoluteNodesStep,
    inputType: null,
    outputType: "nodes"
  },
  {
    regex: XRegExp(`^children(\\((\\d+)\\))?${predicateRegex}$`),
    doc: {
      title: "Children",
      syntax: "children; children(pos)",
      description: "Returns the children of the current node(s), optionally filtered by position within the parent node"
    },
    predicateCapture: 4,
    inputType: "nodes",
    outputType: "nodes",
    function: doChildrenStep
  },
  {
    regex: XRegExp(`^descendants((\\((\\d+)(,\\s*(\\d+))?\\))?)${predicateRegex}$`),
    doc: {
      title: "Descendants",
      syntax: "descendants; descendants(depth); descendants(depth, pos)",
      description: "Returns the descendants of the current node(s), optionally at the specified level, optionally filtered by position"
    },
    predicateCapture: 7,
    inputType: "nodes",
    outputType: "nodes",
    function: doDescendantsStep
  },
  {
    regex: XRegExp(`^leaves${predicateRegex}$`),
    doc: {
      title: "Leaves",
      syntax: "leaves",
      description: "Returns the leaves (ie the nodes with no children) below the current node"
    },
    predicateCapture: 2,
    inputType: "nodes",
    outputType: "nodes",
    function: doLeavesStep
  },
  {
    regex: XRegExp(`^parent${predicateRegex}$`),
    doc: {
      title: "Parent",
      syntax: "parent",
      description: "Returns the parent of the current node"
    },
    predicateCapture: 2,
    inputType: "nodes",
    outputType: "nodes",
    function: doParentStep
  },
  {
    regex: XRegExp(`^ancestor(\\((\\d+)\\))${predicateRegex}$`),
    doc: {
      title: "Ancestor",
      syntax: "ancestor(depth)",
      description: "Returns the nth ancestor of the node"
    },
    predicateCapture: 5,
    inputType: "nodes",
    outputType: "nodes",
    function: doAncestorStep
  },
  {
    regex: XRegExp(`^siblings${predicateRegex}$`),
    doc: {
      title: "Siblings",
      syntax: "siblings",
      description: "Returns the children of the parent of the current node"
    },
    predicateCapture: 2,
    inputType: "nodes",
    outputType: "nodes",
    function: doSiblingsStep
  },
  {
    regex: XRegExp(`^node(\\{([^}]+)\\})?${predicateRegex}$`),
    doc: {
      title: "Node Details",
      syntax: "node; node{ id, parentId, content, children, @foo }",
      description: "Returns an object containing the specified content"
    },
    predicateCapture: 4,
    inputType: "nodes",
    outputType: "node",
    function: doNodeStep
  },
  {
    regex: XRegExp(`^branch(\\{([^}]+)\\})?${predicateRegex}$`),
    doc: {
      title: "Branch",
      syntax: "branch; branch{ id, parentId, content, children, @foo }",
      description: "Returns nested objects containing the specified content"
    },
    predicateCapture: 4,
    inputType: "nodes",
    outputType: "node",
    function: doBranchStep
  },
  {
    regex: XRegExp(`^values(\\{([^}]+)\\})?${predicateRegex}$`),
    doc: {
      title: "Values",
      syntax: "values{ @foo ... }",
      description: "Returns all values across nodes for the specified fields"
    },
    predicateCapture: 4,
    inputType: "nodes",
    outputType: "values",
    function: doValuesStep
  }
];
class Tribos {
  constructor() {
    this.currentStepType = null;
  }
  doStep(docSet, allNodes, nodeLookup, result, queryStep) {
    for (const stepAction of stepActions) {
      const matches = XRegExp.exec(queryStep, stepAction.regex);
      if (matches && stepAction.inputType === this.currentStepType) {
        let ret = stepAction.function(
          docSet,
          allNodes,
          nodeLookup,
          result,
          queryStep,
          matches
        );
        if (matches[stepAction.predicateCapture]) {
          ret = doPredicate(docSet, ret, matches[stepAction.predicateCapture]);
        }
        this.currentStepType = stepAction.outputType;
        return ret;
      }
    }
    return { errors: `Unable to match step ${queryStep}` };
  }
  parse1(docSet, allNodes, nodeLookup, result, queryArray) {
    if (queryArray.length > 0) {
      const stepResult = this.doStep(
        docSet,
        allNodes,
        nodeLookup,
        result,
        queryArray[0]
      );
      if (stepResult.errors || stepResult.data.length === 0) {
        return stepResult;
      } else {
        return this.parse1(
          docSet,
          allNodes,
          nodeLookup,
          stepResult,
          queryArray.slice(1)
        );
      }
    } else {
      return result;
    }
  }
  queryArray(qs) {
    const ret = [];
    for (const s of qs.split("/")) {
      ret.push(s);
    }
    return ret;
  }
  indexNodes(docSet, nodes) {
    const ret = /* @__PURE__ */ new Map();
    for (const [n, node] of nodes.entries()) {
      const nodeId = docSet.unsuccinctifyScopes(node.bs)[0][2].split("/")[1];
      ret.set(nodeId, n);
    }
    return ret;
  }
  doc() {
    return "** Steps **\n\n" + stepActions.map((sa) => sa.doc).map((d) => `* ${d.title} *
${d.syntax}
${d.description}`).join("\n\n") + "** Predicate Operators **\n\n" + Object.values(expressions).filter((e) => e.doc).map(
      (e) => `${e.doc.operator}(${e.doc.args.map((a) => "<" + a + ">").join(", ")}) => ${e.doc.result}
${e.doc.description}`
    ).join("\n\n");
  }
  parse(docSet, nodes, queryString) {
    const result = this.parse1(
      docSet,
      nodes,
      this.indexNodes(docSet, nodes),
      { data: nodes },
      this.queryArray(queryString)
    );
    if (result.data) {
      switch (this.currentStepType) {
        case "nodes":
          result.data = result.data.map((n) => ({
            id: docSet.unsuccinctifyScopes(n.bs)[0][2].split("/")[1]
          }));
      }
    }
    const ret = JSON.stringify(result, null, 2);
    return ret;
  }
}
const treeSequenceSchemaString = `
"""The nodes of a tree"""
type treeSequence {
  """The id of the sequence"""
  id: String!
  """The number of nodes in the tree sequence"""
  nNodes: Int!
  """The nodes in the tree sequence"""
  nodes: [node!]!
  """The JSON result for a Tribos query, as a string"""
  tribos(
    """The Tribos query string"""
    query: String!
  ): String!
  """The JSON results for the Tribos queries, as an array of strings"""
  triboi(
    """The Tribos query strings"""
    queries: [String!]!
  ): [String!]!
  """Tribos documentation"""
  tribosDoc: String!
  """A list of the tags of this sequence"""
  tags: [String!]!
  """A list of the tags of this sequence as key/value tuples"""
  tagsKv: [KeyValue!]!
  """Whether or not the sequence has the specified tag"""
  hasTag(
    """The tag name"""
    tagName: String
  ): Boolean!
}
`;
const treeSequenceResolvers = {
  nNodes: (root) => root.blocks.length,
  nodes: (root) => root.blocks,
  tribos: (root, args, context) => new Tribos().parse(context.docSet, root.blocks, args.query),
  triboi: (root, args, context) => args.queries.map((q) => new Tribos().parse(context.docSet, root.blocks, q)),
  tribosDoc: () => new Tribos().doc(),
  tags: (root) => Array.from(root.tags),
  tagsKv: (root) => Array.from(root.tags).map((t) => {
    if (t.includes(":")) {
      return [
        t.substring(0, t.indexOf(":")),
        t.substring(t.indexOf(":") + 1)
      ];
    } else {
      return [t, ""];
    }
  }),
  hasTag: (root, args) => root.tags.has(args.tagName)
};
const scopeMatchesStartsWith = (sw, s) => {
  if (sw.length === 0) {
    return true;
  }
  for (const swv of sw) {
    if (s.startsWith(swv)) {
      return true;
    }
  }
  return false;
};
const blockSchemaString = `
"""Part of a sequence, roughly equivalent to a USFM paragraph"""
type Block {
  """The length in bytes of the succinct representation of c (block items)"""
  cBL: Int!
  """The length in bytes of the succinct representation of bg (block grafts)"""
  bgBL: Int!
  """The length in bytes of the succinct representation of os (open scopes)"""
  osBL: Int!
  """The length in bytes of the succinct representation of is (included scopes)"""
  isBL: Int!
  """The length in bytes of the succinct representation of nt (nextToken at the start of the block)"""
  ntBL: Int!
  """The number of items in the succinct representation of c (block items)"""
  cL: Int!
  """The number of items in the succinct representation of bg (block grafts)"""
  bgL: Int!
  """The number of items in the succinct representation of os (open scopes)"""
  osL: Int!
  """The number of items in the succinct representation of is (included scopes)"""
  isL: Int!
  """A list of included scopes for this block"""
  is: [Item!]!
  """A list of open scopes for this block"""
  os: [Item!]!
  """The block scope for this block"""
  bs: Item!
  """A list of block grafts for this block"""
  bg: [Item!]!
  """The value of nextToken at the start of this block"""
  nt: Int!
  """A list of items from the c (content) field of the block"""
  items(
    """Only return items that are within specific scopes"""
    withScopes: [String!]
    """If true, withScopes filtering matches items within at least one of the specified scopes"""
    anyScope: Boolean
    """Only return items that are within a chapterVerse range (ch or ch:v or ch:v-v or ch:v-ch:v)"""
    withScriptureCV: String
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
    """Do not return scopes types in list (eg milestone)"""
    excludeScopeTypes: [String!]
  ) : [Item!]! 
  """A list of tokens from the c (content) field of the block"""
  tokens(
    """Only return tokens that are within specific scopes"""
    withScopes: [String!]
    """If true, withScopes filtering matches tokens within at least one of the specified scopes"""
    anyScope: Boolean
    """Only return tokens that are within a chapterVerse range (ch or ch:v or ch:v-v or ch:v-ch:v)"""
    withScriptureCV: String
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
    """Return tokens whose payload is an exact match to one of the specified strings"""
    withChars: [String!]
    """Return tokens whose payload matches one of the specified regexes"""
    withMatchingChars: [String!]
    """Return tokens with one of the specified subTypes"""
    withSubTypes: [String!]
  ) : [Item!]!
  """The text of the block as a single string"""
  text(
    """Only return text that is within a chapterVerse range (ch or ch:v or ch:v-v or ch:v-ch:v)"""
    withScriptureCV: String
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): String!
  """'Block items grouped by scopes or milestones"""
  itemGroups(
    """Produce one itemGroup for every match of the list of scopes"""
    byScopes: [String!]
    """Start a new itemGroup whenever a milestone in the list is encountered"""
    byMilestones: [String!]
  ): [ItemGroup]!
  """The block content as a string in a compact eyeballable format"""
  dump: String!
  """A list of the labels for the block\\'s bs, os and is scopes"""
  scopeLabels(
    """Only include scopes that begin with this value"""
    startsWith: [String!]
  ): [String!]!
}
`;
const blockResolvers = {
  cBL: (root) => root.c.length,
  bgBL: (root) => root.bg.length,
  osBL: (root) => root.os.length,
  isBL: (root) => root.is.length,
  ntBL: (root) => root.nt.length,
  cL: (root, args, context) => context.docSet.countItems(root.c),
  bgL: (root, args, context) => context.docSet.countItems(root.bg),
  osL: (root, args, context) => context.docSet.countItems(root.os),
  isL: (root, args, context) => context.docSet.countItems(root.is),
  is: (root, args, context) => context.docSet.unsuccinctifyScopes(root.is),
  os: (root, args, context) => context.docSet.unsuccinctifyScopes(root.os),
  bs: (root, args, context) => {
    const [itemLength, itemType, itemSubtype] = utils.succinct.headerBytes(
      root.bs,
      0
    );
    return context.docSet.unsuccinctifyScope(root.bs, itemType, itemSubtype, 0);
  },
  bg: (root, args, context) => context.docSet.unsuccinctifyGrafts(root.bg),
  nt: (root) => root.nt.nByte(0),
  items: (root, args, context) => {
    if (args.withScopes && args.withScriptureCV) {
      throw new Error("Cannot specify both withScopes and withScriptureCV");
    }
    if (args.withScriptureCV) {
      return context.docSet.unsuccinctifyItemsWithScriptureCV(
        root,
        args.withScriptureCV,
        args.excludeScopeTypes ? {
          tokens: true,
          scopes: true,
          grafts: true,
          excludeScopeTypes: args.excludeScopeTypes || [],
          anyScope: args.anyScope || false,
          includeContext: args.includeContext || false
        } : {}
      );
    } else {
      return context.docSet.unsuccinctifyPrunedItems(root, {
        tokens: true,
        scopes: true,
        grafts: true,
        excludeScopeTypes: args.excludeScopeTypes || [],
        requiredScopes: args.withScopes || [],
        anyScope: args.anyScope || false
      });
    }
  },
  tokens: (root, args, context) => {
    if (Object.keys(args).filter((a) => a.includes("Chars")).length > 1) {
      throw new Error(
        'Only one of "withChars", "withAnyCaseChars" and "withCharsMatchingRegex" may be specified'
      );
    }
    let ret;
    if (args.withScriptureCV) {
      ret = context.docSet.unsuccinctifyItemsWithScriptureCV(
        root,
        args.withScriptureCV,
        { tokens: true },
        args.includeContext || false
      );
    } else {
      ret = context.docSet.unsuccinctifyPrunedItems(root, {
        tokens: true,
        scopes: true,
        requiredScopes: args.withScopes || [],
        anyScope: args.anyScope || false
      });
    }
    if (args.withSubTypes) {
      ret = ret.filter((i) => args.withSubTypes.includes(i[1]));
    }
    if (args.withChars) {
      ret = ret.filter((i) => args.withChars.includes(i[2]));
    } else if (args.withMatchingChars) {
      ret = ret.filter((i) => {
        for (const re2 of args.withMatchingChars) {
          if (XRegExp.test(i, XRegExp(re2))) {
            return true;
          }
        }
        return false;
      });
    }
    return ret.filter((i) => i[0] === "token");
  },
  text: (root, args, context) => {
    const tokens2 = args.withScriptureCV ? context.docSet.unsuccinctifyItemsWithScriptureCV(
      root,
      args.withScriptureCV,
      { tokens: true },
      false
    ) : context.docSet.unsuccinctifyItems(root.c, { tokens: true }, null);
    let ret = tokens2.map((t) => t[2]).join("").trim();
    if (args.normalizeSpace) {
      ret = ret.replace(/[ \t\n\r]+/g, " ");
    }
    return ret;
  },
  itemGroups: (root, args, context) => {
    if (args.byScopes && args.byMilestones) {
      throw new Error("Cannot specify both byScopes and byMilestones");
    }
    if (!args.byScopes && !args.byMilestones) {
      throw new Error("Must specify either byScopes or byMilestones");
    }
    if (args.byScopes) {
      return context.docSet.sequenceItemsByScopes([root], args.byScopes);
    } else {
      return context.docSet.sequenceItemsByMilestones(
        [root],
        args.byMilestones
      );
    }
  },
  dump: (root, args, context) => dumpBlock(context.docSet.unsuccinctifyBlock(root, {}, null)),
  scopeLabels: (root, args, context) => [...context.docSet.unsuccinctifyBlockScopeLabelsSet(root)].filter(
    (s) => !args.startsWith || scopeMatchesStartsWith(args.startsWith, s)
  )
};
const exactSearchTermIndexes = (docSet, chars, allChars) => {
  let charsIndexesArray = [
    chars.map((c) => [utils.enums.enumStringIndex(docSet.enums.wordLike, c)])
  ];
  if (allChars) {
    charsIndexesArray = charsIndexesArray[0];
  } else {
    charsIndexesArray = charsIndexesArray.map(
      (ci) => ci.reduce((a, b) => a.concat(b))
    );
  }
  return charsIndexesArray;
};
const regexSearchTermIndexes = (docSet, chars, allChars) => {
  let charsIndexesArray = [
    chars.map(
      (c) => utils.enums.enumRegexIndexTuples(docSet.enums.wordLike, c).map((tup) => tup[0])
    )
  ];
  if (allChars) {
    charsIndexesArray = charsIndexesArray[0];
  } else {
    charsIndexesArray = charsIndexesArray.map(
      (ci) => ci.reduce((a, b) => a.concat(b))
    );
  }
  return charsIndexesArray;
};
const sequenceMatchesSearchTerms = (seq, charsIndexesArray, allChars) => {
  if (allChars && charsIndexesArray.filter((i) => i.length === 0).length > 0) {
    return false;
  }
  charsIndexesArray = charsIndexesArray.filter((i) => i.length > 0);
  if (charsIndexesArray.length === 0) {
    return false;
  }
  for (const charsIndexes of charsIndexesArray) {
    let found = false;
    for (const charsIndex of charsIndexes) {
      const isPresent = charsIndex >= 0 && seq.tokensPresent.get(charsIndex) > 0;
      if (isPresent) {
        found = true;
        break;
      }
    }
    if (allChars && !found) {
      return false;
    } else if (!allChars && found) {
      return true;
    }
  }
  return allChars;
};
const sequenceHasChars = (docSet, seq, chars, allChars) => {
  let charsIndexesArray = exactSearchTermIndexes(docSet, chars, allChars);
  return sequenceMatchesSearchTerms(seq, charsIndexesArray, allChars);
};
const sequenceHasMatchingChars = (docSet, seq, chars, allChars) => {
  let charsIndexesArray = regexSearchTermIndexes(docSet, chars, allChars);
  return sequenceMatchesSearchTerms(seq, charsIndexesArray, allChars);
};
const unicodeTree = [
  [
    64335,
    [
      [
        8591,
        [
          [
            4991,
            [
              [
                2143,
                [
                  [
                    1279,
                    [
                      [
                        591,
                        [
                          [
                            255,
                            [
                              [
                                127,
                                "Basic Latin"
                              ],
                              [
                                255,
                                "Latin-1 Supplement"
                              ]
                            ]
                          ],
                          [
                            591,
                            [
                              [
                                383,
                                "Latin Extended-A"
                              ],
                              [
                                591,
                                "Latin Extended-B"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        1279,
                        [
                          [
                            767,
                            [
                              [
                                687,
                                "IPA Extensions"
                              ],
                              [
                                767,
                                "Spacing Modifier Letters"
                              ]
                            ]
                          ],
                          [
                            1279,
                            [
                              [
                                879,
                                "Combining Diacritical Marks"
                              ],
                              [
                                1279,
                                [
                                  [
                                    1023,
                                    "Greek and Coptic"
                                  ],
                                  [
                                    1279,
                                    "Cyrillic"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    2143,
                    [
                      [
                        1871,
                        [
                          [
                            1423,
                            [
                              [
                                1327,
                                "Cyrillic Supplement"
                              ],
                              [
                                1423,
                                "Armenian"
                              ]
                            ]
                          ],
                          [
                            1871,
                            [
                              [
                                1535,
                                "Hebrew"
                              ],
                              [
                                1871,
                                [
                                  [
                                    1791,
                                    "Arabic"
                                  ],
                                  [
                                    1871,
                                    "Syriac"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        2143,
                        [
                          [
                            1983,
                            [
                              [
                                1919,
                                "Arabic Supplement"
                              ],
                              [
                                1983,
                                "Thaana"
                              ]
                            ]
                          ],
                          [
                            2143,
                            [
                              [
                                2047,
                                "NKo"
                              ],
                              [
                                2143,
                                [
                                  [
                                    2111,
                                    "Samaritan"
                                  ],
                                  [
                                    2143,
                                    "Mandaic"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                4991,
                [
                  [
                    3199,
                    [
                      [
                        2559,
                        [
                          [
                            2303,
                            [
                              [
                                2159,
                                "Syriac Supplement"
                              ],
                              [
                                2303,
                                "Arabic Extended-A"
                              ]
                            ]
                          ],
                          [
                            2559,
                            [
                              [
                                2431,
                                "Devanagari"
                              ],
                              [
                                2559,
                                "Bengali"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        3199,
                        [
                          [
                            2815,
                            [
                              [
                                2687,
                                "Gurmukhi"
                              ],
                              [
                                2815,
                                "Gujarati"
                              ]
                            ]
                          ],
                          [
                            3199,
                            [
                              [
                                2943,
                                "Oriya"
                              ],
                              [
                                3199,
                                [
                                  [
                                    3071,
                                    "Tamil"
                                  ],
                                  [
                                    3199,
                                    "Telugu"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    4991,
                    [
                      [
                        3839,
                        [
                          [
                            3455,
                            [
                              [
                                3327,
                                "Kannada"
                              ],
                              [
                                3455,
                                "Malayalam"
                              ]
                            ]
                          ],
                          [
                            3839,
                            [
                              [
                                3583,
                                "Sinhala"
                              ],
                              [
                                3839,
                                [
                                  [
                                    3711,
                                    "Thai"
                                  ],
                                  [
                                    3839,
                                    "Lao"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        4991,
                        [
                          [
                            4255,
                            [
                              [
                                4095,
                                "Tibetan"
                              ],
                              [
                                4255,
                                "Myanmar"
                              ]
                            ]
                          ],
                          [
                            4991,
                            [
                              [
                                4351,
                                "Georgian"
                              ],
                              [
                                4991,
                                [
                                  [
                                    4607,
                                    "Hangul Jamo"
                                  ],
                                  [
                                    4991,
                                    "Ethiopic"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ],
          [
            8591,
            [
              [
                6911,
                [
                  [
                    6015,
                    [
                      [
                        5791,
                        [
                          [
                            5119,
                            [
                              [
                                5023,
                                "Ethiopic Supplement"
                              ],
                              [
                                5119,
                                "Cherokee"
                              ]
                            ]
                          ],
                          [
                            5791,
                            [
                              [
                                5759,
                                "Unified Canadian Aboriginal Syllabics"
                              ],
                              [
                                5791,
                                "Ogham"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        6015,
                        [
                          [
                            5919,
                            [
                              [
                                5887,
                                "Runic"
                              ],
                              [
                                5919,
                                "Tagalog"
                              ]
                            ]
                          ],
                          [
                            6015,
                            [
                              [
                                5951,
                                "Hanunoo"
                              ],
                              [
                                6015,
                                [
                                  [
                                    5983,
                                    "Buhid"
                                  ],
                                  [
                                    6015,
                                    "Tagbanwa"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    6911,
                    [
                      [
                        6527,
                        [
                          [
                            6319,
                            [
                              [
                                6143,
                                "Khmer"
                              ],
                              [
                                6319,
                                "Mongolian"
                              ]
                            ]
                          ],
                          [
                            6527,
                            [
                              [
                                6399,
                                "Unified Canadian Aboriginal Syllabics Extended"
                              ],
                              [
                                6527,
                                [
                                  [
                                    6479,
                                    "Limbu"
                                  ],
                                  [
                                    6527,
                                    "Tai Le"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        6911,
                        [
                          [
                            6655,
                            [
                              [
                                6623,
                                "New Tai Lue"
                              ],
                              [
                                6655,
                                "Khmer Symbols"
                              ]
                            ]
                          ],
                          [
                            6911,
                            [
                              [
                                6687,
                                "Buginese"
                              ],
                              [
                                6911,
                                [
                                  [
                                    6831,
                                    "Tai Tham"
                                  ],
                                  [
                                    6911,
                                    "Combining Diacritical Marks Extended"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                8591,
                [
                  [
                    7551,
                    [
                      [
                        7295,
                        [
                          [
                            7103,
                            [
                              [
                                7039,
                                "Balinese"
                              ],
                              [
                                7103,
                                "Sundanese"
                              ]
                            ]
                          ],
                          [
                            7295,
                            [
                              [
                                7167,
                                "Batak"
                              ],
                              [
                                7295,
                                [
                                  [
                                    7247,
                                    "Lepcha"
                                  ],
                                  [
                                    7295,
                                    "Ol Chiki"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        7551,
                        [
                          [
                            7359,
                            [
                              [
                                7311,
                                "Cyrillic Extended-C"
                              ],
                              [
                                7359,
                                "Georgian Extended"
                              ]
                            ]
                          ],
                          [
                            7551,
                            [
                              [
                                7375,
                                "Sundanese Supplement"
                              ],
                              [
                                7551,
                                [
                                  [
                                    7423,
                                    "Vedic Extensions"
                                  ],
                                  [
                                    7551,
                                    "Phonetic Extensions"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    8591,
                    [
                      [
                        8303,
                        [
                          [
                            7679,
                            [
                              [
                                7615,
                                "Phonetic Extensions Supplement"
                              ],
                              [
                                7679,
                                "Combining Diacritical Marks Supplement"
                              ]
                            ]
                          ],
                          [
                            8303,
                            [
                              [
                                7935,
                                "Latin Extended Additional"
                              ],
                              [
                                8303,
                                [
                                  [
                                    8191,
                                    "Greek Extended"
                                  ],
                                  [
                                    8303,
                                    "General Punctuation"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        8591,
                        [
                          [
                            8399,
                            [
                              [
                                8351,
                                "Superscripts and Subscripts"
                              ],
                              [
                                8399,
                                "Currency Symbols"
                              ]
                            ]
                          ],
                          [
                            8591,
                            [
                              [
                                8447,
                                "Combining Diacritical Marks for Symbols"
                              ],
                              [
                                8591,
                                [
                                  [
                                    8527,
                                    "Letterlike Symbols"
                                  ],
                                  [
                                    8591,
                                    "Number Forms"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ],
      [
        64335,
        [
          [
            12799,
            [
              [
                11359,
                [
                  [
                    9727,
                    [
                      [
                        9279,
                        [
                          [
                            8959,
                            [
                              [
                                8703,
                                "Arrows"
                              ],
                              [
                                8959,
                                "Mathematical Operators"
                              ]
                            ]
                          ],
                          [
                            9279,
                            [
                              [
                                9215,
                                "Miscellaneous Technical"
                              ],
                              [
                                9279,
                                "Control Pictures"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        9727,
                        [
                          [
                            9471,
                            [
                              [
                                9311,
                                "Optical Character Recognition"
                              ],
                              [
                                9471,
                                "Enclosed Alphanumerics"
                              ]
                            ]
                          ],
                          [
                            9727,
                            [
                              [
                                9599,
                                "Box Drawing"
                              ],
                              [
                                9727,
                                [
                                  [
                                    9631,
                                    "Block Elements"
                                  ],
                                  [
                                    9727,
                                    "Geometric Shapes"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    11359,
                    [
                      [
                        10495,
                        [
                          [
                            10175,
                            [
                              [
                                9983,
                                "Miscellaneous Symbols"
                              ],
                              [
                                10175,
                                "Dingbats"
                              ]
                            ]
                          ],
                          [
                            10495,
                            [
                              [
                                10223,
                                "Miscellaneous Mathematical Symbols-A"
                              ],
                              [
                                10495,
                                [
                                  [
                                    10239,
                                    "Supplemental Arrows-A"
                                  ],
                                  [
                                    10495,
                                    "Braille Patterns"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        11359,
                        [
                          [
                            10751,
                            [
                              [
                                10623,
                                "Supplemental Arrows-B"
                              ],
                              [
                                10751,
                                "Miscellaneous Mathematical Symbols-B"
                              ]
                            ]
                          ],
                          [
                            11359,
                            [
                              [
                                11007,
                                "Supplemental Mathematical Operators"
                              ],
                              [
                                11359,
                                [
                                  [
                                    11263,
                                    "Miscellaneous Symbols and Arrows"
                                  ],
                                  [
                                    11359,
                                    "Glagolitic"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                12799,
                [
                  [
                    12255,
                    [
                      [
                        11647,
                        [
                          [
                            11519,
                            [
                              [
                                11391,
                                "Latin Extended-C"
                              ],
                              [
                                11519,
                                "Coptic"
                              ]
                            ]
                          ],
                          [
                            11647,
                            [
                              [
                                11567,
                                "Georgian Supplement"
                              ],
                              [
                                11647,
                                "Tifinagh"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        12255,
                        [
                          [
                            11775,
                            [
                              [
                                11743,
                                "Ethiopic Extended"
                              ],
                              [
                                11775,
                                "Cyrillic Extended-A"
                              ]
                            ]
                          ],
                          [
                            12255,
                            [
                              [
                                11903,
                                "Supplemental Punctuation"
                              ],
                              [
                                12255,
                                [
                                  [
                                    12031,
                                    "CJK Radicals Supplement"
                                  ],
                                  [
                                    12255,
                                    "Kangxi Radicals"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    12799,
                    [
                      [
                        12591,
                        [
                          [
                            12351,
                            [
                              [
                                12287,
                                "Ideographic Description Characters"
                              ],
                              [
                                12351,
                                "CJK Symbols and Punctuation"
                              ]
                            ]
                          ],
                          [
                            12591,
                            [
                              [
                                12447,
                                "Hiragana"
                              ],
                              [
                                12591,
                                [
                                  [
                                    12543,
                                    "Katakana"
                                  ],
                                  [
                                    12591,
                                    "Bopomofo"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        12799,
                        [
                          [
                            12703,
                            [
                              [
                                12687,
                                "Hangul Compatibility Jamo"
                              ],
                              [
                                12703,
                                "Kanbun"
                              ]
                            ]
                          ],
                          [
                            12799,
                            [
                              [
                                12735,
                                "Bopomofo Extended"
                              ],
                              [
                                12799,
                                [
                                  [
                                    12783,
                                    "CJK Strokes"
                                  ],
                                  [
                                    12799,
                                    "Katakana Phonetic Extensions"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ],
          [
            64335,
            [
              [
                43311,
                [
                  [
                    42559,
                    [
                      [
                        19967,
                        [
                          [
                            13311,
                            [
                              [
                                13055,
                                "Enclosed CJK Letters and Months"
                              ],
                              [
                                13311,
                                "CJK Compatibility"
                              ]
                            ]
                          ],
                          [
                            19967,
                            [
                              [
                                19903,
                                "CJK Unified Ideographs Extension A"
                              ],
                              [
                                19967,
                                "Yijing Hexagram Symbols"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        42559,
                        [
                          [
                            42127,
                            [
                              [
                                40959,
                                "CJK Unified Ideographs"
                              ],
                              [
                                42127,
                                "Yi Syllables"
                              ]
                            ]
                          ],
                          [
                            42559,
                            [
                              [
                                42191,
                                "Yi Radicals"
                              ],
                              [
                                42559,
                                [
                                  [
                                    42239,
                                    "Lisu"
                                  ],
                                  [
                                    42559,
                                    "Vai"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    43311,
                    [
                      [
                        43055,
                        [
                          [
                            42751,
                            [
                              [
                                42655,
                                "Cyrillic Extended-B"
                              ],
                              [
                                42751,
                                "Bamum"
                              ]
                            ]
                          ],
                          [
                            43055,
                            [
                              [
                                42783,
                                "Modifier Tone Letters"
                              ],
                              [
                                43055,
                                [
                                  [
                                    43007,
                                    "Latin Extended-D"
                                  ],
                                  [
                                    43055,
                                    "Syloti Nagri"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        43311,
                        [
                          [
                            43135,
                            [
                              [
                                43071,
                                "Common Indic Number Forms"
                              ],
                              [
                                43135,
                                "Phags-pa"
                              ]
                            ]
                          ],
                          [
                            43311,
                            [
                              [
                                43231,
                                "Saurashtra"
                              ],
                              [
                                43311,
                                [
                                  [
                                    43263,
                                    "Devanagari Extended"
                                  ],
                                  [
                                    43311,
                                    "Kayah Li"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                64335,
                [
                  [
                    43887,
                    [
                      [
                        43615,
                        [
                          [
                            43391,
                            [
                              [
                                43359,
                                "Rejang"
                              ],
                              [
                                43391,
                                "Hangul Jamo Extended-A"
                              ]
                            ]
                          ],
                          [
                            43615,
                            [
                              [
                                43487,
                                "Javanese"
                              ],
                              [
                                43615,
                                [
                                  [
                                    43519,
                                    "Myanmar Extended-B"
                                  ],
                                  [
                                    43615,
                                    "Cham"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        43887,
                        [
                          [
                            43743,
                            [
                              [
                                43647,
                                "Myanmar Extended-A"
                              ],
                              [
                                43743,
                                "Tai Viet"
                              ]
                            ]
                          ],
                          [
                            43887,
                            [
                              [
                                43775,
                                "Meetei Mayek Extensions"
                              ],
                              [
                                43887,
                                [
                                  [
                                    43823,
                                    "Ethiopic Extended-A"
                                  ],
                                  [
                                    43887,
                                    "Latin Extended-E"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    64335,
                    [
                      [
                        56191,
                        [
                          [
                            44031,
                            [
                              [
                                43967,
                                "Cherokee Supplement"
                              ],
                              [
                                44031,
                                "Meetei Mayek"
                              ]
                            ]
                          ],
                          [
                            56191,
                            [
                              [
                                55215,
                                "Hangul Syllables"
                              ],
                              [
                                56191,
                                [
                                  [
                                    55295,
                                    "Hangul Jamo Extended-B"
                                  ],
                                  [
                                    56191,
                                    "High Surrogates"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        64335,
                        [
                          [
                            57343,
                            [
                              [
                                56319,
                                "High Private Use Surrogates"
                              ],
                              [
                                57343,
                                "Low Surrogates"
                              ]
                            ]
                          ],
                          [
                            64335,
                            [
                              [
                                63743,
                                "Private Use Area"
                              ],
                              [
                                64335,
                                [
                                  [
                                    64255,
                                    "CJK Compatibility Ideographs"
                                  ],
                                  [
                                    64335,
                                    "Alphabetic Presentation Forms"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  ],
  [
    1114111,
    [
      [
        72031,
        [
          [
            67999,
            [
              [
                66351,
                [
                  [
                    65535,
                    [
                      [
                        65071,
                        [
                          [
                            65039,
                            [
                              [
                                65023,
                                "Arabic Presentation Forms-A"
                              ],
                              [
                                65039,
                                "Variation Selectors"
                              ]
                            ]
                          ],
                          [
                            65071,
                            [
                              [
                                65055,
                                "Vertical Forms"
                              ],
                              [
                                65071,
                                "Combining Half Marks"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        65535,
                        [
                          [
                            65135,
                            [
                              [
                                65103,
                                "CJK Compatibility Forms"
                              ],
                              [
                                65135,
                                "Small Form Variants"
                              ]
                            ]
                          ],
                          [
                            65535,
                            [
                              [
                                65279,
                                "Arabic Presentation Forms-B"
                              ],
                              [
                                65535,
                                [
                                  [
                                    65519,
                                    "Halfwidth and Fullwidth Forms"
                                  ],
                                  [
                                    65535,
                                    "Specials"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    66351,
                    [
                      [
                        65999,
                        [
                          [
                            65791,
                            [
                              [
                                65663,
                                "Linear B Syllabary"
                              ],
                              [
                                65791,
                                "Linear B Ideograms"
                              ]
                            ]
                          ],
                          [
                            65999,
                            [
                              [
                                65855,
                                "Aegean Numbers"
                              ],
                              [
                                65999,
                                [
                                  [
                                    65935,
                                    "Ancient Greek Numbers"
                                  ],
                                  [
                                    65999,
                                    "Ancient Symbols"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        66351,
                        [
                          [
                            66207,
                            [
                              [
                                66047,
                                "Phaistos Disc"
                              ],
                              [
                                66207,
                                "Lycian"
                              ]
                            ]
                          ],
                          [
                            66351,
                            [
                              [
                                66271,
                                "Carian"
                              ],
                              [
                                66351,
                                [
                                  [
                                    66303,
                                    "Coptic Epact Numbers"
                                  ],
                                  [
                                    66351,
                                    "Old Italic"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                67999,
                [
                  [
                    66863,
                    [
                      [
                        66527,
                        [
                          [
                            66431,
                            [
                              [
                                66383,
                                "Gothic"
                              ],
                              [
                                66431,
                                "Old Permic"
                              ]
                            ]
                          ],
                          [
                            66527,
                            [
                              [
                                66463,
                                "Ugaritic"
                              ],
                              [
                                66527,
                                "Old Persian"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        66863,
                        [
                          [
                            66687,
                            [
                              [
                                66639,
                                "Deseret"
                              ],
                              [
                                66687,
                                "Shavian"
                              ]
                            ]
                          ],
                          [
                            66863,
                            [
                              [
                                66735,
                                "Osmanya"
                              ],
                              [
                                66863,
                                [
                                  [
                                    66815,
                                    "Osage"
                                  ],
                                  [
                                    66863,
                                    "Elbasan"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    67999,
                    [
                      [
                        67711,
                        [
                          [
                            67455,
                            [
                              [
                                66927,
                                "Caucasian Albanian"
                              ],
                              [
                                67455,
                                "Linear A"
                              ]
                            ]
                          ],
                          [
                            67711,
                            [
                              [
                                67647,
                                "Cypriot Syllabary"
                              ],
                              [
                                67711,
                                [
                                  [
                                    67679,
                                    "Imperial Aramaic"
                                  ],
                                  [
                                    67711,
                                    "Palmyrene"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        67999,
                        [
                          [
                            67839,
                            [
                              [
                                67759,
                                "Nabataean"
                              ],
                              [
                                67839,
                                "Hatran"
                              ]
                            ]
                          ],
                          [
                            67999,
                            [
                              [
                                67871,
                                "Phoenician"
                              ],
                              [
                                67999,
                                [
                                  [
                                    67903,
                                    "Lydian"
                                  ],
                                  [
                                    67999,
                                    "Meroitic Hieroglyphs"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ],
          [
            72031,
            [
              [
                69759,
                [
                  [
                    68527,
                    [
                      [
                        68255,
                        [
                          [
                            68191,
                            [
                              [
                                68095,
                                "Meroitic Cursive"
                              ],
                              [
                                68191,
                                "Kharoshthi"
                              ]
                            ]
                          ],
                          [
                            68255,
                            [
                              [
                                68223,
                                "Old South Arabian"
                              ],
                              [
                                68255,
                                "Old North Arabian"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        68527,
                        [
                          [
                            68415,
                            [
                              [
                                68351,
                                "Manichaean"
                              ],
                              [
                                68415,
                                "Avestan"
                              ]
                            ]
                          ],
                          [
                            68527,
                            [
                              [
                                68447,
                                "Inscriptional Parthian"
                              ],
                              [
                                68527,
                                [
                                  [
                                    68479,
                                    "Inscriptional Pahlavi"
                                  ],
                                  [
                                    68527,
                                    "Psalter Pahlavi"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    69759,
                    [
                      [
                        69311,
                        [
                          [
                            68863,
                            [
                              [
                                68687,
                                "Old Turkic"
                              ],
                              [
                                68863,
                                "Old Hungarian"
                              ]
                            ]
                          ],
                          [
                            69311,
                            [
                              [
                                68927,
                                "Hanifi Rohingya"
                              ],
                              [
                                69311,
                                [
                                  [
                                    69247,
                                    "Rumi Numeral Symbols"
                                  ],
                                  [
                                    69311,
                                    "Yezidi"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        69759,
                        [
                          [
                            69487,
                            [
                              [
                                69423,
                                "Old Sogdian"
                              ],
                              [
                                69487,
                                "Sogdian"
                              ]
                            ]
                          ],
                          [
                            69759,
                            [
                              [
                                69599,
                                "Chorasmian"
                              ],
                              [
                                69759,
                                [
                                  [
                                    69631,
                                    "Elymaic"
                                  ],
                                  [
                                    69759,
                                    "Brahmi"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                72031,
                [
                  [
                    70527,
                    [
                      [
                        70111,
                        [
                          [
                            69887,
                            [
                              [
                                69839,
                                "Kaithi"
                              ],
                              [
                                69887,
                                "Sora Sompeng"
                              ]
                            ]
                          ],
                          [
                            70111,
                            [
                              [
                                69967,
                                "Chakma"
                              ],
                              [
                                70111,
                                [
                                  [
                                    70015,
                                    "Mahajani"
                                  ],
                                  [
                                    70111,
                                    "Sharada"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        70527,
                        [
                          [
                            70223,
                            [
                              [
                                70143,
                                "Sinhala Archaic Numbers"
                              ],
                              [
                                70223,
                                "Khojki"
                              ]
                            ]
                          ],
                          [
                            70527,
                            [
                              [
                                70319,
                                "Multani"
                              ],
                              [
                                70527,
                                [
                                  [
                                    70399,
                                    "Khudawadi"
                                  ],
                                  [
                                    70527,
                                    "Grantha"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    72031,
                    [
                      [
                        71295,
                        [
                          [
                            70879,
                            [
                              [
                                70783,
                                "Newa"
                              ],
                              [
                                70879,
                                "Tirhuta"
                              ]
                            ]
                          ],
                          [
                            71295,
                            [
                              [
                                71167,
                                "Siddham"
                              ],
                              [
                                71295,
                                [
                                  [
                                    71263,
                                    "Modi"
                                  ],
                                  [
                                    71295,
                                    "Mongolian Supplement"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        72031,
                        [
                          [
                            71487,
                            [
                              [
                                71375,
                                "Takri"
                              ],
                              [
                                71487,
                                "Ahom"
                              ]
                            ]
                          ],
                          [
                            72031,
                            [
                              [
                                71759,
                                "Dogra"
                              ],
                              [
                                72031,
                                [
                                  [
                                    71935,
                                    "Warang Citi"
                                  ],
                                  [
                                    72031,
                                    "Dives Akuru"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ],
      [
        1114111,
        [
          [
            119551,
            [
              [
                92783,
                [
                  [
                    73471,
                    [
                      [
                        72447,
                        [
                          [
                            72271,
                            [
                              [
                                72191,
                                "Nandinagari"
                              ],
                              [
                                72271,
                                "Zanabazar Square"
                              ]
                            ]
                          ],
                          [
                            72447,
                            [
                              [
                                72367,
                                "Soyombo"
                              ],
                              [
                                72447,
                                "Pau Cin Hau"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        73471,
                        [
                          [
                            72895,
                            [
                              [
                                72815,
                                "Bhaiksuki"
                              ],
                              [
                                72895,
                                "Marchen"
                              ]
                            ]
                          ],
                          [
                            73471,
                            [
                              [
                                73055,
                                "Masaram Gondi"
                              ],
                              [
                                73471,
                                [
                                  [
                                    73135,
                                    "Gunjala Gondi"
                                  ],
                                  [
                                    73471,
                                    "Makasar"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    92783,
                    [
                      [
                        75087,
                        [
                          [
                            73727,
                            [
                              [
                                73663,
                                "Lisu Supplement"
                              ],
                              [
                                73727,
                                "Tamil Supplement"
                              ]
                            ]
                          ],
                          [
                            75087,
                            [
                              [
                                74751,
                                "Cuneiform"
                              ],
                              [
                                75087,
                                [
                                  [
                                    74879,
                                    "Cuneiform Numbers and Punctuation"
                                  ],
                                  [
                                    75087,
                                    "Early Dynastic Cuneiform"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        92783,
                        [
                          [
                            78911,
                            [
                              [
                                78895,
                                "Egyptian Hieroglyphs"
                              ],
                              [
                                78911,
                                "Egyptian Hieroglyph Format Controls"
                              ]
                            ]
                          ],
                          [
                            92783,
                            [
                              [
                                83583,
                                "Anatolian Hieroglyphs"
                              ],
                              [
                                92783,
                                [
                                  [
                                    92735,
                                    "Bamum Supplement"
                                  ],
                                  [
                                    92783,
                                    "Mro"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                119551,
                [
                  [
                    101775,
                    [
                      [
                        94111,
                        [
                          [
                            93071,
                            [
                              [
                                92927,
                                "Bassa Vah"
                              ],
                              [
                                93071,
                                "Pahawh Hmong"
                              ]
                            ]
                          ],
                          [
                            94111,
                            [
                              [
                                93855,
                                "Medefaidrin"
                              ],
                              [
                                94111,
                                "Miao"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        101775,
                        [
                          [
                            100351,
                            [
                              [
                                94207,
                                "Ideographic Symbols and Punctuation"
                              ],
                              [
                                100351,
                                "Tangut"
                              ]
                            ]
                          ],
                          [
                            101775,
                            [
                              [
                                101119,
                                "Tangut Components"
                              ],
                              [
                                101775,
                                [
                                  [
                                    101631,
                                    "Khitan Small Script"
                                  ],
                                  [
                                    101775,
                                    "Tangut Supplement"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    119551,
                    [
                      [
                        113823,
                        [
                          [
                            110895,
                            [
                              [
                                110847,
                                "Kana Supplement"
                              ],
                              [
                                110895,
                                "Kana Extended-A"
                              ]
                            ]
                          ],
                          [
                            113823,
                            [
                              [
                                110959,
                                "Small Kana Extension"
                              ],
                              [
                                113823,
                                [
                                  [
                                    111359,
                                    "Nushu"
                                  ],
                                  [
                                    113823,
                                    "Duployan"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        119551,
                        [
                          [
                            119039,
                            [
                              [
                                113839,
                                "Shorthand Format Controls"
                              ],
                              [
                                119039,
                                "Byzantine Musical Symbols"
                              ]
                            ]
                          ],
                          [
                            119551,
                            [
                              [
                                119295,
                                "Musical Symbols"
                              ],
                              [
                                119551,
                                [
                                  [
                                    119375,
                                    "Ancient Greek Musical Notation"
                                  ],
                                  [
                                    119551,
                                    "Mayan Numerals"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ],
          [
            1114111,
            [
              [
                128591,
                [
                  [
                    125279,
                    [
                      [
                        121519,
                        [
                          [
                            119679,
                            [
                              [
                                119647,
                                "Tai Xuan Jing Symbols"
                              ],
                              [
                                119679,
                                "Counting Rod Numerals"
                              ]
                            ]
                          ],
                          [
                            121519,
                            [
                              [
                                120831,
                                "Mathematical Alphanumeric Symbols"
                              ],
                              [
                                121519,
                                "Sutton SignWriting"
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        125279,
                        [
                          [
                            123215,
                            [
                              [
                                122927,
                                "Glagolitic Supplement"
                              ],
                              [
                                123215,
                                "Nyiakeng Puachue Hmong"
                              ]
                            ]
                          ],
                          [
                            125279,
                            [
                              [
                                123647,
                                "Wancho"
                              ],
                              [
                                125279,
                                [
                                  [
                                    125151,
                                    "Mende Kikakui"
                                  ],
                                  [
                                    125279,
                                    "Adlam"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    128591,
                    [
                      [
                        127135,
                        [
                          [
                            126287,
                            [
                              [
                                126143,
                                "Indic Siyaq Numbers"
                              ],
                              [
                                126287,
                                "Ottoman Siyaq Numbers"
                              ]
                            ]
                          ],
                          [
                            127135,
                            [
                              [
                                126719,
                                "Arabic Mathematical Alphabetic Symbols"
                              ],
                              [
                                127135,
                                [
                                  [
                                    127023,
                                    "Mahjong Tiles"
                                  ],
                                  [
                                    127135,
                                    "Domino Tiles"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        128591,
                        [
                          [
                            127487,
                            [
                              [
                                127231,
                                "Playing Cards"
                              ],
                              [
                                127487,
                                "Enclosed Alphanumeric Supplement"
                              ]
                            ]
                          ],
                          [
                            128591,
                            [
                              [
                                127743,
                                "Enclosed Ideographic Supplement"
                              ],
                              [
                                128591,
                                [
                                  [
                                    128511,
                                    "Miscellaneous Symbols and Pictographs"
                                  ],
                                  [
                                    128591,
                                    "Emoticons"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ],
              [
                1114111,
                [
                  [
                    173791,
                    [
                      [
                        129279,
                        [
                          [
                            128767,
                            [
                              [
                                128639,
                                "Ornamental Dingbats"
                              ],
                              [
                                128767,
                                "Transport and Map Symbols"
                              ]
                            ]
                          ],
                          [
                            129279,
                            [
                              [
                                128895,
                                "Alchemical Symbols"
                              ],
                              [
                                129279,
                                [
                                  [
                                    129023,
                                    "Geometric Shapes Extended"
                                  ],
                                  [
                                    129279,
                                    "Supplemental Arrows-C"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        173791,
                        [
                          [
                            129647,
                            [
                              [
                                129535,
                                "Supplemental Symbols and Pictographs"
                              ],
                              [
                                129647,
                                "Chess Symbols"
                              ]
                            ]
                          ],
                          [
                            173791,
                            [
                              [
                                129791,
                                "Symbols and Pictographs Extended-A"
                              ],
                              [
                                173791,
                                [
                                  [
                                    130047,
                                    "Symbols for Legacy Computing"
                                  ],
                                  [
                                    173791,
                                    "CJK Unified Ideographs Extension B"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ],
                  [
                    1114111,
                    [
                      [
                        195103,
                        [
                          [
                            178207,
                            [
                              [
                                177983,
                                "CJK Unified Ideographs Extension C"
                              ],
                              [
                                178207,
                                "CJK Unified Ideographs Extension D"
                              ]
                            ]
                          ],
                          [
                            195103,
                            [
                              [
                                183983,
                                "CJK Unified Ideographs Extension E"
                              ],
                              [
                                195103,
                                [
                                  [
                                    191471,
                                    "CJK Unified Ideographs Extension F"
                                  ],
                                  [
                                    195103,
                                    "CJK Compatibility Ideographs Supplement"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ],
                      [
                        1114111,
                        [
                          [
                            917631,
                            [
                              [
                                201551,
                                "CJK Unified Ideographs Extension G"
                              ],
                              [
                                917631,
                                "Tags"
                              ]
                            ]
                          ],
                          [
                            1114111,
                            [
                              [
                                917999,
                                "Variation Selectors Supplement"
                              ],
                              [
                                1114111,
                                [
                                  [
                                    1048575,
                                    "Supplementary Private Use Area-A"
                                  ],
                                  [
                                    1114111,
                                    "Supplementary Private Use Area-B"
                                  ]
                                ]
                              ]
                            ]
                          ]
                        ]
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  ]
];
const options = {
  tokens: false,
  scopes: true,
  grafts: false,
  requiredScopes: []
};
const blockHasAtts = (docSet, block2, attSpecsArray, attValuesArray, requireAll) => {
  let matched = /* @__PURE__ */ new Set([]);
  for (const item of docSet.unsuccinctifyPrunedItems(block2, options, false)) {
    const [att, attType, element, key, count, value] = item[2].split("/");
    for (const [n, attSpecs] of attSpecsArray.entries()) {
      for (const attSpec of attSpecs) {
        if (attType === attSpec.attType && element === attSpec.tagName && key === attSpec.attKey && parseInt(count) === attSpec.valueN && attValuesArray[n].includes(value)) {
          if (!requireAll) {
            return true;
          }
          matched.add(n);
          break;
        }
      }
      if (matched.size === attSpecsArray.length) {
        return true;
      }
    }
  }
  return false;
};
const unicodeBlock = (c) => {
  const unicodeN = c.charCodeAt(0);
  let tree = unicodeTree;
  while (typeof tree !== "string") {
    const [limit, branch] = tree[0];
    if (unicodeN <= limit) {
      tree = branch;
    } else {
      tree = tree[1][1];
    }
  }
  return tree;
};
const sequenceSchemaString = `
"""A contiguous flow of content"""
type Sequence {
  """The id of the sequence"""
  id: String!
  """The type of the sequence (main, heading...)"""
  type: String!
  """The number of blocks in the sequence"""
  nBlocks: Int!
  """The blocks in the sequence"""
  blocks(
    """Only return blocks where the list of scopes is open"""
    withScopes: [String!]
    """Only return blocks whose zero-indexed position is in the list"""
    positions: [Int!]
    """Only return blocks with the specified block scope (eg 'blockScope/p'"""
    withBlockScope: String
    """Only return blocks that contain items within the specified chapter, verse or chapterVerse range"""
    withScriptureCV: String
    """Ordered list of attribute specs whose values must match those in 'attValues'"""
    attSpecs: [[AttSpec!]!]
    """Ordered list of attribute values, used in conjunction with \\'attSpecs\\'"""
    attValues: [[String!]!]
    """If true, blocks where all attSpecs match will be included"""
    allAtts: Boolean
    """Return blocks containing a token whose payload is an exact match to one of the specified strings"""
    withChars: [String!]
    """Return blocks containing a token whose payload matches the specified regexes"""
    withMatchingChars: [String!]
    """If true, blocks where all regexes match will be included"""
    allChars: Boolean
  ): [Block!]!
  """The items for each block in the sequence"""
  blocksItems: [[Item!]!]
  """The tokens for each block in the sequence"""
  blocksTokens: [[Item!]!]
  """The text for each block in the sequence"""
  blocksText(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): [String!]
  """The text for the sequence"""
  text(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ) : String!
  """Sequence content grouped by scopes or milestones"""
  itemGroups(
    """Produce one itemGroup for every different match of the list of scopes"""
    byScopes: [String!]
    """Start a new itemGroup whenever a milestone in the list is encountered"""
    byMilestones: [String!]
  ) : [ItemGroup!]!
  """A list of the tags of this sequence"""
  tags: [String!]!
  """A list of the tags of this sequence as key/value tuples"""
  tagsKv: [KeyValue!]!
  """Whether or not the sequence has the specified tag"""
  hasTag(
    """The specified tag"""
    tagName: String!
  ): Boolean!
  """A list of wordLike token strings in a main sequence"""
  wordLikes(
    """Whether to coerce the strings (toLower|toUpper|none)"""
    coerceCase: String
  ) : [String!]!
  """A list of token strings the sequence with counts"""
  uniqueTokenCounts(
      """Whether to coerce the strings (toLower|toUpper|none)"""
    coerceCase: String
) : [KeyCount!]!
    """A list of unique characters in the sequence with counts"""
  uniqueCharacterCounts: [KeyCountCategory!]!
  """Returns true if a main sequence contains the specified tokens"""
  hasChars(
    """Token strings to be matched exactly"""
    chars: [String!]
    """If true all tokens must match"""
    allChars: Boolean
  ): Boolean!
  """Returns true if a main sequence contains a match for specified regexes"""
  hasMatchingChars(
    """Regexes to be matched"""
    chars: [String!]
    """If true all regexes must match"""
    allChars: Boolean
  ): Boolean!
}
`;
const sequenceResolvers = {
  nBlocks: (root) => root.blocks.length,
  blocks: (root, args, context) => {
    context.docSet.maybeBuildEnumIndexes();
    if (args.withScopes && args.withScriptureCV) {
      throw new Error("Cannot specify both withScopes and withScriptureCV");
    }
    if (args.attSpecs && !args.attValues) {
      throw new Error("Cannot specify attSpecs without attValues");
    }
    if (!args.attSpecs && args.attValues) {
      throw new Error("Cannot specify attValues without attSpecs");
    }
    if (args.attSpecs && args.attValues && args.attSpecs.length !== args.attValues.length) {
      throw new Error("attSpecs and attValues must be same length");
    }
    if (args.withChars && args.withMatchingChars) {
      throw new Error("Cannot specify both withChars and withMatchingChars");
    }
    let ret = root.blocks;
    if (args.positions) {
      ret = Array.from(ret.entries()).filter((b) => args.positions.includes(b[0])).map((b) => b[1]);
    }
    if (args.withScopes) {
      ret = ret.filter(
        (b) => context.docSet.allScopesInBlock(b, args.withScopes)
      );
    }
    if (args.withScriptureCV) {
      ret = context.docSet.blocksWithScriptureCV(ret, args.withScriptureCV);
    }
    if (args.attSpecs) {
      ret = ret.filter(
        (b) => blockHasAtts(
          context.docSet,
          b,
          args.attSpecs,
          args.attValues,
          args.allAtts || false
        )
      );
    }
    if (args.withBlockScope) {
      ret = ret.filter(
        (b) => context.docSet.blockHasBlockScope(b, args.withBlockScope)
      );
    }
    if (args.withChars) {
      if (root.type === "main" && !sequenceHasChars(context.docSet, root, args.withChars, args.allChars)) {
        return [];
      }
      let charsIndexesArray = exactSearchTermIndexes(
        context.docSet,
        args.withChars,
        args.allChars
      );
      for (const charsIndexes of charsIndexesArray) {
        ret = ret.filter((b) => context.docSet.blockHasChars(b, charsIndexes));
      }
    }
    if (args.withMatchingChars) {
      if (root.type === "main" && !sequenceHasMatchingChars(
        context.docSet,
        root,
        args.withMatchingChars,
        args.allChars
      )) {
        return [];
      }
      let charsIndexesArray = regexSearchTermIndexes(
        context.docSet,
        args.withMatchingChars,
        args.allChars
      );
      for (const charsIndexes of charsIndexesArray) {
        ret = ret.filter((b) => context.docSet.blockHasChars(b, charsIndexes));
      }
    }
    return ret;
  },
  blocksItems: (root, args, context) => root.blocks.map((b) => context.docSet.unsuccinctifyItems(b.c, {}, null)),
  blocksTokens: (root, args, context) => root.blocks.map(
    (b) => context.docSet.unsuccinctifyItems(b.c, { tokens: true }, null)
  ),
  blocksText: (root, args, context) => root.blocks.map((b) => {
    let ret = context.docSet.unsuccinctifyItems(b.c, { tokens: true }, null).map((t) => t[2]).join("");
    if (args.normalizeSpace) {
      ret = ret.replace(/[ \t\n\r]+/g, " ");
    }
    return ret;
  }),
  text: (root, args, context) => {
    let ret = root.blocks.map(
      (b) => context.docSet.unsuccinctifyItems(b.c, { tokens: true }, null).map((t) => t[2]).join("")
    ).join("\n");
    if (args.normalizeSpace) {
      ret = ret.replace(/[ \t\n\r]+/g, " ");
    }
    return ret;
  },
  itemGroups: (root, args, context) => {
    if (args.byScopes && args.byMilestones) {
      throw new Error("Cannot specify both byScopes and byMilestones");
    }
    if (!args.byScopes && !args.byMilestones) {
      throw new Error("Must specify either byScopes or byMilestones");
    }
    if (args.byScopes) {
      return context.docSet.sequenceItemsByScopes(root.blocks, args.byScopes);
    } else {
      return context.docSet.sequenceItemsByMilestones(
        root.blocks,
        args.byMilestones
      );
    }
  },
  tags: (root) => Array.from(root.tags),
  tagsKv: (root) => Array.from(root.tags).map((t) => {
    if (t.includes(":")) {
      return [
        t.substring(0, t.indexOf(":")),
        t.substring(t.indexOf(":") + 1)
      ];
    } else {
      return [t, ""];
    }
  }),
  hasTag: (root, args) => root.tags.has(args.tagName),
  wordLikes: (root, args, context) => {
    if (root.type !== "main") {
      throw new Error(`Only available for the main sequence, not ${root.type}`);
    }
    if (args.coerceCase && !["toLower", "toUpper", "none"].includes(args.coerceCase)) {
      throw new Error(
        `coerceCase, when present, must be 'toLower', 'toUpper' or 'none', not '${args.coerceCase}'`
      );
    }
    context.docSet.maybeBuildEnumIndexes();
    let tokens2 = /* @__PURE__ */ new Set();
    let n = 0;
    for (const b of root.tokensPresent) {
      if (b) {
        const enumOffset = context.docSet.enumIndexes["wordLike"][n];
        let tokenString = context.docSet.enums["wordLike"].countedString(enumOffset);
        if (args.coerceCase === "toLower") {
          tokenString = tokenString.toLowerCase();
        }
        if (args.coerceCase === "toUpper") {
          tokenString = tokenString.toUpperCase();
        }
        tokens2.add(tokenString);
      }
      n++;
    }
    return Array.from(tokens2).sort();
  },
  uniqueCharacterCounts: (root, args, context) => {
    const characters = {};
    root.blocks.forEach(
      (b) => context.docSet.unsuccinctifyItems(b.c, { tokens: true }, null).forEach(
        (t) => {
          const chars = t[2].split("");
          for (const char of chars) {
            characters[char] ? characters[char] += 1 : characters[char] = 1;
          }
        }
      )
    );
    return Object.entries(characters).map((c) => [c[0], c[1], unicodeBlock(c[0])]).sort((a, b) => b[1] - a[1]);
  },
  uniqueTokenCounts: (root, args, context) => {
    const wordlikes = {};
    root.blocks.forEach(
      (b) => context.docSet.unsuccinctifyItems(b.c, { tokens: true }, null).forEach(
        (t) => {
          let wordlike = t[2];
          if (args.coerceCase && !["toLower", "toUpper", "none"].includes(args.coerceCase)) {
            throw new Error(
              `coerceCase, when present, must be 'toLower', 'toUpper' or 'none', not '${args.coerceCase}'`
            );
          }
          if (args.coerceCase === "toLower") {
            wordlike = wordlike.toLowerCase();
          }
          if (args.coerceCase === "toUpper") {
            wordlike = wordlike.toUpperCase();
          }
          wordlikes[wordlike] ? wordlikes[wordlike] += 1 : wordlikes[wordlike] = 1;
        }
      )
    );
    return Object.entries(wordlikes).sort((a, b) => b[1] - a[1]);
  },
  hasChars: (root, args, context) => {
    if (root.type !== "main") {
      throw new Error(`Only available for the main sequence, not ${root.type}`);
    }
    return sequenceHasChars(
      context.docSet,
      root,
      args.chars,
      args.allChars || false
    );
  },
  hasMatchingChars: (root, args, context) => {
    if (root.type !== "main") {
      throw new Error(`Only available for the main sequence, not ${root.type}`);
    }
    return sequenceHasMatchingChars(
      context.docSet,
      root,
      args.chars,
      args.allChars
    );
  }
};
const updatedOpenScopes = (openScopes, items2) => {
  let ret = openScopes;
  for (const item of items2) {
    if (item[0] === "scope") {
      if (item[1] === "start") {
        const existingScopes = ret.filter((s) => s === item[2]);
        if (existingScopes.length === 0) {
          ret.push(item[2]);
        }
      } else {
        ret = ret.filter((s) => s !== item[2]);
      }
    }
  }
  return ret;
};
const do_chapter_cv = (root, context, mainSequence, chapterN, includeContext) => {
  const ci = root.chapterIndex(chapterN);
  if (ci) {
    const block2 = mainSequence.blocks[ci.startBlock];
    if (block2) {
      return [
        [
          updatedOpenScopes(
            context.docSet.unsuccinctifyScopes(block2.os).map((s) => s[2]),
            context.docSet.unsuccinctifyItems(block2.c, {}, 0, []).slice(0, ci.startItem + 1).filter((i) => i[0] === "scope")
          ),
          context.docSet.itemsByIndex(mainSequence, ci, includeContext || false).reduce((a, b) => a.concat([["token", "lineSpace", " "]].concat(b)))
        ]
      ];
    } else {
      return [];
    }
  } else {
    return [];
  }
};
const do_chapter_verse_array = (root, context, mainSequence, chapterN, verses, includeContext, doMap, mappedDocSetId) => {
  let docSet = context.docSet;
  let book = root.headers.bookCode;
  let chapterVerses = verses.map((v) => [parseInt(chapterN), parseInt(v)]);
  if (doMap) {
    const mappedDocSet = root.processor.docSets[mappedDocSetId];
    if (mappedDocSet) {
      docSet = mappedDocSet;
    }
    if ("forward" in mainSequence.verseMapping && chapterN in mainSequence.verseMapping.forward) {
      let mappings = [];
      for (const verse of verses) {
        mappings.push(
          utils.versification.mapVerse(
            mainSequence.verseMapping.forward[chapterN],
            root.headers.bookCode,
            chapterN,
            verse
          )
        );
      }
      const mapping = mappings[0];
      book = mapping[0];
      chapterVerses = mapping[1];
    }
    const mappedDocument = docSet.documentWithBook(book);
    if (mappedDocument) {
      const mappedMainSequence = mappedDocument.sequences[mappedDocument.mainId];
      if (mappedMainSequence.verseMapping && "reversed" in mappedMainSequence.verseMapping) {
        const doubleMappings = [];
        for (const [origC, origV] of chapterVerses) {
          if (`${origC}` in mappedMainSequence.verseMapping.reversed) {
            doubleMappings.push(
              utils.versification.mapVerse(
                mappedMainSequence.verseMapping.reversed[`${origC}`],
                book,
                origC,
                origV
              )
            );
          } else {
            doubleMappings.push([book, [[origC, origV]]]);
          }
          book = doubleMappings[0][0];
          chapterVerses = doubleMappings.map((bcv) => bcv[1]).reduce((a, b) => a.concat(b));
        }
      }
    }
  }
  const cvis = {};
  const document = docSet.documentWithBook(book);
  if (!document) {
    return [];
  }
  const documentMainSequence = document.sequences[document.mainId];
  for (const chapter of chapterVerses.map((cv) => cv[0])) {
    if (!(chapter in cvis)) {
      cvis[chapter] = document.chapterVerseIndex(chapter);
    }
  }
  const retItemGroups = [];
  for (const [chapter, verse] of chapterVerses) {
    if (cvis[chapter]) {
      let retItems = [];
      let firstStartBlock = 0;
      let firstStartItem = 0;
      if (cvis[chapter][verse]) {
        for (const ve of cvis[chapter][verse]) {
          if (!firstStartBlock) {
            firstStartBlock = ve.startBlock;
            firstStartItem = ve.startItem;
          }
          retItems = retItems.concat(
            docSet.itemsByIndex(documentMainSequence, ve, includeContext || null).reduce(
              (a, b) => a.concat([["token", "lineSpace", " "]].concat(b))
            )
          );
        }
        const block2 = documentMainSequence.blocks[firstStartBlock];
        retItemGroups.push(block2 ? [
          updatedOpenScopes(
            docSet.unsuccinctifyScopes(block2.os).map((s) => s[2]),
            docSet.unsuccinctifyItems(block2.c, {}, 0, []).slice(0, firstStartItem + 1).filter((i) => i[0] === "scope")
          ),
          retItems
        ] : []);
      }
    }
  }
  return retItemGroups;
};
const scopesMatchAChapterSpec = (scopes, chapterSpecs) => {
  if (chapterSpecs.length === 0) {
    return false;
  } else if (scopes.includes(`chapter/${chapterSpecs[0][0]}`) && (!chapterSpecs[0][1] || scopes.filter(
    (s) => s.startsWith("verse/") && parseInt(s.split("/")[1]) >= chapterSpecs[0][1]
  ).length > 0) && (!chapterSpecs[0][2] || scopes.filter(
    (s) => s.startsWith("verse/") && parseInt(s.split("/")[1]) <= chapterSpecs[0][2]
  ).length > 0)) {
    return true;
  } else {
    return scopesMatchAChapterSpec(scopes, chapterSpecs.slice(1));
  }
};
const do_chapterVerses = (root, context, mainSequence, fromCV, toCV, includeContext) => {
  const [fromCInt, fromVInt] = fromCV.split(":").map((str) => parseInt(str));
  const [toCInt, toVInt] = toCV.split(":").map((str) => parseInt(str));
  if (toCInt < fromCInt) {
    throw new Error(
      `cv chapterVerses requires fromChapter <= toChapter, not ${fromCInt} to ${toCInt}`
    );
  }
  const chapterSpecs = [];
  let ch = fromCInt;
  while (ch <= toCInt) {
    chapterSpecs.push([
      ch,
      ch === fromCInt ? fromVInt : null,
      ch === toCInt ? toVInt : null
    ]);
    ch++;
  }
  return context.docSet.sequenceItemsByScopes(
    mainSequence.blocks,
    ["chapter/", "verse/"],
    includeContext
  ).filter((ig) => scopesMatchAChapterSpec(ig[0], chapterSpecs));
};
const do_cv_separate_args = (root, args, context, mainSequence, doMap, mappedDocSetId) => {
  if (args.chapter && !args.verses) {
    return do_chapter_cv(
      root,
      context,
      mainSequence,
      args.chapter,
      args.includeContext
    );
  } else if (args.verses) {
    return do_chapter_verse_array(
      root,
      context,
      mainSequence,
      args.chapter,
      args.verses,
      args.includeContext,
      doMap,
      mappedDocSetId
    );
  } else {
    throw new Error("Unexpected args to do_cv_separate_args");
  }
};
const do_cv_string_arg = (root, args, context, mainSequence) => {
  if (XRegExp.test(args.chapterVerses, XRegExp("^[0-9]+:[0-9]+-[0-9]+:[0-9]+$"))) {
    const [fromSpec, toSpec] = args.chapterVerses.split("-");
    return do_chapterVerses(
      root,
      context,
      mainSequence,
      fromSpec,
      toSpec,
      args.includeContext
    );
  } else if (XRegExp.test(args.chapterVerses, XRegExp("^[0-9]+:[0-9]+-[0-9]+$"))) {
    const [ch, vRange] = args.chapterVerses.split(":");
    const [fromV, toV] = vRange.split("-");
    return do_chapterVerses(
      root,
      context,
      mainSequence,
      `${ch}:${fromV}`,
      `${ch}:${toV}`,
      args.includeContext
    );
  } else if (XRegExp.test(args.chapterVerses, XRegExp("^[0-9]+:[0-9]+$"))) {
    const [ch, v] = args.chapterVerses.split(":");
    return do_chapterVerses(
      root,
      context,
      mainSequence,
      `${ch}:${v}`,
      `${ch}:${v}`,
      args.includeContext
    );
  } else if (XRegExp.test(args.chapterVerses, XRegExp("^[0-9]+$"))) {
    const ch = args.chapterVerses;
    const cvi = root.chapterVerseIndex(ch);
    if (!cvi) {
      throw new Error(`No chapter ${ch} found`);
    }
    const verseNs = cvi.map((c, n) => [n, c]).filter((nc) => nc[1].length > 0).map((nc) => nc[0]);
    return do_chapterVerses(
      root,
      context,
      mainSequence,
      `${ch}:${Math.min(verseNs)}`,
      `${ch}:${Math.max(verseNs)}`,
      args.includeContext
    );
  } else {
    throw new Error(
      `Could not parse chapterVerses string '${args.chapterVerses}'`
    );
  }
};
const do_cv = (root, args, context, doMap, mappedDocSetId) => {
  context.docSet = root.processor.docSets[root.docSetId];
  const mainSequence = root.sequences[root.mainId];
  if (!args.chapter && !args.chapterVerses) {
    throw new Error("Must specify either chapter or chapterVerses for cv");
  }
  if (args.chapter && args.chapterVerses) {
    throw new Error("Must not specify both chapter and chapterVerses for cv");
  }
  if (args.chapterVerses && args.verses) {
    throw new Error("Must not specify both chapterVerses and verses for cv");
  }
  if (args.chapter) {
    return do_cv_separate_args(
      root,
      args,
      context,
      mainSequence,
      doMap,
      mappedDocSetId
    );
  } else {
    return do_cv_string_arg(root, args, context, mainSequence);
  }
};
const headerById = (root, id2) => id2 in root.headers ? root.headers[id2] : null;
const documentSchemaString = `
"""A document, typically corresponding to USFM for one book"""
type Document {
  """The id of the document"""
  id: String!
  """A parsed version of the id header"""
  idParts: idParts!
  """The id of the docSet to which this document belongs"""
  docSetId: String!
  """USFM header information such as TOC"""
  headers: [KeyValue!]!
  """One USFM header"""
  header(
    """The header id, corresponding to the tag name minus any trailing '1'"""
    id: String!
  ): String
  """The main sequence"""
  mainSequence: Sequence!
  """The number of sequences"""
  nSequences: Int!
  """A list of sequences for this document"""
  sequences(
    """ids of sequences to include, if found"""
    ids: [String!]
    """types of sequences to include, if found"""
    types: [String!]
    """Only return sequences with all the specified tags"""
    withTags: [String!]
    """Only return sequences with none of the specified tags"""
    withoutTags: [String!]
  ): [Sequence!]!
  """A list of table sequences for this document"""
  tableSequences(
    """ids of sequences to include, if found"""
    ids: [String!]
    """Only return sequences with all the specified tags"""
    withTags: [String!]
    """Only return sequences with none of the specified tags"""
    withoutTags: [String!]
  ): [tableSequence!]!
  """A list of tree sequences for this document"""
  treeSequences(
    """ids of sequences to include, if found"""
    ids: [String!]
    """Only return sequences with all the specified tags"""
    withTags: [String!]
    """Only return sequences with none of the specified tags"""
    withoutTags: [String!]
  ): [treeSequence!]!
  """A list of key-value sequences for this document"""
  kvSequences(
    """ids of sequences to include, if found"""
    ids: [String!]
    """Only return sequences with all the specified tags"""
    withTags: [String!]
    """Only return sequences with none of the specified tags"""
    withoutTags: [String!]
  ): [kvSequence!]!
  """A list of text (ie non-table, non-tree, non-kv) sequences for this document"""
  textSequences(
    """ids of sequences to include, if found"""
    ids: [String!]
    """Only return sequences with all the specified tags"""
    withTags: [String!]
    """Only return sequences with none of the specified tags"""
    withoutTags: [String!]
  ): [Sequence!]!
  """The sequence with the specified id"""
  sequence(
    """id of the sequence"""
    id: String!
  ): Sequence
  """The table sequence with the specified id"""
  tableSequence(
    """id of the sequence"""
    id: String!
  ): tableSequence
  """The tree sequence with the specified id"""
  treeSequence(
    """id of the sequence"""
    id: String!
  ): treeSequence
  """The key-value sequence with the specified id"""
  kvSequence(
    """id of the sequence"""
    id: String!
  ): kvSequence
  """The blocks of the main sequence"""
  mainBlocks: [Block!]!
  """The items for each block of the main sequence"""
  mainBlocksItems: [[Item!]!]!
  """The tokens for each block of the main sequence"""
  mainBlocksTokens: [[Item!]!]!
  """The text for each block of the main sequence"""
  mainBlocksText(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): [String!]!
  """The text for the main sequence"""
  mainText(
    """If true, converts each whitespace character to a single space"""
    normalizeSpace: Boolean
  ): String!
  """A list of the tags of this document"""
  tags: [String!]!
  """A list of the tags of this document as key/value tuples"""
  tagsKv: [KeyValue!]!
  """'Whether or not the document has the specified tag"""
  hasTag(
    tagName: String!
  ): Boolean!
  """Content for a Scripture reference within this document, using local versification"""
  cv(
    """The chapter number (as a string)"""
    chapter: String
    """'A list of verse numbers (as strings)"""
    verses: [String!]
    """A chapterVerse Reference (ch:v-ch:v)"""
    chapterVerses: String
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
  ): [ItemGroup!]!
  """Content for a Scripture reference within this document, using the versification of the specified docSet"""
  mappedCv(
    """The chapter number (as a string)"""
    chapter: String!
    """The id of the mapped docSet"""
    mappedDocSetId: String!
    """A list of verse numbers (as strings)"""
    verses: [String!]!
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
  ): [ItemGroup!]!
  """Content for each verse of a chapter within this document, using the versification of the specified docSet"""
  mappedCvs(
    """The chapter number (as a string)"""
    chapter: String!
    """The id of the mapped docSet"""
    mappedDocSetId: String!
    """If true, adds scope and nextToken information to each token"""
    includeContext: Boolean
  ): [[ItemGroup!]!]!
  """What's previous and next with respect to the specified verse"""
  cvNavigation(
    """The chapter number (as a string)"""
    chapter: String!
    """A verse number (as a string)"""
    verse: String!
  ): cvNavigation
  """The content of the main sequence indexed by chapterVerse"""
  cvIndexes: [cvIndex]!
  """The content of the specified chapter indexed by chapterVerse"""
  cvIndex(
    """The chapter number"""
    chapter: Int!
  ): cvIndex!
  """The content of the main sequence indexed by chapter"""
  cIndexes: [cIndex]!
  """The content of a chapter"""
  cIndex(
    """'The chapter number"""
    chapter: Int!
  ): cIndex!
  """Verses matching the arguments"""
  cvMatching(
    """Return verses containing a token whose payload is an exact match to one of the specified strings"""
    withChars: [String!]
    """Return verses containing a token whose payload matches the specified regexes"""
    withMatchingChars: [String!]
    """Only return blocks where the list of scopes is open"""
    withScopes: [String!]
    """If true, verses where all regexes match will be included"""
    allChars: Boolean
    """If true, verses where all scopes match will be included"""
    allScopes: Boolean
  ): [ItemGroup!]!
  """A string of PERF JSON for this document"""
  perf(
    """Format JSON string with this indent"""
    indent: Int
  ): String! 
  """A string of USJ JSON for this document"""
  usj(
    """Format JSON string with this indent"""
    indent: Int
  ): String! 
  """A string of USFM for this document"""
  usfm: String! 
  """A string of SOFRIA JSON for this document"""
  sofria(
    """Format JSON string with this indent"""
    indent: Int
    """Return SOFRIA for this chapter only"""
    chapter: Int
  ): String! 
}
`;
const documentResolvers = {
  idParts: (root) => {
    const idHeader = headerById(root, "id");
    if (!idHeader) {
      return [null, null];
    }
    const periphMatch = XRegExp.exec(
      idHeader,
      /^(P\d\d)\s+([A-Z0-6]{3})\s+(\S+)\s+-\s+(.*)/
    );
    if (periphMatch) {
      return ["periph", periphMatch.slice(1)];
    }
    const bookMatch = XRegExp.exec(idHeader, /^([A-Z0-6]{3})\s+(.*)/);
    if (bookMatch) {
      return ["book", bookMatch.slice(1)];
    }
    return [null, [idHeader]];
  },
  headers: (root) => Object.entries(root.headers),
  header: (root, args) => headerById(root, args.id),
  mainSequence: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return root.sequences[root.mainId];
  },
  nSequences: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return Object.keys(root.sequences).length;
  },
  sequences: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    if (args.ids) {
      ret = ret.filter((s) => args.ids.includes(s.id));
    }
    if (args.types) {
      ret = ret.filter((s) => args.types.includes(s.type));
    }
    if (args.withTags) {
      ret = ret.filter(
        (s) => args.withTags.filter((t) => s.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (s) => args.withoutTags.filter((t) => s.tags.has(t)).length === 0
      );
    }
    return ret;
  },
  tableSequences: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => s.type === "table");
    if (args.ids) {
      ret = ret.filter((s) => args.ids.includes(s.id));
    }
    if (args.withTags) {
      ret = ret.filter(
        (s) => args.withTags.filter((t) => s.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (s) => args.withoutTags.filter((t) => s.tags.has(t)).length === 0
      );
    }
    return ret;
  },
  treeSequences: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => s.type === "tree");
    if (args.ids) {
      ret = ret.filter((s) => args.ids.includes(s.id));
    }
    if (args.withTags) {
      ret = ret.filter(
        (s) => args.withTags.filter((t) => s.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (s) => args.withoutTags.filter((t) => s.tags.has(t)).length === 0
      );
    }
    return ret;
  },
  kvSequences: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => s.type === "kv");
    if (args.ids) {
      ret = ret.filter((s) => args.ids.includes(s.id));
    }
    if (args.withTags) {
      ret = ret.filter(
        (s) => args.withTags.filter((t) => s.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (s) => args.withoutTags.filter((t) => s.tags.has(t)).length === 0
      );
    }
    return ret;
  },
  textSequences: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter(
      (s) => s.type !== "tree" && s.type !== "table" && s.type !== "kv"
    );
    if (args.ids) {
      ret = ret.filter((s) => args.ids.includes(s.id));
    }
    if (args.withTags) {
      ret = ret.filter(
        (s) => args.withTags.filter((t) => s.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (s) => args.withoutTags.filter((t) => s.tags.has(t)).length === 0
      );
    }
    return ret;
  },
  sequence: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => args.id.includes(s.id));
    return ret[0] || null;
  },
  tableSequence: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => args.id.includes(s.id));
    if (ret[0] && ret[0].type !== "table") {
      throw new Error(
        `Expected sequence id ${ret[0].id} to be of type 'table', not '${ret[0].type}'`
      );
    }
    return ret[0] || null;
  },
  treeSequence: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => args.id.includes(s.id));
    if (ret[0] && ret[0].type !== "tree") {
      throw new Error(
        `Expected sequence id ${ret[0].id} to be of type 'tree', not '${ret[0].type}'`
      );
    }
    return ret[0] || null;
  },
  kvSequence: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    let ret = Object.values(root.sequences);
    ret = ret.filter((s) => args.id.includes(s.id));
    if (ret[0] && ret[0].type !== "vk") {
      throw new Error(
        `Expected sequence id ${ret[0].id} to be of type 'kv', not '${ret[0].type}'`
      );
    }
    return ret[0] || null;
  },
  mainBlocks: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return root.sequences[root.mainId].blocks;
  },
  mainBlocksItems: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return root.sequences[root.mainId].blocks.map(
      (b) => context.docSet.unsuccinctifyItems(b.c, {}, null)
    );
  },
  mainBlocksTokens: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return root.sequences[root.mainId].blocks.map(
      (b) => context.docSet.unsuccinctifyItems(b.c, { tokens: true }, null)
    );
  },
  mainBlocksText: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return root.sequences[root.mainId].blocks.map((b) => {
      const tokens2 = context.docSet.unsuccinctifyItems(
        b.c,
        { tokens: true },
        null
      );
      let ret = tokens2.map((t) => t[2]).join("").trim();
      if (args.normalizeSpace) {
        ret = ret.replace(/[ \t\n\r]+/g, " ");
      }
      return ret;
    });
  },
  mainText: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    return root.sequences[root.mainId].blocks.map((b) => {
      const tokens2 = context.docSet.unsuccinctifyItems(
        b.c,
        { tokens: true },
        null
      );
      let ret = tokens2.map((t) => t[2]).join("").trim();
      if (args.normalizeSpace) {
        ret = ret.replace(/[ \t\n\r]+/g, " ");
      }
      return ret;
    }).join("\n");
  },
  tags: (root) => Array.from(root.tags),
  tagsKv: (root) => Array.from(root.tags).map((t) => {
    if (t.includes(":")) {
      return [
        t.substring(0, t.indexOf(":")),
        t.substring(t.indexOf(":") + 1)
      ];
    } else {
      return [t, ""];
    }
  }),
  hasTag: (root, args) => root.tags.has(args.tagName),
  cv: (root, args, context) => do_cv(root, args, context, false),
  mappedCv: (root, args, context) => {
    if (args.verses.length !== 1) {
      throw new Error(
        `mappedCv expects exactly one verse, not ${args.verses.length}`
      );
    }
    return do_cv(root, args, context, true, args.mappedDocSetId);
  },
  mappedCvs: (root, args, context) => {
    const cvIndex = root.chapterVerseIndex(args.chapter);
    const verses = cvIndex.filter((ve) => ve.length > 0).map((ve) => ve[0].verses);
    let ret = [];
    for (const verse of verses) {
      ret.push(
        do_cv(
          root,
          {
            ...args,
            verses: [verse]
          },
          context,
          true,
          args.mappedDocSetId
        ).map((ig) => [
          [`fromChapter/${args.chapter}`, `fromVerse/${verse}`, ...ig[0]],
          ig[1]
        ])
      );
    }
    return ret;
  },
  cvNavigation: (root, args) => [
    args.chapter,
    args.verse,
    root.chapterVerseIndex((parseInt(args.chapter) - 1).toString()),
    root.chapterVerseIndex(args.chapter),
    root.chapterVerseIndex((parseInt(args.chapter) + 1).toString())
  ],
  cvIndexes: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    context.doc = root;
    return Object.entries(root.chapterVerseIndexes());
  },
  cvIndex: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    context.doc = root;
    return [args.chapter, root.chapterVerseIndex(args.chapter) || []];
  },
  cIndexes: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    context.doc = root;
    return Object.entries(root.chapterIndexes());
  },
  cIndex: (root, args, context) => {
    context.docSet = root.processor.docSets[root.docSetId];
    context.doc = root;
    const ci = root.chapterIndex(args.chapter);
    return [args.chapter, ci || {}];
  },
  cvMatching: (root, args, context) => {
    if (!args.withChars && !args.withMatchingChars && !args.withScopes) {
      throw new Error(
        "Must specify at least one of withChars or withMatchingChars or withScopes"
      );
    }
    if (args.withChars && args.withMatchingChars) {
      throw new Error("Must not specify both withChars and withMatchingChars");
    }
    context.docSet = root.processor.docSets[root.docSetId];
    let charsRegexes;
    if (args.withChars && args.allChars) {
      charsRegexes = args.withChars.map((s) => XRegExp(`^${s}$`));
    } else if (args.withChars) {
      charsRegexes = [XRegExp.union(args.withChars.map((s) => XRegExp(`^${s}$`, "i")))];
    } else if (args.withMatchingChars && args.allChars) {
      charsRegexes = args.withMatchingChars.map((s) => XRegExp(s, "i"));
    } else if (args.withMatchingChars) {
      charsRegexes = [
        XRegExp.union(args.withMatchingChars.map((s) => XRegExp(s, "i")))
      ];
    }
    const allScopesInGroup = (scopes) => {
      for (const expectedScope of args.withScopes || []) {
        if (!scopes.includes(expectedScope)) {
          return false;
        }
      }
      return true;
    };
    const anyScopesInGroup = (scopes) => {
      const expectedScopes = args.withScopes || [];
      for (const expectedScope of expectedScopes) {
        if (scopes.includes(expectedScope)) {
          return true;
        }
      }
      return expectedScopes.length === 0;
    };
    const allRegexesInGroup = (items2) => {
      for (const regex of charsRegexes || []) {
        let found = false;
        for (const item of items2) {
          if (XRegExp.test(item[2], regex)) {
            found = true;
            break;
          }
        }
        if (!found) {
          return false;
        }
      }
      return true;
    };
    const itemGroups = context.docSet.sequenceItemsByScopes(
      root.sequences[root.mainId].blocks,
      ["chapter/", "verses/"]
    );
    return itemGroups.filter(
      (ig) => (args.allScopes ? allScopesInGroup : anyScopesInGroup)(
        ig[1].filter((i) => i[0] === "scope" && i[1] === "start").map((s) => s[2])
      ) && allRegexesInGroup(ig[1])
    );
  },
  perf: (root, args) => root.perf(args.indent),
  usfm: (root) => root.usfm(),
  usj: (root, args) => root.usj(args.indent),
  sofria: (root, args) => root.sofria(args.indent, args.chapter)
};
const ptCompare = (a, b) => {
  const bcA = a.headers.bookCode || "GEN";
  const bcB = b.headers.bookCode || "GEN";
  const posA = utils.canons.ptBooks[bcA] ? utils.canons.ptBooks[bcA].position : 999;
  const posB = utils.canons.ptBooks[bcB] ? utils.canons.ptBooks[bcB].position : 999;
  return posA - posB;
};
const alphaCompare = (a, b) => {
  const bcA = a.headers.bookCode || "GEN";
  const bcB = b.headers.bookCode || "GEN";
  return bcA.localeCompare(bcB);
};
const alpha2Compare = (a, b) => {
  const digits = [1, 2, 3, 4, 5, 6];
  let bcA = a.headers.bookCode || "GEN";
  if (digits.includes(bcA[0])) {
    bcA = bcA.substring(1) + bcA[0];
  }
  let bcB = b.headers.bookCode || "GEN";
  if (digits.includes(bcB[0])) {
    bcB = bcB.substring(1) + bcB[0];
  }
  return bcA.localeCompare(bcB);
};
const bookCodeCompareFunctions = {
  paratext: ptCompare,
  alpha: alphaCompare,
  alpha2: alpha2Compare
};
const docSetSchemaString = `
"""A collection of documents that share the same set of selector values"""
type DocSet {
  """The id of the docSet, which is formed by concatenating the docSet's selector values"""
  id: String!
  """The selectors of the docSet"""
  selectors: [KeyValue!]!
  """A selector for this docSet"""
  selector(
    """The id of the selector"""
    id: String!
  ): String!
  """A list of the tags of this docSet"""
  tags: [String!]!
  """A list of the tags of this docSet as key/value tuples"""
  tagsKv: [KeyValue!]!
  """Whether or not the docSet has the specified tag"""
  hasTag(
    """The tag"""
    tagName: String!
  ): Boolean!
  """The documents in the docSet"""
  documents(
    """A whitelist of ids of documents to include"""
    ids: [String!]
    """A whitelist of ids of documents to include"""
    withChars: [String!]
    """Return documents whose main sequence contains a token whose payload is an exact match to one of the specified strings"""
    withMatchingChars: [String!]
    """If true, documents where all search terms match will be included"""
    allChars: Boolean
    """Only return documents where the list of scopes is used"""
    withScopes: [String!]
    """If true, documents where all scopes are found will be included"""
    allScopes: Boolean
    """Only return documents with the specified header key/values"""
    withHeaderValues: [InputKeyValue!]
    """Only return documents with all the specified tags"""
    withTags: [String!]
    """Only return documents with none of the specified tags"""
    withoutTags: [String!]
    """Sort returned documents by the designated method (currently ${Object.keys(
  bookCodeCompareFunctions
).join(", ")})\`"""
    sortedBy: String
  ): [Document!]!
  """The number of documents in the docSet"""
  nDocuments: Int!
  """A document in the docSet, if present"""
  document(
    """The book code of the required document"""
    bookCode: String!
  ): Document
  """Whether the docSet has versification information loaded"""
  hasMapping: Boolean!
  """The internal index number corresponding to a string in a given docSet enum"""
  enumIndexForString(
    """The enum to be searched"""
    enumType: String!
    """The string to match"""
    searchString: String!
  ): Int!
  """Information about internal indexes matching the case-insensitive regex in a given docSet enum"""
  enumRegexIndexesForString(
    """The enum to be searched"""
    enumType: String!
    """The regex to match"""
    searchRegex: String!
  ): [regexIndex!]!
  """A list of wordLike token strings in the docSet"""
  wordLikes(
    """Whether to coerce the strings (toLower|toUpper|none)"""
    coerceCase: String
  ): [String!]!
  """A list of unique characters in the docSet"""
  uniqueChars: [String!]!
  """A string containing the unique characters in the docSet"""
  uniqueCharsString: String!
  }
`;
const docSetResolvers = {
  selectors: (root) => Object.entries(root.selectors),
  selector: (root, args) => root.selectors[args.id],
  tags: (root) => Array.from(root.tags),
  tagsKv: (root) => Array.from(root.tags).map((t) => {
    if (t.includes(":")) {
      return [
        t.substring(0, t.indexOf(":")),
        t.substring(t.indexOf(":") + 1)
      ];
    } else {
      return [t, ""];
    }
  }),
  hasTag: (root, args) => root.tags.has(args.tagName),
  documents: (root, args, context) => {
    const headerValuesMatch = (docHeaders, requiredHeaders) => {
      for (const requiredHeader of requiredHeaders || []) {
        if (!(requiredHeader.key in docHeaders) || docHeaders[requiredHeader.key] !== requiredHeader.value) {
          return false;
        }
      }
      return true;
    };
    if (args.withChars && args.withMatchingChars) {
      throw new Error("Cannot specify both withChars and withMatchingChars");
    }
    context.docSet = root;
    let ret = root.documents();
    if (args.ids) {
      ret = ret.filter((d) => args.ids.includes(d.id));
    }
    if (args.withChars) {
      ret = ret.filter(
        (d) => sequenceHasChars(
          root,
          d.sequences[d.mainId],
          args.withChars,
          args.allChars
        )
      );
    }
    if (args.withMatchingChars) {
      ret = ret.filter(
        (d) => sequenceHasMatchingChars(
          root,
          d.sequences[d.mainId],
          args.withMatchingChars,
          args.allChars
        )
      );
    }
    if (args.withScopes) {
      const allSequenceScopes = (doc) => new Set(
        doc.sequences[doc.mainId].blocks.map((b) => context.docSet.unsuccinctifyBlockScopeLabelsSet(b)).map((s) => Array.from(s)).reduce((a, b) => a.concat(b))
      );
      ret = ret.filter((d) => {
        const docScopes = allSequenceScopes(d);
        const minHits = args.allScopes ? args.withScopes.length : 1;
        return args.withScopes.filter((s) => docScopes.has(s)).length >= minHits;
      });
    }
    if (args.withHeaderValues) {
      ret = ret.filter(
        (d) => headerValuesMatch(d.headers, args.withHeaderValues)
      );
    }
    if (args.withTags) {
      ret = ret.filter(
        (d) => args.withTags.filter((t) => d.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (d) => args.withoutTags.filter((t) => d.tags.has(t)).length === 0
      );
    }
    if (args.sortedBy) {
      if (!(args.sortedBy in bookCodeCompareFunctions)) {
        throw new Error(
          `sortedBy value must be one of [${Object.keys(
            bookCodeCompareFunctions
          )}], not ${args.sortedBy}`
        );
      }
      ret.sort(bookCodeCompareFunctions[args.sortedBy]);
    }
    return ret;
  },
  nDocuments: (root, args, context) => {
    context.docSet = root;
    return root.documents().length;
  },
  document: (root, args) => root.documentWithBook(args.bookCode),
  hasMapping: (root) => root.tags.has("hasMapping"),
  enumIndexForString: (root, args) => utils.enums.enumStringIndex(root.enums[args.enumType], args.searchString),
  enumRegexIndexesForString: (root, args) => utils.enums.enumRegexIndexTuples(
    root.enums[args.enumType],
    args.searchRegex
  ),
  wordLikes: (root, args) => {
    if (args.coerceCase && !["toLower", "toUpper", "none"].includes(args.coerceCase)) {
      throw new Error(
        `coerceCase, when present, must be 'toLower', 'toUpper' or 'none', not '${args.coerceCase}'`
      );
    }
    let tokens2 = utils.succinct.unpackEnum(root.enums.wordLike);
    if (args.coerceCase === "toLower") {
      tokens2 = tokens2.map((t) => t.toLowerCase());
    }
    if (args.coerceCase === "toUpper") {
      tokens2 = tokens2.map((t) => t.toUpperCase());
    }
    return Array.from(new Set(tokens2));
  },
  uniqueChars: (root) => {
    const retSet = /* @__PURE__ */ new Set([]);
    for (const token of [
      ...utils.succinct.unpackEnum(root.enums.wordLike),
      ...utils.succinct.unpackEnum(root.enums.notWordLike)
    ]) {
      for (const char of token.split("")) {
        retSet.add(char);
      }
    }
    return Array.from(retSet).sort();
  },
  uniqueCharsString: (root) => {
    const retSet = /* @__PURE__ */ new Set([]);
    for (const token of [
      ...utils.succinct.unpackEnum(root.enums.wordLike),
      ...utils.succinct.unpackEnum(root.enums.notWordLike)
    ]) {
      for (const char of token.split("")) {
        retSet.add(char);
      }
    }
    return Array.from(retSet).sort().join("");
  }
};
const vrs = `# Versification  "English"
# Version=2.0
#
# modifications by Reinier de Blois 13/March/2012
# modified mappings Psalms by adding verse #0 to the mappings
# many of the subscripts that are part of verses 1,2 in the original text end up as verse #0 in English translations

# modifications by Studge 26/June/2009
# book definitions are for all books printed in any English of Spanish Bible
# this includes books for Protestant, Catholic and Protestant-Catholic-EasternOrthodox Interconfessional editions
#
# This is the versification used by most English (e.g. RSV) and Spanish Bibles (e.g. RVR)
#
# List of books, chapters, verses
# One line per book.
# One entry for each chapter.
# Verse number is the maximum verse number for that chapter.
# See the lines containing ='s below for verse mappings.
#
#--------------------------------------------------
# Old Testament
GEN 1:31 2:25 3:24 4:26 5:32 6:22 7:24 8:22 9:29 10:32 11:32 12:20 13:18 14:24 15:21 16:16 17:27 18:33 19:38 20:18 21:34 22:24 23:20 24:67 25:34 26:35 27:46 28:22 29:35 30:43 31:55 32:32 33:20 34:31 35:29 36:43 37:36 38:30 39:23 40:23 41:57 42:38 43:34 44:34 45:28 46:34 47:31 48:22 49:33 50:26
EXO 1:22 2:25 3:22 4:31 5:23 6:30 7:25 8:32 9:35 10:29 11:10 12:51 13:22 14:31 15:27 16:36 17:16 18:27 19:25 20:26 21:36 22:31 23:33 24:18 25:40 26:37 27:21 28:43 29:46 30:38 31:18 32:35 33:23 34:35 35:35 36:38 37:29 38:31 39:43 40:38
LEV 1:17 2:16 3:17 4:35 5:19 6:30 7:38 8:36 9:24 10:20 11:47 12:8 13:59 14:57 15:33 16:34 17:16 18:30 19:37 20:27 21:24 22:33 23:44 24:23 25:55 26:46 27:34
NUM 1:54 2:34 3:51 4:49 5:31 6:27 7:89 8:26 9:23 10:36 11:35 12:16 13:33 14:45 15:41 16:50 17:13 18:32 19:22 20:29 21:35 22:41 23:30 24:25 25:18 26:65 27:23 28:31 29:40 30:16 31:54 32:42 33:56 34:29 35:34 36:13
DEU 1:46 2:37 3:29 4:49 5:33 6:25 7:26 8:20 9:29 10:22 11:32 12:32 13:18 14:29 15:23 16:22 17:20 18:22 19:21 20:20 21:23 22:30 23:25 24:22 25:19 26:19 27:26 28:68 29:29 30:20 31:30 32:52 33:29 34:12
JOS 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
JDG 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
RUT 1:22 2:23 3:18 4:22
1SA 1:28 2:36 3:21 4:22 5:12 6:21 7:17 8:22 9:27 10:27 11:15 12:25 13:23 14:52 15:35 16:23 17:58 18:30 19:24 20:42 21:15 22:23 23:29 24:22 25:44 26:25 27:12 28:25 29:11 30:31 31:13
2SA 1:27 2:32 3:39 4:12 5:25 6:23 7:29 8:18 9:13 10:19 11:27 12:31 13:39 14:33 15:37 16:23 17:29 18:33 19:43 20:26 21:22 22:51 23:39 24:25
1KI 1:53 2:46 3:28 4:34 5:18 6:38 7:51 8:66 9:28 10:29 11:43 12:33 13:34 14:31 15:34 16:34 17:24 18:46 19:21 20:43 21:29 22:53
2KI 1:18 2:25 3:27 4:44 5:27 6:33 7:20 8:29 9:37 10:36 11:21 12:21 13:25 14:29 15:38 16:20 17:41 18:37 19:37 20:21 21:26 22:20 23:37 24:20 25:30
1CH 1:54 2:55 3:24 4:43 5:26 6:81 7:40 8:40 9:44 10:14 11:47 12:40 13:14 14:17 15:29 16:43 17:27 18:17 19:19 20:8 21:30 22:19 23:32 24:31 25:31 26:32 27:34 28:21 29:30
2CH 1:17 2:18 3:17 4:22 5:14 6:42 7:22 8:18 9:31 10:19 11:23 12:16 13:22 14:15 15:19 16:14 17:19 18:34 19:11 20:37 21:20 22:12 23:21 24:27 25:28 26:23 27:9 28:27 29:36 30:27 31:21 32:33 33:25 34:33 35:27 36:23
EZR 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44
NEH 1:11 2:20 3:32 4:23 5:19 6:19 7:73 8:18 9:38 10:39 11:36 12:47 13:31
EST 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
JOB 1:22 2:13 3:26 4:21 5:27 6:30 7:21 8:22 9:35 10:22 11:20 12:25 13:28 14:22 15:35 16:22 17:16 18:21 19:29 20:29 21:34 22:30 23:17 24:25 25:6 26:14 27:23 28:28 29:25 30:31 31:40 32:22 33:33 34:37 35:16 36:33 37:24 38:41 39:30 40:24 41:34 42:17
PSA 1:6 2:12 3:8 4:8 5:12 6:10 7:17 8:9 9:20 10:18 11:7 12:8 13:6 14:7 15:5 16:11 17:15 18:50 19:14 20:9 21:13 22:31 23:6 24:10 25:22 26:12 27:14 28:9 29:11 30:12 31:24 32:11 33:22 34:22 35:28 36:12 37:40 38:22 39:13 40:17 41:13 42:11 43:5 44:26 45:17 46:11 47:9 48:14 49:20 50:23 51:19 52:9 53:6 54:7 55:23 56:13 57:11 58:11 59:17 60:12 61:8 62:12 63:11 64:10 65:13 66:20 67:7 68:35 69:36 70:5 71:24 72:20 73:28 74:23 75:10 76:12 77:20 78:72 79:13 80:19 81:16 82:8 83:18 84:12 85:13 86:17 87:7 88:18 89:52 90:17 91:16 92:15 93:5 94:23 95:11 96:13 97:12 98:9 99:9 100:5 101:8 102:28 103:22 104:35 105:45 106:48 107:43 108:13 109:31 110:7 111:10 112:10 113:9 114:8 115:18 116:19 117:2 118:29 119:176 120:7 121:8 122:9 123:4 124:8 125:5 126:6 127:5 128:6 129:8 130:8 131:3 132:18 133:3 134:3 135:21 136:26 137:9 138:8 139:24 140:13 141:10 142:7 143:12 144:15 145:21 146:10 147:20 148:14 149:9 150:6
PRO 1:33 2:22 3:35 4:27 5:23 6:35 7:27 8:36 9:18 10:32 11:31 12:28 13:25 14:35 15:33 16:33 17:28 18:24 19:29 20:30 21:31 22:29 23:35 24:34 25:28 26:28 27:27 28:28 29:27 30:33 31:31
ECC 1:18 2:26 3:22 4:16 5:20 6:12 7:29 8:17 9:18 10:20 11:10 12:14
SNG 1:17 2:17 3:11 4:16 5:16 6:13 7:13 8:14
ISA 1:31 2:22 3:26 4:6 5:30 6:13 7:25 8:22 9:21 10:34 11:16 12:6 13:22 14:32 15:9 16:14 17:14 18:7 19:25 20:6 21:17 22:25 23:18 24:23 25:12 26:21 27:13 28:29 29:24 30:33 31:9 32:20 33:24 34:17 35:10 36:22 37:38 38:22 39:8 40:31 41:29 42:25 43:28 44:28 45:25 46:13 47:15 48:22 49:26 50:11 51:23 52:15 53:12 54:17 55:13 56:12 57:21 58:14 59:21 60:22 61:11 62:12 63:19 64:12 65:25 66:24
JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:22 9:26 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:38 26:24 27:22 28:17 29:32 30:24 31:40 32:44 33:26 34:22 35:19 36:32 37:21 38:28 39:18 40:16 41:18 42:22 43:13 44:30 45:5 46:28 47:7 48:47 49:39 50:46 51:64 52:34
LAM 1:22 2:22 3:66 4:22 5:22
EZK 1:28 2:10 3:27 4:17 5:17 6:14 7:27 8:18 9:11 10:22 11:25 12:28 13:23 14:23 15:8 16:63 17:24 18:32 19:14 20:49 21:32 22:31 23:49 24:27 25:17 26:21 27:36 28:26 29:21 30:26 31:18 32:32 33:33 34:31 35:15 36:38 37:28 38:23 39:29 40:49 41:26 42:20 43:27 44:31 45:25 46:24 47:23 48:35
DAN 1:21 2:49 3:30 4:37 5:31 6:28 7:28 8:27 9:27 10:21 11:45 12:13
HOS 1:11 2:23 3:5 4:19 5:15 6:11 7:16 8:14 9:17 10:15 11:12 12:14 13:16 14:9
JOL 1:20 2:32 3:21
AMO 1:15 2:16 3:15 4:13 5:27 6:14 7:17 8:14 9:15
OBA 1:21
JON 1:17 2:10 3:10 4:11
MIC 1:16 2:13 3:12 4:13 5:15 6:16 7:20
NAM 1:15 2:13 3:19
HAB 1:17 2:20 3:19
ZEP 1:18 2:15 3:20
HAG 1:15 2:23
ZEC 1:21 2:13 3:10 4:14 5:11 6:15 7:14 8:23 9:17 10:12 11:17 12:14 13:9 14:21
MAL 1:14 2:17 3:18 4:6
#-----------------------------------------------
# New Testament
MAT 1:25 2:23 3:17 4:25 5:48 6:34 7:29 8:34 9:38 10:42 11:30 12:50 13:58 14:36 15:39 16:28 17:27 18:35 19:30 20:34 21:46 22:46 23:39 24:51 25:46 26:75 27:66 28:20
MRK 1:45 2:28 3:35 4:41 5:43 6:56 7:37 8:38 9:50 10:52 11:33 12:44 13:37 14:72 15:47 16:20
LUK 1:80 2:52 3:38 4:44 5:39 6:49 7:50 8:56 9:62 10:42 11:54 12:59 13:35 14:35 15:32 16:31 17:37 18:43 19:48 20:47 21:38 22:71 23:56 24:53
JHN 1:51 2:25 3:36 4:54 5:47 6:71 7:53 8:59 9:41 10:42 11:57 12:50 13:38 14:31 15:27 16:33 17:26 18:40 19:42 20:31 21:25
ACT 1:26 2:47 3:26 4:37 5:42 6:15 7:60 8:40 9:43 10:48 11:30 12:25 13:52 14:28 15:41 16:40 17:34 18:28 19:41 20:38 21:40 22:30 23:35 24:27 25:27 26:32 27:44 28:31
ROM 1:32 2:29 3:31 4:25 5:21 6:23 7:25 8:39 9:33 10:21 11:36 12:21 13:14 14:23 15:33 16:27
1CO 1:31 2:16 3:23 4:21 5:13 6:20 7:40 8:13 9:27 10:33 11:34 12:31 13:13 14:40 15:58 16:24
#2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:33 12:21 13:14
# Note sometimes 2CO 13 has 14 verses e.g. KJV. but 13 verses in modern translations
2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:33 12:21 13:14
GAL 1:24 2:21 3:29 4:31 5:26 6:18
EPH 1:23 2:22 3:21 4:32 5:33 6:24
PHP 1:30 2:30 3:21 4:23
COL 1:29 2:23 3:25 4:18
1TH 1:10 2:20 3:13 4:18 5:28
2TH 1:12 2:17 3:18
1TI 1:20 2:15 3:16 4:16 5:25 6:21
2TI 1:18 2:26 3:17 4:22
TIT 1:16 2:15 3:15
PHM 1:25
HEB 1:14 2:18 3:19 4:16 5:14 6:20 7:28 8:13 9:28 10:39 11:40 12:29 13:25
JAS 1:27 2:26 3:18 4:17 5:20
1PE 1:25 2:25 3:22 4:19 5:14
2PE 1:21 2:22 3:18
1JN 1:10 2:29 3:24 4:21 5:21
2JN 1:13
3JN 1:15
JUD 1:25
REV 1:20 2:29 3:22 4:11 5:14 6:17 7:17 8:13 9:21 10:11 11:19 12:18 13:18 14:20 15:8 16:21 17:18 18:24 19:21 20:15 21:27 22:21
# sometimes called the Apocalypse
#---------------------------------------------------------
# Deuterocanonical books
TOB 1:22 2:14 3:17 4:21 5:21 6:17 7:18 8:21 9:6 10:13 11:19 12:22 13:18 14:15
JDT 1:16 2:28 3:10 4:15 5:24 6:21 7:32 8:36 9:14 10:23 11:23 12:20 13:20 14:19 15:13 16:25
#-----------------------
# This is the definition for "Additions to Daniel" as in the KJV [Studge]
# ESG 1:13 2:12 3:6 4:18 5:19 6:16 7:24
# more commonly UBS Bibles have ESG which is the full Esther Greek for modern Bibles e.g. RSV, CEV, GNB etc
ESG 1:39 2:23 3:22 4:47 5:28 6:14 7:10 8:39 9:32 10:13
#-----------------------
WIS 1:16 2:24 3:19 4:20 5:23 6:25 7:30 8:21 9:18 10:21 11:26 12:27 13:19 14:31 15:19 16:29 17:21 18:25 19:22
SIR 1:30 2:18 3:31 4:31 5:15 6:37 7:36 8:19 9:18 10:31 11:34 12:18 13:26 14:27 15:20 16:30 17:32 18:33 19:30 20:32 21:28 22:27 23:27 24:34 25:26 26:29 27:30 28:26 29:28 30:25 31:31 32:24 33:31 34:26 35:20 36:26 37:31 38:34 39:35 40:30 41:23 42:25 43:33 44:23 45:26 46:20 47:25 48:25 49:16 50:29 51:30
#
# In English Bibles Baruch sometimes has 5 chapters and sometimes 6 in Catholic Bibles [Studge]
BAR 1:21 2:35 3:37 4:37 5:9 6:73
#
LJE 1:73
S3Y 1:68
SUS 1:64
BEL 1:42
1MA 1:64 2:70 3:60 4:61 5:68 6:63 7:50 8:32 9:73 10:89 11:74 12:53 13:53 14:49 15:41 16:24
2MA 1:36 2:32 3:40 4:50 5:27 6:31 7:42 8:36 9:29 10:38 11:38 12:45 13:26 14:46 15:39
#-----------------------------------------------------
# Additional Orthodox Books in Interconfessional Bibles e.g. RSV, NRSV
3MA 1:29 2:33 3:30 4:21 5:51 6:41 7:23
4MA 1:35 2:24 3:21 4:26 5:38 6:35 7:23 8:29 9:32 10:21 11:27 12:19 13:27 14:20 15:32 16:25 17:24 18:24
1ES 1:58 2:30 3:24 4:63 5:73 6:34 7:15 8:96 9:55
2ES 1:40 2:48 3:36 4:52 5:56 6:59 7:140 8:63 9:47 10:59 11:46 12:51 13:58 14:48 15:63 16:78
MAN 1:15
PS2 1:7
#-----------------------------------------------------
# ODA and PSS are only used in LXX and SYR projects and are not needed here
# ODA 1:19 2:43 3:10 4:19 5:12 6:8 7:20 8:37 9:22 10:9 11:11 12:15 13:4 14:46
# PSS 1:8 2:37 3:12 4:25 5:19 6:6 7:10 8:34 9:11 10:8 11:9 12:6 13:12 14:10 15:13 16:15 17:46 18:12
#-----------------------------------------------------
# Obselete books used for LXX variant texts, in LXX only in PT 6, and obselete in PT 7, not used in English, Spanish or any other Bibles.  If these codes were used they were used for the wrong books and these definitions were not relevant
JSA 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
JDB 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
TBS 1:22 2:14 3:17 4:21 5:23 6:19 7:17 8:21 9:6 10:14 11:19 12:22 13:18 14:15
SST 1:64
DNT 1:21 2:49 3:97 4:37 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
BLT 1:42
#------------------------------------------------------
# Daniel Greek used in some English Catholic Bibles
DAG 1:21 2:49 3:97 4:37 5:31 6:28 7:28 8:27 9:27 10:21 11:45 12:13 13:64 14:42
# Letter to the Laodiceans which was in the John Wycliffe Bible
LAO 1:20
#
#-----------------------------------------------------
# Mapping
#-----------------------------------------------------
# English = BHS (see org.vrs)
#
# (Note: ranges must not span a chapter, e.g. 4:10-5:11 is illegal)
#
GEN 31:55 = GEN 32:1
GEN 32:1-32 = GEN 32:2-33
EXO 8:1-4 = EXO 7:26-29
EXO 8:5-32 = EXO 8:1-28
EXO 22:1 = EXO 21:37
EXO 22:2-31 = EXO 22:1-30
LEV 6:1-7 = LEV 5:20-26
LEV 6:8-30 = LEV 6:1-23
NUM 16:36-50 = NUM 17:1-15
NUM 17:1-13 = NUM 17:16-28
# NUM 26:1a = NUM 25:19b  # no support for splits yet
# NUM 26:1b = NUM 26:1  # no support for splits yet
NUM 29:40 = NUM 30:1
NUM 30:1-16 = NUM 30:2-17
DEU 12:32 = DEU 13:1
DEU 13:1-18 = DEU 13:2-19
DEU 22:30 = DEU 23:1
DEU 23:1-25 = DEU 23:2-26
DEU 29:1 = DEU 28:69
DEU 29:2-29 = DEU 29:1-28
#
# removed see PTSIL-113
#1SA 20:42 = 1SA 20:41
#
1SA 20:42 = 1SA 21:1
1SA 21:1-15 = 1SA 21:2-16
1SA 23:29 = 1SA 24:1
1SA 24:1-22 = 1SA 24:2-23
2SA 18:33 = 2SA 19:1
2SA 19:1-43 = 2SA 19:2-44
1KI 4:21-34 = 1KI 5:1-14
1KI 5:1-18 = 1KI 5:15-32
# 1KI 18:33a = 1KI 18:33  # no support for splits yet
# 1KI 18:33b = 1KI 18:34  # no support for splits yet
# 1KI 22:43a = 1KI 22:43b  # no support for splits yet
1KI 22:43-53 = 1KI 22:44-54
2KI 11:21 = 2KI 12:1
2KI 12:1-21 = 2KI 12:2-22
1CH 6:1-15 = 1CH 5:27-41
1CH 6:16-81 = 1CH 6:1-66
# 1CH 12:4b = 1CH 12:4  # no support for splits yet
1CH 12:4-40 = 1CH 12:5-41
2CH 2:1 = 2CH 1:18
2CH 2:2-18 = 2CH 2:1-17
2CH 14:1 = 2CH 13:23
2CH 14:2-15 = 2CH 14:1-14
NEH 4:1-6 = NEH 3:33-38
NEH 4:7-23 = NEH 4:1-17
NEH 7:69-73 = NEH 7:68-72
NEH 9:38 = NEH 10:1
NEH 10:1-39 = NEH 10:2-40
JOB 41:1-8 = JOB 40:25-32
JOB 41:9-34 = JOB 41:1-26
PSA 3:0-8 = PSA 3:1-9
PSA 4:0-8 = PSA 4:1-9
PSA 5:0-12 = PSA 5:1-13
PSA 6:0-10 = PSA 6:1-11
PSA 7:0-17 = PSA 7:1-18
PSA 8:0-9 = PSA 8:1-10
PSA 9:0-20 = PSA 9:1-21
PSA 12:0-8 = PSA 12:1-9
PSA 13:0-5 = PSA 13:1-6
PSA 18:0-50 = PSA 18:1-51
PSA 19:0-14 = PSA 19:1-15
PSA 20:0-9 = PSA 20:1-10
PSA 21:0-13 = PSA 21:1-14
PSA 22:0-31 = PSA 22:1-32
PSA 30:0-12 = PSA 30:1-13
PSA 31:0-24 = PSA 31:1-25
PSA 34:0-22 = PSA 34:1-23
PSA 36:0-12 = PSA 36:1-13
PSA 38:0-22 = PSA 38:1-23
PSA 39:0-13 = PSA 39:1-14
PSA 40:0-17 = PSA 40:1-18
PSA 41:0-13 = PSA 41:1-14
PSA 42:0-11 = PSA 42:1-12
PSA 44:0-26 = PSA 44:1-27
PSA 45:0-17 = PSA 45:1-18
PSA 46:0-11 = PSA 46:1-12
PSA 47:0-9 = PSA 47:1-10
PSA 48:0-14 = PSA 48:1-15
PSA 49:0-20 = PSA 49:1-21
PSA 51:0 = PSA 51:1
PSA 51:0 = PSA 51:2
PSA 51:1-19 = PSA 51:3-21
PSA 52:0 = PSA 52:1
PSA 52:0 = PSA 52:2
PSA 52:1-9 = PSA 52:3-11
PSA 53:0-6 = PSA 53:1-7
PSA 54:0 = PSA 54:1
PSA 54:0 = PSA 54:2
PSA 54:1-7 = PSA 54:3-9
PSA 55:0-23 = PSA 55:1-24
PSA 56:0-13 = PSA 56:1-14
PSA 57:0-11 = PSA 57:1-12
PSA 58:0-11 = PSA 58:1-12
PSA 59:0-17 = PSA 59:1-18
PSA 60:0 = PSA 60:1
PSA 60:0 = PSA 60:2
PSA 60:1-12 = PSA 60:3-14
PSA 61:0-8 = PSA 61:1-9
PSA 62:0-12 = PSA 62:1-13
PSA 63:0-11 = PSA 63:1-12
PSA 64:0-10 = PSA 64:1-11
PSA 65:0-13 = PSA 65:1-14
PSA 67:0-7 = PSA 67:1-8
PSA 68:0-35 = PSA 68:1-36
PSA 69:0-36 = PSA 69:1-37
PSA 70:0-5 = PSA 70:1-6
PSA 75:0-10 = PSA 75:1-11
PSA 76:0-12 = PSA 76:1-13
PSA 77:0-20 = PSA 77:1-21
PSA 80:0-19 = PSA 80:1-20
PSA 81:0-16 = PSA 81:1-17
PSA 83:0-18 = PSA 83:1-19
PSA 84:0-12 = PSA 84:1-13
PSA 85:0-13 = PSA 85:1-14
PSA 88:0-18 = PSA 88:1-19
PSA 89:0-52 = PSA 89:1-53
PSA 92:0-15 = PSA 92:1-16
PSA 102:0-28 = PSA 102:1-29
PSA 108:0-13 = PSA 108:1-14
PSA 140:0-13 = PSA 140:1-14
PSA 142:0-7 = PSA 142:1-8
ECC 5:1 = ECC 4:17
ECC 5:2-20 = ECC 5:1-19
SNG 6:13 = SNG 7:1
SNG 7:1-13 = SNG 7:2-14
ISA 9:1 = ISA 8:23
ISA 9:2-21 = ISA 9:1-20
ISA 64:2-12 = ISA 64:1-11
JER 9:1 = JER 8:23
JER 9:2-26 = JER 9:1-25
EZK 20:45-46 = EZK 21:1-2
EZK 20:47 = EZK 21:3
EZK 20:48-49 = EZK 21:4-5
EZK 21:1-32 = EZK 21:6-37
DAN 4:1-3 = DAN 3:31-33
DAN 4:4-37 = DAN 4:1-34
DAN 5:31 = DAN 6:1
DAN 6:1-28 = DAN 6:2-29
HOS 1:10-11 = HOS 2:1-2
HOS 2:1-23 = HOS 2:3-25
HOS 11:12 = HOS 12:1
HOS 12:1-14 = HOS 12:2-15
HOS 13:16 = HOS 14:1
HOS 14:1-9 = HOS 14:2-10
JOL 2:28-32 = JOL 3:1-5
JOL 3:1-21 = JOL 4:1-21
JON 1:17 = JON 2:1
JON 2:1-10 = JON 2:2-11
MIC 5:1 = MIC 4:14
MIC 5:2-15 = MIC 5:1-14
NAM 1:15 = NAM 2:1
NAM 2:1-13 = NAM 2:2-14
ZEC 1:18-21 = ZEC 2:1-4
ZEC 2:1-13 = ZEC 2:5-17
MAL 4:1-6 = MAL 3:19-24
# 40 + 41 -> 40 (per Peter Kirk)
#! &ACT 19:40-41 = ACT 19:40
#
#---------------------------------
# map Baruch 6 onto Letter of Jeremiah [Studge]
BAR 6:1-73 = LJE 1:1-73
#
#------------------------------
# Susanna
DAG 13:1-63 = SUS 1:1-63
# Bel and the Dragon
DAG 14:1-42 = BEL 1:1-42
#----------------------------------
# Mapping Esther Greek onto LXX Esther Greek
#
# This maps the standard verses generated by Create Book
# to the actual verse numbers and segments found in the LXX
# ESG chapter 1
ESG 1:1 = ESG 1:1a
ESG 1:2 = ESG 1:1b
ESG 1:3 = ESG 1:1c
ESG 1:4 = ESG 1:1d
ESG 1:5 = ESG 1:1e
ESG 1:6 = ESG 1:1f
ESG 1:7 = ESG 1:1g
ESG 1:8 = ESG 1:1h
ESG 1:9 = ESG 1:1i
ESG 1:10 = ESG 1:1k
ESG 1:11 = ESG 1:1l
ESG 1:12 = ESG 1:1m
ESG 1:13 = ESG 1:1n
ESG 1:14 = ESG 1:1o
ESG 1:15 = ESG 1:1p
ESG 1:16 = ESG 1:1q
ESG 1:17 = ESG 1:1r
ESG 1:18 = ESG 1:1s
ESG 1:19-39 = ESG 1:2-22
# ESG chapter 3
ESG 3:14 = ESG 3:13a
ESG 3:15 = ESG 3:13b
ESG 3:16 = ESG 3:13c
ESG 3:17 = ESG 3:13d
ESG 3:18 = ESG 3:13e
ESG 3:19 = ESG 3:13f
ESG 3:20 = ESG 3:13g
ESG 3:21 = ESG 3:14
ESG 3:22 = ESG 3:15
# ESG chapter 4
ESG 4:18 = ESG 4:17a
ESG 4:19 = ESG 4:17b
ESG 4:20 = ESG 4:17c
ESG 4:21 = ESG 4:17c
ESG 4:22 = ESG 4:17d
ESG 4:23 = ESG 4:17d
ESG 4:24 = ESG 4:17e
ESG 4:25 = ESG 4:17f
ESG 4:26 = ESG 4:17g
ESG 4:27 = ESG 4:17h
ESG 4:28 = ESG 4:17i
ESG 4:29 = ESG 4:17k
ESG 4:30 = ESG 4:17k
ESG 4:31 = ESG 4:17k
ESG 4:32 = ESG 4:17l
ESG 4:33 = ESG 4:17m
ESG 4:34 = ESG 4:17n
ESG 4:35 = ESG 4:17n
ESG 4:36 = ESG 4:17o
ESG 4:37 = ESG 4:17o
ESG 4:38 = ESG 4:17p
ESG 4:39 = ESG 4:17q
ESG 4:40 = ESG 4:17r
ESG 4:41 = ESG 4:17s
ESG 4:42 = ESG 4:17t
ESG 4:43 = ESG 4:17u
ESG 4:44 = ESG 4:17w
ESG 4:45 = ESG 4:17x
ESG 4:46 = ESG 4:17y
ESG 4:47 = ESG 4:17z
# ESG chapter 5
ESG 5:2 = ESG 5:1a
ESG 5:3 = ESG 5:1a
ESG 5:4 = ESG 5:1a
ESG 5:5 = ESG 5:1b
ESG 5:6 = ESG 5:1c
ESG 5:7 = ESG 5:1d
ESG 5:8 = ESG 5:1e
ESG 5:9 = ESG 5:1f
ESG 5:10 = ESG 5:1f
ESG 5:11 = ESG 5:2
ESG 5:12 = ESG 5:2
ESG 5:13 = ESG 5:2a
ESG 5:14 = ESG 5:2a
ESG 5:15 = ESG 5:2b
ESG 5:16 = ESG 5:2b
ESG 5:17-28 = ESG 5:3-14
# ESG chapter 8
ESG 8:13 = ESG 8:12a
ESG 8:14 = ESG 8:12b
ESG 8:15 = ESG 8:12c
ESG 8:16 = ESG 8:12d
ESG 8:17 = ESG 8:12e
ESG 8:18 = ESG 8:12f
ESG 8:19 = ESG 8:12g
ESG 8:20 = ESG 8:12h
ESG 8:21 = ESG 8:12i
ESG 8:22 = ESG 8:12k
ESG 8:23 = ESG 8:12l
ESG 8:24 = ESG 8:12m
ESG 8:25 = ESG 8:12n
ESG 8:26 = ESG 8:12o
ESG 8:27 = ESG 8:12p
ESG 8:28 = ESG 8:12q
ESG 8:29 = ESG 8:12r
ESG 8:30 = ESG 8:12s
ESG 8:31 = ESG 8:12t
ESG 8:32 = ESG 8:12u
ESG 8:33 = ESG 8:12x
ESG 8:34 = ESG 8:12y
ESG 8:35 = ESG 8:12y
ESG 8:36 = ESG 8:12y
ESG 8:37-41 = ESG 8:13-17
# ESG chapter 10
ESG 10:4 = ESG 10:3a
ESG 10:5 = ESG 10:3b
ESG 10:6 = ESG 10:3c
ESG 10:7 = ESG 10:3d
ESG 10:8 = ESG 10:3e
ESG 10:9 = ESG 10:3f
ESG 10:10 = ESG 10:3g
ESG 10:11 = ESG 10:3h
ESG 10:12 = ESG 10:3i
ESG 10:13 = ESG 10:3k
ESG 10:14 = ESG 10:3l
# S3Y is a small section of the DAG LXX pulled out and translated as a separate book.
# Map it back to the LXX.  This section allow's texts such as TOB (French) which do
# this to scroll correctly with the LXX.
# S3Y is not present in the GRK, HEB, or LXX(Ralphs) text.
# If a text has DAG present, this section must NOT be included in its versification file because
# that would cause references in other texts to DAG to be redirected to a non-existant S3Y.
S3Y 1:1-29 = DAG 3:24-52
S3Y 1:30-31 = DAG 3:52-53
S3Y 1:33 = DAG 3:54
S3Y 1:32 = DAG 3:55
S3Y 1:34-35 = DAG 3:56-57
S3Y 1:37 = DAG 3:58
S3Y 1:36 = DAG 3:59
S3Y 1:38-68 = DAG 3:60-90
`;
const lxxText = `# Versification  "Septuagint"
# Version=1.7
# 
# modifications by Studge 26/ June/ 2009
# This should include the versifications for Bibles which follow LXX versificatio mainly Orthodox Bibles. [Studge]
#
# List of books, chapters, verses
# One line per book.
# One entry for each chapter.
# Verse number is the maximum verse number for that chapter.
# See the lines containing ='s below for verse mappings.
#
# modifications by Reinier 20/ April/ 2010
# all data that are not part of the LXX itself have been commented out with ##
#
# modifications by Michael Lothers 1/ June/ 2011
# added verse segment information in the format: *GEN 1:22,-,a,b
# which indicates GEN 1:22 has three segments, the first has no marking followed by two segments: 1a and 1b
# The lines are preceded by #! so that versions of Paratext prior to 7.3 will ignore them rather than crash.
#
# modifications by Tim Steenwyk 15/ September/ 2011
# removed mapping references to PS3 since they shouldn't be in LXX (Septuagint)
#------------------------------------------------
# Old Testament
GEN 1:31 2:25 3:24 4:26 5:32 6:22 7:24 8:22 9:29 10:32 11:32 12:20 13:18 14:24 15:21 16:16 17:27 18:33 19:38 20:18 21:34 22:24 23:20 24:67 25:34 26:35 27:46 28:22 29:35 30:43 31:54 32:33 33:20 34:31 35:29 36:43 37:36 38:30 39:23 40:23 41:57 42:38 43:34 44:34 45:28 46:34 47:31 48:22 49:33 50:26
EXO 1:22 2:25 3:22 4:31 5:23 6:30 7:29 8:28 9:35 10:29 11:10 12:51 13:22 14:31 15:27 16:36 17:16 18:27 19:25 20:26 21:37 22:30 23:33 24:18 25:40 26:37 27:21 28:43 29:46 30:38 31:18 32:35 33:23 34:35 35:35 36:38 37:21 38:27 39:23 40:38
LEV 1:17 2:16 3:17 4:35 5:26 6:23 7:38 8:36 9:24 10:20 11:47 12:8 13:59 14:57 15:33 16:34 17:16 18:30 19:37 20:27 21:24 22:33 23:44 24:23 25:55 26:46 27:34
NUM 1:54 2:34 3:51 4:49 5:31 6:26 7:89 8:26 9:23 10:36 11:35 12:16 13:33 14:45 15:41 16:35 17:28 18:32 19:22 20:29 21:35 22:41 23:30 24:25 25:18 26:65 27:23 28:31 29:39 30:17 31:54 32:42 33:56 34:29 35:34 36:13
DEU 1:46 2:37 3:29 4:49 5:33 6:25 7:26 8:20 9:29 10:22 11:32 12:31 13:19 14:29 15:23 16:22 17:20 18:22 19:21 20:20 21:23 22:29 23:26 24:22 25:19 26:19 27:26 28:69 29:28 30:20 31:30 32:52 33:29 34:12
JOS 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:29 9:27 10:42 11:23 12:24 13:32 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
JDG 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
RUT 1:22 2:23 3:18 4:22
1SA 1:28 2:36 3:21 4:22 5:12 6:21 7:17 8:22 9:27 10:27 11:15 12:25 13:23 14:52 15:35 16:23 17:54 18:29 19:24 20:42 21:16 22:23 23:28 24:23 25:44 26:25 27:12 28:25 29:11 30:31 31:13
# 1SA called 1 Kings in the Orthodox tradition
2SA 1:27 2:32 3:39 4:12 5:25 6:23 7:29 8:18 9:13 10:19 11:27 12:31 13:39 14:33 15:37 16:23 17:29 18:32 19:44 20:26 21:22 22:51 23:39 24:25
# 2SA called 2 Kings in the Orthodox tradition
1KI 1:53 2:46 3:28 4:19 5:32 6:36 7:50 8:66 9:28 10:29 11:43 12:33 13:34 14:31 15:34 16:34 17:24 18:46 19:21 20:29 21:43 22:54
# 1KI called 3 Kings in the Orthodox tradition
2KI 1:18 2:25 3:27 4:44 5:27 6:33 7:20 8:29 9:37 10:36 11:20 12:22 13:25 14:29 15:38 16:20 17:41 18:37 19:37 20:21 21:26 22:20 23:37 24:20 25:30
# 2KI called 4 Kings in the Orthodox tradition
1CH 1:54 2:55 3:24 4:43 5:41 6:66 7:40 8:40 9:44 10:14 11:47 12:41 13:14 14:17 15:29 16:43 17:27 18:17 19:19 20:8 21:30 22:19 23:32 24:31 25:31 26:32 27:34 28:21 29:30
2CH 1:18 2:17 3:17 4:22 5:14 6:42 7:22 8:18 9:31 10:19 11:23 12:16 13:23 14:14 15:19 16:14 17:19 18:34 19:11 20:37 21:20 22:12 23:21 24:27 25:28 26:23 27:9 28:27 29:36 30:27 31:21 32:33 33:25 34:33 35:27 36:23
#
# Edited by Studge
# Added EZR which is Ezra-Nehemiah, which had been put under 2ES by mistake
# Edited chapters 13 and 20 / SS 14.6.2014
EZR 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44 11:11 12:20 13:37 14:23 15:19 16:19 17:73 18:18 19:38 20:40 21:36 22:47 23:31
#
# most projects based on LXX will use Nehemiah so we ought to add it in.
##NEH 1:11 2:20 3:32 4:23 5:19 6:19 7:73 8:18 9:38 10:39 11:36 12:47 13:31
#
# Edited by Studge
# should not have ESG here but amongst the Deuterocanonical books for PT order
# ESG 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
#
JOB 1:22 2:13 3:26 4:21 5:27 6:30 7:21 8:22 9:35 10:22 11:20 12:25 13:28 14:22 15:35 16:22 17:16 18:21 19:29 20:29 21:34 22:30 23:17 24:25 25:6 26:14 27:23 28:28 29:25 30:31 31:40 32:22 33:33 34:37 35:16 36:33 37:24 38:41 39:30 40:32 41:26 42:17
PSA 1:6 2:12 3:9 4:9 5:13 6:11 7:18 8:10 9:39 10:7 11:9 12:6 13:7 14:5 15:11 16:15 17:51 18:15 19:10 20:14 21:32 22:6 23:10 24:22 25:12 26:14 27:9 28:11 29:13 30:25 31:11 32:22 33:23 34:28 35:13 36:40 37:23 38:14 39:18 40:14 41:12 42:5 43:27 44:18 45:12 46:10 47:15 48:21 49:23 50:21 51:11 52:7 53:9 54:24 55:14 56:12 57:12 58:18 59:14 60:9 61:13 62:12 63:11 64:14 65:20 66:8 67:36 68:37 69:6 70:24 71:20 72:28 73:23 74:11 75:13 76:21 77:72 78:13 79:20 80:17 81:8 82:19 83:13 84:14 85:17 86:7 87:19 88:53 89:17 90:16 91:16 92:5 93:23 94:11 95:13 96:12 97:9 98:9 99:5 100:8 101:29 102:22 103:35 104:45 105:48 106:43 107:14 108:31 109:7 110:10 111:10 112:9 113:26 114:9 115:10 116:2 117:29 118:176 119:7 120:8 121:9 122:4 123:8 124:5 125:6 126:5 127:6 128:8 129:8 130:3 131:18 132:3 133:3 134:21 135:26 136:9 137:8 138:24 139:14 140:10 141:8 142:12 143:15 144:21 145:10 146:11 147:9 148:14 149:9 150:6 151:7
# Psalms has 151 psalms in the Septuagint tradition
PRO 1:33 2:22 3:35 4:27 5:23 6:35 7:27 8:36 9:18 10:32 11:31 12:28 13:25 14:35 15:33 16:33 17:28 18:22 19:29 20:30 21:31 22:29 23:35 24:34 25:28 26:28 27:27 28:28 29:27 30:33 31:31
ECC 1:18 2:26 3:22 4:17 5:19 6:12 7:29 8:17 9:18 10:20 11:10 12:14
SNG 1:17 2:17 3:11 4:16 5:16 6:12 7:14 8:14
ISA 1:31 2:21 3:26 4:6 5:30 6:13 7:25 8:23 9:20 10:34 11:16 12:6 13:22 14:32 15:9 16:14 17:14 18:7 19:25 20:6 21:17 22:25 23:18 24:23 25:12 26:21 27:13 28:29 29:24 30:33 31:9 32:20 33:24 34:17 35:10 36:22 37:38 38:22 39:8 40:31 41:29 42:25 43:28 44:28 45:25 46:13 47:15 48:22 49:26 50:11 51:23 52:15 53:12 54:17 55:13 56:11 57:21 58:14 59:21 60:22 61:11 62:12 63:19 64:11 65:25 66:24
#
# Edited by SS 25.3.2003
# Original: JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:23 9:25 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:38 26:24 27:22 28:17 29:32 30:24 31:40 32:44 33:26 34:22 35:19 36:32 37:21 38:28 39:18 40:16 41:18 42:22 43:13 44:30 45:5 46:28 47:7 48:47 49:39 50:46 51:64 52:34
#
JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:23 9:25 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:20 26:28 27:46 28:64 29:7 30:33 31:44 32:38 33:24 34:22 35:17 36:32 37:24 38:40 39:44 40:13 41:22 42:19 43:32 44:21 45:28 46:18 47:16 48:18 49:22 50:13 51:35 52:34
LAM 1:22 2:22 3:66 4:22 5:22
EZK 1:28 2:10 3:27 4:17 5:17 6:14 7:27 8:18 9:11 10:22 11:25 12:28 13:23 14:23 15:8 16:63 17:24 18:32 19:14 20:44 21:37 22:31 23:49 24:27 25:17 26:21 27:36 28:26 29:21 30:26 31:18 32:32 33:33 34:31 35:15 36:38 37:28 38:23 39:29 40:49 41:26 42:20 43:27 44:31 45:25 46:24 47:23 48:35
#
# There really should not be an entry for DAN in the LXX.vrs. All this material should be in DAG to match Ralhfs.
# However, there are no doubt many projects that incorrectly but the material in DAN so we leave this here
# for backward compatibility
# Following line commented out and DAG-DAN mapping brought up from end of file to allow DAG text to sychronize with HEB where they match
# Edited by Sarah Lind Oct 6 2015
# DAN 1:21 2:49 3:97 4:37 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
DAG 1:1-21 = DAN 1:1-21 
DAG 2:1-49 = DAN 2:1-49
DAG 3:1-23 = DAN 3:1-23
DAG 3:91-97 = DAN 3:24-30
DAG 4:1-3 = DAN 3:31-33
DAG 4:4-37 = DAN 4:1-34
DAG 4:1-2 = DAN 4:4-5
DAG 5:1-30 = DAN 5:1-30
DAG 6:1-29 = DAN 6:1-29
DAG 7:1-28 = DAN 7:1-28
DAG 8:1-27 = DAN 8:1-27
DAG 9:1-27 = DAN 9:1-27
DAG 10:1-21 = DAN 10:1-21
DAG 11:1-45 = DAN 11:1-45
DAG 12:1-13 = DAN 12:1-13
#
HOS 1:9 2:25 3:5 4:19 5:15 6:11 7:16 8:14 9:17 10:15 11:11 12:15 13:15 14:10
JOL 1:20 2:27 3:5 4:21
AMO 1:15 2:16 3:15 4:13 5:27 6:14 7:17 8:14 9:15
OBA 1:21
JON 1:16 2:11 3:10 4:11
MIC 1:16 2:13 3:12 4:14 5:14 6:16 7:20
NAM 1:14 2:14 3:19
HAB 1:17 2:20 3:19
ZEP 1:18 2:15 3:20
HAG 1:15 2:23
ZEC 1:17 2:17 3:10 4:14 5:11 6:15 7:14 8:23 9:17 10:12 11:17 12:14 13:9 14:21
MAL 1:14 2:17 3:24
#
#  It feels a bit odd to include NT in "Septuagint" but I think there are
#  Bibles that follow the _versification_ of OT LXX but also have a NT.
#
# ------------------------------------------------------
# New Testament books
MAT 1:25 2:23 3:17 4:25 5:48 6:34 7:29 8:34 9:38 10:42 11:30 12:50 13:58 14:36 15:39 16:28 17:27 18:35 19:30 20:34 21:46 22:46 23:39 24:51 25:46 26:75 27:66 28:20
MRK 1:45 2:28 3:35 4:41 5:43 6:56 7:37 8:38 9:50 10:52 11:33 12:44 13:37 14:72 15:47 16:20
LUK 1:80 2:52 3:38 4:44 5:39 6:49 7:50 8:56 9:62 10:42 11:54 12:59 13:35 14:35 15:32 16:31 17:37 18:43 19:48 20:47 21:38 22:71 23:56 24:53
JHN 1:51 2:25 3:36 4:54 5:47 6:71 7:53 8:59 9:41 10:42 11:57 12:50 13:38 14:31 15:27 16:33 17:26 18:40 19:42 20:31 21:25
ACT 1:26 2:47 3:26 4:37 5:42 6:15 7:60 8:40 9:43 10:48 11:30 12:25 13:52 14:28 15:41 16:40 17:34 18:28 19:40 20:38 21:40 22:30 23:35 24:27 25:27 26:32 27:44 28:31
ROM 1:32 2:29 3:31 4:25 5:21 6:23 7:25 8:39 9:33 10:21 11:36 12:21 13:14 14:23 15:33 16:27
1CO 1:31 2:16 3:23 4:21 5:13 6:20 7:40 8:13 9:27 10:33 11:34 12:31 13:13 14:40 15:58 16:24
2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:33 12:21 13:13
GAL 1:24 2:21 3:29 4:31 5:26 6:18
EPH 1:23 2:22 3:21 4:32 5:33 6:24
PHP 1:30 2:30 3:21 4:23
COL 1:29 2:23 3:25 4:18
1TH 1:10 2:20 3:13 4:18 5:28
2TH 1:12 2:17 3:18
1TI 1:20 2:15 3:16 4:16 5:25 6:21
2TI 1:18 2:26 3:17 4:22
TIT 1:16 2:15 3:15
PHM 1:25
HEB 1:14 2:18 3:19 4:16 5:14 6:20 7:28 8:13 9:28 10:39 11:40 12:29 13:25
JAS 1:27 2:26 3:18 4:17 5:20
1PE 1:25 2:25 3:22 4:19 5:14
2PE 1:21 2:22 3:18
1JN 1:10 2:29 3:24 4:21 5:21
2JN 1:13
3JN 1:15
JUD 1:25
REV 1:20 2:29 3:22 4:11 5:14 6:17 7:17 8:13 9:21 10:11 11:19 12:18 13:18 14:20 15:8 16:21 17:18 18:24 19:21 20:15 21:27 22:21
#--------------------------------------------------
# Deuterocanonical Books
TOB 1:22 2:14 3:17 4:21 5:23 6:19 7:17 8:21 9:6 10:14 11:19 12:22 13:18 14:15
JDT 1:16 2:28 3:10 4:15 5:24 6:21 7:32 8:36 9:14 10:23 11:23 12:20 13:20 14:19 15:14 16:25
# added ESG definition in its right PT order
ESG 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
# note chapter 4 v17 is 17a-z
# note chapter 8 v12 is 12a-x
# note chapter 10 v3 is 3a-l
WIS 1:16 2:24 3:19 4:20 5:23 6:25 7:30 8:21 9:18 10:21 11:26 12:27 13:19 14:31 15:19 16:29 17:20 18:25 19:22
SIR 1:30 2:18 3:31 4:31 5:15 6:37 7:36 8:19 9:18 10:31 11:34 12:18 13:26 14:27 15:20 16:30 17:32 18:33 19:30 20:31 21:28 22:27 23:27 24:34 25:26 26:29 27:30 28:26 29:28 30:25 31:31 32:24 33:33 34:26 35:24 36:27 37:31 38:34 39:35 40:30 41:27 42:25 43:33 44:23 45:26 46:20 47:25 48:25 49:16 50:29 51:30
BAR 1:22 2:35 3:38 4:37 5:9
LJE 1:72
# Edited SUS / SS 14.6.2014
SUS 1:64
BEL 1:42
1MA 1:64 2:70 3:60 4:61 5:68 6:63 7:50 8:32 9:73 10:89 11:74 12:53 13:53 14:49 15:41 16:24
2MA 1:36 2:32 3:40 4:50 5:27 6:31 7:42 8:36 9:29 10:38 11:38 12:45 13:26 14:46 15:39
3MA 1:29 2:33 3:30 4:21 5:51 6:41 7:23
4MA 1:35 2:24 3:21 4:26 5:38 6:35 7:23 8:29 9:32 10:21 11:27 12:19 13:27 14:20 15:32 16:25 17:24 18:24
# 1ES Ezra (Greek)
1ES 1:55 2:26 3:24 4:63 5:71 6:33 7:15 8:92 9:55
#-----------------------------------------------------
# Edited by Studge - Had the wrong definition of 2ES
# 2ES 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44 11:11 12:20 13:37 14:17 15:19 16:19 17:73 18:18 19:37 20:40 21:36 22:47 23:31
# 2ES is not a LXX book but is from the Vulgate and has 16 chapters
# edited by Studge added the correct definition of 2ES
2ES 1:40 2:48 3:36 4:52 5:56 6:59 7:140 8:63 9:47 10:59 11:46 12:51 13:58 14:48 15:63 16:78
#
# Edited by Studge
#MAN and PS2 were not defined which are in LXX
MAN 1:15
PS2 1:7
#-------------------------------------------------------
# ODA and PSS are in the PT 6 files but now missing from the LXX files in PT 7
ODA 1:19 2:43 3:10 4:19 5:12 6:8 7:20 8:37 9:22 10:9 11:11 12:15 13:4 14:46
PSS 1:8 2:37 3:12 4:25 5:19 6:6 7:10 8:34 9:11 10:8 11:9 12:6 13:12 14:10 15:13 16:15 17:46 18:12
#-------------------------------------------------------
# NR: LXX variant texts now obselete, kep for backward compatability
JSA 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:45 20:9 21:45 22:34 23:16 24:33
JDB 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
TBS 1:22 2:14 3:17 4:21 5:23 6:19 7:17 8:21 9:6 10:14 11:19 12:22 13:18 14:15
SST 1:64
DNT 1:21 2:49 3:97 4:37 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
BLT 1:42
#--------------------------------------------------------
# Greek Daniel
# Edited chapter 5 and 6 and removed chapters 13 and 14 that are not in Rahlfs / SS 14.6.2014
DAG 1:21 2:49 3:97 4:37 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
#--------------------------------------------------------
# Syriac books for Peshitta projects SYR and SYA
#
# Syriac Psalms 152-155
##PS3 1:17 2:20 3:6 4:6
#
# Apocalypse of Baruch
##2BA 1:5 2:2 3:9 4:7 5:7 6:10 7:2 8:5 9:1 10:19 11:7 12:5 13:12 14:19 15:8 16:1 17:4 18:2 19:8 20:6 21:26 22:8 23:7 24:4 25:4 26:1 27:15 28:7 29:8 30:5 31:5 32:9 33:3 34:1 35:5 36:10 37:1 38:4 39:8 40:4 41:6 42:8 43:3 44:15 45:2 46:7 47:2 48:50 49:3 50:4 51:16 52:8 53:12 54:22 55:8 56:16 57:3 58:2 59:12 60:2 61:8 62:8 63:11 64:10 65:2 66:8 67:9 68:8 69:5 70:10 71:3 72:6 73:7 74:4 75:8 76:5 77:26
#
# Letter of Baruch
##LBA 78:7 79:3 80:7 81:4 82:9 83:23 84:11 85:15 86:3
#--------------------------------------------------------
# Books for Ethiopian Canon
# Jubilees (Ethiopian canon)
##JUB 1:26 2:17 3:19 4:24 5:36 6:34 7:37 8:40 9:27 10:48 11:39 12:56 13:34 14:55 15:20 16:28 17:30 18:31 19:59 20:66 21:30 22:38 23:59 24:30 25:50 26:48 27:37 28:38 29:27 30:29 31:31 32:24 33:30 34:20
# Enoch (Ethiopian canon)
##ENO 1:28 2:42 3:30 4:88 5:40 6:42 7:39 8:46 9:42 10:16 11:19 12:40 13:34 14:35 15:45 16:41 17:69 18:42 19:29 20:53 21:57 22:14 23:26 24:16 25:30 26:37 27:21 28:34 29:28 30:23 31:29 32:82 33:59 34:49 35:36 36:30 37:34 38:36 39:24 40:40 41:22 42:16
# 1 Meqabyan (Ethiopian canon)
##1MQ 1:28 2:28 3:38 4:37 5:39 6:38 7:33 8:35 9:10 10:8 11:8 12:44 13:27 14:23 15:20 16:9 17:8 18:12 19:17 20:4 21:31 22:11 23:7 4:22 25:18 26:5 27:20 28:49 29:17 30:16 31:7 32:4 33:11 34:18 35:8 36:46
# 2 Meqabyan (Ethiopian canon)
##2MQ 1:13 2:11 3:29 4:32 5:18 6:24 7:9 8:24 9:27 10:28 11:25 12:15 13:14 14:36 15:21 16:15 17:12 18:14 19:15 20:14 
# 3 Meqabyan (Ethiopian canon)
##3MQ 1:24 2:23 3:11 4:36 5:16 6:16 7:5 8:12 9:36 10:29
# Reproof (Ethiopian canon)
##REP 1:28 2:28 3:27 4:28 5:27 6:22
# 4 Baruch / Rest of the Words of Baruch (Ethiopian canon)
##4BA 1:30 2:29 3:30 4:33 5:62
#---------------------------------------------------------
# Edited by SS 14.6.2014 added deliberatelly omitted verses
-GEN 31:51
-GEN 35:21

-EXO 25:6
-EXO 28:23
-EXO 28:24
-EXO 28:25
-EXO 28:26
-EXO 28:27
-EXO 28:28
-EXO 32:9
-EXO 35:8
-EXO 35:15
-EXO 35:17
-EXO 35:18
-EXO 40:7
-EXO 40:11
-EXO 40:28
-EXO 40:30
-EXO 40:31
-EXO 40:32

-JOS 6:4
-JOS 8:13
-JOS 8:26
-JOS 10:15
-JOS 20:4
-JOS 20:5
-JOS 20:6

-1SA 13:1
-1SA 17:21
-1SA 17:22
-1SA 17:23
-1SA 17:24
-1SA 17:25
-1SA 17:26
-1SA 17:27
-1SA 17:28
-1SA 17:29
-1SA 17:30
-1SA 17:31
-1SA 17:41
-1SA 17:50
-1SA 18:1
-1SA 18:2
-1SA 18:3
-1SA 18:4
-1SA 18:5
-1SA 18:10
-1SA 18:11
-1SA 18:17
-1SA 18:18
-1SA 18:19
-1SA 23:12

-1KI 3:1
-1KI 5:5
-1KI 5:6
-1KI 5:7
-1KI 5:8
-1KI 5:31
-1KI 6:11
-1KI 6:12
-1KI 6:13
-1KI 6:14
-1KI 6:18
-1KI 8:12
-1KI 8:13
-1KI 9:15
-1KI 9:16
-1KI 9:17
-1KI 9:18
-1KI 9:19
-1KI 9:20
-1KI 9:21
-1KI 9:22
-1KI 9:23
-1KI 9:24
-1KI 9:25
-1KI 11:3
-1KI 11:23
-1KI 11:24
-1KI 11:39
-1KI 12:2
-1KI 12:17
-1KI 13:27
-1KI 14:1
-1KI 14:2
-1KI 14:3
-1KI 14:4
-1KI 14:5
-1KI 14:6
-1KI 14:7
-1KI 14:8
-1KI 14:9
-1KI 14:10
-1KI 14:11
-1KI 14:12
-1KI 14:13
-1KI 14:14
-1KI 14:15
-1KI 14:16
-1KI 14:17
-1KI 14:18
-1KI 14:19
-1KI 14:20
-1KI 15:6
-1KI 15:32
-1KI 22:47
-1KI 22:48
-1KI 22:49
-1KI 22:50

-1SA 17:12
-1SA 17:13
-1SA 17:14
-1SA 17:15
-1SA 17:16
-1SA 17:17
-1SA 17:18
-1SA 17:19
-1SA 17:20

-1CH 1:11
-1CH 1:12
-1CH 1:13
-1CH 1:14
-1CH 1:15
-1CH 1:16
-1CH 1:18
-1CH 1:19
-1CH 1:20
-1CH 1:21
-1CH 1:22
-1CH 1:23
-1CH 16:24

-2CH 27:8

-EZR 13:7
-EZR 14:18
-EZR 14:19
-EZR 14:20
-EZR 14:21
-EZR 14:22
-EZR 14:23
-EZR 19:38
-EZR 21:16
-EZR 21:20
-EZR 21:21
-EZR 21:28
-EZR 21:29
-EZR 21:32
-EZR 21:33
-EZR 21:34
-EZR 21:35
-EZR 22:4
-EZR 22:5
-EZR 22:6

-JOB 23:14

-PSA 115:5

-PRO 4:7
-PRO 8:33
-PRO 11:4
-PRO 15:31
-PRO 16:1
-PRO 16:3
-PRO 16:4
-PRO 16:6
-PRO 19:1
-PRO 19:2
-PRO 20:14
-PRO 20:15
-PRO 20:16
-PRO 20:17
-PRO 20:18
-PRO 20:19
-PRO 20:20
-PRO 20:21
-PRO 20:22
-PRO 21:5
-PRO 22:6
-PRO 23:23

-JER 2:1
-JER 7:1
-JER 8:11
-JER 8:12
-JER 10:6
-JER 10:7
-JER 10:8
-JER 10:10
-JER 11:7
-JER 17:1
-JER 17:2
-JER 17:3
-JER 17:4
-JER 26:1
-JER 26:26
-JER 28:45
-JER 28:46
-JER 28:47
-JER 28:48
-JER 30:22
-JER 32:1
-JER 32:2
-JER 32:3
-JER 32:4
-JER 32:5
-JER 32:6
-JER 32:7
-JER 32:8
-JER 32:9
-JER 32:10
-JER 32:11
-JER 32:12
-JER 32:14
-JER 34:1
-JER 34:7
-JER 34:13
-JER 34:17
-JER 34:21
-JER 36:16
-JER 36:17
-JER 36:18
-JER 36:19
-JER 36:20
-JER 37:10
-JER 37:11
-JER 37:15
-JER 37:22
-JER 46:4
-JER 46:5
-JER 46:6
-JER 46:7
-JER 46:8
-JER 46:9
-JER 46:10
-JER 46:11
-JER 46:12
-JER 46:13
-JER 52:2
-JER 52:3
-JER 52:15
-JER 52:28
-JER 52:29
-JER 52:30

-LAM 3:22
-LAM 3:23
-LAM 3:24
-LAM 3:29

-EZK 1:14
-EZK 10:14
-EZK 27:31
-EZK 32:19
-EZK 33:26
-EZK 40:30

#------------- DC books ------------

-TOB 4:8
-TOB 4:9
-TOB 4:10
-TOB 4:11
-TOB 4:12
-TOB 4:13
-TOB 4:14
-TOB 4:15
-TOB 4:16
-TOB 4:17
-TOB 4:18
-TOB 13:8
-TOB 13:9
-TOB 13:10

-ESG 4:6
-ESG 9:5
-ESG 9:30

-SIR 1:5
-SIR 1:7
-SIR 1:21
-SIR 3:19
-SIR 3:25
-SIR 6:1
-SIR 10:21
-SIR 11:15
-SIR 11:16
-SIR 13:14
-SIR 16:15
-SIR 16:16
-SIR 17:5
-SIR 17:9
-SIR 17:16
-SIR 17:18
-SIR 17:21
-SIR 18:3
-SIR 19:18
-SIR 19:19
-SIR 19:21
-SIR 22:7
-SIR 22:8
-SIR 24:18
-SIR 24:24
-SIR 25:12
-SIR 26:19
-SIR 26:20
-SIR 26:21
-SIR 26:22
-SIR 26:23
-SIR 26:24
-SIR 26:25
-SIR 26:26
-SIR 26:27

-4MA 10:4
-4MA 11:7
-4MA 11:8

#---------------------------------------------------------
# Mapping
# LXX = BHS (see org.vrs)
#
# (Note: for performance reasons ranges must not span a chapter, e.g. 4:10-5:11 is illegal)
#
# 2ES = EZR and NEH
#
EXO 20:13 = EXO 20:14
EXO 20:14 = EXO 20:15
EXO 20:15 = EXO 20:13
EXO 21:16 = EXO 21:17
EXO 21:17 = EXO 21:16
EXO 36:9 = EXO 39:2
EXO 36:10 = EXO 39:3
EXO 36:11 = EXO 39:4
EXO 36:12 = EXO 39:5
EXO 36:13 = EXO 39:6
EXO 36:14 = EXO 39:7
EXO 36:15 = EXO 39:8
EXO 36:16 = EXO 39:9
EXO 36:17 = EXO 39:10
EXO 36:20 = EXO 39:13
EXO 36:21 = EXO 39:14
EXO 36:22 = EXO 39:15
EXO 36:23 = EXO 39:16
EXO 36:25 = EXO 39:17
EXO 36:26 = EXO 39:18
EXO 36:27 = EXO 39:19
EXO 36:28 = EXO 39:20
EXO 36:29 = EXO 39:21
EXO 36:30 = EXO 39:22
EXO 36:31 = EXO 39:23
EXO 36:32 = EXO 39:24
EXO 36:33 = EXO 39:25
EXO 36:34 = EXO 39:26
EXO 36:35 = EXO 39:27
EXO 36:36 = EXO 39:28
EXO 36:37 = EXO 39:29
EXO 36:38 = EXO 39:30

DEU 5:17 = DEU 5:18
DEU 5:18 = DEU 5:17

1KI 20:1-29 = 1KI 21:1-29 
1KI 21:1-43 = 1KI 20:1-43

#
# Map The Greek versioin of Esther onto the Hebrew version of Esther
# using the Hebrew version as the reference point.
# Normally DC material would not have any entries in this part of the lxx.vrs file
# because the LXX serves as the reference point for DC material.
# Material which is placed in separate books in HEB and LXX (i.e. EST and ESG)
# is however placed here and referenced to the HEB reference points.
ESG 1:1-22 = EST 1:1-22
ESG 2:1-23 = EST 2:1-23
ESG 3:1-15 = EST 3:1-15
ESG 4:1-17 = EST 4:1-17
ESG 5:1-14 = EST 5:1-14
ESG 6:1-14 = EST 6:1-14
ESG 7:1-10 = EST 7:1-10
ESG 8:1-17 = EST 8:1-17
ESG 9:1-32 = EST 9:1-32
ESG 10:1-3 = EST 10:1-3
#
# PSA 9 = 9+10
PSA 9:22 = PSA 10:0
PSA 9:22-39 = PSA 10:1-18
PSA 10:0-7 = PSA 11:0-7
PSA 11:0-9 = PSA 12:0-9
PSA 12:0-6 = PSA 13:0-6
PSA 13:0-7 = PSA 14:0-7
PSA 14:0-5 = PSA 15:0-5
PSA 15:0-11 = PSA 16:0-11
PSA 16:0-15 = PSA 17:0-15
PSA 17:0-51 = PSA 18:0-51
PSA 18:0-15 = PSA 19:0-15
PSA 19:0-10 = PSA 20:0-10
PSA 20:0-14 = PSA 21:0-14
PSA 21:0-32 = PSA 22:0-32
PSA 22:0-6 = PSA 23:0-6
PSA 23:0-10 = PSA 24:0-10
PSA 24:0-22 = PSA 25:0-22
PSA 25:0-12 = PSA 26:0-12
PSA 26:0-14 = PSA 27:0-14
PSA 27:0-9 = PSA 28:0-9
PSA 28:0-11 = PSA 29:0-11
PSA 29:0-13 = PSA 30:0-13
PSA 30:0-25 = PSA 31:0-25
PSA 31:0-11 = PSA 32:0-11
PSA 32:0-22 = PSA 33:0-22
PSA 33:0-23 = PSA 34:0-23
PSA 34:0-28 = PSA 35:0-28
PSA 35:0-13 = PSA 36:0-13
PSA 36:0-40 = PSA 37:0-40
PSA 37:0-23 = PSA 38:0-23
PSA 38:0-14 = PSA 39:0-14
PSA 39:0-18 = PSA 40:0-18
PSA 40:0-14 = PSA 41:0-14
PSA 41:0-12 = PSA 42:0-12
PSA 42:0-5 = PSA 43:0-5
PSA 43:0-27 = PSA 44:0-27
PSA 44:0-18 = PSA 45:0-18
PSA 45:0-12 = PSA 46:0-12
PSA 46:0-10 = PSA 47:0-10
PSA 47:0-15 = PSA 48:0-15
PSA 48:0-21 = PSA 49:0-21
PSA 49:0-23 = PSA 50:0-23
PSA 50:0-21 = PSA 51:0-21
PSA 51:0-11 = PSA 52:0-11
PSA 52:0-7 = PSA 53:0-7
PSA 53:0-9 = PSA 54:0-9
PSA 54:0-24 = PSA 55:0-24
PSA 55:0-14 = PSA 56:0-14
PSA 56:0-12 = PSA 57:0-12
PSA 57:0-12 = PSA 58:0-12
PSA 58:0-18 = PSA 59:0-18
PSA 59:0-14 = PSA 60:0-14
PSA 60:0-9 = PSA 61:0-9
PSA 61:0-13 = PSA 62:0-13
PSA 62:0-12 = PSA 63:0-12
PSA 63:0-11 = PSA 64:0-11
PSA 64:0-14 = PSA 65:0-14
PSA 65:0-20 = PSA 66:0-20
PSA 66:0-8 = PSA 67:0-8
PSA 67:0-36 = PSA 68:0-36
PSA 68:0-37 = PSA 69:0-37
PSA 69:0-6 = PSA 70:0-6
PSA 70:0-24 = PSA 71:0-24
PSA 71:0-20 = PSA 72:0-20
PSA 72:0-28 = PSA 73:0-28
PSA 73:0-23 = PSA 74:0-23
PSA 74:0-11 = PSA 75:0-11
PSA 75:0-13 = PSA 76:0-13
PSA 76:0-21 = PSA 77:0-21
PSA 77:0-72 = PSA 78:0-72
PSA 78:0-13 = PSA 79:0-13
PSA 79:0-20 = PSA 80:0-20
PSA 80:0-17 = PSA 81:0-17
PSA 81:0-8 = PSA 82:0-8
PSA 82:0-19 = PSA 83:0-19
PSA 83:0-13 = PSA 84:0-13
PSA 84:0-14 = PSA 85:0-14
PSA 85:0-17 = PSA 86:0-17
PSA 86:0-7 = PSA 87:0-7
PSA 87:0-19 = PSA 88:0-19
PSA 88:0-53 = PSA 89:0-53
PSA 89:0-17 = PSA 90:0-17
PSA 90:0-16 = PSA 91:0-16
PSA 91:0-16 = PSA 92:0-16
PSA 92:0-5 = PSA 93:0-5
PSA 93:0-23 = PSA 94:0-23
PSA 94:0-11 = PSA 95:0-11
PSA 95:0-13 = PSA 96:0-13
PSA 96:0-12 = PSA 97:0-12
PSA 97:0-9 = PSA 98:0-9
PSA 98:0-9 = PSA 99:0-9
PSA 99:0-5 = PSA 100:0-5
PSA 100:0-8 = PSA 101:0-8
PSA 101:0-29 = PSA 102:0-29
PSA 102:0-22 = PSA 103:0-22
PSA 103:0-35 = PSA 104:0-35
PSA 104:0-45 = PSA 105:0-45
PSA 105:0-48 = PSA 106:0-48
PSA 106:0-43 = PSA 107:0-43
PSA 107:0-14 = PSA 108:0-14
PSA 108:0-31 = PSA 109:0-31
PSA 109:0-7 = PSA 110:0-7
PSA 110:0-10 = PSA 111:0-10
PSA 111:0-10 = PSA 112:0-10
PSA 112:0-9 = PSA 113:0-9
PSA 113:0-8 = PSA 114:0-8
PSA 113:9 = PSA 115:0
PSA 113:9-26 = PSA 115:1-18
PSA 114:0-9 = PSA 116:0-9
PSA 115:0 = PSA 116:10
PSA 115:1-10 = PSA 116:10-19	
PSA 116:0-2 = PSA 117:0-2
PSA 117:0-29 = PSA 118:0-29
PSA 118:0-176 = PSA 119:0-176
PSA 119:0-7 = PSA 120:0-7
PSA 120:0-8 = PSA 121:0-8
PSA 121:0-9 = PSA 122:0-9
PSA 122:0-4 = PSA 123:0-4
PSA 123:0-8 = PSA 124:0-8
PSA 124:0-5 = PSA 125:0-5
PSA 125:0-6 = PSA 126:0-6
PSA 126:0-5 = PSA 127:0-5
PSA 127:0-6 = PSA 128:0-6
PSA 128:0-8 = PSA 129:0-8
PSA 129:0-8 = PSA 130:0-8
PSA 130:0-3 = PSA 131:0-3
PSA 131:0-18 = PSA 132:0-18
PSA 132:0-3 = PSA 133:0-3
PSA 133:0-3 = PSA 134:0-3
PSA 134:0-21 = PSA 135:0-21
PSA 135:0-26 = PSA 136:0-26
PSA 136:0-9 = PSA 137:0-9
PSA 137:0-8 = PSA 138:0-8
PSA 138:0-24 = PSA 139:0-24
PSA 139:0-14 = PSA 140:0-14
PSA 140:0-10 = PSA 141:0-10
PSA 141:0-8 = PSA 142:0-8
PSA 142:0-12 = PSA 143:0-12
PSA 143:0-15 = PSA 144:0-15
PSA 144:0-21 = PSA 145:0-21
PSA 145:0-10 = PSA 146:0-10
# 146 + 147 -> 147
PSA 146:0-11 = PSA 147:0-11
PSA 147:0 = PSA 147:12
PSA 147:1-9 = PSA 147:12-20
# PSA 151 -> PS2
PSA 151:0-7 = PS2 1:0-7
#
# Jeremiah according to Rahlfs
# Added by SS 25.3.2003
#
# JER 1-25:13 = JER 1-25:13
# JER 25:14 = part of JER 49:34
# JER 25:20 = part of JER 49:34
# JER 52 = JER 52
#
JER 25:14-19 = JER 49:34-39
JER 25:20 = JER 49:34
JER 26:1-28 = JER 46:1-28
JER 27:1-46 = JER 50:1-46
JER 28:1-64 = JER 51:1-64
JER 29:1-7 = JER 47:1-7
JER 30:1-16 = JER 49:7-22
JER 30:17-22 = JER 49:1-6
JER 30:23-28 = JER 49:28-33
JER 30:29-33 = JER 49:23-27
JER 31:1-44 = JER 48:1-44
# Verses 31:1-13 do not exist
JER 32:13 = JER 25:13
# Verse 32:14 does not exist
JER 32:15-38 = JER 25:15-38
JER 33:1-24 = JER 26:1-24
JER 34:1-22 = JER 27:1-22
JER 35:1-17 = JER 28:1-17
JER 36:1-32 = JER 29:1-32
JER 37:1-24 = JER 30:1-24
JER 38:1-40 = JER 31:1-40
JER 39:1-44 = JER 32:1-44
JER 40:1-13 = JER 33:1-13
JER 41:1-22 = JER 34:1-22
JER 42:1-19 = JER 35:1-19
JER 43:1-32 = JER 36:1-32
JER 44:1-21 = JER 37:1-21
JER 45:1-28 = JER 38:1-28
JER 46:1-3 = JER 39:1-3
# Verses 46:4-13 do not exist
JER 46:14-18 = JER 39:14-18
JER 47:1-16 = JER 40:1-16
JER 48:1-18 = JER 41:1-18
JER 49:1-22 = JER 42:1-22
JER 50:1-13 = JER 43:1-13
JER 51:1-30 = JER 44:1-30
JER 51:31-35 = JER 45:1-5
#
# Map The Greek versioin of Daniel onto the Hebrew version of Daniel
# using the Hebrew version as the reference point.
# Normally DC material would not have any entries in this part of the lxx.vrs file
# because the LXX serves as the reference point for DC material.
# Material which is placed in separate books in HEB and LXX (i.e. DAN and DAG)
# is however placed here and referenced to the HEB reference point.
#
# If you have a text in which the DAG material has been (incorrectly) placed into DAN
# you must create a versification file in which DAN appears as the first book in 
# the following section.  You cannot have both DAN = DAN and DAG = DAN entries
# in a single file.
DAG 1:1-21 = DAN 1:1-21
DAG 2:1-49 = DAN 2:1-49
DAG 3:1-23 = DAN 3:1-23
DAG 3:91-97 = DAN 3:24-30
DAG 4:1-3 = DAN 3:31-33
DAG 4:4-37 = DAN 4:1-34
DAG 5:1-31 = DAN 5:1-31
DAG 6:1-28 = DAN 6:1-28
DAG 7:1-28 = DAN 7:1-28
DAG 8:1-27 = DAN 8:1-27
DAG 9:1-27 = DAN 9:1-27
DAG 10:1-21 = DAN 10:1-21
DAG 11:1-45 = DAN 11:1-45 
DAG 12:1-13 = DAN 12:1-13
#
# No entries present for S3Y because this book would not normally be present in a text based
# on the LXX versification. The S3Y material would instead start at DAG 3:24.
#
# When Ezra-Nehemiah is one book Ezra 11-23 maps onto Nehemiah
# LXX mapping onto BHS
EZR 11:1-11 = NEH 1:1-11
EZR 12:1-20 = NEH 2:1-20
EZR 13:1-38 = NEH 3:1-38
EZR 14:1-17 = NEH 4:1-17
EZR 15:1-19 = NEH 5:1-19
EZR 16:1-19 = NEH 6:1-19
EZR 17:1-72 = NEH 7:1-72
EZR 18:1-18 = NEH 8:1-18
EZR 19:1-37 = NEH 9:1-37
EZR 20:1-40 = NEH 10:1-40
EZR 21:1-36 = NEH 11:1-36
EZR 22:1-47 = NEH 12:1-47
EZR 23:1-31 = NEH 13:1-31
#---------------------------
# Mapping 2 Esdras onto the older Apocalypse of Ezra [Studge]
2ES 3:1-36 = EZA 1:1-36
2ES 4:1-52 = EZA 2:1-52
2ES 5:1-56 = EZA 3:1-56
2ES 6:1-59 = EZA 4:1-59
2ES 7:1-35 = EZA 5:1-35
2ES 7:106-140 = EZA 5:36-70
2ES 8:1-63 = EZA 6:1-63
2ES 9:1-47 = EZA 7:1-47
2ES 10:1-60 = EZA 8:1-60
2ES 11:1-46 = EZA 9:1-46
2ES 12:1-51 = EZA 10:1-51
2ES 13:1-58 = EZA 11:1-58
2ES 14:1-48 = EZA 12:1-48
#----------------------------
# Some texts (but not LXX) contain SUS and BEL as chapters 13 and 14 of DAG.
# There should not be any entries for DAG 13 and DAG 14 in the lxx.vrs because these chapters do not 
# exist in the LXX.
# If you have a text which has DAG 13 and 14 you will need to have a .vrs file that includes the following
# two mapping.
#
# Susanna
# DAG 13:1-63 = SUS 1:1-63
# Bel and the Dragon
# DAG 14:1-42 = BEL 1:1-42
#
#----------------------------
# Verse segment information for the Septuagint.
# The verse segment information is preceded by a '#!' so that it will be ignored by versions 
# of Paratext prior to Paratext 7.3 (and thus avoid crashing it with an unexpected format). 
#! *EXO 28:29,-,a 
#! *EXO 35:12,-,a 
#! *JOS 9:2,-,a,b,c,d,e,f 
#! *JOS 15:59,-,a 
#! *JOS 19:47,-,a 
#! *JOS 19:48,-,a 
#! *JOS 21:42,-,a,b,c,d 
#! *JOS 24:31,-,a 
#! *JOS 24:33,-,a,b 
#! *1SA 30:28,-,a 
#! *2SA 5:16,-,a 
#! *1KI 2:35,-,a,b,c,d,e,f,g,h,i,k,l,m,n,o 
#! *1KI 2:46,-,a,b,c,d,e,f,g,h,i,k,l 
#! *1KI 5:14,-,a,b 
#! *1KI 6:1,-,a,b,c,d 
#! *1KI 6:36,-,a 
#! *1KI 8:53,-,a 
#! *1KI 9:9,-,a 
#! *1KI 10:22,-,a,b,c 
#! *1KI 10:26,-,a 
#! *1KI 12:24,-,a,b,c,d,e,f,g,h,i,k,l,m,n,o,p,q,r,s,t,u,x,y,z 
#! *1KI 16:28,-,a,b,c,d,e,f,g,h 
#! *2KI 1:18,-,a,b,c,d 
#! *2CH 35:19,-,a,b,c,d 
#! *2CH 36:2,-,a,b,c 
#! *2CH 36:4,-,a 
#! *2CH 36:5,-,a,b,c,d 
#! *JOB 2:9,-,a,b,c,d,e 
#! *JOB 19:4,-,a 
#! *JOB 23:15,-,a 
#! *JOB 36:28,-,a,b 
#! *JOB 42:17,-,a,b,c,d,e 
#! *PSA 144:13,-,a 
#! *PRO 3:16,-,a 
#! *PRO 3:22,-,a 
#! *PRO 4:27,-,a,b 
#! *PRO 6:8,-,a,b,c 
#! *PRO 6:11,-,a 
#! *PRO 7:1,-,a 
#! *PRO 8:21,-,a 
#! *PRO 9:10,-,a 
#! *PRO 9:12,-,a,b,c 
#! *PRO 9:18,-,a,b,c,d 
#! *PRO 10:4,-,a 
#! *PRO 12:11,-,a 
#! *PRO 12:13,-,a 
#! *PRO 13:9,-,a 
#! *PRO 13:13,-,a 
#! *PRO 15:18,-,a 
#! *PRO 15:27,-,a 
#! *PRO 15:28,-,a 
#! *PRO 15:29,-,a,b 
#! *PRO 17:6,-,a 
#! *PRO 17:16,-,a 
#! *PRO 18:22,-,a 
#! *PRO 20:9,-,a,b,c 
#! *PRO 22:8,-,a 
#! *PRO 22:9,-,a 
#! *PRO 22:14,-,a 
#! *PRO 24:22,-,a,b,c,d,e 
#! *PRO 25:10,-,a 
#! *PRO 25:20,-,a 
#! *PRO 26:11,-,a 
#! *PRO 27:20,-,a 
#! *PRO 27:21,-,a 
#! *PRO 28:17,-,a 
#! *ESG 1:1,-,b,c,d,e,f,g,h,i,k,l,m,n,o,p,q,r,s 
#! *ESG 3:13,-,a,b,c,d,e,f,g 
#! *ESG 4:17,-,a,b,c,d,e,f,g,h,i,k,l,m,n,o,p,q,r,s,t,u,w,x,y,z 
#! *ESG 5:1,-,a,b,c,d,e,f 
#! *ESG 5:2,-,a,b 
#! *ESG 8:12,-,a,b,c,d,e,f,g,h,i,k,l,m,n,o,p,q,r,s,t,u,x 
#! *ESG 10:3,-,a,b,c,d,e,f,g,h,i,k,l 
#! *SIR 1:1,-,a,b,c,d,e,f,g,h 
`;
const orgText = `# Versification  "Original" 
# Version=1.200
# (not a very good name but I have not heard a better suggestion)
#
# modifications by Studge 26/June/2009
#
# BHS versification for OT, UBS GNT versification for NT
# following the Masoretic order
# OT translations using Masorteic verse structures should map onto this text
# NT versifications maps onto Nestle-Aland
#
# List of books, chapters, verses
# One line per book.
# One entry for each chapter.
# Verse number is the maximum verse number for that chapter.
# See the lines containing ='s below for verse mappings.
#
#---------------------------------------------------------------
# Old Testament
GEN 1:31 2:25 3:24 4:26 5:32 6:22 7:24 8:22 9:29 10:32 11:32 12:20 13:18 14:24 15:21 16:16 17:27 18:33 19:38 20:18 21:34 22:24 23:20 24:67 25:34 26:35 27:46 28:22 29:35 30:43 31:54 32:33 33:20 34:31 35:29 36:43 37:36 38:30 39:23 40:23 41:57 42:38 43:34 44:34 45:28 46:34 47:31 48:22 49:33 50:26
EXO 1:22 2:25 3:22 4:31 5:23 6:30 7:29 8:28 9:35 10:29 11:10 12:51 13:22 14:31 15:27 16:36 17:16 18:27 19:25 20:26 21:37 22:30 23:33 24:18 25:40 26:37 27:21 28:43 29:46 30:38 31:18 32:35 33:23 34:35 35:35 36:38 37:29 38:31 39:43 40:38
LEV 1:17 2:16 3:17 4:35 5:26 6:23 7:38 8:36 9:24 10:20 11:47 12:8 13:59 14:57 15:33 16:34 17:16 18:30 19:37 20:27 21:24 22:33 23:44 24:23 25:55 26:46 27:34
NUM 1:54 2:34 3:51 4:49 5:31 6:27 7:89 8:26 9:23 10:36 11:35 12:16 13:33 14:45 15:41 16:35 17:28 18:32 19:22 20:29 21:35 22:41 23:30 24:25 25:19 26:65 27:23 28:31 29:39 30:17 31:54 32:42 33:56 34:29 35:34 36:13
DEU 1:46 2:37 3:29 4:49 5:33 6:25 7:26 8:20 9:29 10:22 11:32 12:31 13:19 14:29 15:23 16:22 17:20 18:22 19:21 20:20 21:23 22:29 23:26 24:22 25:19 26:19 27:26 28:69 29:28 30:20 31:30 32:52 33:29 34:12
JOS 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
JDG 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
RUT 1:22 2:23 3:18 4:22
1SA 1:28 2:36 3:21 4:22 5:12 6:21 7:17 8:22 9:27 10:27 11:15 12:25 13:23 14:52 15:35 16:23 17:58 18:30 19:24 20:42 21:16 22:23 23:28 24:23 25:44 26:25 27:12 28:25 29:11 30:31 31:13
2SA 1:27 2:32 3:39 4:12 5:25 6:23 7:29 8:18 9:13 10:19 11:27 12:31 13:39 14:33 15:37 16:23 17:29 18:32 19:44 20:26 21:22 22:51 23:39 24:25
1KI 1:53 2:46 3:28 4:20 5:32 6:38 7:51 8:66 9:28 10:29 11:43 12:33 13:34 14:31 15:34 16:34 17:24 18:46 19:21 20:43 21:29 22:54
2KI 1:18 2:25 3:27 4:44 5:27 6:33 7:20 8:29 9:37 10:36 11:20 12:22 13:25 14:29 15:38 16:20 17:41 18:37 19:37 20:21 21:26 22:20 23:37 24:20 25:30
1CH 1:54 2:55 3:24 4:43 5:41 6:66 7:40 8:40 9:44 10:14 11:47 12:41 13:14 14:17 15:29 16:43 17:27 18:17 19:19 20:8 21:30 22:19 23:32 24:31 25:31 26:32 27:34 28:21 29:30
2CH 1:18 2:17 3:17 4:22 5:14 6:42 7:22 8:18 9:31 10:19 11:23 12:16 13:23 14:14 15:19 16:14 17:19 18:34 19:11 20:37 21:20 22:12 23:21 24:27 25:28 26:23 27:9 28:27 29:36 30:27 31:21 32:33 33:25 34:33 35:27 36:23
EZR 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44
NEH 1:11 2:20 3:38 4:17 5:19 6:19 7:72 8:18 9:37 10:40 11:36 12:47 13:31
EST 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
JOB 1:22 2:13 3:26 4:21 5:27 6:30 7:21 8:22 9:35 10:22 11:20 12:25 13:28 14:22 15:35 16:22 17:16 18:21 19:29 20:29 21:34 22:30 23:17 24:25 25:6 26:14 27:23 28:28 29:25 30:31 31:40 32:22 33:33 34:37 35:16 36:33 37:24 38:41 39:30 40:32 41:26 42:17
PSA 1:6 2:12 3:9 4:9 5:13 6:11 7:18 8:10 9:21 10:18 11:7 12:9 13:6 14:7 15:5 16:11 17:15 18:51 19:15 20:10 21:14 22:32 23:6 24:10 25:22 26:12 27:14 28:9 29:11 30:13 31:25 32:11 33:22 34:23 35:28 36:13 37:40 38:23 39:14 40:18 41:14 42:12 43:5 44:27 45:18 46:12 47:10 48:15 49:21 50:23 51:21 52:11 53:7 54:9 55:24 56:14 57:12 58:12 59:18 60:14 61:9 62:13 63:12 64:11 65:14 66:20 67:8 68:36 69:37 70:6 71:24 72:20 73:28 74:23 75:11 76:13 77:21 78:72 79:13 80:20 81:17 82:8 83:19 84:13 85:14 86:17 87:7 88:19 89:53 90:17 91:16 92:16 93:5 94:23 95:11 96:13 97:12 98:9 99:9 100:5 101:8 102:29 103:22 104:35 105:45 106:48 107:43 108:14 109:31 110:7 111:10 112:10 113:9 114:8 115:18 116:19 117:2 118:29 119:176 120:7 121:8 122:9 123:4 124:8 125:5 126:6 127:5 128:6 129:8 130:8 131:3 132:18 133:3 134:3 135:21 136:26 137:9 138:8 139:24 140:14 141:10 142:8 143:12 144:15 145:21 146:10 147:20 148:14 149:9 150:6
PRO 1:33 2:22 3:35 4:27 5:23 6:35 7:27 8:36 9:18 10:32 11:31 12:28 13:25 14:35 15:33 16:33 17:28 18:24 19:29 20:30 21:31 22:29 23:35 24:34 25:28 26:28 27:27 28:28 29:27 30:33 31:31
ECC 1:18 2:26 3:22 4:17 5:19 6:12 7:29 8:17 9:18 10:20 11:10 12:14
SNG 1:17 2:17 3:11 4:16 5:16 6:12 7:14 8:14
ISA 1:31 2:22 3:26 4:6 5:30 6:13 7:25 8:23 9:20 10:34 11:16 12:6 13:22 14:32 15:9 16:14 17:14 18:7 19:25 20:6 21:17 22:25 23:18 24:23 25:12 26:21 27:13 28:29 29:24 30:33 31:9 32:20 33:24 34:17 35:10 36:22 37:38 38:22 39:8 40:31 41:29 42:25 43:28 44:28 45:25 46:13 47:15 48:22 49:26 50:11 51:23 52:15 53:12 54:17 55:13 56:12 57:21 58:14 59:21 60:22 61:11 62:12 63:19 64:11 65:25 66:24
JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:23 9:25 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:38 26:24 27:22 28:17 29:32 30:24 31:40 32:44 33:26 34:22 35:19 36:32 37:21 38:28 39:18 40:16 41:18 42:22 43:13 44:30 45:5 46:28 47:7 48:47 49:39 50:46 51:64 52:34
LAM 1:22 2:22 3:66 4:22 5:22
EZK 1:28 2:10 3:27 4:17 5:17 6:14 7:27 8:18 9:11 10:22 11:25 12:28 13:23 14:23 15:8 16:63 17:24 18:32 19:14 20:44 21:37 22:31 23:49 24:27 25:17 26:21 27:36 28:26 29:21 30:26 31:18 32:32 33:33 34:31 35:15 36:38 37:28 38:23 39:29 40:49 41:26 42:20 43:27 44:31 45:25 46:24 47:23 48:35
DAN 1:21 2:49 3:33 4:34 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
HOS 1:9 2:25 3:5 4:19 5:15 6:11 7:16 8:14 9:17 10:15 11:11 12:15 13:15 14:10
JOL 1:20 2:27 3:5 4:21
AMO 1:15 2:16 3:15 4:13 5:27 6:14 7:17 8:14 9:15
OBA 1:21
JON 1:16 2:11 3:10 4:11
MIC 1:16 2:13 3:12 4:14 5:14 6:16 7:20
NAM 1:14 2:14 3:19
HAB 1:17 2:20 3:19
ZEP 1:18 2:15 3:20
HAG 1:15 2:23
ZEC 1:17 2:17 3:10 4:14 5:11 6:15 7:14 8:23 9:17 10:12 11:17 12:14 13:9 14:21
MAL 1:14 2:17 3:24
#---------------------------------------------------------
# New Testament books
MAT 1:25 2:23 3:17 4:25 5:48 6:34 7:29 8:34 9:38 10:42 11:30 12:50 13:58 14:36 15:39 16:28 17:27 18:35 19:30 20:34 21:46 22:46 23:39 24:51 25:46 26:75 27:66 28:20
MRK 1:45 2:28 3:35 4:41 5:43 6:56 7:37 8:38 9:50 10:52 11:33 12:44 13:37 14:72 15:47 16:20
LUK 1:80 2:52 3:38 4:44 5:39 6:49 7:50 8:56 9:62 10:42 11:54 12:59 13:35 14:35 15:32 16:31 17:37 18:43 19:48 20:47 21:38 22:71 23:56 24:53
JHN 1:51 2:25 3:36 4:54 5:47 6:71 7:53 8:59 9:41 10:42 11:57 12:50 13:38 14:31 15:27 16:33 17:26 18:40 19:42 20:31 21:25
ACT 1:26 2:47 3:26 4:37 5:42 6:15 7:60 8:40 9:43 10:48 11:30 12:25 13:52 14:28 15:41 16:40 17:34 18:28 19:40 20:38 21:40 22:30 23:35 24:27 25:27 26:32 27:44 28:31
ROM 1:32 2:29 3:31 4:25 5:21 6:23 7:25 8:39 9:33 10:21 11:36 12:21 13:14 14:23 15:33 16:27
1CO 1:31 2:16 3:23 4:21 5:13 6:20 7:40 8:13 9:27 10:33 11:34 12:31 13:13 14:40 15:58 16:24
2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:33 12:21 13:13
GAL 1:24 2:21 3:29 4:31 5:26 6:18
EPH 1:23 2:22 3:21 4:32 5:33 6:24
PHP 1:30 2:30 3:21 4:23
COL 1:29 2:23 3:25 4:18
1TH 1:10 2:20 3:13 4:18 5:28
2TH 1:12 2:17 3:18
1TI 1:20 2:15 3:16 4:16 5:25 6:21
2TI 1:18 2:26 3:17 4:22
TIT 1:16 2:15 3:15
PHM 1:25
HEB 1:14 2:18 3:19 4:16 5:14 6:20 7:28 8:13 9:28 10:39 11:40 12:29 13:25
JAS 1:27 2:26 3:18 4:17 5:20
1PE 1:25 2:25 3:22 4:19 5:14
2PE 1:21 2:22 3:18
1JN 1:10 2:29 3:24 4:21 5:21
2JN 1:13
3JN 1:15
JUD 1:25
REV 1:20 2:29 3:22 4:11 5:14 6:17 7:17 8:13 9:21 10:11 11:19 12:18 13:18 14:20 15:8 16:21 17:18 18:24 19:21 20:15 21:27 22:21
#------------------------------------------------
# Deuterocanonical books from the LXX which are in the Catholic tradition
TOB 1:22 2:14 3:17 4:21 5:23 6:19 7:17 8:21 9:6 10:14 11:19 12:22 13:18 14:15
JDT 1:16 2:28 3:10 4:15 5:24 6:21 7:32 8:36 9:14 10:23 11:23 12:20 13:20 14:19 15:14 16:25
ESG 1:39 2:23 3:22 4:47 5:28 6:14 7:10 8:39 9:32 10:13
WIS 1:16 2:24 3:19 4:20 5:23 6:25 7:30 8:21 9:18 10:21 11:26 12:27 13:19 14:31 15:19 16:29 17:20 18:25 19:22
SIR 1:30 2:18 3:31 4:31 5:15 6:37 7:36 8:19 9:18 10:31 11:34 12:18 13:26 14:27 15:20 16:30 17:32 18:33 19:30 20:31 21:28 22:27 23:27 24:34 25:26 26:29 27:30 28:26 29:28 30:25 31:31 32:24 33:33 34:26 35:24 36:27 37:31 38:34 39:35 40:30 41:27 42:25 43:33 44:23 45:26 46:20 47:25 48:25 49:16 50:29 51:30
BAR 1:22 2:35 3:38 4:37 5:9
LJE 1:72
S3Y 1:67
SUS 1:64
BEL 1:42
1MA 1:64 2:70 3:60 4:61 5:68 6:63 7:50 8:32 9:73 10:89 11:74 12:53 13:53 14:49 15:41 16:24
2MA 1:36 2:32 3:40 4:50 5:27 6:31 7:42 8:36 9:29 10:38 11:38 12:45 13:26 14:46 15:39
#---------------------------------------------------
# Additional Orthodox books from the LXX
3MA 1:29 2:33 3:30 4:21 5:51 6:41 7:23
4MA 1:35 2:24 3:21 4:26 5:38 6:35 7:23 8:29 9:32 10:21 11:27 12:19 13:27 14:20 15:32 16:25 17:24 18:24
1ES 1:55 2:26 3:24 4:63 5:71 6:33 7:15 8:92 9:55
# This was the wrong definition for 2ES
# 2ES 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44 11:11 12:20 13:37 14:17 15:19 16:19 17:73 18:18 19:37 20:40 21:36 22:47 23:31
# This is the correct definition of 2ES, the "original" book was EZA
2ES 1:40 2:48 3:36 4:52 5:56 6:59 7:140 8:63 9:47 10:59 11:46 12:51 13:58 14:48 15:63 16:78
MAN 1:15
PS2 1:7
#-------------------------------------------------------
# ODA and PSS are only in the LXX and SYR projects. 
ODA 1:19 2:43 3:10 4:19 5:12 6:8 7:20 8:37 9:22 10:9 11:11 12:15 13:4 14:46
PSS 1:8 2:37 3:12 4:25 5:19 6:6 7:10 8:34 9:11 10:8 11:9 12:6 13:12 14:10 15:13 16:15 17:46 18:12
#-------------------------------------------------------
# the following codes are for obselete LXX variants only in LXX and not supported in PT 7
JSA 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
JDB 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
TBS 1:22 2:14 3:17 4:21 5:23 6:19 7:17 8:21 9:6 10:14 11:19 12:22 13:18 14:15
SST 1:64
DNT 1:21 2:49 3:97 4:37 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
BLT 1:42
#
# No mappings are present for this versification since it represents
# the "standard" versification to which all OT and NT texts are mapped in these files.
# (DC texts follow the LXX)
#
#-------------------------------------------------------
# Apocalypse of Ezra [Studge]
EZA 1:36 2:52 3:56 4:59 5:139 6:63 7:47 8:60 9:46 10:51 11:58 12:48
#--------------------------------------------------------
# Jubilees and Enoch have both been found in the Hebrew [Studge]
# might be needed if we add Dead Sea Scrolls
# Jubilees (Ethiopian canon)
JUB 1:26 2:17 3:19 4:24 5:36 6:34 7:37 8:40 9:27 10:48 11:39 12:56 13:34 14:55 15:20 16:28 17:30 18:31 19:59 20:66 21:30 22:38 23:59 24:30 25:50 26:48 27:37 28:38 29:27 30:29 31:31 32:24 33:30 34:20
# Enoch (Ethiopian canon)
ENO 1:28 2:42 3:30 4:88 5:40 6:42 7:39 8:46 9:42 10:16 11:19 12:40 13:34 14:35 15:45 16:41 17:69 18:42 19:29 20:53 21:57 22:14 23:26 24:16 25:30 26:37 27:21 28:34 29:28 30:23 31:29 32:82 33:59 34:49 35:36 36:30 37:34 38:36 39:24 40:40 41:22 42:16
#
# S3Y is a small section of the DAG LXX pulled out and translated as a separate book.
# Map it back to the LXX.  This section allow's texts such as TOB (French) which do
# this to scroll correctly with the LXX.
# S3Y is not present in the GRK, HEB, or LXX(Ralphs) text.
# If a text has DAG present, this section must NOT be included in its versification file because
# that would cause references in other texts to DAG to be redirected to a non-existant S3Y.
S3Y 1:1-29 = DAG 3:24-52
S3Y 1:30-31 = DAG 3:52-53
S3Y 1:33 = DAG 3:54
S3Y 1:32 = DAG 3:55
S3Y 1:34-35 = DAG 3:56-57
S3Y 1:37 = DAG 3:58
S3Y 1:36 = DAG 3:59
S3Y 1:38-68 = DAG 3:60-90
`;
const rscText = `# Versification  "Russian Protestant"
# Version=1.4
#
# This is the versification used by the "Canonical" (Protestant) edition of the Russian Synodal Bible
# Initial version provided by Peter_Kirk@sil.org
# Corrected 27/May/2003 by matjaz.crnivec@drustvo-svds.si:
#   Number of vss: ISA 3; REV 12
#   Mappings: LEV 14; 1KI 22; 1CH 12; NEH 7; ISA 3; 2CO 11; REV 13
#
# List of books, chapters, verses
# One line per book.
# One entry for each chapter.
# Verse number is the maximum verse number for that chapter.
# See the lines containing ='s below for verse mappings.
#
#------------------------------------------------------------
# Old Testament
GEN 1:31 2:25 3:24 4:26 5:32 6:22 7:24 8:22 9:29 10:32 11:32 12:20 13:18 14:24 15:21 16:16 17:27 18:33 19:38 20:18 21:34 22:24 23:20 24:67 25:34 26:35 27:46 28:22 29:35 30:43 31:55 32:32 33:20 34:31 35:29 36:43 37:36 38:30 39:23 40:23 41:57 42:38 43:34 44:34 45:28 46:34 47:31 48:22 49:33 50:26
EXO 1:22 2:25 3:22 4:31 5:23 6:30 7:25 8:32 9:35 10:29 11:10 12:51 13:22 14:31 15:27 16:36 17:16 18:27 19:25 20:26 21:36 22:31 23:33 24:18 25:40 26:37 27:21 28:43 29:46 30:38 31:18 32:35 33:23 34:35 35:35 36:38 37:29 38:31 39:43 40:38
LEV 1:17 2:16 3:17 4:35 5:19 6:30 7:38 8:36 9:24 10:20 11:47 12:8 13:59 14:56 15:33 16:34 17:16 18:30 19:37 20:27 21:24 22:33 23:44 24:23 25:55 26:46 27:34
NUM 1:54 2:34 3:51 4:49 5:31 6:27 7:89 8:26 9:23 10:36 11:35 12:15 13:34 14:45 15:41 16:50 17:13 18:32 19:22 20:29 21:35 22:41 23:30 24:25 25:18 26:65 27:23 28:31 29:39 30:17 31:54 32:42 33:56 34:29 35:34 36:13
DEU 1:46 2:37 3:29 4:49 5:33 6:25 7:26 8:20 9:29 10:22 11:32 12:32 13:18 14:29 15:23 16:22 17:20 18:22 19:21 20:20 21:23 22:30 23:25 24:22 25:19 26:19 27:26 28:68 29:29 30:20 31:30 32:52 33:29 34:12
JOS 1:18 2:24 3:17 4:24 5:16 6:26 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
JDG 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
RUT 1:22 2:23 3:18 4:22
1SA 1:28 2:36 3:21 4:22 5:12 6:21 7:17 8:22 9:27 10:27 11:15 12:25 13:23 14:52 15:35 16:23 17:58 18:30 19:24 20:43 21:15 22:23 23:28 24:23 25:44 26:25 27:12 28:25 29:11 30:31 31:13
2SA 1:27 2:32 3:39 4:12 5:25 6:23 7:29 8:18 9:13 10:19 11:27 12:31 13:39 14:33 15:37 16:23 17:29 18:33 19:43 20:26 21:22 22:51 23:39 24:25
1KI 1:53 2:46 3:28 4:34 5:18 6:38 7:51 8:66 9:28 10:29 11:43 12:33 13:34 14:31 15:34 16:34 17:24 18:46 19:21 20:43 21:29 22:53
2KI 1:18 2:25 3:27 4:44 5:27 6:33 7:20 8:29 9:37 10:36 11:21 12:21 13:25 14:29 15:38 16:20 17:41 18:37 19:37 20:21 21:26 22:20 23:37 24:20 25:30
1CH 1:54 2:55 3:24 4:43 5:26 6:81 7:40 8:40 9:44 10:14 11:47 12:40 13:14 14:17 15:29 16:43 17:27 18:17 19:19 20:8 21:30 22:19 23:32 24:31 25:31 26:32 27:34 28:21 29:30
2CH 1:17 2:18 3:17 4:22 5:14 6:42 7:22 8:18 9:31 10:19 11:23 12:16 13:22 14:15 15:19 16:14 17:19 18:34 19:11 20:37 21:20 22:12 23:21 24:27 25:28 26:23 27:9 28:27 29:36 30:27 31:21 32:33 33:25 34:33 35:27 36:23
EZR 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44
NEH 1:11 2:20 3:32 4:23 5:19 6:19 7:73 8:18 9:38 10:39 11:36 12:47 13:31
EST 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
JOB 1:22 2:13 3:26 4:21 5:27 6:30 7:21 8:22 9:35 10:22 11:20 12:25 13:28 14:22 15:35 16:22 17:16 18:21 19:29 20:29 21:34 22:30 23:17 24:25 25:6 26:14 27:23 28:28 29:25 30:31 31:40 32:22 33:33 34:37 35:16 36:33 37:24 38:41 39:35 40:27 41:26 42:17
PSA 1:6 2:12 3:9 4:9 5:13 6:11 7:18 8:10 9:39 10:7 11:9 12:6 13:7 14:5 15:11 16:15 17:51 18:15 19:10 20:14 21:32 22:6 23:10 24:22 25:12 26:14 27:9 28:11 29:13 30:25 31:11 32:22 33:23 34:28 35:13 36:40 37:23 38:14 39:18 40:14 41:12 42:5 43:27 44:18 45:12 46:10 47:15 48:21 49:23 50:21 51:11 52:7 53:9 54:24 55:14 56:12 57:12 58:18 59:14 60:9 61:13 62:12 63:11 64:14 65:20 66:8 67:36 68:37 69:6 70:24 71:20 72:28 73:23 74:11 75:13 76:21 77:72 78:13 79:20 80:17 81:8 82:19 83:13 84:14 85:17 86:7 87:19 88:53 89:17 90:16 91:16 92:5 93:23 94:11 95:13 96:12 97:9 98:9 99:5 100:8 101:29 102:22 103:35 104:45 105:48 106:43 107:14 108:31 109:7 110:10 111:10 112:9 113:26 114:9 115:10 116:2 117:29 118:176 119:7 120:8 121:9 122:4 123:8 124:5 125:6 126:5 127:6 128:8 129:8 130:3 131:18 132:3 133:3 134:21 135:26 136:9 137:8 138:24 139:14 140:10 141:7 142:12 143:15 144:21 145:10 146:11 147:9 148:14 149:9 150:6
PRO 1:33 2:22 3:35 4:27 5:23 6:35 7:27 8:36 9:18 10:32 11:31 12:28 13:25 14:35 15:33 16:33 17:28 18:24 19:29 20:30 21:31 22:29 23:35 24:34 25:28 26:28 27:27 28:28 29:27 30:33 31:31
ECC 1:18 2:26 3:22 4:17 5:19 6:12 7:29 8:17 9:18 10:20 11:10 12:14
SNG 1:16 2:17 3:11 4:16 5:16 6:12 7:14 8:14
ISA 1:31 2:22 3:25 4:6 5:30 6:13 7:25 8:22 9:21 10:34 11:16 12:6 13:22 14:32 15:9 16:14 17:14 18:7 19:25 20:6 21:17 22:25 23:18 24:23 25:12 26:21 27:13 28:29 29:24 30:33 31:9 32:20 33:24 34:17 35:10 36:22 37:38 38:22 39:8 40:31 41:29 42:25 43:28 44:28 45:25 46:13 47:15 48:22 49:26 50:11 51:23 52:15 53:12 54:17 55:13 56:12 57:21 58:14 59:21 60:22 61:11 62:12 63:19 64:12 65:25 66:24
JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:22 9:26 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:38 26:24 27:22 28:17 29:32 30:24 31:40 32:44 33:26 34:22 35:19 36:32 37:21 38:28 39:18 40:16 41:18 42:22 43:13 44:30 45:5 46:28 47:7 48:47 49:39 50:46 51:64 52:34
LAM 1:22 2:22 3:66 4:22 5:22
EZK 1:28 2:10 3:27 4:17 5:17 6:14 7:27 8:18 9:11 10:22 11:25 12:28 13:23 14:23 15:8 16:63 17:24 18:32 19:14 20:49 21:32 22:31 23:49 24:27 25:17 26:21 27:36 28:26 29:21 30:26 31:18 32:32 33:33 34:31 35:15 36:38 37:28 38:23 39:29 40:49 41:26 42:20 43:27 44:31 45:25 46:24 47:23 48:35
DAN 1:21 2:49 3:33 4:34 5:31 6:28 7:28 8:27 9:27 10:21 11:45 12:13
HOS 1:11 2:23 3:5 4:19 5:15 6:11 7:16 8:14 9:17 10:15 11:12 12:14 13:15 14:10
JOL 1:20 2:32 3:21
AMO 1:15 2:16 3:15 4:13 5:27 6:14 7:17 8:14 9:15
OBA 1:21
JON 1:16 2:11 3:10 4:11
MIC 1:16 2:13 3:12 4:13 5:15 6:16 7:20
NAM 1:15 2:13 3:19
HAB 1:17 2:20 3:19
ZEP 1:18 2:15 3:20
HAG 1:15 2:23
ZEC 1:21 2:13 3:10 4:14 5:11 6:15 7:14 8:23 9:17 10:12 11:17 12:14 13:9 14:21
MAL 1:14 2:17 3:18 4:6
#-------------------------------------------------------
# New Testament books
MAT 1:25 2:23 3:17 4:25 5:48 6:34 7:29 8:34 9:38 10:42 11:30 12:50 13:58 14:36 15:39 16:28 17:27 18:35 19:30 20:34 21:46 22:46 23:39 24:51 25:46 26:75 27:66 28:20
MRK 1:45 2:28 3:35 4:41 5:43 6:56 7:37 8:38 9:50 10:52 11:33 12:44 13:37 14:72 15:47 16:20
LUK 1:80 2:52 3:38 4:44 5:39 6:49 7:50 8:56 9:62 10:42 11:54 12:59 13:35 14:35 15:32 16:31 17:37 18:43 19:48 20:47 21:38 22:71 23:56 24:53
JHN 1:51 2:25 3:36 4:54 5:47 6:71 7:53 8:59 9:41 10:42 11:57 12:50 13:38 14:31 15:27 16:33 17:26 18:40 19:42 20:31 21:25
ACT 1:26 2:47 3:26 4:37 5:42 6:15 7:60 8:40 9:43 10:48 11:30 12:25 13:52 14:28 15:41 16:40 17:34 18:28 19:40 20:38 21:40 22:30 23:35 24:27 25:27 26:32 27:44 28:31
ROM 1:32 2:29 3:31 4:25 5:21 6:23 7:25 8:39 9:33 10:21 11:36 12:21 13:14 14:26 15:33 16:24
1CO 1:31 2:16 3:23 4:21 5:13 6:20 7:40 8:13 9:27 10:33 11:34 12:31 13:13 14:40 15:58 16:24
2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:32 12:21 13:13
GAL 1:24 2:21 3:29 4:31 5:26 6:18
EPH 1:23 2:22 3:21 4:32 5:33 6:24
PHP 1:30 2:30 3:21 4:23
COL 1:29 2:23 3:25 4:18
1TH 1:10 2:20 3:13 4:18 5:28
2TH 1:12 2:17 3:18
1TI 1:20 2:15 3:16 4:16 5:25 6:21
2TI 1:18 2:26 3:17 4:22
TIT 1:16 2:15 3:15
PHM 1:25
HEB 1:14 2:18 3:19 4:16 5:14 6:20 7:28 8:13 9:28 10:39 11:40 12:29 13:25
JAS 1:27 2:26 3:18 4:17 5:20
1PE 1:25 2:25 3:22 4:19 5:14
2PE 1:21 2:22 3:18
1JN 1:10 2:29 3:24 4:21 5:21
2JN 1:13
3JN 1:15
JUD 1:25
REV 1:20 2:29 3:22 4:11 5:14 6:17 7:17 8:13 9:21 10:11 11:19 12:17 13:18 14:20 15:8 16:21 17:18 18:24 19:21 20:15 21:27 22:21
#
#------------------------------------------------------------
# Mapping
#-------------------------------------------------------------
# Russian = BHS (see org.vrs)
#
# (Note: ranges must not span a chapter, e.g. 4:10-5:11 is illegal)
#
GEN 31:55 = GEN 32:1
GEN 32:1-32 = GEN 32:2-33
EXO 8:1-4 = EXO 7:26-29
EXO 8:5-32 = EXO 8:1-28
EXO 22:1 = EXO 21:37
EXO 22:2-31 = EXO 22:1-30
LEV 6:1-7 = LEV 5:20-26
LEV 6:8-30 = LEV 6:1-23
# LEV 14:55b = LEV 14:56   # cant handle split verses yet
LEV 14:55 = LEV 14:55
LEV 14:55 = LEV 14:56
LEV 14:56 = LEV 14:57
NUM 13:1 = NUM 12:16
NUM 13:2-34 = NUM 13:1-33
NUM 16:36-50 = NUM 17:1-15
NUM 17:1-13 = NUM 17:16-28
NUM 26:1 = NUM 25:19
NUM 26:1 = NUM 26:1
DEU 12:32 = DEU 13:1
DEU 13:1-18 = DEU 13:2-19
DEU 22:30 = DEU 23:1
DEU 23:1-25 = DEU 23:2-26
DEU 29:1 = DEU 28:69
DEU 29:2-29 = DEU 29:1-28
JOS 5:16 = JOS 6:1
JOS 6:1-26 = JOS 6:2-27
1SA 20:43 = 1SA 21:1
1SA 21:1-15 = 1SA 21:2-16
2SA 18:33 = 2SA 19:1
2SA 19:1-43 = 2SA 19:2-44
1KI 4:21-34 = 1KI 5:1-14
1KI 5:1-18 = 1KI 5:15-32
#1KI 22:43b = 1KI 22:44   # cant handle split verses yet
1KI 22:43 = 1KI 22:43
1KI 22:43 = 1KI 22:44
1KI 22:44-53 = 1KI 22:45-54
2KI 11:21 = 2KI 12:1
2KI 12:1-21 = 2KI 12:2-22
1CH 6:1-15 = 1CH 5:27-41
1CH 6:16-81 = 1CH 6:1-66
# 1CH 12:4b = 1CH 12:5   # cant handle split verses yet
1CH 12:4 = 1CH 12:4
1CH 12:4 = 1CH 12:5
1CH 12:5-40 = 1CH 12:6-41
2CH 2:1 = 2CH 1:18
2CH 2:2-18 = 2CH 2:1-17
2CH 14:1 = 2CH 13:23
2CH 14:2-15 = 2CH 14:1-14
NEH 4:1-6 = NEH 3:33-38
NEH 4:7-23 = NEH 4:1-17
# NEH 7:68 = NEH 7:67b   # cant handle split verses yet
NEH 7:67 = NEH 7:67
NEH 7:68 = NEH 7:67
NEH 7:69-73 = NEH 7:68-72
NEH 9:38 = NEH 10:1
NEH 10:1-39 = NEH 10:2-40
JOB 39:31-35 = JOB 40:1-5
JOB 40:1-19 = JOB 40:6-24
JOB 40:20-27 = JOB 40:25-32
# PSA 9 = 9+10
PSA 9:22 = PSA 10:0
PSA 9:22-39 = PSA 10:1-18
PSA 10:0-7 = PSA 11:0-7
PSA 11:0-9 = PSA 12:0-9
PSA 12:0-6 = PSA 13:0-6
PSA 13:0-7 = PSA 14:0-7
PSA 14:0-5 = PSA 15:0-5
PSA 15:0-11 = PSA 16:0-11
PSA 16:0-15 = PSA 17:0-15
PSA 17:0-51 = PSA 18:0-51
PSA 18:0-15 = PSA 19:0-15
PSA 19:0-10 = PSA 20:0-10
PSA 20:0-14 = PSA 21:0-14
PSA 21:0-32 = PSA 22:0-32
PSA 22:0-6 = PSA 23:0-6
PSA 23:0-10 = PSA 24:0-10
PSA 24:0-22 = PSA 25:0-22
PSA 25:0-12 = PSA 26:0-12
PSA 26:0-14 = PSA 27:0-14
PSA 27:0-9 = PSA 28:0-9
PSA 28:0-11 = PSA 29:0-11
PSA 29:0-13 = PSA 30:0-13
PSA 30:0-25 = PSA 31:0-25
PSA 31:0-11 = PSA 32:0-11
PSA 32:0-22 = PSA 33:0-22
PSA 33:0-23 = PSA 34:0-23
PSA 34:0-28 = PSA 35:0-28
PSA 35:0-13 = PSA 36:0-13
PSA 36:0-40 = PSA 37:0-40
PSA 37:0-23 = PSA 38:0-23
PSA 38:0-14 = PSA 39:0-14
PSA 39:0-18 = PSA 40:0-18
PSA 40:0-14 = PSA 41:0-14
PSA 41:0-12 = PSA 42:0-12
PSA 42:0-5 = PSA 43:0-5
PSA 43:0-27 = PSA 44:0-27
PSA 44:0-18 = PSA 45:0-18
PSA 45:0-12 = PSA 46:0-12
PSA 46:0-10 = PSA 47:0-10
PSA 47:0-15 = PSA 48:0-15
PSA 48:0-21 = PSA 49:0-21
PSA 49:0-23 = PSA 50:0-23
PSA 50:0-21 = PSA 51:0-21
PSA 51:0-11 = PSA 52:0-11
PSA 52:0-7 = PSA 53:0-7
PSA 53:0-9 = PSA 54:0-9
PSA 54:0-24 = PSA 55:0-24
PSA 55:0-14 = PSA 56:0-14
PSA 56:0-12 = PSA 57:0-12
PSA 57:0-12 = PSA 58:0-12
PSA 58:0-18 = PSA 59:0-18
PSA 59:0-14 = PSA 60:0-14
PSA 60:0-9 = PSA 61:0-9
PSA 61:0-13 = PSA 62:0-13
PSA 62:0-12 = PSA 63:0-12
PSA 63:0-11 = PSA 64:0-11
PSA 64:0-14 = PSA 65:0-14
PSA 65:0-20 = PSA 66:0-20
PSA 66:0-8 = PSA 67:0-8
PSA 67:0-36 = PSA 68:0-36
PSA 68:0-37 = PSA 69:0-37
PSA 69:0-6 = PSA 70:0-6
PSA 70:0-24 = PSA 71:0-24
PSA 71:0-20 = PSA 72:0-20
PSA 72:0-28 = PSA 73:0-28
PSA 73:0-23 = PSA 74:0-23
PSA 74:0-11 = PSA 75:0-11
PSA 75:0-13 = PSA 76:0-13
PSA 76:0-21 = PSA 77:0-21
PSA 77:0-72 = PSA 78:0-72
PSA 78:0-13 = PSA 79:0-13
PSA 79:0-20 = PSA 80:0-20
PSA 80:0-17 = PSA 81:0-17
PSA 81:0-8 = PSA 82:0-8
PSA 82:0-19 = PSA 83:0-19
PSA 83:0-13 = PSA 84:0-13
PSA 84:0-14 = PSA 85:0-14
PSA 85:0-17 = PSA 86:0-17
PSA 86:0-1 = PSA 87:0-1
PSA 86:2 = PSA 87:1
PSA 86:2-7 = PSA 87:2-7
PSA 87:0-19 = PSA 88:0-19
PSA 88:0-53 = PSA 89:0-53
PSA 89:0-1 = PSA 90:0
PSA 89:2-6 = PSA 90:1-5
PSA 89:6 = PSA 90:6
PSA 89:7-17 = PSA 90:7-17
PSA 90:0-16 = PSA 91:0-16
PSA 91:0-16 = PSA 92:0-16
PSA 92:0-5 = PSA 93:0-5
PSA 93:0-23 = PSA 94:0-23
PSA 94:0-11 = PSA 95:0-11
PSA 95:0-13 = PSA 96:0-13
PSA 96:0-12 = PSA 97:0-12
PSA 97:0-9 = PSA 98:0-9
PSA 98:0-9 = PSA 99:0-9
PSA 99:0-5 = PSA 100:0-5
PSA 100:0-8 = PSA 101:0-8
PSA 101:0-29 = PSA 102:0-29
PSA 102:0-22 = PSA 103:0-22
PSA 103:0-35 = PSA 104:0-35
PSA 104:0-45 = PSA 105:0-45
PSA 105:0-48 = PSA 106:0-48
PSA 106:0-43 = PSA 107:0-43
PSA 107:0-14 = PSA 108:0-14
PSA 108:0-31 = PSA 109:0-31
PSA 109:0-7 = PSA 110:0-7
PSA 110:0-10 = PSA 111:0-10
PSA 111:0-10 = PSA 112:0-10
PSA 112:0-9 = PSA 113:0-9
PSA 113:0-8 = PSA 114:0-8
PSA 113:9 = PSA 115:0
PSA 113:9-26 = PSA 115:1-18
PSA 114:0-9 = PSA 116:0-9
PSA 115:0 = PSA 116:10
PSA 115:1-10 = PSA 116:10-19	
PSA 116:0-2 = PSA 117:0-2
PSA 117:0-29 = PSA 118:0-29
PSA 118:0-176 = PSA 119:0-176
PSA 119:0-7 = PSA 120:0-7
PSA 120:0-8 = PSA 121:0-8
PSA 121:0-9 = PSA 122:0-9
PSA 122:0-4 = PSA 123:0-4
PSA 123:0-8 = PSA 124:0-8
PSA 124:0-5 = PSA 125:0-5
PSA 125:0-6 = PSA 126:0-6
PSA 126:0-5 = PSA 127:0-5
PSA 127:0-6 = PSA 128:0-6
PSA 128:0-8 = PSA 129:0-8
PSA 129:0-8 = PSA 130:0-8
PSA 130:0-3 = PSA 131:0-3
PSA 131:0-18 = PSA 132:0-18
PSA 132:0-3 = PSA 133:0-3
PSA 133:0-3 = PSA 134:0-3
PSA 134:0-21 = PSA 135:0-21
PSA 135:0-26 = PSA 136:0-26
PSA 136:0-9 = PSA 137:0-9
PSA 137:0-8 = PSA 138:0-8
PSA 138:0-24 = PSA 139:0-24
PSA 139:0-14 = PSA 140:0-14
PSA 140:0-10 = PSA 141:0-10
PSA 141:0 = PSA 142:0-1
PSA 141:1-7 = PSA 142:2-8
PSA 142:0-12 = PSA 143:0-12
PSA 143:0-15 = PSA 144:0-15
PSA 144:0-21 = PSA 145:0-21
PSA 145:0-10 = PSA 146:0-10
# 146 + 147 -> 147
PSA 146:0-11 = PSA 147:0-11
PSA 147:0 = PSA 147:12
PSA 147:1-9 = PSA 147:12-20
SNG 1:1-16 = SNG 1:2-17
# ISA 3:19b = ISA 3:20   # cant handle split verses yet
ISA 3:19 = ISA 3:19
ISA 3:19 = ISA 3:20
ISA 3:20-25 = ISA 3:21-26
ISA 9:1 = ISA 8:23
ISA 9:2-21 = ISA 9:1-20
ISA 63:19 = ISA 63:19
ISA 64:1 = ISA 63:19
ISA 64:2-12 = ISA 64:1-11
JER 9:1 = JER 8:23
JER 9:2-26 = JER 9:1-25
EZK 20:45-49 = EZK 21:1-5
EZK 21:1-32 = EZK 21:6-37
DAN 5:31 = DAN 6:1
DAN 6:1-28 = DAN 6:2-29
HOS 1:10-11 = HOS 2:1-2
HOS 2:1-23 = HOS 2:3-25
HOS 11:12 = HOS 12:1
HOS 12:1-14 = HOS 12:2-15
JOL 2:28-32 = JOL 3:1-5
JOL 3:1-21 = JOL 4:1-21
MIC 5:1 = MIC 4:14
MIC 5:2-15 = MIC 5:1-14
NAM 1:15 = NAM 2:1
NAM 2:1-13 = NAM 2:2-14
ZEC 1:18-21 = ZEC 2:1-4
ZEC 2:1-13 = ZEC 2:5-17
MAL 4:1-6 = MAL 3:19-24
ROM 14:24-26 = ROM 16:25-27
# 2CO 11:32b = 2CO 11:33   # cant handle split verses yet
2CO 11:32 = 2CO 11:32
2CO 11:32 = 2CO 11:33
# REV 13:1a = REV 12:18   # cant handle split verses yet
# REV 13:1b = REV 13:1    # cant handle split verses yet
REV 13:1 = REV 12:18
REV 13:1 = REV 13:1
`;
const rsoText = `# Versification  "Russian Orthodox"
# Version=1.3
#
# This is the versification used by the Orthodox (or "non-canonical") edition of the Russian Synodal Bible
# Initial version provided by Peter_Kirk@sil.org
# Corrected 27/May/2003 by matjaz.crnivec@drustvo-svds.si:
#   Number of vss: 2CH 37; PSA 114; ISA 3; REV 12; 2ES (whole book added),
#   Mappings: LEV 14; 1KI 22; 1CH 12; 2CH 37; NEH 7; PSA 114; ISA 3; 2CO 11; REV 13; 2ES 7; 10
#
# modifications by Studge 26/June/2009
# amended by HAB April 2010
#
# List of books, chapters, verses
# One line per book.
# One entry for each chapter.
# Verse number is the maximum verse number for that chapter.
# See the lines containing ='s below for verse mappings.
#
#----------------------------------------------------------
GEN 1:31 2:25 3:24 4:26 5:32 6:22 7:24 8:22 9:29 10:32 11:32 12:20 13:18 14:24 15:21 16:16 17:27 18:33 19:38 20:18 21:34 22:24 23:20 24:67 25:34 26:35 27:46 28:22 29:35 30:43 31:55 32:32 33:20 34:31 35:29 36:43 37:36 38:30 39:23 40:23 41:57 42:38 43:34 44:34 45:28 46:34 47:31 48:22 49:33 50:26
EXO 1:22 2:25 3:22 4:31 5:23 6:30 7:25 8:32 9:35 10:29 11:10 12:51 13:22 14:31 15:27 16:36 17:16 18:27 19:25 20:26 21:36 22:31 23:33 24:18 25:40 26:37 27:21 28:43 29:46 30:38 31:18 32:35 33:23 34:35 35:35 36:38 37:29 38:31 39:43 40:38
LEV 1:17 2:16 3:17 4:35 5:19 6:30 7:38 8:36 9:24 10:20 11:47 12:8 13:59 14:56 15:33 16:34 17:16 18:30 19:37 20:27 21:24 22:33 23:44 24:23 25:55 26:46 27:34
NUM 1:54 2:34 3:51 4:49 5:31 6:27 7:89 8:26 9:23 10:36 11:35 12:15 13:34 14:45 15:41 16:50 17:13 18:32 19:22 20:29 21:35 22:41 23:30 24:25 25:18 26:65 27:23 28:31 29:39 30:17 31:54 32:42 33:56 34:29 35:34 36:13
DEU 1:46 2:37 3:29 4:49 5:33 6:25 7:26 8:20 9:29 10:22 11:32 12:32 13:18 14:29 15:23 16:22 17:20 18:22 19:21 20:20 21:23 22:30 23:25 24:22 25:19 26:19 27:26 28:68 29:29 30:20 31:30 32:52 33:29 34:12
JOS 1:18 2:24 3:17 4:24 5:16 6:26 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:36
JDG 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
RUT 1:22 2:23 3:18 4:22
1SA 1:28 2:36 3:21 4:22 5:12 6:21 7:17 8:22 9:27 10:27 11:15 12:25 13:23 14:52 15:35 16:23 17:58 18:30 19:24 20:43 21:15 22:23 23:28 24:23 25:44 26:25 27:12 28:25 29:11 30:31 31:13
2SA 1:27 2:32 3:39 4:12 5:25 6:23 7:29 8:18 9:13 10:19 11:27 12:31 13:39 14:33 15:37 16:23 17:29 18:33 19:43 20:26 21:22 22:51 23:39 24:25
1KI 1:53 2:46 3:28 4:34 5:18 6:38 7:51 8:66 9:28 10:29 11:43 12:33 13:34 14:31 15:34 16:34 17:24 18:46 19:21 20:43 21:29 22:53
2KI 1:18 2:25 3:27 4:44 5:27 6:33 7:20 8:29 9:37 10:36 11:21 12:21 13:25 14:29 15:38 16:20 17:41 18:37 19:37 20:21 21:26 22:20 23:37 24:20 25:30
1CH 1:54 2:55 3:24 4:43 5:26 6:81 7:40 8:40 9:44 10:14 11:47 12:40 13:14 14:17 15:29 16:43 17:27 18:17 19:19 20:8 21:30 22:19 23:32 24:31 25:31 26:32 27:34 28:21 29:30
2CH 1:17 2:18 3:17 4:22 5:14 6:42 7:22 8:18 9:31 10:19 11:23 12:16 13:22 14:15 15:19 16:14 17:19 18:34 19:11 20:37 21:20 22:12 23:21 24:27 25:28 26:23 27:9 28:27 29:36 30:27 31:21 32:33 33:25 34:33 35:27 36:23 37:12
EZR 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44
NEH 1:11 2:20 3:32 4:23 5:19 6:19 7:73 8:18 9:38 10:39 11:36 12:47 13:31
#--------------
# Notes EST is the Greek Esther which should have been under ESG
EST 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
#--------------
JOB 1:22 2:13 3:26 4:21 5:27 6:30 7:21 8:22 9:35 10:22 11:20 12:25 13:28 14:22 15:35 16:22 17:16 18:21 19:29 20:29 21:34 22:30 23:17 24:25 25:6 26:14 27:23 28:28 29:25 30:31 31:40 32:22 33:33 34:37 35:16 36:33 37:24 38:41 39:35 40:27 41:26 42:17
PSA 1:6 2:12 3:9 4:9 5:13 6:11 7:18 8:10 9:39 10:7 11:9 12:6 13:7 14:5 15:11 16:15 17:51 18:15 19:10 20:14 21:32 22:6 23:10 24:22 25:12 26:14 27:9 28:11 29:13 30:25 31:11 32:22 33:23 34:28 35:13 36:40 37:23 38:14 39:18 40:14 41:12 42:5 43:27 44:18 45:12 46:10 47:15 48:21 49:23 50:21 51:11 52:7 53:9 54:24 55:14 56:12 57:12 58:18 59:14 60:9 61:13 62:12 63:11 64:14 65:20 66:8 67:36 68:37 69:6 70:24 71:20 72:28 73:23 74:11 75:13 76:21 77:72 78:13 79:20 80:17 81:8 82:19 83:13 84:14 85:17 86:7 87:19 88:53 89:17 90:16 91:16 92:5 93:23 94:11 95:13 96:12 97:9 98:9 99:5 100:8 101:29 102:22 103:35 104:45 105:48 106:43 107:14 108:31 109:7 110:10 111:10 112:9 113:26 114:8 115:10 116:2 117:29 118:176 119:7 120:8 121:9 122:4 123:8 124:5 125:6 126:5 127:6 128:8 129:8 130:3 131:18 132:3 133:3 134:21 135:26 136:9 137:8 138:24 139:14 140:10 141:7 142:12 143:15 144:21 145:10 146:11 147:9 148:14 149:9 150:6 151:7
PRO 1:33 2:22 3:35 4:29 5:23 6:35 7:27 8:36 9:18 10:32 11:31 12:28 13:26 14:35 15:33 16:33 17:28 18:25 19:29 20:30 21:31 22:29 23:35 24:34 25:28 26:28 27:27 28:28 29:27 30:33 31:31
ECC 1:18 2:26 3:22 4:17 5:19 6:12 7:29 8:17 9:18 10:20 11:10 12:14
SNG 1:16 2:17 3:11 4:16 5:16 6:12 7:14 8:14
ISA 1:31 2:22 3:25 4:6 5:30 6:13 7:25 8:22 9:21 10:34 11:16 12:6 13:22 14:32 15:9 16:14 17:14 18:7 19:25 20:6 21:17 22:25 23:18 24:23 25:12 26:21 27:13 28:29 29:24 30:33 31:9 32:20 33:24 34:17 35:10 36:22 37:38 38:22 39:8 40:31 41:29 42:25 43:28 44:28 45:25 46:13 47:15 48:22 49:26 50:11 51:23 52:15 53:12 54:17 55:13 56:12 57:21 58:14 59:21 60:22 61:11 62:12 63:19 64:12 65:25 66:24
JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:22 9:26 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:38 26:24 27:22 28:17 29:32 30:24 31:40 32:44 33:26 34:22 35:19 36:32 37:21 38:28 39:18 40:16 41:18 42:22 43:13 44:30 45:5 46:28 47:7 48:47 49:39 50:46 51:64 52:34
LAM 1:22 2:22 3:66 4:22 5:22
EZK 1:28 2:10 3:27 4:17 5:17 6:14 7:27 8:18 9:11 10:22 11:25 12:28 13:23 14:23 15:8 16:63 17:24 18:32 19:14 20:49 21:32 22:31 23:49 24:27 25:17 26:21 27:36 28:26 29:21 30:26 31:18 32:32 33:33 34:31 35:15 36:38 37:28 38:23 39:29 40:49 41:26 42:20 43:27 44:31 45:25 46:24 47:23 48:35
DAN 1:21 2:49 3:100 4:34 5:31 6:28 7:28 8:27 9:27 10:21 11:45 12:13 13:64 14:42
HOS 1:11 2:23 3:5 4:19 5:15 6:11 7:16 8:14 9:17 10:15 11:12 12:14 13:15 14:10
JOL 1:20 2:32 3:21
AMO 1:15 2:16 3:15 4:13 5:27 6:14 7:17 8:14 9:15
OBA 1:21
JON 1:16 2:11 3:10 4:11
MIC 1:16 2:13 3:12 4:13 5:15 6:16 7:20
NAM 1:15 2:13 3:19
HAB 1:17 2:20 3:19
ZEP 1:18 2:15 3:20
HAG 1:15 2:23
ZEC 1:21 2:13 3:10 4:14 5:11 6:15 7:14 8:23 9:17 10:12 11:17 12:14 13:9 14:21
MAL 1:14 2:17 3:18 4:6
#----------------------------------------------------
MAT 1:25 2:23 3:17 4:25 5:48 6:34 7:29 8:34 9:38 10:42 11:30 12:50 13:58 14:36 15:39 16:28 17:27 18:35 19:30 20:34 21:46 22:46 23:39 24:51 25:46 26:75 27:66 28:20
MRK 1:45 2:28 3:35 4:41 5:43 6:56 7:37 8:38 9:50 10:52 11:33 12:44 13:37 14:72 15:47 16:20
LUK 1:80 2:52 3:38 4:44 5:39 6:49 7:50 8:56 9:62 10:42 11:54 12:59 13:35 14:35 15:32 16:31 17:37 18:43 19:48 20:47 21:38 22:71 23:56 24:53
JHN 1:51 2:25 3:36 4:54 5:47 6:71 7:53 8:59 9:41 10:42 11:57 12:50 13:38 14:31 15:27 16:33 17:26 18:40 19:42 20:31 21:25
ACT 1:26 2:47 3:26 4:37 5:42 6:15 7:60 8:40 9:43 10:48 11:30 12:25 13:52 14:28 15:41 16:40 17:34 18:28 19:40 20:38 21:40 22:30 23:35 24:27 25:27 26:32 27:44 28:31
ROM 1:32 2:29 3:31 4:25 5:21 6:23 7:25 8:39 9:33 10:21 11:36 12:21 13:14 14:26 15:33 16:24
1CO 1:31 2:16 3:23 4:21 5:13 6:20 7:40 8:13 9:27 10:33 11:34 12:31 13:13 14:40 15:58 16:24
2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:32 12:21 13:13
GAL 1:24 2:21 3:29 4:31 5:26 6:18
EPH 1:23 2:22 3:21 4:32 5:33 6:24
PHP 1:30 2:30 3:21 4:23
COL 1:29 2:23 3:25 4:18
1TH 1:10 2:20 3:13 4:18 5:28
2TH 1:12 2:17 3:18
1TI 1:20 2:15 3:16 4:16 5:25 6:21
2TI 1:18 2:26 3:17 4:22
TIT 1:16 2:15 3:15
PHM 1:25
HEB 1:14 2:18 3:19 4:16 5:14 6:20 7:28 8:13 9:28 10:39 11:40 12:29 13:25
JAS 1:27 2:26 3:18 4:17 5:20
1PE 1:25 2:25 3:22 4:19 5:14
2PE 1:21 2:22 3:18
1JN 1:10 2:29 3:24 4:21 5:21
2JN 1:13
3JN 1:15
JUD 1:25
REV 1:20 2:29 3:22 4:11 5:14 6:17 7:17 8:13 9:21 10:11 11:19 12:17 13:18 14:20 15:8 16:21 17:18 18:24 19:21 20:15 21:27 22:21
#---------------------------------------------
TOB 1:22 2:14 3:17 4:21 5:22 6:18 7:17 8:21 9:6 10:13 11:18 12:22 13:18 14:15
JDT 1:16 2:28 3:10 4:15 5:24 6:21 7:32 8:36 9:14 10:23 11:23 12:20 13:20 14:19 15:14 16:25
# ESG added which ought to replace EST
ESG 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:3
WIS 1:16 2:24 3:19 4:20 5:24 6:27 7:30 8:21 9:19 10:21 11:27 12:28 13:19 14:31 15:19 16:29 17:20 18:25 19:21
SIR 1:30 2:18 3:31 4:35 5:18 6:37 7:39 8:22 9:23 10:34 11:34 12:18 13:32 14:27 15:20 16:31 17:31 18:33 19:28 20:31 21:31 22:31 23:37 24:37 25:29 26:27 27:33 28:30 29:31 30:27 31:37 32:25 33:33 34:26 35:23 36:29 37:34 38:39 39:42 40:32 41:29 42:26 43:36 44:27 45:31 46:23 47:31 48:28 49:18 50:31 51:38
BAR 1:22 2:35 3:38 4:37 5:9
LJE 1:72
1MA 1:64 2:70 3:60 4:61 5:68 6:63 7:50 8:32 9:73 10:89 11:74 12:53 13:53 14:49 15:41 16:24
2MA 1:36 2:33 3:40 4:50 5:27 6:31 7:42 8:36 9:29 10:38 11:38 12:45 13:26 14:46 15:39
3MA 1:25 2:24 3:22 4:16 5:36 6:37 7:20
1ES 1:58 2:31 3:24 4:63 5:70 6:34 7:15 8:92 9:55
# in the Russian tradition the book of 1ES is called 2 Esdras [Studge]
2ES 1:40 2:48 3:36 4:52 5:56 6:59 7:70 8:63 9:47 10:60 11:46 12:51 13:58 14:48 15:63 16:78
# in the Russian tradition the book of 2ES is called 3 Esdras [Studge]
# added Prayer of Manasseh which is appended to 2 Chronicles in RSO
MAN 1:15
#
#----------------------------------------------
# Mapping
#----------------------------------------------
# Russian = BHS (see org.vrs)
#
# (Note: ranges must not span a chapter, e.g. 4:10-5:11 is illegal)
#
GEN 31:55 = GEN 32:1
GEN 32:1-32 = GEN 32:2-33
EXO 8:1-4 = EXO 7:26-29
EXO 8:5-32 = EXO 8:1-28
EXO 22:1 = EXO 21:37
EXO 22:2-31 = EXO 22:1-30
LEV 6:1-7 = LEV 5:20-26
LEV 6:8-30 = LEV 6:1-23
# LEV 14:55 = LEV 14:55-56
LEV 14:55 = LEV 14:55
LEV 14:55 = LEV 14:56
LEV 14:56 = LEV 14:57
NUM 13:1 = NUM 12:16
NUM 13:2-34 = NUM 13:1-33
NUM 16:36-50 = NUM 17:1-15
NUM 17:1-13 = NUM 17:16-28
NUM 26:1 = NUM 25:19
NUM 26:1 = NUM 26:1
DEU 12:32 = DEU 13:1
DEU 13:1-18 = DEU 13:2-19
DEU 22:30 = DEU 23:1
DEU 23:1-25 = DEU 23:2-26
DEU 29:1 = DEU 28:69
DEU 29:2-29 = DEU 29:1-28
JOS 5:16 = JOS 6:1
JOS 6:1-26 = JOS 6:2-27
1SA 20:43 = 1SA 21:1
1SA 21:1-15 = 1SA 21:2-16
2SA 18:33 = 2SA 19:1
2SA 19:1-43 = 2SA 19:2-44
1KI 4:21-34 = 1KI 5:1-14
1KI 5:1-18 = 1KI 5:15-32
# 1KI 22:43 = 1KI 22:43-44
1KI 22:43 = 1KI 22:43
1KI 22:43 = 1KI 22:44
1KI 22:44-53 = 1KI 22:45-54
2KI 11:21 = 2KI 12:1
2KI 12:1-21 = 2KI 12:2-22
1CH 6:1-15 = 1CH 5:27-41
1CH 6:16-81 = 1CH 6:1-66
# 1CH 12:4 = 1CH 12:4-5
1CH 12:4 = 1CH 12:4
1CH 12:4 = 1CH 12:5
1CH 12:5-40 = 1CH 12:6-41
2CH 2:1 = 2CH 1:18
2CH 2:2-18 = 2CH 2:1-17
2CH 14:1 = 2CH 13:23
2CH 14:2-15 = 2CH 14:1-14
# All the 37th chapter maps across verse boundaries!
#-----------------------
# Prayer of Manasseh
2CH 37:1 = MAN 1:1
2CH 37:2 = MAN 1:2
2CH 37:2 = MAN 1:3
2CH 37:2 = MAN 1:4
2CH 37:2 = MAN 1:5
2CH 37:3 = MAN 1:5
2CH 37:4 = MAN 1:6
2CH 37:5 = MAN 1:7
2CH 37:6 = MAN 1:7
2CH 37:6 = MAN 1:8
2CH 37:7 = MAN 1:8
2CH 37:7 = MAN 1:9
2CH 37:8 = MAN 1:9
2CH 37:8 = MAN 1:10
2CH 37:9 = MAN 1:10
2CH 37:10 = MAN 1:10
2CH 37:10 = MAN 1:11
2CH 37:11 = MAN 1:12
2CH 37:11 = MAN 1:13
2CH 37:11 = MAN 1:14
2CH 37:11 = MAN 1:15
2CH 37:12 = MAN 1:15
#--------------------------
NEH 4:1-6 = NEH 3:33-38
NEH 4:7-23 = NEH 4:1-17
# NEH 7:67-68 = NEH 7:67
NEH 7:67 = NEH 7:67
NEH 7:68 = NEH 7:67
NEH 7:69-73 = NEH 7:68-72
NEH 9:38 = NEH 10:1
NEH 10:1-39 = NEH 10:2-40
JOB 39:31-35 = JOB 40:1-5
JOB 40:1-19 = JOB 40:6-24
JOB 40:20-27 = JOB 40:25-32
# PSA 9 = 9+10
PSA 9:22 = PSA 10:0
PSA 9:22-39 = PSA 10:1-18
PSA 10:0-7 = PSA 11:0-7
PSA 11:0-9 = PSA 12:0-9
PSA 12:0-6 = PSA 13:0-6
PSA 13:0-7 = PSA 14:0-7
PSA 14:0-5 = PSA 15:0-5
PSA 15:0-11 = PSA 16:0-11
PSA 16:0-15 = PSA 17:0-15
PSA 17:0-51 = PSA 18:0-51
PSA 18:0-15 = PSA 19:0-15
PSA 19:0-10 = PSA 20:0-10
PSA 20:0-14 = PSA 21:0-14
PSA 21:0-32 = PSA 22:0-32
PSA 22:0-6 = PSA 23:0-6
PSA 23:0-10 = PSA 24:0-10
PSA 24:0-22 = PSA 25:0-22
PSA 25:0-12 = PSA 26:0-12
PSA 26:0-14 = PSA 27:0-14
PSA 27:0-9 = PSA 28:0-9
PSA 28:0-11 = PSA 29:0-11
PSA 29:0-13 = PSA 30:0-13
PSA 30:0-25 = PSA 31:0-25
PSA 31:0-11 = PSA 32:0-11
PSA 32:0-22 = PSA 33:0-22
PSA 33:0-23 = PSA 34:0-23
PSA 34:0-28 = PSA 35:0-28
PSA 35:0-13 = PSA 36:0-13
PSA 36:0-40 = PSA 37:0-40
PSA 37:0-23 = PSA 38:0-23
PSA 38:0-14 = PSA 39:0-14
PSA 39:0-18 = PSA 40:0-18
PSA 40:0-14 = PSA 41:0-14
PSA 41:0-12 = PSA 42:0-12
PSA 42:0-5 = PSA 43:0-5
PSA 43:0-27 = PSA 44:0-27
PSA 44:0-18 = PSA 45:0-18
PSA 45:0-12 = PSA 46:0-12
PSA 46:0-10 = PSA 47:0-10
PSA 47:0-15 = PSA 48:0-15
PSA 48:0-21 = PSA 49:0-21
PSA 49:0-23 = PSA 50:0-23
PSA 50:0-21 = PSA 51:0-21
PSA 51:0-11 = PSA 52:0-11
PSA 52:0-7 = PSA 53:0-7
PSA 53:0-9 = PSA 54:0-9
PSA 54:0-24 = PSA 55:0-24
PSA 55:0-14 = PSA 56:0-14
PSA 56:0-12 = PSA 57:0-12
PSA 57:0-12 = PSA 58:0-12
PSA 58:0-18 = PSA 59:0-18
PSA 59:0-14 = PSA 60:0-14
PSA 60:0-9 = PSA 61:0-9
PSA 61:0-13 = PSA 62:0-13
PSA 62:0-12 = PSA 63:0-12
PSA 63:0-11 = PSA 64:0-11
PSA 64:0-14 = PSA 65:0-14
PSA 65:0-20 = PSA 66:0-20
PSA 66:0-8 = PSA 67:0-8
PSA 67:0-36 = PSA 68:0-36
PSA 68:0-37 = PSA 69:0-37
PSA 69:0-6 = PSA 70:0-6
PSA 70:0-24 = PSA 71:0-24
PSA 71:0-20 = PSA 72:0-20
PSA 72:0-28 = PSA 73:0-28
PSA 73:0-23 = PSA 74:0-23
PSA 74:0-11 = PSA 75:0-11
PSA 75:0-13 = PSA 76:0-13
PSA 76:0-21 = PSA 77:0-21
PSA 77:0-72 = PSA 78:0-72
PSA 78:0-13 = PSA 79:0-13
PSA 79:0-20 = PSA 80:0-20
PSA 80:0-17 = PSA 81:0-17
PSA 81:0-8 = PSA 82:0-8
PSA 82:0-19 = PSA 83:0-19
PSA 83:0-13 = PSA 84:0-13
PSA 84:0-14 = PSA 85:0-14
PSA 85:0-17 = PSA 86:0-17
PSA 86:0-1 = PSA 87:1
PSA 86:2 = PSA 87:1
PSA 86:2-7 = PSA 87:2-7
PSA 87:0-19 = PSA 88:0-19
PSA 88:0-53 = PSA 89:0-53
PSA 89:0-1 = PSA 90:0-1
PSA 89:2-6 = PSA 90:1-6
PSA 89:7-17 = PSA 90:7-17
PSA 90:0-16 = PSA 91:0-16
PSA 91:0-16 = PSA 92:0-16
PSA 92:0-5 = PSA 93:0-5
PSA 93:0-23 = PSA 94:0-23
PSA 94:0-11 = PSA 95:0-11
PSA 95:0-13 = PSA 96:0-13
PSA 96:0-12 = PSA 97:0-12
PSA 97:0-9 = PSA 98:0-9
PSA 98:0-9 = PSA 99:0-9
PSA 99:0-5 = PSA 100:0-5
PSA 100:0-8 = PSA 101:0-8
PSA 101:0-29 = PSA 102:0-29
PSA 102:0-22 = PSA 103:0-22
PSA 103:0-35 = PSA 104:0-35
PSA 104:0-45 = PSA 105:0-45
PSA 105:0-48 = PSA 106:0-48
PSA 106:0-43 = PSA 107:0-43
PSA 107:0-14 = PSA 108:0-14
PSA 108:0-31 = PSA 109:0-31
PSA 109:0-7 = PSA 110:0-7
PSA 110:0-10 = PSA 111:0-10
PSA 111:0-10 = PSA 112:0-10
PSA 112:0-9 = PSA 113:0-9
PSA 113:0-8 = PSA 114:0-8
PSA 113:9 = PSA 115:0
PSA 113:9-26 = PSA 115:1-18
PSA 114:0-8 = PSA 116:0-8
PSA 114:8 = PSA 116:9
PSA 115:0-10 = PSA 116:10-19	
PSA 116:0-2 = PSA 117:0-2
PSA 117:0-29 = PSA 118:0-29
PSA 118:0-176 = PSA 119:0-176
PSA 119:0-7 = PSA 120:0-7
PSA 120:0-8 = PSA 121:0-8
PSA 121:0-9 = PSA 122:0-9
PSA 122:0-4 = PSA 123:0-4
PSA 123:0-8 = PSA 124:0-8
PSA 124:0-5 = PSA 125:0-5
PSA 125:0-6 = PSA 126:0-6
PSA 126:0-5 = PSA 127:0-5
PSA 127:0-6 = PSA 128:0-6
PSA 128:0-8 = PSA 129:0-8
PSA 129:0-8 = PSA 130:0-8
PSA 130:0-3 = PSA 131:0-3
PSA 131:0-18 = PSA 132:0-18
PSA 132:0-3 = PSA 133:0-3
PSA 133:0-3 = PSA 134:0-3
PSA 134:0-21 = PSA 135:0-21
PSA 135:0-26 = PSA 136:0-26
PSA 136:0-9 = PSA 137:0-9
PSA 137:0-8 = PSA 138:0-8
PSA 138:0-24 = PSA 139:0-24
PSA 139:0-14 = PSA 140:0-14
PSA 140:0-10 = PSA 141:0-10
PSA 141:0 = PSA 142:0
PSA 141:1-7 = PSA 142:2-8
PSA 142:0-12 = PSA 143:0-12
PSA 143:0-15 = PSA 144:0-15
PSA 144:0-21 = PSA 145:0-21
PSA 145:0-10 = PSA 146:0-10
# 146 + 147 -> 147
PSA 146:0-11 = PSA 147:0-11
PSA 147:0 = PSA 147:12
PSA 147:1-9 = PSA 147:12-20
#---------------------------
# additional LXX Psalm
PSA 151:1-7 = PS2 1:1-7
#----------------------------
PRO 13:15-26 = PRO 13:14-25
PRO 18:9-25 = PRO 18:8-24
SNG 1:1-16 = SNG 1:2-17
# ISA 3:19 = ISA 3:19-20
ISA 3:19 = ISA 3:19
ISA 3:19 = ISA 3:20
ISA 3:20-25 = ISA 3:16-21
ISA 9:1 = ISA 8:23
ISA 9:2-21 = ISA 9:1-20
ISA 63:19 = ISA 63:19
ISA 64:1 = ISA 63:19
ISA 64:2-12 = ISA 64:1-11
JER 9:1 = JER 8:23
JER 9:2-26 = JER 9:1-25
EZK 20:45-49 = EZK 21:1-5
EZK 21:1-32 = EZK 21:6-37
HOS 1:10-11 = HOS 2:1-2
HOS 2:1-23 = HOS 2:3-25
HOS 11:12 = HOS 12:1
HOS 12:1-14 = HOS 12:2-15
JOL 2:28-32 = JOL 3:1-5
JOL 3:1-21 = JOL 4:1-21
MIC 5:1 = MIC 4:14
MIC 5:2-15 = MIC 5:1-14
NAM 1:15 = NAM 2:1
NAM 2:1-13 = NAM 2:2-14
ZEC 1:18-21 = ZEC 2:1-4
ZEC 2:1-13 = ZEC 2:5-17
MAL 4:1-6 = MAL 3:19-24
ROM 14:24-26 = ROM 16:25-27
# 2CO 11:32 = 2CO 11:32-33
2CO 11:32 = 2CO 11:32
2CO 11:32 = 2CO 11:33
# REV 13:1 = REV 12:18-13:1
REV 13:1 = REV 12:18
REV 13:1 = REV 13:1
#----------------------------
2ES 7:36-70 = 2ES 7:106-140
# 2ES 10:59-60 = 2ES 10:59
2ES 10:59 = 2ES 10:59
2ES 10:60 = 2ES 10:59
#---------------------------------------------------------
# Mapping 2 Esdras onto the older Apocalypse of Ezra [Studge]
2ES 3:1-36 = EZA 1:1-36
2ES 4:1-52 = EZA 2:1-52
2ES 5:1-56 = EZA 3:1-56
2ES 6:1-59 = EZA 4:1-59
2ES 7:1-35 = EZA 5:1-35
2ES 7:106-140 = EZA 5:36-70
2ES 8:1-63 = EZA 6:1-63
2ES 9:1-47 = EZA 7:1-47
2ES 10:1-60 = EZA 8:1-60
2ES 11:1-46 = EZA 9:1-46
2ES 12:1-51 = EZA 10:1-51
2ES 13:1-58 = EZA 11:1-58
2ES 14:1-48 = EZA 12:1-48
#----------------------------------------------------
# Mapping Daniel to Hebrew Daniel and Greek additions [HAB]
DAN 3:24-90 = DAG 3:24-90
DAN 3:91-100 = DAN 3:24-33
# Susanna
DAN 13:1-64 = SUS 1:1-64
# Bel and the Dragon
DAN 14:1-42 = BEL 1:1-42
#--------------------------------------------------
# Mapping Esther Greek onto LXX Esther Greek
#
# This maps the standard verses generated by Create Book
# to the actual verse numbers and segments found in the LXX
# ESG chapter 1
ESG 1:1 = ESG 1:1a
ESG 1:2 = ESG 1:1b
ESG 1:3 = ESG 1:1c
ESG 1:4 = ESG 1:1d
ESG 1:5 = ESG 1:1e
ESG 1:6 = ESG 1:1f
ESG 1:7 = ESG 1:1g
ESG 1:8 = ESG 1:1h
ESG 1:9 = ESG 1:1i
ESG 1:10 = ESG 1:1k
ESG 1:11 = ESG 1:1l
ESG 1:12 = ESG 1:1m
ESG 1:13 = ESG 1:1n
ESG 1:14 = ESG 1:1o
ESG 1:15 = ESG 1:1p
ESG 1:16 = ESG 1:1q
ESG 1:17 = ESG 1:1r
ESG 1:18 = ESG 1:1s
ESG 1:19-39 = ESG 1:2-22
# ESG chapter 3
ESG 3:14 = ESG 3:13a
ESG 3:15 = ESG 3:13b
ESG 3:16 = ESG 3:13c
ESG 3:17 = ESG 3:13d
ESG 3:18 = ESG 3:13e
ESG 3:19 = ESG 3:13f
ESG 3:20 = ESG 3:13g
ESG 3:21 = ESG 3:14
ESG 3:22 = ESG 3:15
# ESG chapter 4
ESG 4:18 = ESG 4:17a
ESG 4:19 = ESG 4:17b
ESG 4:20 = ESG 4:17c
ESG 4:21 = ESG 4:17c
ESG 4:22 = ESG 4:17d
ESG 4:23 = ESG 4:17d
ESG 4:24 = ESG 4:17e
ESG 4:25 = ESG 4:17f
ESG 4:26 = ESG 4:17g
ESG 4:27 = ESG 4:17h
ESG 4:28 = ESG 4:17i
ESG 4:29 = ESG 4:17k
ESG 4:30 = ESG 4:17k
ESG 4:31 = ESG 4:17k
ESG 4:32 = ESG 4:17l
ESG 4:33 = ESG 4:17m
ESG 4:34 = ESG 4:17n
ESG 4:35 = ESG 4:17n
ESG 4:36 = ESG 4:17o
ESG 4:37 = ESG 4:17o
ESG 4:38 = ESG 4:17p
ESG 4:39 = ESG 4:17q
ESG 4:40 = ESG 4:17r
ESG 4:41 = ESG 4:17s
ESG 4:42 = ESG 4:17t
ESG 4:43 = ESG 4:17u
ESG 4:44 = ESG 4:17w
ESG 4:45 = ESG 4:17x
ESG 4:46 = ESG 4:17y
ESG 4:47 = ESG 4:17z
# ESG chapter 5
ESG 5:2 = ESG 5:1a
ESG 5:3 = ESG 5:1a
ESG 5:4 = ESG 5:1a
ESG 5:5 = ESG 5:1b
ESG 5:6 = ESG 5:1c
ESG 5:7 = ESG 5:1d
ESG 5:8 = ESG 5:1e
ESG 5:9 = ESG 5:1f
ESG 5:10 = ESG 5:1f
ESG 5:11 = ESG 5:2
ESG 5:12 = ESG 5:2
ESG 5:13 = ESG 5:2a
ESG 5:14 = ESG 5:2a
ESG 5:15 = ESG 5:2b
ESG 5:16 = ESG 5:2b
ESG 5:17-28 = ESG 5:3-14
# ESG chapter 8
ESG 8:13 = ESG 8:12a
ESG 8:14 = ESG 8:12b
ESG 8:15 = ESG 8:12c
ESG 8:16 = ESG 8:12d
ESG 8:17 = ESG 8:12e
ESG 8:18 = ESG 8:12f
ESG 8:19 = ESG 8:12g
ESG 8:20 = ESG 8:12h
ESG 8:21 = ESG 8:12i
ESG 8:22 = ESG 8:12k
ESG 8:23 = ESG 8:12l
ESG 8:24 = ESG 8:12m
ESG 8:25 = ESG 8:12n
ESG 8:26 = ESG 8:12o
ESG 8:27 = ESG 8:12p
ESG 8:28 = ESG 8:12q
ESG 8:29 = ESG 8:12r
ESG 8:30 = ESG 8:12s
ESG 8:31 = ESG 8:12t
ESG 8:32 = ESG 8:12u
ESG 8:33 = ESG 8:12x
ESG 8:34 = ESG 8:12y
ESG 8:35 = ESG 8:12y
ESG 8:36 = ESG 8:12y
ESG 8:37-41 = ESG 8:13-17
# ESG chapter 10
ESG 10:4 = ESG 10:3a
ESG 10:5 = ESG 10:3b
ESG 10:6 = ESG 10:3c
ESG 10:7 = ESG 10:3d
ESG 10:8 = ESG 10:3e
ESG 10:9 = ESG 10:3f
ESG 10:10 = ESG 10:3g
ESG 10:11 = ESG 10:3h
ESG 10:12 = ESG 10:3i
ESG 10:13 = ESG 10:3k
ESG 10:14 = ESG 10:3l
`;
const vulText = `# Versification  "Vulgate"
# Version=1.5
# 
# modifications by Studge 26/June/2009
# this is for Bibles which follow the versification of the Vulgate, mainly Catholic Bibles
# therefore this includes deuterocanonical books from Vulgate and Latin manuscripts
# Vulgate projects in Paratext are VUL83 (Stuttgart text) and NVL98 (Nova Vulgata) [Studge]
#
# mapping for XXA -> PSA has been deleted  [requested by RdB - Barb]
# XXB has been moved to LAO [Barb] Jan 2011
#
# No mapping done for TOB, JDT and SIR, since they seem to follow another 'vorlage' than LXX
# The versification of 2ES present here should become THE standard/original versification of this book! (Vulgate is 'the original' text of this book)
#
# List of books, chapters, verses
# One line per book.
# One entry for each chapter.
# Verse number is the maximum verse number for that chapter.
# See the lines containing ='s below for verse mappings.
#
#-----------------------------------------------------------
# Old Testament
GEN 1:31 2:25 3:24 4:26 5:32 6:22 7:24 8:22 9:29 10:32 11:32 12:20 13:18 14:24 15:21 16:16 17:27 18:33 19:38 20:18 21:34 22:24 23:20 24:67 25:34 26:35 27:46 28:22 29:35 30:43 31:55 32:32 33:20 34:31 35:29 36:43 37:36 38:30 39:23 40:23 41:57 42:38 43:34 44:34 45:28 46:34 47:31 48:22 49:32 50:25
EXO 1:22 2:25 3:22 4:31 5:23 6:30 7:25 8:32 9:35 10:29 11:10 12:51 13:22 14:31 15:27 16:36 17:16 18:27 19:25 20:26 21:36 22:31 23:33 24:18 25:40 26:37 27:21 28:43 29:46 30:38 31:18 32:35 33:23 34:35 35:35 36:38 37:29 38:31 39:43 40:36
LEV 1:17 2:16 3:17 4:35 5:19 6:30 7:38 8:36 9:24 10:20 11:47 12:8 13:59 14:57 15:33 16:34 17:16 18:30 19:37 20:27 21:24 22:33 23:44 24:23 25:55 26:45 27:34
NUM 1:54 2:34 3:51 4:49 5:31 6:27 7:89 8:26 9:23 10:36 11:34 12:15 13:34 14:45 15:41 16:50 17:13 18:32 19:22 20:30 21:35 22:41 23:30 24:25 25:18 26:65 27:23 28:31 29:39 30:17 31:54 32:42 33:56 34:29 35:34 36:13
DEU 1:46 2:37 3:29 4:49 5:33 6:25 7:26 8:20 9:29 10:22 11:32 12:32 13:18 14:29 15:23 16:22 17:20 18:22 19:21 20:20 21:23 22:30 23:25 24:22 25:19 26:19 27:26 28:68 29:29 30:20 31:30 32:52 33:29 34:12
JOS 1:18 2:24 3:17 4:25 5:16 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:43 22:34 23:16 24:33
JDG 1:36 2:23 3:31 4:24 5:32 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:24
RUT 1:22 2:23 3:18 4:22
1SA 1:28 2:36 3:21 4:22 5:12 6:21 7:17 8:22 9:27 10:27 11:15 12:25 13:23 14:52 15:35 16:23 17:58 18:30 19:24 20:43 21:15 22:23 23:28 24:23 25:44 26:25 27:12 28:25 29:11 30:31 31:13
2SA 1:27 2:32 3:39 4:12 5:25 6:23 7:29 8:18 9:13 10:19 11:27 12:31 13:39 14:33 15:37 16:23 17:29 18:33 19:43 20:26 21:22 22:51 23:39 24:25
1KI 1:53 2:46 3:28 4:34 5:18 6:38 7:51 8:66 9:28 10:29 11:43 12:33 13:34 14:31 15:34 16:34 17:24 18:46 19:21 20:43 21:29 22:54
2KI 1:18 2:25 3:27 4:44 5:27 6:33 7:20 8:29 9:37 10:36 11:21 12:21 13:25 14:29 15:38 16:20 17:41 18:37 19:37 20:21 21:26 22:20 23:37 24:20 25:30
1CH 1:54 2:55 3:24 4:43 5:26 6:81 7:40 8:40 9:44 10:14 11:46 12:40 13:14 14:17 15:29 16:43 17:27 18:17 19:19 20:7 21:30 22:19 23:32 24:31 25:31 26:32 27:34 28:21 29:30
2CH 1:17 2:18 3:17 4:22 5:14 6:42 7:22 8:18 9:31 10:19 11:23 12:16 13:22 14:15 15:19 16:14 17:19 18:34 19:11 20:37 21:20 22:12 23:21 24:27 25:28 26:23 27:9 28:27 29:36 30:27 31:21 32:33 33:25 34:33 35:27 36:23
EZR 1:11 2:70 3:13 4:24 5:17 6:22 7:28 8:36 9:15 10:44
# EZR is for the Vulgate book called 1 Esdras
NEH 1:11 2:20 3:31 4:23 5:19 6:19 7:73 8:18 9:38 10:39 11:36 12:46 13:31
# NEH is for the Vulgate book called 2 Esdras
#------------------------------------
# In the Vulgate projects VUL83 Esther is the Greek Esther not Hebrew Esther, this definition is for Greek Esther. The book has been put under EST instead of ESG [Studge]
# in VUL83 the definition of EST is
#EST 1:22 2:23 3:15 4:17 5:14 6:14 7:10 8:17 9:32 10:13 11:12 12:6 13:18 14:19 15:19 16:24
# in NVL98 Nova Vulgata the definition of EST is
EST 1:32 2:23 3:15 4:47 5:28 6:14 7:10 8:41 9:32 10:13 
# Note that chapter 3 v 15 is 15a-i
# Note that chapter 4 v 47 is 17aa-kk
#-----------------------------------
JOB 1:22 2:13 3:26 4:21 5:27 6:30 7:21 8:22 9:35 10:22 11:20 12:25 13:28 14:22 15:35 16:23 17:16 18:21 19:29 20:29 21:34 22:30 23:17 24:25 25:6 26:14 27:23 28:28 29:25 30:31 31:40 32:22 33:33 34:37 35:16 36:33 37:24 38:41 39:35 40:28 41:25 42:16
PSA 1:6 2:13 3:9 4:10 5:13 6:11 7:18 8:10 9:39 10:8 11:9 12:6 13:7 14:5 15:10 16:15 17:51 18:15 19:10 20:14 21:32 22:6 23:10 24:22 25:12 26:14 27:9 28:11 29:13 30:25 31:11 32:22 33:23 34:28 35:13 36:40 37:23 38:14 39:18 40:14 41:12 42:5 43:26 44:18 45:12 46:10 47:15 48:21 49:23 50:21 51:11 52:7 53:9 54:24 55:13 56:12 57:12 58:18 59:14 60:9 61:13 62:12 63:11 64:14 65:20 66:8 67:36 68:37 69:6 70:24 71:20 72:28 73:23 74:11 75:13 76:21 77:72 78:13 79:20 80:17 81:8 82:19 83:13 84:14 85:17 86:7 87:19 88:53 89:17 90:16 91:16 92:5 93:23 94:11 95:13 96:12 97:9 98:9 99:5 100:8 101:29 102:22 103:35 104:45 105:48 106:43 107:14 108:31 109:7 110:10 111:10 112:9 113:26 114:9 115:19 116:2 117:29 118:176 119:7 120:8 121:9 122:4 123:8 124:5 125:6 126:5 127:6 128:8 129:8 130:3 131:18 132:3 133:3 134:21 135:26 136:9 137:8 138:24 139:14 140:10 141:8 142:12 143:15 144:21 145:10 146:11 147:20 148:14 149:9 150:6
PRO 1:33 2:22 3:35 4:27 5:23 6:35 7:27 8:36 9:18 10:32 11:31 12:28 13:25 14:35 15:33 16:33 17:28 18:24 19:29 20:30 21:31 22:29 23:35 24:34 25:28 26:28 27:27 28:28 29:27 30:33 31:31
ECC 1:18 2:26 3:22 4:17 5:19 6:11 7:30 8:17 9:18 10:20 11:10 12:14
SNG 1:16 2:17 3:11 4:16 5:17 6:12 7:13 8:14
ISA 1:31 2:22 3:26 4:6 5:30 6:13 7:25 8:22 9:21 10:34 11:16 12:6 13:22 14:32 15:9 16:14 17:14 18:7 19:25 20:6 21:17 22:25 23:18 24:23 25:12 26:21 27:13 28:29 29:24 30:33 31:9 32:20 33:24 34:17 35:10 36:22 37:38 38:22 39:8 40:31 41:29 42:25 43:28 44:28 45:25 46:13 47:15 48:22 49:26 50:11 51:23 52:15 53:12 54:17 55:13 56:12 57:21 58:14 59:21 60:22 61:11 62:12 63:19 64:12 65:25 66:24
JER 1:19 2:37 3:25 4:31 5:31 6:30 7:34 8:22 9:26 10:25 11:23 12:17 13:27 14:22 15:21 16:21 17:27 18:23 19:15 20:18 21:14 22:30 23:40 24:10 25:38 26:24 27:22 28:17 29:32 30:24 31:40 32:44 33:26 34:22 35:19 36:32 37:20 38:28 39:18 40:16 41:18 42:22 43:13 44:30 45:5 46:28 47:7 48:47 49:39 50:46 51:64 52:34
LAM 1:22 2:22 3:66 4:22 5:22
EZK 1:28 2:9 3:27 4:17 5:17 6:14 7:27 8:18 9:11 10:22 11:25 12:28 13:23 14:23 15:8 16:63 17:24 18:32 19:14 20:49 21:32 22:31 23:49 24:27 25:17 26:21 27:36 28:26 29:21 30:26 31:18 32:32 33:33 34:31 35:15 36:38 37:28 38:23 39:29 40:49 41:26 42:20 43:27 44:31 45:25 46:24 47:23 48:35
#-------------------
# Daniel in NVL98 has 14 chapters and is Greek LXX Daniel
# the Additions to Daniel are repeated in S3Y, SUS and BEL in NVL98
# in NVL98 and VUL83, DAN is used for Greek Daniel and it should be under DAG
DAN 1:21 2:49 3:100 4:34 5:31 6:28 7:28 8:27 9:27 10:21 11:45 12:13 13:65 14:41
#
#--------------------
HOS 1:11 2:24 3:5 4:19 5:15 6:11 7:16 8:14 9:17 10:15 11:12 12:14 13:15 14:10
JOL 1:20 2:32 3:21
AMO 1:15 2:16 3:15 4:13 5:27 6:15 7:17 8:14 9:15
OBA 1:21
JON 1:16 2:11 3:10 4:11
MIC 1:16 2:13 3:12 4:13 5:14 6:16 7:20
NAM 1:15 2:13 3:19
HAB 1:17 2:20 3:19
ZEP 1:18 2:15 3:20
HAG 1:14 2:24
ZEC 1:21 2:13 3:10 4:14 5:11 6:15 7:14 8:23 9:17 10:12 11:17 12:14 13:9 14:21
MAL 1:14 2:17 3:18 4:6
#--------------------------------------
# New Testament books
MAT 1:25 2:23 3:17 4:25 5:48 6:34 7:29 8:34 9:38 10:42 11:30 12:50 13:58 14:36 15:39 16:28 17:26 18:35 19:30 20:34 21:46 22:46 23:39 24:51 25:46 26:75 27:66 28:20
MRK 1:45 2:28 3:35 4:40 5:43 6:56 7:37 8:39 9:49 10:52 11:33 12:44 13:37 14:72 15:47 16:20
LUK 1:80 2:52 3:38 4:44 5:39 6:49 7:50 8:56 9:62 10:42 11:54 12:59 13:35 14:35 15:32 16:31 17:37 18:43 19:48 20:47 21:38 22:71 23:56 24:53
JHN 1:51 2:25 3:36 4:54 5:47 6:72 7:53 8:59 9:41 10:42 11:57 12:50 13:38 14:31 15:27 16:33 17:26 18:40 19:42 20:31 21:25
ACT 1:26 2:47 3:26 4:37 5:42 6:15 7:59 8:40 9:43 10:48 11:30 12:25 13:52 14:27 15:41 16:40 17:34 18:28 19:40 20:38 21:40 22:30 23:35 24:27 25:27 26:32 27:44 28:31
ROM 1:32 2:29 3:31 4:25 5:21 6:23 7:25 8:39 9:33 10:21 11:36 12:21 13:14 14:23 15:33 16:27
1CO 1:31 2:16 3:23 4:21 5:13 6:20 7:40 8:13 9:27 10:33 11:34 12:31 13:13 14:40 15:58 16:24
2CO 1:24 2:17 3:18 4:18 5:21 6:18 7:16 8:24 9:15 10:18 11:33 12:21 13:13
GAL 1:24 2:21 3:29 4:31 5:26 6:18
EPH 1:23 2:22 3:21 4:32 5:33 6:24
PHP 1:30 2:30 3:21 4:23
COL 1:29 2:23 3:25 4:18
1TH 1:10 2:20 3:13 4:18 5:28
2TH 1:12 2:17 3:18
1TI 1:20 2:15 3:16 4:16 5:25 6:21
2TI 1:18 2:26 3:17 4:22
TIT 1:16 2:15 3:15
PHM 1:25
HEB 1:14 2:18 3:19 4:16 5:14 6:20 7:28 8:13 9:28 10:39 11:40 12:29 13:25
JAS 1:27 2:26 3:18 4:17 5:20
1PE 1:25 2:25 3:22 4:19 5:14
2PE 1:21 2:22 3:18
1JN 1:10 2:29 3:24 4:21 5:21
2JN 1:13
3JN 1:15
JUD 1:25
REV 1:20 2:29 3:22 4:11 5:14 6:17 7:17 8:13 9:21 10:11 11:19 12:18 13:18 14:20 15:8 16:21 17:18 18:24 19:21 20:15 21:27 22:21
#-------------------------------------------------
# Deuterocanonical books in the Catholic tradition
TOB 1:25 2:23 3:25 4:23 5:28 6:22 7:20 8:24 9:12 10:13 11:21 12:22 13:23 14:17
JDT 1:12 2:18 3:15 4:17 5:29 6:21 7:25 8:34 9:19 10:20 11:21 12:20 13:31 14:18 15:15 16:31
#---------
# ESG for Esther Greek has been put under EST in NVL98, a blank ESG was included in VUL83
# this definition for ESG is for the full Esther Greek which is in the Vulgate NVL98 [Studge]
ESG 1:39 2:23 3:22 4:47 5:28 6:14 7:10 8:39 9:32 10:13
#---------
WIS 1:16 2:25 3:19 4:20 5:24 6:27 7:30 8:21 9:19 10:21 11:27 12:27 13:19 14:31 15:19 16:29 17:20 18:25 19:20
SIR 1:40 2:23 3:34 4:36 5:18 6:37 7:40 8:22 9:25 10:34 11:36 12:19 13:32 14:27 15:22 16:31 17:31 18:33 19:28 20:33 21:31 22:33 23:38 24:47 25:36 26:28 27:33 28:30 29:35 30:27 31:42 32:28 33:33 34:31 35:26 36:28 37:34 38:39 39:41 40:32 41:28 42:26 43:37 44:27 45:31 46:23 47:31 48:28 49:19 50:31 51:38 52:13
BAR 1:22 2:35 3:38 4:37 5:9 6:72
LJE 1:72
# NB Letter of Jeremiah is chapter 6 of Baruch in the Vulgate tradition [Studge]
# the 3 additions to Daniel are part of Daniel in the Vulgate tradition [Studge]
S3Y 1:67
SUS 1:64
BEL 1:42
1MA 1:67 2:70 3:60 4:61 5:68 6:63 7:50 8:32 9:73 10:89 11:74 12:54 13:54 14:49 15:41 16:24
2MA 1:36 2:33 3:40 4:50 5:27 6:31 7:42 8:36 9:29 10:38 11:38 12:46 13:26 14:46 15:40
#--------------------------------------------------
# Note that 3MA and 4MA are in the LXX tradition but not in the Vulgate, and not in VUL83 Latin critical text, but maybe in Interconfessional editions [Studge]
3MA 1:29 2:33 3:30 4:21 5:51 6:41 7:23
4MA 1:35 2:24 3:21 4:26 5:38 6:35 7:23 8:29 9:32 10:21 11:27 12:19 13:27 14:20 15:32 16:25 17:24 18:24
#----------------------------------------------------
# 1ES, 2ES, MAN and PS2 are in the Vulgate Apocrypha, but not in modern Catholic Bibles, but maybe in Interconfessional editions [Studge]
1ES 1:58 2:31 3:24 4:63 5:73 6:34 7:15 8:97 9:56
# 1ES is for the Vulgate book called 3 Esdras
2ES 1:40 2:48 3:36 4:52 5:55 6:59 7:139 8:63 9:47 10:60 11:46 12:51 13:58 14:47 15:63 16:78
# 2ES is for the Vulgate book called 4 Esdras
MAN 1:15
PS2 1:7
#-----------------------------------------------------
# ODA and PSS are only in LXX and SYR and not needed in any Vulgate manuscripts or any Catholic Bibles, I am not convinced they are needed in this versification file [Studge]
#ODA 1:19 2:43 3:10 4:19 5:12 6:8 7:20 8:37 9:22 10:9 11:11 12:15 13:4 14:46
#PSS 1:8 2:37 3:12 4:25 5:19 6:6 7:10 8:34 9:11 10:8 11:9 12:6 13:12 14:10 15:13 16:15 17:46 18:12
#------------------------------------------------------
# Variant LXX books, only used in LXX, now obselete in Paratext 7, never part of Vulgate
# if these codes were used in any Vulgate versification projects they used the wrong code, and so the definitions are not relevant [Studge]
# JSA 1:18 2:24 3:17 4:24 5:15 6:27 7:26 8:35 9:27 10:43 11:23 12:24 13:33 14:15 15:63 16:10 17:18 18:28 19:51 20:9 21:45 22:34 23:16 24:33
# JDB 1:36 2:23 3:31 4:24 5:31 6:40 7:25 8:35 9:57 10:18 11:40 12:15 13:25 14:20 15:20 16:31 17:13 18:31 19:30 20:48 21:25
# TBS 1:22 2:14 3:17 4:21 5:23 6:19 7:17 8:21 9:6 10:14 11:19 12:22 13:18 14:15
# SST 1:64
# DNT 1:21 2:49 3:97 4:37 5:30 6:29 7:28 8:27 9:27 10:21 11:45 12:13
# BLT 1:42
#------------------------------------------------------
# add in versifications for 4,5 & 6 Ezra which are in Latin manuscripts [Studge]
5EZ 1:40 2:48 
EZA 1:36 2:52 3:55 4:59 5:139 6:63 7:47 8:60 9:46 10:51 11:58 12:47 
6EZ 1:63 12:78
#------------------------------------------------------
# XXA and XXB books in project VUL83, left for backward compatability
# XXA was used for a variant form of Psalms, but should be in a Latin Variant project [Studge]
# XXA 1:6 2:13 3:9 4:10 5:13 6:11 7:18 8:10 9:39 10:8 11:9 12:6 13:7 14:5 15:10 16:15 17:51 18:15 19:10 20:14 21:32 22:6 23:10 24:22 25:12 26:14 27:9 28:11 29:13 30:25 31:11 32:22 33:23 34:28 35:13 36:40 37:23 38:14 39:18 40:14 41:12 42:5 43:26 44:18 45:12 46:10 47:15 48:21 49:23 50:21 51:11 52:7 53:9 54:24 55:13 56:12 57:12 58:18 59:14 60:9 61:13 62:12 63:11 64:14 65:20 66:8 67:36 68:37 69:6 70:24 71:20 72:28 73:23 74:11 75:13 76:21 77:72 78:13 79:20 80:17 81:8 82:19 83:13 84:14 85:17 86:7 87:19 88:53 89:17 90:16 91:16 92:5 93:23 94:11 95:13 96:12 97:9 98:9 99:5 100:8 101:29 102:22 103:35 104:45 105:48 106:43 107:14 108:31 109:7 110:10 111:10 112:9 113:26 114:9 115:19 116:2 117:29 118:176 119:7 120:8 121:9 122:4 123:8 124:5 125:6 126:5 127:6 128:8 129:8 130:3 131:18 132:3 133:3 134:21 135:26 136:9 137:8 138:24 139:14 140:10 141:8 142:12 143:15 144:21 145:10 146:11 147:20 148:14 149:9 150:6
# XXB was used for the Letter to the Laodiceans, but should be under LAO [Studge]
# XXB 1:20
#----------------------------------------------------------
# Daniel Greek is currently under DAN [Studge]
DAG 1:21 2:49 3:97 4:37 5:31 6:28 7:28 8:27 9:27 10:21 11:45 12:13 13:64 14:42
# Letter to the Laodiceans in the VUL83 and some mediaeval translations of the Vulgate e.g. John Wycliffe's English Bible, appeared after Revelation [Studge]
LAO 1:20
#----------------------------------------------------------
# Mapping
#----------------------------------------------------------
# Vulgate = BHS (see org.vrs)
#
# (Note: for performance reasons ranges must not span a chapter, e.g. 4:10-5:11 is illegal)
#
GEN 31:55 = GEN 32:1
GEN 32:1-32 = GEN 32:2-33
# missing <- GEN 49:32
GEN 49:31 = GEN 49:31
GEN 49:31 = GEN 49:32
GEN 49:32 = GEN 49:33
# GEN 50:22 <- GEN 50:22-23
GEN 50:22 = GEN 50:22
GEN 50:22 = GEN 50:23
GEN 50:23-25 = GEN 50:24-26
EXO 8:1-4 = EXO 7:26-29
EXO 8:5-32 = EXO 8:1-28
EXO 22:1 = EXO 21:37
EXO 22:2-31 = EXO 22:1-30
# EXO 40:13 <- EXO 40:13-15
EXO 40:13 = EXO 40:13
EXO 40:13 = EXO 40:14
EXO 40:13 = EXO 40:15
EXO 40:14-36 = EXO 40:16-38
LEV 6:1-7 = LEV 5:20-26
LEV 6:8-30 = LEV 6:1-23
# LEV 26:45 <- LEV 26:45-46
LEV 26:45 = LEV 26:45
LEV 26:45 = LEV 26:46
# NUM 11:34 <- NUM 11:34-35
NUM 11:34 = NUM 11:34
NUM 11:34 = NUM 11:35
NUM 13:1 = NUM 12:16
NUM 13:2-34 = NUM 13:1-33
NUM 16:36-50 = NUM 17:1-15
NUM 17:1-13 = NUM 17:16-28
# NUM 20:28-29 -> NUM 20:28
NUM 20:28 = NUM 20:28
NUM 20:29 = NUM 20:28
NUM 20:30 = NUM 20:29
# NUM 26:1 <- NUM 25:19--26:1
NUM 26:1 = NUM 25:19
NUM 26:1 = NUM 26:1
DEU 12:32 = DEU 13:1
DEU 13:1-18 = DEU 13:2-19
DEU 22:30 = DEU 23:1
DEU 23:1-25 = DEU 23:2-26
DEU 29:1 = DEU 28:69
DEU 29:2-29 = DEU 29:1-28
# JOS 4:23-24 -> JOS 4:23
JOS 4:23 = JOS 4:23
JOS 4:24 = JOS 4:23
JOS 4:25 = JOS 4:24
# JOS 5:14-15 -> JOS 5:14
JOS 5:14 = JOS 5:14
JOS 5:15 = JOS 5:14
JOS 5:16 = JOS 5:15
# JOS 21:36 (missing) <- JOS 21:36-37
JOS 21:36 = JOS 21:36
JOS 21:36 = JOS 21:37
# JOS 21:37 <- JOS 21:38-39
JOS 21:37 = JOS 21:38
JOS 21:37 = JOS 21:39
JOS 21:38-43 = JOS 21:40-45
# JDG 5:31-32 -> JDG 5:31
JDG 5:31 = JDG 5:31
JDG 5:32 = JDG 5:31
# JDG 21:24 <- JDG 21:24-25
JDG 21:24 = JDG 21:24
JDG 21:24 = JDG 21:25
1SA 20:43 = 1SA 21:1
1SA 21:1-15 = 1SA 21:2-16
2SA 18:33 = 2SA 19:1
2SA 19:1-43 = 2SA 19:2-44
1KI 4:21-34 = 1KI 5:1-14
1KI 5:1-18 = 1KI 5:15-32
2KI 11:21 = 2KI 12:1
2KI 12:1-21 = 2KI 12:2-22
1CH 6:1-15 = 1CH 5:27-41
1CH 6:16-81 = 1CH 6:1-66
# 1CH 11:46 <- 1CH 11:46-47
1CH 11:46 = 1CH 11:46
1CH 11:46 = 1CH 11:47
# 1CH 12:4 <- 1CH 12:4-5
1CH 12:4 = 1CH 12:4
1CH 12:4 = 1CH 12:5
1CH 12:5-40 = 1CH 12:6-41
# 1CH 20:7 <- 1CH 20:7-8
1CH 20:7 = 1CH 20:7
1CH 20:7 = 1CH 20:8
2CH 2:1 = 2CH 1:18
2CH 2:2-18 = 2CH 2:1-17
2CH 14:1 = 2CH 13:23
2CH 14:2-15 = 2CH 14:1-14
# NEH 3:30 <- NEH 3:30-31
NEH 3:30 = NEH 3:30
NEH 3:30 = NEH 3:31
NEH 3:31 = NEH 3:32
NEH 4:1-6 = NEH 3:33-38
NEH 4:7-23 = NEH 4:1-17
# NEH 7:68 (missing) -> NEH 7:67b
NEH 7:67 = NEH 7:67
NEH 7:68 = NEH 7:67
NEH 7:69-73 = NEH 7:68-72
NEH 9:38 = NEH 10:1
NEH 10:1-39 = NEH 10:2-40
# NEH 12:33 <- NEH 12:33-34
NEH 12:33 = NEH 12:33
NEH 12:33 = NEH 12:34
NEH 12:34-46 = NEH 12:35-47
# mapping EST onto ESG, it should map ESG onto EST
#EST 10:4-13 = ESG 1:4-13
#EST 11:1-12 = ESG 2:1-12
#EST 12:1-6 = ESG 3:1-6
#EST 13:1-18 = ESG 4:1-18
#EST 14:1-19 = ESG 5:1-19
#EST 15:1-16 = ESG 6:1-16
#EST 16:1-24 = ESG 7:1-24
# JOB 16:4-5 -> JOB 16:4
JOB 16:4 = JOB 16:4
JOB 16:5 = JOB 16:4
JOB 16:6-23 = JOB 16:5-22
JOB 39:31-35 = JOB 40:1-5
JOB 40:1-27 = JOB 40:6-32
JOB 40:28 = JOB 41:1
JOB 41:1-25 = JOB 41:2-26
# JOB 42:16 <- JOB 42:16-17
JOB 42:16 = JOB 42:16
JOB 42:16 = JOB 42:17
# In PSA, the equivalent mappings (in chs. 1-9; 147-150) are given too, because XXA is mapped to PSA as well !!!
# There could still be some errors regarding the irregular mapping of psalm titles (like in PSA 12:1 <- PSA 13:1-2)
PSA 1:0-6 = PSA 1:0-6
PSA 2:0-11 = PSA 2:0-11
# PSA 2:12-13 -> PSA 2:12
PSA 2:12 = PSA 2:12
PSA 2:13 = PSA 2:12
PSA 3:0-9 = PSA 3:0-9
PSA 4:0-8 = PSA 4:0-8
# PSA 4:9-10 -> PSA 4:9
PSA 4:9 = PSA 4:9
PSA 4:10 = PSA 4:9
PSA 5:0-13 = PSA 5:0-13
PSA 6:0-11 = PSA 6:0-11
PSA 7:0-18 = PSA 7:0-18
PSA 8:0-10 = PSA 8:0-10
PSA 9:0-21 = PSA 9:0-21
PSA 9:22 = PSA 10:0
PSA 9:22-39 = PSA 10:1-18
# PSA 10:1-2 -> PSA 11:1
PSA 10:0-1 = PSA 11:0-1
PSA 10:2 = PSA 11:1
PSA 10:3-8 = PSA 11:2-7
PSA 11:0-9 = PSA 12:0-9
# PSA 12:1 <- PSA 13:1-2
PSA 12:0-1 = PSA 13:0-1
PSA 12:1 = PSA 13:2
# PSA 12:2-3 -> PSA 13:3
PSA 12:2 = PSA 13:3
PSA 12:3 = PSA 13:3
PSA 12:4-6 = PSA 13:4-6
PSA 13:0-7 = PSA 14:0-7
PSA 14:0-1 = PSA 15:0-1
# PSA 14:3a = PSA 15:2b
PSA 14:2 = PSA 15:2
PSA 14:3 = PSA 15:2
PSA 14:3 = PSA 15:3
PSA 14:4-5 = PSA 15:4-5
PSA 15:0-9 = PSA 16:0-9
# PSA 15:10 <- PSA 16:10-11
PSA 15:10 = PSA 16:10
PSA 15:10 = PSA 16:11
PSA 16:0-15 = PSA 17:0-15
PSA 17:0-51 = PSA 18:0-51
PSA 18:0-15 = PSA 19:0-15
PSA 19:0-10 = PSA 20:0-10
PSA 20:0-14 = PSA 21:0-14
PSA 21:0-32 = PSA 22:0-32
PSA 22:0-6 = PSA 23:0-6
PSA 23:0-10 = PSA 24:0-10
PSA 24:0-22 = PSA 25:0-22
PSA 25:0-12 = PSA 26:0-12
PSA 26:0-14 = PSA 27:0-14
PSA 27:0-9 = PSA 28:0-9
PSA 28:0-11 = PSA 29:0-11
PSA 29:0-13 = PSA 30:0-13
PSA 30:0-25 = PSA 31:0-25
PSA 31:0-11 = PSA 32:0-11
PSA 32:0-22 = PSA 33:0-22
PSA 33:0-23 = PSA 34:0-23
PSA 34:0-28 = PSA 35:0-28
PSA 35:0-13 = PSA 36:0-13
PSA 36:0-40 = PSA 37:0-40
PSA 37:0-23 = PSA 38:0-23
PSA 38:0-14 = PSA 39:0-14
PSA 39:0-18 = PSA 40:0-18
PSA 40:0-14 = PSA 41:0-14
PSA 41:0-12 = PSA 42:0-12
PSA 42:0-5 = PSA 43:0-5
PSA 43:0-21 = PSA 44:0-21
# PSA 43:22 <- PSA 44:22-23
PSA 43:22 = PSA 44:22
PSA 43:22 = PSA 44:23
PSA 43:23-26 = PSA 44:24-27
PSA 44:0-18 = PSA 45:0-18
PSA 45:0-12 = PSA 46:0-12
PSA 46:0-10 = PSA 47:0-10
PSA 47:0-15 = PSA 48:0-15
PSA 48:0-21 = PSA 49:0-21
PSA 49:0-23 = PSA 50:0-23
PSA 50:0-21 = PSA 51:0-21
PSA 51:0-11 = PSA 52:0-11
PSA 52:0-7 = PSA 53:0-7
PSA 53:0-9 = PSA 54:0-9
PSA 54:0-24 = PSA 55:0-24
PSA 55:0-10 = PSA 56:0-10
# PSA 55:11 <- PSA 56:11-12
PSA 55:11 = PSA 56:11
PSA 55:11 = PSA 56:12
PSA 55:12-13 = PSA 56:13-14
PSA 56:0-12 = PSA 57:0-12
PSA 57:0-12 = PSA 58:0-12
PSA 58:0-18 = PSA 59:0-18
PSA 59:0-14 = PSA 60:0-14
PSA 60:0-9 = PSA 61:0-9
PSA 61:0-13 = PSA 62:0-13
PSA 62:0-12 = PSA 63:0-12
PSA 63:0-11 = PSA 64:0-11
PSA 64:0-14 = PSA 65:0-14
PSA 65:0-20 = PSA 66:0-20
PSA 66:0-8 = PSA 67:0-8
PSA 67:0-36 = PSA 68:0-36
PSA 68:0-37 = PSA 69:0-37
PSA 69:0-6 = PSA 70:0-6
PSA 70:0-24 = PSA 71:0-24
PSA 71:0-20 = PSA 72:0-20
PSA 72:0-28 = PSA 73:0-28
PSA 73:0-23 = PSA 74:0-23
PSA 74:0-11 = PSA 75:0-11
PSA 75:0-13 = PSA 76:0-13
PSA 76:0-21 = PSA 77:0-21
PSA 77:0-72 = PSA 78:0-72
PSA 78:0-13 = PSA 79:0-13
PSA 79:0-20 = PSA 80:0-20
PSA 80:0-17 = PSA 81:0-17
PSA 81:0-8 = PSA 82:0-8
PSA 82:0-19 = PSA 83:0-19
PSA 83:0-13 = PSA 84:0-13
PSA 84:0-14 = PSA 85:0-14
PSA 85:0-17 = PSA 86:0-17
PSA 86:0-7 = PSA 87:0-7
PSA 87:0-19 = PSA 88:0-19
PSA 88:0-53 = PSA 89:0-53
PSA 89:0-17 = PSA 90:0-17
PSA 90:0-16 = PSA 91:0-16
PSA 91:0-16 = PSA 92:0-16
PSA 92:0-5 = PSA 93:0-5
PSA 93:0-23 = PSA 94:0-23
PSA 94:0-11 = PSA 95:0-11
PSA 95:0-13 = PSA 96:0-13
PSA 96:0-12 = PSA 97:0-12
PSA 97:0-9 = PSA 98:0-9
PSA 98:0-9 = PSA 99:0-9
PSA 99:0-5 = PSA 100:0-5
PSA 100:0-8 = PSA 101:0-8
PSA 101:0-29 = PSA 102:0-29
PSA 102:0-22 = PSA 103:0-22
PSA 103:0-35 = PSA 104:0-35
PSA 104:0-45 = PSA 105:0-45
PSA 105:0-48 = PSA 106:0-48
PSA 106:0-43 = PSA 107:0-43
PSA 107:0-14 = PSA 108:0-14
PSA 108:0-31 = PSA 109:0-31
PSA 109:0-7 = PSA 110:0-7
PSA 110:0-10 = PSA 111:0-10
PSA 111:0-10 = PSA 112:0-10
PSA 112:0-9 = PSA 113:0-9
PSA 113:0-8 = PSA 114:0-8
PSA 113:9 = PSA 115:0
PSA 113:9-26 = PSA 115:1-18
PSA 114:1-9 = PSA 116:1-9
# What does 115:1-9 map to?  this seems very wrong
PSA 115:10-19 = PSA 116:10-19
PSA 116:0-2 = PSA 117:0-2
PSA 117:0-29 = PSA 118:0-29
PSA 118:0-176 = PSA 119:0-176
PSA 119:0-7 = PSA 120:0-7
PSA 120:0-8 = PSA 121:0-8
PSA 121:0-9 = PSA 122:0-9
PSA 122:0-4 = PSA 123:0-4
PSA 123:0-8 = PSA 124:0-8
PSA 124:0-5 = PSA 125:0-5
PSA 125:0-6 = PSA 126:0-6
PSA 126:0-5 = PSA 127:0-5
PSA 127:0-6 = PSA 128:0-6
PSA 128:0-8 = PSA 129:0-8
PSA 129:0-8 = PSA 130:0-8
PSA 130:0-3 = PSA 131:0-3
PSA 131:0-18 = PSA 132:0-18
PSA 132:0-3 = PSA 133:0-3
PSA 133:0-3 = PSA 134:0-3
PSA 134:0-21 = PSA 135:0-21
PSA 135:0-26 = PSA 136:0-26
PSA 136:0-9 = PSA 137:0-9
PSA 137:0-8 = PSA 138:0-8
PSA 138:0-24 = PSA 139:0-24
PSA 139:0-14 = PSA 140:0-14
PSA 140:0-10 = PSA 141:0-10
PSA 141:0-8 = PSA 142:0-8
PSA 142:0-12 = PSA 143:0-12
PSA 143:0-15 = PSA 144:0-15
PSA 144:0-21 = PSA 145:0-21
# PSA 145:2a = PSA 146:1b
PSA 145:0-1 = PSA 146:0-1
PSA 145:2 = PSA 146:1
PSA 145:2 = PSA 146:2
PSA 145:3-10 = PSA 146:3-10
PSA 146:0-11 = PSA 147:0-11
PSA 147:12-20 = PSA 147:12-20
PSA 148:0-14 = PSA 148:0-14
PSA 149:0-9 = PSA 149:0-9
PSA 150:0-6 = PSA 150:0-6
ECC 7:1 = ECC 6:12
ECC 7:2-30 = ECC 7:1-29
SNG 1:1 = SNG 1:1
SNG 1:1-16 = SNG 1:2-17
SNG 5:17 = SNG 6:1
SNG 6:1-11 = SNG 6:2-12
# SNG 6:12 -> SNG 7:1a
# SNG 7:1 <- SNG 7:1b-2
# or:  SNG 6:12--7:1 = SNG 7:1-2
SNG 6:12 = SNG 7:1
SNG 7:1 = SNG 7:1
SNG 7:1 = SNG 7:2
SNG 7:2-13 = SNG 7:3-14
# ISA 8:22d = ISA 8:23a
ISA 8:22 = ISA 8:22
ISA 8:22 = ISA 8:23
ISA 9:1 = ISA 8:23
ISA 9:2-21 = ISA 9:1-20
# ISA 9:20d = ISA 9:20ab
ISA 9:20 = ISA 9:19
ISA 9:20 = ISA 9:20
ISA 9:21 = ISA 9:20
# ISA 64:1 -> ISA 63:19cd
ISA 63:19 = ISA 63:19
ISA 64:1 = ISA 63:19
ISA 64:2-12 = ISA 64:1-11
JER 9:1 = JER 8:23
JER 9:2-26 = JER 9:1-25
# JER 37:4 <- JER 37:4-5
JER 37:4 = JER 37:4
JER 37:4 = JER 37:5
JER 37:5-20 = JER 37:6-21
# EZK 2:9 <- EZK 2:9-10
EZK 2:9 = EZK 2:9
EZK 2:9 = EZK 2:10
EZK 20:45-49 = EZK 21:1-5
EZK 21:1-32 = EZK 21:6-37
DAN 3:24-90 = S3Y 1:1-67
DAN 3:91-100 = DAN 3:24-33
DAN 5:31 = DAN 6:1
DAN 6:1-28 = DAN 6:2-29
DAN 13:1-64 = SUS 1:1-64
DAN 13:65 = BEL 1:1
DAN 14:1 = BEL 1:1
DAN 14:2-41 = BEL 1:2-41
HOS 1:10-11 = HOS 2:1-2
HOS 2:1-22 = HOS 2:3-24
# HOS 2:23-24 -> HOS 2:25
HOS 2:23 = HOS 2:25
HOS 2:24 = HOS 2:25
HOS 11:12 = HOS 12:1
HOS 12:1-14 = HOS 12:2-15
JOL 2:28-32 = JOL 3:1-5
JOL 3:1-21 = JOL 4:1-21
# AMO 6:10-11 -> AMO 6:10
AMO 6:10 = AMO 6:10
AMO 6:11 = AMO 6:10
AMO 6:12-15 = AMO 6:11-14
MIC 5:1 = MIC 4:14
MIC 5:2-10 = MIC 5:1-9
# MIC 5:11 <- MIC 5:10-11
MIC 5:11 = MIC 5:10
MIC 5:11 = MIC 5:11
# MIC 5:12-14 = MIC 5:12-14
JON 1:17 = JON 2:1
JON 2:1-10 = JON 2:2-11
NAM 1:15 = NAM 2:1
NAM 2:1-13 = NAM 2:2-14
HAG 2:1 = HAG 1:15
HAG 2:2-24 = HAG 2:1-23
ZEC 1:18-21 = ZEC 2:1-4
ZEC 2:1-13 = ZEC 2:5-17
MAL 4:1-6 = MAL 3:19-24
#
#
# Mapping
# Vulgate = UBS GNT
#
#
# MAT 17:14 <- MAT 17:14-15
MAT 17:15-26 = MAT 17:16-27
# MRK 4:40 <- MRK 4:40-41
MRK 4:40 = MRK 4:40
MRK 4:40 = MRK 4:41
MRK 8:39 = MRK 9:1
MRK 9:1-49 = MRK 9:2-50
# JHN 6:51-52 -> JHN 6:51
JHN 6:51 = JHN 6:51
JHN 6:52 = JHN 6:51
JHN 6:53-72 = JHN 6:52-71
# ACT 7:55 <- ACT 7:55-56
ACT 7:55 = ACT 7:55
ACT 7:55 = ACT 7:56
ACT 7:56-59 = ACT 7:57-60
# ACT 14:6 <- ACT 14:6-7
ACT 14:6 = ACT 14:6
ACT 14:6 = ACT 14:7
ACT 14:7-27 = ACT 14:8-28
#
#
#
# Mapping
# Vulgate = +/-LXX
#
#
# WIS 2:24-25 -> WIS 2:24
WIS 2:24 = WIS 2:24
WIS 2:25 = WIS 2:24
# WIS 5:13-14 -> WIS 5:13
WIS 5:13 = WIS 5:13
WIS 5:14 = WIS 5:13
WIS 5:15-24 = WIS 5:14-23
# WIS 6:1 -> missing
WIS 6:2-21 = WIS 6:1-20
WIS 6:22 = WIS 6:21
WIS 6:23 = WIS 6:21
# WIS 6:23 -> missing
WIS 6:24-27 = WIS 6:22-25
# WIS 9:18-19 -> WIS 9:18
WIS 9:18 = WIS 9:18
WIS 9:19 = WIS 9:18
# WIS 11:5-6 -> WIS 11:5
WIS 11:5 = WIS 11:5
WIS 11:6 = WIS 11:5
WIS 11:7-27 = WIS 11:6-26
# WIS 19:12 <- WIS 19:12-13
WIS 19:12 = WIS 19:12
WIS 19:12 = WIS 19:13
WIS 19:13-19 = WIS 19:14-20
# WIS 19:20 <- WIS 19:21-22
WIS 19:20 = WIS 19:21
WIS 19:20 = WIS 19:22
BAR 6:1-72 = LJE 1:1-72
# 1MA 1:4-5 -> 1MA 1:4
1MA 1:4 = 1MA 1:4
1MA 1:5 = 1MA 1:4
1MA 1:6-31 = 1MA 1:5-30
# 1MA 1:31-32 -> 1MA 1:30
1MA 1:31 = 1MA 1:30
1MA 1:32 = 1MA 1:30
1MA 1:33-35 = 1MA 1:31-33
# 1MA 1:36ab <- 1MA 1:34
# 1MA 1:36bc = 1MA 1:35a
# 1MA 1:37 -> 1MA 1:35b
1MA 1:36 = 1MA 1:34
1MA 1:36 = 1MA 1:35
1MA 1:37 = 1MA 1:35
1MA 1:38-46 = 1MA 1:36-44
# 1MA 1:47-48 -> 1MA 1:45
1MA 1:47 = 1MA 1:45
1MA 1:48 = 1MA 1:45
1MA 1:49-67 = 1MA 1:46-64
# 1MA 12:53-54 -> 1MA 12:53
1MA 12:53 = 1MA 12:53
1MA 12:54 = 1MA 12:53
# 1MA 13:52-53 -> 1MA 13:52
1MA 13:52 = 1MA 13:52
1MA 13:53 = 1MA 13:52
1MA 13:54 = 1MA 13:53
# 2MA 2:18-19 -> 2MA 2:18
2MA 2:18 = 2MA 2:18
2MA 2:19 = 2MA 2:18
2MA 2:20-33 = 2MA 2:19-32
# 2MA 12:45-46 -> 2MA 12:45
2MA 12:45 = 2MA 12:45
2MA 12:46 = 2MA 12:45
# 2MA 15:36-37 -> 2MA 15:36
2MA 15:36 = 2MA 15:36
2MA 15:37 = 2MA 15:36
2MA 15:38-40 = 2MA 15:37-39
#
#
# For 1ES the mapping info is taken from the Bible Works program
# mapping Vulgate onto LXX
#
1ES 1:4 = 1ES 1:3
1ES 1:4 = 1ES 1:4
1ES 1:5 = 1ES 1:4
1ES 1:5 = 1ES 1:5
1ES 1:10 = 1ES 1:10
1ES 1:10 = 1ES 1:11
1ES 1:11 = 1ES 1:12
1ES 1:12 = 1ES 1:13
1ES 1:13 = 1ES 1:13
1ES 1:13 = 1ES 1:14
1ES 1:14 = 1ES 1:14
1ES 1:15 = 1ES 1:15
1ES 1:16 = 1ES 1:15
1ES 1:17 = 1ES 1:16
1ES 1:18 = 1ES 1:16
1ES 1:19-50 = 1ES 1:17-48
1ES 1:51 = 1ES 1:49
1ES 1:52 = 1ES 1:49
1ES 1:53-58 = 1ES 1:50-55
1ES 2:1 = 1ES 2:1
1ES 2:2 = 1ES 2:1
1ES 2:3 = 1ES 2:2
1ES 2:4 = 1ES 2:2
1ES 2:5 = 1ES 2:3
1ES 2:6 = 1ES 2:4
1ES 2:7 = 1ES 2:4
1ES 2:8 = 1ES 2:5
1ES 2:9 = 1ES 2:6
1ES 2:10 = 1ES 2:7
1ES 2:11 = 1ES 2:8
1ES 2:12 = 1ES 2:8
1ES 2:13 = 1ES 2:9
1ES 2:13 = 1ES 2:10
1ES 2:14 = 1ES 2:11
1ES 2:15 = 1ES 2:11
1ES 2:16-19 = 1ES 2:12-15
1ES 2:20 = 1ES 2:16
1ES 2:21 = 1ES 2:16
1ES 2:22 = 1ES 2:17
1ES 2:23 = 1ES 2:17
1ES 2:24 = 1ES 2:18
1ES 2:25 = 1ES 2:19
1ES 2:26 = 1ES 2:20
1ES 2:26 = 1ES 2:21
1ES 2:27 = 1ES 2:21
1ES 2:27 = 1ES 2:22
1ES 2:28 = 1ES 2:23
1ES 2:29 = 1ES 2:24
1ES 2:30 = 1ES 2:25
1ES 2:30 = 1ES 2:26
1ES 3:14 = 1ES 3:14
1ES 3:15 = 1ES 3:14
1ES 3:16 = 1ES 3:15
1ES 3:17 = 1ES 3:16
1ES 3:17 = 1ES 3:17
1ES 4:10 = 1ES 4:10
1ES 4:10 = 1ES 4:11
1ES 4:11 = 1ES 4:11
1ES 4:33 = 1ES 4:33
1ES 4:33 = 1ES 4:34
1ES 4:39 = 1ES 4:39
1ES 4:40 = 1ES 4:39
1ES 4:40 = 1ES 4:40
1ES 5:41 = 1ES 5:41
1ES 5:42 = 1ES 5:41
1ES 5:43-53 = 1ES 5:42-52
1ES 5:54 = 1ES 5:53
1ES 5:55 = 1ES 5:53
1ES 5:56 = 1ES 5:54
1ES 5:57 = 1ES 5:55
1ES 5:58 = 1ES 5:56
1ES 5:58 = 1ES 5:57
1ES 5:59 = 1ES 5:57
1ES 5:60 = 1ES 5:57
1ES 5:61-72 = 1ES 5:58-69
1ES 5:73 = 1ES 5:70
1ES 5:73 = 1ES 5:71
1ES 6:8 = 1ES 6:8
1ES 6:9 = 1ES 6:8
1ES 6:10-34 = 1ES 6:9-33
1ES 8:5 = 1ES 8:5
1ES 8:6 = 1ES 8:5
1ES 8:6 = 1ES 8:6
1ES 8:13 = 1ES 8:13
1ES 8:14 = 1ES 8:13
1ES 8:14 = 1ES 8:14
1ES 8:19 = 1ES 8:19
1ES 8:20 = 1ES 8:19
1ES 8:20 = 1ES 8:20
1ES 8:43 = 1ES 8:43
1ES 8:44 = 1ES 8:43
1ES 8:45-49 = 1ES 8:44-48
1ES 8:50 = 1ES 8:49
1ES 8:50 = 1ES 8:50
1ES 8:56 = 1ES 8:56
1ES 8:57 = 1ES 8:56
1ES 8:58-62 = 1ES 8:57-61
1ES 8:63 = 1ES 8:62
1ES 8:64 = 1ES 8:62
1ES 8:65 = 1ES 8:63
1ES 8:66 = 1ES 8:63
1ES 8:67-85 = 1ES 8:64-82
1ES 8:86 = 1ES 8:83
1ES 8:86 = 1ES 8:84
1ES 8:87 = 1ES 8:84
1ES 8:88-92 = 1ES 8:85-89
1ES 8:93 = 1ES 8:90
1ES 8:94 = 1ES 8:90
1ES 8:95 = 1ES 8:91
1ES 8:96 = 1ES 8:92
#
#--------------------------------------------------------------------------
# mapping XXA onto PSA, XXA should be in a variant Vulgate project [Studge]
# Both PSA and XXA are synchronized to PSA in the original versification.
# Is this allowed???
# by request of RdB, XXA mapping to PSA has been deleted - [Barb] 20110127
# XXA has been moved to PSA and the old PSA is now the Resource VULGP83 [Barb]
# There could still be some errors regarding the irregular mapping of psalm titles (like in PSA 12:1 <- PSA 13:1-2)
#
#
#-------------------------------------------------------
# Removing the following lines (FB 52696)
#2ES 3:1-36 = EZA 1:1-36
#2ES 4:1-52 = EZA 2:1-52
#2ES 5:1-56 = EZA 3:1-56
#2ES 6:1-59 = EZA 4:1-59
#2ES 7:1-35 = EZA 5:1-35
#2ES 7:106-140 = EZA 5:36-70
#2ES 8:1-63 = EZA 6:1-63
#2ES 9:1-47 = EZA 7:1-47
#2ES 10:1-60 = EZA 8:1-60
#2ES 11:1-46 = EZA 9:1-46
#2ES 12:1-51 = EZA 10:1-51
#2ES 13:1-58 = EZA 11:1-58
#2ES 14:1-48 = EZA 12:1-48
#-----------------------------------------------------
# map Letter to the Laodiceans [Studge]
# XXB 1:1-7 = LAO 1:1-7
#-----------------------------------------------------
# map Esther Greek onto Hebrew Esther [Studge]
# to be added in
#-----------------------------------------------------
# Mapping Additions to Daniel onto Hebrew Daniel [Studge]
DAG 1:1-21 = DAN 1:1-21
DAG 2:1-49 = DAN 2:1-49
DAG 3:24-52 = S3Y 1:1-29
DAG 3:52-23 = S3Y 1:30-31
DAG 3:54 = S3Y 1:33
DAG 3:55 = S3Y 1:32
DAG 3:56-57 = S3Y 1:34-35
DAG 3:58 = S3Y 1:37
DAG 3:59 = S3Y 1:36
DAG 3:60-90 = S3Y 1:38-68
DAG 3:91-97 = DAN 3:24-30
DAG 4:1-3 = DAN 3:31-33
DAG 4:4-37 = DAN 4:1-34
DAG 5:1-31 = DAN 5:1-31
DAG 6:1-28 = DAN 6:1-28
DAG 7:1-28 = DAN 7:1-28
DAG 8:1-27 = DAN 8:1-27
DAG 9:1-27 = DAN 9:1-27
DAG 10:1-21 = DAN 10:1-21
DAG 11:1-45 = DAN 11:1-45 
DAG 12:1-13 = DAN 12:1-13
# Susanna
DAG 13:1-63 = SUS 1:63
# Bel and the Dragon
DAG 14:1-42 = BEL 1:42
#-------------------------------------------------------
`;
const exporting = {
  eng: { raw: vrs },
  lxx: { raw: lxxText },
  org: { raw: orgText },
  rsc: { raw: rscText },
  rso: { raw: rsoText },
  vul: { raw: vulText }
};
const cvRegex = /^([A-Z0-9]{3}) (([0-9]+:[0-9]+) ?)*$/;
for (const [vrsName, vrsRecord] of Object.entries(exporting)) {
  vrsRecord.cv = {};
  const lineMatches = vrsRecord.raw.split("\n").filter((l) => l.match(cvRegex));
  if (!lineMatches) {
    continue;
  }
  for (const line of lineMatches) {
    const cvBook = line.slice(0, 3);
    vrsRecord.cv[cvBook] = {};
    for (const cvString of line.substr(4).split(" ")) {
      const [c, v] = cvString.split(":");
      vrsRecord.cv[cvBook][c] = v;
    }
  }
}
const querySchemaString = `
"""The top level of Proskomma queries"""
type Query {
  """The id of the processor, which is different for each Proskomma instance"""
  id: String!
  """A string describing the processor class"""
  processor: String!
  """The NPM package version"""
  packageVersion: String!
  """The selectors used to define docSets"""
  selectors: [selectorSpec!]!
  """The number of docSets"""
  nDocSets: Int!
  """The docSets in the processor"""
  docSets(
    """A whitelist of ids of docSets to include"""
    ids: [String!]
    """Only return docSets that match the list of selector values"""
    withSelectors: [InputKeyValue!]
    """Only return docSets containing a document with the specified bookCode"""
    withBook: String
    """Only return docSets with all the specified tags"""
    withTags: [String!]
    """Only return docSets with none of the specified tags"""
    withoutTags: [String!]
  ): [DocSet!]!
  """The docSet with the specified id"""
  docSet(
    """The id of the docSet"""
    id: String!
  ): DocSet
  """The number of documents in the processor"""
  nDocuments: Int!
  """The documents in the processor"""
  documents(
    """A whitelist of ids of documents to include"""
    ids: [String!]
    """Only return documents with the specified bookCode"""
    withBook: String
    """Only return documents with the specified header key/values"""
    withHeaderValues: [InputKeyValue!]
    """Only return documents with all the specified tags"""
    withTags: [String!]
    """Only return documents with none of the specified tags"""
    withoutTags: [String!]
    """Sort returned documents by the designated method (currently ${Object.keys(
  bookCodeCompareFunctions
).join(", ")})"""
    sortedBy: String
  ): [Document!]!
  """The document with the specified id, or the specified docSet and withBook"""
  document(
    """The id of the document"""
    id: String
    """The docSet of the document (use with withBook)"""
    docSetId: String
    """The book of the document (use with docSetId)"""
    withBook: String
  ) : Document
  """Reference information about standard versifications"""
  versifications: [versification!]!
  """Reference information about a named, standard versification"""
  versification(
    """The id of the versification"""
    id: String!
  ) : versification!
}
`;
const queryResolvers = {
  id: (root) => root.processorId,
  selectors: (root) => root.selectors,
  docSets: (root, args) => {
    const docSetMatchesSelectors = (ds, selectors) => {
      for (const selector of selectors) {
        if (ds.selectors[selector.key].toString() !== selector.value) {
          return false;
        }
      }
      return true;
    };
    let ret = ("withBook" in args ? root.docSetsWithBook(args.withBook) : Object.values(root.docSets)).filter((ds) => !args.ids || args.ids.includes(ds.id));
    if (args.withSelectors) {
      ret = ret.filter((ds) => docSetMatchesSelectors(ds, args.withSelectors));
    }
    if (args.withTags) {
      ret = ret.filter(
        (ds) => args.withTags.filter((t) => ds.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (ds) => args.withoutTags.filter((t) => ds.tags.has(t)).length === 0
      );
    }
    return ret;
  },
  docSet: (root, args) => root.docSetById(args.id),
  documents: (root, args) => {
    const headerValuesMatch = (docHeaders, requiredHeaders) => {
      for (const requiredHeader of requiredHeaders || []) {
        if (!(requiredHeader.key in docHeaders) || docHeaders[requiredHeader.key] !== requiredHeader.value) {
          return false;
        }
      }
      return true;
    };
    let ret = args.withBook ? root.documentsWithBook(args.withBook) : root.documentList();
    ret = ret.filter((d) => !args.ids || args.ids.includes(d.id));
    if (args.withHeaderValues) {
      ret = ret.filter(
        (d) => headerValuesMatch(d.headers, args.withHeaderValues)
      );
    }
    if (args.withTags) {
      ret = ret.filter(
        (d) => args.withTags.filter((t) => d.tags.has(t)).length === args.withTags.length
      );
    }
    if (args.withoutTags) {
      ret = ret.filter(
        (d) => args.withoutTags.filter((t) => d.tags.has(t)).length === 0
      );
    }
    if (args.sortedBy) {
      if (!(args.sortedBy in bookCodeCompareFunctions)) {
        throw new Error(
          `sortedBy value must be one of [${Object.keys(
            bookCodeCompareFunctions
          ).join(", ")}], not ${args.sortedBy}`
        );
      }
      ret.sort(bookCodeCompareFunctions[args.sortedBy]);
    }
    return ret;
  },
  document: (root, args) => {
    if (args.id && !args.docSetId && !args.withBook) {
      return root.documentById(args.id);
    } else if (!args.id && args.docSetId && args.withBook) {
      return root.documentsWithBook(args.withBook).filter((d) => d.docSetId === args.docSetId)[0];
    } else {
      throw new Error(
        "document requires either id or both docSetId and withBook (but not all three)"
      );
    }
  },
  versifications: () => Object.entries(exporting),
  versification: (root, args) => Object.entries(exporting).filter((v) => v[0] === args.id)[0]
};
const selectorSpecSchemaString = `
"""Specification of a selector"""
type selectorSpec {
  """Name (ie the key)"""
  name: String!
  """Data type (string or integer)"""
  type: String!
  """Regex for validating string selector"""
  regex: String
  """Inclusive minimum value for integer selector"""
  min: String
  """Inclusive maximum value for integer selector"""
  max: String
  """Enum of permitted string values"""
  enum: [String!]
}
`;
const selectorSpecResolvers = {
  regex: (root) => root.regex || null,
  min: (root) => root.min || null,
  max: (root) => root.max || null,
  enum: (root) => root.enum || null
};
const inputSelectorSpecSchemaString = `
"""Input specification of a selector"""
input inputSelectorSpec {
  """Name (ie the key)"""
  name: String!
  """Data type (string or integer)"""
  type: String!
  """Regex for validating string selector"""
  regex: String
  """Inclusive minimum value for integer selector"""
  min: String
  """Inclusive maximum value for integer selector"""
  max: String
  """Enum of permitted string values"""
  enum: [String!]
}
`;
const remakeBlocks = (docSet, document, sequence, blocksSpec2) => {
  const nBlocks = sequence.blocks.length;
  for (let blockN = 0; blockN < nBlocks; blockN++) {
    document.deleteBlock(sequence.id, 0, false);
  }
  for (let blockN = 0; blockN < blocksSpec2.length; blockN++) {
    const block2 = blocksSpec2[blockN];
    document.newBlock(sequence.id, blockN, block2.bs.payload, null, false);
    const bgResult = docSet.updateBlockGrafts(
      document.id,
      sequence.id,
      blockN,
      block2.bg
    );
    if (!bgResult) {
      return false;
    }
    const osResult = docSet.updateOpenScopes(
      document.id,
      sequence.id,
      blockN,
      block2.os
    );
    if (!osResult) {
      return false;
    }
    const isResult = docSet.updateIncludedScopes(
      document.id,
      sequence.id,
      blockN,
      block2.is
    );
    if (!isResult) {
      return false;
    }
    const itemsResult = docSet.updateItems(
      document.id,
      sequence.id,
      blockN,
      block2.items
    );
    if (!itemsResult) {
      return false;
    }
  }
};
const addMutationsSchemaString = `
  """Adds a document which will be assigned to an existing or new docSet on the basis of the specified selectors"""
  addDocument(
    """The selectors for this document, the keys of which must match those of the Proskomma instance"""
    selectors: [InputKeyValue!]!
    """The format of the content (probably usfm or usx)"""
    contentType: String!
    """The document content as a string"""
    content: String!
    """A list of tags to be added"""
    tags: [String!]
  ): Boolean!
  """Creates a new, empty sequence"""
  newSequence(
    """The id of the document to which the sequence will be added"""
    documentId: String!
    """The type of the new sequence (main, heading...)"""
    type: String!
    """The JSON describing blocks, if any, for the new sequence"""
    blocksSpec: [inputBlockSpec!]
    """If true, graft to the first block of the main sequence"""
    graftToMain: Boolean
    """'A list of tags to be added"""
    tags: [String!]
  ): String!
  """Adds a new block to a sequence"""
  newBlock(
    """The id of the document containing the sequence to which the block will be added"""
    documentId: String!
    """The id of the sequence to which the block will be added"""
    sequenceId: String!
    """The zero-indexed position at which to add the block"""
    blockN: Int!
    """The scope to be applied to the block, eg blockScope/p"""
    blockScope: String!
  ): Boolean!
`;
const addMutationsResolvers = {
  addDocument: (root, args) => {
    const selectorsObject = {};
    args.selectors.forEach((s) => {
      selectorsObject[s.key] = s.value;
    });
    return !!root.importDocument(
      selectorsObject,
      args.contentType,
      args.content,
      null,
      null,
      null,
      args.tags || []
    );
  },
  newSequence: (root, args) => {
    const document = root.documents[args.documentId];
    const docSet = document.processor.docSets[document.docSetId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    const newSeqId = document.newSequence(args.type, args.tags);
    if (args.blocksSpec) {
      remakeBlocks(
        docSet,
        document,
        document.sequences[newSeqId],
        args.blocksSpec
      );
      document.buildChapterVerseIndex();
    }
    if (args.graftToMain) {
      docSet.maybeBuildPreEnums();
      const mainSequenceBG = document.sequences[document.mainId].blocks[0].bg;
      const graftTypeEnumIndex = docSet.enumForCategoryValue(
        "graftTypes",
        args.type,
        true
      );
      const seqEnumIndex = docSet.enumForCategoryValue("ids", newSeqId, true);
      utils.succinct.pushSuccinctGraftBytes(
        mainSequenceBG,
        graftTypeEnumIndex,
        seqEnumIndex
      );
    }
    return newSeqId;
  },
  newBlock: (root, args) => {
    const document = root.documents[args.documentId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    return document.newBlock(args.sequenceId, args.blockN, args.blockScope);
  }
};
const deleteMutationsSchemaString = `
  """Deletes a docSet"""
  deleteDocSet(
    """The id of the docSet containing the document to be deleted"""
    docSetId: String!
  ): Boolean
  """Deletes a document"""
  deleteDocument(
    """The id of the docSet containing the document to be deleted"""
    docSetId: String!
    """The id of the document to be deleted"""
    documentId: String!
  ): Boolean
  """Deletes a sequence from a document"""
  deleteSequence(
    """The id of the document containing the sequence to be deleted"""
    documentId: String!
    """The id of the sequence to be deleted"""
    sequenceId: String!
  ): Boolean
  """Deletes a block from a sequence"""
  deleteBlock(
    """The id of the document containing the sequence from which the block will be deleted"""
    documentId: String!
    """The id of the sequence from which the block will be deleted"""
    sequenceId: String!
    """The zero-indexed number of the block to be deleted"""
    blockN: Int!
  ): Boolean
`;
const deleteMutationsResolvers = {
  deleteDocSet: (root, args) => root.deleteDocSet(args.docSetId),
  deleteDocument: (root, args) => root.deleteDocument(args.docSetId, args.documentId),
  deleteSequence: (root, args) => {
    const document = root.documents[args.documentId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    return document.deleteSequence(args.sequenceId);
  },
  deleteBlock: (root, args) => {
    const document = root.documents[args.documentId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    return document.deleteBlock(args.sequenceId, args.blockN);
  }
};
const rehashMutationsSchemaString = `
  """Explicitly rebuild the text lookup tables for a docSet. (You probably don't need to do this)"""
  rehashDocSet(
    """The id of the docSet"""
    docSetId: String!
  ): Boolean!
`;
const rehashMutationsResolvers = {
  rehashDocSet: (root, args) => root.rehashDocSet(args.docSetId)
};
const tagMutationsSchemaString = `
  """Add one or more tags to a docSet, if they are not already present"""
  addDocSetTags(
    """The id of the docSet to which the tags will be added"""
    docSetId: String!
    """A list of tags to be added"""
    tags: [String]!
  ): [String!]!
  """Add one or more tags to a document, if they are not already present"""
  addDocumentTags(
    """The id of the docSet containing the document to which the tags will be added"""
    docSetId: String!
    """The id of the document to which the tags will be added"""
    documentId: String!
    """A list of tags to be added"""
    tags: [String]!
  ): [String!]
  """Add one or more tags to a sequence, if they are not already present"""
  addSequenceTags(
    """The id of the docSet containing the document containing the sequence to which the tags will be added"""
    docSetId: String!
    """The id of the document containing the sequence to which the tags will be added"""
    documentId: String!
    """The id of the sequence to which the tags will be added"""
    sequenceId: String!
    """A list of tags to be added"""
    tags: [String]!
  ) : [String!]
  """Remove one or more tags from a docSet, if they are present"""
  removeDocSetTags(
    """The id of the docSet from which the tags will be removed"""
    docSetId: String!
    """A list of tags to be removed"""
    tags: [String]!
  ): [String!]
  """Remove one or more tags from a document, if they are present"""
  removeDocumentTags(
    """The id of the docSet containing the document from which the tags will be removed"""
    docSetId: String!
    """The id of the document from which the tags will be removed"""
    documentId: String!
    """A list of tags to be removed"""
    tags: [String]!
  ): [String!]
  """Remove one or more tags from a sequence, if they are present"""
  removeSequenceTags(
    """The id of the docSet containing the document containing the sequence from which the tags will be removed"""
    docSetId: String!
    """The id of the document containing the sequence from which the tags will be removed"""
    documentId: String!
    """The id of the sequence from which the tags will be removed"""
    sequenceId: String!
    """A list of tags to be removed"""
    tags: [String]!
  ) : [String!]
`;
const tagMutationsResolvers = {
  addDocSetTags: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    for (const tag of args.tags) {
      docSet.addTag(tag);
    }
    return Array.from(docSet.tags);
  },
  addDocumentTags: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    const document = docSet.processor.documents[args.documentId];
    for (const tag of args.tags) {
      document.addTag(tag);
    }
    return Array.from(document.tags);
  },
  addSequenceTags: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    const document = docSet.processor.documents[args.documentId];
    const sequence = document.sequences[args.sequenceId];
    for (const tag of args.tags) {
      utils.tags.addTag(sequence.tags, tag);
    }
    return Array.from(sequence.tags);
  },
  removeDocSetTags: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    for (const tag of args.tags) {
      docSet.removeTag(tag);
    }
    return Array.from(docSet.tags);
  },
  removeDocumentTags: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    const document = docSet.processor.documents[args.documentId];
    for (const tag of args.tags) {
      document.removeTag(tag);
    }
    return Array.from(document.tags);
  },
  removeSequenceTags: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    const document = docSet.processor.documents[args.documentId];
    const sequence = document.sequences[args.sequenceId];
    for (const tag of args.tags) {
      utils.tags.removeTag(sequence.tags, tag);
    }
    return Array.from(sequence.tags);
  }
};
const perf2PkJsonPipeline = [
  {
    id: 0,
    type: "Inputs",
    inputs: {
      perf: "json"
    }
  },
  {
    id: 1,
    title: "PERF to PkJSON",
    name: "perf2PkJson",
    type: "Transform",
    inputs: [
      {
        name: "perf",
        type: "json",
        source: "Input perf"
      }
    ],
    outputs: [
      {
        name: "pkJson",
        type: "json"
      }
    ],
    documentation: "",
    description: "PERF=>JSON: Converts PERF to current Proskomma input format"
  },
  {
    id: 999,
    type: "Outputs",
    outputs: [
      {
        name: "pkJson",
        type: "json",
        source: "Transform 1 pkJson"
      }
    ]
  }
];
const pipelines = { perf2PkJsonPipeline };
const calculateUsfmChapterPositionsCode2 = function({ perf }) {
  const cl = new dist.PerfRenderFromJson({
    srcJson: perf,
    actions: calculateUsfmChapterPositionsActions
  });
  const output = {};
  cl.renderDocument({
    docId: "",
    config: { maxLength: 60 },
    output
  });
  return { report: output.report };
};
const calculateUsfmChapterPositions = {
  name: "calculateUsfmChapterPositions",
  type: "Transform",
  description: "PERF=>JSON: Generates positions for inserting chapter numbers into USFM",
  inputs: [
    {
      name: "perf",
      type: "json",
      source: ""
    }
  ],
  outputs: [
    {
      name: "report",
      type: "json"
    }
  ],
  code: calculateUsfmChapterPositionsCode2
};
const wordLikeRegex = lexingRegexes.filter((r) => r[1] === "wordLike")[0][2];
const lineSpaceRegex = lexingRegexes.filter((r) => r[1] === "lineSpace")[0][2];
const punctuationRegex = lexingRegexes.filter(
  (r) => r[1] === "punctuation"
)[0][2];
const closeAllOpenScopes = (workspace) => {
  [...workspace.os].reverse().forEach((o) => {
    workspace.block.items.push({
      type: "scope",
      subType: "end",
      payload: o
    });
  });
  workspace.os = [];
};
const closeParagraphScopes = (workspace) => {
  [...workspace.os.filter((o) => ["span"].includes(o.split("/")[1]))].reverse().forEach((o) => {
    workspace.block.items.push({
      type: "scope",
      subType: "end",
      payload: o
    });
    workspace.os = [...workspace.os.filter((wo) => wo !== o)];
  });
};
const closeVerseScopes = (workspace) => {
  [...workspace.os.filter((o) => ["verse", "verses"].includes(o.split("/")[0]))].reverse().forEach((o) => {
    workspace.block.items.push({
      type: "scope",
      subType: "end",
      payload: o
    });
    workspace.os = [...workspace.os.filter((wo) => wo !== o)];
  });
};
const closeChapterScopes = (workspace) => {
  [...workspace.os.filter((o) => ["chapter"].includes(o.split("/")[0]))].reverse().forEach((o) => {
    workspace.block.items.push({
      type: "scope",
      subType: "end",
      payload: o
    });
    workspace.os = [...workspace.os.filter((wo) => wo !== o)];
  });
};
const perf2PkJsonActions = {
  startDocument: [
    {
      description: "Set up word object",
      test: () => true,
      action: ({ workspace, output }) => {
        output.pkJson = {};
        workspace.sequenceId = null;
        workspace.block = null;
        workspace.os = [];
        workspace.waitingBlockGrafts = [];
      }
    }
  ],
  startSequence: [
    {
      description: "Add sequence array to output",
      test: () => true,
      action: (environment) => {
        environment.output.pkJson[environment.context.sequences[0].id] = [];
        environment.workspace.sequenceId = environment.context.sequences[0].id;
      }
    }
  ],
  endSequence: [
    {
      description: "Reset sequenceId pointer",
      test: () => true,
      action: (environment) => {
        var _a;
        closeAllOpenScopes(environment.workspace);
        environment.workspace.sequenceId = (_a = environment.context.sequences[1]) == null ? void 0 : _a.id;
      }
    }
  ],
  unresolvedBlockGraft: [
    {
      description: "Stash for next para",
      test: () => true,
      action: ({ context, workspace }) => {
        const target = context.sequences[0].block.target;
        if (target) {
          workspace.waitingBlockGrafts.push({
            type: "graft",
            subType: context.sequences[0].block.subType,
            payload: context.sequences[0].block.target
          });
        }
      }
    }
  ],
  unresolvedInlineGraft: [
    {
      description: "Follow inline grafts",
      test: () => true,
      action: ({ context, workspace }) => {
        const target = context.sequences[0].element.target;
        if (target) {
          workspace.block.items.push({
            type: "graft",
            subType: context.sequences[0].element.subType,
            payload: context.sequences[0].element.target
          });
        }
      }
    }
  ],
  startParagraph: [
    {
      description: "Add object for paragraph block",
      test: () => true,
      action: ({ context, workspace, output }) => {
        workspace.block = {
          os: [...workspace.os],
          is: [],
          bs: {
            type: "scope",
            subType: "start",
            payload: `blockTag/${context.sequences[0].block.subType.split(":")[1]}`
          },
          bg: [...workspace.waitingBlockGrafts],
          items: []
        };
        output.pkJson[workspace.sequenceId].push(workspace.block);
      }
    }
  ],
  endParagraph: [
    {
      description: "Close open scopes",
      test: () => true,
      action: ({ workspace }) => {
        closeParagraphScopes(workspace);
        workspace.waitingBlockGrafts = [];
      }
    }
  ],
  mark: [
    {
      description: "ts mark as milestone",
      test: ({ context }) => ["usfm:ts"].includes(context.sequences[0].element.subType),
      action: ({ workspace }) => {
        const milestoneScope = `milestone/ts`;
        if (!workspace.block.is.includes(milestoneScope)) {
          workspace.block.is.push(milestoneScope);
        }
        workspace.os.push(milestoneScope);
        workspace.block.items.push({
          type: "scope",
          subType: "start",
          payload: milestoneScope
        });
        workspace.block.items.push({
          type: "scope",
          subType: "end",
          payload: milestoneScope
        });
      }
    },
    {
      description: "Chapter",
      test: ({ context }) => ["chapter"].includes(context.sequences[0].element.subType),
      action: ({ context, workspace }) => {
        closeVerseScopes(workspace);
        closeChapterScopes(workspace);
        const element = context.sequences[0].element;
        const chapterScope = `chapter/${element.atts["number"]}`;
        if (!workspace.block.is.includes(chapterScope)) {
          workspace.block.is.push(chapterScope);
        }
        workspace.os.push(chapterScope);
        workspace.block.items.push({
          type: "scope",
          subType: "start",
          payload: chapterScope
        });
      }
    },
    {
      description: "Verses",
      test: ({ context }) => ["verses"].includes(context.sequences[0].element.subType),
      action: ({ context, workspace }) => {
        closeVerseScopes(workspace);
        const element = context.sequences[0].element;
        const vn = element.atts["number"];
        let va = [parseInt(vn)];
        if (vn.includes("-")) {
          let [vs, ve] = vn.split("-").map((s) => parseInt(s));
          va = [vs];
          while (vs <= ve) {
            vs++;
            va.push(vs);
          }
        }
        for (const v of va) {
          const verseScope = `verse/${v}`;
          workspace.os.push(verseScope);
          if (!workspace.block.is.includes(verseScope)) {
            workspace.block.is.push(verseScope);
          }
          workspace.block.items.push({
            type: "scope",
            subType: "start",
            payload: verseScope
          });
        }
        const versesScope = `verses/${element.atts["number"]}`;
        if (!workspace.block.is.includes(versesScope)) {
          workspace.block.is.push(versesScope);
        }
        workspace.os.push(versesScope);
        workspace.block.items.push({
          type: "scope",
          subType: "start",
          payload: versesScope
        });
      }
    }
  ],
  startMilestone: [
    {
      description: "Add scope and update state",
      test: () => true,
      action: ({ context, workspace }) => {
        const element = context.sequences[0].element;
        const milestoneScope = `milestone/${element.subType.split(":")[1]}`;
        if (!workspace.block.is.includes(milestoneScope)) {
          workspace.block.is.push(milestoneScope);
        }
        workspace.os.push(milestoneScope);
        workspace.block.items.push({
          type: "scope",
          subType: "start",
          payload: milestoneScope
        });
        for (const [attKey, attValue] of Object.entries(element.atts || {})) {
          const valueParts = attValue.toString().split(",");
          for (const [partN, part] of valueParts.entries()) {
            const attScope = `attribute/milestone/${element.subType.split(":")[1]}/${attKey}/${partN}/${part}`;
            if (!workspace.block.is.includes(attScope)) {
              workspace.block.is.push(attScope);
            }
            workspace.os.push(attScope);
            workspace.block.items.push({
              type: "scope",
              subType: "start",
              payload: attScope
            });
          }
        }
      }
    }
  ],
  endMilestone: [
    {
      description: "Remove scope and update state",
      test: () => true,
      action: ({ context, workspace }) => {
        const element = context.sequences[0].element;
        const attScopeRoot = `attribute/milestone/${element.subType.split(":")[1]}`;
        for (const att of [
          ...workspace.os.filter((s) => s.startsWith(attScopeRoot))
        ].reverse()) {
          workspace.os = workspace.os.filter((o) => o !== att);
          workspace.block.items.push({
            type: "scope",
            subType: "end",
            payload: att
          });
        }
        const milestoneScope = `milestone/${element.subType.split(":")[1]}`;
        workspace.os = workspace.os.filter((s) => s !== milestoneScope);
        workspace.block.items.push({
          type: "scope",
          subType: "end",
          payload: milestoneScope
        });
      }
    }
  ],
  startWrapper: [
    {
      description: "Add scope and update state",
      test: () => true,
      action: ({ context, workspace }) => {
        const element = context.sequences[0].element;
        const wrapperScope = `${element.subType === "usfm:w" ? "spanWithAtts" : "span"}/${element.subType.split(":")[1]}`;
        if (!workspace.block.is.includes(wrapperScope)) {
          workspace.block.is.push(wrapperScope);
        }
        workspace.os.push(wrapperScope);
        workspace.block.items.push({
          type: "scope",
          subType: "start",
          payload: wrapperScope
        });
        for (const [attKey, attValue] of Object.entries(element.atts || {})) {
          const valueParts = attValue.toString().split(",");
          for (const [partN, part] of valueParts.entries()) {
            const attScope = `attribute/spanWithAtts/w/${attKey}/${partN}/${part}`;
            if (!workspace.block.is.includes(attScope)) {
              workspace.block.is.push(attScope);
            }
            workspace.os.push(attScope);
            workspace.block.items.push({
              type: "scope",
              subType: "start",
              payload: attScope
            });
          }
        }
      }
    }
  ],
  endWrapper: [
    {
      description: "Remove scope and update state",
      test: () => true,
      action: ({ context, workspace }) => {
        const element = context.sequences[0].element;
        for (const [attKey, attValue] of [
          ...Object.entries(element.atts || {})
        ].reverse()) {
          const valueParts = attValue.toString().split(",");
          for (const [partN, part] of [...valueParts.entries()].reverse()) {
            const attScope = `attribute/spanWithAtts/w/${attKey}/${partN}/${part}`;
            workspace.os = workspace.os.filter((o) => o !== attScope);
            workspace.block.items.push({
              type: "scope",
              subType: "end",
              payload: attScope
            });
          }
        }
        const wrapperScope = `${element.subType === "usfm:w" ? "spanWithAtts" : "span"}/${element.subType.split(":")[1]}`;
        workspace.os = workspace.os.filter((s) => s !== wrapperScope);
        workspace.block.items.push({
          type: "scope",
          subType: "end",
          payload: wrapperScope
        });
      }
    }
  ],
  text: [
    {
      description: "Log occurrences",
      test: () => true,
      action: ({ context, workspace }) => {
        const text = context.sequences[0].element.text;
        const re2 = XRegExp.union(lexingRegexes.map((x) => x[2]));
        const words = XRegExp.match(text, re2, "all");
        for (const word of words) {
          let subType;
          if (XRegExp.test(word, wordLikeRegex)) {
            subType = "wordLike";
          } else if (XRegExp.test(word, lineSpaceRegex)) {
            subType = "lineSpace";
          } else if (XRegExp.test(word, punctuationRegex)) {
            subType = "punctuation";
          }
          workspace.block.items.push({
            type: "token",
            subType,
            payload: word
          });
        }
      }
    }
  ],
  endDocument: [
    {
      description: "Rework hanging end cv scopes",
      test: () => true,
      action: ({ output }) => {
        const sequenceBlocks = Object.values(output.pkJson)[0];
        for (let blockN = 1; blockN < sequenceBlocks.length; blockN++) {
          let thisBlockItems = sequenceBlocks[blockN].items;
          const lastBlockItems = sequenceBlocks[blockN - 1].items;
          let itemN = 0;
          while (itemN < thisBlockItems.length) {
            const item = thisBlockItems[itemN];
            if (item.type !== "scope" || item.subType !== "end") {
              break;
            }
            itemN++;
          }
          while (itemN > 0) {
            const movingScope = thisBlockItems.shift();
            lastBlockItems.push(movingScope);
            sequenceBlocks[blockN].os = sequenceBlocks[blockN].os.filter(
              (s) => s !== movingScope.payload
            );
            itemN--;
          }
        }
      }
    }
  ]
};
const perf2PkJsonCode = function({ perf }) {
  const cl = new dist.PerfRenderFromJson({
    srcJson: perf,
    ignoreMissingSequences: true,
    actions: perf2PkJsonActions
  });
  const output = {};
  cl.renderDocument({
    docId: "",
    config: {},
    output
  });
  return { pkJson: output.pkJson };
};
const perf2PkJson = {
  name: "perf2PkJson",
  type: "Transform",
  description: "PERF=>JSON: Converts PERF to current Proskomma input format",
  documentation: "",
  inputs: [
    {
      name: "perf",
      type: "json",
      source: ""
    }
  ],
  outputs: [
    {
      name: "pkJson",
      type: "json"
    }
  ],
  code: perf2PkJsonCode
};
const customTransforms = {
  calculateUsfmChapterPositions,
  perf2PkJson
};
const updateMutationsSchemaString = `
  """Replaces the items of a block with a new set of items"""
  updateItems(
    """The id of the docSet containing the document containing the sequence containing the block for which the items will be updated"""
    docSetId: String!
    """The id of the document containing the sequence containing the block for which the items will be updated"""
    documentId: String!
    """The id of the sequence containing the block for which the items will be updated (defaults to the main sequence)"""
    sequenceId: String
    """The zero-indexed number of the block for which the items will be updated"""
    blockPosition: Int!
    """The new content for the block as item objects"""
    items: [InputItemObject!]
    """BlockGrafts for the block as item objects"""
    blockGrafts: [InputItemObject!]
    """Optional blockScope for the block as an item object"""
    blockScope: InputItemObject
  ): Boolean!
  """Replaces all the blocks of a sequence with a new set of blocks"""
  updateAllBlocks(
    """The id of the docSet containing the document containing the sequence for which the blocks will be updated"""
    docSetId: String!
    """The id of the document containing the sequence for which the blocks will be updated"""
    documentId: String!
    """The id of the sequence for which the blocks will be updated (defaults to the main sequence)"""
    sequenceId: String
    """The JSON describing blocks"""
    blocksSpec: [inputBlockSpec!]!
  ): Boolean!
  """Replaces all the blocks of a sequence with a new set of blocks derived from PERF"""
  updateSequenceFromPerf(
    """The id of the docSet containing the document containing the sequence for which the blocks will be updated"""
    docSetId: String!
    """The id of the document containing the sequence for which the blocks will be updated"""
    documentId: String!
    """The id of the sequence for which the blocks will be updated (defaults to the main sequence)"""
    sequenceId: String
    """The JSON describing blocks"""
    perf: String!
  ): Boolean!
  """Garbage collects unused sequences within a document. (You probably don\\'t need to do this.)"""
  gcSequences(
    """The id of the docSet containing the document to be garbage collected"""
    docSetId: String!
    """The id of the document to be garbage collected"""
    documentId: String!
  ) : Boolean!
 
`;
const updateMutationsResolvers = {
  updateItems: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    if (!docSet) {
      throw new Error(`DocSet '${args.docSetId}' not found`);
    }
    if (!args.items) {
      throw new Error("Must provide items");
    }
    const itemsResult = docSet.updateItems(
      args.documentId,
      args.sequenceId,
      args.blockPosition,
      args.items
    );
    if (!itemsResult) {
      return false;
    }
    if (args.blockGrafts) {
      const bgResult = docSet.updateBlockGrafts(
        args.documentId,
        args.sequenceId,
        args.blockPosition,
        args.blockGrafts
      );
      if (!bgResult) {
        return false;
      }
    }
    if (args.blockScope) {
      const bsResult = docSet.updateBlockScope(
        args.documentId,
        args.sequenceId,
        args.blockPosition,
        args.blockScope
      );
      if (!bsResult) {
        return false;
      }
    }
    return true;
  },
  updateAllBlocks: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    if (!docSet) {
      throw new Error(`DocSet '${args.docSetId}' not found`);
    }
    const document = root.documents[args.documentId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    const sequence = document.sequences[args.sequenceId || document.mainId];
    if (!sequence) {
      throw new Error(
        `Sequence '${args.sequenceId || document.mainId}' not found`
      );
    }
    remakeBlocks(docSet, document, sequence, args.blocksSpec);
    document.buildChapterVerseIndex();
    return true;
  },
  updateSequenceFromPerf: async (root, args) => {
    const docSet = root.docSets[args.docSetId];
    if (!docSet) {
      throw new Error(`DocSet '${args.docSetId}' not found`);
    }
    const document = root.documents[args.documentId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    const sequence = document.sequences[args.sequenceId || document.mainId];
    if (!sequence) {
      throw new Error(
        `Sequence '${args.sequenceId || document.mainId}' not found`
      );
    }
    const sequencePerf = JSON.parse(args.perf);
    const perf = {
      schema: {
        structure: "flat",
        structure_version: "0.3.0",
        constraints: [
          {
            name: "perf",
            version: "0.3.0"
          }
        ]
      },
      metadata: {
        translation: {},
        document: {}
      },
      sequences: {},
      main_sequence_id: args.sequenceId
    };
    perf.sequences[args.sequenceId] = sequencePerf;
    let blocksSpec2 = {};
    try {
      const pipelineHandler = new dist.PipelineHandler({
        pipelines,
        transforms: customTransforms,
        proskomma: root
      });
      const output = await pipelineHandler.runPipeline("perf2PkJsonPipeline", {
        perf
      });
      blocksSpec2 = Object.values(output.pkJson)[0];
    } catch (err) {
      console.error("pipelineHandler Error :\n", err);
      return false;
    }
    remakeBlocks(docSet, document, sequence, blocksSpec2);
    document.buildChapterVerseIndex();
    return true;
  },
  gcSequences: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    if (!docSet) {
      throw new Error(`DocSet '${args.docSetId}' not found`);
    }
    const document = root.documents[args.documentId];
    if (!document) {
      throw new Error(`Document '${args.documentId}' not found`);
    }
    if (document.gcSequences()) {
      docSet.rehash();
      return true;
    } else {
      return false;
    }
  }
};
const versificationMutationsSchemaString = `
  """Adds verse mapping tables to the documents in a docSet, where the verse mapping may be provided in legacy .vrs or JSON format"""
  setVerseMapping(
    """the id of the docSet to which the verse mapping will be added"""
    docSetId: String!
    """The verse mapping, in legacy .vrs format (as a string)"""
    vrsSource: String
    """The verse mapping, in JSON format (as a string)"""
    jsonSource: String
  ): Boolean!
  """Removes verse mapping tables from the documents in a docSet"""
  unsetVerseMapping(
    """The id of the docSet from which verse mapping will be removed"""
    docSetId: String!
  ): Boolean!
`;
const versificationMutationsResolvers = {
  setVerseMapping: (root, args) => {
    if (args.vrsSource && args.jsonSource) {
      throw new Error("Cannot specify both vrsSource and jsonSource");
    } else if (!args.vrsSource && !args.jsonSource) {
      throw new Error("Must specify either vrsSource or jsonSource");
    }
    const docSet = root.docSets[args.docSetId];
    if (!docSet) {
      return false;
    }
    let jsonSource;
    if (args.vrsSource) {
      jsonSource = utils.versification.vrs2json(args.vrsSource);
    } else {
      jsonSource = args.jsonSource;
    }
    const forwardSuccinctTree = utils.versification.succinctifyVerseMappings(
      jsonSource.mappedVerses
    );
    const reversedJsonSource = utils.versification.reverseVersification(jsonSource);
    const reversedSuccinctTree = utils.versification.succinctifyVerseMappings(
      reversedJsonSource.reverseMappedVerses
    );
    for (const document of docSet.documents().filter((doc) => "bookCode" in doc.headers)) {
      const bookCode = document.headers["bookCode"];
      const bookDocument = docSet.documentWithBook(bookCode);
      if (!bookDocument) {
        continue;
      }
      const bookMainSequence = bookDocument.sequences[bookDocument.mainId];
      bookMainSequence.verseMapping = {};
      if (bookCode in forwardSuccinctTree) {
        bookMainSequence.verseMapping.forward = forwardSuccinctTree[bookCode];
      }
      if (bookCode in reversedSuccinctTree) {
        bookMainSequence.verseMapping.reversed = reversedSuccinctTree[bookCode];
      }
    }
    docSet.tags.add("hasMapping");
    return true;
  },
  unsetVerseMapping: (root, args) => {
    const docSet = root.docSets[args.docSetId];
    if (!docSet) {
      return false;
    }
    for (const document of docSet.documents().filter((doc) => "bookCode" in doc.headers)) {
      const bookCode = document.headers["bookCode"];
      const bookDocument = docSet.documentWithBook(bookCode);
      if (bookDocument) {
        const bookMainSequence = bookDocument.sequences[bookDocument.mainId];
        bookMainSequence.verseMapping = {};
      }
    }
    docSet.tags.delete("hasMapping");
    return true;
  }
};
const mutationsSchemaString = `
type Mutation {
${addMutationsSchemaString}
${deleteMutationsSchemaString}
${rehashMutationsSchemaString}
${tagMutationsSchemaString}
${updateMutationsSchemaString}
${versificationMutationsSchemaString}
}`;
const mutationsResolvers = {
  ...addMutationsResolvers,
  ...deleteMutationsResolvers,
  ...rehashMutationsResolvers,
  ...tagMutationsResolvers,
  ...updateMutationsResolvers,
  ...versificationMutationsResolvers
};
const versificationSchemaString = `
"""Information about a standard versification scheme"""
type versification {
  """id, derived from the Paratext vrs filename"""
  id: String!
  """A string of the original vrs file"""
  vrs: String!
  """Chapter/verse information for each book"""
  cvBooks: [cvBook!]!
  """Chapter/verse information for one book"""
  cvBook(
    """The bookCode"""
    bookCode: String!
  ): cvBook!
}
`;
const versificationResolvers = {
  id: (root) => root[0],
  vrs: (root) => root[1].raw,
  cvBooks: (root) => Object.entries(root[1].cv),
  cvBook: (root, args) => Object.entries(root[1].cv).filter((b) => b[0] === args.bookCode)[0]
};
const cvBookSchemaString = `
"""Chapter/verse information for a book"""
type cvBook {
  """The bookCode"""
  bookCode: String!
  """The chapter records"""
  chapters: [cvChapter!]!
}
`;
const cvBookResolvers = {
  bookCode: (root) => root[0],
  chapters: (root) => Object.entries(root[1])
};
const cvChapterSchemaString = `
"""Information for a chapter"""
type cvChapter {
  """The chapter"""
  chapter: Int!
  """The maximum verse number"""
  maxVerse: Int!
}
`;
const cvChapterResolvers = {
  chapter: (root) => parseInt(root[0]),
  maxVerse: (root) => parseInt(root[1])
};
const typeDefs = `
      ${querySchemaString}
      ${mutationsSchemaString}
      ${keyValueSchemaString}
      ${keyCountSchemaString}
      ${keyCountCategorySchemaString}
      ${cvSchemaString}
      ${idPartsSchemaString}
      ${inputAttSpecSchemaString}
      ${keyMatchesSchemaString}
      ${inputKeyValueSchemaString}
      ${keyValuesSchemaString}
      ${inputItemObjectSchemaString}
      ${itemSchemaString}
      ${itemGroupSchemaString}
      ${kvEntrySchemaString}
      ${regexIndexSchemaString}
      ${rowEqualsSpecSchemaString}
      ${rowMatchSpecSchemaString}
      ${verseRangeSchemaString}
      ${origSchemaString}
      ${verseNumberSchemaString}
      ${cellSchemaString}
      ${cIndexSchemaString}
      ${cvVerseElementSchemaString}
      ${cvVersesSchemaString}
      ${cvIndexSchemaString}
      ${cvNavigationSchemaString}
      ${inputBlockSpecSchemaString}
      ${nodeSchemaString}
      ${kvSequenceSchemaString}
      ${tableSequenceSchemaString}
      ${treeSequenceSchemaString}
      ${blockSchemaString}
      ${sequenceSchemaString}
      ${documentSchemaString}
      ${docSetSchemaString}
      ${selectorSpecSchemaString}
      ${inputSelectorSpecSchemaString}
      ${versificationSchemaString}
      ${cvBookSchemaString}
      ${cvChapterSchemaString}
  `;
const resolvers = {
  Mutation: mutationsResolvers,
  Query: queryResolvers,
  KeyValue: keyValueResolvers,
  KeyCount: keyCountResolvers,
  KeyCountCategory: keyCountCategoryResolvers,
  cv: cvResolvers,
  idParts: idPartsResolvers,
  Item: itemResolvers,
  ItemGroup: itemGroupResolvers,
  kvEntry: kvEntryResolvers,
  regexIndex: regexIndexResolvers,
  verseNumber: verseNumberResolvers,
  cell: cellResolvers,
  cIndex: cIndexResolvers,
  cvVerseElement: cvVerseElementResolvers,
  cvVerses: cvVersesResolvers,
  cvIndex: cvIndexResolvers,
  cvNavigation: cvNavigationResolvers,
  node: nodeResolvers,
  kvSequence: kvSequenceResolvers,
  tableSequence: tableSequenceResolvers,
  treeSequence: treeSequenceResolvers,
  Block: blockResolvers,
  Sequence: sequenceResolvers,
  Document: documentResolvers,
  DocSet: docSetResolvers,
  selectorSpec: selectorSpecResolvers,
  versification: versificationResolvers,
  cvBook: cvBookResolvers,
  cvChapter: cvChapterResolvers
};
const { labelForScope } = utils.scopeDefs;
const tsvToInputBlock = (tsv, hasHeadings) => {
  const ret = [];
  const rows = tsv.split(/[\n\r]+/);
  for (const [rowN, rowTSV] of rows.entries()) {
    if (hasHeadings && rowN === 0) {
      continue;
    }
    const row = rowTSV.split("	");
    for (const [cellN, cellString] of row.entries()) {
      const cellRecord = {
        os: [],
        bg: [],
        bs: {
          type: "scope",
          subType: "start",
          payload: labelForScope("tTableRow", [`${rowN}`])
        },
        is: [],
        items: []
      };
      const colScope = `tTableCol/${cellN}`;
      cellRecord.is.push({
        type: "scope",
        subType: "start",
        payload: colScope
      });
      cellRecord.items.push({
        type: "scope",
        subType: "start",
        payload: colScope
      });
      for (const [token, tokenType] of tokenizeString(cellString)) {
        cellRecord.items.push({
          type: "token",
          subType: tokenType,
          payload: token
        });
      }
      cellRecord.items.push({
        type: "scope",
        subType: "end",
        payload: colScope
      });
      ret.push(cellRecord);
    }
  }
  return ret;
};
const tsvHeadingTags = (tsv) => {
  const firstRow = tsv.split(/[\n\r]+/)[0];
  return firstRow.split("	").map((c, n) => `col${n}:${c.trim()}`);
};
const treeToInputBlock = (treeJson) => {
  const ret = [];
  for (const node of flattenNodes(numberNodes(treeJson))) {
    const nodeRecord = {
      os: [],
      bg: [],
      bs: {
        type: "scope",
        subType: "start",
        payload: labelForScope("tTreeNode", [`${node.id}`])
      },
      is: [],
      items: []
    };
    const scopePayload = labelForScope("tTreeParent", [`${node.parentId}`]);
    nodeRecord.items.push({
      type: "scope",
      subType: "start",
      payload: scopePayload
    });
    nodeRecord.is.push({
      type: "scope",
      subType: "start",
      payload: scopePayload
    });
    if (node.content) {
      for (const [name2, content] of Object.entries(node.content)) {
        const treeContentStart = nodeRecord.items.length;
        const tokenized = tokenizeString(content);
        const scopePayload2 = labelForScope("tTreeContent", [
          name2,
          node.id,
          `${treeContentStart}`,
          `${tokenized.length}`
        ]);
        nodeRecord.items.push({
          type: "scope",
          subType: "start",
          payload: scopePayload2
        });
        nodeRecord.is.push({
          type: "scope",
          subType: "start",
          payload: scopePayload2
        });
        for (const [payload, subType] of tokenized) {
          nodeRecord.items.push({
            type: "token",
            subType,
            payload
          });
        }
        nodeRecord.items.push({
          type: "scope",
          subType: "end",
          payload: scopePayload2
        });
      }
    }
    if (node.children) {
      for (const [childN, childNodeN] of node.children.entries()) {
        const scopePayload2 = labelForScope("tTreeChild", [childN, childNodeN]);
        nodeRecord.items.push({
          type: "scope",
          subType: "start",
          payload: scopePayload2
        });
        nodeRecord.is.push({
          type: "scope",
          subType: "start",
          payload: scopePayload2
        });
        nodeRecord.items.push({
          type: "scope",
          subType: "end",
          payload: scopePayload2
        });
      }
    }
    nodeRecord.items.push({
      type: "scope",
      subType: "end",
      payload: scopePayload
    });
    ret.push(nodeRecord);
  }
  return ret;
};
const escapePayload = (str) => str.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
const object2Query = (obs) => "[" + obs.map(
  (ob) => `
    {
      type: "${ob.type}" 
      subType: "${ob.subType}" 
      payload: "${escapePayload(ob.payload)}"
    }`
).join(",") + "]";
const oneObject2Query = (ob) => `{
      type: "${ob.type}" 
      subType: "${ob.subType}" 
      payload: "${escapePayload(ob.payload)}"}`;
const blocksSpec2Query = (bSpec) => "[\n" + bSpec.map(
  (b) => `  {
    bs: ${oneObject2Query(b.bs)}, 
    bg: ${object2Query(
    b.bg
  )}, 
    os: ${object2Query(b.os)}, 
    is: ${object2Query(
    b.is
  )}, 
    items: ${object2Query(b.items)}}
`
) + "]";
const blocksSpec = {
  tokenizeString,
  tsvToInputBlock,
  tsvHeadingTags,
  treeToInputBlock,
  blocksSpec2Query,
  object2Query,
  oneObject2Query
};
const tree2nodes = (tree) => flattenNodes(numberNodes(tree));
const executableSchema = makeExecutableSchema({
  typeDefs,
  resolvers
});
class Proskomma {
  constructor(selectors) {
    this.processorId = utils.generateId();
    this.documents = {};
    this.docSetsBySelector = {};
    this.docSets = {};
    this.filters = {};
    this.customTags = {
      heading: [],
      paragraph: [],
      char: [],
      word: [],
      intro: [],
      introHeading: []
    };
    this.emptyBlocks = [];
    this.selectors = selectors || [
      {
        name: "lang",
        type: "string",
        regex: "[a-z]{3}"
      },
      {
        name: "abbr",
        type: "string"
      }
    ];
    this.validateSelectorSpec(this.selectors);
    this.mutex = new Mutex();
    this.nextPeriph = 0;
    this.nextTable = 0;
    this.nextNodes = 0;
  }
  validateSelectors() {
    if (this.selectors.length === 0) {
      throw new Error("No selectors found");
    }
    for (const [n, selector] of this.selectors.entries()) {
      if (!("name" in selector)) {
        throw new Error(`Selector ${n} has no name`);
      }
      if (!("type" in selector)) {
        throw new Error(`Selector ${n} has no type`);
      }
      if (!["string", "integer"].includes(selector.type)) {
        throw new Error(
          `Type for selector ${n} must be string or number, not ${selector.type}`
        );
      }
      if (selector.type === "string") {
        if ("min" in selector) {
          throw new Error("String selector should not include 'min'");
        }
        if ("max" in selector) {
          throw new Error("String selector should not include 'max'");
        }
        if ("regex" in selector) {
          try {
            XRegExp(selector.regex);
          } catch (err) {
            throw new Error(`Regex '${selector.regex}' is not valid: ${err}`);
          }
        }
        if ("enum" in selector) {
          for (const enumElement of selector.enum) {
            if (typeof enumElement !== "string") {
              throw new Error(
                `Enum values for selector ${selector.name} should be strings, not '${enumElement}'`
              );
            }
          }
        }
      } else {
        if ("regex" in selector) {
          throw new Error("Integer selector should not include 'regex'");
        }
        if ("min" in selector && typeof selector.min !== "number") {
          throw new Error(`'min' must be a number, not '${selector.min}'`);
        }
        if ("max" in selector && typeof selector.max !== "number") {
          throw new Error(`'max' must be a number, not '${selector.max}'`);
        }
        if ("min" in selector && "max" in selector && selector.min > selector.max) {
          throw new Error(
            `'min' cannot be greater than 'max' (${selector.min} > ${selector.max})`
          );
        }
        if ("enum" in selector) {
          for (const enumElement of selector.enum) {
            if (typeof enumElement !== "number") {
              throw new Error(
                `Enum values for selector ${selector.name} should be numbers, not '${enumElement}'`
              );
            }
          }
        }
      }
      for (const selectorKey of Object.keys(selector)) {
        if (!["name", "type", "regex", "min", "max", "enum"].includes(selectorKey)) {
          throw new Error(`Unexpected key '${selectorKey}' in selector ${n}`);
        }
      }
    }
  }
  validateSelectorSpec(spec) {
    for (const specElement of spec) {
      if (!specElement["name"]) {
        throw new Error(
          `name not found in selector spec element '${JSON.stringify(
            specElement
          )}'`
        );
      }
      if (!specElement["type"]) {
        throw new Error(
          `type not found in selector spec element '${JSON.stringify(
            specElement
          )}'`
        );
      }
      if (!["string", "integer"].includes(specElement.type)) {
        throw new Error(
          `Type for spec element must be string or number, not ${specElement.type}`
        );
      }
      for (const selectorKey of Object.keys(specElement)) {
        if (!["name", "type", "regex", "min", "max", "enum"].includes(selectorKey)) {
          throw new Error(`Unexpected key '${selectorKey}' in selectorSpec`);
        }
      }
    }
  }
  selectorString(docSetSelectors) {
    return this.selectors.map((s) => s.name).map((n) => `${docSetSelectors[n]}`).join("_");
  }
  processor() {
    return "Proskomma JS";
  }
  packageVersion() {
    return packageJson.version;
  }
  docSetList() {
    return Object.values(this.docSets);
  }
  docSetsById(ids) {
    return Object.values(this.docSets).filter((ds) => ids.includes(ds.id));
  }
  docSetById(id2) {
    return this.docSets[id2];
  }
  docSetsWithBook(bookCode) {
    const docIdsWithBook = Object.values(this.documents).filter(
      (doc) => "bookCode" in doc.headers && doc.headers["bookCode"] === bookCode
    ).map((doc) => doc.id);
    const docIdWithBookInDocSet = (ds) => {
      for (const docId of docIdsWithBook) {
        if (ds.docIds.includes(docId)) {
          return true;
        }
      }
      return false;
    };
    return Object.values(this.docSets).filter(
      (ds) => docIdWithBookInDocSet(ds)
    );
  }
  nDocSets() {
    return this.docSetList().length;
  }
  nDocuments() {
    return this.documentList().length;
  }
  documentList() {
    return Object.values(this.documents);
  }
  documentById(id2) {
    return this.documents[id2];
  }
  documentsById(ids) {
    return Object.values(this.documents).filter((doc) => ids.includes(doc.id));
  }
  documentsWithBook(bookCode) {
    return Object.values(this.documents).filter(
      (doc) => "bookCode" in doc.headers && doc.headers["bookCode"] === bookCode
    );
  }
  importDocument(selectors, contentType, contentString, filterOptions, customTags, emptyBlocks, tags2) {
    return this.importDocuments(
      selectors,
      contentType,
      [contentString],
      filterOptions,
      customTags,
      emptyBlocks,
      tags2
    )[0];
  }
  importDocuments(selectors, contentType, contentStrings, filterOptions, customTags, emptyBlocks, tags2) {
    if (!filterOptions) {
      filterOptions = this.filters;
    }
    if (!customTags) {
      customTags = this.customTags;
    }
    if (!emptyBlocks) {
      emptyBlocks = this.emptyBlocks;
    }
    if (!tags2) {
      tags2 = [];
    }
    const docSetId = this.findOrMakeDocSet(selectors);
    const docSet = this.docSets[docSetId];
    docSet.buildPreEnums();
    const docs = [];
    for (const contentString of contentStrings) {
      let doc = new Document(
        this,
        docSetId,
        contentType,
        contentString,
        filterOptions,
        customTags,
        emptyBlocks,
        tags2
      );
      const bookCode = doc.headers.bookCode;
      const existingBookCodes = Object.values(this.documents).filter((d) => docSet.docIds.includes(d.id)).map((d) => d.headers.bookCode);
      if (existingBookCodes.includes(bookCode)) {
        throw new Error(
          `Attempt to import document with bookCode '${bookCode}' which already exists in docSet ${docSetId}`
        );
      }
      this.addDocument(doc, docSetId);
      docs.push(doc);
    }
    docSet.preEnums = {};
    return docs;
  }
  importUsfmPeriph(selectors, contentString, filterOptions, customTags, emptyBlocks, tags2) {
    const lines = contentString.toString().split(/[\n\r]+/);
    const bookCode = lines[0].substring(4, 7);
    if (!["FRT", "BAK", "INT"].includes(bookCode)) {
      throw new Error(
        `importUsfmInt() expected bookCode of FRT, BAK or INT, not '${bookCode}'`
      );
    }
    let periphs = [];
    for (const line of lines) {
      if (line.substring(0, 7) === "\\periph") {
        let matchedBits = XRegExp.exec(
          line,
          XRegExp('^\\\\periph (.*)\\|\\s*id\\s*=\\s*"([^"]+)"\\s*$')
        );
        if (!matchedBits) {
          throw new Error(`Unable to parse periph line '${line}'`);
        }
        const periphDesc = matchedBits[1];
        const periphId = matchedBits[2];
        const periphBookCode = `\\id P${this.nextPeriph > 9 ? this.nextPeriph : "0" + this.nextPeriph}`;
        periphs.push([`${periphBookCode} INT ${periphId} - ${periphDesc}`]);
        this.nextPeriph++;
      } else if (periphs.length > 0 && line.substring(0, 3) !== "\\id") {
        periphs[periphs.length - 1].push(line);
      }
    }
    this.importDocuments(
      selectors,
      "usfm",
      periphs.map((p) => p.join("\n")),
      filterOptions,
      customTags,
      emptyBlocks,
      tags2
    );
  }
  cleanUsfm(usfm, options2) {
    options2 = options2 || {};
    const lines = usfm.toString().split(/[\n\r]+/);
    const ret = [];
    let inHeaders = true;
    const headers = [
      "\\id",
      "\\ide",
      "\\usfm",
      "\\sts",
      "\\rem",
      "\\h",
      "\\toc"
    ];
    for (const line of lines) {
      const firstWord = line.split(" ")[0].replace(/[0-9]+/g, "");
      if ("remove" in options2 && options2.remove.includes(firstWord)) {
        continue;
      }
      const isHeaderLine = headers.includes(firstWord);
      if (inHeaders && !isHeaderLine && firstWord !== "\\mt") {
        ret.push("\\mt1 USFM");
      }
      ret.push(line);
      if (!isHeaderLine) {
        inHeaders = false;
      }
    }
    return ret.join("\n");
  }
  deleteDocSet(docSetId) {
    if (!(docSetId in this.docSets)) {
      return false;
    }
    for (const docId of Object.entries(this.documents).filter((tup) => tup[1].docSetId === docSetId).map((tup) => tup[0])) {
      this.deleteDocument(docSetId, docId, false, false);
    }
    let selected = this.docSetsBySelector;
    const parentSelectors = this.selectors.slice(0, this.selectors.length - 1);
    for (const selector of parentSelectors) {
      selected = selected[this.docSets[docSetId].selectors[selector.name]];
    }
    const lastSelectorName = this.selectors[this.selectors.length - 1].name;
    const lastSelectorValue = this.docSets[docSetId].selectors[lastSelectorName];
    if (!selected[lastSelectorValue]) {
      throw new Error(
        `Could not find docSetId '${docSetId}' in docSetsBySelector in deleteDocSet`
      );
    }
    delete selected[lastSelectorValue];
    delete this.docSets[docSetId];
    return true;
  }
  deleteDocument(docSetId, documentId, maybeDeleteDocSet, maybeRehashDocSet) {
    maybeDeleteDocSet = maybeDeleteDocSet === void 0 ? true : maybeDeleteDocSet;
    maybeRehashDocSet = maybeRehashDocSet === void 0 ? true : maybeRehashDocSet;
    if (!(docSetId in this.docSets)) {
      return false;
    }
    if (!(documentId in this.documents)) {
      return false;
    }
    delete this.documents[documentId];
    if (this.docSets[docSetId].docIds.length > 1) {
      this.docSets[docSetId].docIds = this.docSets[docSetId].docIds.filter(
        (i) => i !== documentId
      );
      if (maybeRehashDocSet) {
        this.rehashDocSet(docSetId);
      }
    } else if (maybeDeleteDocSet) {
      this.deleteDocSet(docSetId);
    }
    return true;
  }
  rehashDocSet(docSetId) {
    if (!(docSetId in this.docSets)) {
      return false;
    }
    const docSet = this.docSets[docSetId];
    return docSet.rehash();
  }
  addDocument(doc, docSetId) {
    this.documents[doc.id] = doc;
    this.docSets[docSetId].docIds.push(doc.id);
    this.docSets[docSetId].buildEnumIndexes();
  }
  loadSuccinctDocSet(succinctOb, bookCodes2) {
    const succinctId = succinctOb.id;
    if (succinctId in this.docSets && !bookCodes2) {
      throw new Error(
        `Attempting to succinct load docSet ${succinctId} which is already loaded, without bookCodes argument`
      );
    }
    const docSet = new DocSet(this, null, null, succinctOb);
    const docSetId = docSet.id;
    this.docSets[docSetId] = docSet;
    let selectorTree = this.docSetsBySelector;
    const selectors = succinctOb.metadata.selectors;
    for (const selector of this.selectors) {
      if (selector.name === this.selectors[this.selectors.length - 1].name) {
        if (!(selectors[selector.name] in selectorTree)) {
          selectorTree[selectors[selector.name]] = docSet;
          this.docSets[docSet.id] = docSet;
        }
      } else {
        if (!(selectors[selector.name] in selectorTree)) {
          selectorTree[selectors[selector.name]] = {};
        }
        selectorTree = selectorTree[selectors[selector.name]];
      }
    }
    docSet.buildPreEnums();
    const docs = [];
    const selectDocs = (dId) => !bookCodes2 || bookCodes2.includes(succinctOb.docs[dId].headers.bookCode);
    for (const docId of Object.keys(succinctOb.docs).filter(selectDocs)) {
      let doc = this.newDocumentFromSuccinct(docId, succinctOb);
      docs.push(doc);
    }
    docSet.preEnums = {};
    return docs;
  }
  augmentSuccinctDocSet(succinctOb, bookCodes2) {
    if (!bookCodes2 || bookCodes2.length === 0) {
      throw new Error("bookCodes argument must be present and contain at least one element in augmentSuccinctDocSet");
    }
    const selectDocs = (dId) => {
      const doc = succinctOb.docs[dId];
      return bookCodes2.includes(doc.headers.bookCode);
    };
    if (!this.docSets[succinctOb.id]) {
      throw new Error(`docSet id '${succinctOb.id}' not found in Proskomma when using augmentSuccinctDocSet. Load it first with optional bookCodes argument`);
    }
    for (const docId of Object.keys(succinctOb.docs).filter(selectDocs)) {
      if (!this.documents[docId]) {
        this.newDocumentFromSuccinct(docId, succinctOb);
      }
    }
  }
  newDocumentFromSuccinct(docId, succinctOb) {
    const doc = new Document(this, succinctOb.id);
    doc.id = docId;
    const succinctDocOb = succinctOb.docs[docId];
    doc.filterOptions = {};
    doc.customTags = [];
    doc.emptyBlocks = [];
    doc.tags = new Set(succinctDocOb.tags);
    doc.headers = succinctDocOb.headers;
    doc.mainId = succinctDocOb.mainId;
    doc.sequences = {};
    for (const [seqId, seq] of Object.entries(succinctDocOb.sequences)) {
      doc.sequences[seqId] = {
        id: seqId,
        type: seq.type,
        tags: new Set(seq.tags),
        blocks: []
      };
      if (seq.type === "main") {
        doc.sequences[seqId].chapters = {};
        if (!("chapters" in seq)) {
          throw new Error("chapters not found in main sequence");
        }
        for (const [chK, chV] of Object.entries(seq.chapters)) {
          const bA = new utils.ByteArray();
          bA.fromBase64(chV);
          doc.sequences[seqId].chapters[chK] = bA;
        }
        doc.sequences[seqId].chapterVerses = {};
        if (!("chapterVerses" in seq)) {
          throw new Error("chapterVerses not found in main sequence");
        }
        for (const [chvK, chvV] of Object.entries(seq.chapterVerses)) {
          const bA = new utils.ByteArray();
          bA.fromBase64(chvV);
          doc.sequences[seqId].chapterVerses[chvK] = bA;
        }
        if (!("tokensPresent" in seq)) {
          throw new Error("tokensPresent not found in main sequence");
        }
        doc.sequences[seqId].tokensPresent = new BitSet(seq.tokensPresent);
      }
      for (const succinctBlock of seq.blocks) {
        const block2 = {};
        for (const [blockField, blockSuccinct] of Object.entries(
          succinctBlock
        )) {
          const ba = new utils.ByteArray(256);
          ba.fromBase64(blockSuccinct);
          block2[blockField] = ba;
        }
        doc.sequences[seqId].blocks.push(block2);
      }
    }
    this.addDocument(doc, succinctOb.id);
    return doc;
  }
  findOrMakeDocSet(selectors) {
    let selectorTree = this.docSetsBySelector;
    let docSet;
    for (const selector of this.selectors) {
      if (selector.name === this.selectors[this.selectors.length - 1].name) {
        if (selectors[selector.name] in selectorTree) {
          docSet = selectorTree[selectors[selector.name]];
        } else {
          docSet = new DocSet(this, selectors);
          selectorTree[selectors[selector.name]] = docSet;
          this.docSets[docSet.id] = docSet;
        }
      } else {
        if (!(selectors[selector.name] in selectorTree)) {
          selectorTree[selectors[selector.name]] = {};
        }
        selectorTree = selectorTree[selectors[selector.name]];
      }
    }
    return docSet.id;
  }
  async gqlQuery(query, callback) {
    const release = await this.mutex.acquire();
    try {
      const result = await graphql({
        schema: executableSchema,
        source: query,
        rootValue: this,
        contextValue: {}
      });
      if (callback) {
        callback(result);
      }
      return result;
    } finally {
      release();
    }
  }
  gqlQuerySync(query, callback) {
    const result = graphqlSync({
      schema: executableSchema,
      source: query,
      rootValue: this,
      contextValue: {}
    });
    if (callback) {
      callback(result);
    }
    return result;
  }
  serializeSuccinct(docSetId) {
    return this.docSets[docSetId].serializeSuccinct();
  }
  checksum() {
    const dsChecksums = Object.values(this.docSets).map((ds) => ds.checksum()).sort().join(" ");
    return crc32.calculate(dsChecksums);
  }
}
export {
  Proskomma,
  blocksSpec as blocksSpecUtils,
  lexingRegexes,
  resolvers,
  tree2nodes,
  typeDefs,
  utils
};