// deno-fmt-ignore-file
// deno-lint-ignore-file
// This code was bundled using `deno bundle` and it's not recommended to edit it manually

function distance(a, b) {
    if (a.length == 0) {
        return b.length;
    }
    if (b.length == 0) {
        return a.length;
    }
    const matrix = [];
    for(let i2 = 0; i2 <= b.length; i2++){
        matrix[i2] = [
            i2
        ];
    }
    for(let j = 0; j <= a.length; j++){
        matrix[0][j] = j;
    }
    for(let i1 = 1; i1 <= b.length; i1++){
        for(let j = 1; j <= a.length; j++){
            if (b.charAt(i1 - 1) == a.charAt(j - 1)) {
                matrix[i1][j] = matrix[i1 - 1][j - 1];
            } else {
                matrix[i1][j] = Math.min(matrix[i1 - 1][j - 1] + 1, Math.min(matrix[i1][j - 1] + 1, matrix[i1 - 1][j] + 1));
            }
        }
    }
    return matrix[b.length][a.length];
}
function paramCaseToCamelCase(str1) {
    return str1.replace(/-([a-z])/g, (g)=>g[1].toUpperCase()
    );
}
function getOption(flags, name1) {
    while(name1[0] === "-"){
        name1 = name1.slice(1);
    }
    for (const flag of flags){
        if (isOption(flag, name1)) {
            return flag;
        }
    }
    return;
}
function didYouMeanOption(option1, options) {
    const optionNames = options.map((option)=>[
            option.name,
            ...option.aliases ?? []
        ]
    ).flat().map((option)=>getFlag(option)
    );
    return didYouMean(" Did you mean option", getFlag(option1), optionNames);
}
function didYouMeanType(type, types3) {
    return didYouMean(" Did you mean type", type, types3);
}
function didYouMean(message, type, types4) {
    const match = closest(type, types4);
    return match ? `${message} "${match}"?` : "";
}
function getFlag(name2) {
    if (name2.startsWith("-")) {
        return name2;
    }
    if (name2.length > 1) {
        return `--${name2}`;
    }
    return `-${name2}`;
}
function isOption(option, name3) {
    return option.name === name3 || option.aliases && option.aliases.indexOf(name3) !== -1;
}
function closest(str2, arr) {
    let minDistance = Infinity;
    let minIndex = 0;
    for(let i3 = 0; i3 < arr.length; i3++){
        const dist = distance(str2, arr[i3]);
        if (dist < minDistance) {
            minDistance = dist;
            minIndex = i3;
        }
    }
    return arr[minIndex];
}
function getDefaultValue(option) {
    return typeof option.default === "function" ? option.default() : option.default;
}
class FlagsError extends Error {
    constructor(message){
        super(message);
        Object.setPrototypeOf(this, FlagsError.prototype);
    }
}
class UnknownRequiredOption extends FlagsError {
    constructor(option, options){
        super(`Unknown required option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, UnknownRequiredOption.prototype);
    }
}
class UnknownConflictingOption extends FlagsError {
    constructor(option, options){
        super(`Unknown conflicting option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, UnknownConflictingOption.prototype);
    }
}
class UnknownType extends FlagsError {
    constructor(type, types5){
        super(`Unknown type "${type}".${didYouMeanType(type, types5)}`);
        Object.setPrototypeOf(this, UnknownType.prototype);
    }
}
class ValidationError extends FlagsError {
    constructor(message){
        super(message);
        Object.setPrototypeOf(this, ValidationError.prototype);
    }
}
class DuplicateOption extends ValidationError {
    constructor(name4){
        super(`Option "${getFlag(name4).replace(/^--no-/, "--")}" can only occur once, but was found several times.`);
        Object.setPrototypeOf(this, DuplicateOption.prototype);
    }
}
class UnknownOption extends ValidationError {
    constructor(option, options){
        super(`Unknown option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, UnknownOption.prototype);
    }
}
class MissingOptionValue extends ValidationError {
    constructor(option){
        super(`Missing value for option "${getFlag(option)}".`);
        Object.setPrototypeOf(this, MissingOptionValue.prototype);
    }
}
class InvalidOptionValue extends ValidationError {
    constructor(option, expected, value){
        super(`Option "${getFlag(option)}" must be of type "${expected}", but got "${value}".`);
        Object.setPrototypeOf(this, InvalidOptionValue.prototype);
    }
}
class OptionNotCombinable extends ValidationError {
    constructor(option){
        super(`Option "${getFlag(option)}" cannot be combined with other options.`);
        Object.setPrototypeOf(this, OptionNotCombinable.prototype);
    }
}
class ConflictingOption extends ValidationError {
    constructor(option, conflictingOption){
        super(`Option "${getFlag(option)}" conflicts with option "${getFlag(conflictingOption)}".`);
        Object.setPrototypeOf(this, ConflictingOption.prototype);
    }
}
class DependingOption extends ValidationError {
    constructor(option, dependingOption){
        super(`Option "${getFlag(option)}" depends on option "${getFlag(dependingOption)}".`);
        Object.setPrototypeOf(this, DependingOption.prototype);
    }
}
class MissingRequiredOption extends ValidationError {
    constructor(option){
        super(`Missing required option "${getFlag(option)}".`);
        Object.setPrototypeOf(this, MissingRequiredOption.prototype);
    }
}
class RequiredArgumentFollowsOptionalArgument extends ValidationError {
    constructor(arg){
        super(`An required argument cannot follow an optional argument, but "${arg}"  is defined as required.`);
        Object.setPrototypeOf(this, RequiredArgumentFollowsOptionalArgument.prototype);
    }
}
class ArgumentFollowsVariadicArgument extends ValidationError {
    constructor(arg){
        super(`An argument cannot follow an variadic argument, but got "${arg}".`);
        Object.setPrototypeOf(this, ArgumentFollowsVariadicArgument.prototype);
    }
}
class NoArguments extends ValidationError {
    constructor(){
        super(`No arguments.`);
        Object.setPrototypeOf(this, NoArguments.prototype);
    }
}
class InvalidTypeError extends ValidationError {
    constructor({ label , name: name5 , value: value1 , type  }, expected){
        super(`${label} "${name5}" must be of type "${type}", but got "${value1}".` + (expected ? ` Expected values: ${expected.map((value)=>`"${value}"`
        ).join(", ")}` : ""));
        Object.setPrototypeOf(this, MissingOptionValue.prototype);
    }
}
function normalize(args) {
    const normalized = [];
    let inLiteral = false;
    for (const arg of args){
        if (inLiteral) {
            normalized.push(arg);
        } else if (arg === "--") {
            inLiteral = true;
            normalized.push(arg);
        } else if (arg.length > 1 && arg[0] === "-") {
            const isLong = arg[1] === "-";
            const isDotted = !isLong && arg[2] === ".";
            if (arg.includes("=")) {
                const parts = arg.split("=");
                const flag = parts.shift();
                if (isLong) {
                    normalized.push(flag);
                } else {
                    normalizeShortFlags(flag);
                }
                normalized.push(parts.join("="));
            } else if (isLong || isDotted) {
                normalized.push(arg);
            } else {
                normalizeShortFlags(arg);
            }
        } else {
            normalized.push(arg);
        }
    }
    return normalized;
    function normalizeShortFlags(flag) {
        const flags = flag.slice(1).split("");
        if (isNaN(Number(flag[flag.length - 1]))) {
            flags.forEach((val)=>normalized.push(`-${val}`)
            );
        } else {
            normalized.push(`-${flags.shift()}`);
            normalized.push(flags.join(""));
        }
    }
}
var OptionType;
(function(OptionType1) {
    OptionType1["STRING"] = "string";
    OptionType1["NUMBER"] = "number";
    OptionType1["INTEGER"] = "integer";
    OptionType1["BOOLEAN"] = "boolean";
})(OptionType || (OptionType = {}));
const __boolean = (type)=>{
    if (~[
        "1",
        "true"
    ].indexOf(type.value)) {
        return true;
    }
    if (~[
        "0",
        "false"
    ].indexOf(type.value)) {
        return false;
    }
    throw new InvalidTypeError(type);
};
const number = (type)=>{
    const value = Number(type.value);
    if (Number.isFinite(value)) {
        return value;
    }
    throw new InvalidTypeError(type);
};
const string = ({ value  })=>{
    return value;
};
function validateFlags(flags, values1, _knownFlaks, allowEmpty, optionNames = {}) {
    const defaultValues = {};
    for (const option of flags){
        let name6;
        let defaultValue = undefined;
        if (option.name.startsWith("no-")) {
            const propName = option.name.replace(/^no-/, "");
            if (propName in values1) {
                continue;
            }
            const positiveOption = getOption(flags, propName);
            if (positiveOption) {
                continue;
            }
            name6 = paramCaseToCamelCase(propName);
            defaultValue = true;
        }
        if (!name6) {
            name6 = paramCaseToCamelCase(option.name);
        }
        if (!(name6 in optionNames)) {
            optionNames[name6] = option.name;
        }
        const hasDefaultValue = typeof values1[name6] === "undefined" && (typeof option.default !== "undefined" || typeof defaultValue !== "undefined");
        if (hasDefaultValue) {
            values1[name6] = getDefaultValue(option) ?? defaultValue;
            defaultValues[option.name] = true;
            if (typeof option.value === "function") {
                values1[name6] = option.value(values1[name6]);
            }
        }
    }
    const keys1 = Object.keys(values1);
    if (keys1.length === 0 && allowEmpty) {
        return;
    }
    const options = keys1.map((name7)=>({
            name: name7,
            option: getOption(flags, optionNames[name7])
        })
    );
    for (const { name: name1 , option: option1  } of options){
        if (!option1) {
            throw new UnknownOption(name1, flags);
        }
        if (option1.standalone) {
            if (keys1.length > 1) {
                if (options.every(({ option: opt  })=>opt && (option1 === opt || defaultValues[opt.name])
                )) {
                    return;
                }
                throw new OptionNotCombinable(option1.name);
            }
            return;
        }
        option1.conflicts?.forEach((flag)=>{
            if (isset(flag, values1)) {
                throw new ConflictingOption(option1.name, flag);
            }
        });
        option1.depends?.forEach((flag)=>{
            if (!isset(flag, values1) && !defaultValues[option1.name]) {
                throw new DependingOption(option1.name, flag);
            }
        });
        const isArray2 = (option1.args?.length || 0) > 1;
        option1.args?.forEach((arg, i4)=>{
            if (arg.requiredValue && (typeof values1[name1] === "undefined" || isArray2 && typeof values1[name1][i4] === "undefined")) {
                throw new MissingOptionValue(option1.name);
            }
        });
    }
    for (const option2 of flags){
        if (option2.required && !(paramCaseToCamelCase(option2.name) in values1)) {
            if ((!option2.conflicts || !option2.conflicts.find((flag)=>!!values1[flag]
            )) && !options.find((opt)=>opt.option?.conflicts?.find((flag)=>flag === option2.name
                )
            )) {
                throw new MissingRequiredOption(option2.name);
            }
        }
    }
    if (keys1.length === 0 && !allowEmpty) {
        throw new NoArguments();
    }
}
function isset(flag, values2) {
    const name8 = paramCaseToCamelCase(flag);
    return typeof values2[name8] !== "undefined";
}
const integer = (type)=>{
    const value = Number(type.value);
    if (Number.isInteger(value)) {
        return value;
    }
    throw new InvalidTypeError(type);
};
const Types = {
    [OptionType.STRING]: string,
    [OptionType.NUMBER]: number,
    [OptionType.INTEGER]: integer,
    [OptionType.BOOLEAN]: __boolean
};
function parseFlags(args2, opts = {}) {
    !opts.flags && (opts.flags = []);
    const normalized = normalize(args2);
    let inLiteral = false;
    let negate = false;
    const flags = {};
    const optionNames = {};
    let literal1 = [];
    let unknown = [];
    let stopEarly = null;
    opts.flags.forEach((opt)=>{
        opt.depends?.forEach((flag)=>{
            if (!opts.flags || !getOption(opts.flags, flag)) {
                throw new UnknownRequiredOption(flag, opts.flags ?? []);
            }
        });
        opt.conflicts?.forEach((flag)=>{
            if (!opts.flags || !getOption(opts.flags, flag)) {
                throw new UnknownConflictingOption(flag, opts.flags ?? []);
            }
        });
    });
    for(let i5 = 0; i5 < normalized.length; i5++){
        let option1;
        let args1;
        const current = normalized[i5];
        if (inLiteral) {
            literal1.push(current);
            continue;
        }
        if (current === "--") {
            inLiteral = true;
            continue;
        }
        const isFlag = current.length > 1 && current[0] === "-";
        const next = ()=>normalized[i5 + 1]
        ;
        if (isFlag) {
            if (current[2] === "-" || current[1] === "-" && current.length === 3) {
                throw new UnknownOption(current, opts.flags);
            }
            negate = current.startsWith("--no-");
            option1 = getOption(opts.flags, current);
            if (!option1) {
                if (opts.flags.length) {
                    throw new UnknownOption(current, opts.flags);
                }
                option1 = {
                    name: current.replace(/^-+/, ""),
                    optionalValue: true,
                    type: OptionType.STRING
                };
            }
            const positiveName = option1.name.replace(/^no-?/, "");
            const propName = paramCaseToCamelCase(positiveName);
            if (typeof flags[propName] !== "undefined" && !option1.collect) {
                throw new DuplicateOption(current);
            }
            args1 = option1.args?.length ? option1.args : [
                {
                    type: option1.type,
                    requiredValue: option1.requiredValue,
                    optionalValue: option1.optionalValue,
                    variadic: option1.variadic,
                    list: option1.list,
                    separator: option1.separator
                }
            ];
            let argIndex = 0;
            let inOptionalArg = false;
            const previous = flags[propName];
            parseNext(option1, args1);
            if (typeof flags[propName] === "undefined") {
                if (typeof option1.default !== "undefined") {
                    flags[propName] = getDefaultValue(option1);
                } else if (args1[argIndex].requiredValue) {
                    throw new MissingOptionValue(option1.name);
                } else {
                    flags[propName] = true;
                }
            }
            if (option1.value) {
                flags[propName] = option1.value(flags[propName], previous);
            } else if (option1.collect) {
                const value = Array.isArray(previous) ? previous : [];
                value.push(flags[propName]);
                flags[propName] = value;
            }
            optionNames[propName] = option1.name;
            opts.option?.(option1, flags[propName]);
            function parseNext(option3, args) {
                const arg1 = args[argIndex];
                if (!arg1) {
                    const flag = next();
                    throw new UnknownOption(flag, opts.flags ?? []);
                }
                if (!arg1.type) {
                    arg1.type = OptionType.BOOLEAN;
                }
                if (option3.args?.length) {
                    if ((typeof arg1.optionalValue === "undefined" || arg1.optionalValue === false) && typeof arg1.requiredValue === "undefined") {
                        arg1.requiredValue = true;
                    }
                } else {
                    if (arg1.type !== OptionType.BOOLEAN && (typeof arg1.optionalValue === "undefined" || arg1.optionalValue === false) && typeof arg1.requiredValue === "undefined") {
                        arg1.requiredValue = true;
                    }
                }
                if (arg1.requiredValue) {
                    if (inOptionalArg) {
                        throw new RequiredArgumentFollowsOptionalArgument(option3.name);
                    }
                } else {
                    inOptionalArg = true;
                }
                if (negate) {
                    flags[propName] = false;
                    return;
                }
                let result2;
                let increase = false;
                if (arg1.list && hasNext(arg1)) {
                    const parsed = next().split(arg1.separator || ",").map((nextValue)=>{
                        const value = parseValue(option3, arg1, nextValue);
                        if (typeof value === "undefined") {
                            throw new InvalidOptionValue(option3.name, arg1.type ?? "?", nextValue);
                        }
                        return value;
                    });
                    if (parsed?.length) {
                        result2 = parsed;
                    }
                } else {
                    if (hasNext(arg1)) {
                        result2 = parseValue(option3, arg1, next());
                    } else if (arg1.optionalValue && arg1.type === OptionType.BOOLEAN) {
                        result2 = true;
                    }
                }
                if (increase) {
                    i5++;
                    if (!arg1.variadic) {
                        argIndex++;
                    } else if (args[argIndex + 1]) {
                        throw new ArgumentFollowsVariadicArgument(next());
                    }
                }
                if (typeof result2 !== "undefined" && (args.length > 1 || arg1.variadic)) {
                    if (!flags[propName]) {
                        flags[propName] = [];
                    }
                    flags[propName].push(result2);
                    if (hasNext(arg1)) {
                        parseNext(option3, args);
                    }
                } else {
                    flags[propName] = result2;
                }
                function hasNext(arg) {
                    return !!(normalized[i5 + 1] && (arg.optionalValue || arg.requiredValue || arg.variadic) && (normalized[i5 + 1][0] !== "-" || arg.type === OptionType.NUMBER && !isNaN(Number(normalized[i5 + 1]))) && arg);
                }
                function parseValue(option, arg, value) {
                    const type = arg.type || OptionType.STRING;
                    const result = opts.parse ? opts.parse({
                        label: "Option",
                        type,
                        name: `--${option.name}`,
                        value
                    }) : parseFlagValue(option, arg, value);
                    if (typeof result !== "undefined") {
                        increase = true;
                    }
                    return result;
                }
            }
        } else {
            if (opts.stopEarly) {
                stopEarly = current;
                break;
            }
            unknown.push(current);
        }
    }
    if (stopEarly) {
        const stopEarlyArgIndex = args2.indexOf(stopEarly);
        if (stopEarlyArgIndex !== -1) {
            const doubleDashIndex = args2.indexOf("--");
            unknown = args2.slice(stopEarlyArgIndex, doubleDashIndex === -1 ? undefined : doubleDashIndex);
            if (doubleDashIndex !== -1) {
                literal1 = args2.slice(doubleDashIndex + 1);
            }
        }
    }
    if (opts.flags?.length) {
        validateFlags(opts.flags, flags, opts.knownFlaks, opts.allowEmpty, optionNames);
    }
    const result1 = Object.keys(flags).reduce((result3, key)=>{
        if (~key.indexOf(".")) {
            key.split(".").reduce((result, subKey, index, parts)=>{
                if (index === parts.length - 1) {
                    result[subKey] = flags[key];
                } else {
                    result[subKey] = result[subKey] ?? {};
                }
                return result[subKey];
            }, result3);
        } else {
            result3[key] = flags[key];
        }
        return result3;
    }, {});
    return {
        flags: result1,
        unknown,
        literal: literal1
    };
}
function parseFlagValue(option, arg, value) {
    const type = arg.type || OptionType.STRING;
    const parseType = Types[type];
    if (!parseType) {
        throw new UnknownType(type, Object.keys(Types));
    }
    return parseType({
        label: "Option",
        type,
        name: `--${option.name}`,
        value
    });
}
function getPermissions() {
    return hasPermissions([
        "env",
        "hrtime",
        "net",
        "plugin",
        "read",
        "run",
        "write", 
    ]);
}
function isUnstable() {
    return !!Deno.permissions;
}
function didYouMeanCommand(command1, commands1, excludes = []) {
    const commandNames = commands1.map((command)=>command.getName()
    ).filter((command)=>!excludes.includes(command)
    );
    return didYouMean(" Did you mean command", command1, commandNames);
}
async function hasPermission(permission) {
    try {
        return (await Deno.permissions?.query?.({
            name: permission
        }))?.state === "granted";
    } catch  {
        return false;
    }
}
async function hasPermissions(names) {
    const permissions = {};
    await Promise.all(names.map((name9)=>hasPermission(name9).then((hasPermission1)=>permissions[name9] = hasPermission1
        )
    ));
    return permissions;
}
const ARGUMENT_REGEX = /^[<\[].+[\]>]$/;
const ARGUMENT_DETAILS_REGEX = /[<\[:>\]]/;
function splitArguments(args) {
    const parts = args.trim().split(/[, =] */g);
    const typeParts = [];
    while(parts[parts.length - 1] && ARGUMENT_REGEX.test(parts[parts.length - 1])){
        typeParts.unshift(parts.pop());
    }
    const typeDefinition = typeParts.join(" ");
    return {
        flags: parts,
        typeDefinition
    };
}
function parseArgumentsDefinition(argsDefinition) {
    const argumentDetails = [];
    let hasOptional = false;
    let hasVariadic = false;
    const parts = argsDefinition.split(/ +/);
    for (const arg of parts){
        if (hasVariadic) {
            throw new ArgumentFollowsVariadicArgument(arg);
        }
        const parts = arg.split(ARGUMENT_DETAILS_REGEX);
        const type = parts[2] || OptionType.STRING;
        const details = {
            optionalValue: arg[0] !== "<",
            name: parts[1],
            action: parts[3] || type,
            variadic: false,
            list: type ? arg.indexOf(type + "[]") !== -1 : false,
            type
        };
        if (!details.optionalValue && hasOptional) {
            throw new RequiredArgumentFollowsOptionalArgument(details.name);
        }
        if (arg[0] === "[") {
            hasOptional = true;
        }
        if (details.name.length > 3) {
            const istVariadicLeft = details.name.slice(0, 3) === "...";
            const istVariadicRight = details.name.slice(-3) === "...";
            hasVariadic = details.variadic = istVariadicLeft || istVariadicRight;
            if (istVariadicLeft) {
                details.name = details.name.slice(3);
            } else if (istVariadicRight) {
                details.name = details.name.slice(0, -3);
            }
        }
        if (details.name) {
            argumentDetails.push(details);
        }
    }
    return argumentDetails;
}
const { Deno: Deno2  } = globalThis;
const noColor = typeof Deno2?.noColor === "boolean" ? Deno2.noColor : true;
let enabled = !noColor;
function setColorEnabled(value) {
    if (noColor) {
        return;
    }
    enabled = value;
}
function getColorEnabled() {
    return enabled;
}
function code(open, close) {
    return {
        open: `\x1b[${open.join(";")}m`,
        close: `\x1b[${close}m`,
        regexp: new RegExp(`\\x1b\\[${close}m`, "g")
    };
}
function run(str3, code1) {
    return enabled ? `${code1.open}${str3.replace(code1.regexp, code1.open)}${code1.close}` : str3;
}
function reset(str4) {
    return run(str4, code([
        0
    ], 0));
}
function bold(str5) {
    return run(str5, code([
        1
    ], 22));
}
function dim(str6) {
    return run(str6, code([
        2
    ], 22));
}
function italic(str7) {
    return run(str7, code([
        3
    ], 23));
}
function underline(str8) {
    return run(str8, code([
        4
    ], 24));
}
function inverse(str9) {
    return run(str9, code([
        7
    ], 27));
}
function hidden(str10) {
    return run(str10, code([
        8
    ], 28));
}
function strikethrough(str11) {
    return run(str11, code([
        9
    ], 29));
}
function black(str12) {
    return run(str12, code([
        30
    ], 39));
}
function red(str13) {
    return run(str13, code([
        31
    ], 39));
}
function green(str14) {
    return run(str14, code([
        32
    ], 39));
}
function yellow(str15) {
    return run(str15, code([
        33
    ], 39));
}
function blue(str16) {
    return run(str16, code([
        34
    ], 39));
}
function magenta(str17) {
    return run(str17, code([
        35
    ], 39));
}
function cyan(str18) {
    return run(str18, code([
        36
    ], 39));
}
function white(str19) {
    return run(str19, code([
        37
    ], 39));
}
function gray(str20) {
    return brightBlack(str20);
}
function brightBlack(str21) {
    return run(str21, code([
        90
    ], 39));
}
function brightRed(str22) {
    return run(str22, code([
        91
    ], 39));
}
function brightGreen(str23) {
    return run(str23, code([
        92
    ], 39));
}
function brightYellow(str24) {
    return run(str24, code([
        93
    ], 39));
}
function brightBlue(str25) {
    return run(str25, code([
        94
    ], 39));
}
function brightMagenta(str26) {
    return run(str26, code([
        95
    ], 39));
}
function brightCyan(str27) {
    return run(str27, code([
        96
    ], 39));
}
function brightWhite(str28) {
    return run(str28, code([
        97
    ], 39));
}
function bgBlack(str29) {
    return run(str29, code([
        40
    ], 49));
}
function bgRed(str30) {
    return run(str30, code([
        41
    ], 49));
}
function bgGreen(str31) {
    return run(str31, code([
        42
    ], 49));
}
function bgYellow(str32) {
    return run(str32, code([
        43
    ], 49));
}
function bgBlue(str33) {
    return run(str33, code([
        44
    ], 49));
}
function bgMagenta(str34) {
    return run(str34, code([
        45
    ], 49));
}
function bgCyan(str35) {
    return run(str35, code([
        46
    ], 49));
}
function bgWhite(str36) {
    return run(str36, code([
        47
    ], 49));
}
function bgBrightBlack(str37) {
    return run(str37, code([
        100
    ], 49));
}
function bgBrightRed(str38) {
    return run(str38, code([
        101
    ], 49));
}
function bgBrightGreen(str39) {
    return run(str39, code([
        102
    ], 49));
}
function bgBrightYellow(str40) {
    return run(str40, code([
        103
    ], 49));
}
function bgBrightBlue(str41) {
    return run(str41, code([
        104
    ], 49));
}
function bgBrightMagenta(str42) {
    return run(str42, code([
        105
    ], 49));
}
function bgBrightCyan(str43) {
    return run(str43, code([
        106
    ], 49));
}
function bgBrightWhite(str44) {
    return run(str44, code([
        107
    ], 49));
}
function clampAndTruncate(n, max = 255, min = 0) {
    return Math.trunc(Math.max(Math.min(n, max), min));
}
function rgb8(str45, color) {
    return run(str45, code([
        38,
        5,
        clampAndTruncate(color)
    ], 39));
}
function bgRgb8(str46, color) {
    return run(str46, code([
        48,
        5,
        clampAndTruncate(color)
    ], 49));
}
function rgb24(str47, color) {
    if (typeof color === "number") {
        return run(str47, code([
            38,
            2,
            color >> 16 & 255,
            color >> 8 & 255,
            color & 255
        ], 39));
    }
    return run(str47, code([
        38,
        2,
        clampAndTruncate(color.r),
        clampAndTruncate(color.g),
        clampAndTruncate(color.b), 
    ], 39));
}
function bgRgb24(str48, color) {
    if (typeof color === "number") {
        return run(str48, code([
            48,
            2,
            color >> 16 & 255,
            color >> 8 & 255,
            color & 255
        ], 49));
    }
    return run(str48, code([
        48,
        2,
        clampAndTruncate(color.r),
        clampAndTruncate(color.g),
        clampAndTruncate(color.b), 
    ], 49));
}
const ANSI_PATTERN = new RegExp([
    "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", 
].join("|"), "g");
function stripColor(string1) {
    return string1.replace(ANSI_PATTERN, "");
}
const mod = {
    setColorEnabled: setColorEnabled,
    getColorEnabled: getColorEnabled,
    reset: reset,
    bold: bold,
    dim: dim,
    italic: italic,
    underline: underline,
    inverse: inverse,
    hidden: hidden,
    strikethrough: strikethrough,
    black: black,
    red: red,
    green: green,
    yellow: yellow,
    blue: blue,
    magenta: magenta,
    cyan: cyan,
    white: white,
    gray: gray,
    brightBlack: brightBlack,
    brightRed: brightRed,
    brightGreen: brightGreen,
    brightYellow: brightYellow,
    brightBlue: brightBlue,
    brightMagenta: brightMagenta,
    brightCyan: brightCyan,
    brightWhite: brightWhite,
    bgBlack: bgBlack,
    bgRed: bgRed,
    bgGreen: bgGreen,
    bgYellow: bgYellow,
    bgBlue: bgBlue,
    bgMagenta: bgMagenta,
    bgCyan: bgCyan,
    bgWhite: bgWhite,
    bgBrightBlack: bgBrightBlack,
    bgBrightRed: bgBrightRed,
    bgBrightGreen: bgBrightGreen,
    bgBrightYellow: bgBrightYellow,
    bgBrightBlue: bgBrightBlue,
    bgBrightMagenta: bgBrightMagenta,
    bgBrightCyan: bgBrightCyan,
    bgBrightWhite: bgBrightWhite,
    rgb8: rgb8,
    bgRgb8: bgRgb8,
    rgb24: rgb24,
    bgRgb24: bgRgb24,
    stripColor: stripColor
};
class CommandError extends Error {
    constructor(message){
        super(message);
        Object.setPrototypeOf(this, CommandError.prototype);
    }
}
class ValidationError1 extends CommandError {
    exitCode;
    constructor(message, { exitCode  } = {}){
        super(message);
        Object.setPrototypeOf(this, ValidationError1.prototype);
        this.exitCode = exitCode ?? 1;
    }
}
class DuplicateOptionName extends CommandError {
    constructor(name10){
        super(`Option with name "${getFlag(name10)}" already exists.`);
        Object.setPrototypeOf(this, DuplicateOptionName.prototype);
    }
}
class MissingCommandName extends CommandError {
    constructor(){
        super("Missing command name.");
        Object.setPrototypeOf(this, MissingCommandName.prototype);
    }
}
class DuplicateCommandName extends CommandError {
    constructor(name11){
        super(`Duplicate command name "${name11}".`);
        Object.setPrototypeOf(this, DuplicateCommandName.prototype);
    }
}
class DuplicateCommandAlias extends CommandError {
    constructor(alias){
        super(`Duplicate command alias "${alias}".`);
        Object.setPrototypeOf(this, DuplicateCommandAlias.prototype);
    }
}
class CommandNotFound extends CommandError {
    constructor(name12, commands2, excluded){
        super(`Unknown command "${name12}".${didYouMeanCommand(name12, commands2, excluded)}`);
        Object.setPrototypeOf(this, UnknownCommand.prototype);
    }
}
class DuplicateType extends CommandError {
    constructor(name13){
        super(`Type with name "${name13}" already exists.`);
        Object.setPrototypeOf(this, DuplicateType.prototype);
    }
}
class DuplicateCompletion extends CommandError {
    constructor(name14){
        super(`Completion with name "${name14}" already exists.`);
        Object.setPrototypeOf(this, DuplicateCompletion.prototype);
    }
}
class DuplicateExample extends CommandError {
    constructor(name15){
        super(`Example with name "${name15}" already exists.`);
        Object.setPrototypeOf(this, DuplicateExample.prototype);
    }
}
class DuplicateEnvironmentVariable extends CommandError {
    constructor(name16){
        super(`Environment variable with name "${name16}" already exists.`);
        Object.setPrototypeOf(this, DuplicateEnvironmentVariable.prototype);
    }
}
class EnvironmentVariableSingleValue extends CommandError {
    constructor(name17){
        super(`An environment variable can only have one value, but "${name17}" has more than one.`);
        Object.setPrototypeOf(this, EnvironmentVariableSingleValue.prototype);
    }
}
class EnvironmentVariableOptionalValue extends CommandError {
    constructor(name18){
        super(`An environment variable cannot have an optional value, but "${name18}" is defined as optional.`);
        Object.setPrototypeOf(this, EnvironmentVariableOptionalValue.prototype);
    }
}
class EnvironmentVariableVariadicValue extends CommandError {
    constructor(name19){
        super(`An environment variable cannot have an variadic value, but "${name19}" is defined as variadic.`);
        Object.setPrototypeOf(this, EnvironmentVariableVariadicValue.prototype);
    }
}
class DefaultCommandNotFound extends CommandError {
    constructor(name20, commands3){
        super(`Default command "${name20}" not found.${didYouMeanCommand(name20, commands3)}`);
        Object.setPrototypeOf(this, DefaultCommandNotFound.prototype);
    }
}
class CommandExecutableNotFound extends CommandError {
    constructor(name21, files){
        super(`Command executable not found: ${name21}:\n    - ${files.join("\\n    - ")}`);
        Object.setPrototypeOf(this, CommandExecutableNotFound.prototype);
    }
}
class UnknownCompletionCommand extends CommandError {
    constructor(name22, commands4){
        super(`Auto-completion failed. Unknown command "${name22}".${didYouMeanCommand(name22, commands4)}`);
        Object.setPrototypeOf(this, UnknownCompletionCommand.prototype);
    }
}
class UnknownCommand extends ValidationError1 {
    constructor(name23, commands5, excluded){
        super(`Unknown command "${name23}".${didYouMeanCommand(name23, commands5, excluded)}`);
        Object.setPrototypeOf(this, UnknownCommand.prototype);
    }
}
class NoArgumentsAllowed extends ValidationError1 {
    constructor(name24){
        super(`No arguments allowed for command "${name24}".`);
        Object.setPrototypeOf(this, NoArgumentsAllowed.prototype);
    }
}
class MissingArguments extends ValidationError1 {
    constructor(args){
        super("Missing argument(s): " + args.join(", "));
        Object.setPrototypeOf(this, MissingArguments.prototype);
    }
}
class MissingArgument extends ValidationError1 {
    constructor(arg){
        super(`Missing argument "${arg}".`);
        Object.setPrototypeOf(this, MissingArgument.prototype);
    }
}
class TooManyArguments extends ValidationError1 {
    constructor(args){
        super(`Too many arguments: ${args.join(" ")}`);
        Object.setPrototypeOf(this, TooManyArguments.prototype);
    }
}
class Type {
}
class BooleanType extends Type {
    parse(type) {
        return __boolean(type);
    }
    complete() {
        return [
            "true",
            "false"
        ];
    }
}
class NumberType extends Type {
    parse(type) {
        return number(type);
    }
}
class StringType extends Type {
    parse(type) {
        return string(type);
    }
}
const border = {
    top: "─",
    topMid: "┬",
    topLeft: "┌",
    topRight: "┐",
    bottom: "─",
    bottomMid: "┴",
    bottomLeft: "└",
    bottomRight: "┘",
    left: "│",
    leftMid: "├",
    mid: "─",
    midMid: "┼",
    right: "│",
    rightMid: "┤",
    middle: "│"
};
class Cell {
    value;
    options = {};
    get length() {
        return this.toString().length;
    }
    static from(value) {
        const cell = new this(value);
        if (value instanceof Cell) {
            cell.options = {
                ...value.options
            };
        }
        return cell;
    }
    constructor(value){
        this.value = value;
    }
    toString() {
        return this.value.toString();
    }
    setValue(value) {
        this.value = value;
        return this;
    }
    clone(value) {
        const cell = new Cell(value ?? this);
        cell.options = {
            ...this.options
        };
        return cell;
    }
    border(enable, override = true) {
        if (override || typeof this.options.border === "undefined") {
            this.options.border = enable;
        }
        return this;
    }
    colSpan(span, override = true) {
        if (override || typeof this.options.colSpan === "undefined") {
            this.options.colSpan = span;
        }
        return this;
    }
    rowSpan(span, override = true) {
        if (override || typeof this.options.rowSpan === "undefined") {
            this.options.rowSpan = span;
        }
        return this;
    }
    align(direction, override = true) {
        if (override || typeof this.options.align === "undefined") {
            this.options.align = direction;
        }
        return this;
    }
    getBorder() {
        return this.options.border === true;
    }
    getColSpan() {
        return typeof this.options.colSpan === "number" && this.options.colSpan > 0 ? this.options.colSpan : 1;
    }
    getRowSpan() {
        return typeof this.options.rowSpan === "number" && this.options.rowSpan > 0 ? this.options.rowSpan : 1;
    }
    getAlign() {
        return this.options.align ?? "left";
    }
}
class Row extends Array {
    options = {};
    static from(cells) {
        const row = new this(...cells);
        if (cells instanceof Row) {
            row.options = {
                ...cells.options
            };
        }
        return row;
    }
    clone() {
        const row = new Row(...this.map((cell)=>cell instanceof Cell ? cell.clone() : cell
        ));
        row.options = {
            ...this.options
        };
        return row;
    }
    border(enable, override = true) {
        if (override || typeof this.options.border === "undefined") {
            this.options.border = enable;
        }
        return this;
    }
    align(direction, override = true) {
        if (override || typeof this.options.align === "undefined") {
            this.options.align = direction;
        }
        return this;
    }
    getBorder() {
        return this.options.border === true;
    }
    hasBorder() {
        return this.getBorder() || this.some((cell)=>cell instanceof Cell && cell.getBorder()
        );
    }
    getAlign() {
        return this.options.align ?? "left";
    }
}
function consumeWords(length, content) {
    let consumed = "";
    const words = content.split(/ /g);
    for(let i6 = 0; i6 < words.length; i6++){
        let word = words[i6];
        const hasLineBreak = word.indexOf("\n") !== -1;
        if (hasLineBreak) {
            word = word.split("\n").shift();
        }
        if (consumed) {
            const nextLength = stripColor(word).length;
            const consumedLength = stripColor(consumed).length;
            if (consumedLength + nextLength >= length) {
                break;
            }
        }
        consumed += (i6 > 0 ? " " : "") + word;
        if (hasLineBreak) {
            break;
        }
    }
    return consumed;
}
function longest(index, rows, maxWidth) {
    return Math.max(...rows.map((row)=>(row[index] instanceof Cell && row[index].getColSpan() > 1 ? "" : row[index]?.toString() || "").split("\n").map((r)=>{
            const str49 = typeof maxWidth === "undefined" ? r : consumeWords(maxWidth, r);
            return stripColor(str49).length || 0;
        })
    ).flat());
}
class TableLayout {
    table;
    options;
    constructor(table, options){
        this.table = table;
        this.options = options;
    }
    toString() {
        const opts = this.createLayout();
        return opts.rows.length ? this.renderRows(opts) : "";
    }
    createLayout() {
        Object.keys(this.options.chars).forEach((key)=>{
            if (typeof this.options.chars[key] !== "string") {
                this.options.chars[key] = "";
            }
        });
        const hasBodyBorder = this.table.getBorder() || this.table.hasBodyBorder();
        const hasHeaderBorder = this.table.hasHeaderBorder();
        const hasBorder = hasHeaderBorder || hasBodyBorder;
        const header = this.table.getHeader();
        const rows = this.spanRows(header ? [
            header,
            ...this.table
        ] : this.table.slice());
        const columns = Math.max(...rows.map((row)=>row.length
        ));
        for (const row1 of rows){
            const length = row1.length;
            if (length < columns) {
                const diff = columns - length;
                for(let i7 = 0; i7 < diff; i7++){
                    row1.push(this.createCell(null, row1));
                }
            }
        }
        const padding = [];
        const width = [];
        for(let colIndex = 0; colIndex < columns; colIndex++){
            const minColWidth = Array.isArray(this.options.minColWidth) ? this.options.minColWidth[colIndex] : this.options.minColWidth;
            const maxColWidth = Array.isArray(this.options.maxColWidth) ? this.options.maxColWidth[colIndex] : this.options.maxColWidth;
            const colWidth = longest(colIndex, rows, maxColWidth);
            width[colIndex] = Math.min(maxColWidth, Math.max(minColWidth, colWidth));
            padding[colIndex] = Array.isArray(this.options.padding) ? this.options.padding[colIndex] : this.options.padding;
        }
        return {
            padding,
            width,
            rows,
            columns,
            hasBorder,
            hasBodyBorder,
            hasHeaderBorder
        };
    }
    spanRows(_rows, rowIndex = 0, colIndex = 0, rowSpan = [], colSpan = 1) {
        const rows = _rows;
        if (rowIndex >= rows.length && rowSpan.every((span)=>span === 1
        )) {
            return rows;
        } else if (rows[rowIndex] && colIndex >= rows[rowIndex].length && colIndex >= rowSpan.length && colSpan === 1) {
            return this.spanRows(rows, ++rowIndex, 0, rowSpan, 1);
        }
        if (colSpan > 1) {
            colSpan--;
            rowSpan[colIndex] = rowSpan[colIndex - 1];
            rows[rowIndex].splice(colIndex - 1, 0, rows[rowIndex][colIndex - 1]);
            return this.spanRows(rows, rowIndex, ++colIndex, rowSpan, colSpan);
        }
        if (colIndex === 0) {
            rows[rowIndex] = this.createRow(rows[rowIndex] || []);
        }
        if (rowSpan[colIndex] > 1) {
            rowSpan[colIndex]--;
            rows[rowIndex].splice(colIndex, 0, rows[rowIndex - 1][colIndex]);
            return this.spanRows(rows, rowIndex, ++colIndex, rowSpan, colSpan);
        }
        rows[rowIndex][colIndex] = this.createCell(rows[rowIndex][colIndex] || null, rows[rowIndex]);
        colSpan = rows[rowIndex][colIndex].getColSpan();
        rowSpan[colIndex] = rows[rowIndex][colIndex].getRowSpan();
        return this.spanRows(rows, rowIndex, ++colIndex, rowSpan, colSpan);
    }
    createRow(row) {
        return Row.from(row).border(this.table.getBorder(), false).align(this.table.getAlign(), false);
    }
    createCell(cell, row) {
        return Cell.from(cell ?? "").border(row.getBorder(), false).align(row.getAlign(), false);
    }
    renderRows(opts) {
        let result = "";
        const rowSpan = new Array(opts.columns).fill(1);
        for(let rowIndex = 0; rowIndex < opts.rows.length; rowIndex++){
            result += this.renderRow(rowSpan, rowIndex, opts);
        }
        return result.slice(0, -1);
    }
    renderRow(rowSpan, rowIndex, opts, isMultiline) {
        const row = opts.rows[rowIndex];
        const prevRow = opts.rows[rowIndex - 1];
        const nextRow = opts.rows[rowIndex + 1];
        let result = "";
        let colSpan = 1;
        if (!isMultiline && rowIndex === 0 && row.hasBorder()) {
            result += this.renderBorderRow(undefined, row, rowSpan, opts);
        }
        let isMultilineRow = false;
        result += " ".repeat(this.options.indent || 0);
        for(let colIndex = 0; colIndex < opts.columns; colIndex++){
            if (colSpan > 1) {
                colSpan--;
                rowSpan[colIndex] = rowSpan[colIndex - 1];
                continue;
            }
            result += this.renderCell(colIndex, row, opts);
            if (rowSpan[colIndex] > 1) {
                if (!isMultiline) {
                    rowSpan[colIndex]--;
                }
            } else if (!prevRow || prevRow[colIndex] !== row[colIndex]) {
                rowSpan[colIndex] = row[colIndex].getRowSpan();
            }
            colSpan = row[colIndex].getColSpan();
            if (rowSpan[colIndex] === 1 && row[colIndex].length) {
                isMultilineRow = true;
            }
        }
        if (opts.columns > 0) {
            if (row[opts.columns - 1].getBorder()) {
                result += this.options.chars.right;
            } else if (opts.hasBorder) {
                result += " ";
            }
        }
        result += "\n";
        if (isMultilineRow) {
            return result + this.renderRow(rowSpan, rowIndex, opts, isMultilineRow);
        }
        if (rowIndex === 0 && opts.hasHeaderBorder || rowIndex < opts.rows.length - 1 && opts.hasBodyBorder) {
            result += this.renderBorderRow(row, nextRow, rowSpan, opts);
        }
        if (rowIndex === opts.rows.length - 1 && row.hasBorder()) {
            result += this.renderBorderRow(row, undefined, rowSpan, opts);
        }
        return result;
    }
    renderCell(colIndex, row, opts, noBorder) {
        let result = "";
        const prevCell = row[colIndex - 1];
        const cell = row[colIndex];
        if (!noBorder) {
            if (colIndex === 0) {
                if (cell.getBorder()) {
                    result += this.options.chars.left;
                } else if (opts.hasBorder) {
                    result += " ";
                }
            } else {
                if (cell.getBorder() || prevCell?.getBorder()) {
                    result += this.options.chars.middle;
                } else if (opts.hasBorder) {
                    result += " ";
                }
            }
        }
        let maxLength = opts.width[colIndex];
        const colSpan = cell.getColSpan();
        if (colSpan > 1) {
            for(let o = 1; o < colSpan; o++){
                maxLength += opts.width[colIndex + o] + opts.padding[colIndex + o];
                if (opts.hasBorder) {
                    maxLength += opts.padding[colIndex + o] + 1;
                }
            }
        }
        const { current , next  } = this.renderCellValue(cell, maxLength);
        row[colIndex].setValue(next);
        if (opts.hasBorder) {
            result += " ".repeat(opts.padding[colIndex]);
        }
        result += current;
        if (opts.hasBorder || colIndex < opts.columns - 1) {
            result += " ".repeat(opts.padding[colIndex]);
        }
        return result;
    }
    renderCellValue(cell, maxLength) {
        const length = Math.min(maxLength, stripColor(cell.toString()).length);
        let words = consumeWords(length, cell.toString());
        const breakWord = stripColor(words).length > length;
        if (breakWord) {
            words = words.slice(0, length);
        }
        const next = cell.toString().slice(words.length + (breakWord ? 0 : 1));
        const fillLength = maxLength - stripColor(words).length;
        const align = cell.getAlign();
        let current;
        if (fillLength === 0) {
            current = words;
        } else if (align === "left") {
            current = words + " ".repeat(fillLength);
        } else if (align === "center") {
            current = " ".repeat(Math.floor(fillLength / 2)) + words + " ".repeat(Math.ceil(fillLength / 2));
        } else if (align === "right") {
            current = " ".repeat(fillLength) + words;
        } else {
            throw new Error("Unknown direction: " + align);
        }
        return {
            current,
            next: cell.clone(next)
        };
    }
    renderBorderRow(prevRow, nextRow, rowSpan, opts) {
        let result = "";
        let colSpan = 1;
        for(let colIndex = 0; colIndex < opts.columns; colIndex++){
            if (rowSpan[colIndex] > 1) {
                if (!nextRow) {
                    throw new Error("invalid layout");
                }
                if (colSpan > 1) {
                    colSpan--;
                    continue;
                }
            }
            result += this.renderBorderCell(colIndex, prevRow, nextRow, rowSpan, opts);
            colSpan = nextRow?.[colIndex].getColSpan() ?? 1;
        }
        return result.length ? " ".repeat(this.options.indent) + result + "\n" : "";
    }
    renderBorderCell(colIndex, prevRow, nextRow, rowSpan, opts) {
        const a1 = prevRow?.[colIndex - 1];
        const a2 = nextRow?.[colIndex - 1];
        const b1 = prevRow?.[colIndex];
        const b2 = nextRow?.[colIndex];
        const a1Border = !!a1?.getBorder();
        const a2Border = !!a2?.getBorder();
        const b1Border = !!b1?.getBorder();
        const b2Border = !!b2?.getBorder();
        const hasColSpan = (cell)=>(cell?.getColSpan() ?? 1) > 1
        ;
        const hasRowSpan = (cell)=>(cell?.getRowSpan() ?? 1) > 1
        ;
        let result = "";
        if (colIndex === 0) {
            if (rowSpan[colIndex] > 1) {
                if (b1Border) {
                    result += this.options.chars.left;
                } else {
                    result += " ";
                }
            } else if (b1Border && b2Border) {
                result += this.options.chars.leftMid;
            } else if (b1Border) {
                result += this.options.chars.bottomLeft;
            } else if (b2Border) {
                result += this.options.chars.topLeft;
            } else {
                result += " ";
            }
        } else if (colIndex < opts.columns) {
            if (a1Border && b2Border || b1Border && a2Border) {
                const a1ColSpan = hasColSpan(a1);
                const a2ColSpan = hasColSpan(a2);
                const b1ColSpan = hasColSpan(b1);
                const b2ColSpan = hasColSpan(b2);
                const a1RowSpan = hasRowSpan(a1);
                const a2RowSpan = hasRowSpan(a2);
                const b1RowSpan = hasRowSpan(b1);
                const b2RowSpan = hasRowSpan(b2);
                const hasAllBorder = a1Border && b2Border && b1Border && a2Border;
                const hasAllRowSpan = a1RowSpan && b1RowSpan && a2RowSpan && b2RowSpan;
                const hasAllColSpan = a1ColSpan && b1ColSpan && a2ColSpan && b2ColSpan;
                if (hasAllRowSpan && hasAllBorder) {
                    result += this.options.chars.middle;
                } else if (hasAllColSpan && hasAllBorder && a1 === b1 && a2 === b2) {
                    result += this.options.chars.mid;
                } else if (a1ColSpan && b1ColSpan && a1 === b1) {
                    result += this.options.chars.topMid;
                } else if (a2ColSpan && b2ColSpan && a2 === b2) {
                    result += this.options.chars.bottomMid;
                } else if (a1RowSpan && a2RowSpan && a1 === a2) {
                    result += this.options.chars.leftMid;
                } else if (b1RowSpan && b2RowSpan && b1 === b2) {
                    result += this.options.chars.rightMid;
                } else {
                    result += this.options.chars.midMid;
                }
            } else if (a1Border && b1Border) {
                if (hasColSpan(a1) && hasColSpan(b1) && a1 === b1) {
                    result += this.options.chars.bottom;
                } else {
                    result += this.options.chars.bottomMid;
                }
            } else if (b1Border && b2Border) {
                if (rowSpan[colIndex] > 1) {
                    result += this.options.chars.left;
                } else {
                    result += this.options.chars.leftMid;
                }
            } else if (b2Border && a2Border) {
                if (hasColSpan(a2) && hasColSpan(b2) && a2 === b2) {
                    result += this.options.chars.top;
                } else {
                    result += this.options.chars.topMid;
                }
            } else if (a1Border && a2Border) {
                if (hasRowSpan(a1) && a1 === a2) {
                    result += this.options.chars.right;
                } else {
                    result += this.options.chars.rightMid;
                }
            } else if (a1Border) {
                result += this.options.chars.bottomRight;
            } else if (b1Border) {
                result += this.options.chars.bottomLeft;
            } else if (a2Border) {
                result += this.options.chars.topRight;
            } else if (b2Border) {
                result += this.options.chars.topLeft;
            } else {
                result += " ";
            }
        }
        const length = opts.padding[colIndex] + opts.width[colIndex] + opts.padding[colIndex];
        if (rowSpan[colIndex] > 1 && nextRow) {
            result += this.renderCell(colIndex, nextRow, opts, true);
            if (nextRow[colIndex] === nextRow[nextRow.length - 1]) {
                if (b1Border) {
                    result += this.options.chars.right;
                } else {
                    result += " ";
                }
                return result;
            }
        } else if (b1Border && b2Border) {
            result += this.options.chars.mid.repeat(length);
        } else if (b1Border) {
            result += this.options.chars.bottom.repeat(length);
        } else if (b2Border) {
            result += this.options.chars.top.repeat(length);
        } else {
            result += " ".repeat(length);
        }
        if (colIndex === opts.columns - 1) {
            if (b1Border && b2Border) {
                result += this.options.chars.rightMid;
            } else if (b1Border) {
                result += this.options.chars.bottomRight;
            } else if (b2Border) {
                result += this.options.chars.topRight;
            } else {
                result += " ";
            }
        }
        return result;
    }
}
class Table extends Array {
    static _chars = {
        ...border
    };
    options = {
        indent: 0,
        border: false,
        maxColWidth: Infinity,
        minColWidth: 0,
        padding: 1,
        chars: {
            ...Table._chars
        }
    };
    headerRow;
    static from(rows) {
        const table = new this(...rows);
        if (rows instanceof Table) {
            table.options = {
                ...rows.options
            };
            table.headerRow = rows.headerRow ? Row.from(rows.headerRow) : undefined;
        }
        return table;
    }
    static fromJson(rows) {
        return new this().fromJson(rows);
    }
    static chars(chars) {
        Object.assign(this._chars, chars);
        return this;
    }
    static render(rows) {
        Table.from(rows).render();
    }
    fromJson(rows) {
        this.header(Object.keys(rows[0]));
        this.body(rows.map((row)=>Object.values(row)
        ));
        return this;
    }
    header(header) {
        this.headerRow = header instanceof Row ? header : Row.from(header);
        return this;
    }
    body(rows) {
        this.length = 0;
        this.push(...rows);
        return this;
    }
    clone() {
        const table = new Table(...this.map((row)=>row instanceof Row ? row.clone() : Row.from(row).clone()
        ));
        table.options = {
            ...this.options
        };
        table.headerRow = this.headerRow?.clone();
        return table;
    }
    toString() {
        return new TableLayout(this, this.options).toString();
    }
    render() {
        Deno.stdout.writeSync(new TextEncoder().encode(this.toString() + "\n"));
        return this;
    }
    maxColWidth(width, override = true) {
        if (override || typeof this.options.maxColWidth === "undefined") {
            this.options.maxColWidth = width;
        }
        return this;
    }
    minColWidth(width, override = true) {
        if (override || typeof this.options.minColWidth === "undefined") {
            this.options.minColWidth = width;
        }
        return this;
    }
    indent(width, override = true) {
        if (override || typeof this.options.indent === "undefined") {
            this.options.indent = width;
        }
        return this;
    }
    padding(padding, override = true) {
        if (override || typeof this.options.padding === "undefined") {
            this.options.padding = padding;
        }
        return this;
    }
    border(enable, override = true) {
        if (override || typeof this.options.border === "undefined") {
            this.options.border = enable;
        }
        return this;
    }
    align(direction, override = true) {
        if (override || typeof this.options.align === "undefined") {
            this.options.align = direction;
        }
        return this;
    }
    chars(chars) {
        Object.assign(this.options.chars, chars);
        return this;
    }
    getHeader() {
        return this.headerRow;
    }
    getBody() {
        return [
            ...this
        ];
    }
    getMaxColWidth() {
        return this.options.maxColWidth;
    }
    getMinColWidth() {
        return this.options.minColWidth;
    }
    getIndent() {
        return this.options.indent;
    }
    getPadding() {
        return this.options.padding;
    }
    getBorder() {
        return this.options.border === true;
    }
    hasHeaderBorder() {
        const hasBorder = this.headerRow?.hasBorder();
        return hasBorder === true || this.getBorder() && hasBorder !== false;
    }
    hasBodyBorder() {
        return this.getBorder() || this.some((row)=>row instanceof Row ? row.hasBorder() : row.some((cell)=>cell instanceof Cell ? cell.getBorder : false
            )
        );
    }
    hasBorder() {
        return this.hasHeaderBorder() || this.hasBodyBorder();
    }
    getAlign() {
        return this.options.align ?? "left";
    }
}
class HelpGenerator {
    cmd;
    indent = 2;
    options;
    static generate(cmd, options) {
        return new HelpGenerator(cmd, options).generate();
    }
    constructor(cmd, options = {}){
        this.cmd = cmd;
        this.options = {
            types: false,
            hints: true,
            colors: true,
            ...options
        };
    }
    generate() {
        const areColorsEnabled = getColorEnabled();
        setColorEnabled(this.options.colors);
        const result = this.generateHeader() + this.generateDescription() + this.generateOptions() + this.generateCommands() + this.generateEnvironmentVariables() + this.generateExamples() + "\n";
        setColorEnabled(areColorsEnabled);
        return result;
    }
    generateHeader() {
        const rows = [
            [
                bold("Usage:"),
                magenta(`${this.cmd.getPath()}${this.cmd.getArgsDefinition() ? " " + this.cmd.getArgsDefinition() : ""}`), 
            ], 
        ];
        const version1 = this.cmd.getVersion();
        if (version1) {
            rows.push([
                bold("Version:"),
                yellow(`${this.cmd.getVersion()}`)
            ]);
        }
        return "\n" + Table.from(rows).indent(this.indent).padding(1).toString() + "\n";
    }
    generateDescription() {
        if (!this.cmd.getDescription()) {
            return "";
        }
        return this.label("Description") + Table.from([
            [
                this.cmd.getDescription()
            ], 
        ]).indent(this.indent * 2).maxColWidth(140).padding(1).toString() + "\n";
    }
    generateOptions() {
        const options = this.cmd.getOptions(false);
        if (!options.length) {
            return "";
        }
        const hasTypeDefinitions = !!options.find((option)=>!!option.typeDefinition
        );
        if (hasTypeDefinitions) {
            return this.label("Options") + Table.from([
                ...options.map((option)=>[
                        option.flags.map((flag)=>blue(flag)
                        ).join(", "),
                        highlightArguments(option.typeDefinition || "", this.options.types),
                        red(bold("-")) + " " + option.description.split("\n").shift(),
                        this.generateHints(option), 
                    ]
                ), 
            ]).padding([
                2,
                2,
                2
            ]).indent(this.indent * 2).maxColWidth([
                60,
                60,
                80,
                60
            ]).toString() + "\n";
        }
        return this.label("Options") + Table.from([
            ...options.map((option)=>[
                    option.flags.map((flag)=>blue(flag)
                    ).join(", "),
                    red(bold("-")) + " " + option.description.split("\n").shift(),
                    this.generateHints(option), 
                ]
            ), 
        ]).padding([
            2,
            2
        ]).indent(this.indent * 2).maxColWidth([
            60,
            80,
            60
        ]).toString() + "\n";
    }
    generateCommands() {
        const commands6 = this.cmd.getCommands(false);
        if (!commands6.length) {
            return "";
        }
        const hasTypeDefinitions = !!commands6.find((command)=>!!command.getArgsDefinition()
        );
        if (hasTypeDefinitions) {
            return this.label("Commands") + Table.from([
                ...commands6.map((command)=>[
                        [
                            command.getName(),
                            ...command.getAliases()
                        ].map((name25)=>blue(name25)
                        ).join(", "),
                        highlightArguments(command.getArgsDefinition() || "", this.options.types),
                        red(bold("-")) + " " + command.getDescription().split("\n").shift(), 
                    ]
                ), 
            ]).padding([
                2,
                2,
                2
            ]).indent(this.indent * 2).toString() + "\n";
        }
        return this.label("Commands") + Table.from([
            ...commands6.map((command)=>[
                    [
                        command.getName(),
                        ...command.getAliases()
                    ].map((name26)=>blue(name26)
                    ).join(", "),
                    red(bold("-")) + " " + command.getDescription().split("\n").shift(), 
                ]
            ), 
        ]).padding([
            2,
            2
        ]).indent(this.indent * 2).toString() + "\n";
    }
    generateEnvironmentVariables() {
        const envVars = this.cmd.getEnvVars(false);
        if (!envVars.length) {
            return "";
        }
        return this.label("Environment variables") + Table.from([
            ...envVars.map((envVar)=>[
                    envVar.names.map((name27)=>blue(name27)
                    ).join(", "),
                    highlightArgumentDetails(envVar.details, this.options.types),
                    `${red(bold("-"))} ${envVar.description}`, 
                ]
            ), 
        ]).padding(2).indent(this.indent * 2).toString() + "\n";
    }
    generateExamples() {
        const examples = this.cmd.getExamples();
        if (!examples.length) {
            return "";
        }
        return this.label("Examples") + Table.from(examples.map((example)=>[
                dim(bold(`${capitalize(example.name)}:`)),
                example.description, 
            ]
        )).padding(1).indent(this.indent * 2).maxColWidth(150).toString() + "\n";
    }
    generateHints(option) {
        if (!this.options.hints) {
            return "";
        }
        const hints = [];
        option.required && hints.push(yellow(`required`));
        typeof option.default !== "undefined" && hints.push(bold(`Default: `) + inspect(option.default, this.options.colors));
        option.depends?.length && hints.push(yellow(bold(`Depends: `)) + italic(option.depends.map(getFlag).join(", ")));
        option.conflicts?.length && hints.push(red(bold(`Conflicts: `)) + italic(option.conflicts.map(getFlag).join(", ")));
        const type = this.cmd.getType(option.args[0]?.type)?.handler;
        if (type instanceof Type) {
            const possibleValues = type.values?.(this.cmd, this.cmd.getParent());
            if (possibleValues?.length) {
                hints.push(bold(`Values: `) + possibleValues.map((value)=>inspect(value, this.options.colors)
                ).join(", "));
            }
        }
        if (hints.length) {
            return `(${hints.join(", ")})`;
        }
        return "";
    }
    label(label) {
        return "\n" + " ".repeat(this.indent) + bold(`${label}:`) + "\n\n";
    }
}
function capitalize(string2) {
    return (string2?.charAt(0).toUpperCase() + string2.slice(1)) ?? "";
}
function inspect(value, colors) {
    return Deno.inspect(value, {
        depth: 1,
        colors,
        trailingComma: false
    });
}
function highlightArguments(argsDefinition, types6 = true) {
    if (!argsDefinition) {
        return "";
    }
    return parseArgumentsDefinition(argsDefinition).map((arg)=>highlightArgumentDetails(arg, types6)
    ).join(" ");
}
function highlightArgumentDetails(arg, types7 = true) {
    let str50 = "";
    str50 += yellow(arg.optionalValue ? "[" : "<");
    let name28 = "";
    name28 += arg.name;
    if (arg.variadic) {
        name28 += "...";
    }
    name28 = magenta(name28);
    str50 += name28;
    if (types7) {
        str50 += yellow(":");
        str50 += red(arg.type);
    }
    if (arg.list) {
        str50 += green("[]");
    }
    str50 += yellow(arg.optionalValue ? "]" : ">");
    return str50;
}
class IntegerType extends Type {
    parse(type) {
        return integer(type);
    }
}
class Command {
    types = new Map();
    rawArgs = [];
    literalArgs = [];
    _name = "COMMAND";
    _parent;
    _globalParent;
    ver;
    desc = "";
    fn;
    options = [];
    commands = new Map();
    examples = [];
    envVars = [];
    aliases = [];
    completions = new Map();
    cmd = this;
    argsDefinition;
    isExecutable = false;
    throwOnError = false;
    _allowEmpty = true;
    _stopEarly = false;
    defaultCommand;
    _useRawArgs = false;
    args = [];
    isHidden = false;
    isGlobal = false;
    hasDefaults = false;
    _versionOption;
    _helpOption;
    _help;
    versionOption(flags, desc, opts) {
        this._versionOption = flags === false ? flags : {
            flags,
            desc,
            opts: typeof opts === "function" ? {
                action: opts
            } : opts
        };
        return this;
    }
    helpOption(flags, desc, opts) {
        this._helpOption = flags === false ? flags : {
            flags,
            desc,
            opts: typeof opts === "function" ? {
                action: opts
            } : opts
        };
        return this;
    }
    command(nameAndArguments, cmdOrDescription, override) {
        const result = splitArguments(nameAndArguments);
        const name29 = result.flags.shift();
        const aliases = result.flags;
        if (!name29) {
            throw new MissingCommandName();
        }
        if (this.getBaseCommand(name29, true)) {
            if (!override) {
                throw new DuplicateCommandName(name29);
            }
            this.removeCommand(name29);
        }
        let description;
        let cmd;
        if (typeof cmdOrDescription === "string") {
            description = cmdOrDescription;
        }
        if (cmdOrDescription instanceof Command) {
            cmd = cmdOrDescription.reset();
        } else {
            cmd = new Command();
        }
        cmd._name = name29;
        cmd._parent = this;
        if (description) {
            cmd.description(description);
        }
        if (result.typeDefinition) {
            cmd.arguments(result.typeDefinition);
        }
        aliases.forEach((alias)=>cmd.alias(alias)
        );
        this.commands.set(name29, cmd);
        this.select(name29);
        return this;
    }
    alias(alias) {
        if (this.cmd._name === alias || this.cmd.aliases.includes(alias)) {
            throw new DuplicateCommandAlias(alias);
        }
        this.cmd.aliases.push(alias);
        return this;
    }
    reset() {
        this.cmd = this;
        return this;
    }
    select(name30) {
        const cmd = this.getBaseCommand(name30, true);
        if (!cmd) {
            throw new CommandNotFound(name30, this.getBaseCommands(true));
        }
        this.cmd = cmd;
        return this;
    }
    name(name31) {
        this.cmd._name = name31;
        return this;
    }
    version(version2) {
        if (typeof version2 === "string") {
            this.cmd.ver = ()=>version2
            ;
        } else if (typeof version2 === "function") {
            this.cmd.ver = version2;
        }
        return this;
    }
    help(help) {
        if (typeof help === "string") {
            this.cmd._help = ()=>help
            ;
        } else if (typeof help === "function") {
            this.cmd._help = help;
        } else {
            this.cmd._help = (cmd)=>HelpGenerator.generate(cmd, help)
            ;
        }
        return this;
    }
    description(description) {
        this.cmd.desc = description;
        return this;
    }
    hidden() {
        this.cmd.isHidden = true;
        return this;
    }
    global() {
        this.cmd.isGlobal = true;
        return this;
    }
    executable() {
        this.cmd.isExecutable = true;
        return this;
    }
    arguments(args) {
        this.cmd.argsDefinition = args;
        return this;
    }
    action(fn) {
        this.cmd.fn = fn;
        return this;
    }
    allowEmpty(allowEmpty = true) {
        this.cmd._allowEmpty = allowEmpty;
        return this;
    }
    stopEarly(stopEarly = true) {
        this.cmd._stopEarly = stopEarly;
        return this;
    }
    useRawArgs(useRawArgs = true) {
        this.cmd._useRawArgs = useRawArgs;
        return this;
    }
    default(name32) {
        this.cmd.defaultCommand = name32;
        return this;
    }
    globalType(name33, type, options) {
        return this.type(name33, type, {
            ...options,
            global: true
        });
    }
    type(name34, handler, options) {
        if (this.cmd.types.get(name34) && !options?.override) {
            throw new DuplicateType(name34);
        }
        this.cmd.types.set(name34, {
            ...options,
            name: name34,
            handler
        });
        if (handler instanceof Type && (typeof handler.complete !== "undefined" || typeof handler.values !== "undefined")) {
            const completeHandler = (cmd, parent)=>handler.complete?.(cmd, parent) || []
            ;
            this.complete(name34, completeHandler, options);
        }
        return this;
    }
    globalComplete(name35, complete, options) {
        return this.complete(name35, complete, {
            ...options,
            global: true
        });
    }
    complete(name36, complete, options) {
        if (this.cmd.completions.has(name36) && !options?.override) {
            throw new DuplicateCompletion(name36);
        }
        this.cmd.completions.set(name36, {
            name: name36,
            complete,
            ...options
        });
        return this;
    }
    throwErrors() {
        this.cmd.throwOnError = true;
        return this;
    }
    shouldThrowErrors() {
        return this.cmd.throwOnError || !!this.cmd._parent?.shouldThrowErrors();
    }
    globalOption(flags, desc, opts) {
        if (typeof opts === "function") {
            return this.option(flags, desc, {
                value: opts,
                global: true
            });
        }
        return this.option(flags, desc, {
            ...opts,
            global: true
        });
    }
    option(flags, desc, opts) {
        if (typeof opts === "function") {
            return this.option(flags, desc, {
                value: opts
            });
        }
        const result = splitArguments(flags);
        const args = result.typeDefinition ? parseArgumentsDefinition(result.typeDefinition) : [];
        const option = {
            ...opts,
            name: "",
            description: desc,
            args,
            flags: result.flags,
            typeDefinition: result.typeDefinition
        };
        if (option.separator) {
            for (const arg of args){
                if (arg.list) {
                    arg.separator = option.separator;
                }
            }
        }
        for (const part of option.flags){
            const arg = part.trim();
            const isLong = /^--/.test(arg);
            const name37 = isLong ? arg.slice(2) : arg.slice(1);
            if (this.cmd.getBaseOption(name37, true)) {
                if (opts?.override) {
                    this.removeOption(name37);
                } else {
                    throw new DuplicateOptionName(name37);
                }
            }
            if (!option.name && isLong) {
                option.name = name37;
            } else if (!option.aliases) {
                option.aliases = [
                    name37
                ];
            } else {
                option.aliases.push(name37);
            }
        }
        if (option.prepend) {
            this.cmd.options.unshift(option);
        } else {
            this.cmd.options.push(option);
        }
        return this;
    }
    example(name38, description) {
        if (this.cmd.hasExample(name38)) {
            throw new DuplicateExample(name38);
        }
        this.cmd.examples.push({
            name: name38,
            description
        });
        return this;
    }
    globalEnv(name39, description, options) {
        return this.env(name39, description, {
            ...options,
            global: true
        });
    }
    env(name40, description, options) {
        const result = splitArguments(name40);
        if (!result.typeDefinition) {
            result.typeDefinition = "<value:boolean>";
        }
        if (result.flags.some((envName)=>this.cmd.getBaseEnvVar(envName, true)
        )) {
            throw new DuplicateEnvironmentVariable(name40);
        }
        const details = parseArgumentsDefinition(result.typeDefinition);
        if (details.length > 1) {
            throw new EnvironmentVariableSingleValue(name40);
        } else if (details.length && details[0].optionalValue) {
            throw new EnvironmentVariableOptionalValue(name40);
        } else if (details.length && details[0].variadic) {
            throw new EnvironmentVariableVariadicValue(name40);
        }
        this.cmd.envVars.push({
            name: result.flags[0],
            names: result.flags,
            description,
            type: details[0].type,
            details: details.shift(),
            ...options
        });
        return this;
    }
    async parse(args = Deno.args, dry) {
        try {
            this.reset();
            this.registerDefaults();
            this.rawArgs = args;
            const subCommand = args.length > 0 && this.getCommand(args[0], true);
            if (subCommand) {
                subCommand._globalParent = this;
                return await subCommand.parse(this.rawArgs.slice(1), dry);
            }
            const result = {
                options: {},
                args: this.rawArgs,
                cmd: this,
                literal: this.literalArgs
            };
            if (this.isExecutable) {
                if (!dry) {
                    await this.executeExecutable(this.rawArgs);
                }
                return result;
            } else if (this._useRawArgs) {
                if (dry) {
                    return result;
                }
                return await this.execute({}, ...this.rawArgs);
            } else {
                const { action , flags , unknown , literal: literal2  } = this.parseFlags(this.rawArgs);
                this.literalArgs = literal2;
                const params = this.parseArguments(unknown, flags);
                await this.validateEnvVars();
                if (dry || action) {
                    if (action) {
                        await action.call(this, flags, ...params);
                    }
                    return {
                        options: flags,
                        args: params,
                        cmd: this,
                        literal: this.literalArgs
                    };
                }
                return await this.execute(flags, ...params);
            }
        } catch (error1) {
            throw this.error(error1);
        }
    }
    registerDefaults() {
        if (this.hasDefaults || this.getParent()) {
            return this;
        }
        this.hasDefaults = true;
        this.reset();
        !this.types.has("string") && this.type("string", new StringType(), {
            global: true
        });
        !this.types.has("number") && this.type("number", new NumberType(), {
            global: true
        });
        !this.types.has("integer") && this.type("integer", new IntegerType(), {
            global: true
        });
        !this.types.has("boolean") && this.type("boolean", new BooleanType(), {
            global: true
        });
        if (!this._help) {
            this.help({
                hints: true,
                types: false
            });
        }
        if (this._versionOption !== false && (this._versionOption || this.ver)) {
            this.option(this._versionOption?.flags || "-V, --version", this._versionOption?.desc || "Show the version number for this program.", {
                standalone: true,
                prepend: true,
                action: function() {
                    this.showVersion();
                    Deno.exit(0);
                },
                ...this._versionOption?.opts ?? {}
            });
        }
        if (this._helpOption !== false) {
            this.option(this._helpOption?.flags || "-h, --help", this._helpOption?.desc || "Show this help.", {
                standalone: true,
                global: true,
                prepend: true,
                action: function() {
                    this.showHelp();
                    Deno.exit(0);
                },
                ...this._helpOption?.opts ?? {}
            });
        }
        return this;
    }
    async execute(options, ...args) {
        if (this.fn) {
            await this.fn(options, ...args);
        } else if (this.defaultCommand) {
            const cmd = this.getCommand(this.defaultCommand, true);
            if (!cmd) {
                throw new DefaultCommandNotFound(this.defaultCommand, this.getCommands());
            }
            cmd._globalParent = this;
            await cmd.execute(options, ...args);
        }
        return {
            options,
            args,
            cmd: this,
            literal: this.literalArgs
        };
    }
    async executeExecutable(args) {
        const permissions = await getPermissions();
        if (!permissions.read) {
            await Deno.permissions?.request({
                name: "read"
            });
        }
        if (!permissions.run) {
            await Deno.permissions?.request({
                name: "run"
            });
        }
        const [main1, ...names] = this.getPath().split(" ");
        names.unshift(main1.replace(/\.ts$/, ""));
        const executableName = names.join("-");
        const files = [];
        const parts = Deno.mainModule.replace(/^file:\/\//g, "").split("/");
        if (Deno.build.os === "windows" && parts[0] === "") {
            parts.shift();
        }
        parts.pop();
        const path2 = parts.join("/");
        files.push(path2 + "/" + executableName, path2 + "/" + executableName + ".ts");
        files.push(executableName, executableName + ".ts");
        const denoOpts = [];
        if (isUnstable()) {
            denoOpts.push("--unstable");
        }
        denoOpts.push("--allow-read", "--allow-run");
        Object.keys(permissions).forEach((name41)=>{
            if (name41 === "read" || name41 === "run") {
                return;
            }
            if (permissions[name41]) {
                denoOpts.push(`--allow-${name41}`);
            }
        });
        for (const file of files){
            try {
                Deno.lstatSync(file);
            } catch (error2) {
                if (error2 instanceof Deno.errors.NotFound) {
                    continue;
                }
                throw error2;
            }
            const cmd = [
                "deno",
                "run",
                ...denoOpts,
                file,
                ...args
            ];
            const process = Deno.run({
                cmd: cmd
            });
            const status = await process.status();
            if (!status.success) {
                Deno.exit(status.code);
            }
            return;
        }
        throw new CommandExecutableNotFound(executableName, files);
    }
    parseFlags(args) {
        try {
            let action;
            const result = parseFlags(args, {
                stopEarly: this._stopEarly,
                allowEmpty: this._allowEmpty,
                flags: this.getOptions(true),
                parse: (type)=>this.parseType(type)
                ,
                option: (option)=>{
                    if (!action && option.action) {
                        action = option.action;
                    }
                }
            });
            return {
                ...result,
                action
            };
        } catch (error3) {
            if (error3 instanceof ValidationError) {
                throw new ValidationError1(error3.message);
            }
            throw error3;
        }
    }
    parseType(type1) {
        const typeSettings = this.getType(type1.type);
        if (!typeSettings) {
            throw new UnknownType(type1.type, this.getTypes().map((type)=>type.name
            ));
        }
        return typeSettings.handler instanceof Type ? typeSettings.handler.parse(type1) : typeSettings.handler(type1);
    }
    async validateEnvVars() {
        if (!await hasPermission("env")) {
            return;
        }
        const envVars = this.getEnvVars(true);
        if (!envVars.length) {
            return;
        }
        envVars.forEach((env)=>{
            const name1 = env.names.find((name42)=>!!Deno.env.get(name42)
            );
            if (name1) {
                this.parseType({
                    label: "Environment variable",
                    type: env.type,
                    name: name1,
                    value: Deno.env.get(name1) ?? ""
                });
            }
        });
    }
    parseArguments(args, flags) {
        const params = [];
        args = args.slice(0);
        if (!this.hasArguments()) {
            if (args.length) {
                if (this.hasCommands(true)) {
                    throw new UnknownCommand(args[0], this.getCommands());
                } else {
                    throw new NoArgumentsAllowed(this.getPath());
                }
            }
        } else {
            if (!args.length) {
                const required = this.getArguments().filter((expectedArg)=>!expectedArg.optionalValue
                ).map((expectedArg)=>expectedArg.name
                );
                if (required.length) {
                    const flagNames = Object.keys(flags);
                    const hasStandaloneOption = !!flagNames.find((name43)=>this.getOption(name43, true)?.standalone
                    );
                    if (!hasStandaloneOption) {
                        throw new MissingArguments(required);
                    }
                }
            } else {
                for (const expectedArg of this.getArguments()){
                    if (!args.length) {
                        if (expectedArg.optionalValue) {
                            break;
                        }
                        throw new MissingArgument(`Missing argument: ${expectedArg.name}`);
                    }
                    let arg;
                    if (expectedArg.variadic) {
                        arg = args.splice(0, args.length).map((value)=>this.parseType({
                                label: "Argument",
                                type: expectedArg.type,
                                name: expectedArg.name,
                                value
                            })
                        );
                    } else {
                        arg = this.parseType({
                            label: "Argument",
                            type: expectedArg.type,
                            name: expectedArg.name,
                            value: args.shift()
                        });
                    }
                    if (arg) {
                        params.push(arg);
                    }
                }
                if (args.length) {
                    throw new TooManyArguments(args);
                }
            }
        }
        return params;
    }
    error(error4) {
        if (this.shouldThrowErrors() || !(error4 instanceof ValidationError1)) {
            return error4;
        }
        this.showHelp();
        Deno.stderr.writeSync(new TextEncoder().encode(red(`  ${bold("error")}: ${error4.message}\n`) + "\n"));
        Deno.exit(error4 instanceof ValidationError1 ? error4.exitCode : 1);
    }
    getName() {
        return this._name;
    }
    getParent() {
        return this._parent;
    }
    getGlobalParent() {
        return this._globalParent;
    }
    getMainCommand() {
        return this._parent?.getMainCommand() ?? this;
    }
    getAliases() {
        return this.aliases;
    }
    getPath() {
        return this._parent ? this._parent.getPath() + " " + this._name : this._name;
    }
    getArgsDefinition() {
        return this.argsDefinition;
    }
    getArgument(name44) {
        return this.getArguments().find((arg)=>arg.name === name44
        );
    }
    getArguments() {
        if (!this.args.length && this.argsDefinition) {
            this.args = parseArgumentsDefinition(this.argsDefinition);
        }
        return this.args;
    }
    hasArguments() {
        return !!this.argsDefinition;
    }
    getVersion() {
        return this.getVersionHandler()?.call(this, this);
    }
    getVersionHandler() {
        return this.ver ?? this._parent?.getVersionHandler();
    }
    getDescription() {
        return typeof this.desc === "function" ? this.desc = this.desc() : this.desc;
    }
    getShortDescription() {
        return this.getDescription().trim().split("\n").shift();
    }
    getRawArgs() {
        return this.rawArgs;
    }
    getLiteralArgs() {
        return this.literalArgs;
    }
    showVersion() {
        Deno.stdout.writeSync(new TextEncoder().encode(this.getVersion()));
    }
    showHelp() {
        Deno.stdout.writeSync(new TextEncoder().encode(this.getHelp()));
    }
    getHelp() {
        this.registerDefaults();
        return this.getHelpHandler().call(this, this);
    }
    getHelpHandler() {
        return this._help ?? this._parent?.getHelpHandler();
    }
    hasOptions(hidden1) {
        return this.getOptions(hidden1).length > 0;
    }
    getOptions(hidden2) {
        return this.getGlobalOptions(hidden2).concat(this.getBaseOptions(hidden2));
    }
    getBaseOptions(hidden3) {
        if (!this.options.length) {
            return [];
        }
        return hidden3 ? this.options.slice(0) : this.options.filter((opt)=>!opt.hidden
        );
    }
    getGlobalOptions(hidden4) {
        const getOptions1 = (cmd, options = [], names = [])=>{
            if (cmd) {
                if (cmd.options.length) {
                    cmd.options.forEach((option)=>{
                        if (option.global && !this.options.find((opt)=>opt.name === option.name
                        ) && names.indexOf(option.name) === -1 && (hidden4 || !option.hidden)) {
                            names.push(option.name);
                            options.push(option);
                        }
                    });
                }
                return getOptions1(cmd._parent, options, names);
            }
            return options;
        };
        return getOptions1(this._parent);
    }
    hasOption(name45, hidden5) {
        return !!this.getOption(name45, hidden5);
    }
    getOption(name46, hidden6) {
        return this.getBaseOption(name46, hidden6) ?? this.getGlobalOption(name46, hidden6);
    }
    getBaseOption(name47, hidden7) {
        const option1 = this.options.find((option)=>option.name === name47
        );
        return option1 && (hidden7 || !option1.hidden) ? option1 : undefined;
    }
    getGlobalOption(name48, hidden8) {
        if (!this._parent) {
            return;
        }
        const option = this._parent.getBaseOption(name48, hidden8);
        if (!option || !option.global) {
            return this._parent.getGlobalOption(name48, hidden8);
        }
        return option;
    }
    removeOption(name49) {
        const index = this.options.findIndex((option)=>option.name === name49
        );
        if (index === -1) {
            return;
        }
        return this.options.splice(index, 1)[0];
    }
    hasCommands(hidden9) {
        return this.getCommands(hidden9).length > 0;
    }
    getCommands(hidden10) {
        return this.getGlobalCommands(hidden10).concat(this.getBaseCommands(hidden10));
    }
    getBaseCommands(hidden11) {
        const commands7 = Array.from(this.commands.values());
        return hidden11 ? commands7 : commands7.filter((cmd)=>!cmd.isHidden
        );
    }
    getGlobalCommands(hidden12) {
        const getCommands = (cmd1, commands8 = [], names = [])=>{
            if (cmd1) {
                if (cmd1.commands.size) {
                    cmd1.commands.forEach((cmd)=>{
                        if (cmd.isGlobal && this !== cmd && !this.commands.has(cmd._name) && names.indexOf(cmd._name) === -1 && (hidden12 || !cmd.isHidden)) {
                            names.push(cmd._name);
                            commands8.push(cmd);
                        }
                    });
                }
                return getCommands(cmd1._parent, commands8, names);
            }
            return commands8;
        };
        return getCommands(this._parent);
    }
    hasCommand(name50, hidden13) {
        return !!this.getCommand(name50, hidden13);
    }
    getCommand(name51, hidden14) {
        return this.getBaseCommand(name51, hidden14) ?? this.getGlobalCommand(name51, hidden14);
    }
    getBaseCommand(name52, hidden15) {
        for (const cmd of this.commands.values()){
            if (cmd._name === name52 || cmd.aliases.includes(name52)) {
                return cmd && (hidden15 || !cmd.isHidden) ? cmd : undefined;
            }
        }
    }
    getGlobalCommand(name53, hidden16) {
        if (!this._parent) {
            return;
        }
        const cmd = this._parent.getBaseCommand(name53, hidden16);
        if (!cmd?.isGlobal) {
            return this._parent.getGlobalCommand(name53, hidden16);
        }
        return cmd;
    }
    removeCommand(name54) {
        const command = this.getBaseCommand(name54, true);
        if (command) {
            this.commands.delete(command._name);
        }
        return command;
    }
    getTypes() {
        return this.getGlobalTypes().concat(this.getBaseTypes());
    }
    getBaseTypes() {
        return Array.from(this.types.values());
    }
    getGlobalTypes() {
        const getTypes = (cmd, types8 = [], names = [])=>{
            if (cmd) {
                if (cmd.types.size) {
                    cmd.types.forEach((type)=>{
                        if (type.global && !this.types.has(type.name) && names.indexOf(type.name) === -1) {
                            names.push(type.name);
                            types8.push(type);
                        }
                    });
                }
                return getTypes(cmd._parent, types8, names);
            }
            return types8;
        };
        return getTypes(this._parent);
    }
    getType(name55) {
        return this.getBaseType(name55) ?? this.getGlobalType(name55);
    }
    getBaseType(name56) {
        return this.types.get(name56);
    }
    getGlobalType(name57) {
        if (!this._parent) {
            return;
        }
        const cmd = this._parent.getBaseType(name57);
        if (!cmd?.global) {
            return this._parent.getGlobalType(name57);
        }
        return cmd;
    }
    getCompletions() {
        return this.getGlobalCompletions().concat(this.getBaseCompletions());
    }
    getBaseCompletions() {
        return Array.from(this.completions.values());
    }
    getGlobalCompletions() {
        const getCompletions = (cmd, completions = [], names = [])=>{
            if (cmd) {
                if (cmd.completions.size) {
                    cmd.completions.forEach((completion)=>{
                        if (completion.global && !this.completions.has(completion.name) && names.indexOf(completion.name) === -1) {
                            names.push(completion.name);
                            completions.push(completion);
                        }
                    });
                }
                return getCompletions(cmd._parent, completions, names);
            }
            return completions;
        };
        return getCompletions(this._parent);
    }
    getCompletion(name58) {
        return this.getBaseCompletion(name58) ?? this.getGlobalCompletion(name58);
    }
    getBaseCompletion(name59) {
        return this.completions.get(name59);
    }
    getGlobalCompletion(name60) {
        if (!this._parent) {
            return;
        }
        const completion = this._parent.getBaseCompletion(name60);
        if (!completion?.global) {
            return this._parent.getGlobalCompletion(name60);
        }
        return completion;
    }
    hasEnvVars(hidden17) {
        return this.getEnvVars(hidden17).length > 0;
    }
    getEnvVars(hidden18) {
        return this.getGlobalEnvVars(hidden18).concat(this.getBaseEnvVars(hidden18));
    }
    getBaseEnvVars(hidden19) {
        if (!this.envVars.length) {
            return [];
        }
        return hidden19 ? this.envVars.slice(0) : this.envVars.filter((env)=>!env.hidden
        );
    }
    getGlobalEnvVars(hidden20) {
        const getEnvVars = (cmd, envVars = [], names = [])=>{
            if (cmd) {
                if (cmd.envVars.length) {
                    cmd.envVars.forEach((envVar)=>{
                        if (envVar.global && !this.envVars.find((env)=>env.names[0] === envVar.names[0]
                        ) && names.indexOf(envVar.names[0]) === -1 && (hidden20 || !envVar.hidden)) {
                            names.push(envVar.names[0]);
                            envVars.push(envVar);
                        }
                    });
                }
                return getEnvVars(cmd._parent, envVars, names);
            }
            return envVars;
        };
        return getEnvVars(this._parent);
    }
    hasEnvVar(name61, hidden21) {
        return !!this.getEnvVar(name61, hidden21);
    }
    getEnvVar(name62, hidden22) {
        return this.getBaseEnvVar(name62, hidden22) ?? this.getGlobalEnvVar(name62, hidden22);
    }
    getBaseEnvVar(name63, hidden23) {
        const envVar = this.envVars.find((env)=>env.names.indexOf(name63) !== -1
        );
        return envVar && (hidden23 || !envVar.hidden) ? envVar : undefined;
    }
    getGlobalEnvVar(name64, hidden24) {
        if (!this._parent) {
            return;
        }
        const envVar = this._parent.getBaseEnvVar(name64, hidden24);
        if (!envVar?.global) {
            return this._parent.getGlobalEnvVar(name64, hidden24);
        }
        return envVar;
    }
    hasExamples() {
        return this.examples.length > 0;
    }
    getExamples() {
        return this.examples;
    }
    hasExample(name65) {
        return !!this.getExample(name65);
    }
    getExample(name66) {
        return this.examples.find((example)=>example.name === name66
        );
    }
}
class BashCompletionsGenerator {
    cmd;
    static generate(cmd) {
        return new BashCompletionsGenerator(cmd).generate();
    }
    constructor(cmd){
        this.cmd = cmd;
    }
    generate() {
        const path3 = this.cmd.getPath();
        const version3 = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
        return `#!/usr/bin/env bash
# bash completion support for ${path3}${version3}

_${replaceSpecialChars(path3)}() {
  local word cur prev
  local -a opts
  COMPREPLY=()
  cur="\${COMP_WORDS[COMP_CWORD]}"
  prev="\${COMP_WORDS[COMP_CWORD-1]}"
  cmd="_"
  opts=()

  _${replaceSpecialChars(this.cmd.getName())}_complete() {
    local action="$1"; shift
    mapfile -t values < <( ${this.cmd.getName()} completions complete "\${action}" "\${@}" )
    for i in "\${values[@]}"; do
      opts+=("$i")
    done
  }

  ${this.generateCompletions(this.cmd).trim()}

  for word in "\${COMP_WORDS[@]}"; do
    case "\${word}" in
      -*) ;;
      *)
        cmd_tmp="\${cmd}_\${word//[^[:alnum:]]/_}"
        if type "\${cmd_tmp}" &>/dev/null; then
          cmd="\${cmd_tmp}"
        fi
    esac
  done

  \${cmd}

  if [[ \${#opts[@]} -eq 0 ]]; then
    # shellcheck disable=SC2207
    COMPREPLY=($(compgen -f "\${cur}"))
    return 0
  fi

  local values
  values="$( printf "\\n%s" "\${opts[@]}" )"
  local IFS=$'\\n'
  # shellcheck disable=SC2207
  local result=($(compgen -W "\${values[@]}" -- "\${cur}"))
  if [[ \${#result[@]} -eq 0 ]]; then
    # shellcheck disable=SC2207
    COMPREPLY=($(compgen -f "\${cur}"))
  else
    # shellcheck disable=SC2207
    COMPREPLY=($(printf '%q\\n' "\${result[@]}"))
  fi

  return 0
}

complete -F _${replaceSpecialChars(path3)} -o bashdefault -o default ${path3}
`;
    }
    generateCompletions(command, path4 = "", index = 1) {
        path4 = (path4 ? path4 + " " : "") + command.getName();
        const commandCompletions = this.generateCommandCompletions(command, path4, index);
        const childCommandCompletions = command.getCommands(false).filter((subCommand)=>subCommand !== command
        ).map((subCommand)=>this.generateCompletions(subCommand, path4, index + 1)
        ).join("");
        return `${commandCompletions}

${childCommandCompletions}`;
    }
    generateCommandCompletions(command, path5, index) {
        const flags = this.getFlags(command);
        const childCommandNames = command.getCommands(false).map((childCommand)=>childCommand.getName()
        );
        const completionsPath = ~path5.indexOf(" ") ? " " + path5.split(" ").slice(1).join(" ") : "";
        const optionArguments = this.generateOptionArguments(command, completionsPath);
        const completionsCmd = this.generateCommandCompletionsCommand(command.getArguments(), completionsPath);
        return `  __${replaceSpecialChars(path5)}() {
    opts=(${[
            ...flags,
            ...childCommandNames
        ].join(" ")})
    ${completionsCmd}
    if [[ \${cur} == -* || \${COMP_CWORD} -eq ${index} ]] ; then
      return 0
    fi
    ${optionArguments}
  }`;
    }
    getFlags(command) {
        return command.getOptions(false).map((option)=>option.flags
        ).flat();
    }
    generateOptionArguments(command, completionsPath) {
        let opts = "";
        const options = command.getOptions(false);
        if (options.length) {
            opts += 'case "${prev}" in';
            for (const option of options){
                const flags = option.flags.map((flag)=>flag.trim()
                ).join("|");
                const completionsCmd = this.generateOptionCompletionsCommand(option.args, completionsPath, {
                    standalone: option.standalone
                });
                opts += `\n      ${flags}) ${completionsCmd} ;;`;
            }
            opts += "\n    esac";
        }
        return opts;
    }
    generateCommandCompletionsCommand(args, path6) {
        if (args.length) {
            return `_${replaceSpecialChars(this.cmd.getName())}_complete ${args[0].action}${path6}`;
        }
        return "";
    }
    generateOptionCompletionsCommand(args, path7, opts) {
        if (args.length) {
            return `opts=(); _${replaceSpecialChars(this.cmd.getName())}_complete ${args[0].action}${path7}`;
        }
        if (opts?.standalone) {
            return "opts=()";
        }
        return "";
    }
}
function replaceSpecialChars(str51) {
    return str51.replace(/[^a-zA-Z0-9]/g, "_");
}
class BashCompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        this.description(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            return `Generate shell completions for bash.

To enable bash completions for this program add following line to your ${dim(italic("~/.bashrc"))}:

    ${dim(italic(`source <(${baseCmd.getPath()} completions bash)`))}`;
        }).action(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            Deno.stdout.writeSync(new TextEncoder().encode(BashCompletionsGenerator.generate(baseCmd)));
        });
    }
}
class CompleteCommand extends Command {
    constructor(cmd1){
        super();
        this.description("Get completions for given action from given command.").arguments("<action:string> [command...:string]").action(async (_, action, commandNames)=>{
            let parent;
            const completeCommand = commandNames?.reduce((cmd, name67)=>{
                parent = cmd;
                const childCmd = cmd.getCommand(name67, false);
                if (!childCmd) {
                    throw new UnknownCompletionCommand(name67, cmd.getCommands());
                }
                return childCmd;
            }, cmd1 || this.getMainCommand()) ?? (cmd1 || this.getMainCommand());
            const completion = completeCommand.getCompletion(action);
            const result = await completion?.complete(completeCommand, parent) ?? [];
            if (result?.length) {
                Deno.stdout.writeSync(new TextEncoder().encode(result.join("\n")));
            }
        }).reset();
    }
}
class FishCompletionsGenerator {
    cmd;
    static generate(cmd) {
        return new FishCompletionsGenerator(cmd).generate();
    }
    constructor(cmd){
        this.cmd = cmd;
    }
    generate() {
        const path8 = this.cmd.getPath();
        const version4 = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
        return `#!/usr/bin/env fish
# fish completion support for ${path8}${version4}

function __fish_${replaceSpecialChars1(this.cmd.getName())}_using_command
  set cmds ${getCommandFnNames(this.cmd).join(" ")}
  set words (commandline -opc)
  set cmd "_"
  for word in $words
    switch $word
      case '-*'
        continue
      case '*'
        set word (string replace -r -a '\\W' '_' $word)
        set cmd_tmp $cmd"_$word"
        if contains $cmd_tmp $cmds
          set cmd $cmd_tmp
        end
    end
  end
  if [ "$cmd" = "$argv[1]" ]
    return 0
  end
  return 1
end

${this.generateCompletions(this.cmd).trim()}
`;
    }
    generateCompletions(command) {
        const parent = command.getParent();
        let result = ``;
        if (parent) {
            result += "\n" + this.complete(parent, {
                description: command.getShortDescription(),
                arguments: command.getName()
            });
        }
        const commandArgs = command.getArguments();
        if (commandArgs.length) {
            result += "\n" + this.complete(command, {
                arguments: commandArgs.length ? this.getCompletionCommand(commandArgs[0].action + " " + getCompletionsPath(command)) : undefined
            });
        }
        for (const option of command.getOptions(false)){
            result += "\n" + this.completeOption(command, option);
        }
        for (const subCommand of command.getCommands(false)){
            result += this.generateCompletions(subCommand);
        }
        return result;
    }
    completeOption(command, option) {
        const shortOption = option.flags.find((flag)=>flag.length === 2
        )?.replace(/^(-)+/, "");
        const longOption = option.flags.find((flag)=>flag.length > 2
        )?.replace(/^(-)+/, "");
        return this.complete(command, {
            description: option.description,
            shortOption: shortOption,
            longOption: longOption,
            required: true,
            standalone: option.standalone,
            arguments: option.args.length ? this.getCompletionCommand(option.args[0].action + " " + getCompletionsPath(command)) : undefined
        });
    }
    complete(command, options) {
        const cmd = [
            "complete"
        ];
        cmd.push("-c", this.cmd.getName());
        cmd.push("-n", `'__fish_${replaceSpecialChars1(this.cmd.getName())}_using_command __${replaceSpecialChars1(command.getPath())}'`);
        options.shortOption && cmd.push("-s", options.shortOption);
        options.longOption && cmd.push("-l", options.longOption);
        options.standalone && cmd.push("-x");
        cmd.push("-k");
        cmd.push("-f");
        if (options.arguments) {
            options.required && cmd.push("-r");
            cmd.push("-a", options.arguments);
        }
        options.description && cmd.push("-d", `'${options.description}'`);
        return cmd.join(" ");
    }
    getCompletionCommand(cmd) {
        return `'(${this.cmd.getName()} completions complete ${cmd.trim()})'`;
    }
}
function getCommandFnNames(cmd, cmds = []) {
    cmds.push(`__${replaceSpecialChars1(cmd.getPath())}`);
    cmd.getCommands(false).forEach((command)=>{
        getCommandFnNames(command, cmds);
    });
    return cmds;
}
function getCompletionsPath(command) {
    return command.getPath().split(" ").slice(1).join(" ");
}
function replaceSpecialChars1(str52) {
    return str52.replace(/[^a-zA-Z0-9]/g, "_");
}
class FishCompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        this.description(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            return `Generate shell completions for fish.

To enable fish completions for this program add following line to your ${dim(italic("~/.config/fish/config.fish"))}:

    ${dim(italic(`source (${baseCmd.getPath()} completions fish | psub)`))}`;
        }).action(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            Deno.stdout.writeSync(new TextEncoder().encode(FishCompletionsGenerator.generate(baseCmd)));
        });
    }
}
class ZshCompletionsGenerator {
    cmd;
    actions = new Map();
    static generate(cmd) {
        return new ZshCompletionsGenerator(cmd).generate();
    }
    constructor(cmd){
        this.cmd = cmd;
    }
    generate() {
        const path9 = this.cmd.getPath();
        const name68 = this.cmd.getName();
        const version5 = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
        return `#!/usr/bin/env zsh
# zsh completion support for ${path9}${version5}

autoload -U is-at-least

# shellcheck disable=SC2154
(( $+functions[__${replaceSpecialChars2(name68)}_complete] )) ||
function __${replaceSpecialChars2(name68)}_complete {
  local name="$1"; shift
  local action="$1"; shift
  integer ret=1
  local -a values
  local expl lines
  _tags "$name"
  while _tags; do
    if _requested "$name"; then
      # shellcheck disable=SC2034
      lines="$(${name68} completions complete "\${action}" "\${@}")"
      values=("\${(ps:\\n:)lines}")
      if (( \${#values[@]} )); then
        while _next_label "$name" expl "$action"; do
          compadd -S '' "\${expl[@]}" "\${values[@]}"
        done
      fi
    fi
  done
}

${this.generateCompletions(this.cmd).trim()}

# _${replaceSpecialChars2(path9)} "\${@}"

compdef _${replaceSpecialChars2(path9)} ${path9}

`;
    }
    generateCompletions(command, path10 = "") {
        if (!command.hasCommands(false) && !command.hasOptions(false) && !command.hasArguments()) {
            return "";
        }
        path10 = (path10 ? path10 + " " : "") + command.getName();
        return `# shellcheck disable=SC2154
(( $+functions[_${replaceSpecialChars2(path10)}] )) ||
function _${replaceSpecialChars2(path10)}() {` + (!command.getParent() ? `
  local state` : "") + this.generateCommandCompletions(command, path10) + this.generateSubCommandCompletions(command, path10) + this.generateArgumentCompletions(command, path10) + this.generateActions(command) + `\n}\n\n` + command.getCommands(false).filter((subCommand)=>subCommand !== command
        ).map((subCommand)=>this.generateCompletions(subCommand, path10)
        ).join("");
    }
    generateCommandCompletions(command, path11) {
        const commands9 = command.getCommands(false);
        let completions = commands9.map((subCommand)=>`'${subCommand.getName()}:${subCommand.getShortDescription()}'`
        ).join("\n      ");
        if (completions) {
            completions = `
    local -a commands
    # shellcheck disable=SC2034
    commands=(
      ${completions}
    )
    _describe 'command' commands`;
        }
        if (command.hasArguments()) {
            const completionsPath = path11.split(" ").slice(1).join(" ");
            const arg = command.getArguments()[0];
            const action = this.addAction(arg, completionsPath);
            if (action && command.getCompletion(arg.action)) {
                completions += `\n    __${replaceSpecialChars2(this.cmd.getName())}_complete ${action.arg.name} ${action.arg.action} ${action.cmd}`;
            }
        }
        if (completions) {
            completions = `\n\n  function _commands() {${completions}\n  }`;
        }
        return completions;
    }
    generateSubCommandCompletions(command1, path12) {
        if (command1.hasCommands(false)) {
            const actions = command1.getCommands(false).map((command)=>`${command.getName()}) _${replaceSpecialChars2(path12 + " " + command.getName())} ;;`
            ).join("\n      ");
            return `\n
  function _command_args() {
    case "\${words[1]}" in\n      ${actions}\n    esac
  }`;
        }
        return "";
    }
    generateArgumentCompletions(command, path13) {
        this.actions.clear();
        const options = this.generateOptions(command, path13);
        let argIndex = 0;
        let argsCommand = "\n\n  _arguments -w -s -S -C";
        if (command.hasOptions()) {
            argsCommand += ` \\\n    ${options.join(" \\\n    ")}`;
        }
        if (command.hasCommands(false) || command.getArguments().filter((arg)=>command.getCompletion(arg.action)
        ).length) {
            argsCommand += ` \\\n    '${++argIndex}: :_commands'`;
        }
        if (command.hasArguments() || command.hasCommands(false)) {
            const args = [];
            for (const arg1 of command.getArguments().slice(1)){
                const completionsPath = path13.split(" ").slice(1).join(" ");
                const action = this.addAction(arg1, completionsPath);
                args.push(`${++argIndex}${arg1.optionalValue ? "::" : ":"}${action.name}`);
            }
            argsCommand += args.map((arg)=>`\\\n    '${arg}'`
            ).join("");
            if (command.hasCommands(false)) {
                argsCommand += ` \\\n    '*:: :->command_args'`;
            }
        }
        return argsCommand;
    }
    generateOptions(command, path14) {
        const options = [];
        const cmdArgs = path14.split(" ");
        cmdArgs.shift();
        const completionsPath = cmdArgs.join(" ");
        const excludedFlags = command.getOptions(false).map((option)=>option.standalone ? option.flags : false
        ).flat().filter((flag)=>typeof flag === "string"
        );
        for (const option1 of command.getOptions(false)){
            options.push(this.generateOption(option1, completionsPath, excludedFlags));
        }
        return options;
    }
    generateOption(option, completionsPath, excludedOptions) {
        const flags = option.flags;
        let excludedFlags = option.conflicts?.length ? [
            ...excludedOptions,
            ...option.conflicts.map((opt)=>"--" + opt.replace(/^--/, "")
            ), 
        ] : excludedOptions;
        excludedFlags = option.collect ? excludedFlags : [
            ...excludedFlags,
            ...flags, 
        ];
        let args = "";
        for (const arg of option.args){
            const action = this.addAction(arg, completionsPath);
            if (arg.variadic) {
                args += `${arg.optionalValue ? "::" : ":"}${arg.name}:->${action.name}`;
            } else {
                args += `${arg.optionalValue ? "::" : ":"}${arg.name}:->${action.name}`;
            }
        }
        let description = option.description.trim().split("\n").shift();
        description = description.replace(/\[/g, "\\[").replace(/]/g, "\\]").replace(/"/g, '\\"').replace(/'/g, "'\"'\"'");
        const collect = option.collect ? "*" : "";
        if (option.standalone) {
            return `'(- *)'{${collect}${flags}}'[${description}]${args}'`;
        } else {
            const excluded = excludedFlags.length ? `'(${excludedFlags.join(" ")})'` : "";
            if (collect || flags.length > 1) {
                return `${excluded}{${collect}${flags}}'[${description}]${args}'`;
            } else {
                return `${excluded}${flags}'[${description}]${args}'`;
            }
        }
    }
    addAction(arg, cmd) {
        const action = `${arg.name}-${arg.action}`;
        if (!this.actions.has(action)) {
            this.actions.set(action, {
                arg: arg,
                label: `${arg.name}: ${arg.action}`,
                name: action,
                cmd
            });
        }
        return this.actions.get(action);
    }
    generateActions(command) {
        let actions = [];
        if (this.actions.size) {
            actions = Array.from(this.actions).map(([name69, action])=>`${name69}) __${replaceSpecialChars2(this.cmd.getName())}_complete ${action.arg.name} ${action.arg.action} ${action.cmd} ;;`
            );
        }
        if (command.hasCommands(false)) {
            actions.unshift(`command_args) _command_args ;;`);
        }
        if (actions.length) {
            return `\n\n  case "$state" in\n    ${actions.join("\n    ")}\n  esac`;
        }
        return "";
    }
}
function replaceSpecialChars2(str53) {
    return str53.replace(/[^a-zA-Z0-9]/g, "_");
}
class ZshCompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        this.description(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            return `Generate shell completions for zsh.

To enable zsh completions for this program add following line to your ${dim(italic("~/.zshrc"))}:

    ${dim(italic(`source <(${baseCmd.getPath()} completions zsh)`))}`;
        }).action(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            Deno.stdout.writeSync(new TextEncoder().encode(ZshCompletionsGenerator.generate(baseCmd)));
        });
    }
}
class CompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        this.description(()=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            return `Generate shell completions.

To enable shell completions for this program add the following line to your ${dim(italic("~/.bashrc"))} or similar:

    ${dim(italic(`source <(${baseCmd.getPath()} completions [shell])`))}

    For more information run ${dim(italic(`${baseCmd.getPath()} completions [shell] --help`))}
`;
        }).action(()=>this.showHelp()
        ).command("bash", new BashCompletionsCommand(this.#cmd)).command("fish", new FishCompletionsCommand(this.#cmd)).command("zsh", new ZshCompletionsCommand(this.#cmd)).command("complete", new CompleteCommand(this.#cmd).hidden()).reset();
    }
}
class CommandType extends StringType {
    complete(_cmd, parent) {
        return parent?.getCommands(false).map((cmd)=>cmd.getName()
        ) || [];
    }
}
class HelpCommand extends Command {
    constructor(cmd){
        super();
        this.type("command", new CommandType()).arguments("[command:command]").description("Show this help or the help of a sub-command.").action((_, name70)=>{
            if (!cmd) {
                cmd = name70 ? this.getGlobalParent()?.getBaseCommand(name70) : this.getGlobalParent();
            }
            if (!cmd) {
                const cmds = this.getGlobalParent()?.getCommands();
                throw new UnknownCommand(name70 ?? "", cmds ?? [], [
                    this.getName(),
                    ...this.getAliases(), 
                ]);
            }
            cmd.showHelp();
            Deno.exit(0);
        });
    }
}
class EnumType extends Type {
    allowedValues;
    constructor(values3){
        super();
        this.allowedValues = values3;
    }
    parse(type) {
        for (const value of this.allowedValues){
            if (value.toString() === type.value) {
                return value;
            }
        }
        throw new InvalidTypeError(type, this.allowedValues.slice());
    }
    values() {
        return this.allowedValues.slice();
    }
    complete() {
        return this.values();
    }
}
const osType = (()=>{
    const { Deno  } = globalThis;
    if (typeof Deno?.build?.os === "string") {
        return Deno.build.os;
    }
    const { navigator  } = globalThis;
    if (navigator?.appVersion?.includes?.("Win") ?? false) {
        return "windows";
    }
    return "linux";
})();
const isWindows = osType === "windows";
const CHAR_FORWARD_SLASH = 47;
function assertPath(path15) {
    if (typeof path15 !== "string") {
        throw new TypeError(`Path must be a string. Received ${JSON.stringify(path15)}`);
    }
}
function isPosixPathSeparator(code2) {
    return code2 === 47;
}
function isPathSeparator(code3) {
    return isPosixPathSeparator(code3) || code3 === 92;
}
function isWindowsDeviceRoot(code4) {
    return code4 >= 97 && code4 <= 122 || code4 >= 65 && code4 <= 90;
}
function normalizeString(path16, allowAboveRoot, separator, isPathSeparator1) {
    let res = "";
    let lastSegmentLength = 0;
    let lastSlash = -1;
    let dots = 0;
    let code5;
    for(let i8 = 0, len = path16.length; i8 <= len; ++i8){
        if (i8 < len) code5 = path16.charCodeAt(i8);
        else if (isPathSeparator1(code5)) break;
        else code5 = CHAR_FORWARD_SLASH;
        if (isPathSeparator1(code5)) {
            if (lastSlash === i8 - 1 || dots === 1) {} else if (lastSlash !== i8 - 1 && dots === 2) {
                if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) {
                    if (res.length > 2) {
                        const lastSlashIndex = res.lastIndexOf(separator);
                        if (lastSlashIndex === -1) {
                            res = "";
                            lastSegmentLength = 0;
                        } else {
                            res = res.slice(0, lastSlashIndex);
                            lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
                        }
                        lastSlash = i8;
                        dots = 0;
                        continue;
                    } else if (res.length === 2 || res.length === 1) {
                        res = "";
                        lastSegmentLength = 0;
                        lastSlash = i8;
                        dots = 0;
                        continue;
                    }
                }
                if (allowAboveRoot) {
                    if (res.length > 0) res += `${separator}..`;
                    else res = "..";
                    lastSegmentLength = 2;
                }
            } else {
                if (res.length > 0) res += separator + path16.slice(lastSlash + 1, i8);
                else res = path16.slice(lastSlash + 1, i8);
                lastSegmentLength = i8 - lastSlash - 1;
            }
            lastSlash = i8;
            dots = 0;
        } else if (code5 === 46 && dots !== -1) {
            ++dots;
        } else {
            dots = -1;
        }
    }
    return res;
}
function _format(sep3, pathObject) {
    const dir = pathObject.dir || pathObject.root;
    const base1 = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
    if (!dir) return base1;
    if (dir === pathObject.root) return dir + base1;
    return dir + sep3 + base1;
}
const WHITESPACE_ENCODINGS = {
    "\u0009": "%09",
    "\u000A": "%0A",
    "\u000B": "%0B",
    "\u000C": "%0C",
    "\u000D": "%0D",
    "\u0020": "%20"
};
function encodeWhitespace(string3) {
    return string3.replaceAll(/[\s]/g, (c)=>{
        return WHITESPACE_ENCODINGS[c] ?? c;
    });
}
class DenoStdInternalError extends Error {
    constructor(message){
        super(message);
        this.name = "DenoStdInternalError";
    }
}
function assert(expr, msg = "") {
    if (!expr) {
        throw new DenoStdInternalError(msg);
    }
}
const sep = "\\";
const delimiter = ";";
function resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for(let i9 = pathSegments.length - 1; i9 >= -1; i9--){
        let path17;
        const { Deno  } = globalThis;
        if (i9 >= 0) {
            path17 = pathSegments[i9];
        } else if (!resolvedDevice) {
            if (typeof Deno?.cwd !== "function") {
                throw new TypeError("Resolved a drive-letter-less path without a CWD.");
            }
            path17 = Deno.cwd();
        } else {
            if (typeof Deno?.env?.get !== "function" || typeof Deno?.cwd !== "function") {
                throw new TypeError("Resolved a relative path without a CWD.");
            }
            path17 = Deno.cwd();
            if (path17 === undefined || path17.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
                path17 = `${resolvedDevice}\\`;
            }
        }
        assertPath(path17);
        const len = path17.length;
        if (len === 0) continue;
        let rootEnd = 0;
        let device = "";
        let isAbsolute1 = false;
        const code6 = path17.charCodeAt(0);
        if (len > 1) {
            if (isPathSeparator(code6)) {
                isAbsolute1 = true;
                if (isPathSeparator(path17.charCodeAt(1))) {
                    let j = 2;
                    let last = j;
                    for(; j < len; ++j){
                        if (isPathSeparator(path17.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        const firstPart = path17.slice(last, j);
                        last = j;
                        for(; j < len; ++j){
                            if (!isPathSeparator(path17.charCodeAt(j))) break;
                        }
                        if (j < len && j !== last) {
                            last = j;
                            for(; j < len; ++j){
                                if (isPathSeparator(path17.charCodeAt(j))) break;
                            }
                            if (j === len) {
                                device = `\\\\${firstPart}\\${path17.slice(last)}`;
                                rootEnd = j;
                            } else if (j !== last) {
                                device = `\\\\${firstPart}\\${path17.slice(last, j)}`;
                                rootEnd = j;
                            }
                        }
                    }
                } else {
                    rootEnd = 1;
                }
            } else if (isWindowsDeviceRoot(code6)) {
                if (path17.charCodeAt(1) === 58) {
                    device = path17.slice(0, 2);
                    rootEnd = 2;
                    if (len > 2) {
                        if (isPathSeparator(path17.charCodeAt(2))) {
                            isAbsolute1 = true;
                            rootEnd = 3;
                        }
                    }
                }
            }
        } else if (isPathSeparator(code6)) {
            rootEnd = 1;
            isAbsolute1 = true;
        }
        if (device.length > 0 && resolvedDevice.length > 0 && device.toLowerCase() !== resolvedDevice.toLowerCase()) {
            continue;
        }
        if (resolvedDevice.length === 0 && device.length > 0) {
            resolvedDevice = device;
        }
        if (!resolvedAbsolute) {
            resolvedTail = `${path17.slice(rootEnd)}\\${resolvedTail}`;
            resolvedAbsolute = isAbsolute1;
        }
        if (resolvedAbsolute && resolvedDevice.length > 0) break;
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
function normalize1(path18) {
    assertPath(path18);
    const len = path18.length;
    if (len === 0) return ".";
    let rootEnd = 0;
    let device;
    let isAbsolute2 = false;
    const code7 = path18.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator(code7)) {
            isAbsolute2 = true;
            if (isPathSeparator(path18.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator(path18.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    const firstPart = path18.slice(last, j);
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator(path18.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator(path18.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            return `\\\\${firstPart}\\${path18.slice(last)}\\`;
                        } else if (j !== last) {
                            device = `\\\\${firstPart}\\${path18.slice(last, j)}`;
                            rootEnd = j;
                        }
                    }
                }
            } else {
                rootEnd = 1;
            }
        } else if (isWindowsDeviceRoot(code7)) {
            if (path18.charCodeAt(1) === 58) {
                device = path18.slice(0, 2);
                rootEnd = 2;
                if (len > 2) {
                    if (isPathSeparator(path18.charCodeAt(2))) {
                        isAbsolute2 = true;
                        rootEnd = 3;
                    }
                }
            }
        }
    } else if (isPathSeparator(code7)) {
        return "\\";
    }
    let tail;
    if (rootEnd < len) {
        tail = normalizeString(path18.slice(rootEnd), !isAbsolute2, "\\", isPathSeparator);
    } else {
        tail = "";
    }
    if (tail.length === 0 && !isAbsolute2) tail = ".";
    if (tail.length > 0 && isPathSeparator(path18.charCodeAt(len - 1))) {
        tail += "\\";
    }
    if (device === undefined) {
        if (isAbsolute2) {
            if (tail.length > 0) return `\\${tail}`;
            else return "\\";
        } else if (tail.length > 0) {
            return tail;
        } else {
            return "";
        }
    } else if (isAbsolute2) {
        if (tail.length > 0) return `${device}\\${tail}`;
        else return `${device}\\`;
    } else if (tail.length > 0) {
        return device + tail;
    } else {
        return device;
    }
}
function isAbsolute(path19) {
    assertPath(path19);
    const len = path19.length;
    if (len === 0) return false;
    const code8 = path19.charCodeAt(0);
    if (isPathSeparator(code8)) {
        return true;
    } else if (isWindowsDeviceRoot(code8)) {
        if (len > 2 && path19.charCodeAt(1) === 58) {
            if (isPathSeparator(path19.charCodeAt(2))) return true;
        }
    }
    return false;
}
function join(...paths) {
    const pathsCount = paths.length;
    if (pathsCount === 0) return ".";
    let joined;
    let firstPart = null;
    for(let i10 = 0; i10 < pathsCount; ++i10){
        const path20 = paths[i10];
        assertPath(path20);
        if (path20.length > 0) {
            if (joined === undefined) joined = firstPart = path20;
            else joined += `\\${path20}`;
        }
    }
    if (joined === undefined) return ".";
    let needsReplace = true;
    let slashCount = 0;
    assert(firstPart != null);
    if (isPathSeparator(firstPart.charCodeAt(0))) {
        ++slashCount;
        const firstLen = firstPart.length;
        if (firstLen > 1) {
            if (isPathSeparator(firstPart.charCodeAt(1))) {
                ++slashCount;
                if (firstLen > 2) {
                    if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount;
                    else {
                        needsReplace = false;
                    }
                }
            }
        }
    }
    if (needsReplace) {
        for(; slashCount < joined.length; ++slashCount){
            if (!isPathSeparator(joined.charCodeAt(slashCount))) break;
        }
        if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`;
    }
    return normalize1(joined);
}
function relative(from, to) {
    assertPath(from);
    assertPath(to);
    if (from === to) return "";
    const fromOrig = resolve(from);
    const toOrig = resolve(to);
    if (fromOrig === toOrig) return "";
    from = fromOrig.toLowerCase();
    to = toOrig.toLowerCase();
    if (from === to) return "";
    let fromStart = 0;
    let fromEnd = from.length;
    for(; fromStart < fromEnd; ++fromStart){
        if (from.charCodeAt(fromStart) !== 92) break;
    }
    for(; fromEnd - 1 > fromStart; --fromEnd){
        if (from.charCodeAt(fromEnd - 1) !== 92) break;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 0;
    let toEnd = to.length;
    for(; toStart < toEnd; ++toStart){
        if (to.charCodeAt(toStart) !== 92) break;
    }
    for(; toEnd - 1 > toStart; --toEnd){
        if (to.charCodeAt(toEnd - 1) !== 92) break;
    }
    const toLen = toEnd - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i11 = 0;
    for(; i11 <= length; ++i11){
        if (i11 === length) {
            if (toLen > length) {
                if (to.charCodeAt(toStart + i11) === 92) {
                    return toOrig.slice(toStart + i11 + 1);
                } else if (i11 === 2) {
                    return toOrig.slice(toStart + i11);
                }
            }
            if (fromLen > length) {
                if (from.charCodeAt(fromStart + i11) === 92) {
                    lastCommonSep = i11;
                } else if (i11 === 2) {
                    lastCommonSep = 3;
                }
            }
            break;
        }
        const fromCode = from.charCodeAt(fromStart + i11);
        const toCode = to.charCodeAt(toStart + i11);
        if (fromCode !== toCode) break;
        else if (fromCode === 92) lastCommonSep = i11;
    }
    if (i11 !== length && lastCommonSep === -1) {
        return toOrig;
    }
    let out = "";
    if (lastCommonSep === -1) lastCommonSep = 0;
    for(i11 = fromStart + lastCommonSep + 1; i11 <= fromEnd; ++i11){
        if (i11 === fromEnd || from.charCodeAt(i11) === 92) {
            if (out.length === 0) out += "..";
            else out += "\\..";
        }
    }
    if (out.length > 0) {
        return out + toOrig.slice(toStart + lastCommonSep, toEnd);
    } else {
        toStart += lastCommonSep;
        if (toOrig.charCodeAt(toStart) === 92) ++toStart;
        return toOrig.slice(toStart, toEnd);
    }
}
function toNamespacedPath(path21) {
    if (typeof path21 !== "string") return path21;
    if (path21.length === 0) return "";
    const resolvedPath = resolve(path21);
    if (resolvedPath.length >= 3) {
        if (resolvedPath.charCodeAt(0) === 92) {
            if (resolvedPath.charCodeAt(1) === 92) {
                const code9 = resolvedPath.charCodeAt(2);
                if (code9 !== 63 && code9 !== 46) {
                    return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
                }
            }
        } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) {
            if (resolvedPath.charCodeAt(1) === 58 && resolvedPath.charCodeAt(2) === 92) {
                return `\\\\?\\${resolvedPath}`;
            }
        }
    }
    return path21;
}
function dirname(path22) {
    assertPath(path22);
    const len = path22.length;
    if (len === 0) return ".";
    let rootEnd = -1;
    let end = -1;
    let matchedSlash = true;
    let offset = 0;
    const code10 = path22.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator(code10)) {
            rootEnd = offset = 1;
            if (isPathSeparator(path22.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator(path22.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator(path22.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator(path22.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            return path22;
                        }
                        if (j !== last) {
                            rootEnd = offset = j + 1;
                        }
                    }
                }
            }
        } else if (isWindowsDeviceRoot(code10)) {
            if (path22.charCodeAt(1) === 58) {
                rootEnd = offset = 2;
                if (len > 2) {
                    if (isPathSeparator(path22.charCodeAt(2))) rootEnd = offset = 3;
                }
            }
        }
    } else if (isPathSeparator(code10)) {
        return path22;
    }
    for(let i12 = len - 1; i12 >= offset; --i12){
        if (isPathSeparator(path22.charCodeAt(i12))) {
            if (!matchedSlash) {
                end = i12;
                break;
            }
        } else {
            matchedSlash = false;
        }
    }
    if (end === -1) {
        if (rootEnd === -1) return ".";
        else end = rootEnd;
    }
    return path22.slice(0, end);
}
function basename(path23, ext = "") {
    if (ext !== undefined && typeof ext !== "string") {
        throw new TypeError('"ext" argument must be a string');
    }
    assertPath(path23);
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i13;
    if (path23.length >= 2) {
        const drive = path23.charCodeAt(0);
        if (isWindowsDeviceRoot(drive)) {
            if (path23.charCodeAt(1) === 58) start = 2;
        }
    }
    if (ext !== undefined && ext.length > 0 && ext.length <= path23.length) {
        if (ext.length === path23.length && ext === path23) return "";
        let extIdx = ext.length - 1;
        let firstNonSlashEnd = -1;
        for(i13 = path23.length - 1; i13 >= start; --i13){
            const code11 = path23.charCodeAt(i13);
            if (isPathSeparator(code11)) {
                if (!matchedSlash) {
                    start = i13 + 1;
                    break;
                }
            } else {
                if (firstNonSlashEnd === -1) {
                    matchedSlash = false;
                    firstNonSlashEnd = i13 + 1;
                }
                if (extIdx >= 0) {
                    if (code11 === ext.charCodeAt(extIdx)) {
                        if (--extIdx === -1) {
                            end = i13;
                        }
                    } else {
                        extIdx = -1;
                        end = firstNonSlashEnd;
                    }
                }
            }
        }
        if (start === end) end = firstNonSlashEnd;
        else if (end === -1) end = path23.length;
        return path23.slice(start, end);
    } else {
        for(i13 = path23.length - 1; i13 >= start; --i13){
            if (isPathSeparator(path23.charCodeAt(i13))) {
                if (!matchedSlash) {
                    start = i13 + 1;
                    break;
                }
            } else if (end === -1) {
                matchedSlash = false;
                end = i13 + 1;
            }
        }
        if (end === -1) return "";
        return path23.slice(start, end);
    }
}
function extname(path24) {
    assertPath(path24);
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path24.length >= 2 && path24.charCodeAt(1) === 58 && isWindowsDeviceRoot(path24.charCodeAt(0))) {
        start = startPart = 2;
    }
    for(let i14 = path24.length - 1; i14 >= start; --i14){
        const code12 = path24.charCodeAt(i14);
        if (isPathSeparator(code12)) {
            if (!matchedSlash) {
                startPart = i14 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i14 + 1;
        }
        if (code12 === 46) {
            if (startDot === -1) startDot = i14;
            else if (preDotState !== 1) preDotState = 1;
        } else if (startDot !== -1) {
            preDotState = -1;
        }
    }
    if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        return "";
    }
    return path24.slice(startDot, end);
}
function format(pathObject) {
    if (pathObject === null || typeof pathObject !== "object") {
        throw new TypeError(`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`);
    }
    return _format("\\", pathObject);
}
function parse(path25) {
    assertPath(path25);
    const ret = {
        root: "",
        dir: "",
        base: "",
        ext: "",
        name: ""
    };
    const len = path25.length;
    if (len === 0) return ret;
    let rootEnd = 0;
    let code13 = path25.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator(code13)) {
            rootEnd = 1;
            if (isPathSeparator(path25.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator(path25.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator(path25.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator(path25.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            rootEnd = j;
                        } else if (j !== last) {
                            rootEnd = j + 1;
                        }
                    }
                }
            }
        } else if (isWindowsDeviceRoot(code13)) {
            if (path25.charCodeAt(1) === 58) {
                rootEnd = 2;
                if (len > 2) {
                    if (isPathSeparator(path25.charCodeAt(2))) {
                        if (len === 3) {
                            ret.root = ret.dir = path25;
                            return ret;
                        }
                        rootEnd = 3;
                    }
                } else {
                    ret.root = ret.dir = path25;
                    return ret;
                }
            }
        }
    } else if (isPathSeparator(code13)) {
        ret.root = ret.dir = path25;
        return ret;
    }
    if (rootEnd > 0) ret.root = path25.slice(0, rootEnd);
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i15 = path25.length - 1;
    let preDotState = 0;
    for(; i15 >= rootEnd; --i15){
        code13 = path25.charCodeAt(i15);
        if (isPathSeparator(code13)) {
            if (!matchedSlash) {
                startPart = i15 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i15 + 1;
        }
        if (code13 === 46) {
            if (startDot === -1) startDot = i15;
            else if (preDotState !== 1) preDotState = 1;
        } else if (startDot !== -1) {
            preDotState = -1;
        }
    }
    if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        if (end !== -1) {
            ret.base = ret.name = path25.slice(startPart, end);
        }
    } else {
        ret.name = path25.slice(startPart, startDot);
        ret.base = path25.slice(startPart, end);
        ret.ext = path25.slice(startDot, end);
    }
    if (startPart > 0 && startPart !== rootEnd) {
        ret.dir = path25.slice(0, startPart - 1);
    } else ret.dir = ret.root;
    return ret;
}
function fromFileUrl(url) {
    url = url instanceof URL ? url : new URL(url);
    if (url.protocol != "file:") {
        throw new TypeError("Must be a file URL.");
    }
    let path26 = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
    if (url.hostname != "") {
        path26 = `\\\\${url.hostname}${path26}`;
    }
    return path26;
}
function toFileUrl(path27) {
    if (!isAbsolute(path27)) {
        throw new TypeError("Must be an absolute path.");
    }
    const [, hostname, pathname] = path27.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/);
    const url = new URL("file:///");
    url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25"));
    if (hostname != null && hostname != "localhost") {
        url.hostname = hostname;
        if (!url.hostname) {
            throw new TypeError("Invalid hostname.");
        }
    }
    return url;
}
const mod1 = {
    sep: sep,
    delimiter: delimiter,
    resolve: resolve,
    normalize: normalize1,
    isAbsolute: isAbsolute,
    join: join,
    relative: relative,
    toNamespacedPath: toNamespacedPath,
    dirname: dirname,
    basename: basename,
    extname: extname,
    format: format,
    parse: parse,
    fromFileUrl: fromFileUrl,
    toFileUrl: toFileUrl
};
const sep1 = "/";
const delimiter1 = ":";
function resolve1(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for(let i16 = pathSegments.length - 1; i16 >= -1 && !resolvedAbsolute; i16--){
        let path28;
        if (i16 >= 0) path28 = pathSegments[i16];
        else {
            const { Deno  } = globalThis;
            if (typeof Deno?.cwd !== "function") {
                throw new TypeError("Resolved a relative path without a CWD.");
            }
            path28 = Deno.cwd();
        }
        assertPath(path28);
        if (path28.length === 0) {
            continue;
        }
        resolvedPath = `${path28}/${resolvedPath}`;
        resolvedAbsolute = path28.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
        if (resolvedPath.length > 0) return `/${resolvedPath}`;
        else return "/";
    } else if (resolvedPath.length > 0) return resolvedPath;
    else return ".";
}
function normalize2(path29) {
    assertPath(path29);
    if (path29.length === 0) return ".";
    const isAbsolute1 = path29.charCodeAt(0) === 47;
    const trailingSeparator = path29.charCodeAt(path29.length - 1) === 47;
    path29 = normalizeString(path29, !isAbsolute1, "/", isPosixPathSeparator);
    if (path29.length === 0 && !isAbsolute1) path29 = ".";
    if (path29.length > 0 && trailingSeparator) path29 += "/";
    if (isAbsolute1) return `/${path29}`;
    return path29;
}
function isAbsolute1(path30) {
    assertPath(path30);
    return path30.length > 0 && path30.charCodeAt(0) === 47;
}
function join1(...paths) {
    if (paths.length === 0) return ".";
    let joined;
    for(let i17 = 0, len = paths.length; i17 < len; ++i17){
        const path31 = paths[i17];
        assertPath(path31);
        if (path31.length > 0) {
            if (!joined) joined = path31;
            else joined += `/${path31}`;
        }
    }
    if (!joined) return ".";
    return normalize2(joined);
}
function relative1(from, to) {
    assertPath(from);
    assertPath(to);
    if (from === to) return "";
    from = resolve1(from);
    to = resolve1(to);
    if (from === to) return "";
    let fromStart = 1;
    const fromEnd = from.length;
    for(; fromStart < fromEnd; ++fromStart){
        if (from.charCodeAt(fromStart) !== 47) break;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 1;
    const toEnd = to.length;
    for(; toStart < toEnd; ++toStart){
        if (to.charCodeAt(toStart) !== 47) break;
    }
    const toLen = toEnd - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i18 = 0;
    for(; i18 <= length; ++i18){
        if (i18 === length) {
            if (toLen > length) {
                if (to.charCodeAt(toStart + i18) === 47) {
                    return to.slice(toStart + i18 + 1);
                } else if (i18 === 0) {
                    return to.slice(toStart + i18);
                }
            } else if (fromLen > length) {
                if (from.charCodeAt(fromStart + i18) === 47) {
                    lastCommonSep = i18;
                } else if (i18 === 0) {
                    lastCommonSep = 0;
                }
            }
            break;
        }
        const fromCode = from.charCodeAt(fromStart + i18);
        const toCode = to.charCodeAt(toStart + i18);
        if (fromCode !== toCode) break;
        else if (fromCode === 47) lastCommonSep = i18;
    }
    let out = "";
    for(i18 = fromStart + lastCommonSep + 1; i18 <= fromEnd; ++i18){
        if (i18 === fromEnd || from.charCodeAt(i18) === 47) {
            if (out.length === 0) out += "..";
            else out += "/..";
        }
    }
    if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
    else {
        toStart += lastCommonSep;
        if (to.charCodeAt(toStart) === 47) ++toStart;
        return to.slice(toStart);
    }
}
function toNamespacedPath1(path32) {
    return path32;
}
function dirname1(path33) {
    assertPath(path33);
    if (path33.length === 0) return ".";
    const hasRoot = path33.charCodeAt(0) === 47;
    let end = -1;
    let matchedSlash = true;
    for(let i19 = path33.length - 1; i19 >= 1; --i19){
        if (path33.charCodeAt(i19) === 47) {
            if (!matchedSlash) {
                end = i19;
                break;
            }
        } else {
            matchedSlash = false;
        }
    }
    if (end === -1) return hasRoot ? "/" : ".";
    if (hasRoot && end === 1) return "//";
    return path33.slice(0, end);
}
function basename1(path34, ext = "") {
    if (ext !== undefined && typeof ext !== "string") {
        throw new TypeError('"ext" argument must be a string');
    }
    assertPath(path34);
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i20;
    if (ext !== undefined && ext.length > 0 && ext.length <= path34.length) {
        if (ext.length === path34.length && ext === path34) return "";
        let extIdx = ext.length - 1;
        let firstNonSlashEnd = -1;
        for(i20 = path34.length - 1; i20 >= 0; --i20){
            const code14 = path34.charCodeAt(i20);
            if (code14 === 47) {
                if (!matchedSlash) {
                    start = i20 + 1;
                    break;
                }
            } else {
                if (firstNonSlashEnd === -1) {
                    matchedSlash = false;
                    firstNonSlashEnd = i20 + 1;
                }
                if (extIdx >= 0) {
                    if (code14 === ext.charCodeAt(extIdx)) {
                        if (--extIdx === -1) {
                            end = i20;
                        }
                    } else {
                        extIdx = -1;
                        end = firstNonSlashEnd;
                    }
                }
            }
        }
        if (start === end) end = firstNonSlashEnd;
        else if (end === -1) end = path34.length;
        return path34.slice(start, end);
    } else {
        for(i20 = path34.length - 1; i20 >= 0; --i20){
            if (path34.charCodeAt(i20) === 47) {
                if (!matchedSlash) {
                    start = i20 + 1;
                    break;
                }
            } else if (end === -1) {
                matchedSlash = false;
                end = i20 + 1;
            }
        }
        if (end === -1) return "";
        return path34.slice(start, end);
    }
}
function extname1(path35) {
    assertPath(path35);
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for(let i21 = path35.length - 1; i21 >= 0; --i21){
        const code15 = path35.charCodeAt(i21);
        if (code15 === 47) {
            if (!matchedSlash) {
                startPart = i21 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i21 + 1;
        }
        if (code15 === 46) {
            if (startDot === -1) startDot = i21;
            else if (preDotState !== 1) preDotState = 1;
        } else if (startDot !== -1) {
            preDotState = -1;
        }
    }
    if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        return "";
    }
    return path35.slice(startDot, end);
}
function format1(pathObject) {
    if (pathObject === null || typeof pathObject !== "object") {
        throw new TypeError(`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`);
    }
    return _format("/", pathObject);
}
function parse1(path36) {
    assertPath(path36);
    const ret = {
        root: "",
        dir: "",
        base: "",
        ext: "",
        name: ""
    };
    if (path36.length === 0) return ret;
    const isAbsolute2 = path36.charCodeAt(0) === 47;
    let start;
    if (isAbsolute2) {
        ret.root = "/";
        start = 1;
    } else {
        start = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let i22 = path36.length - 1;
    let preDotState = 0;
    for(; i22 >= start; --i22){
        const code16 = path36.charCodeAt(i22);
        if (code16 === 47) {
            if (!matchedSlash) {
                startPart = i22 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i22 + 1;
        }
        if (code16 === 46) {
            if (startDot === -1) startDot = i22;
            else if (preDotState !== 1) preDotState = 1;
        } else if (startDot !== -1) {
            preDotState = -1;
        }
    }
    if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        if (end !== -1) {
            if (startPart === 0 && isAbsolute2) {
                ret.base = ret.name = path36.slice(1, end);
            } else {
                ret.base = ret.name = path36.slice(startPart, end);
            }
        }
    } else {
        if (startPart === 0 && isAbsolute2) {
            ret.name = path36.slice(1, startDot);
            ret.base = path36.slice(1, end);
        } else {
            ret.name = path36.slice(startPart, startDot);
            ret.base = path36.slice(startPart, end);
        }
        ret.ext = path36.slice(startDot, end);
    }
    if (startPart > 0) ret.dir = path36.slice(0, startPart - 1);
    else if (isAbsolute2) ret.dir = "/";
    return ret;
}
function fromFileUrl1(url) {
    url = url instanceof URL ? url : new URL(url);
    if (url.protocol != "file:") {
        throw new TypeError("Must be a file URL.");
    }
    return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"));
}
function toFileUrl1(path37) {
    if (!isAbsolute1(path37)) {
        throw new TypeError("Must be an absolute path.");
    }
    const url = new URL("file:///");
    url.pathname = encodeWhitespace(path37.replace(/%/g, "%25").replace(/\\/g, "%5C"));
    return url;
}
const mod2 = {
    sep: sep1,
    delimiter: delimiter1,
    resolve: resolve1,
    normalize: normalize2,
    isAbsolute: isAbsolute1,
    join: join1,
    relative: relative1,
    toNamespacedPath: toNamespacedPath1,
    dirname: dirname1,
    basename: basename1,
    extname: extname1,
    format: format1,
    parse: parse1,
    fromFileUrl: fromFileUrl1,
    toFileUrl: toFileUrl1
};
const SEP = isWindows ? "\\" : "/";
const SEP_PATTERN = isWindows ? /[\\/]+/ : /\/+/;
const path = isWindows ? mod1 : mod2;
const { join: join2 , normalize: normalize3  } = path;
const regExpEscapeChars = [
    "!",
    "$",
    "(",
    ")",
    "*",
    "+",
    ".",
    "=",
    "?",
    "[",
    "\\",
    "^",
    "{",
    "|", 
];
const rangeEscapeChars = [
    "-",
    "\\",
    "]"
];
function globToRegExp(glob, { extended =true , globstar: globstarOption = true , os =osType , caseInsensitive =false  } = {}) {
    if (glob == "") {
        return /(?!)/;
    }
    const sep4 = os == "windows" ? "(?:\\\\|/)+" : "/+";
    const sepMaybe = os == "windows" ? "(?:\\\\|/)*" : "/*";
    const seps = os == "windows" ? [
        "\\",
        "/"
    ] : [
        "/"
    ];
    const globstar = os == "windows" ? "(?:[^\\\\/]*(?:\\\\|/|$)+)*" : "(?:[^/]*(?:/|$)+)*";
    const wildcard = os == "windows" ? "[^\\\\/]*" : "[^/]*";
    const escapePrefix = os == "windows" ? "`" : "\\";
    let newLength = glob.length;
    for(; newLength > 1 && seps.includes(glob[newLength - 1]); newLength--);
    glob = glob.slice(0, newLength);
    let regExpString = "";
    for(let j = 0; j < glob.length;){
        let segment = "";
        const groupStack = [];
        let inRange = false;
        let inEscape = false;
        let endsWithSep = false;
        let i23 = j;
        for(; i23 < glob.length && !seps.includes(glob[i23]); i23++){
            if (inEscape) {
                inEscape = false;
                const escapeChars = inRange ? rangeEscapeChars : regExpEscapeChars;
                segment += escapeChars.includes(glob[i23]) ? `\\${glob[i23]}` : glob[i23];
                continue;
            }
            if (glob[i23] == escapePrefix) {
                inEscape = true;
                continue;
            }
            if (glob[i23] == "[") {
                if (!inRange) {
                    inRange = true;
                    segment += "[";
                    if (glob[i23 + 1] == "!") {
                        i23++;
                        segment += "^";
                    } else if (glob[i23 + 1] == "^") {
                        i23++;
                        segment += "\\^";
                    }
                    continue;
                } else if (glob[i23 + 1] == ":") {
                    let k = i23 + 1;
                    let value = "";
                    while(glob[k + 1] != null && glob[k + 1] != ":"){
                        value += glob[k + 1];
                        k++;
                    }
                    if (glob[k + 1] == ":" && glob[k + 2] == "]") {
                        i23 = k + 2;
                        if (value == "alnum") segment += "\\dA-Za-z";
                        else if (value == "alpha") segment += "A-Za-z";
                        else if (value == "ascii") segment += "\x00-\x7F";
                        else if (value == "blank") segment += "\t ";
                        else if (value == "cntrl") segment += "\x00-\x1F\x7F";
                        else if (value == "digit") segment += "\\d";
                        else if (value == "graph") segment += "\x21-\x7E";
                        else if (value == "lower") segment += "a-z";
                        else if (value == "print") segment += "\x20-\x7E";
                        else if (value == "punct") {
                            segment += "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_‘{|}~";
                        } else if (value == "space") segment += "\\s\v";
                        else if (value == "upper") segment += "A-Z";
                        else if (value == "word") segment += "\\w";
                        else if (value == "xdigit") segment += "\\dA-Fa-f";
                        continue;
                    }
                }
            }
            if (glob[i23] == "]" && inRange) {
                inRange = false;
                segment += "]";
                continue;
            }
            if (inRange) {
                if (glob[i23] == "\\") {
                    segment += `\\\\`;
                } else {
                    segment += glob[i23];
                }
                continue;
            }
            if (glob[i23] == ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
                segment += ")";
                const type = groupStack.pop();
                if (type == "!") {
                    segment += wildcard;
                } else if (type != "@") {
                    segment += type;
                }
                continue;
            }
            if (glob[i23] == "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i23] == "+" && extended && glob[i23 + 1] == "(") {
                i23++;
                groupStack.push("+");
                segment += "(?:";
                continue;
            }
            if (glob[i23] == "@" && extended && glob[i23 + 1] == "(") {
                i23++;
                groupStack.push("@");
                segment += "(?:";
                continue;
            }
            if (glob[i23] == "?") {
                if (extended && glob[i23 + 1] == "(") {
                    i23++;
                    groupStack.push("?");
                    segment += "(?:";
                } else {
                    segment += ".";
                }
                continue;
            }
            if (glob[i23] == "!" && extended && glob[i23 + 1] == "(") {
                i23++;
                groupStack.push("!");
                segment += "(?!";
                continue;
            }
            if (glob[i23] == "{") {
                groupStack.push("BRACE");
                segment += "(?:";
                continue;
            }
            if (glob[i23] == "}" && groupStack[groupStack.length - 1] == "BRACE") {
                groupStack.pop();
                segment += ")";
                continue;
            }
            if (glob[i23] == "," && groupStack[groupStack.length - 1] == "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i23] == "*") {
                if (extended && glob[i23 + 1] == "(") {
                    i23++;
                    groupStack.push("*");
                    segment += "(?:";
                } else {
                    const prevChar = glob[i23 - 1];
                    let numStars = 1;
                    while(glob[i23 + 1] == "*"){
                        i23++;
                        numStars++;
                    }
                    const nextChar = glob[i23 + 1];
                    if (globstarOption && numStars == 2 && [
                        ...seps,
                        undefined
                    ].includes(prevChar) && [
                        ...seps,
                        undefined
                    ].includes(nextChar)) {
                        segment += globstar;
                        endsWithSep = true;
                    } else {
                        segment += wildcard;
                    }
                }
                continue;
            }
            segment += regExpEscapeChars.includes(glob[i23]) ? `\\${glob[i23]}` : glob[i23];
        }
        if (groupStack.length > 0 || inRange || inEscape) {
            segment = "";
            for (const c of glob.slice(j, i23)){
                segment += regExpEscapeChars.includes(c) ? `\\${c}` : c;
                endsWithSep = false;
            }
        }
        regExpString += segment;
        if (!endsWithSep) {
            regExpString += i23 < glob.length ? sep4 : sepMaybe;
            endsWithSep = true;
        }
        while(seps.includes(glob[i23]))i23++;
        if (!(i23 > j)) {
            throw new Error("Assertion failure: i > j (potential infinite loop)");
        }
        j = i23;
    }
    regExpString = `^${regExpString}$`;
    return new RegExp(regExpString, caseInsensitive ? "i" : "");
}
function isGlob(str54) {
    const chars = {
        "{": "}",
        "(": ")",
        "[": "]"
    };
    const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
    if (str54 === "") {
        return false;
    }
    let match;
    while(match = regex.exec(str54)){
        if (match[2]) return true;
        let idx = match.index + match[0].length;
        const open = match[1];
        const close = open ? chars[open] : null;
        if (open && close) {
            const n = str54.indexOf(close, idx);
            if (n !== -1) {
                idx = n + 1;
            }
        }
        str54 = str54.slice(idx);
    }
    return false;
}
function normalizeGlob(glob, { globstar =false  } = {}) {
    if (glob.match(/\0/g)) {
        throw new Error(`Glob contains invalid characters: "${glob}"`);
    }
    if (!globstar) {
        return normalize3(glob);
    }
    const s = SEP_PATTERN.source;
    const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g");
    return normalize3(glob.replace(badParentPattern, "\0")).replace(/\0/g, "..");
}
function joinGlobs(globs, { extended =true , globstar =false  } = {}) {
    if (!globstar || globs.length == 0) {
        return join2(...globs);
    }
    if (globs.length === 0) return ".";
    let joined;
    for (const glob of globs){
        const path1 = glob;
        if (path1.length > 0) {
            if (!joined) joined = path1;
            else joined += `${SEP}${path1}`;
        }
    }
    if (!joined) return ".";
    return normalizeGlob(joined, {
        extended,
        globstar
    });
}
const path1 = isWindows ? mod1 : mod2;
const posix = mod2;
const { basename: basename2 , delimiter: delimiter2 , dirname: dirname2 , extname: extname2 , format: format2 , fromFileUrl: fromFileUrl2 , isAbsolute: isAbsolute2 , join: join3 , normalize: normalize4 , parse: parse2 , relative: relative2 , resolve: resolve2 , sep: sep2 , toFileUrl: toFileUrl2 , toNamespacedPath: toNamespacedPath2 ,  } = path1;
function _createWalkEntrySync(path38) {
    path38 = normalize4(path38);
    const name71 = basename2(path38);
    const info1 = Deno.statSync(path38);
    return {
        path: path38,
        name: name71,
        isFile: info1.isFile,
        isDirectory: info1.isDirectory,
        isSymlink: info1.isSymlink
    };
}
function include(path39, exts, match, skip) {
    if (exts && !exts.some((ext)=>path39.endsWith(ext)
    )) {
        return false;
    }
    if (match && !match.some((pattern)=>!!path39.match(pattern)
    )) {
        return false;
    }
    if (skip && skip.some((pattern)=>!!path39.match(pattern)
    )) {
        return false;
    }
    return true;
}
function wrapErrorWithRootPath(err, root1) {
    if (err instanceof Error && "root" in err) return err;
    const e = new Error();
    e.root = root1;
    e.message = err instanceof Error ? `${err.message} for path "${root1}"` : `[non-error thrown] for path "${root1}"`;
    e.stack = err instanceof Error ? err.stack : undefined;
    e.cause = err instanceof Error ? err.cause : undefined;
    return e;
}
function* walkSync(root2, { maxDepth =Infinity , includeFiles =true , includeDirs =true , followSymlinks =false , exts =undefined , match =undefined , skip =undefined  } = {}) {
    if (maxDepth < 0) {
        return;
    }
    if (includeDirs && include(root2, exts, match, skip)) {
        yield _createWalkEntrySync(root2);
    }
    if (maxDepth < 1 || !include(root2, undefined, undefined, skip)) {
        return;
    }
    let entries;
    try {
        entries = Deno.readDirSync(root2);
    } catch (err) {
        throw wrapErrorWithRootPath(err, normalize4(root2));
    }
    for (const entry of entries){
        assert(entry.name != null);
        let path40 = join3(root2, entry.name);
        let { isSymlink , isDirectory  } = entry;
        if (isSymlink) {
            if (!followSymlinks) continue;
            path40 = Deno.realPathSync(path40);
            ({ isSymlink , isDirectory  } = Deno.lstatSync(path40));
        }
        if (isSymlink || isDirectory) {
            yield* walkSync(path40, {
                maxDepth: maxDepth - 1,
                includeFiles,
                includeDirs,
                followSymlinks,
                exts,
                match,
                skip
            });
        } else if (includeFiles && include(path40, exts, match, skip)) {
            yield {
                path: path40,
                ...entry
            };
        }
    }
}
function split(path41) {
    const s = SEP_PATTERN.source;
    const segments = path41.replace(new RegExp(`^${s}|${s}$`, "g"), "").split(SEP_PATTERN);
    const isAbsolute_ = isAbsolute2(path41);
    return {
        segments,
        isAbsolute: isAbsolute_,
        hasTrailingSep: !!path41.match(new RegExp(`${s}$`)),
        winRoot: isWindows && isAbsolute_ ? segments.shift() : undefined
    };
}
function throwUnlessNotFound(error5) {
    if (!(error5 instanceof Deno.errors.NotFound)) {
        throw error5;
    }
}
function comparePath(a, b) {
    if (a.path < b.path) return -1;
    if (a.path > b.path) return 1;
    return 0;
}
function* expandGlobSync(glob, { root: root3 = Deno.cwd() , exclude =[] , includeDirs =true , extended =true , globstar =false , caseInsensitive  } = {}) {
    const globOptions = {
        extended,
        globstar,
        caseInsensitive
    };
    const absRoot = resolve2(root3);
    const resolveFromRoot = (path42)=>resolve2(absRoot, path42)
    ;
    const excludePatterns = exclude.map(resolveFromRoot).map((s)=>globToRegExp(s, globOptions)
    );
    const shouldInclude1 = (path43)=>!excludePatterns.some((p)=>!!path43.match(p)
        )
    ;
    const { segments , isAbsolute: isGlobAbsolute , hasTrailingSep , winRoot  } = split(glob);
    let fixedRoot = isGlobAbsolute ? winRoot != undefined ? winRoot : "/" : absRoot;
    while(segments.length > 0 && !isGlob(segments[0])){
        const seg = segments.shift();
        assert(seg != null);
        fixedRoot = joinGlobs([
            fixedRoot,
            seg
        ], globOptions);
    }
    let fixedRootInfo;
    try {
        fixedRootInfo = _createWalkEntrySync(fixedRoot);
    } catch (error2) {
        return throwUnlessNotFound(error2);
    }
    function* advanceMatch(walkInfo, globSegment) {
        if (!walkInfo.isDirectory) {
            return;
        } else if (globSegment == "..") {
            const parentPath = joinGlobs([
                walkInfo.path,
                ".."
            ], globOptions);
            try {
                if (shouldInclude1(parentPath)) {
                    return yield _createWalkEntrySync(parentPath);
                }
            } catch (error6) {
                throwUnlessNotFound(error6);
            }
            return;
        } else if (globSegment == "**") {
            return yield* walkSync(walkInfo.path, {
                skip: excludePatterns
            });
        }
        const globPattern = globToRegExp(globSegment, globOptions);
        for (const walkEntry of walkSync(walkInfo.path, {
            maxDepth: 1,
            skip: excludePatterns
        })){
            if (walkEntry.path != walkInfo.path && walkEntry.name.match(globPattern)) {
                yield walkEntry;
            }
        }
    }
    let currentMatches = [
        fixedRootInfo
    ];
    for (const segment of segments){
        const nextMatchMap = new Map();
        for (const currentMatch of currentMatches){
            for (const nextMatch of advanceMatch(currentMatch, segment)){
                nextMatchMap.set(nextMatch.path, nextMatch);
            }
        }
        currentMatches = [
            ...nextMatchMap.values()
        ].sort(comparePath);
    }
    if (hasTrailingSep) {
        currentMatches = currentMatches.filter((entry)=>entry.isDirectory
        );
    }
    if (!includeDirs) {
        currentMatches = currentMatches.filter((entry)=>!entry.isDirectory
        );
    }
    yield* currentMatches;
}
var LogLevels;
(function(LogLevels1) {
    LogLevels1[LogLevels1["NOTSET"] = 0] = "NOTSET";
    LogLevels1[LogLevels1["DEBUG"] = 10] = "DEBUG";
    LogLevels1[LogLevels1["INFO"] = 20] = "INFO";
    LogLevels1[LogLevels1["WARNING"] = 30] = "WARNING";
    LogLevels1[LogLevels1["ERROR"] = 40] = "ERROR";
    LogLevels1[LogLevels1["CRITICAL"] = 50] = "CRITICAL";
})(LogLevels || (LogLevels = {}));
Object.keys(LogLevels).filter((key)=>isNaN(Number(key))
);
const byLevel = {
    [String(LogLevels.NOTSET)]: "NOTSET",
    [String(LogLevels.DEBUG)]: "DEBUG",
    [String(LogLevels.INFO)]: "INFO",
    [String(LogLevels.WARNING)]: "WARNING",
    [String(LogLevels.ERROR)]: "ERROR",
    [String(LogLevels.CRITICAL)]: "CRITICAL"
};
function getLevelByName(name72) {
    switch(name72){
        case "NOTSET":
            return LogLevels.NOTSET;
        case "DEBUG":
            return LogLevels.DEBUG;
        case "INFO":
            return LogLevels.INFO;
        case "WARNING":
            return LogLevels.WARNING;
        case "ERROR":
            return LogLevels.ERROR;
        case "CRITICAL":
            return LogLevels.CRITICAL;
        default:
            throw new Error(`no log level found for "${name72}"`);
    }
}
function getLevelName(level) {
    const levelName = byLevel[level];
    if (levelName) {
        return levelName;
    }
    throw new Error(`no level name found for level: ${level}`);
}
class LogRecord {
    msg;
    #args;
    #datetime;
    level;
    levelName;
    loggerName;
    constructor(options){
        this.msg = options.msg;
        this.#args = [
            ...options.args
        ];
        this.level = options.level;
        this.loggerName = options.loggerName;
        this.#datetime = new Date();
        this.levelName = getLevelName(options.level);
    }
    get args() {
        return [
            ...this.#args
        ];
    }
    get datetime() {
        return new Date(this.#datetime.getTime());
    }
}
class Logger {
    #level;
    #handlers;
    #loggerName;
    constructor(loggerName, levelName, options = {}){
        this.#loggerName = loggerName;
        this.#level = getLevelByName(levelName);
        this.#handlers = options.handlers || [];
    }
    get level() {
        return this.#level;
    }
    set level(level) {
        this.#level = level;
    }
    get levelName() {
        return getLevelName(this.#level);
    }
    set levelName(levelName) {
        this.#level = getLevelByName(levelName);
    }
    get loggerName() {
        return this.#loggerName;
    }
    set handlers(hndls) {
        this.#handlers = hndls;
    }
    get handlers() {
        return this.#handlers;
    }
    _log(level, msg, ...args) {
        if (this.level > level) {
            return msg instanceof Function ? undefined : msg;
        }
        let fnResult;
        let logMessage;
        if (msg instanceof Function) {
            fnResult = msg();
            logMessage = this.asString(fnResult);
        } else {
            logMessage = this.asString(msg);
        }
        const record = new LogRecord({
            msg: logMessage,
            args: args,
            level: level,
            loggerName: this.loggerName
        });
        this.#handlers.forEach((handler)=>{
            handler.handle(record);
        });
        return msg instanceof Function ? fnResult : msg;
    }
    asString(data1) {
        if (typeof data1 === "string") {
            return data1;
        } else if (data1 === null || typeof data1 === "number" || typeof data1 === "bigint" || typeof data1 === "boolean" || typeof data1 === "undefined" || typeof data1 === "symbol") {
            return String(data1);
        } else if (data1 instanceof Error) {
            return data1.stack;
        } else if (typeof data1 === "object") {
            return JSON.stringify(data1);
        }
        return "undefined";
    }
    debug(msg, ...args) {
        return this._log(LogLevels.DEBUG, msg, ...args);
    }
    info(msg, ...args) {
        return this._log(LogLevels.INFO, msg, ...args);
    }
    warning(msg, ...args) {
        return this._log(LogLevels.WARNING, msg, ...args);
    }
    error(msg, ...args) {
        return this._log(LogLevels.ERROR, msg, ...args);
    }
    critical(msg, ...args) {
        return this._log(LogLevels.CRITICAL, msg, ...args);
    }
}
async function exists(filePath) {
    try {
        await Deno.lstat(filePath);
        return true;
    } catch (err) {
        if (err instanceof Deno.errors.NotFound) {
            return false;
        }
        throw err;
    }
}
function existsSync(filePath) {
    try {
        Deno.lstatSync(filePath);
        return true;
    } catch (err) {
        if (err instanceof Deno.errors.NotFound) {
            return false;
        }
        throw err;
    }
}
function concat(...buf) {
    let length = 0;
    for (const b of buf){
        length += b.length;
    }
    const output = new Uint8Array(length);
    let index = 0;
    for (const b1 of buf){
        output.set(b1, index);
        index += b1.length;
    }
    return output;
}
function copy(src, dst, off = 0) {
    off = Math.max(0, Math.min(off, dst.byteLength));
    const dstBytesAvailable = dst.byteLength - off;
    if (src.byteLength > dstBytesAvailable) {
        src = src.subarray(0, dstBytesAvailable);
    }
    dst.set(src, off);
    return src.byteLength;
}
const MIN_READ = 32 * 1024;
const MAX_SIZE = 2 ** 32 - 2;
class Buffer {
    #buf;
    #off = 0;
    constructor(ab){
        this.#buf = ab === undefined ? new Uint8Array(0) : new Uint8Array(ab);
    }
    bytes(options = {
        copy: true
    }) {
        if (options.copy === false) return this.#buf.subarray(this.#off);
        return this.#buf.slice(this.#off);
    }
    empty() {
        return this.#buf.byteLength <= this.#off;
    }
    get length() {
        return this.#buf.byteLength - this.#off;
    }
    get capacity() {
        return this.#buf.buffer.byteLength;
    }
    truncate(n) {
        if (n === 0) {
            this.reset();
            return;
        }
        if (n < 0 || n > this.length) {
            throw Error("bytes.Buffer: truncation out of range");
        }
        this.#reslice(this.#off + n);
    }
    reset() {
        this.#reslice(0);
        this.#off = 0;
    }
     #tryGrowByReslice(n) {
        const l = this.#buf.byteLength;
        if (n <= this.capacity - l) {
            this.#reslice(l + n);
            return l;
        }
        return -1;
    }
     #reslice(len) {
        assert(len <= this.#buf.buffer.byteLength);
        this.#buf = new Uint8Array(this.#buf.buffer, 0, len);
    }
    readSync(p) {
        if (this.empty()) {
            this.reset();
            if (p.byteLength === 0) {
                return 0;
            }
            return null;
        }
        const nread = copy(this.#buf.subarray(this.#off), p);
        this.#off += nread;
        return nread;
    }
    read(p) {
        const rr = this.readSync(p);
        return Promise.resolve(rr);
    }
    writeSync(p) {
        const m = this.#grow(p.byteLength);
        return copy(p, this.#buf, m);
    }
    write(p) {
        const n1 = this.writeSync(p);
        return Promise.resolve(n1);
    }
     #grow(n2) {
        const m = this.length;
        if (m === 0 && this.#off !== 0) {
            this.reset();
        }
        const i = this.#tryGrowByReslice(n2);
        if (i >= 0) {
            return i;
        }
        const c = this.capacity;
        if (n2 <= Math.floor(c / 2) - m) {
            copy(this.#buf.subarray(this.#off), this.#buf);
        } else if (c + n2 > MAX_SIZE) {
            throw new Error("The buffer cannot be grown beyond the maximum size.");
        } else {
            const buf = new Uint8Array(Math.min(2 * c + n2, MAX_SIZE));
            copy(this.#buf.subarray(this.#off), buf);
            this.#buf = buf;
        }
        this.#off = 0;
        this.#reslice(Math.min(m + n2, MAX_SIZE));
        return m;
    }
    grow(n3) {
        if (n3 < 0) {
            throw Error("Buffer.grow: negative count");
        }
        const m = this.#grow(n3);
        this.#reslice(m);
    }
    async readFrom(r) {
        let n4 = 0;
        const tmp = new Uint8Array(MIN_READ);
        while(true){
            const shouldGrow = this.capacity - this.length < MIN_READ;
            const buf = shouldGrow ? tmp : new Uint8Array(this.#buf.buffer, this.length);
            const nread = await r.read(buf);
            if (nread === null) {
                return n4;
            }
            if (shouldGrow) this.writeSync(buf.subarray(0, nread));
            else this.#reslice(this.length + nread);
            n4 += nread;
        }
    }
    readFromSync(r) {
        let n5 = 0;
        const tmp = new Uint8Array(MIN_READ);
        while(true){
            const shouldGrow = this.capacity - this.length < MIN_READ;
            const buf = shouldGrow ? tmp : new Uint8Array(this.#buf.buffer, this.length);
            const nread = r.readSync(buf);
            if (nread === null) {
                return n5;
            }
            if (shouldGrow) this.writeSync(buf.subarray(0, nread));
            else this.#reslice(this.length + nread);
            n5 += nread;
        }
    }
}
const DEFAULT_BUF_SIZE = 4096;
const MIN_BUF_SIZE = 16;
const CR = "\r".charCodeAt(0);
const LF = "\n".charCodeAt(0);
class BufferFullError extends Error {
    partial;
    name = "BufferFullError";
    constructor(partial){
        super("Buffer full");
        this.partial = partial;
    }
}
class PartialReadError extends Error {
    name = "PartialReadError";
    partial;
    constructor(){
        super("Encountered UnexpectedEof, data only partially read");
    }
}
class BufReader {
    #buf;
    #rd;
    #r = 0;
    #w = 0;
    #eof = false;
    static create(r, size = 4096) {
        return r instanceof BufReader ? r : new BufReader(r, size);
    }
    constructor(rd, size = 4096){
        if (size < 16) {
            size = MIN_BUF_SIZE;
        }
        this.#reset(new Uint8Array(size), rd);
    }
    size() {
        return this.#buf.byteLength;
    }
    buffered() {
        return this.#w - this.#r;
    }
    #fill = async ()=>{
        if (this.#r > 0) {
            this.#buf.copyWithin(0, this.#r, this.#w);
            this.#w -= this.#r;
            this.#r = 0;
        }
        if (this.#w >= this.#buf.byteLength) {
            throw Error("bufio: tried to fill full buffer");
        }
        for(let i24 = 100; i24 > 0; i24--){
            const rr = await this.#rd.read(this.#buf.subarray(this.#w));
            if (rr === null) {
                this.#eof = true;
                return;
            }
            assert(rr >= 0, "negative read");
            this.#w += rr;
            if (rr > 0) {
                return;
            }
        }
        throw new Error(`No progress after ${100} read() calls`);
    };
    reset(r) {
        this.#reset(this.#buf, r);
    }
    #reset = (buf, rd)=>{
        this.#buf = buf;
        this.#rd = rd;
        this.#eof = false;
    };
    async read(p) {
        let rr = p.byteLength;
        if (p.byteLength === 0) return rr;
        if (this.#r === this.#w) {
            if (p.byteLength >= this.#buf.byteLength) {
                const rr = await this.#rd.read(p);
                const nread = rr ?? 0;
                assert(nread >= 0, "negative read");
                return rr;
            }
            this.#r = 0;
            this.#w = 0;
            rr = await this.#rd.read(this.#buf);
            if (rr === 0 || rr === null) return rr;
            assert(rr >= 0, "negative read");
            this.#w += rr;
        }
        const copied = copy(this.#buf.subarray(this.#r, this.#w), p, 0);
        this.#r += copied;
        return copied;
    }
    async readFull(p) {
        let bytesRead = 0;
        while(bytesRead < p.length){
            try {
                const rr = await this.read(p.subarray(bytesRead));
                if (rr === null) {
                    if (bytesRead === 0) {
                        return null;
                    } else {
                        throw new PartialReadError();
                    }
                }
                bytesRead += rr;
            } catch (err) {
                if (err instanceof PartialReadError) {
                    err.partial = p.subarray(0, bytesRead);
                } else if (err instanceof Error) {
                    const e = new PartialReadError();
                    e.partial = p.subarray(0, bytesRead);
                    e.stack = err.stack;
                    e.message = err.message;
                    e.cause = err.cause;
                    throw err;
                }
                throw err;
            }
        }
        return p;
    }
    async readByte() {
        while(this.#r === this.#w){
            if (this.#eof) return null;
            await this.#fill();
        }
        const c = this.#buf[this.#r];
        this.#r++;
        return c;
    }
    async readString(delim) {
        if (delim.length !== 1) {
            throw new Error("Delimiter should be a single character");
        }
        const buffer = await this.readSlice(delim.charCodeAt(0));
        if (buffer === null) return null;
        return new TextDecoder().decode(buffer);
    }
    async readLine() {
        let line = null;
        try {
            line = await this.readSlice(LF);
        } catch (err) {
            if (err instanceof Deno.errors.BadResource) {
                throw err;
            }
            let partial;
            if (err instanceof PartialReadError) {
                partial = err.partial;
                assert(partial instanceof Uint8Array, "bufio: caught error from `readSlice()` without `partial` property");
            }
            if (!(err instanceof BufferFullError)) {
                throw err;
            }
            partial = err.partial;
            if (!this.#eof && partial && partial.byteLength > 0 && partial[partial.byteLength - 1] === CR) {
                assert(this.#r > 0, "bufio: tried to rewind past start of buffer");
                this.#r--;
                partial = partial.subarray(0, partial.byteLength - 1);
            }
            if (partial) {
                return {
                    line: partial,
                    more: !this.#eof
                };
            }
        }
        if (line === null) {
            return null;
        }
        if (line.byteLength === 0) {
            return {
                line,
                more: false
            };
        }
        if (line[line.byteLength - 1] == LF) {
            let drop = 1;
            if (line.byteLength > 1 && line[line.byteLength - 2] === CR) {
                drop = 2;
            }
            line = line.subarray(0, line.byteLength - drop);
        }
        return {
            line,
            more: false
        };
    }
    async readSlice(delim) {
        let s = 0;
        let slice1;
        while(true){
            let i25 = this.#buf.subarray(this.#r + s, this.#w).indexOf(delim);
            if (i25 >= 0) {
                i25 += s;
                slice1 = this.#buf.subarray(this.#r, this.#r + i25 + 1);
                this.#r += i25 + 1;
                break;
            }
            if (this.#eof) {
                if (this.#r === this.#w) {
                    return null;
                }
                slice1 = this.#buf.subarray(this.#r, this.#w);
                this.#r = this.#w;
                break;
            }
            if (this.buffered() >= this.#buf.byteLength) {
                this.#r = this.#w;
                const oldbuf = this.#buf;
                const newbuf = this.#buf.slice(0);
                this.#buf = newbuf;
                throw new BufferFullError(oldbuf);
            }
            s = this.#w - this.#r;
            try {
                await this.#fill();
            } catch (err) {
                if (err instanceof PartialReadError) {
                    err.partial = slice1;
                } else if (err instanceof Error) {
                    const e = new PartialReadError();
                    e.partial = slice1;
                    e.stack = err.stack;
                    e.message = err.message;
                    e.cause = err.cause;
                    throw err;
                }
                throw err;
            }
        }
        return slice1;
    }
    async peek(n6) {
        if (n6 < 0) {
            throw Error("negative count");
        }
        let avail = this.#w - this.#r;
        while(avail < n6 && avail < this.#buf.byteLength && !this.#eof){
            try {
                await this.#fill();
            } catch (err) {
                if (err instanceof PartialReadError) {
                    err.partial = this.#buf.subarray(this.#r, this.#w);
                } else if (err instanceof Error) {
                    const e = new PartialReadError();
                    e.partial = this.#buf.subarray(this.#r, this.#w);
                    e.stack = err.stack;
                    e.message = err.message;
                    e.cause = err.cause;
                    throw err;
                }
                throw err;
            }
            avail = this.#w - this.#r;
        }
        if (avail === 0 && this.#eof) {
            return null;
        } else if (avail < n6 && this.#eof) {
            return this.#buf.subarray(this.#r, this.#r + avail);
        } else if (avail < n6) {
            throw new BufferFullError(this.#buf.subarray(this.#r, this.#w));
        }
        return this.#buf.subarray(this.#r, this.#r + n6);
    }
}
class AbstractBufBase {
    buf;
    usedBufferBytes = 0;
    err = null;
    constructor(buf){
        this.buf = buf;
    }
    size() {
        return this.buf.byteLength;
    }
    available() {
        return this.buf.byteLength - this.usedBufferBytes;
    }
    buffered() {
        return this.usedBufferBytes;
    }
}
class BufWriter extends AbstractBufBase {
    #writer;
    static create(writer, size = 4096) {
        return writer instanceof BufWriter ? writer : new BufWriter(writer, size);
    }
    constructor(writer, size = 4096){
        if (size <= 0) {
            size = DEFAULT_BUF_SIZE;
        }
        const buf = new Uint8Array(size);
        super(buf);
        this.#writer = writer;
    }
    reset(w) {
        this.err = null;
        this.usedBufferBytes = 0;
        this.#writer = w;
    }
    async flush() {
        if (this.err !== null) throw this.err;
        if (this.usedBufferBytes === 0) return;
        try {
            const p = this.buf.subarray(0, this.usedBufferBytes);
            let nwritten = 0;
            while(nwritten < p.length){
                nwritten += await this.#writer.write(p.subarray(nwritten));
            }
        } catch (e) {
            if (e instanceof Error) {
                this.err = e;
            }
            throw e;
        }
        this.buf = new Uint8Array(this.buf.length);
        this.usedBufferBytes = 0;
    }
    async write(data2) {
        if (this.err !== null) throw this.err;
        if (data2.length === 0) return 0;
        let totalBytesWritten = 0;
        let numBytesWritten = 0;
        while(data2.byteLength > this.available()){
            if (this.buffered() === 0) {
                try {
                    numBytesWritten = await this.#writer.write(data2);
                } catch (e) {
                    if (e instanceof Error) {
                        this.err = e;
                    }
                    throw e;
                }
            } else {
                numBytesWritten = copy(data2, this.buf, this.usedBufferBytes);
                this.usedBufferBytes += numBytesWritten;
                await this.flush();
            }
            totalBytesWritten += numBytesWritten;
            data2 = data2.subarray(numBytesWritten);
        }
        numBytesWritten = copy(data2, this.buf, this.usedBufferBytes);
        this.usedBufferBytes += numBytesWritten;
        totalBytesWritten += numBytesWritten;
        return totalBytesWritten;
    }
}
class BufWriterSync extends AbstractBufBase {
    #writer;
    static create(writer, size = 4096) {
        return writer instanceof BufWriterSync ? writer : new BufWriterSync(writer, size);
    }
    constructor(writer, size = 4096){
        if (size <= 0) {
            size = DEFAULT_BUF_SIZE;
        }
        const buf = new Uint8Array(size);
        super(buf);
        this.#writer = writer;
    }
    reset(w) {
        this.err = null;
        this.usedBufferBytes = 0;
        this.#writer = w;
    }
    flush() {
        if (this.err !== null) throw this.err;
        if (this.usedBufferBytes === 0) return;
        try {
            const p = this.buf.subarray(0, this.usedBufferBytes);
            let nwritten = 0;
            while(nwritten < p.length){
                nwritten += this.#writer.writeSync(p.subarray(nwritten));
            }
        } catch (e) {
            if (e instanceof Error) {
                this.err = e;
            }
            throw e;
        }
        this.buf = new Uint8Array(this.buf.length);
        this.usedBufferBytes = 0;
    }
    writeSync(data3) {
        if (this.err !== null) throw this.err;
        if (data3.length === 0) return 0;
        let totalBytesWritten = 0;
        let numBytesWritten = 0;
        while(data3.byteLength > this.available()){
            if (this.buffered() === 0) {
                try {
                    numBytesWritten = this.#writer.writeSync(data3);
                } catch (e) {
                    if (e instanceof Error) {
                        this.err = e;
                    }
                    throw e;
                }
            } else {
                numBytesWritten = copy(data3, this.buf, this.usedBufferBytes);
                this.usedBufferBytes += numBytesWritten;
                this.flush();
            }
            totalBytesWritten += numBytesWritten;
            data3 = data3.subarray(numBytesWritten);
        }
        numBytesWritten = copy(data3, this.buf, this.usedBufferBytes);
        this.usedBufferBytes += numBytesWritten;
        totalBytesWritten += numBytesWritten;
        return totalBytesWritten;
    }
}
async function* readLines(reader, decoderOpts) {
    const bufReader = new BufReader(reader);
    let chunks = [];
    const decoder = new TextDecoder(decoderOpts?.encoding, decoderOpts);
    while(true){
        const res = await bufReader.readLine();
        if (!res) {
            if (chunks.length > 0) {
                yield decoder.decode(concat(...chunks));
            }
            break;
        }
        chunks.push(res.line);
        if (!res.more) {
            yield decoder.decode(concat(...chunks));
            chunks = [];
        }
    }
}
const DEFAULT_FORMATTER = "{levelName} {msg}";
class BaseHandler {
    level;
    levelName;
    formatter;
    constructor(levelName, options = {}){
        this.level = getLevelByName(levelName);
        this.levelName = levelName;
        this.formatter = options.formatter || DEFAULT_FORMATTER;
    }
    handle(logRecord) {
        if (this.level > logRecord.level) return;
        const msg = this.format(logRecord);
        return this.log(msg);
    }
    format(logRecord) {
        if (this.formatter instanceof Function) {
            return this.formatter(logRecord);
        }
        return this.formatter.replace(/{(\S+)}/g, (match, p1)=>{
            const value = logRecord[p1];
            if (value == null) {
                return match;
            }
            return String(value);
        });
    }
    log(_msg) {}
    async setup() {}
    async destroy() {}
}
class ConsoleHandler extends BaseHandler {
    format(logRecord) {
        let msg = super.format(logRecord);
        switch(logRecord.level){
            case LogLevels.INFO:
                msg = blue(msg);
                break;
            case LogLevels.WARNING:
                msg = yellow(msg);
                break;
            case LogLevels.ERROR:
                msg = red(msg);
                break;
            case LogLevels.CRITICAL:
                msg = bold(red(msg));
                break;
            default:
                break;
        }
        return msg;
    }
    log(msg) {
        console.log(msg);
    }
}
class WriterHandler extends BaseHandler {
    _writer;
    #encoder = new TextEncoder();
}
class FileHandler extends WriterHandler {
    _file;
    _buf;
    _filename;
    _mode;
    _openOptions;
    _encoder = new TextEncoder();
    #unloadCallback = (()=>{
        this.destroy();
    }).bind(this);
    constructor(levelName, options){
        super(levelName, options);
        this._filename = options.filename;
        this._mode = options.mode ? options.mode : "a";
        this._openOptions = {
            createNew: this._mode === "x",
            create: this._mode !== "x",
            append: this._mode === "a",
            truncate: this._mode !== "a",
            write: true
        };
    }
    async setup() {
        this._file = await Deno.open(this._filename, this._openOptions);
        this._writer = this._file;
        this._buf = new BufWriterSync(this._file);
        addEventListener("unload", this.#unloadCallback);
    }
    handle(logRecord) {
        super.handle(logRecord);
        if (logRecord.level > LogLevels.ERROR) {
            this.flush();
        }
    }
    log(msg) {
        if (this._encoder.encode(msg).byteLength + 1 > this._buf.available()) {
            this.flush();
        }
        this._buf.writeSync(this._encoder.encode(msg + "\n"));
    }
    flush() {
        if (this._buf?.buffered() > 0) {
            this._buf.flush();
        }
    }
    destroy() {
        this.flush();
        this._file?.close();
        this._file = undefined;
        removeEventListener("unload", this.#unloadCallback);
        return Promise.resolve();
    }
}
const DEFAULT_LEVEL = "INFO";
const DEFAULT_CONFIG = {
    handlers: {
        default: new ConsoleHandler(DEFAULT_LEVEL)
    },
    loggers: {
        default: {
            level: DEFAULT_LEVEL,
            handlers: [
                "default"
            ]
        }
    }
};
const state = {
    handlers: new Map(),
    loggers: new Map(),
    config: DEFAULT_CONFIG
};
function getLogger(name73) {
    if (!name73) {
        const d = state.loggers.get("default");
        assert(d != null, `"default" logger must be set for getting logger without name`);
        return d;
    }
    const result = state.loggers.get(name73);
    if (!result) {
        const logger = new Logger(name73, "NOTSET", {
            handlers: []
        });
        state.loggers.set(name73, logger);
        return logger;
    }
    return result;
}
function debug(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").debug(msg, ...args);
    }
    return getLogger("default").debug(msg, ...args);
}
function info(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").info(msg, ...args);
    }
    return getLogger("default").info(msg, ...args);
}
function warning(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").warning(msg, ...args);
    }
    return getLogger("default").warning(msg, ...args);
}
function error(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").error(msg, ...args);
    }
    return getLogger("default").error(msg, ...args);
}
async function setup(config) {
    state.config = {
        handlers: {
            ...DEFAULT_CONFIG.handlers,
            ...config.handlers
        },
        loggers: {
            ...DEFAULT_CONFIG.loggers,
            ...config.loggers
        }
    };
    state.handlers.forEach((handler)=>{
        handler.destroy();
    });
    state.handlers.clear();
    const handlers1 = state.config.handlers || {};
    for(const handlerName1 in handlers1){
        const handler = handlers1[handlerName1];
        await handler.setup();
        state.handlers.set(handlerName1, handler);
    }
    state.loggers.clear();
    const loggers = state.config.loggers || {};
    for(const loggerName in loggers){
        const loggerConfig = loggers[loggerName];
        const handlerNames = loggerConfig.handlers || [];
        const handlers2 = [];
        handlerNames.forEach((handlerName)=>{
            const handler = state.handlers.get(handlerName);
            if (handler) {
                handlers2.push(handler);
            }
        });
        const levelName = loggerConfig.level || DEFAULT_LEVEL;
        const logger = new Logger(loggerName, levelName, {
            handlers: handlers2
        });
        state.loggers.set(loggerName, logger);
    }
}
await setup(DEFAULT_CONFIG);
function isSubdir(src, dest, sep5 = sep2) {
    if (src === dest) {
        return false;
    }
    const srcArray = src.split(sep5);
    const destArray = dest.split(sep5);
    return srcArray.every((current, i26)=>destArray[i26] === current
    );
}
function getFileInfoType(fileInfo) {
    return fileInfo.isFile ? "file" : fileInfo.isDirectory ? "dir" : fileInfo.isSymlink ? "symlink" : undefined;
}
async function ensureDir(dir) {
    try {
        const fileInfo = await Deno.lstat(dir);
        if (!fileInfo.isDirectory) {
            throw new Error(`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`);
        }
    } catch (err) {
        if (err instanceof Deno.errors.NotFound) {
            await Deno.mkdir(dir, {
                recursive: true
            });
            return;
        }
        throw err;
    }
}
function ensureDirSync(dir) {
    try {
        const fileInfo = Deno.lstatSync(dir);
        if (!fileInfo.isDirectory) {
            throw new Error(`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`);
        }
    } catch (err) {
        if (err instanceof Deno.errors.NotFound) {
            Deno.mkdirSync(dir, {
                recursive: true
            });
            return;
        }
        throw err;
    }
}
function moveSync(src, dest, { overwrite =false  } = {}) {
    const srcStat = Deno.statSync(src);
    if (srcStat.isDirectory && isSubdir(src, dest)) {
        throw new Error(`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`);
    }
    if (overwrite) {
        if (existsSync(dest)) {
            Deno.removeSync(dest, {
                recursive: true
            });
        }
    } else {
        if (existsSync(dest)) {
            throw new Error("dest already exists.");
        }
    }
    Deno.renameSync(src, dest);
}
var EOL;
(function(EOL1) {
    EOL1["LF"] = "\n";
    EOL1["CRLF"] = "\r\n";
})(EOL || (EOL = {}));
class YAMLError extends Error {
    mark;
    constructor(message = "(unknown reason)", mark = ""){
        super(`${message} ${mark}`);
        this.mark = mark;
        this.name = this.constructor.name;
    }
    toString(_compact) {
        return `${this.name}: ${this.message} ${this.mark}`;
    }
}
function isBoolean(value) {
    return typeof value === "boolean" || value instanceof Boolean;
}
function isObject(value) {
    return value !== null && typeof value === "object";
}
function repeat(str55, count) {
    let result = "";
    for(let cycle = 0; cycle < count; cycle++){
        result += str55;
    }
    return result;
}
function isNegativeZero(i27) {
    return i27 === 0 && Number.NEGATIVE_INFINITY === 1 / i27;
}
class Mark {
    name;
    buffer;
    position;
    line;
    column;
    constructor(name74, buffer, position, line, column){
        this.name = name74;
        this.buffer = buffer;
        this.position = position;
        this.line = line;
        this.column = column;
    }
    getSnippet(indent = 4, maxLength = 75) {
        if (!this.buffer) return null;
        let head = "";
        let start = this.position;
        while(start > 0 && "\x00\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(start - 1)) === -1){
            start -= 1;
            if (this.position - start > maxLength / 2 - 1) {
                head = " ... ";
                start += 5;
                break;
            }
        }
        let tail = "";
        let end = this.position;
        while(end < this.buffer.length && "\x00\r\n\x85\u2028\u2029".indexOf(this.buffer.charAt(end)) === -1){
            end += 1;
            if (end - this.position > maxLength / 2 - 1) {
                tail = " ... ";
                end -= 5;
                break;
            }
        }
        const snippet = this.buffer.slice(start, end);
        return `${repeat(" ", indent)}${head}${snippet}${tail}\n${repeat(" ", indent + this.position - start + head.length)}^`;
    }
    toString(compact) {
        let snippet, where = "";
        if (this.name) {
            where += `in "${this.name}" `;
        }
        where += `at line ${this.line + 1}, column ${this.column + 1}`;
        if (!compact) {
            snippet = this.getSnippet();
            if (snippet) {
                where += `:\n${snippet}`;
            }
        }
        return where;
    }
}
function compileList(schema, name75, result) {
    const exclude = [];
    for (const includedSchema of schema.include){
        result = compileList(includedSchema, name75, result);
    }
    for (const currentType of schema[name75]){
        for(let previousIndex = 0; previousIndex < result.length; previousIndex++){
            const previousType = result[previousIndex];
            if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
                exclude.push(previousIndex);
            }
        }
        result.push(currentType);
    }
    return result.filter((_type, index)=>!exclude.includes(index)
    );
}
function compileMap(...typesList) {
    const result = {
        fallback: {},
        mapping: {},
        scalar: {},
        sequence: {}
    };
    for (const types9 of typesList){
        for (const type of types9){
            if (type.kind !== null) {
                result[type.kind][type.tag] = result["fallback"][type.tag] = type;
            }
        }
    }
    return result;
}
class Schema {
    static SCHEMA_DEFAULT;
    implicit;
    explicit;
    include;
    compiledImplicit;
    compiledExplicit;
    compiledTypeMap;
    constructor(definition){
        this.explicit = definition.explicit || [];
        this.implicit = definition.implicit || [];
        this.include = definition.include || [];
        for (const type of this.implicit){
            if (type.loadKind && type.loadKind !== "scalar") {
                throw new YAMLError("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
            }
        }
        this.compiledImplicit = compileList(this, "implicit", []);
        this.compiledExplicit = compileList(this, "explicit", []);
        this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
    }
    extend(definition) {
        return new Schema({
            implicit: [
                ...new Set([
                    ...this.implicit,
                    ...definition?.implicit ?? []
                ]), 
            ],
            explicit: [
                ...new Set([
                    ...this.explicit,
                    ...definition?.explicit ?? []
                ]), 
            ],
            include: [
                ...new Set([
                    ...this.include,
                    ...definition?.include ?? []
                ])
            ]
        });
    }
    static create() {}
}
const DEFAULT_RESOLVE = ()=>true
;
const DEFAULT_CONSTRUCT = (data4)=>data4
;
function checkTagFormat(tag) {
    return tag;
}
class Type1 {
    tag;
    kind = null;
    instanceOf;
    predicate;
    represent;
    defaultStyle;
    styleAliases;
    loadKind;
    constructor(tag, options){
        this.tag = checkTagFormat(tag);
        if (options) {
            this.kind = options.kind;
            this.resolve = options.resolve || DEFAULT_RESOLVE;
            this.construct = options.construct || DEFAULT_CONSTRUCT;
            this.instanceOf = options.instanceOf;
            this.predicate = options.predicate;
            this.represent = options.represent;
            this.defaultStyle = options.defaultStyle;
            this.styleAliases = options.styleAliases;
        }
    }
    resolve = ()=>true
    ;
    construct = (data5)=>data5
    ;
}
const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
function resolveYamlBinary(data6) {
    if (data6 === null) return false;
    let code17;
    let bitlen = 0;
    const max = data6.length;
    const map1 = BASE64_MAP;
    for(let idx = 0; idx < max; idx++){
        code17 = map1.indexOf(data6.charAt(idx));
        if (code17 > 64) continue;
        if (code17 < 0) return false;
        bitlen += 6;
    }
    return bitlen % 8 === 0;
}
function constructYamlBinary(data7) {
    const input = data7.replace(/[\r\n=]/g, "");
    const max = input.length;
    const map2 = BASE64_MAP;
    const result = [];
    let bits = 0;
    for(let idx = 0; idx < max; idx++){
        if (idx % 4 === 0 && idx) {
            result.push(bits >> 16 & 255);
            result.push(bits >> 8 & 255);
            result.push(bits & 255);
        }
        bits = bits << 6 | map2.indexOf(input.charAt(idx));
    }
    const tailbits = max % 4 * 6;
    if (tailbits === 0) {
        result.push(bits >> 16 & 255);
        result.push(bits >> 8 & 255);
        result.push(bits & 255);
    } else if (tailbits === 18) {
        result.push(bits >> 10 & 255);
        result.push(bits >> 2 & 255);
    } else if (tailbits === 12) {
        result.push(bits >> 4 & 255);
    }
    return new Buffer(new Uint8Array(result));
}
function representYamlBinary(object) {
    const max = object.length;
    const map3 = BASE64_MAP;
    let result = "";
    let bits = 0;
    for(let idx = 0; idx < max; idx++){
        if (idx % 3 === 0 && idx) {
            result += map3[bits >> 18 & 63];
            result += map3[bits >> 12 & 63];
            result += map3[bits >> 6 & 63];
            result += map3[bits & 63];
        }
        bits = (bits << 8) + object[idx];
    }
    const tail = max % 3;
    if (tail === 0) {
        result += map3[bits >> 18 & 63];
        result += map3[bits >> 12 & 63];
        result += map3[bits >> 6 & 63];
        result += map3[bits & 63];
    } else if (tail === 2) {
        result += map3[bits >> 10 & 63];
        result += map3[bits >> 4 & 63];
        result += map3[bits << 2 & 63];
        result += map3[64];
    } else if (tail === 1) {
        result += map3[bits >> 2 & 63];
        result += map3[bits << 4 & 63];
        result += map3[64];
        result += map3[64];
    }
    return result;
}
function isBinary(obj) {
    const buf = new Buffer();
    try {
        if (0 > buf.readFromSync(obj)) return true;
        return false;
    } catch  {
        return false;
    } finally{
        buf.reset();
    }
}
const binary = new Type1("tag:yaml.org,2002:binary", {
    construct: constructYamlBinary,
    kind: "scalar",
    predicate: isBinary,
    represent: representYamlBinary,
    resolve: resolveYamlBinary
});
function resolveYamlBoolean(data8) {
    const max = data8.length;
    return max === 4 && (data8 === "true" || data8 === "True" || data8 === "TRUE") || max === 5 && (data8 === "false" || data8 === "False" || data8 === "FALSE");
}
function constructYamlBoolean(data9) {
    return data9 === "true" || data9 === "True" || data9 === "TRUE";
}
const bool = new Type1("tag:yaml.org,2002:bool", {
    construct: constructYamlBoolean,
    defaultStyle: "lowercase",
    kind: "scalar",
    predicate: isBoolean,
    represent: {
        lowercase (object) {
            return object ? "true" : "false";
        },
        uppercase (object) {
            return object ? "TRUE" : "FALSE";
        },
        camelcase (object) {
            return object ? "True" : "False";
        }
    },
    resolve: resolveYamlBoolean
});
const YAML_FLOAT_PATTERN = new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?" + "|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?" + "|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*" + "|[-+]?\\.(?:inf|Inf|INF)" + "|\\.(?:nan|NaN|NAN))$");
function resolveYamlFloat(data10) {
    if (!YAML_FLOAT_PATTERN.test(data10) || data10[data10.length - 1] === "_") {
        return false;
    }
    return true;
}
function constructYamlFloat(data11) {
    let value = data11.replace(/_/g, "").toLowerCase();
    const sign = value[0] === "-" ? -1 : 1;
    const digits1 = [];
    if ("+-".indexOf(value[0]) >= 0) {
        value = value.slice(1);
    }
    if (value === ".inf") {
        return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
    }
    if (value === ".nan") {
        return NaN;
    }
    if (value.indexOf(":") >= 0) {
        value.split(":").forEach((v)=>{
            digits1.unshift(parseFloat(v));
        });
        let valueNb = 0;
        let base2 = 1;
        digits1.forEach((d)=>{
            valueNb += d * base2;
            base2 *= 60;
        });
        return sign * valueNb;
    }
    return sign * parseFloat(value);
}
const SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;
function representYamlFloat(object, style) {
    if (isNaN(object)) {
        switch(style){
            case "lowercase":
                return ".nan";
            case "uppercase":
                return ".NAN";
            case "camelcase":
                return ".NaN";
        }
    } else if (Number.POSITIVE_INFINITY === object) {
        switch(style){
            case "lowercase":
                return ".inf";
            case "uppercase":
                return ".INF";
            case "camelcase":
                return ".Inf";
        }
    } else if (Number.NEGATIVE_INFINITY === object) {
        switch(style){
            case "lowercase":
                return "-.inf";
            case "uppercase":
                return "-.INF";
            case "camelcase":
                return "-.Inf";
        }
    } else if (isNegativeZero(object)) {
        return "-0.0";
    }
    const res = object.toString(10);
    return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace("e", ".e") : res;
}
function isFloat(object) {
    return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || isNegativeZero(object));
}
const __float = new Type1("tag:yaml.org,2002:float", {
    construct: constructYamlFloat,
    defaultStyle: "lowercase",
    kind: "scalar",
    predicate: isFloat,
    represent: representYamlFloat,
    resolve: resolveYamlFloat
});
function reconstructFunction(code18) {
    const func1 = new Function(`return ${code18}`)();
    if (!(func1 instanceof Function)) {
        throw new TypeError(`Expected function but got ${typeof func1}: ${code18}`);
    }
    return func1;
}
new Type1("tag:yaml.org,2002:js/function", {
    kind: "scalar",
    resolve (data12) {
        if (data12 === null) {
            return false;
        }
        try {
            reconstructFunction(`${data12}`);
            return true;
        } catch (_err) {
            return false;
        }
    },
    construct (data13) {
        return reconstructFunction(data13);
    },
    predicate (object) {
        return object instanceof Function;
    },
    represent (object) {
        return object.toString();
    }
});
function isHexCode(c) {
    return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
}
function isOctCode(c) {
    return 48 <= c && c <= 55;
}
function isDecCode(c) {
    return 48 <= c && c <= 57;
}
function resolveYamlInteger(data14) {
    const max = data14.length;
    let index = 0;
    let hasDigits = false;
    if (!max) return false;
    let ch = data14[index];
    if (ch === "-" || ch === "+") {
        ch = data14[++index];
    }
    if (ch === "0") {
        if (index + 1 === max) return true;
        ch = data14[++index];
        if (ch === "b") {
            index++;
            for(; index < max; index++){
                ch = data14[index];
                if (ch === "_") continue;
                if (ch !== "0" && ch !== "1") return false;
                hasDigits = true;
            }
            return hasDigits && ch !== "_";
        }
        if (ch === "x") {
            index++;
            for(; index < max; index++){
                ch = data14[index];
                if (ch === "_") continue;
                if (!isHexCode(data14.charCodeAt(index))) return false;
                hasDigits = true;
            }
            return hasDigits && ch !== "_";
        }
        for(; index < max; index++){
            ch = data14[index];
            if (ch === "_") continue;
            if (!isOctCode(data14.charCodeAt(index))) return false;
            hasDigits = true;
        }
        return hasDigits && ch !== "_";
    }
    if (ch === "_") return false;
    for(; index < max; index++){
        ch = data14[index];
        if (ch === "_") continue;
        if (ch === ":") break;
        if (!isDecCode(data14.charCodeAt(index))) {
            return false;
        }
        hasDigits = true;
    }
    if (!hasDigits || ch === "_") return false;
    if (ch !== ":") return true;
    return /^(:[0-5]?[0-9])+$/.test(data14.slice(index));
}
function constructYamlInteger(data15) {
    let value = data15;
    const digits2 = [];
    if (value.indexOf("_") !== -1) {
        value = value.replace(/_/g, "");
    }
    let sign = 1;
    let ch = value[0];
    if (ch === "-" || ch === "+") {
        if (ch === "-") sign = -1;
        value = value.slice(1);
        ch = value[0];
    }
    if (value === "0") return 0;
    if (ch === "0") {
        if (value[1] === "b") return sign * parseInt(value.slice(2), 2);
        if (value[1] === "x") return sign * parseInt(value, 16);
        return sign * parseInt(value, 8);
    }
    if (value.indexOf(":") !== -1) {
        value.split(":").forEach((v)=>{
            digits2.unshift(parseInt(v, 10));
        });
        let valueInt = 0;
        let base3 = 1;
        digits2.forEach((d)=>{
            valueInt += d * base3;
            base3 *= 60;
        });
        return sign * valueInt;
    }
    return sign * parseInt(value, 10);
}
function isInteger(object) {
    return Object.prototype.toString.call(object) === "[object Number]" && object % 1 === 0 && !isNegativeZero(object);
}
const __int = new Type1("tag:yaml.org,2002:int", {
    construct: constructYamlInteger,
    defaultStyle: "decimal",
    kind: "scalar",
    predicate: isInteger,
    represent: {
        binary (obj) {
            return obj >= 0 ? `0b${obj.toString(2)}` : `-0b${obj.toString(2).slice(1)}`;
        },
        octal (obj) {
            return obj >= 0 ? `0${obj.toString(8)}` : `-0${obj.toString(8).slice(1)}`;
        },
        decimal (obj) {
            return obj.toString(10);
        },
        hexadecimal (obj) {
            return obj >= 0 ? `0x${obj.toString(16).toUpperCase()}` : `-0x${obj.toString(16).toUpperCase().slice(1)}`;
        }
    },
    resolve: resolveYamlInteger,
    styleAliases: {
        binary: [
            2,
            "bin"
        ],
        decimal: [
            10,
            "dec"
        ],
        hexadecimal: [
            16,
            "hex"
        ],
        octal: [
            8,
            "oct"
        ]
    }
});
const map = new Type1("tag:yaml.org,2002:map", {
    construct (data16) {
        return data16 !== null ? data16 : {};
    },
    kind: "mapping"
});
function resolveYamlMerge(data17) {
    return data17 === "<<" || data17 === null;
}
const merge = new Type1("tag:yaml.org,2002:merge", {
    kind: "scalar",
    resolve: resolveYamlMerge
});
function resolveYamlNull(data18) {
    const max = data18.length;
    return max === 1 && data18 === "~" || max === 4 && (data18 === "null" || data18 === "Null" || data18 === "NULL");
}
function constructYamlNull() {
    return null;
}
function isNull(object) {
    return object === null;
}
const nil = new Type1("tag:yaml.org,2002:null", {
    construct: constructYamlNull,
    defaultStyle: "lowercase",
    kind: "scalar",
    predicate: isNull,
    represent: {
        canonical () {
            return "~";
        },
        lowercase () {
            return "null";
        },
        uppercase () {
            return "NULL";
        },
        camelcase () {
            return "Null";
        }
    },
    resolve: resolveYamlNull
});
const { hasOwn  } = Object;
const _toString = Object.prototype.toString;
function resolveYamlOmap(data19) {
    const objectKeys = [];
    let pairKey = "";
    let pairHasKey = false;
    for (const pair of data19){
        pairHasKey = false;
        if (_toString.call(pair) !== "[object Object]") return false;
        for(pairKey in pair){
            if (hasOwn(pair, pairKey)) {
                if (!pairHasKey) pairHasKey = true;
                else return false;
            }
        }
        if (!pairHasKey) return false;
        if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
        else return false;
    }
    return true;
}
function constructYamlOmap(data20) {
    return data20 !== null ? data20 : [];
}
const omap = new Type1("tag:yaml.org,2002:omap", {
    construct: constructYamlOmap,
    kind: "sequence",
    resolve: resolveYamlOmap
});
const _toString1 = Object.prototype.toString;
function resolveYamlPairs(data21) {
    const result = Array.from({
        length: data21.length
    });
    for(let index = 0; index < data21.length; index++){
        const pair = data21[index];
        if (_toString1.call(pair) !== "[object Object]") return false;
        const keys2 = Object.keys(pair);
        if (keys2.length !== 1) return false;
        result[index] = [
            keys2[0],
            pair[keys2[0]]
        ];
    }
    return true;
}
function constructYamlPairs(data22) {
    if (data22 === null) return [];
    const result = Array.from({
        length: data22.length
    });
    for(let index = 0; index < data22.length; index += 1){
        const pair = data22[index];
        const keys3 = Object.keys(pair);
        result[index] = [
            keys3[0],
            pair[keys3[0]]
        ];
    }
    return result;
}
const pairs = new Type1("tag:yaml.org,2002:pairs", {
    construct: constructYamlPairs,
    kind: "sequence",
    resolve: resolveYamlPairs
});
const REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/;
const regexp = new Type1("tag:yaml.org,2002:js/regexp", {
    kind: "scalar",
    resolve (data23) {
        if (data23 === null || !data23.length) {
            return false;
        }
        const regexp1 = `${data23}`;
        if (regexp1.charAt(0) === "/") {
            if (!REGEXP.test(data23)) {
                return false;
            }
            const modifiers = [
                ...regexp1.match(REGEXP)?.groups?.modifiers ?? ""
            ];
            if (new Set(modifiers).size < modifiers.length) {
                return false;
            }
        }
        return true;
    },
    construct (data24) {
        const { regexp: regexp2 = `${data24}` , modifiers =""  } = `${data24}`.match(REGEXP)?.groups ?? {};
        return new RegExp(regexp2, modifiers);
    },
    predicate (object) {
        return object instanceof RegExp;
    },
    represent (object) {
        return object.toString();
    }
});
const seq = new Type1("tag:yaml.org,2002:seq", {
    construct (data25) {
        return data25 !== null ? data25 : [];
    },
    kind: "sequence"
});
const { hasOwn: hasOwn1  } = Object;
function resolveYamlSet(data26) {
    if (data26 === null) return true;
    for(const key in data26){
        if (hasOwn1(data26, key)) {
            if (data26[key] !== null) return false;
        }
    }
    return true;
}
function constructYamlSet(data27) {
    return data27 !== null ? data27 : {};
}
const set = new Type1("tag:yaml.org,2002:set", {
    construct: constructYamlSet,
    kind: "mapping",
    resolve: resolveYamlSet
});
const str = new Type1("tag:yaml.org,2002:str", {
    construct (data28) {
        return data28 !== null ? data28 : "";
    },
    kind: "scalar"
});
const YAML_DATE_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9])" + "-([0-9][0-9])$");
const YAML_TIMESTAMP_REGEXP = new RegExp("^([0-9][0-9][0-9][0-9])" + "-([0-9][0-9]?)" + "-([0-9][0-9]?)" + "(?:[Tt]|[ \\t]+)" + "([0-9][0-9]?)" + ":([0-9][0-9])" + ":([0-9][0-9])" + "(?:\\.([0-9]*))?" + "(?:[ \\t]*(Z|([-+])([0-9][0-9]?)" + "(?::([0-9][0-9]))?))?$");
function resolveYamlTimestamp(data29) {
    if (data29 === null) return false;
    if (YAML_DATE_REGEXP.exec(data29) !== null) return true;
    if (YAML_TIMESTAMP_REGEXP.exec(data29) !== null) return true;
    return false;
}
function constructYamlTimestamp(data30) {
    let match = YAML_DATE_REGEXP.exec(data30);
    if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data30);
    if (match === null) throw new Error("Date resolve error");
    const year = +match[1];
    const month = +match[2] - 1;
    const day = +match[3];
    if (!match[4]) {
        return new Date(Date.UTC(year, month, day));
    }
    const hour = +match[4];
    const minute = +match[5];
    const second = +match[6];
    let fraction = 0;
    if (match[7]) {
        let partFraction = match[7].slice(0, 3);
        while(partFraction.length < 3){
            partFraction += "0";
        }
        fraction = +partFraction;
    }
    let delta = null;
    if (match[9]) {
        const tzHour = +match[10];
        const tzMinute = +(match[11] || 0);
        delta = (tzHour * 60 + tzMinute) * 60000;
        if (match[9] === "-") delta = -delta;
    }
    const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
    if (delta) date.setTime(date.getTime() - delta);
    return date;
}
function representYamlTimestamp(date) {
    return date.toISOString();
}
const timestamp = new Type1("tag:yaml.org,2002:timestamp", {
    construct: constructYamlTimestamp,
    instanceOf: Date,
    kind: "scalar",
    represent: representYamlTimestamp,
    resolve: resolveYamlTimestamp
});
const undefinedType = new Type1("tag:yaml.org,2002:js/undefined", {
    kind: "scalar",
    resolve () {
        return true;
    },
    construct () {
        return undefined;
    },
    predicate (object) {
        return typeof object === "undefined";
    },
    represent () {
        return "";
    }
});
const failsafe = new Schema({
    explicit: [
        str,
        seq,
        map
    ]
});
const json = new Schema({
    implicit: [
        nil,
        bool,
        __int,
        __float
    ],
    include: [
        failsafe
    ]
});
const core = new Schema({
    include: [
        json
    ]
});
const def = new Schema({
    explicit: [
        binary,
        omap,
        pairs,
        set
    ],
    implicit: [
        timestamp,
        merge
    ],
    include: [
        core
    ]
});
new Schema({
    explicit: [
        regexp,
        undefinedType
    ],
    include: [
        def
    ]
});
class State {
    schema;
    constructor(schema = def){
        this.schema = schema;
    }
}
class LoaderState extends State {
    input;
    documents = [];
    length;
    lineIndent = 0;
    lineStart = 0;
    position = 0;
    line = 0;
    filename;
    onWarning;
    legacy;
    json;
    listener;
    implicitTypes;
    typeMap;
    version;
    checkLineBreaks;
    tagMap;
    anchorMap;
    tag;
    anchor;
    kind;
    result = "";
    constructor(input, { filename , schema , onWarning , legacy =false , json: json1 = false , listener =null  }){
        super(schema);
        this.input = input;
        this.filename = filename;
        this.onWarning = onWarning;
        this.legacy = legacy;
        this.json = json1;
        this.listener = listener;
        this.implicitTypes = this.schema.compiledImplicit;
        this.typeMap = this.schema.compiledTypeMap;
        this.length = input.length;
    }
}
const { hasOwn: hasOwn2  } = Object;
const CONTEXT_BLOCK_IN = 3;
const CONTEXT_BLOCK_OUT = 4;
const CHOMPING_STRIP = 2;
const CHOMPING_KEEP = 3;
const PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
const PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
const PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/;
const PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i;
const PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
function _class(obj) {
    return Object.prototype.toString.call(obj);
}
function isEOL(c) {
    return c === 10 || c === 13;
}
function isWhiteSpace(c) {
    return c === 9 || c === 32;
}
function isWsOrEol(c) {
    return c === 9 || c === 32 || c === 10 || c === 13;
}
function isFlowIndicator(c) {
    return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
}
function fromHexCode(c) {
    if (48 <= c && c <= 57) {
        return c - 48;
    }
    const lc = c | 32;
    if (97 <= lc && lc <= 102) {
        return lc - 97 + 10;
    }
    return -1;
}
function escapedHexLen(c) {
    if (c === 120) {
        return 2;
    }
    if (c === 117) {
        return 4;
    }
    if (c === 85) {
        return 8;
    }
    return 0;
}
function fromDecimalCode(c) {
    if (48 <= c && c <= 57) {
        return c - 48;
    }
    return -1;
}
function simpleEscapeSequence(c) {
    return c === 48 ? "\x00" : c === 97 ? "\x07" : c === 98 ? "\x08" : c === 116 ? "\x09" : c === 9 ? "\x09" : c === 110 ? "\x0A" : c === 118 ? "\x0B" : c === 102 ? "\x0C" : c === 114 ? "\x0D" : c === 101 ? "\x1B" : c === 32 ? " " : c === 34 ? "\x22" : c === 47 ? "/" : c === 92 ? "\x5C" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
}
function charFromCodepoint(c) {
    if (c <= 65535) {
        return String.fromCharCode(c);
    }
    return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
}
const simpleEscapeCheck = Array.from({
    length: 256
});
const simpleEscapeMap = Array.from({
    length: 256
});
for(let i78 = 0; i78 < 256; i78++){
    simpleEscapeCheck[i78] = simpleEscapeSequence(i78) ? 1 : 0;
    simpleEscapeMap[i78] = simpleEscapeSequence(i78);
}
function generateError(state1, message) {
    return new YAMLError(message, new Mark(state1.filename, state1.input, state1.position, state1.line, state1.position - state1.lineStart));
}
function throwError(state2, message) {
    throw generateError(state2, message);
}
function throwWarning(state3, message) {
    if (state3.onWarning) {
        state3.onWarning.call(null, generateError(state3, message));
    }
}
const directiveHandlers = {
    YAML (state4, _name, ...args) {
        if (state4.version !== null) {
            return throwError(state4, "duplication of %YAML directive");
        }
        if (args.length !== 1) {
            return throwError(state4, "YAML directive accepts exactly one argument");
        }
        const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
        if (match === null) {
            return throwError(state4, "ill-formed argument of the YAML directive");
        }
        const major = parseInt(match[1], 10);
        const minor = parseInt(match[2], 10);
        if (major !== 1) {
            return throwError(state4, "unacceptable YAML version of the document");
        }
        state4.version = args[0];
        state4.checkLineBreaks = minor < 2;
        if (minor !== 1 && minor !== 2) {
            return throwWarning(state4, "unsupported YAML version of the document");
        }
    },
    TAG (state5, _name, ...args) {
        if (args.length !== 2) {
            return throwError(state5, "TAG directive accepts exactly two arguments");
        }
        const handle = args[0];
        const prefix = args[1];
        if (!PATTERN_TAG_HANDLE.test(handle)) {
            return throwError(state5, "ill-formed tag handle (first argument) of the TAG directive");
        }
        if (state5.tagMap && hasOwn2(state5.tagMap, handle)) {
            return throwError(state5, `there is a previously declared suffix for "${handle}" tag handle`);
        }
        if (!PATTERN_TAG_URI.test(prefix)) {
            return throwError(state5, "ill-formed tag prefix (second argument) of the TAG directive");
        }
        if (typeof state5.tagMap === "undefined") {
            state5.tagMap = {};
        }
        state5.tagMap[handle] = prefix;
    }
};
function captureSegment(state6, start, end, checkJson) {
    let result;
    if (start < end) {
        result = state6.input.slice(start, end);
        if (checkJson) {
            for(let position = 0, length = result.length; position < length; position++){
                const character = result.charCodeAt(position);
                if (!(character === 9 || 32 <= character && character <= 1114111)) {
                    return throwError(state6, "expected valid JSON character");
                }
            }
        } else if (PATTERN_NON_PRINTABLE.test(result)) {
            return throwError(state6, "the stream contains non-printable characters");
        }
        state6.result += result;
    }
}
function mergeMappings(state7, destination, source, overridableKeys) {
    if (!isObject(source)) {
        return throwError(state7, "cannot merge mappings; the provided source object is unacceptable");
    }
    const keys4 = Object.keys(source);
    for(let i1 = 0, len1 = keys4.length; i1 < len1; i1++){
        const key = keys4[i1];
        if (!hasOwn2(destination, key)) {
            destination[key] = source[key];
            overridableKeys[key] = true;
        }
    }
}
function storeMappingPair(state8, result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) {
    if (Array.isArray(keyNode)) {
        keyNode = Array.prototype.slice.call(keyNode);
        for(let index = 0, quantity = keyNode.length; index < quantity; index++){
            if (Array.isArray(keyNode[index])) {
                return throwError(state8, "nested arrays are not supported inside keys");
            }
            if (typeof keyNode === "object" && _class(keyNode[index]) === "[object Object]") {
                keyNode[index] = "[object Object]";
            }
        }
    }
    if (typeof keyNode === "object" && _class(keyNode) === "[object Object]") {
        keyNode = "[object Object]";
    }
    keyNode = String(keyNode);
    if (result === null) {
        result = {};
    }
    if (keyTag === "tag:yaml.org,2002:merge") {
        if (Array.isArray(valueNode)) {
            for(let index = 0, quantity = valueNode.length; index < quantity; index++){
                mergeMappings(state8, result, valueNode[index], overridableKeys);
            }
        } else {
            mergeMappings(state8, result, valueNode, overridableKeys);
        }
    } else {
        if (!state8.json && !hasOwn2(overridableKeys, keyNode) && hasOwn2(result, keyNode)) {
            state8.line = startLine || state8.line;
            state8.position = startPos || state8.position;
            return throwError(state8, "duplicated mapping key");
        }
        result[keyNode] = valueNode;
        delete overridableKeys[keyNode];
    }
    return result;
}
function readLineBreak(state9) {
    const ch = state9.input.charCodeAt(state9.position);
    if (ch === 10) {
        state9.position++;
    } else if (ch === 13) {
        state9.position++;
        if (state9.input.charCodeAt(state9.position) === 10) {
            state9.position++;
        }
    } else {
        return throwError(state9, "a line break is expected");
    }
    state9.line += 1;
    state9.lineStart = state9.position;
}
function skipSeparationSpace(state10, allowComments, checkIndent) {
    let lineBreaks = 0, ch = state10.input.charCodeAt(state10.position);
    while(ch !== 0){
        while(isWhiteSpace(ch)){
            ch = state10.input.charCodeAt(++state10.position);
        }
        if (allowComments && ch === 35) {
            do {
                ch = state10.input.charCodeAt(++state10.position);
            }while (ch !== 10 && ch !== 13 && ch !== 0)
        }
        if (isEOL(ch)) {
            readLineBreak(state10);
            ch = state10.input.charCodeAt(state10.position);
            lineBreaks++;
            state10.lineIndent = 0;
            while(ch === 32){
                state10.lineIndent++;
                ch = state10.input.charCodeAt(++state10.position);
            }
        } else {
            break;
        }
    }
    if (checkIndent !== -1 && lineBreaks !== 0 && state10.lineIndent < checkIndent) {
        throwWarning(state10, "deficient indentation");
    }
    return lineBreaks;
}
function testDocumentSeparator(state11) {
    let _position = state11.position;
    let ch = state11.input.charCodeAt(_position);
    if ((ch === 45 || ch === 46) && ch === state11.input.charCodeAt(_position + 1) && ch === state11.input.charCodeAt(_position + 2)) {
        _position += 3;
        ch = state11.input.charCodeAt(_position);
        if (ch === 0 || isWsOrEol(ch)) {
            return true;
        }
    }
    return false;
}
function writeFoldedLines(state12, count) {
    if (count === 1) {
        state12.result += " ";
    } else if (count > 1) {
        state12.result += repeat("\n", count - 1);
    }
}
function readPlainScalar(state13, nodeIndent, withinFlowCollection) {
    const kind = state13.kind;
    const result = state13.result;
    let ch = state13.input.charCodeAt(state13.position);
    if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96) {
        return false;
    }
    let following;
    if (ch === 63 || ch === 45) {
        following = state13.input.charCodeAt(state13.position + 1);
        if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
            return false;
        }
    }
    state13.kind = "scalar";
    state13.result = "";
    let captureEnd, captureStart = captureEnd = state13.position;
    let hasPendingContent = false;
    let line = 0;
    while(ch !== 0){
        if (ch === 58) {
            following = state13.input.charCodeAt(state13.position + 1);
            if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
                break;
            }
        } else if (ch === 35) {
            const preceding = state13.input.charCodeAt(state13.position - 1);
            if (isWsOrEol(preceding)) {
                break;
            }
        } else if (state13.position === state13.lineStart && testDocumentSeparator(state13) || withinFlowCollection && isFlowIndicator(ch)) {
            break;
        } else if (isEOL(ch)) {
            line = state13.line;
            const lineStart = state13.lineStart;
            const lineIndent = state13.lineIndent;
            skipSeparationSpace(state13, false, -1);
            if (state13.lineIndent >= nodeIndent) {
                hasPendingContent = true;
                ch = state13.input.charCodeAt(state13.position);
                continue;
            } else {
                state13.position = captureEnd;
                state13.line = line;
                state13.lineStart = lineStart;
                state13.lineIndent = lineIndent;
                break;
            }
        }
        if (hasPendingContent) {
            captureSegment(state13, captureStart, captureEnd, false);
            writeFoldedLines(state13, state13.line - line);
            captureStart = captureEnd = state13.position;
            hasPendingContent = false;
        }
        if (!isWhiteSpace(ch)) {
            captureEnd = state13.position + 1;
        }
        ch = state13.input.charCodeAt(++state13.position);
    }
    captureSegment(state13, captureStart, captureEnd, false);
    if (state13.result) {
        return true;
    }
    state13.kind = kind;
    state13.result = result;
    return false;
}
function readSingleQuotedScalar(state14, nodeIndent) {
    let ch, captureStart, captureEnd;
    ch = state14.input.charCodeAt(state14.position);
    if (ch !== 39) {
        return false;
    }
    state14.kind = "scalar";
    state14.result = "";
    state14.position++;
    captureStart = captureEnd = state14.position;
    while((ch = state14.input.charCodeAt(state14.position)) !== 0){
        if (ch === 39) {
            captureSegment(state14, captureStart, state14.position, true);
            ch = state14.input.charCodeAt(++state14.position);
            if (ch === 39) {
                captureStart = state14.position;
                state14.position++;
                captureEnd = state14.position;
            } else {
                return true;
            }
        } else if (isEOL(ch)) {
            captureSegment(state14, captureStart, captureEnd, true);
            writeFoldedLines(state14, skipSeparationSpace(state14, false, nodeIndent));
            captureStart = captureEnd = state14.position;
        } else if (state14.position === state14.lineStart && testDocumentSeparator(state14)) {
            return throwError(state14, "unexpected end of the document within a single quoted scalar");
        } else {
            state14.position++;
            captureEnd = state14.position;
        }
    }
    return throwError(state14, "unexpected end of the stream within a single quoted scalar");
}
function readDoubleQuotedScalar(state15, nodeIndent) {
    let ch = state15.input.charCodeAt(state15.position);
    if (ch !== 34) {
        return false;
    }
    state15.kind = "scalar";
    state15.result = "";
    state15.position++;
    let captureEnd, captureStart = captureEnd = state15.position;
    let tmp;
    while((ch = state15.input.charCodeAt(state15.position)) !== 0){
        if (ch === 34) {
            captureSegment(state15, captureStart, state15.position, true);
            state15.position++;
            return true;
        }
        if (ch === 92) {
            captureSegment(state15, captureStart, state15.position, true);
            ch = state15.input.charCodeAt(++state15.position);
            if (isEOL(ch)) {
                skipSeparationSpace(state15, false, nodeIndent);
            } else if (ch < 256 && simpleEscapeCheck[ch]) {
                state15.result += simpleEscapeMap[ch];
                state15.position++;
            } else if ((tmp = escapedHexLen(ch)) > 0) {
                let hexLength = tmp;
                let hexResult = 0;
                for(; hexLength > 0; hexLength--){
                    ch = state15.input.charCodeAt(++state15.position);
                    if ((tmp = fromHexCode(ch)) >= 0) {
                        hexResult = (hexResult << 4) + tmp;
                    } else {
                        return throwError(state15, "expected hexadecimal character");
                    }
                }
                state15.result += charFromCodepoint(hexResult);
                state15.position++;
            } else {
                return throwError(state15, "unknown escape sequence");
            }
            captureStart = captureEnd = state15.position;
        } else if (isEOL(ch)) {
            captureSegment(state15, captureStart, captureEnd, true);
            writeFoldedLines(state15, skipSeparationSpace(state15, false, nodeIndent));
            captureStart = captureEnd = state15.position;
        } else if (state15.position === state15.lineStart && testDocumentSeparator(state15)) {
            return throwError(state15, "unexpected end of the document within a double quoted scalar");
        } else {
            state15.position++;
            captureEnd = state15.position;
        }
    }
    return throwError(state15, "unexpected end of the stream within a double quoted scalar");
}
function readFlowCollection(state16, nodeIndent) {
    let ch = state16.input.charCodeAt(state16.position);
    let terminator;
    let isMapping = true;
    let result = {};
    if (ch === 91) {
        terminator = 93;
        isMapping = false;
        result = [];
    } else if (ch === 123) {
        terminator = 125;
    } else {
        return false;
    }
    if (state16.anchor !== null && typeof state16.anchor != "undefined" && typeof state16.anchorMap != "undefined") {
        state16.anchorMap[state16.anchor] = result;
    }
    ch = state16.input.charCodeAt(++state16.position);
    const tag = state16.tag, anchor = state16.anchor;
    let readNext = true;
    let valueNode, keyNode, keyTag = keyNode = valueNode = null, isExplicitPair, isPair = isExplicitPair = false;
    let following = 0, line = 0;
    const overridableKeys = {};
    while(ch !== 0){
        skipSeparationSpace(state16, true, nodeIndent);
        ch = state16.input.charCodeAt(state16.position);
        if (ch === terminator) {
            state16.position++;
            state16.tag = tag;
            state16.anchor = anchor;
            state16.kind = isMapping ? "mapping" : "sequence";
            state16.result = result;
            return true;
        }
        if (!readNext) {
            return throwError(state16, "missed comma between flow collection entries");
        }
        keyTag = keyNode = valueNode = null;
        isPair = isExplicitPair = false;
        if (ch === 63) {
            following = state16.input.charCodeAt(state16.position + 1);
            if (isWsOrEol(following)) {
                isPair = isExplicitPair = true;
                state16.position++;
                skipSeparationSpace(state16, true, nodeIndent);
            }
        }
        line = state16.line;
        composeNode(state16, nodeIndent, 1, false, true);
        keyTag = state16.tag || null;
        keyNode = state16.result;
        skipSeparationSpace(state16, true, nodeIndent);
        ch = state16.input.charCodeAt(state16.position);
        if ((isExplicitPair || state16.line === line) && ch === 58) {
            isPair = true;
            ch = state16.input.charCodeAt(++state16.position);
            skipSeparationSpace(state16, true, nodeIndent);
            composeNode(state16, nodeIndent, 1, false, true);
            valueNode = state16.result;
        }
        if (isMapping) {
            storeMappingPair(state16, result, overridableKeys, keyTag, keyNode, valueNode);
        } else if (isPair) {
            result.push(storeMappingPair(state16, null, overridableKeys, keyTag, keyNode, valueNode));
        } else {
            result.push(keyNode);
        }
        skipSeparationSpace(state16, true, nodeIndent);
        ch = state16.input.charCodeAt(state16.position);
        if (ch === 44) {
            readNext = true;
            ch = state16.input.charCodeAt(++state16.position);
        } else {
            readNext = false;
        }
    }
    return throwError(state16, "unexpected end of the stream within a flow collection");
}
function readBlockScalar(state17, nodeIndent) {
    let chomping = 1, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false;
    let ch = state17.input.charCodeAt(state17.position);
    let folding = false;
    if (ch === 124) {
        folding = false;
    } else if (ch === 62) {
        folding = true;
    } else {
        return false;
    }
    state17.kind = "scalar";
    state17.result = "";
    let tmp = 0;
    while(ch !== 0){
        ch = state17.input.charCodeAt(++state17.position);
        if (ch === 43 || ch === 45) {
            if (1 === chomping) {
                chomping = ch === 43 ? CHOMPING_KEEP : CHOMPING_STRIP;
            } else {
                return throwError(state17, "repeat of a chomping mode identifier");
            }
        } else if ((tmp = fromDecimalCode(ch)) >= 0) {
            if (tmp === 0) {
                return throwError(state17, "bad explicit indentation width of a block scalar; it cannot be less than one");
            } else if (!detectedIndent) {
                textIndent = nodeIndent + tmp - 1;
                detectedIndent = true;
            } else {
                return throwError(state17, "repeat of an indentation width identifier");
            }
        } else {
            break;
        }
    }
    if (isWhiteSpace(ch)) {
        do {
            ch = state17.input.charCodeAt(++state17.position);
        }while (isWhiteSpace(ch))
        if (ch === 35) {
            do {
                ch = state17.input.charCodeAt(++state17.position);
            }while (!isEOL(ch) && ch !== 0)
        }
    }
    while(ch !== 0){
        readLineBreak(state17);
        state17.lineIndent = 0;
        ch = state17.input.charCodeAt(state17.position);
        while((!detectedIndent || state17.lineIndent < textIndent) && ch === 32){
            state17.lineIndent++;
            ch = state17.input.charCodeAt(++state17.position);
        }
        if (!detectedIndent && state17.lineIndent > textIndent) {
            textIndent = state17.lineIndent;
        }
        if (isEOL(ch)) {
            emptyLines++;
            continue;
        }
        if (state17.lineIndent < textIndent) {
            if (chomping === 3) {
                state17.result += repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (chomping === 1) {
                if (didReadContent) {
                    state17.result += "\n";
                }
            }
            break;
        }
        if (folding) {
            if (isWhiteSpace(ch)) {
                atMoreIndented = true;
                state17.result += repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (atMoreIndented) {
                atMoreIndented = false;
                state17.result += repeat("\n", emptyLines + 1);
            } else if (emptyLines === 0) {
                if (didReadContent) {
                    state17.result += " ";
                }
            } else {
                state17.result += repeat("\n", emptyLines);
            }
        } else {
            state17.result += repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
        }
        didReadContent = true;
        detectedIndent = true;
        emptyLines = 0;
        const captureStart = state17.position;
        while(!isEOL(ch) && ch !== 0){
            ch = state17.input.charCodeAt(++state17.position);
        }
        captureSegment(state17, captureStart, state17.position, false);
    }
    return true;
}
function readBlockSequence(state18, nodeIndent) {
    let line, following, detected = false, ch;
    const tag = state18.tag, anchor = state18.anchor, result = [];
    if (state18.anchor !== null && typeof state18.anchor !== "undefined" && typeof state18.anchorMap !== "undefined") {
        state18.anchorMap[state18.anchor] = result;
    }
    ch = state18.input.charCodeAt(state18.position);
    while(ch !== 0){
        if (ch !== 45) {
            break;
        }
        following = state18.input.charCodeAt(state18.position + 1);
        if (!isWsOrEol(following)) {
            break;
        }
        detected = true;
        state18.position++;
        if (skipSeparationSpace(state18, true, -1)) {
            if (state18.lineIndent <= nodeIndent) {
                result.push(null);
                ch = state18.input.charCodeAt(state18.position);
                continue;
            }
        }
        line = state18.line;
        composeNode(state18, nodeIndent, 3, false, true);
        result.push(state18.result);
        skipSeparationSpace(state18, true, -1);
        ch = state18.input.charCodeAt(state18.position);
        if ((state18.line === line || state18.lineIndent > nodeIndent) && ch !== 0) {
            return throwError(state18, "bad indentation of a sequence entry");
        } else if (state18.lineIndent < nodeIndent) {
            break;
        }
    }
    if (detected) {
        state18.tag = tag;
        state18.anchor = anchor;
        state18.kind = "sequence";
        state18.result = result;
        return true;
    }
    return false;
}
function readBlockMapping(state19, nodeIndent, flowIndent) {
    const tag = state19.tag, anchor = state19.anchor, result = {}, overridableKeys = {};
    let following, allowCompact = false, line, pos, keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
    if (state19.anchor !== null && typeof state19.anchor !== "undefined" && typeof state19.anchorMap !== "undefined") {
        state19.anchorMap[state19.anchor] = result;
    }
    ch = state19.input.charCodeAt(state19.position);
    while(ch !== 0){
        following = state19.input.charCodeAt(state19.position + 1);
        line = state19.line;
        pos = state19.position;
        if ((ch === 63 || ch === 58) && isWsOrEol(following)) {
            if (ch === 63) {
                if (atExplicitKey) {
                    storeMappingPair(state19, result, overridableKeys, keyTag, keyNode, null);
                    keyTag = keyNode = valueNode = null;
                }
                detected = true;
                atExplicitKey = true;
                allowCompact = true;
            } else if (atExplicitKey) {
                atExplicitKey = false;
                allowCompact = true;
            } else {
                return throwError(state19, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
            }
            state19.position += 1;
            ch = following;
        } else if (composeNode(state19, flowIndent, 2, false, true)) {
            if (state19.line === line) {
                ch = state19.input.charCodeAt(state19.position);
                while(isWhiteSpace(ch)){
                    ch = state19.input.charCodeAt(++state19.position);
                }
                if (ch === 58) {
                    ch = state19.input.charCodeAt(++state19.position);
                    if (!isWsOrEol(ch)) {
                        return throwError(state19, "a whitespace character is expected after the key-value separator within a block mapping");
                    }
                    if (atExplicitKey) {
                        storeMappingPair(state19, result, overridableKeys, keyTag, keyNode, null);
                        keyTag = keyNode = valueNode = null;
                    }
                    detected = true;
                    atExplicitKey = false;
                    allowCompact = false;
                    keyTag = state19.tag;
                    keyNode = state19.result;
                } else if (detected) {
                    return throwError(state19, "can not read an implicit mapping pair; a colon is missed");
                } else {
                    state19.tag = tag;
                    state19.anchor = anchor;
                    return true;
                }
            } else if (detected) {
                return throwError(state19, "can not read a block mapping entry; a multiline key may not be an implicit key");
            } else {
                state19.tag = tag;
                state19.anchor = anchor;
                return true;
            }
        } else {
            break;
        }
        if (state19.line === line || state19.lineIndent > nodeIndent) {
            if (composeNode(state19, nodeIndent, 4, true, allowCompact)) {
                if (atExplicitKey) {
                    keyNode = state19.result;
                } else {
                    valueNode = state19.result;
                }
            }
            if (!atExplicitKey) {
                storeMappingPair(state19, result, overridableKeys, keyTag, keyNode, valueNode, line, pos);
                keyTag = keyNode = valueNode = null;
            }
            skipSeparationSpace(state19, true, -1);
            ch = state19.input.charCodeAt(state19.position);
        }
        if (state19.lineIndent > nodeIndent && ch !== 0) {
            return throwError(state19, "bad indentation of a mapping entry");
        } else if (state19.lineIndent < nodeIndent) {
            break;
        }
    }
    if (atExplicitKey) {
        storeMappingPair(state19, result, overridableKeys, keyTag, keyNode, null);
    }
    if (detected) {
        state19.tag = tag;
        state19.anchor = anchor;
        state19.kind = "mapping";
        state19.result = result;
    }
    return detected;
}
function readTagProperty(state20) {
    let position, isVerbatim = false, isNamed = false, tagHandle = "", tagName, ch;
    ch = state20.input.charCodeAt(state20.position);
    if (ch !== 33) return false;
    if (state20.tag !== null) {
        return throwError(state20, "duplication of a tag property");
    }
    ch = state20.input.charCodeAt(++state20.position);
    if (ch === 60) {
        isVerbatim = true;
        ch = state20.input.charCodeAt(++state20.position);
    } else if (ch === 33) {
        isNamed = true;
        tagHandle = "!!";
        ch = state20.input.charCodeAt(++state20.position);
    } else {
        tagHandle = "!";
    }
    position = state20.position;
    if (isVerbatim) {
        do {
            ch = state20.input.charCodeAt(++state20.position);
        }while (ch !== 0 && ch !== 62)
        if (state20.position < state20.length) {
            tagName = state20.input.slice(position, state20.position);
            ch = state20.input.charCodeAt(++state20.position);
        } else {
            return throwError(state20, "unexpected end of the stream within a verbatim tag");
        }
    } else {
        while(ch !== 0 && !isWsOrEol(ch)){
            if (ch === 33) {
                if (!isNamed) {
                    tagHandle = state20.input.slice(position - 1, state20.position + 1);
                    if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
                        return throwError(state20, "named tag handle cannot contain such characters");
                    }
                    isNamed = true;
                    position = state20.position + 1;
                } else {
                    return throwError(state20, "tag suffix cannot contain exclamation marks");
                }
            }
            ch = state20.input.charCodeAt(++state20.position);
        }
        tagName = state20.input.slice(position, state20.position);
        if (PATTERN_FLOW_INDICATORS.test(tagName)) {
            return throwError(state20, "tag suffix cannot contain flow indicator characters");
        }
    }
    if (tagName && !PATTERN_TAG_URI.test(tagName)) {
        return throwError(state20, `tag name cannot contain such characters: ${tagName}`);
    }
    if (isVerbatim) {
        state20.tag = tagName;
    } else if (typeof state20.tagMap !== "undefined" && hasOwn2(state20.tagMap, tagHandle)) {
        state20.tag = state20.tagMap[tagHandle] + tagName;
    } else if (tagHandle === "!") {
        state20.tag = `!${tagName}`;
    } else if (tagHandle === "!!") {
        state20.tag = `tag:yaml.org,2002:${tagName}`;
    } else {
        return throwError(state20, `undeclared tag handle "${tagHandle}"`);
    }
    return true;
}
function readAnchorProperty(state21) {
    let ch = state21.input.charCodeAt(state21.position);
    if (ch !== 38) return false;
    if (state21.anchor !== null) {
        return throwError(state21, "duplication of an anchor property");
    }
    ch = state21.input.charCodeAt(++state21.position);
    const position = state21.position;
    while(ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)){
        ch = state21.input.charCodeAt(++state21.position);
    }
    if (state21.position === position) {
        return throwError(state21, "name of an anchor node must contain at least one character");
    }
    state21.anchor = state21.input.slice(position, state21.position);
    return true;
}
function readAlias(state22) {
    let ch = state22.input.charCodeAt(state22.position);
    if (ch !== 42) return false;
    ch = state22.input.charCodeAt(++state22.position);
    const _position = state22.position;
    while(ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)){
        ch = state22.input.charCodeAt(++state22.position);
    }
    if (state22.position === _position) {
        return throwError(state22, "name of an alias node must contain at least one character");
    }
    const alias = state22.input.slice(_position, state22.position);
    if (typeof state22.anchorMap !== "undefined" && !hasOwn2(state22.anchorMap, alias)) {
        return throwError(state22, `unidentified alias "${alias}"`);
    }
    if (typeof state22.anchorMap !== "undefined") {
        state22.result = state22.anchorMap[alias];
    }
    skipSeparationSpace(state22, true, -1);
    return true;
}
function composeNode(state23, parentIndent, nodeContext, allowToSeek, allowCompact) {
    let allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, type, flowIndent, blockIndent;
    if (state23.listener && state23.listener !== null) {
        state23.listener("open", state23);
    }
    state23.tag = null;
    state23.anchor = null;
    state23.kind = null;
    state23.result = null;
    const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
    if (allowToSeek) {
        if (skipSeparationSpace(state23, true, -1)) {
            atNewLine = true;
            if (state23.lineIndent > parentIndent) {
                indentStatus = 1;
            } else if (state23.lineIndent === parentIndent) {
                indentStatus = 0;
            } else if (state23.lineIndent < parentIndent) {
                indentStatus = -1;
            }
        }
    }
    if (indentStatus === 1) {
        while(readTagProperty(state23) || readAnchorProperty(state23)){
            if (skipSeparationSpace(state23, true, -1)) {
                atNewLine = true;
                allowBlockCollections = allowBlockStyles;
                if (state23.lineIndent > parentIndent) {
                    indentStatus = 1;
                } else if (state23.lineIndent === parentIndent) {
                    indentStatus = 0;
                } else if (state23.lineIndent < parentIndent) {
                    indentStatus = -1;
                }
            } else {
                allowBlockCollections = false;
            }
        }
    }
    if (allowBlockCollections) {
        allowBlockCollections = atNewLine || allowCompact;
    }
    if (indentStatus === 1 || 4 === nodeContext) {
        const cond = 1 === nodeContext || 2 === nodeContext;
        flowIndent = cond ? parentIndent : parentIndent + 1;
        blockIndent = state23.position - state23.lineStart;
        if (indentStatus === 1) {
            if (allowBlockCollections && (readBlockSequence(state23, blockIndent) || readBlockMapping(state23, blockIndent, flowIndent)) || readFlowCollection(state23, flowIndent)) {
                hasContent = true;
            } else {
                if (allowBlockScalars && readBlockScalar(state23, flowIndent) || readSingleQuotedScalar(state23, flowIndent) || readDoubleQuotedScalar(state23, flowIndent)) {
                    hasContent = true;
                } else if (readAlias(state23)) {
                    hasContent = true;
                    if (state23.tag !== null || state23.anchor !== null) {
                        return throwError(state23, "alias node should not have Any properties");
                    }
                } else if (readPlainScalar(state23, flowIndent, 1 === nodeContext)) {
                    hasContent = true;
                    if (state23.tag === null) {
                        state23.tag = "?";
                    }
                }
                if (state23.anchor !== null && typeof state23.anchorMap !== "undefined") {
                    state23.anchorMap[state23.anchor] = state23.result;
                }
            }
        } else if (indentStatus === 0) {
            hasContent = allowBlockCollections && readBlockSequence(state23, blockIndent);
        }
    }
    if (state23.tag !== null && state23.tag !== "!") {
        if (state23.tag === "?") {
            for(let typeIndex = 0, typeQuantity = state23.implicitTypes.length; typeIndex < typeQuantity; typeIndex++){
                type = state23.implicitTypes[typeIndex];
                if (type.resolve(state23.result)) {
                    state23.result = type.construct(state23.result);
                    state23.tag = type.tag;
                    if (state23.anchor !== null && typeof state23.anchorMap !== "undefined") {
                        state23.anchorMap[state23.anchor] = state23.result;
                    }
                    break;
                }
            }
        } else if (hasOwn2(state23.typeMap[state23.kind || "fallback"], state23.tag)) {
            type = state23.typeMap[state23.kind || "fallback"][state23.tag];
            if (state23.result !== null && type.kind !== state23.kind) {
                return throwError(state23, `unacceptable node kind for !<${state23.tag}> tag; it should be "${type.kind}", not "${state23.kind}"`);
            }
            if (!type.resolve(state23.result)) {
                return throwError(state23, `cannot resolve a node with !<${state23.tag}> explicit tag`);
            } else {
                state23.result = type.construct(state23.result);
                if (state23.anchor !== null && typeof state23.anchorMap !== "undefined") {
                    state23.anchorMap[state23.anchor] = state23.result;
                }
            }
        } else {
            return throwError(state23, `unknown tag !<${state23.tag}>`);
        }
    }
    if (state23.listener && state23.listener !== null) {
        state23.listener("close", state23);
    }
    return state23.tag !== null || state23.anchor !== null || hasContent;
}
function readDocument(state24) {
    const documentStart = state24.position;
    let position, directiveName, directiveArgs, hasDirectives = false, ch;
    state24.version = null;
    state24.checkLineBreaks = state24.legacy;
    state24.tagMap = {};
    state24.anchorMap = {};
    while((ch = state24.input.charCodeAt(state24.position)) !== 0){
        skipSeparationSpace(state24, true, -1);
        ch = state24.input.charCodeAt(state24.position);
        if (state24.lineIndent > 0 || ch !== 37) {
            break;
        }
        hasDirectives = true;
        ch = state24.input.charCodeAt(++state24.position);
        position = state24.position;
        while(ch !== 0 && !isWsOrEol(ch)){
            ch = state24.input.charCodeAt(++state24.position);
        }
        directiveName = state24.input.slice(position, state24.position);
        directiveArgs = [];
        if (directiveName.length < 1) {
            return throwError(state24, "directive name must not be less than one character in length");
        }
        while(ch !== 0){
            while(isWhiteSpace(ch)){
                ch = state24.input.charCodeAt(++state24.position);
            }
            if (ch === 35) {
                do {
                    ch = state24.input.charCodeAt(++state24.position);
                }while (ch !== 0 && !isEOL(ch))
                break;
            }
            if (isEOL(ch)) break;
            position = state24.position;
            while(ch !== 0 && !isWsOrEol(ch)){
                ch = state24.input.charCodeAt(++state24.position);
            }
            directiveArgs.push(state24.input.slice(position, state24.position));
        }
        if (ch !== 0) readLineBreak(state24);
        if (hasOwn2(directiveHandlers, directiveName)) {
            directiveHandlers[directiveName](state24, directiveName, ...directiveArgs);
        } else {
            throwWarning(state24, `unknown document directive "${directiveName}"`);
        }
    }
    skipSeparationSpace(state24, true, -1);
    if (state24.lineIndent === 0 && state24.input.charCodeAt(state24.position) === 45 && state24.input.charCodeAt(state24.position + 1) === 45 && state24.input.charCodeAt(state24.position + 2) === 45) {
        state24.position += 3;
        skipSeparationSpace(state24, true, -1);
    } else if (hasDirectives) {
        return throwError(state24, "directives end mark is expected");
    }
    composeNode(state24, state24.lineIndent - 1, 4, false, true);
    skipSeparationSpace(state24, true, -1);
    if (state24.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state24.input.slice(documentStart, state24.position))) {
        throwWarning(state24, "non-ASCII line breaks are interpreted as content");
    }
    state24.documents.push(state24.result);
    if (state24.position === state24.lineStart && testDocumentSeparator(state24)) {
        if (state24.input.charCodeAt(state24.position) === 46) {
            state24.position += 3;
            skipSeparationSpace(state24, true, -1);
        }
        return;
    }
    if (state24.position < state24.length - 1) {
        return throwError(state24, "end of the stream or a document separator is expected");
    } else {
        return;
    }
}
function loadDocuments(input, options) {
    input = String(input);
    options = options || {};
    if (input.length !== 0) {
        if (input.charCodeAt(input.length - 1) !== 10 && input.charCodeAt(input.length - 1) !== 13) {
            input += "\n";
        }
        if (input.charCodeAt(0) === 65279) {
            input = input.slice(1);
        }
    }
    const state25 = new LoaderState(input, options);
    state25.input += "\0";
    while(state25.input.charCodeAt(state25.position) === 32){
        state25.lineIndent += 1;
        state25.position += 1;
    }
    while(state25.position < state25.length - 1){
        readDocument(state25);
    }
    return state25.documents;
}
function load(input, options) {
    const documents = loadDocuments(input, options);
    if (documents.length === 0) {
        return;
    }
    if (documents.length === 1) {
        return documents[0];
    }
    throw new YAMLError("expected a single document in the stream, but found more");
}
function parse3(content, options) {
    return load(content, options);
}
const { hasOwn: hasOwn3  } = Object;
function compileStyleMap(schema, map4) {
    if (typeof map4 === "undefined" || map4 === null) return {};
    let type;
    const result = {};
    const keys5 = Object.keys(map4);
    let tag, style;
    for(let index = 0, length = keys5.length; index < length; index += 1){
        tag = keys5[index];
        style = String(map4[tag]);
        if (tag.slice(0, 2) === "!!") {
            tag = `tag:yaml.org,2002:${tag.slice(2)}`;
        }
        type = schema.compiledTypeMap.fallback[tag];
        if (type && typeof type.styleAliases !== "undefined" && hasOwn3(type.styleAliases, style)) {
            style = type.styleAliases[style];
        }
        result[tag] = style;
    }
    return result;
}
class DumperState extends State {
    indent;
    noArrayIndent;
    skipInvalid;
    flowLevel;
    sortKeys;
    lineWidth;
    noRefs;
    noCompatMode;
    condenseFlow;
    implicitTypes;
    explicitTypes;
    tag = null;
    result = "";
    duplicates = [];
    usedDuplicates = [];
    styleMap;
    dump;
    constructor({ schema , indent =2 , noArrayIndent =false , skipInvalid =false , flowLevel =-1 , styles =null , sortKeys =false , lineWidth =80 , noRefs =false , noCompatMode =false , condenseFlow =false  }){
        super(schema);
        this.indent = Math.max(1, indent);
        this.noArrayIndent = noArrayIndent;
        this.skipInvalid = skipInvalid;
        this.flowLevel = flowLevel;
        this.styleMap = compileStyleMap(this.schema, styles);
        this.sortKeys = sortKeys;
        this.lineWidth = lineWidth;
        this.noRefs = noRefs;
        this.noCompatMode = noCompatMode;
        this.condenseFlow = condenseFlow;
        this.implicitTypes = this.schema.compiledImplicit;
        this.explicitTypes = this.schema.compiledExplicit;
    }
}
const _toString2 = Object.prototype.toString;
const { hasOwn: hasOwn4  } = Object;
const ESCAPE_SEQUENCES = {};
ESCAPE_SEQUENCES[0] = "\\0";
ESCAPE_SEQUENCES[7] = "\\a";
ESCAPE_SEQUENCES[8] = "\\b";
ESCAPE_SEQUENCES[9] = "\\t";
ESCAPE_SEQUENCES[10] = "\\n";
ESCAPE_SEQUENCES[11] = "\\v";
ESCAPE_SEQUENCES[12] = "\\f";
ESCAPE_SEQUENCES[13] = "\\r";
ESCAPE_SEQUENCES[27] = "\\e";
ESCAPE_SEQUENCES[34] = '\\"';
ESCAPE_SEQUENCES[92] = "\\\\";
ESCAPE_SEQUENCES[133] = "\\N";
ESCAPE_SEQUENCES[160] = "\\_";
ESCAPE_SEQUENCES[8232] = "\\L";
ESCAPE_SEQUENCES[8233] = "\\P";
const DEPRECATED_BOOLEANS_SYNTAX = [
    "y",
    "Y",
    "yes",
    "Yes",
    "YES",
    "on",
    "On",
    "ON",
    "n",
    "N",
    "no",
    "No",
    "NO",
    "off",
    "Off",
    "OFF", 
];
function encodeHex(character) {
    const string4 = character.toString(16).toUpperCase();
    let handle;
    let length;
    if (character <= 255) {
        handle = "x";
        length = 2;
    } else if (character <= 65535) {
        handle = "u";
        length = 4;
    } else if (character <= 4294967295) {
        handle = "U";
        length = 8;
    } else {
        throw new YAMLError("code point within a string may not be greater than 0xFFFFFFFF");
    }
    return `\\${handle}${repeat("0", length - string4.length)}${string4}`;
}
function indentString(string5, spaces) {
    const ind = repeat(" ", spaces), length = string5.length;
    let position = 0, next = -1, result = "", line;
    while(position < length){
        next = string5.indexOf("\n", position);
        if (next === -1) {
            line = string5.slice(position);
            position = length;
        } else {
            line = string5.slice(position, next + 1);
            position = next + 1;
        }
        if (line.length && line !== "\n") result += ind;
        result += line;
    }
    return result;
}
function generateNextLine(state26, level) {
    return `\n${repeat(" ", state26.indent * level)}`;
}
function testImplicitResolving(state27, str56) {
    let type;
    for(let index = 0, length = state27.implicitTypes.length; index < length; index += 1){
        type = state27.implicitTypes[index];
        if (type.resolve(str56)) {
            return true;
        }
    }
    return false;
}
function isWhitespace(c) {
    return c === 32 || c === 9;
}
function isPrintable(c) {
    return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== 65279 || 65536 <= c && c <= 1114111;
}
function isPlainSafe(c) {
    return isPrintable(c) && c !== 65279 && c !== 44 && c !== 91 && c !== 93 && c !== 123 && c !== 125 && c !== 58 && c !== 35;
}
function isPlainSafeFirst(c) {
    return isPrintable(c) && c !== 65279 && !isWhitespace(c) && c !== 45 && c !== 63 && c !== 58 && c !== 44 && c !== 91 && c !== 93 && c !== 123 && c !== 125 && c !== 35 && c !== 38 && c !== 42 && c !== 33 && c !== 124 && c !== 62 && c !== 39 && c !== 34 && c !== 37 && c !== 64 && c !== 96;
}
function needIndentIndicator(string6) {
    const leadingSpaceRe = /^\n* /;
    return leadingSpaceRe.test(string6);
}
const STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5;
function chooseScalarStyle(string7, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
    const shouldTrackWidth = lineWidth !== -1;
    let hasLineBreak = false, hasFoldableLine = false, previousLineBreak = -1, plain = isPlainSafeFirst(string7.charCodeAt(0)) && !isWhitespace(string7.charCodeAt(string7.length - 1));
    let __char, i28;
    if (singleLineOnly) {
        for(i28 = 0; i28 < string7.length; i28++){
            __char = string7.charCodeAt(i28);
            if (!isPrintable(__char)) {
                return 5;
            }
            plain = plain && isPlainSafe(__char);
        }
    } else {
        for(i28 = 0; i28 < string7.length; i28++){
            __char = string7.charCodeAt(i28);
            if (__char === 10) {
                hasLineBreak = true;
                if (shouldTrackWidth) {
                    hasFoldableLine = hasFoldableLine || i28 - previousLineBreak - 1 > lineWidth && string7[previousLineBreak + 1] !== " ";
                    previousLineBreak = i28;
                }
            } else if (!isPrintable(__char)) {
                return 5;
            }
            plain = plain && isPlainSafe(__char);
        }
        hasFoldableLine = hasFoldableLine || shouldTrackWidth && i28 - previousLineBreak - 1 > lineWidth && string7[previousLineBreak + 1] !== " ";
    }
    if (!hasLineBreak && !hasFoldableLine) {
        return plain && !testAmbiguousType(string7) ? 1 : 2;
    }
    if (indentPerLevel > 9 && needIndentIndicator(string7)) {
        return 5;
    }
    return hasFoldableLine ? 4 : 3;
}
function foldLine(line, width) {
    if (line === "" || line[0] === " ") return line;
    const breakRe = / [^ ]/g;
    let match;
    let start = 0, end, curr = 0, next = 0;
    let result = "";
    while(match = breakRe.exec(line)){
        next = match.index;
        if (next - start > width) {
            end = curr > start ? curr : next;
            result += `\n${line.slice(start, end)}`;
            start = end + 1;
        }
        curr = next;
    }
    result += "\n";
    if (line.length - start > width && curr > start) {
        result += `${line.slice(start, curr)}\n${line.slice(curr + 1)}`;
    } else {
        result += line.slice(start);
    }
    return result.slice(1);
}
function dropEndingNewline(string8) {
    return string8[string8.length - 1] === "\n" ? string8.slice(0, -1) : string8;
}
function foldString(string9, width) {
    const lineRe = /(\n+)([^\n]*)/g;
    let result = (()=>{
        let nextLF = string9.indexOf("\n");
        nextLF = nextLF !== -1 ? nextLF : string9.length;
        lineRe.lastIndex = nextLF;
        return foldLine(string9.slice(0, nextLF), width);
    })();
    let prevMoreIndented = string9[0] === "\n" || string9[0] === " ";
    let moreIndented;
    let match;
    while(match = lineRe.exec(string9)){
        const prefix = match[1], line = match[2];
        moreIndented = line[0] === " ";
        result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
        prevMoreIndented = moreIndented;
    }
    return result;
}
function escapeString(string10) {
    let result = "";
    let __char, nextChar;
    let escapeSeq;
    for(let i29 = 0; i29 < string10.length; i29++){
        __char = string10.charCodeAt(i29);
        if (__char >= 55296 && __char <= 56319) {
            nextChar = string10.charCodeAt(i29 + 1);
            if (nextChar >= 56320 && nextChar <= 57343) {
                result += encodeHex((__char - 55296) * 1024 + nextChar - 56320 + 65536);
                i29++;
                continue;
            }
        }
        escapeSeq = ESCAPE_SEQUENCES[__char];
        result += !escapeSeq && isPrintable(__char) ? string10[i29] : escapeSeq || encodeHex(__char);
    }
    return result;
}
function blockHeader(string11, indentPerLevel) {
    const indentIndicator = needIndentIndicator(string11) ? String(indentPerLevel) : "";
    const clip = string11[string11.length - 1] === "\n";
    const keep = clip && (string11[string11.length - 2] === "\n" || string11 === "\n");
    const chomp = keep ? "+" : clip ? "" : "-";
    return `${indentIndicator}${chomp}\n`;
}
function writeScalar(state28, string12, level, iskey) {
    state28.dump = (()=>{
        if (string12.length === 0) {
            return "''";
        }
        if (!state28.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string12) !== -1) {
            return `'${string12}'`;
        }
        const indent = state28.indent * Math.max(1, level);
        const lineWidth = state28.lineWidth === -1 ? -1 : Math.max(Math.min(state28.lineWidth, 40), state28.lineWidth - indent);
        const singleLineOnly = iskey || state28.flowLevel > -1 && level >= state28.flowLevel;
        function testAmbiguity(str57) {
            return testImplicitResolving(state28, str57);
        }
        switch(chooseScalarStyle(string12, singleLineOnly, state28.indent, lineWidth, testAmbiguity)){
            case STYLE_PLAIN:
                return string12;
            case STYLE_SINGLE:
                return `'${string12.replace(/'/g, "''")}'`;
            case STYLE_LITERAL:
                return `|${blockHeader(string12, state28.indent)}${dropEndingNewline(indentString(string12, indent))}`;
            case STYLE_FOLDED:
                return `>${blockHeader(string12, state28.indent)}${dropEndingNewline(indentString(foldString(string12, lineWidth), indent))}`;
            case STYLE_DOUBLE:
                return `"${escapeString(string12)}"`;
            default:
                throw new YAMLError("impossible error: invalid scalar style");
        }
    })();
}
function writeFlowSequence(state29, level, object) {
    let _result = "";
    const _tag = state29.tag;
    for(let index = 0, length = object.length; index < length; index += 1){
        if (writeNode(state29, level, object[index], false, false)) {
            if (index !== 0) _result += `,${!state29.condenseFlow ? " " : ""}`;
            _result += state29.dump;
        }
    }
    state29.tag = _tag;
    state29.dump = `[${_result}]`;
}
function writeBlockSequence(state30, level, object, compact = false) {
    let _result = "";
    const _tag = state30.tag;
    for(let index = 0, length = object.length; index < length; index += 1){
        if (writeNode(state30, level + 1, object[index], true, true)) {
            if (!compact || index !== 0) {
                _result += generateNextLine(state30, level);
            }
            if (state30.dump && 10 === state30.dump.charCodeAt(0)) {
                _result += "-";
            } else {
                _result += "- ";
            }
            _result += state30.dump;
        }
    }
    state30.tag = _tag;
    state30.dump = _result || "[]";
}
function writeFlowMapping(state31, level, object) {
    let _result = "";
    const _tag = state31.tag, objectKeyList = Object.keys(object);
    let pairBuffer, objectKey, objectValue;
    for(let index = 0, length = objectKeyList.length; index < length; index += 1){
        pairBuffer = state31.condenseFlow ? '"' : "";
        if (index !== 0) pairBuffer += ", ";
        objectKey = objectKeyList[index];
        objectValue = object[objectKey];
        if (!writeNode(state31, level, objectKey, false, false)) {
            continue;
        }
        if (state31.dump.length > 1024) pairBuffer += "? ";
        pairBuffer += `${state31.dump}${state31.condenseFlow ? '"' : ""}:${state31.condenseFlow ? "" : " "}`;
        if (!writeNode(state31, level, objectValue, false, false)) {
            continue;
        }
        pairBuffer += state31.dump;
        _result += pairBuffer;
    }
    state31.tag = _tag;
    state31.dump = `{${_result}}`;
}
function writeBlockMapping(state32, level, object, compact = false) {
    const _tag = state32.tag, objectKeyList = Object.keys(object);
    let _result = "";
    if (state32.sortKeys === true) {
        objectKeyList.sort();
    } else if (typeof state32.sortKeys === "function") {
        objectKeyList.sort(state32.sortKeys);
    } else if (state32.sortKeys) {
        throw new YAMLError("sortKeys must be a boolean or a function");
    }
    let pairBuffer = "", objectKey, objectValue, explicitPair;
    for(let index = 0, length = objectKeyList.length; index < length; index += 1){
        pairBuffer = "";
        if (!compact || index !== 0) {
            pairBuffer += generateNextLine(state32, level);
        }
        objectKey = objectKeyList[index];
        objectValue = object[objectKey];
        if (!writeNode(state32, level + 1, objectKey, true, true, true)) {
            continue;
        }
        explicitPair = state32.tag !== null && state32.tag !== "?" || state32.dump && state32.dump.length > 1024;
        if (explicitPair) {
            if (state32.dump && 10 === state32.dump.charCodeAt(0)) {
                pairBuffer += "?";
            } else {
                pairBuffer += "? ";
            }
        }
        pairBuffer += state32.dump;
        if (explicitPair) {
            pairBuffer += generateNextLine(state32, level);
        }
        if (!writeNode(state32, level + 1, objectValue, true, explicitPair)) {
            continue;
        }
        if (state32.dump && 10 === state32.dump.charCodeAt(0)) {
            pairBuffer += ":";
        } else {
            pairBuffer += ": ";
        }
        pairBuffer += state32.dump;
        _result += pairBuffer;
    }
    state32.tag = _tag;
    state32.dump = _result || "{}";
}
function detectType(state33, object, explicit = false) {
    const typeList = explicit ? state33.explicitTypes : state33.implicitTypes;
    let type;
    let style;
    let _result;
    for(let index = 0, length = typeList.length; index < length; index += 1){
        type = typeList[index];
        if ((type.instanceOf || type.predicate) && (!type.instanceOf || typeof object === "object" && object instanceof type.instanceOf) && (!type.predicate || type.predicate(object))) {
            state33.tag = explicit ? type.tag : "?";
            if (type.represent) {
                style = state33.styleMap[type.tag] || type.defaultStyle;
                if (_toString2.call(type.represent) === "[object Function]") {
                    _result = type.represent(object, style);
                } else if (hasOwn4(type.represent, style)) {
                    _result = type.represent[style](object, style);
                } else {
                    throw new YAMLError(`!<${type.tag}> tag resolver accepts not "${style}" style`);
                }
                state33.dump = _result;
            }
            return true;
        }
    }
    return false;
}
function writeNode(state34, level, object, block, compact, iskey = false) {
    state34.tag = null;
    state34.dump = object;
    if (!detectType(state34, object, false)) {
        detectType(state34, object, true);
    }
    const type = _toString2.call(state34.dump);
    if (block) {
        block = state34.flowLevel < 0 || state34.flowLevel > level;
    }
    const objectOrArray = type === "[object Object]" || type === "[object Array]";
    let duplicateIndex = -1;
    let duplicate = false;
    if (objectOrArray) {
        duplicateIndex = state34.duplicates.indexOf(object);
        duplicate = duplicateIndex !== -1;
    }
    if (state34.tag !== null && state34.tag !== "?" || duplicate || state34.indent !== 2 && level > 0) {
        compact = false;
    }
    if (duplicate && state34.usedDuplicates[duplicateIndex]) {
        state34.dump = `*ref_${duplicateIndex}`;
    } else {
        if (objectOrArray && duplicate && !state34.usedDuplicates[duplicateIndex]) {
            state34.usedDuplicates[duplicateIndex] = true;
        }
        if (type === "[object Object]") {
            if (block && Object.keys(state34.dump).length !== 0) {
                writeBlockMapping(state34, level, state34.dump, compact);
                if (duplicate) {
                    state34.dump = `&ref_${duplicateIndex}${state34.dump}`;
                }
            } else {
                writeFlowMapping(state34, level, state34.dump);
                if (duplicate) {
                    state34.dump = `&ref_${duplicateIndex} ${state34.dump}`;
                }
            }
        } else if (type === "[object Array]") {
            const arrayLevel = state34.noArrayIndent && level > 0 ? level - 1 : level;
            if (block && state34.dump.length !== 0) {
                writeBlockSequence(state34, arrayLevel, state34.dump, compact);
                if (duplicate) {
                    state34.dump = `&ref_${duplicateIndex}${state34.dump}`;
                }
            } else {
                writeFlowSequence(state34, arrayLevel, state34.dump);
                if (duplicate) {
                    state34.dump = `&ref_${duplicateIndex} ${state34.dump}`;
                }
            }
        } else if (type === "[object String]") {
            if (state34.tag !== "?") {
                writeScalar(state34, state34.dump, level, iskey);
            }
        } else {
            if (state34.skipInvalid) return false;
            throw new YAMLError(`unacceptable kind of an object to dump ${type}`);
        }
        if (state34.tag !== null && state34.tag !== "?") {
            state34.dump = `!<${state34.tag}> ${state34.dump}`;
        }
    }
    return true;
}
function inspectNode(object, objects, duplicatesIndexes) {
    if (object !== null && typeof object === "object") {
        const index = objects.indexOf(object);
        if (index !== -1) {
            if (duplicatesIndexes.indexOf(index) === -1) {
                duplicatesIndexes.push(index);
            }
        } else {
            objects.push(object);
            if (Array.isArray(object)) {
                for(let idx = 0, length = object.length; idx < length; idx += 1){
                    inspectNode(object[idx], objects, duplicatesIndexes);
                }
            } else {
                const objectKeyList = Object.keys(object);
                for(let idx = 0, length = objectKeyList.length; idx < length; idx += 1){
                    inspectNode(object[objectKeyList[idx]], objects, duplicatesIndexes);
                }
            }
        }
    }
}
function getDuplicateReferences(object, state35) {
    const objects = [], duplicatesIndexes = [];
    inspectNode(object, objects, duplicatesIndexes);
    const length = duplicatesIndexes.length;
    for(let index = 0; index < length; index += 1){
        state35.duplicates.push(objects[duplicatesIndexes[index]]);
    }
    state35.usedDuplicates = Array.from({
        length
    });
}
function dump(input, options) {
    options = options || {};
    const state36 = new DumperState(options);
    if (!state36.noRefs) getDuplicateReferences(input, state36);
    if (writeNode(state36, 0, input, true, true)) return `${state36.dump}\n`;
    return "";
}
function stringify(obj, options) {
    return dump(obj, options);
}
var State1;
(function(State2) {
    State2[State2["PASSTHROUGH"] = 0] = "PASSTHROUGH";
    State2[State2["PERCENT"] = 1] = "PERCENT";
    State2[State2["POSITIONAL"] = 2] = "POSITIONAL";
    State2[State2["PRECISION"] = 3] = "PRECISION";
    State2[State2["WIDTH"] = 4] = "WIDTH";
})(State1 || (State1 = {}));
var WorP;
(function(WorP1) {
    WorP1[WorP1["WIDTH"] = 0] = "WIDTH";
    WorP1[WorP1["PRECISION"] = 1] = "PRECISION";
})(WorP || (WorP = {}));
var F;
(function(F1) {
    F1[F1["sign"] = 1] = "sign";
    F1[F1["mantissa"] = 2] = "mantissa";
    F1[F1["fractional"] = 3] = "fractional";
    F1[F1["esign"] = 4] = "esign";
    F1[F1["exponent"] = 5] = "exponent";
})(F || (F = {}));
function glb(array, value, compare) {
    compare = compare || ((a, b)=>a - b
    );
    if (array.length === 0) {
        return -1;
    }
    if (array.length === 1) {
        if (compare(value, array[0]) < 0) {
            return -1;
        } else {
            return 0;
        }
    }
    let left = 0;
    let right = array.length - 1;
    const vLeft = array[left], vRight = array[right];
    if (compare(value, vRight) >= 0) {
        return right;
    }
    if (compare(value, vLeft) < 0) {
        return -1;
    }
    while(right - left > 1){
        const center = left + (right - left >> 1);
        const vCenter = array[center];
        const cmp = compare(value, vCenter);
        if (cmp < 0) {
            right = center;
        } else if (cmp === 0) {
            left = center;
        } else {
            left = center;
        }
    }
    return left;
}
let Deno1;
try {
    Deno1 = globalThis.Deno;
} catch (_e) {}
const noColor1 = typeof (Deno1 && Deno1.noColor) === "boolean" ? Deno1.noColor : true;
let enabled1 = !noColor1;
function code1(open, close) {
    return {
        open: `\x1b[${open.join(";")}m`,
        close: `\x1b[${close}m`,
        regexp: new RegExp(`\\x1b\\[${close}m`, "g")
    };
}
function run1(str58, code19) {
    return enabled1 ? `${code19.open}${str58.replace(code19.regexp, code19.open)}${code19.close}` : str58;
}
function red1(str59) {
    return run1(str59, code1([
        31
    ], 39));
}
function blue1(str60) {
    return run1(str60, code1([
        34
    ], 39));
}
new RegExp([
    "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", 
].join("|"), "g");
function platformHasNonAsciiCharacters() {
    try {
        return Deno.build.os !== "windows";
    } catch (_e) {
        return false;
    }
}
function tidyverseInfo(msg) {
    if (platformHasNonAsciiCharacters()) {
        return `${blue1("ℹ")} ${msg}`;
    } else {
        return `${blue1("i")} ${msg}`;
    }
}
function tidyverseError(msg) {
    if (platformHasNonAsciiCharacters()) {
        return `${red1("✖")} ${msg}`;
    } else {
        return `${red1("x")} ${msg}`;
    }
}
function tidyverseFormatError(msg) {
    let { heading , error: error7 , info: info2  } = msg;
    if (msg.location) {
        heading = `${locationString(msg.location)} ${heading}`;
    }
    if (msg.fileName) {
        heading = `In file ${msg.fileName}\n${heading}`;
    }
    const strings = [
        heading,
        msg.sourceContext,
        ...error7.map(tidyverseError),
        ...Object.values(info2).map(tidyverseInfo),
        "", 
    ];
    return strings.join("\n");
}
function quotedStringColor(msg) {
    return blue1(msg);
}
function addFileInfo(msg, src) {
    if (src.fileName !== undefined) {
        msg.fileName = src.fileName;
    }
}
function addInstancePathInfo(msg, instancePath) {
    if (instancePath.length) {
        const niceInstancePath = instancePath.map((s)=>blue1(String(s))
        ).join(":");
        msg.info["instance-path-location"] = `The error happened in location ${niceInstancePath}.`;
    }
}
function locationString(loc) {
    const { start , end  } = loc;
    if (start.line === end.line) {
        if (start.column === end.column) {
            return `(line ${start.line + 1}, column ${start.column + 1})`;
        } else {
            return `(line ${start.line + 1}, columns ${start.column + 1}--${end.column + 1})`;
        }
    } else {
        return `(line ${start.line + 1}, column ${start.column + 1} through line ${end.line + 1}, column ${end.column + 1})`;
    }
}
function errorKey(err) {
    const positionKey = (pos)=>`${pos.line}-${pos.column}`
    ;
    return `${err.fileName || ""}-${positionKey(err.location.start)}-${positionKey(err.location.end)}`;
}
function reportOnce(reporter, reportSet) {
    const errorsReported = reportSet || new Set();
    return (err)=>{
        const key = errorKey(err);
        if (errorsReported.has(key)) {
            return;
        }
        errorsReported.add(key);
        reporter(err);
    };
}
function lines(text) {
    return text.split(/\r?\n/);
}
function normalizeNewlines(text) {
    return lines(text).join("\n");
}
function* matchAll(text, regexp1) {
    if (!regexp1.global) {
        throw new Error("matchAll requires global regexps");
    }
    let match;
    while((match = regexp1.exec(text)) !== null){
        yield match;
    }
}
function* lineOffsets(text) {
    yield 0;
    for (const match of matchAll(text, /\r?\n/g)){
        yield match.index + match[0].length;
    }
}
function* lineBreakPositions(text) {
    for (const match of matchAll(text, /\r?\n/g)){
        yield match.index;
    }
}
function indexToRowCol(text) {
    const offsets = Array.from(lineOffsets(text));
    return function(offset) {
        if (offset === 0) {
            return {
                line: 0,
                column: 0
            };
        }
        const startIndex = glb(offsets, offset);
        return {
            line: startIndex,
            column: offset - offsets[startIndex]
        };
    };
}
function formatLineRange(text, firstLine, lastLine) {
    const lineWidth = Math.max(String(firstLine + 1).length, String(lastLine + 1).length);
    const pad = " ".repeat(lineWidth);
    const ls = lines(text);
    const result = [];
    for(let i30 = firstLine; i30 <= lastLine; ++i30){
        const numberStr = `${pad}${i30 + 1}: `.slice(-(lineWidth + 2));
        const lineStr = ls[i30];
        result.push({
            lineNumber: i30,
            content: numberStr + quotedStringColor(lineStr),
            rawLine: ls[i30]
        });
    }
    return {
        prefixWidth: lineWidth + 2,
        lines: result
    };
}
function editDistance(w1, w2) {
    const cost = (c)=>{
        if ("_-".indexOf(c) !== -1) {
            return 1;
        }
        return 10;
    };
    const cost2 = (c1, c2)=>{
        if (c1 === c2) {
            return 0;
        }
        if ("_-".indexOf(c1) !== -1 && "_-".indexOf(c2) !== -1) {
            return 1;
        }
        if (c1.toLocaleLowerCase() === c2.toLocaleLowerCase()) {
            return 1;
        }
        const cc1 = c1.charCodeAt(0);
        const cc2 = c2.charCodeAt(0);
        if (cc1 >= 48 && cc1 <= 57 && cc2 >= 48 && cc2 <= 57) {
            return 1;
        }
        return 10;
    };
    const s1 = w1.length + 1;
    const s2 = w2.length + 1;
    const v = new Int32Array(s1 * s2);
    for(let i31 = 0; i31 < s1; ++i31){
        for(let j = 0; j < s2; ++j){
            if (i31 === 0 && j === 0) {
                continue;
            } else if (i31 === 0) {
                v[i31 * s2 + j] = v[i31 * s2 + (j - 1)] + cost(w2[j - 1]);
            } else if (j === 0) {
                v[i31 * s2 + j] = v[(i31 - 1) * s2 + j] + cost(w1[i31 - 1]);
            } else {
                v[i31 * s2 + j] = Math.min(v[(i31 - 1) * s2 + (j - 1)] + cost2(w1[i31 - 1], w2[j - 1]), v[i31 * s2 + (j - 1)] + cost(w2[j - 1]), v[(i31 - 1) * s2 + j] + cost(w1[i31 - 1]));
            }
        }
    }
    return v[(w1.length + 1) * (w2.length + 1) - 1];
}
function detectCaseConvention(key) {
    if (key.toLocaleLowerCase() !== key) {
        return "capitalizationCase";
    }
    if (key.indexOf("_") !== -1) {
        return "underscore_case";
    }
    if (key.indexOf("-") !== -1) {
        return "dash-case";
    }
    return undefined;
}
function resolveCaseConventionRegex(keys6, conventions) {
    if (conventions !== undefined) {
        if (conventions.length === 0) {
            throw new Error("Internal Error: resolveCaseConventionRegex requires nonempty `conventions`");
        }
        return {
            pattern: conventions.map((c)=>`(${c})`
            ).join("|"),
            list: conventions
        };
    }
    const disallowedNearMisses = [];
    const foundConventions = new Set();
    for (const key of keys6){
        const found = detectCaseConvention(key);
        if (found) {
            foundConventions.add(found);
        }
        switch(found){
            case "capitalizationCase":
                disallowedNearMisses.push(toUnderscoreCase(key), toDashCase(key));
                break;
            case "dash-case":
                disallowedNearMisses.push(toUnderscoreCase(key), toCapitalizationCase(key));
                break;
            case "underscore_case":
                disallowedNearMisses.push(toDashCase(key), toCapitalizationCase(key));
                break;
        }
    }
    if (foundConventions.size === 0) {
        return {
            pattern: undefined,
            list: []
        };
    }
    return {
        pattern: `^(?!(${disallowedNearMisses.join("|")}))`,
        list: Array.from(foundConventions)
    };
}
function toDashCase(str61) {
    return toUnderscoreCase(str61).replace(/_/g, "-");
}
function toUnderscoreCase(str62) {
    return str62.replace(/([A-Z]+)/g, (_match, p1)=>`-${p1}`
    ).replace(/-/g, "_").split("_").filter((x)=>x.length
    ).join("_").toLocaleLowerCase();
}
function toCapitalizationCase(str63) {
    return toUnderscoreCase(str63).replace(/_(.)/g, (_match, p1)=>p1.toLocaleUpperCase()
    );
}
class ErrorEx extends Error {
    constructor(name76, message, printName = true, printStack = true){
        super(message);
        this.name = name76;
        this.printName = printName;
        this.printStack = printStack;
    }
    printName;
    printStack;
}
function asErrorEx(e) {
    if (e instanceof ErrorEx) {
        return e;
    } else if (e instanceof Error) {
        e.printName = e.name !== "Error";
        e.printStack = !!e.message;
        return e;
    } else {
        return new ErrorEx("Error", String(e), false, true);
    }
}
function schemaType(schema) {
    if (schema === false) {
        return "false";
    }
    if (schema === true) {
        return "true";
    }
    return schema.type;
}
function schemaDispatch(s, d) {
    const st = schemaType(s);
    if (d[st]) {
        d[st](s);
    }
}
function schemaCall(s, d, other) {
    const st = schemaType(s);
    if (d[st]) {
        return d[st](s);
    }
    if (other) {
        return other(s);
    }
    throw new Error(`Internal Error: dispatch failed for type ${st}`);
}
function schemaDocString(d) {
    if (typeof d === "string") {
        return d;
    }
    if (d.short) {
        return d.short;
    }
    return "";
}
function schemaDescription(schema) {
    if (schema === true) {
        return `be anything`;
    } else if (schema === false) {
        return `be no possible value`;
    } else {
        return schema.description || `be ${schemaType(schema)}`;
    }
}
const booleanSchema = {
    "type": "boolean",
    "description": "be `true` or `false`",
    "completions": [
        "true",
        "false"
    ],
    "exhaustiveCompletions": true
};
const numberSchema = {
    "type": "number",
    "description": "be a number"
};
const stringSchema = {
    "type": "string",
    "description": "be a string"
};
const nullSchema = {
    "type": "null",
    "description": "be the null value",
    "completions": [
        "null"
    ],
    "exhaustiveCompletions": true
};
function tagSchema(schema, tags) {
    return {
        ...schema,
        tags: {
            ...schema.tags || {},
            ...tags
        }
    };
}
function enumSchema(...args) {
    if (args.length === 0) {
        throw new Error("Internal Error: Empty enum schema not supported.");
    }
    return {
        "type": "enum",
        "enum": args,
        "description": args.length > 1 ? `be one of: ${args.map((x)=>"`" + x + "`"
        ).join(", ")}` : `be '${args[0]}'`,
        "completions": args.map(String),
        "exhaustiveCompletions": true
    };
}
function regexSchema(arg, description) {
    const result = {
        "type": "string",
        "pattern": arg
    };
    if (description) {
        result.description = description;
    } else {
        result.description = `be a string that satisfies regex "${arg}"`;
    }
    return result;
}
function anyOfSchema(...args) {
    return {
        "type": "anyOf",
        "anyOf": args,
        "description": `be at least one of: ${args.map((x)=>schemaDescription(x).slice(3)
        ).join(", ")}`
    };
}
function allOfSchema(...args) {
    return {
        "type": "allOf",
        "allOf": args,
        "description": `be all of: ${args.map((x)=>schemaDescription(x).slice(3)
        ).join(", ")}`
    };
}
function objectSchema(params = {}) {
    let { properties , patternProperties , required , additionalProperties , description , baseSchema , exhaustive , completions: completionsParam , namingConvention , propertyNames: propertyNamesSchema ,  } = params;
    required = required || [];
    properties = properties || {};
    patternProperties = patternProperties || {};
    const tags = {};
    let tagsAreSet = false;
    let propertyNames = propertyNamesSchema;
    const objectKeys = Object.getOwnPropertyNames(completionsParam || properties);
    if (namingConvention !== "ignore") {
        const { pattern , list  } = resolveCaseConventionRegex(objectKeys, namingConvention);
        if (pattern !== undefined) {
            if (propertyNames === undefined) {
                propertyNames = {
                    "type": "string",
                    pattern
                };
            } else {
                propertyNames = allOfSchema(propertyNames, {
                    "type": "string",
                    pattern
                });
            }
            tags["case-convention"] = list;
            tagsAreSet = true;
        }
    }
    if (completionsParam) {
        tags["completions"] = completionsParam;
        tagsAreSet = true;
    }
    const hasDescription = description !== undefined;
    description = description || "be an object";
    let result = undefined;
    if (baseSchema) {
        if (baseSchema.type !== "object") {
            throw new Error("Internal Error: can only extend other object Schema");
        }
        result = Object.assign({}, baseSchema);
        if (result.$id) {
            delete result.$id;
        }
        if (exhaustive && baseSchema.exhaustiveCompletions) {
            result.exhaustiveCompletions = true;
        }
        if (hasDescription) {
            result.description = description;
        }
        result.properties = Object.assign({}, result.properties, properties);
        result.patternProperties = Object.assign({}, result.patternProperties, patternProperties);
        if (required) {
            result.required = (result.required || []).slice();
            result.required.push(...required);
        }
        if (additionalProperties !== undefined) {
            if (result.additionalProperties === false) {
                throw new Error("Internal Error: don't know how to subclass object schema with additionalProperties === false");
            }
            if (result.additionalProperties) {
                result.additionalProperties = allOfSchema(result.additionalProperties, additionalProperties);
            } else {
                result.additionalProperties = additionalProperties;
            }
        }
        if (propertyNames !== undefined) {
            if (result.propertyNames !== undefined) {
                result.propertyNames = anyOfSchema(propertyNames, result.propertyNames);
            } else {
                result.propertyNames = propertyNames;
            }
        }
    } else {
        result = {
            "type": "object",
            description
        };
        if (exhaustive) {
            result.exhaustiveCompletions = true;
        }
        if (properties) {
            result.properties = properties;
        }
        if (patternProperties) {
            result.patternProperties = patternProperties;
        }
        if (required && required.length > 0) {
            result.required = required;
        }
        if (additionalProperties !== undefined) {
            result.additionalProperties = additionalProperties;
        }
        if (propertyNames !== undefined) {
            result.propertyNames = propertyNames;
        }
    }
    if (tagsAreSet) {
        result.tags = tags;
    }
    return result;
}
function arraySchema(items) {
    if (items) {
        return {
            "type": "array",
            "description": `be an array of values, where each element must ${schemaDescription(items)}`,
            items
        };
    } else {
        return {
            "type": "array",
            "description": `be an array of values`
        };
    }
}
function documentSchema(schema, doc) {
    const result = Object.assign({}, schema);
    result.documentation = doc;
    return result;
}
function describeSchema(schema, description) {
    const result = Object.assign({}, schema);
    result.description = `be ${description}`;
    return result;
}
function completeSchema(schema, ...completions) {
    const result = Object.assign({}, schema);
    const prevCompletions = (schema.completions || []).slice();
    prevCompletions.push(...completions);
    result.completions = prevCompletions;
    return result;
}
function completeSchemaOverwrite(schema, ...completions) {
    const result = Object.assign({}, schema);
    result.completions = completions;
    return result;
}
function idSchema(schema, id) {
    const result = Object.assign({}, schema);
    result["$id"] = id;
    return result;
}
function errorMessageSchema(schema, errorMessage) {
    return {
        ...schema,
        errorMessage
    };
}
function refSchema($ref, description) {
    return {
        "type": "ref",
        $ref,
        description
    };
}
function valueSchema(val, description) {
    return {
        "type": "enum",
        "enum": [
            val
        ],
        "description": description || `be ${JSON.stringify(val)}`
    };
}
const definitionsObject = {};
function hasSchemaDefinition(key) {
    return definitionsObject[key] !== undefined;
}
function getSchemaDefinition(key) {
    if (definitionsObject[key] === undefined) {
        throw new Error(`Internal Error: Schema ${key} not found.`);
    }
    return definitionsObject[key];
}
function setSchemaDefinition(schema) {
    if (schema.$id === undefined) {
        throw new Error("Internal Error, setSchemaDefinition needs $id");
    }
    if (definitionsObject[schema.$id] === undefined) {
        definitionsObject[schema.$id] = schema;
    }
}
function getSchemaDefinitionsObject() {
    return Object.assign({}, definitionsObject);
}
function expandAliasesFrom(lst, defs) {
    const aliases = defs;
    const result = [];
    lst = lst.slice();
    for(let i32 = 0; i32 < lst.length; ++i32){
        const el = lst[i32];
        if (el.startsWith("$")) {
            const v = aliases[el.slice(1)];
            if (v === undefined) {
                throw new Error(`Internal Error: ${el} doesn't have an entry in the aliases map`);
            }
            lst.push(...v);
        } else {
            result.push(el);
        }
    }
    return result;
}
Object.freeze({
    __proto__: null
});
class DataSet {
    constructor(raw2018, raw2019, raw2020, raw2021){
        this._raw2018 = raw2018;
        this._raw2019 = raw2019;
        this._raw2020 = raw2020;
        this._raw2021 = raw2021;
    }
    get es2018() {
        return this._set2018 || (this._set2018 = new Set(this._raw2018.split(" ")));
    }
    get es2019() {
        return this._set2019 || (this._set2019 = new Set(this._raw2019.split(" ")));
    }
    get es2020() {
        return this._set2020 || (this._set2020 = new Set(this._raw2020.split(" ")));
    }
    get es2021() {
        return this._set2021 || (this._set2021 = new Set(this._raw2021.split(" ")));
    }
}
new Set([
    "General_Category",
    "gc"
]);
new Set([
    "Script",
    "Script_Extensions",
    "sc",
    "scx"
]);
new DataSet("C Cased_Letter Cc Cf Close_Punctuation Cn Co Combining_Mark Connector_Punctuation Control Cs Currency_Symbol Dash_Punctuation Decimal_Number Enclosing_Mark Final_Punctuation Format Initial_Punctuation L LC Letter Letter_Number Line_Separator Ll Lm Lo Lowercase_Letter Lt Lu M Mark Math_Symbol Mc Me Mn Modifier_Letter Modifier_Symbol N Nd Nl No Nonspacing_Mark Number Open_Punctuation Other Other_Letter Other_Number Other_Punctuation Other_Symbol P Paragraph_Separator Pc Pd Pe Pf Pi Po Private_Use Ps Punctuation S Sc Separator Sk Sm So Space_Separator Spacing_Mark Surrogate Symbol Titlecase_Letter Unassigned Uppercase_Letter Z Zl Zp Zs cntrl digit punct", "", "", "");
new DataSet("Adlam Adlm Aghb Ahom Anatolian_Hieroglyphs Arab Arabic Armenian Armi Armn Avestan Avst Bali Balinese Bamu Bamum Bass Bassa_Vah Batak Batk Beng Bengali Bhaiksuki Bhks Bopo Bopomofo Brah Brahmi Brai Braille Bugi Buginese Buhd Buhid Cakm Canadian_Aboriginal Cans Cari Carian Caucasian_Albanian Chakma Cham Cher Cherokee Common Copt Coptic Cprt Cuneiform Cypriot Cyrillic Cyrl Deseret Deva Devanagari Dsrt Dupl Duployan Egyp Egyptian_Hieroglyphs Elba Elbasan Ethi Ethiopic Geor Georgian Glag Glagolitic Gonm Goth Gothic Gran Grantha Greek Grek Gujarati Gujr Gurmukhi Guru Han Hang Hangul Hani Hano Hanunoo Hatr Hatran Hebr Hebrew Hira Hiragana Hluw Hmng Hung Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Ital Java Javanese Kaithi Kali Kana Kannada Katakana Kayah_Li Khar Kharoshthi Khmer Khmr Khoj Khojki Khudawadi Knda Kthi Lana Lao Laoo Latin Latn Lepc Lepcha Limb Limbu Lina Linb Linear_A Linear_B Lisu Lyci Lycian Lydi Lydian Mahajani Mahj Malayalam Mand Mandaic Mani Manichaean Marc Marchen Masaram_Gondi Meetei_Mayek Mend Mende_Kikakui Merc Mero Meroitic_Cursive Meroitic_Hieroglyphs Miao Mlym Modi Mong Mongolian Mro Mroo Mtei Mult Multani Myanmar Mymr Nabataean Narb Nbat New_Tai_Lue Newa Nko Nkoo Nshu Nushu Ogam Ogham Ol_Chiki Olck Old_Hungarian Old_Italic Old_North_Arabian Old_Permic Old_Persian Old_South_Arabian Old_Turkic Oriya Orkh Orya Osage Osge Osma Osmanya Pahawh_Hmong Palm Palmyrene Pau_Cin_Hau Pauc Perm Phag Phags_Pa Phli Phlp Phnx Phoenician Plrd Prti Psalter_Pahlavi Qaac Qaai Rejang Rjng Runic Runr Samaritan Samr Sarb Saur Saurashtra Sgnw Sharada Shavian Shaw Shrd Sidd Siddham SignWriting Sind Sinh Sinhala Sora Sora_Sompeng Soyo Soyombo Sund Sundanese Sylo Syloti_Nagri Syrc Syriac Tagalog Tagb Tagbanwa Tai_Le Tai_Tham Tai_Viet Takr Takri Tale Talu Tamil Taml Tang Tangut Tavt Telu Telugu Tfng Tglg Thaa Thaana Thai Tibetan Tibt Tifinagh Tirh Tirhuta Ugar Ugaritic Vai Vaii Wara Warang_Citi Xpeo Xsux Yi Yiii Zanabazar_Square Zanb Zinh Zyyy", "Dogr Dogra Gong Gunjala_Gondi Hanifi_Rohingya Maka Makasar Medefaidrin Medf Old_Sogdian Rohg Sogd Sogdian Sogo", "Elym Elymaic Hmnp Nand Nandinagari Nyiakeng_Puachue_Hmong Wancho Wcho", "Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi");
new DataSet("AHex ASCII ASCII_Hex_Digit Alpha Alphabetic Any Assigned Bidi_C Bidi_Control Bidi_M Bidi_Mirrored CI CWCF CWCM CWKCF CWL CWT CWU Case_Ignorable Cased Changes_When_Casefolded Changes_When_Casemapped Changes_When_Lowercased Changes_When_NFKC_Casefolded Changes_When_Titlecased Changes_When_Uppercased DI Dash Default_Ignorable_Code_Point Dep Deprecated Dia Diacritic Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Ext Extender Gr_Base Gr_Ext Grapheme_Base Grapheme_Extend Hex Hex_Digit IDC IDS IDSB IDST IDS_Binary_Operator IDS_Trinary_Operator ID_Continue ID_Start Ideo Ideographic Join_C Join_Control LOE Logical_Order_Exception Lower Lowercase Math NChar Noncharacter_Code_Point Pat_Syn Pat_WS Pattern_Syntax Pattern_White_Space QMark Quotation_Mark RI Radical Regional_Indicator SD STerm Sentence_Terminal Soft_Dotted Term Terminal_Punctuation UIdeo Unified_Ideograph Upper Uppercase VS Variation_Selector White_Space XIDC XIDS XID_Continue XID_Start space", "Extended_Pictographic", "", "EBase EComp EMod EPres ExtPict");
({
    at (s, end, i33) {
        return i33 < end ? s.charCodeAt(i33) : -1;
    },
    width (c) {
        return 1;
    }
});
({
    at (s, end, i34) {
        return i34 < end ? s.codePointAt(i34) : -1;
    },
    width (c) {
        return c > 65535 ? 2 : 1;
    }
});
function resolveDescription(s) {
    if (typeof s === "string") {
        return s;
    }
    const valueS = resolveSchema(s);
    if (valueS === false || valueS === true) {
        return "";
    }
    if (valueS.documentation === undefined) {
        return "";
    }
    if (typeof valueS.documentation === "string") {
        return valueS.documentation;
    }
    if (valueS.documentation.short) {
        return valueS.documentation.short;
    } else {
        return "";
    }
}
function resolveSchema(schema, visit, hasRef, next) {
    if (schema === false || schema === true) {
        return schema;
    }
    if (hasRef === undefined) {
        hasRef = (cursor)=>{
            return schemaCall(cursor, {
                ref: (_s)=>true
            }, (_s)=>false
            );
        };
    }
    if (!hasRef(schema)) {
        return schema;
    }
    if (visit === undefined) {
        visit = (_schema)=>{};
    }
    if (next === undefined) {
        next = (cursor)=>{
            const result = schemaCall(cursor, {
                ref: (s)=>getSchemaDefinition(s.$ref)
            });
            if (result === undefined) {
                throw new Error("Internal Error, couldn't resolve schema ${JSON.stringify(cursor)}");
            }
            return result;
        };
    }
    let cursor1 = schema;
    let cursor2 = schema;
    let stopped = false;
    do {
        cursor1 = next(cursor1);
        visit(cursor1);
        if (hasRef(cursor2)) {
            cursor2 = next(cursor2);
        } else {
            stopped = true;
        }
        if (hasRef(cursor2)) {
            cursor2 = next(cursor2);
        } else {
            stopped = true;
        }
        if (!stopped && cursor1 === cursor2) {
            throw new Error(`reference cycle detected at ${JSON.stringify(cursor1)}`);
        }
    }while (hasRef(cursor1))
    return cursor1;
}
function navigateSchemaBySchemaPathSingle(schema, path44) {
    const ensurePathFragment = (fragment, expected)=>{
        if (fragment !== expected) {
            throw new Error(`Internal Error in navigateSchemaBySchemaPathSingle: ${fragment} !== ${expected}`);
        }
    };
    const inner = (subschema, index)=>{
        if (subschema === undefined) {
            throw new Error(`Internal Error in navigateSchemaBySchemaPathSingle: invalid path navigation`);
        }
        if (index === path44.length) {
            return subschema;
        }
        const st = schemaType(subschema);
        switch(st){
            case "anyOf":
                ensurePathFragment(path44[index], "anyOf");
                return inner(subschema.anyOf[path44[index + 1]], index + 2);
            case "allOf":
                ensurePathFragment(path44[index], "allOf");
                return inner(subschema.allOf[path44[index + 1]], index + 2);
            case "array":
                ensurePathFragment(path44[index], "array");
                return inner(subschema.arrayOf.schema, index + 2);
            case "object":
                ensurePathFragment(path44[index], "object");
                if (path44[index + 1] === "properties") {
                    return inner(subschema.properties[path44[index + 2]], index + 3);
                } else if (path44[index + 1] === "patternProperties") {
                    return inner(subschema.patternProperties[path44[index + 2]], index + 3);
                } else if (path44[index + 1] === "additionalProperties") {
                    return inner(subschema.additionalProperties, index + 2);
                } else {
                    throw new Error(`Internal Error in navigateSchemaBySchemaPathSingle: bad path fragment ${path44[index]} in object navigation`);
                }
            default:
                throw new Error(`Internal Error in navigateSchemaBySchemaPathSingle: can't navigate schema type ${st}`);
        }
    };
    return inner(schema, 0);
}
function schemaCompletions(s1) {
    if (s1 === true || s1 === false) {
        return [];
    }
    let schema1 = resolveSchema(s1);
    schema1 = resolveSchema(schema1, (_schema)=>{}, (schema)=>{
        return schema.tags !== undefined && schema.tags["complete-from"] !== undefined;
    }, (schema)=>{
        return navigateSchemaBySchemaPathSingle(schema, schema.tags["complete-from"]);
    });
    if (schema1 === true || schema1 === false) {
        return [];
    }
    const normalize5 = (completions)=>{
        const result = (completions || []).map((c)=>{
            if (typeof c === "string") {
                return {
                    type: "value",
                    display: c,
                    value: c,
                    description: "",
                    suggest_on_accept: false,
                    schema: schema1
                };
            }
            return {
                ...c,
                description: resolveDescription(c.description),
                schema: schema1
            };
        });
        return result;
    };
    if (schema1.completions && schema1.completions.length) {
        return normalize5(schema1.completions);
    }
    if (schema1.tags && schema1.tags.completions && schema1.tags.completions.length) {
        return normalize5(schema1.tags.completions);
    }
    return schemaCall(schema1, {
        array: (s)=>{
            if (s.items) {
                return schemaCompletions(s.items);
            } else {
                return [];
            }
        },
        anyOf: (s)=>{
            return s.anyOf.map(schemaCompletions).flat();
        },
        allOf: (s)=>{
            return s.allOf.map(schemaCompletions).flat();
        },
        "object": (s)=>{
            s.cachedCompletions = getObjectCompletions(s);
            return normalize5(s.cachedCompletions);
        }
    }, (_)=>[]
    );
}
function getObjectCompletions(s) {
    const completionsParam = s.tags && s.tags.completions || [];
    return schemaCall(s, {
        "object": (schema3)=>{
            const properties = schema3.properties;
            const objectKeys = completionsParam.length ? completionsParam : Object.getOwnPropertyNames(properties);
            const completions = [];
            for (const k1 of objectKeys){
                const schema2 = properties && properties[k1];
                const maybeDescriptions = [];
                let hidden25 = false;
                if (schema2 !== undefined && schema2 !== true && schema2 !== false) {
                    if (schema2.documentation) {
                        maybeDescriptions.push(schemaDocString(schema2.documentation));
                    } else {
                        let described = false;
                        const visitor = (schema)=>{
                            if (schema === false || schema === true) {
                                return;
                            }
                            if (schema.hidden) {
                                hidden25 = true;
                            }
                            if (described) {
                                return;
                            }
                            if (schema.documentation) {
                                maybeDescriptions.push(schemaDocString(schema.documentation));
                                described = true;
                            }
                        };
                        try {
                            resolveSchema(schema2, visitor);
                        } catch (_e) {}
                        if (!described) {
                            schemaDispatch(schema2, {
                                ref: (schema)=>maybeDescriptions.push({
                                        $ref: schema.$ref
                                    })
                            });
                        }
                    }
                }
                if (hidden25) {
                    continue;
                }
                let description = "";
                for (const md of maybeDescriptions){
                    if (md !== undefined) {
                        description = md;
                        break;
                    }
                }
                completions.push({
                    type: "key",
                    display: "",
                    value: `${k1}: `,
                    description,
                    suggest_on_accept: true
                });
            }
            return completions;
        }
    }, (_)=>completionsParam.map((c)=>({
                type: "value",
                display: "",
                value: c,
                description: "",
                suggest_on_accept: false
            })
        )
    );
}
function possibleSchemaKeys(schema) {
    const precomputedCompletions = schemaCompletions(schema).filter((c)=>c.type === "key"
    ).map((c)=>c.value.split(":")[0]
    );
    if (precomputedCompletions.length) {
        return precomputedCompletions;
    }
    const results = [];
    walkSchema(schema, {
        "object": (s)=>{
            results.push(...Object.keys(s.properties || {}));
            return true;
        },
        "array": (_s)=>true
    });
    return results;
}
function possibleSchemaValues(schema) {
    const results = [];
    walkSchema(schema, {
        "enum": (s)=>{
            results.push(...s["enum"].map(String));
            return true;
        },
        "array": (_s)=>true
        ,
        "object": (_s)=>true
    });
    return results;
}
function walkSchema(schema, f) {
    const recur = {
        "anyOf": (ss)=>{
            for (const s of ss.anyOf){
                walkSchema(s, f);
            }
        },
        "allOf": (ss)=>{
            for (const s of ss.allOf){
                walkSchema(s, f);
            }
        },
        "array": (x)=>{
            if (x.items) {
                walkSchema(x.items, f);
            }
        },
        "object": (x)=>{
            if (x.properties) {
                for (const ss of Object.values(x.properties)){
                    walkSchema(ss, f);
                }
            }
            if (x.patternProperties) {
                for (const ss of Object.values(x.patternProperties)){
                    walkSchema(ss, f);
                }
            }
            if (x.propertyNames) {
                walkSchema(x.propertyNames, f);
            }
        }
    };
    if (typeof f === "function") {
        if (f(schema) === true) {
            return;
        }
    } else {
        if (schemaCall(schema, f, (_)=>false
        ) === true) {
            return;
        }
    }
    schemaCall(schema, recur, (_)=>false
    );
}
function mappedString(source, pieces, fileName) {
    if (typeof source === "string") {
        const offsetInfo = [];
        let offset = 0;
        const resultList = pieces.filter((piece)=>typeof piece === "string" || piece.start !== piece.end
        ).map((piece)=>{
            if (typeof piece === "string") {
                offsetInfo.push({
                    fromSource: false,
                    length: piece.length,
                    offset
                });
                offset += piece.length;
                return piece;
            } else {
                const resultPiece = source.substring(piece.start, piece.end);
                offsetInfo.push({
                    fromSource: true,
                    length: resultPiece.length,
                    offset,
                    range: {
                        start: piece.start,
                        end: piece.end
                    }
                });
                offset += resultPiece.length;
                return resultPiece;
            }
        });
        const value = resultList.join("");
        const map5 = (targetOffset)=>{
            const ix = glb(offsetInfo, {
                offset: targetOffset
            }, (a, b)=>a.offset - b.offset
            );
            if (ix < 0) {
                return undefined;
            }
            const info3 = offsetInfo[ix];
            if (!info3.fromSource) {
                return undefined;
            }
            const localOffset = targetOffset - info3.offset;
            if (localOffset >= info3.length) {
                return undefined;
            }
            return info3.range.start + localOffset;
        };
        const mapClosest = (targetOffset)=>{
            if (offsetInfo.length === 0 || targetOffset < 0) {
                return undefined;
            }
            const firstIx = glb(offsetInfo, {
                offset: targetOffset
            }, (a, b)=>a.offset - b.offset
            );
            let ix = firstIx;
            let smallestSourceInfo = undefined;
            while(ix >= 0){
                const info4 = offsetInfo[ix];
                if (!info4.fromSource) {
                    ix--;
                    continue;
                }
                smallestSourceInfo = info4;
                if (ix === firstIx) {
                    const localOffset = targetOffset - info4.offset;
                    if (localOffset < info4.length) {
                        return info4.range.start + localOffset;
                    }
                }
                return info4.range.end - 1;
            }
            if (smallestSourceInfo === undefined) {
                return undefined;
            } else {
                return smallestSourceInfo.range.start;
            }
        };
        return {
            value,
            originalString: source,
            fileName,
            map: map5,
            mapClosest
        };
    } else {
        const { value , originalString , map: previousMap , mapClosest: previousMapClosest , fileName: previousFileName ,  } = source;
        const { value: resultValue , map: nextMap , mapClosest: nextMapClosest ,  } = mappedString(value, pieces);
        const composeMap = (offset)=>{
            const v = nextMap(offset);
            if (v === undefined) {
                return v;
            }
            return previousMap(v);
        };
        const composeMapClosest = (offset)=>{
            const v = nextMapClosest(offset);
            if (v === undefined) {
                return v;
            }
            return previousMapClosest(v);
        };
        return {
            value: resultValue,
            originalString,
            map: composeMap,
            mapClosest: composeMapClosest,
            fileName: previousFileName
        };
    }
}
function asMappedString(str64, fileName) {
    if (typeof str64 === "string") {
        return {
            value: str64,
            originalString: str64,
            map: (x)=>x
            ,
            mapClosest: (x)=>x
            ,
            fileName
        };
    } else if (fileName !== undefined) {
        throw new Error("Internal error: can't change the fileName of an existing MappedString");
    } else {
        return str64;
    }
}
function mappedConcat(strings) {
    if (strings.length === 0) {
        throw new Error("strings must be non-empty");
    }
    let currentOffset = 0;
    const offsets = [];
    for (const s1 of strings){
        currentOffset += s1.value.length;
        offsets.push(currentOffset);
    }
    const value = "".concat(...strings.map((s)=>s.value
    ));
    return {
        value,
        originalString: strings[0].originalString,
        fileName: strings[0].fileName,
        map (offset) {
            if (offset < 0 || offset >= value.length) {
                return undefined;
            }
            const ix = glb(offsets, offset);
            return strings[ix].map(offset - offsets[ix]);
        },
        mapClosest (offset) {
            if (offset < 0 || offset >= value.length) {
                return undefined;
            }
            const ix = glb(offsets, offset);
            return strings[ix].mapClosest(offset - offsets[ix]);
        }
    };
}
function mappedIndexToRowCol(eitherText) {
    const text = asMappedString(eitherText);
    const f = indexToRowCol(text.originalString);
    return function(offset) {
        const n1 = text.mapClosest(offset);
        if (n1 === undefined) {
            throw new Error("Internal Error: bad offset in mappedIndexRowCol");
        }
        return f(n1);
    };
}
function mappedNormalizeNewlines(eitherText) {
    const text = asMappedString(eitherText);
    let start = 0;
    const chunks = [];
    for (const offset of lineBreakPositions(text.value)){
        if (text.value[offset] !== "\r") {
            continue;
        }
        chunks.push({
            start,
            end: offset
        });
        chunks.push({
            start: offset + 1,
            end: offset + 2
        });
        start = offset + 2;
    }
    if (start !== text.value.length) {
        chunks.push({
            start,
            end: text.value.length
        });
    }
    return mappedString(text, chunks);
}
function skipRegexpAll(eitherText, re) {
    const text = asMappedString(eitherText);
    let start = 0;
    const chunks = [];
    for (const match of matchAll(text.value, re)){
        chunks.push({
            start,
            end: match.index
        });
        start = match[0].length + match.index;
    }
    if (start !== text.value.length) {
        chunks.push({
            start,
            end: text.value.length
        });
    }
    return mappedString(text, chunks);
}
function skipRegexp(eitherText, re) {
    const text = asMappedString(eitherText);
    const m = text.value.match(re);
    if (m) {
        return mappedString(text, [
            {
                start: 0,
                end: m.index
            },
            {
                start: m.index + m[0].length,
                end: text.value.length
            }, 
        ]);
    } else {
        return text;
    }
}
class ValidationContext {
    instancePath;
    root;
    nodeStack;
    currentNode;
    constructor(){
        this.instancePath = [];
        this.currentNode = {
            edge: "#",
            errors: [],
            children: []
        };
        this.nodeStack = [
            this.currentNode
        ];
        this.root = this.currentNode;
    }
    error(value, schema, message) {
        this.currentNode.errors.push({
            value,
            schema,
            message,
            instancePath: this.instancePath.slice(),
            schemaPath: this.nodeStack.map((node)=>node.edge
            )
        });
    }
    pushSchema(schemaPath) {
        const newNode = {
            edge: schemaPath,
            errors: [],
            children: []
        };
        this.currentNode.children.push(newNode);
        this.currentNode = newNode;
        this.nodeStack.push(newNode);
    }
    popSchema(success) {
        this.nodeStack.pop();
        this.currentNode = this.nodeStack[this.nodeStack.length - 1];
        if (success) {
            this.currentNode.children.pop();
        }
        return success;
    }
    pushInstance(instance) {
        this.instancePath.push(instance);
    }
    popInstance() {
        this.instancePath.pop();
    }
    withSchemaPath(schemaPath, chunk) {
        this.pushSchema(schemaPath);
        return this.popSchema(chunk());
    }
    validate(schema, source, value, pruneErrors = true) {
        if (validateGeneric(value, schema, this)) {
            return [];
        }
        return this.collectErrors(schema, source, value, pruneErrors);
    }
    collectErrors(_schema, source, _value, pruneErrors = true) {
        const inner = (node)=>{
            const result = [];
            if (node.edge === "anyOf" && pruneErrors) {
                const innerResults = node.children.map(inner);
                const isRequiredError = (e)=>e.schemaPath.indexOf("required") === e.schemaPath.length - 1
                ;
                const isPropertyNamesError = (e)=>e.schemaPath.indexOf("required") !== -1
                ;
                if (innerResults.some((el)=>el.length && isRequiredError(el[0])
                ) && innerResults.some((el)=>el.length && isPropertyNamesError(el[0])
                )) {
                    return innerResults.filter((r)=>{
                        return r.length && r[0].schemaPath.slice(-1)[0] === "required";
                    })[0];
                }
                const errorTypeQuality = (e)=>{
                    const t = e.schemaPath.slice().reverse();
                    if (t[0] === "type") {
                        if (t[1] === "null") {
                            return 10;
                        }
                        return 1;
                    }
                    return 1;
                };
                const better = (a, b)=>{
                    for(let i35 = 0; i35 < a.length; ++i35){
                        if (a[i35] < b[i35]) {
                            return -1;
                        }
                        if (a[i35] > b[i35]) {
                            return 1;
                        }
                    }
                    return 0;
                };
                let bestResults = [];
                let bestError = [
                    Infinity,
                    Infinity
                ];
                for (const resultGroup of innerResults){
                    let maxQuality = -Infinity;
                    let totalSpan = 0;
                    for (const result of resultGroup){
                        totalSpan += result.value.end - result.value.start;
                        maxQuality = Math.max(maxQuality, errorTypeQuality(result));
                    }
                    const thisError = [
                        maxQuality,
                        totalSpan
                    ];
                    if (better(thisError, bestError)) {
                        bestError = thisError;
                        bestResults = resultGroup;
                    }
                }
                return bestResults;
            } else {
                result.push(...node.errors);
                for (const child of node.children){
                    result.push(...inner(child));
                }
                return result;
            }
        };
        const errors1 = inner(this.root);
        const locF = mappedIndexToRowCol(source);
        const result1 = errors1.map((validationError)=>{
            let location;
            try {
                location = {
                    start: locF(validationError.value.start),
                    end: locF(validationError.value.end)
                };
            } catch (_e) {
                location = {
                    start: {
                        line: 0,
                        column: 0
                    },
                    end: {
                        line: 0,
                        column: 0
                    }
                };
            }
            return {
                source: mappedString(source, [
                    {
                        start: validationError.value.start,
                        end: validationError.value.end
                    }
                ]),
                violatingObject: validationError.value,
                instancePath: validationError.instancePath,
                schemaPath: validationError.schemaPath,
                schema: validationError.schema,
                message: validationError.message,
                location: location,
                niceError: {
                    heading: validationError.message,
                    error: [],
                    info: {},
                    fileName: source.fileName,
                    location: location,
                    sourceContext: createSourceContext(source, location)
                }
            };
        });
        return result1;
    }
}
function createSourceContext(src, location) {
    const nLines = lines(src.originalString).length;
    const { start , end ,  } = location;
    const { prefixWidth , lines: formattedLines ,  } = formatLineRange(src.originalString, Math.max(0, start.line - 1), Math.min(end.line + 1, nLines - 1));
    const contextLines = [];
    let mustPrintEllipsis = true;
    for (const { lineNumber , content , rawLine  } of formattedLines){
        if (lineNumber < start.line || lineNumber > end.line) {
            if (rawLine.trim().length) {
                contextLines.push(content);
            }
        } else {
            if (lineNumber >= start.line + 2 && lineNumber <= end.line - 2) {
                if (mustPrintEllipsis) {
                    mustPrintEllipsis = false;
                    contextLines.push("...");
                }
            } else {
                const startColumn = lineNumber > start.line ? 0 : start.column;
                const endColumn = lineNumber < end.line ? rawLine.length : end.column;
                contextLines.push(content);
                contextLines.push(" ".repeat(prefixWidth + startColumn) + "~".repeat(endColumn - startColumn));
            }
        }
    }
    return contextLines.join("\n");
}
function validateGeneric(value, s, context) {
    s = resolveSchema(s);
    const st = schemaType(s);
    return context.withSchemaPath(st, ()=>schemaCall(s, {
            "false": (schema)=>{
                context.error(value, schema, "false");
                return false;
            },
            "true": (_)=>true
            ,
            "boolean": (schema)=>validateBoolean(value, schema, context)
            ,
            "number": (schema)=>validateNumber(value, schema, context)
            ,
            "string": (schema)=>validateString(value, schema, context)
            ,
            "null": (schema)=>validateNull(value, schema, context)
            ,
            "enum": (schema)=>validateEnum(value, schema, context)
            ,
            "anyOf": (schema)=>validateAnyOf(value, schema, context)
            ,
            "allOf": (schema)=>validateAllOf(value, schema, context)
            ,
            "array": (schema)=>validateArray(value, schema, context)
            ,
            "object": (schema)=>validateObject(value, schema, context)
            ,
            "ref": (schema)=>validateGeneric(value, resolveSchema(schema), context)
        })
    );
}
function typeIsValid(value, schema, context, valid) {
    if (!valid) {
        return context.withSchemaPath("type", ()=>{
            context.error(value, schema, "type mismatch");
            return false;
        });
    }
    return valid;
}
function validateBoolean(value, schema, context) {
    return typeIsValid(value, schema, context, typeof value.result === "boolean");
}
function validateNumber(value, schema, context) {
    if (!typeIsValid(value, schema, context, typeof value.result === "number")) {
        return false;
    }
    let result = true;
    if (schema.minimum !== undefined) {
        result = context.withSchemaPath("minimum", ()=>{
            const v = value.result;
            if (!(v >= schema.minimum)) {
                context.error(value, schema, `value ${value.result} is less than required minimum ${schema.minimum}`);
                return false;
            }
            return true;
        });
    }
    if (schema.maximum !== undefined) {
        result = context.withSchemaPath("maximum", ()=>{
            const v = value.result;
            if (!(v <= schema.maximum)) {
                context.error(value, schema, `value ${value.result} is greater than required maximum ${schema.maximum}`);
                return false;
            }
            return true;
        });
    }
    if (schema.exclusiveMinimum !== undefined) {
        result = context.withSchemaPath("exclusiveMinimum", ()=>{
            const v = value.result;
            if (!(v > schema.exclusiveMinimum)) {
                context.error(value, schema, `value ${value.result} is less than or equal to required (exclusive) minimum ${schema.exclusiveMinimum}`);
                return false;
            }
            return true;
        });
    }
    if (schema.exclusiveMaximum !== undefined) {
        result = context.withSchemaPath("exclusiveMaximum", ()=>{
            const v = value.result;
            if (!(v < schema.exclusiveMaximum)) {
                context.error(value, schema, `value ${value.result} is greater than or equal to required (exclusive) maximum ${schema.exclusiveMaximum}`);
                return false;
            }
            return true;
        });
    }
    return result;
}
function validateString(value, schema, context) {
    if (!typeIsValid(value, schema, context, typeof value.result === "string")) {
        return false;
    }
    if (schema.pattern !== undefined) {
        if (schema.compiledPattern === undefined) {
            schema.compiledPattern = new RegExp(schema.pattern);
        }
        if (!value.result.match(schema.compiledPattern)) {
            return context.withSchemaPath("pattern", ()=>{
                context.error(value, schema, `value doesn't match pattern`);
                return false;
            });
        }
    }
    return true;
}
function validateNull(value, schema, context) {
    if (!typeIsValid(value, schema, context, value.result === null)) {
        return false;
    }
    return true;
}
function validateEnum(value, schema, context) {
    for (const enumValue of schema["enum"]){
        if (enumValue === value.result) {
            return true;
        }
    }
    context.error(value, schema, `must match one of the values`);
    return false;
}
function validateAnyOf(value, schema, context) {
    let passingSchemas = 0;
    for(let i36 = 0; i36 < schema.anyOf.length; ++i36){
        const subSchema = schema.anyOf[i36];
        context.withSchemaPath(i36, ()=>{
            if (validateGeneric(value, subSchema, context)) {
                passingSchemas++;
                return true;
            }
            return false;
        });
    }
    return passingSchemas > 0;
}
function validateAllOf(value, schema, context) {
    let passingSchemas = 0;
    for(let i37 = 0; i37 < schema.allOf.length; ++i37){
        const subSchema = schema.allOf[i37];
        context.withSchemaPath(i37, ()=>{
            if (validateGeneric(value, subSchema, context)) {
                passingSchemas++;
                return true;
            }
            return false;
        });
    }
    return passingSchemas === schema.allOf.length;
}
function validateArray(value, schema, context) {
    let result2 = true;
    if (!typeIsValid(value, schema, context, Array.isArray(value.result))) {
        return false;
    }
    const length = value.result.length;
    if (schema.minItems !== undefined && length < schema.minItems) {
        context.withSchemaPath("minItems", ()=>{
            context.error(value, schema, `array should have at least ${schema.minItems} items but has ${length} items instead`);
            return false;
        });
        result2 = false;
    }
    if (schema.maxItems !== undefined && length > schema.maxItems) {
        context.withSchemaPath("maxItems", ()=>{
            context.error(value, schema, `array should have at most ${schema.maxItems} items but has ${length} items instead`);
            return false;
        });
        result2 = false;
    }
    if (schema.items !== undefined) {
        result2 = context.withSchemaPath("items", ()=>{
            let result = true;
            for(let i38 = 0; i38 < value.components.length; ++i38){
                context.pushInstance(i38);
                result = validateGeneric(value.components[i38], schema.items, context) && result;
                context.popInstance();
            }
            return result;
        }) && result2;
    }
    return result2;
}
function validateObject(value, schema, context) {
    const isObject2 = typeof value.result === "object" && !Array.isArray(value.result) && value.result !== null;
    if (!typeIsValid(value, schema, context, isObject2)) {
        return false;
    }
    let result3 = true;
    const ownProperties = new Set(Object.getOwnPropertyNames(value.result));
    const objResult = value.result;
    const locate = (key, keyOrValue = "value")=>{
        for(let i39 = 0; i39 < value.components.length; i39 += 2){
            if (value.components[i39].result === key) {
                if (keyOrValue === "value") {
                    return value.components[i39 + 1];
                } else {
                    return value.components[i39];
                }
            }
        }
        throw new Error(`Internal Error, couldn't locate key ${key}`);
    };
    const inspectedProps = new Set();
    if (schema.properties !== undefined) {
        result3 = context.withSchemaPath("properties", ()=>{
            let result = true;
            for (const [key, subSchema] of Object.entries(schema.properties)){
                if (ownProperties.has(key)) {
                    inspectedProps.add(key);
                    context.pushInstance(key);
                    result = context.withSchemaPath(key, ()=>validateGeneric(locate(key), subSchema, context)
                    ) && result;
                    context.popInstance();
                }
            }
            return result;
        }) && result3;
    }
    if (schema.patternProperties !== undefined) {
        result3 = context.withSchemaPath("patternProperties", ()=>{
            let result = true;
            for (const [key, subSchema] of Object.entries(schema.patternProperties)){
                if (schema.compiledPatterns === undefined) {
                    schema.compiledPatterns = {};
                }
                if (schema.compiledPatterns[key] === undefined) {
                    schema.compiledPatterns[key] = new RegExp(key);
                }
                const regexp2 = schema.compiledPatterns[key];
                for (const [objectKey, _val] of Object.entries(objResult)){
                    if (objectKey.match(regexp2)) {
                        inspectedProps.add(objectKey);
                        context.pushInstance(objectKey);
                        result = context.withSchemaPath(key, ()=>validateGeneric(locate(objectKey), subSchema, context)
                        ) && result;
                        context.popInstance();
                    }
                }
            }
            return result;
        }) && result3;
    }
    if (schema.additionalProperties !== undefined) {
        result3 = context.withSchemaPath("additionalProperties", ()=>{
            return Object.keys(objResult).filter((objectKey)=>!inspectedProps.has(objectKey)
            ).every((objectKey)=>validateGeneric(locate(objectKey), schema.additionalProperties, context)
            );
        }) && result3;
    }
    if (schema.propertyNames !== undefined) {
        result3 = context.withSchemaPath("propertyNames", ()=>{
            return Array.from(ownProperties).every((key)=>validateGeneric(locate(key, "key"), schema.propertyNames, context)
            );
        }) && result3;
    }
    if (schema.required !== undefined) {
        result3 = context.withSchemaPath("required", ()=>{
            let result = true;
            for (const reqKey of schema.required){
                if (!ownProperties.has(reqKey)) {
                    context.error(value, schema, `object is missing required property ${reqKey}`);
                    result = false;
                }
            }
            return result;
        }) && result3;
    }
    return result3;
}
function validate(value, schema, source) {
    const context = new ValidationContext();
    return context.validate(schema, source, value);
}
function getVerbatimInput(error8) {
    return error8.source.value;
}
function navigate(path45, annotation, returnKey = false, pathIndex = 0) {
    if (annotation === undefined) {
        throw new Error("Can't navigate an undefined annotation");
    }
    if (pathIndex >= path45.length) {
        return annotation;
    }
    if (annotation.kind === "mapping" || annotation.kind === "block_mapping") {
        const { components  } = annotation;
        const searchKey = path45[pathIndex];
        const lastKeyIndex = ~~((components.length - 1) / 2) * 2;
        for(let i40 = lastKeyIndex; i40 >= 0; i40 -= 2){
            const key = components[i40].result;
            if (key === searchKey) {
                if (returnKey && pathIndex === path45.length - 1) {
                    return navigate(path45, components[i40], returnKey, pathIndex + 1);
                } else {
                    return navigate(path45, components[i40 + 1], returnKey, pathIndex + 1);
                }
            }
        }
        return annotation;
    } else if ([
        "sequence",
        "block_sequence",
        "flow_sequence"
    ].indexOf(annotation.kind) !== -1) {
        const searchKey = Number(path45[pathIndex]);
        if (isNaN(searchKey) || searchKey < 0 || searchKey >= annotation.components.length) {
            return annotation;
        }
        return navigate(path45, annotation.components[searchKey], returnKey, pathIndex + 1);
    } else {
        return annotation;
    }
}
class YAMLSchema {
    schema;
    errorHandlers;
    constructor(schema){
        this.errorHandlers = [];
        this.schema = schema;
    }
    addHandler(handler) {
        this.errorHandlers.push(handler);
    }
    transformErrors(annotation, errors2) {
        return errors2.map((error9)=>{
            for (const handler of this.errorHandlers){
                error9 = handler(error9, annotation, this.schema);
            }
            return error9;
        });
    }
    async validateParse(src, annotation) {
        const validationErrors = validate(annotation, this.schema, src);
        if (validationErrors.length) {
            const localizedErrors = this.transformErrors(annotation, validationErrors);
            return {
                result: annotation.result,
                errors: localizedErrors
            };
        } else {
            return {
                result: annotation.result,
                errors: []
            };
        }
    }
    reportErrorsInSource(result, _src, message, error10, log) {
        if (result.errors.length) {
            if (message.length) {
                error10(message);
            }
            for (const err of result.errors){
                log(err.niceError);
            }
        }
        return result;
    }
    async validateParseWithErrors(src, annotation, message, error11, log) {
        const result = await this.validateParse(src, annotation);
        this.reportErrorsInSource(result, src, message, error11, log);
        return result;
    }
}
function setDefaultErrorHandlers(validator) {
    validator.addHandler(expandEmptySpan);
    validator.addHandler(improveErrorHeadingForValueErrors);
    validator.addHandler(checkForTypeMismatch);
    validator.addHandler(checkForBadBoolean);
    validator.addHandler(checkForBadColon);
    validator.addHandler(identifyKeyErrors);
    validator.addHandler(checkForNearbyCorrection);
    validator.addHandler(checkForNearbyRequired);
    validator.addHandler(schemaDefinedErrors);
}
function errorKeyword(error12) {
    if (error12.schemaPath.length === 0) {
        return "";
    }
    return String(error12.schemaPath[error12.schemaPath.length - 1]);
}
function getBadKey(error13) {
    if (error13.schemaPath.indexOf("propertyNames") === -1) {
        return undefined;
    }
    const result = error13.violatingObject.result;
    if (typeof result !== "string") {
        throw new Error("Internal Error: propertyNames error has a violating non-string.");
    }
    return result;
}
function isEmptyValue(error14) {
    const rawVerbatimInput = getVerbatimInput(error14);
    return rawVerbatimInput.trim().length === 0;
}
function getLastFragment(instancePath) {
    if (instancePath.length === 0) {
        return undefined;
    }
    return instancePath[instancePath.length - 1];
}
function reindent(str65) {
    return str65;
}
function formatHeadingForKeyError(_error, _parse, _schema, key) {
    return `property name ${blue1(key)} is invalid`;
}
function formatHeadingForValueError(error15, _parse, _schema) {
    const rawVerbatimInput = reindent(getVerbatimInput(error15));
    const rawLines = lines(rawVerbatimInput);
    let verbatimInput;
    if (rawLines.length > 4) {
        verbatimInput = quotedStringColor([
            ...rawLines.slice(0, 2),
            "...",
            ...rawLines.slice(-2)
        ].join("\n"));
    } else {
        verbatimInput = quotedStringColor(rawVerbatimInput);
    }
    const empty1 = isEmptyValue(error15);
    const lastFragment = getLastFragment(error15.instancePath);
    switch(typeof lastFragment){
        case "undefined":
            if (empty1) {
                return "YAML value is missing.";
            } else {
                return `YAML value ${verbatimInput} must ${schemaDescription(error15.schema)}.`;
            }
        case "number":
            if (empty1) {
                return `Array entry ${lastFragment + 1} is empty but it must instead ${schemaDescription(error15.schema)}.`;
            } else {
                return `Array entry ${lastFragment + 1} with value ${verbatimInput} failed to ${schemaDescription(error15.schema)}.`;
            }
        case "string":
            {
                const formatLastFragment = blue1(lastFragment);
                if (empty1) {
                    return `Key ${formatLastFragment} has empty value but it must instead ${schemaDescription(error15.schema)}`;
                } else {
                    return `Key ${formatLastFragment} has value ${verbatimInput}, which must ${schemaDescription(error15.schema)}`;
                }
            }
    }
}
function identifyKeyErrors(error16, parse10, schema) {
    if (error16.schemaPath.indexOf("propertyNames") === -1) {
        return error16;
    }
    const badKey = getBadKey(error16);
    if (badKey) {
        if (error16.instancePath.length && error16.instancePath[error16.instancePath.length - 1] !== badKey) {
            addInstancePathInfo(error16.niceError, [
                ...error16.instancePath,
                badKey
            ]);
        } else {
            addInstancePathInfo(error16.niceError, error16.instancePath);
        }
        error16.niceError.heading = formatHeadingForKeyError(error16, parse10, schema, badKey);
    }
    return error16;
}
function improveErrorHeadingForValueErrors(error17, parse11, schema) {
    if (error17.schemaPath.indexOf("propertyNames") !== -1 || errorKeyword(error17) === "required") {
        return error17;
    }
    return {
        ...error17,
        niceError: {
            ...error17.niceError,
            heading: formatHeadingForValueError(error17, parse11, schema)
        }
    };
}
function expandEmptySpan(error18, parse12, _schema) {
    if (error18.location.start.line !== error18.location.end.line || error18.location.start.column !== error18.location.end.column || !isEmptyValue(error18) || typeof getLastFragment(error18.instancePath) === "undefined") {
        return error18;
    }
    const lastKey = navigate(error18.instancePath, parse12, true);
    const locF = mappedIndexToRowCol(parse12.source);
    try {
        const location = {
            start: locF(lastKey.start - 1),
            end: locF(lastKey.end - 1)
        };
        return {
            ...error18,
            location,
            niceError: {
                ...error18.niceError,
                location
            }
        };
    } catch (_e) {
        return error18;
    }
}
function checkForTypeMismatch(error19, parse13, schema) {
    const rawVerbatimInput = getVerbatimInput(error19);
    const rawLines = lines(rawVerbatimInput);
    let verbatimInput;
    if (rawLines.length > 4) {
        verbatimInput = quotedStringColor([
            ...rawLines.slice(0, 2),
            "...",
            ...rawLines.slice(-2)
        ].join("\n"));
    } else {
        verbatimInput = quotedStringColor(rawVerbatimInput);
    }
    const goodType = (obj)=>{
        if (Array.isArray(obj)) {
            return "an array";
        }
        if (obj === null) {
            return "a null value";
        }
        return typeof obj;
    };
    if (errorKeyword(error19) === "type" && rawVerbatimInput.length > 0) {
        const newError = {
            ...error19.niceError,
            heading: formatHeadingForValueError(error19, parse13, schema),
            error: [
                `The value ${verbatimInput} is ${goodType(error19.violatingObject.result)}.`, 
            ],
            info: {},
            location: error19.niceError.location
        };
        addInstancePathInfo(newError, error19.instancePath);
        addFileInfo(newError, error19.source);
        return {
            ...error19,
            niceError: newError
        };
    }
    return error19;
}
function checkForBadBoolean(error20, parse14, _schema) {
    const schema = error20.schema;
    if (!(typeof error20.violatingObject.result === "string" && errorKeyword(error20) === "type" && schemaType(schema) === "boolean")) {
        return error20;
    }
    const strValue = error20.violatingObject.result;
    const verbatimInput = quotedStringColor(getVerbatimInput(error20));
    const yesses = new Set("y|Y|yes|Yes|YES|true|True|TRUE|on|On|ON".split("|"));
    const nos = new Set("n|N|no|No|NO|false|False|FALSE|off|Off|OFF".split("|"));
    let fix;
    if (yesses.has(strValue)) {
        fix = true;
    } else if (nos.has(strValue)) {
        fix = false;
    } else {
        return error20;
    }
    const errorMessage = `The value ${verbatimInput} is a string.`;
    const suggestion1 = `Quarto uses YAML 1.2, which interprets booleans strictly.`;
    const suggestion2 = `Try using ${quotedStringColor(String(fix))} instead.`;
    const newError = {
        heading: formatHeadingForValueError(error20, parse14, schema),
        error: [
            errorMessage
        ],
        info: {},
        location: error20.niceError.location
    };
    addInstancePathInfo(newError, error20.instancePath);
    addFileInfo(newError, error20.source);
    newError.info["yaml-version-1.2"] = suggestion1;
    newError.info["suggestion-fix"] = suggestion2;
    return {
        ...error20,
        niceError: newError
    };
}
function checkForBadColon(error21, parse15, schema) {
    if (typeof error21.violatingObject.result !== "string") {
        return error21;
    }
    const e = error21.schemaPath.slice(-2);
    if (e.length !== 2) {
        return error21;
    }
    if (e[0] !== "object" || e[1] !== "type") {
        return error21;
    }
    if (!error21.violatingObject.result.match(/^.+:[^ ].*$/)) {
        return error21;
    }
    const verbatimInput = quotedStringColor(getVerbatimInput(error21));
    const errorMessage = `The value ${verbatimInput} is a string.`;
    const suggestion1 = `In YAML, key-value pairs in objects must be separated by a space.`;
    const suggestion2 = `Did you mean ${quotedStringColor(quotedStringColor(getVerbatimInput(error21)).replace(/:/g, ": "))} instead?`;
    const newError = {
        heading: formatHeadingForValueError(error21, parse15, schema),
        error: [
            errorMessage
        ],
        info: {},
        location: error21.niceError.location
    };
    addInstancePathInfo(newError, error21.instancePath);
    addFileInfo(newError, error21.source);
    newError.info["yaml-key-value-pairs"] = suggestion1;
    newError.info["suggestion-fix"] = suggestion2;
    return {
        ...error21,
        niceError: newError
    };
}
function createErrorFragments(error22) {
    const rawVerbatimInput = getVerbatimInput(error22);
    const verbatimInput = quotedStringColor(reindent(rawVerbatimInput));
    const pathFragments = error22.instancePath.map((s)=>blue1(String(s))
    );
    return {
        location: locationString(error22.location),
        fullPath: pathFragments.join(":"),
        key: pathFragments[pathFragments.length - 1],
        value: verbatimInput
    };
}
function schemaDefinedErrors(error23, _parse, _schema) {
    const schema = error23.schema;
    if (schema === true || schema === false) {
        return error23;
    }
    if (schema.errorMessage === undefined) {
        return error23;
    }
    if (typeof schema.errorMessage !== "string") {
        return error23;
    }
    let result = schema.errorMessage;
    for (const [k, v] of Object.entries(createErrorFragments(error23))){
        result = result.replace("${" + k + "}", v);
    }
    return {
        ...error23,
        niceError: {
            ...error23.niceError,
            heading: result
        }
    };
}
function checkForNearbyRequired(error24, _parse, _schema) {
    const schema = error24.schema;
    if (errorKeyword(error24) !== "required") {
        return error24;
    }
    const missingKeys = [];
    const errObj = error24.violatingObject.result;
    const keys7 = Object.keys(errObj);
    schemaCall(schema, {
        object (s) {
            if (s.required === undefined) {
                throw new Error("Internal Error: required schema error without a required field");
            }
            for (const r of s.required){
                if (keys7.indexOf(r) === -1) {
                    missingKeys.push(r);
                }
            }
        }
    }, (_)=>{
        throw new Error("Internal Error: required error on a non-object schema");
    });
    for (const missingKey of missingKeys){
        let bestCorrection;
        let bestDistance = Infinity;
        for (const correction of keys7){
            const d = editDistance(correction, missingKey);
            if (d < bestDistance) {
                bestCorrection = [
                    correction
                ];
                bestDistance = d;
            } else if (d === bestDistance) {
                bestCorrection.push(correction);
                bestDistance = d;
            }
        }
        if (bestDistance > missingKey.length * 10 * 0.3) {
            continue;
        }
        const suggestions = bestCorrection.map((s)=>blue1(s)
        );
        if (suggestions.length === 1) {
            error24.niceError.info[`did-you-mean-key`] = `Is ${suggestions[0]} a typo of ${blue1(missingKey)}?`;
        } else if (suggestions.length === 2) {
            error24.niceError.info[`did-you-mean-key`] = `Is ${suggestions[0]} or ${suggestions[1]} a typo of ${blue1(missingKey)}?`;
        } else {
            suggestions[suggestions.length - 1] = `or ${suggestions[suggestions.length - 1]}`;
            error24.niceError.info[`did-you-mean-key`] = `Is one of ${suggestions.join(", ")} a typo of ${blue1(missingKey)}?`;
        }
    }
    return error24;
}
function checkForNearbyCorrection(error25, parse16, _schema) {
    const schema = error25.schema;
    const corrections = [];
    let errVal = "";
    let keyOrValue = "";
    const key = getBadKey(error25);
    if (key) {
        errVal = key;
        corrections.push(...possibleSchemaKeys(schema));
        keyOrValue = "key";
    } else {
        const val = navigate(error25.instancePath, parse16);
        if (typeof val.result !== "string") {
            return error25;
        }
        errVal = val.result;
        corrections.push(...possibleSchemaValues(schema));
        keyOrValue = "value";
    }
    if (corrections.length === 0) {
        return error25;
    }
    let bestCorrection;
    let bestDistance = Infinity;
    for (const correction of corrections){
        const d = editDistance(correction, errVal);
        if (d < bestDistance) {
            bestCorrection = [
                correction
            ];
            bestDistance = d;
        } else if (d === bestDistance) {
            bestCorrection.push(correction);
            bestDistance = d;
        }
    }
    if (bestDistance > errVal.length * 10 * 0.3) {
        return error25;
    }
    const suggestions = bestCorrection.map((s)=>blue1(s)
    );
    if (suggestions.length === 1) {
        error25.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions[0]}?`;
    } else if (suggestions.length === 2) {
        error25.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions[0]} or ${suggestions[1]}?`;
    } else {
        suggestions[suggestions.length - 1] = `or ${suggestions[suggestions.length - 1]}`;
        error25.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions.join(", ")}?`;
    }
    return error25;
}
const yamlValidators = {};
function getSchemaName(schema) {
    if (schema === true || schema === false) {
        throw new Error("Expected schema to be named");
    }
    let schemaName = schema["$id"];
    if (schemaName !== undefined) {
        return schemaName;
    }
    if (schemaType(schema) === "ref") {
        schemaName = schema["$ref"];
    }
    if (schemaName !== undefined) {
        return schemaName;
    }
    throw new Error("Expected schema to be named");
}
function getValidator(schema) {
    const schemaName = getSchemaName(schema);
    if (yamlValidators[schemaName]) {
        return yamlValidators[schemaName];
    }
    const validator = new YAMLSchema(schema);
    yamlValidators[schemaName] = validator;
    setDefaultErrorHandlers(validator);
    return validator;
}
async function withValidator(schema, fun) {
    let result;
    let error26;
    try {
        const validator = getValidator(schema);
        result = await fun(validator);
    } catch (e) {
        error26 = e;
    }
    if (error26 !== undefined) {
        throw error26;
    }
    return result;
}
function addValidatorErrorHandler(schema, handler) {
    return withValidator(schema, async (validator)=>{
        validator.addHandler(handler);
    });
}
function memoize(f, keyMemoizer) {
    const memo = {};
    const inner = (...args)=>{
        const key = keyMemoizer(...args);
        const v = memo[key];
        if (v !== undefined) {
            return v;
        }
        memo[key] = f(...args);
        return memo[key];
    };
    return inner;
}
const regExpEscapeChars1 = [
    "!",
    "$",
    "(",
    ")",
    "*",
    "+",
    ".",
    "=",
    "?",
    "[",
    "\\",
    "^",
    "{",
    "|", 
];
const rangeEscapeChars1 = [
    "-",
    "\\",
    "]"
];
function globToRegExp1(glob, { extended =true , globstar: globstarOption = true , caseInsensitive =false  } = {}) {
    if (glob == "") {
        return /(?!)/;
    }
    const sep6 = "/+";
    const sepMaybe = "/*";
    const seps = [
        "/"
    ];
    const globstar = "(?:[^/]*(?:/|$)+)*";
    const wildcard = "[^/]*";
    const escapePrefix = "\\";
    let newLength = glob.length;
    for(; newLength > 1 && seps.includes(glob[newLength - 1]); newLength--);
    glob = glob.slice(0, newLength);
    let regExpString = "";
    for(let j = 0; j < glob.length;){
        let segment = "";
        const groupStack = [];
        let inRange = false;
        let inEscape = false;
        let endsWithSep = false;
        let i41 = j;
        for(; i41 < glob.length && !seps.includes(glob[i41]); i41++){
            if (inEscape) {
                inEscape = false;
                const escapeChars = inRange ? rangeEscapeChars1 : regExpEscapeChars1;
                segment += escapeChars.includes(glob[i41]) ? `\\${glob[i41]}` : glob[i41];
                continue;
            }
            if (glob[i41] == escapePrefix) {
                inEscape = true;
                continue;
            }
            if (glob[i41] == "[") {
                if (!inRange) {
                    inRange = true;
                    segment += "[";
                    if (glob[i41 + 1] == "!") {
                        i41++;
                        segment += "^";
                    } else if (glob[i41 + 1] == "^") {
                        i41++;
                        segment += "\\^";
                    }
                    continue;
                } else if (glob[i41 + 1] == ":") {
                    let k = i41 + 1;
                    let value = "";
                    while(glob[k + 1] != null && glob[k + 1] != ":"){
                        value += glob[k + 1];
                        k++;
                    }
                    if (glob[k + 1] == ":" && glob[k + 2] == "]") {
                        i41 = k + 2;
                        if (value == "alnum") segment += "\\dA-Za-z";
                        else if (value == "alpha") segment += "A-Za-z";
                        else if (value == "ascii") segment += "\x00-\x7F";
                        else if (value == "blank") segment += "\t ";
                        else if (value == "cntrl") segment += "\x00-\x1F\x7F";
                        else if (value == "digit") segment += "\\d";
                        else if (value == "graph") segment += "\x21-\x7E";
                        else if (value == "lower") segment += "a-z";
                        else if (value == "print") segment += "\x20-\x7E";
                        else if (value == "punct") {
                            segment += "!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_‘{|}~";
                        } else if (value == "space") segment += "\\s\v";
                        else if (value == "upper") segment += "A-Z";
                        else if (value == "word") segment += "\\w";
                        else if (value == "xdigit") segment += "\\dA-Fa-f";
                        continue;
                    }
                }
            }
            if (glob[i41] == "]" && inRange) {
                inRange = false;
                segment += "]";
                continue;
            }
            if (inRange) {
                if (glob[i41] == "\\") {
                    segment += `\\\\`;
                } else {
                    segment += glob[i41];
                }
                continue;
            }
            if (glob[i41] == ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
                segment += ")";
                const type = groupStack.pop();
                if (type == "!") {
                    segment += wildcard;
                } else if (type != "@") {
                    segment += type;
                }
                continue;
            }
            if (glob[i41] == "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i41] == "+" && extended && glob[i41 + 1] == "(") {
                i41++;
                groupStack.push("+");
                segment += "(?:";
                continue;
            }
            if (glob[i41] == "@" && extended && glob[i41 + 1] == "(") {
                i41++;
                groupStack.push("@");
                segment += "(?:";
                continue;
            }
            if (glob[i41] == "?") {
                if (extended && glob[i41 + 1] == "(") {
                    i41++;
                    groupStack.push("?");
                    segment += "(?:";
                } else {
                    segment += ".";
                }
                continue;
            }
            if (glob[i41] == "!" && extended && glob[i41 + 1] == "(") {
                i41++;
                groupStack.push("!");
                segment += "(?!";
                continue;
            }
            if (glob[i41] == "{") {
                groupStack.push("BRACE");
                segment += "(?:";
                continue;
            }
            if (glob[i41] == "}" && groupStack[groupStack.length - 1] == "BRACE") {
                groupStack.pop();
                segment += ")";
                continue;
            }
            if (glob[i41] == "," && groupStack[groupStack.length - 1] == "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i41] == "*") {
                if (extended && glob[i41 + 1] == "(") {
                    i41++;
                    groupStack.push("*");
                    segment += "(?:";
                } else {
                    const prevChar = glob[i41 - 1];
                    let numStars = 1;
                    while(glob[i41 + 1] == "*"){
                        i41++;
                        numStars++;
                    }
                    const nextChar = glob[i41 + 1];
                    if (globstarOption && numStars == 2 && [
                        ...seps,
                        undefined
                    ].includes(prevChar) && [
                        ...seps,
                        undefined
                    ].includes(nextChar)) {
                        segment += globstar;
                        endsWithSep = true;
                    } else {
                        segment += wildcard;
                    }
                }
                continue;
            }
            segment += regExpEscapeChars1.includes(glob[i41]) ? `\\${glob[i41]}` : glob[i41];
        }
        if (groupStack.length > 0 || inRange || inEscape) {
            segment = "";
            for (const c of glob.slice(j, i41)){
                segment += regExpEscapeChars1.includes(c) ? `\\${c}` : c;
                endsWithSep = false;
            }
        }
        regExpString += segment;
        if (!endsWithSep) {
            regExpString += i41 < glob.length ? sep6 : sepMaybe;
            endsWithSep = true;
        }
        while(seps.includes(glob[i41]))i41++;
        if (!(i41 > j)) {
            throw new Error("Assertion failure: i > j (potential infinite loop)");
        }
        j = i41;
    }
    regExpString = `^${regExpString}$`;
    return new RegExp(regExpString, caseInsensitive ? "i" : "");
}
const _resources = {};
function setYamlIntelligenceResources(resources) {
    for (const [key, value] of Object.entries(resources)){
        _resources[key] = value;
    }
}
function exportYamlIntelligenceResources(pretty = false) {
    if (pretty) {
        return JSON.stringify(_resources, null, 2);
    } else {
        return JSON.stringify(_resources);
    }
}
function getYamlIntelligenceResource(filename) {
    if (_resources[filename] === undefined) {
        throw new Error(`Internal Error: getYamlIntelligenceResource called with missing resource ${filename}`);
    }
    return _resources[filename];
}
function expandResourceGlob(glob) {
    return Object.keys(_resources).filter((key)=>key.match(globToRegExp1(glob))
    ).map((key)=>[
            key,
            getYamlIntelligenceResource(key)
        ]
    );
}
function fromEntries(iterable) {
    return [
        ...iterable
    ].reduce((obj, [key, val])=>{
        obj[key] = val;
        return obj;
    }, {});
}
function setBaseSchemaProperties(yaml, schema) {
    if (yaml.additionalCompletions) {
        schema = completeSchema(schema, ...yaml.additionalCompletions);
    }
    if (yaml.completions) {
        schema = completeSchemaOverwrite(schema, ...yaml.completions);
    }
    if (yaml.id) {
        schema = idSchema(schema, yaml.id);
    }
    if (yaml.hidden === true) {
        schema = completeSchemaOverwrite(schema);
        schema = tagSchema(schema, {
            "hidden": true
        });
    }
    if (yaml.tags) {
        schema = tagSchema(schema, yaml.tags);
    }
    if (yaml.description) {
        schema = tagSchema(schema, {
            description: yaml.description
        });
        if (typeof yaml.description === "string") {
            schema = documentSchema(schema, yaml.description);
        } else if (typeof yaml.description === "object") {
            schema = documentSchema(schema, yaml.description.short);
        }
    }
    const result = Object.assign({}, schema);
    if (yaml.errorDescription) {
        result.description = yaml.errorDescription;
    }
    if (yaml.errorMessage) {
        result.errorMessage = yaml.errorMessage;
    }
    return result;
}
function convertFromNull(yaml) {
    return setBaseSchemaProperties(yaml["null"], nullSchema);
}
function convertFromSchema(yaml) {
    const schema = convertFromYaml(yaml.schema);
    return setBaseSchemaProperties(yaml, schema);
}
function convertFromString(yaml) {
    if (yaml["string"].pattern) {
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml["string"], regexSchema(yaml["string"].pattern)));
    } else {
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml["string"], stringSchema));
    }
}
function convertFromPattern(yaml) {
    if (typeof yaml.pattern === "string") {
        return setBaseSchemaProperties(yaml, regexSchema(yaml.pattern));
    } else {
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml.pattern, regexSchema(yaml.pattern.regex)));
    }
}
function convertFromPath(yaml) {
    return setBaseSchemaProperties(yaml["path"], stringSchema);
}
function convertFromNumber(yaml) {
    return setBaseSchemaProperties(yaml["number"], numberSchema);
}
function convertFromBoolean(yaml) {
    return setBaseSchemaProperties(yaml["boolean"], booleanSchema);
}
function convertFromRef(yaml) {
    return setBaseSchemaProperties(yaml, refSchema(yaml.ref, `be ${yaml.ref}`));
}
function convertFromMaybeArrayOf(yaml) {
    const inner = convertFromYaml(yaml.maybeArrayOf);
    const schema = tagSchema(anyOfSchema(inner, arraySchema(inner)), {
        "complete-from": [
            "anyOf",
            0
        ]
    });
    return setBaseSchemaProperties(yaml, schema);
}
function convertFromArrayOf(yaml) {
    if (yaml.arrayOf.schema) {
        const result = arraySchema(convertFromYaml(yaml.arrayOf.schema));
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml.arrayOf, result));
    } else {
        return setBaseSchemaProperties(yaml, arraySchema(convertFromYaml(yaml.arrayOf)));
    }
}
function convertFromAllOf(yaml) {
    if (yaml.allOf.schemas) {
        const inner = yaml.allOf.schemas.map((x)=>convertFromYaml(x)
        );
        const schema = allOfSchema(...inner);
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml.allOf, schema));
    } else {
        const inner = yaml.allOf.map((x)=>convertFromYaml(x)
        );
        const schema = allOfSchema(...inner);
        return setBaseSchemaProperties(yaml, schema);
    }
}
function convertFromAnyOf(yaml) {
    if (yaml.anyOf.schemas) {
        const inner = yaml.anyOf.schemas.map((x)=>convertFromYaml(x)
        );
        const schema = anyOfSchema(...inner);
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml.anyOf, schema));
    } else {
        const inner = yaml.anyOf.map((x)=>convertFromYaml(x)
        );
        const schema = anyOfSchema(...inner);
        return setBaseSchemaProperties(yaml, schema);
    }
}
function convertFromEnum(yaml) {
    const schema = yaml["enum"];
    if (schema.hasOwnProperty("values")) {
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml["enum"], enumSchema(...schema.values)));
    } else {
        return setBaseSchemaProperties(yaml, enumSchema(...schema));
    }
}
function convertFromRecord(yaml) {
    if (yaml.record.properties) {
        const schema = convertFromObject({
            "object": {
                "properties": yaml.record.properties,
                "closed": true,
                "required": "all"
            }
        });
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml.record, schema));
    } else {
        const schema = convertFromObject({
            "object": {
                "properties": yaml.record,
                "closed": true,
                "required": "all"
            }
        });
        return setBaseSchemaProperties(yaml, schema);
    }
}
function convertFromObject(yaml) {
    const schema = yaml["object"];
    const params = {};
    if (schema.namingConvention) {
        switch(schema.namingConvention){
            case "capitalizationCase":
                params.namingConvention = "capitalizationCase";
                break;
            case "capitalization-case":
                params.namingConvention = "capitalizationCase";
                break;
            case "capitalization_case":
                params.namingConvention = "capitalizationCase";
                break;
            case "underscoreCase":
                params.namingConvention = "underscore_case";
                break;
            case "underscore-case":
                params.namingConvention = "underscore_case";
                break;
            case "underscore_case":
                params.namingConvention = "underscore_case";
                break;
            case "dashCase":
                params.namingConvention = "dash-case";
                break;
            case "dash-case":
                params.namingConvention = "dash-case";
                break;
            case "dash_case":
                params.namingConvention = "dash-case";
                break;
            case "camelCase":
                params.namingConvention = "capitalizationCase";
                break;
            case "camel-case":
                params.namingConvention = "capitalizationCase";
                break;
            case "camel_case":
                params.namingConvention = "capitalizationCase";
                break;
            case "snakeCase":
                params.namingConvention = "underscore_case";
                break;
            case "snake-case":
                params.namingConvention = "underscore_case";
                break;
            case "snake_case":
                params.namingConvention = "underscore_case";
                break;
            case "kebabCase":
                params.namingConvention = "dash-case";
                break;
            case "kebab-case":
                params.namingConvention = "dash-case";
                break;
            case "kebab_case":
                params.namingConvention = "dash-case";
                break;
            default:
                throw new Error("Internal Error: this should have failed validation");
        }
        params.namingConvention = schema.namingConvention;
    }
    if (schema.properties) {
        params.properties = fromEntries(Object.entries(schema.properties).map(([key, value])=>[
                key,
                convertFromYaml(value)
            ]
        ));
    }
    if (schema.patternProperties) {
        params.patternProperties = fromEntries(Object.entries(schema.properties).map(([key, value])=>[
                key,
                convertFromYaml(value)
            ]
        ));
    }
    if (schema.propertyNames !== undefined) {
        params.propertyNames = convertFromYaml(schema.propertyNames);
    } else if (schema.closed === true) {
        const objectKeys = Object.keys(params.properties || {});
        if (objectKeys.length === 0) {
            throw new Error("object schema `closed` requires field `properties`.");
        }
        if (params.namingConvention !== undefined && params.namingConvention !== "ignore") {
            throw new Error("object schema `closed` is only supported with namingConvention: `ignore`");
        }
        params.namingConvention = "ignore";
        params.propertyNames = enumSchema(...objectKeys);
    }
    if (schema.additionalProperties !== undefined) {
        if (schema.additionalProperties === false) {
            params.additionalProperties = false;
        } else {
            params.additionalProperties = convertFromYaml(schema.additionalProperties);
        }
    }
    if (schema["super"]) {
        params.baseSchema = convertFromYaml(schema["super"]);
    }
    if (schema["required"] === "all") {
        params.required = Object.keys(schema.properties || {});
    } else if (schema["required"]) {
        params.required = schema["required"];
    }
    if (schema["completions"]) {
        params.completions = schema["completions"];
    }
    return setBaseSchemaProperties(yaml, setBaseSchemaProperties(schema, objectSchema(params)));
}
function lookup(yaml) {
    if (!hasSchemaDefinition(yaml.resolveRef)) {
        throw new Error(`lookup of key ${yaml.resolveRef} in definitions failed`);
    }
    return getSchemaDefinition(yaml.resolveRef);
}
function convertFromYaml(yaml) {
    const literalValues = [
        {
            val: "object",
            schema: objectSchema()
        },
        {
            val: "path",
            schema: stringSchema
        },
        {
            val: "string",
            schema: stringSchema
        },
        {
            val: "number",
            schema: numberSchema
        },
        {
            val: "boolean",
            schema: booleanSchema
        },
        {
            val: null,
            schema: nullSchema
        }, 
    ];
    for (const { val , schema  } of literalValues){
        if (yaml === val) {
            return schema;
        }
    }
    if (typeof yaml !== "object") {
        return valueSchema(yaml);
    }
    const schemaObjectKeyFunctions = [
        {
            key: "anyOf",
            value: convertFromAnyOf
        },
        {
            key: "allOf",
            value: convertFromAllOf
        },
        {
            key: "boolean",
            value: convertFromBoolean
        },
        {
            key: "arrayOf",
            value: convertFromArrayOf
        },
        {
            key: "enum",
            value: convertFromEnum
        },
        {
            key: "maybeArrayOf",
            value: convertFromMaybeArrayOf
        },
        {
            key: "null",
            value: convertFromNull
        },
        {
            key: "number",
            value: convertFromNumber
        },
        {
            key: "object",
            value: convertFromObject
        },
        {
            key: "path",
            value: convertFromPath
        },
        {
            key: "record",
            value: convertFromRecord
        },
        {
            key: "ref",
            value: convertFromRef
        },
        {
            key: "resolveRef",
            value: lookup
        },
        {
            key: "string",
            value: convertFromString
        },
        {
            key: "pattern",
            value: convertFromPattern
        },
        {
            key: "schema",
            value: convertFromSchema
        }, 
    ];
    for (const { key: objectKey , value: fun  } of schemaObjectKeyFunctions){
        if (yaml[objectKey] !== undefined) {
            return fun(yaml);
        }
    }
    throw new Error("Internal Error: Cannot convert object; this should have failed validation.");
}
function objectSchemaFromFieldsObject(fields, exclude) {
    exclude = exclude || ((_key)=>false
    );
    const properties = {};
    convertFromFieldsObject(fields, properties);
    for (const key of Object.keys(properties)){
        if (exclude(key)) {
            delete properties[key];
        }
    }
    return objectSchema({
        properties
    });
}
function annotateSchemaFromField(field, schema) {
    if (field.enabled !== undefined) {
        schema = tagSchema(schema, {
            formats: field.enabled
        });
    }
    if (field.disabled !== undefined) {
        schema = tagSchema(schema, {
            formats: field.disabled.map((x)=>`!${x}`
            )
        });
    }
    if (field.tags) {
        schema = tagSchema(schema, field.tags);
    }
    if (field.description) {
        if (typeof field.description === "string") {
            schema = documentSchema(schema, field.description);
        } else if (typeof field.description === "object") {
            schema = documentSchema(schema, field.description.short);
        }
        schema = tagSchema(schema, {
            description: field.description
        });
    }
    if (field.hidden) {
        schema = tagSchema(schema, {
            "hidden": true
        });
    }
    return schema;
}
function schemaFromField(entry) {
    const schema = convertFromYaml(entry.schema);
    return annotateSchemaFromField(entry, schema);
}
function convertFromFieldsObject(yaml, obj) {
    const result = obj || {};
    for (const field of yaml){
        let schema = convertFromYaml(field.schema);
        schema = annotateSchemaFromField(field, schema);
        result[field.name] = schema;
        if (field.alias) {
            result[field.alias] = schema;
        }
    }
    return result;
}
function schemaFieldsFromGlob(globPath, testFun) {
    const result = [];
    testFun = testFun || ((_e, _p)=>true
    );
    for (const [file, fields] of expandResourceGlob(globPath)){
        for (const field of fields){
            const fieldName = field.name;
            const schemaId = `quarto-resource-${file.split("/").slice(-1)[0].slice(0, -4)}-${fieldName}`;
            if (testFun(field, file)) {
                result.push({
                    schemaId,
                    field
                });
            }
        }
    }
    return result;
}
memoize(()=>{
    const groups = getYamlIntelligenceResource("schema/groups.yml");
    const result = [];
    for (const [topLevel, sub] of Object.entries(groups)){
        for (const key of Object.keys(sub)){
            result.push(`${topLevel}-${key}`);
        }
    }
    return result;
}, ()=>"const"
);
function objectRefSchemaFromContextGlob(contextGlob, testFun) {
    const regexp3 = globToRegExp1(contextGlob);
    return objectRefSchemaFromGlob("schema/{document,cell}-*.yml", (field, path46)=>{
        if (testFun !== undefined && !testFun(field, path46)) {
            return false;
        }
        const pathContext = path46.split("/").slice(-1)[0].slice(0, -4);
        const schemaContexts = field !== undefined && field.tags !== undefined && field.tags.contexts || [];
        if (pathContext.match(regexp3)) {
            return true;
        }
        return schemaContexts.some((c)=>c.match(regexp3)
        );
    });
}
function objectRefSchemaFromGlob(glob, testFun) {
    const properties = {};
    for (const { schemaId , field  } of schemaFieldsFromGlob(glob, testFun)){
        const schema = refSchema(schemaId, schemaId);
        properties[field.name] = schema;
        if (field.alias) {
            properties[field.alias] = schema;
        }
    }
    return objectSchema({
        properties
    });
}
async function buildResourceSchemas() {
    const path47 = "schema/{cell-*,document-*,project}.yml";
    for (const [file, fields] of expandResourceGlob(path47)){
        const yaml = fields;
        const entries = Object.entries(convertFromFieldsObject(yaml));
        for (const [fieldName, fieldSchema] of entries){
            const schemaId = `quarto-resource-${file.split("/").slice(-1)[0].slice(0, -4)}-${fieldName}`;
            const schema = idSchema(fieldSchema, schemaId);
            setSchemaDefinition(schema);
            await withValidator(schema, async (_validator)=>{});
        }
    }
}
function defineCached(thunk, schemaId) {
    let schema;
    return async ()=>{
        if (hasSchemaDefinition(schemaId)) {
            schema = getSchemaDefinition(schemaId);
            return refSchema(schema.$id, schema.description || `be a {schema['$id'] as string}`);
        }
        const result = await thunk();
        const { errorHandlers  } = result;
        schema = result.schema;
        if (schemaId !== schema.$id) {
            schema = idSchema(schema, schemaId);
        }
        define(schema);
        for (const fun of errorHandlers){
            addValidatorErrorHandler(schema, fun);
        }
        return refSchema(schema.$id, schema.description || `be a {schema['$id']}`);
    };
}
function define(schema) {
    if (schema !== true && schema !== false && schema.$id && !hasSchemaDefinition(schema.$id)) {
        setSchemaDefinition(schema);
    }
}
async function loadDefaultSchemaDefinitions() {
    await loadSchemaDefinitions(getYamlIntelligenceResource("schema/definitions.yml"));
    await buildResourceSchemas();
}
async function loadSchemaDefinitions(yaml) {
    await Promise.all(yaml.map(async (yamlSchema)=>{
        const schema = convertFromYaml(yamlSchema);
        if (schema.$id === undefined) {
            throw new Error(`Internal error: unnamed schema in definitions`);
        }
        setSchemaDefinition(schema);
    }));
}
function getFormatExecuteOptionsSchema() {
    const schema = idSchema(objectRefSchemaFromContextGlob("document-execute"), "front-matter-execute");
    define(schema);
    return refSchema("front-matter-execute", "be a front-matter-execute object");
}
let formatAliases = undefined;
function getFormatAliases() {
    if (formatAliases !== undefined) {
        return formatAliases;
    }
    formatAliases = getYamlIntelligenceResource("schema/format-aliases.yml").aliases;
    return formatAliases;
}
function expandFormatAliases(lst) {
    return expandAliasesFrom(lst, getFormatAliases());
}
function useSchema(schema, format4) {
    const formats1 = schema && schema.tags && schema.tags.formats;
    if (formats1 === undefined) {
        return true;
    }
    const disabled = formats1.filter((f)=>f.startsWith("!")
    ).map((f)=>f.slice(1)
    );
    const enabled2 = formats1.filter((f)=>!f.startsWith("!")
    );
    if (disabled.length > 0 && expandFormatAliases(disabled).indexOf(format4) !== -1) {
        return false;
    }
    if (enabled2.length > 0 && expandFormatAliases(enabled2).indexOf(format4) === -1) {
        return false;
    }
    return true;
}
function getFormatSchema(format5) {
    const schema1 = objectRefSchemaFromContextGlob("document-*", (field)=>{
        const schema = schemaFromField(field);
        return useSchema(schema, format5);
    });
    return anyOfSchema(schema1, enumSchema("default"));
}
function pandocFormatsResource() {
    return getYamlIntelligenceResource("pandoc/formats.yml");
}
async function makeFrontMatterFormatSchema(nonStrict = false) {
    const hideFormat = (format6)=>{
        const hideList = [
            "html",
            "epub",
            "docbook"
        ];
        const hidden26 = hideList.some((h)=>format6.startsWith(h) && format6.length > h.length
        );
        return {
            name: format6,
            hidden: hidden26
        };
    };
    const formatSchemaDescriptorList = (await pandocFormatsResource()).concat("hugo").map((format7)=>{
        const { name: name77 , hidden: hidden27 ,  } = hideFormat(format7);
        return {
            regex: `^${name77}(\\+.+)?$`,
            schema: getFormatSchema(name77),
            name: name77,
            hidden: hidden27
        };
    });
    const formatSchemas = formatSchemaDescriptorList.map(({ regex , schema  })=>[
            regex,
            schema
        ]
    );
    const plusFormatStringSchemas = formatSchemaDescriptorList.map(({ regex , name: name78 , hidden: hidden28  })=>{
        const schema = regexSchema(regex, `be '${name78}'`);
        if (hidden28) {
            return schema;
        }
        return completeSchema(schema, name78);
    });
    const completionsObject = fromEntries(formatSchemaDescriptorList.filter(({ hidden: hidden29  })=>!hidden29
    ).map(({ name: name79  })=>[
            name79,
            ""
        ]
    ));
    return errorMessageSchema(anyOfSchema(describeSchema(anyOfSchema(...plusFormatStringSchemas), "the name of a pandoc-supported output format"), allOfSchema(objectSchema({
        patternProperties: fromEntries(formatSchemas),
        completions: completionsObject,
        additionalProperties: nonStrict
    }))), "${value} is not a valid output format.");
}
const getFrontMatterFormatSchema = defineCached(async ()=>{
    return {
        schema: await makeFrontMatterFormatSchema(),
        errorHandlers: []
    };
}, "front-matter-format");
defineCached(async ()=>{
    return {
        schema: await makeFrontMatterFormatSchema(true),
        errorHandlers: []
    };
}, "front-matter-format-nonstrict");
const getFrontMatterSchema = defineCached(async ()=>{
    const executeObjSchema = await getFormatExecuteOptionsSchema();
    return {
        schema: anyOfSchema(nullSchema, allOfSchema(objectSchema({
            properties: {
                execute: executeObjSchema,
                format: await getFrontMatterFormatSchema()
            },
            description: "be a Quarto YAML front matter object"
        }), objectRefSchemaFromContextGlob("document-*", (field)=>field.name !== "format"
        ), executeObjSchema)),
        errorHandlers: []
    };
}, "front-matter");
function Diff() {}
Diff.prototype = {
    diff: function diff(oldString, newString) {
        var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
        var callback = options.callback;
        if (typeof options === "function") {
            callback = options;
            options = {};
        }
        this.options = options;
        var self = this;
        function done(value) {
            if (callback) {
                setTimeout(function() {
                    callback(void 0, value);
                }, 0);
                return true;
            } else {
                return value;
            }
        }
        oldString = this.castInput(oldString);
        newString = this.castInput(newString);
        oldString = this.removeEmpty(this.tokenize(oldString));
        newString = this.removeEmpty(this.tokenize(newString));
        var newLen = newString.length, oldLen = oldString.length;
        var editLength = 1;
        var maxEditLength = newLen + oldLen;
        var bestPath = [
            {
                newPos: -1,
                components: []
            }
        ];
        var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
        if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
            return done([
                {
                    value: this.join(newString),
                    count: newString.length
                }
            ]);
        }
        function execEditLength() {
            for(var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2){
                var basePath = void 0;
                var addPath1 = bestPath[diagonalPath - 1], removePath1 = bestPath[diagonalPath + 1], _oldPos = (removePath1 ? removePath1.newPos : 0) - diagonalPath;
                if (addPath1) {
                    bestPath[diagonalPath - 1] = void 0;
                }
                var canAdd = addPath1 && addPath1.newPos + 1 < newLen, canRemove = removePath1 && 0 <= _oldPos && _oldPos < oldLen;
                if (!canAdd && !canRemove) {
                    bestPath[diagonalPath] = void 0;
                    continue;
                }
                if (!canAdd || canRemove && addPath1.newPos < removePath1.newPos) {
                    basePath = clonePath(removePath1);
                    self.pushComponent(basePath.components, void 0, true);
                } else {
                    basePath = addPath1;
                    basePath.newPos++;
                    self.pushComponent(basePath.components, true, void 0);
                }
                _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
                if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
                    return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
                } else {
                    bestPath[diagonalPath] = basePath;
                }
            }
            editLength++;
        }
        if (callback) {
            (function exec1() {
                setTimeout(function() {
                    if (editLength > maxEditLength) {
                        return callback();
                    }
                    if (!execEditLength()) {
                        exec1();
                    }
                }, 0);
            })();
        } else {
            while(editLength <= maxEditLength){
                var ret = execEditLength();
                if (ret) {
                    return ret;
                }
            }
        }
    },
    pushComponent: function pushComponent(components, added, removed) {
        var last = components[components.length - 1];
        if (last && last.added === added && last.removed === removed) {
            components[components.length - 1] = {
                count: last.count + 1,
                added,
                removed
            };
        } else {
            components.push({
                count: 1,
                added,
                removed
            });
        }
    },
    extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
        var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
        while(newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])){
            newPos++;
            oldPos++;
            commonCount++;
        }
        if (commonCount) {
            basePath.components.push({
                count: commonCount
            });
        }
        basePath.newPos = newPos;
        return oldPos;
    },
    equals: function equals(left, right) {
        if (this.options.comparator) {
            return this.options.comparator(left, right);
        } else {
            return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
        }
    },
    removeEmpty: function removeEmpty(array) {
        var ret = [];
        for(var i42 = 0; i42 < array.length; i42++){
            if (array[i42]) {
                ret.push(array[i42]);
            }
        }
        return ret;
    },
    castInput: function castInput(value) {
        return value;
    },
    tokenize: function tokenize(value) {
        return value.split("");
    },
    join: function join(chars) {
        return chars.join("");
    }
};
function buildValues(diff2, components, newString, oldString, useLongestToken) {
    var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
    for(; componentPos < componentLen; componentPos++){
        var component = components[componentPos];
        if (!component.removed) {
            if (!component.added && useLongestToken) {
                var value = newString.slice(newPos, newPos + component.count);
                value = value.map(function(value2, i43) {
                    var oldValue = oldString[oldPos + i43];
                    return oldValue.length > value2.length ? oldValue : value2;
                });
                component.value = diff2.join(value);
            } else {
                component.value = diff2.join(newString.slice(newPos, newPos + component.count));
            }
            newPos += component.count;
            if (!component.added) {
                oldPos += component.count;
            }
        } else {
            component.value = diff2.join(oldString.slice(oldPos, oldPos + component.count));
            oldPos += component.count;
            if (componentPos && components[componentPos - 1].added) {
                var tmp = components[componentPos - 1];
                components[componentPos - 1] = components[componentPos];
                components[componentPos] = tmp;
            }
        }
    }
    var lastComponent = components[componentLen - 1];
    if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff2.equals("", lastComponent.value)) {
        components[componentLen - 2].value += lastComponent.value;
        components.pop();
    }
    return components;
}
function clonePath(path48) {
    return {
        newPos: path48.newPos,
        components: path48.components.slice(0)
    };
}
new Diff();
var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
var reWhitespace = /\S/;
var wordDiff = new Diff();
wordDiff.equals = function(left, right) {
    if (this.options.ignoreCase) {
        left = left.toLowerCase();
        right = right.toLowerCase();
    }
    return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
};
wordDiff.tokenize = function(value) {
    var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
    for(var i44 = 0; i44 < tokens.length - 1; i44++){
        if (!tokens[i44 + 1] && tokens[i44 + 2] && extendedWordChars.test(tokens[i44]) && extendedWordChars.test(tokens[i44 + 2])) {
            tokens[i44] += tokens[i44 + 2];
            tokens.splice(i44 + 1, 2);
            i44--;
        }
    }
    return tokens;
};
var lineDiff = new Diff();
lineDiff.tokenize = function(value) {
    var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
    if (!linesAndNewlines[linesAndNewlines.length - 1]) {
        linesAndNewlines.pop();
    }
    for(var i45 = 0; i45 < linesAndNewlines.length; i45++){
        var line = linesAndNewlines[i45];
        if (i45 % 2 && !this.options.newlineIsToken) {
            retLines[retLines.length - 1] += line;
        } else {
            if (this.options.ignoreWhitespace) {
                line = line.trim();
            }
            retLines.push(line);
        }
    }
    return retLines;
};
function diffLines(oldStr, newStr, callback) {
    return lineDiff.diff(oldStr, newStr, callback);
}
var sentenceDiff = new Diff();
sentenceDiff.tokenize = function(value) {
    return value.split(/(\S.+?[.!?])(?=\s+|$)/);
};
var cssDiff = new Diff();
cssDiff.tokenize = function(value) {
    return value.split(/([{}:;,]|\s+)/);
};
function _typeof(obj) {
    "@babel/helpers - typeof";
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function(obj2) {
            return typeof obj2;
        };
    } else {
        _typeof = function(obj2) {
            return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
        };
    }
    return _typeof(obj);
}
var objectPrototypeToString = Object.prototype.toString;
var jsonDiff = new Diff();
jsonDiff.useLongestToken = true;
jsonDiff.tokenize = lineDiff.tokenize;
jsonDiff.castInput = function(value) {
    var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
        return typeof v === "undefined" ? undefinedReplacement : v;
    } : _this$options$stringi;
    return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, "  ");
};
jsonDiff.equals = function(left, right) {
    return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
};
function canonicalize(obj, stack, replacementStack, replacer, key) {
    stack = stack || [];
    replacementStack = replacementStack || [];
    if (replacer) {
        obj = replacer(key, obj);
    }
    var i46;
    for(i46 = 0; i46 < stack.length; i46 += 1){
        if (stack[i46] === obj) {
            return replacementStack[i46];
        }
    }
    var canonicalizedObj;
    if (objectPrototypeToString.call(obj) === "[object Array]") {
        stack.push(obj);
        canonicalizedObj = new Array(obj.length);
        replacementStack.push(canonicalizedObj);
        for(i46 = 0; i46 < obj.length; i46 += 1){
            canonicalizedObj[i46] = canonicalize(obj[i46], stack, replacementStack, replacer, key);
        }
        stack.pop();
        replacementStack.pop();
        return canonicalizedObj;
    }
    if (obj && obj.toJSON) {
        obj = obj.toJSON();
    }
    if (_typeof(obj) === "object" && obj !== null) {
        stack.push(obj);
        canonicalizedObj = {};
        replacementStack.push(canonicalizedObj);
        var sortedKeys = [], _key;
        for(_key in obj){
            if (obj.hasOwnProperty(_key)) {
                sortedKeys.push(_key);
            }
        }
        sortedKeys.sort();
        for(i46 = 0; i46 < sortedKeys.length; i46 += 1){
            _key = sortedKeys[i46];
            canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
        }
        stack.pop();
        replacementStack.pop();
    } else {
        canonicalizedObj = obj;
    }
    return canonicalizedObj;
}
var arrayDiff = new Diff();
arrayDiff.tokenize = function(value) {
    return value.slice();
};
arrayDiff.join = arrayDiff.removeEmpty = function(value) {
    return value;
};
function matchAll1(str66, regex) {
    let match;
    regex = new RegExp(regex);
    const result = [];
    while((match = regex.exec(str66)) != null){
        result.push(match);
    }
    return result;
}
function rangedLines(text, includeNewLines = false) {
    const regex = /\r?\n/g;
    const result = [];
    let startOffset = 0;
    if (!includeNewLines) {
        for (const r of matchAll1(text, regex)){
            result.push({
                substring: text.substring(startOffset, r.index),
                range: {
                    start: startOffset,
                    end: r.index
                }
            });
            startOffset = r.index + r[0].length;
        }
        result.push({
            substring: text.substring(startOffset, text.length),
            range: {
                start: startOffset,
                end: text.length
            }
        });
        return result;
    } else {
        const matches = matchAll1(text, regex);
        let prevOffset = 0;
        for (const r of matches){
            const stringEnd = r.index + 1;
            result.push({
                substring: text.substring(prevOffset, stringEnd),
                range: {
                    start: prevOffset,
                    end: stringEnd
                }
            });
            prevOffset = stringEnd;
        }
        result.push({
            substring: text.substring(prevOffset, text.length),
            range: {
                start: prevOffset,
                end: text.length
            }
        });
        return result;
    }
}
function mappedDiff(source, target) {
    const sourceLineRanges = rangedLines(source.value).map((x)=>x.range
    );
    let sourceCursor = 0;
    const resultChunks = [];
    for (const action of diffLines(source.value, target)){
        if (action.removed) {
            sourceCursor += action.count;
        } else if (action.added) {
            resultChunks.push(action.value);
        } else {
            const start = sourceLineRanges[sourceCursor].start;
            const nextCursor = sourceCursor + action.count;
            const end = nextCursor < sourceLineRanges.length ? sourceLineRanges[nextCursor].start : sourceLineRanges[sourceLineRanges.length - 1].end;
            sourceCursor = nextCursor;
            resultChunks.push({
                start,
                end
            });
        }
    }
    return mappedString(source, resultChunks, source.fileName);
}
function getenv(name80, defaultValue) {
    const value = Deno.env.get(name80);
    if (value === undefined) {
        if (defaultValue === undefined) {
            throw new Error(`Required environment variable ${name80} not specified.`);
        } else {
            return defaultValue;
        }
    } else {
        return value;
    }
}
function appendLogOptions(cmd) {
    return cmd.option("--log <level>", "Path to log file", {
        global: true
    }).option("--log-level <level>", "Log level (info, warning, error, critical)", {
        global: true
    }).option("--log-format <format>", "Log format (plain, json-stream)", {
        global: true
    }).option("--quiet", "Suppress console output.", {
        global: true
    });
}
function logOptions(args) {
    const logOptions1 = {};
    logOptions1.log = args.l || args.log;
    logOptions1.level = args.ll || args["log-level"];
    logOptions1.quiet = args.q || args.quiet;
    logOptions1.format = parseFormat(args.lf || args["log-format"]);
    return logOptions1;
}
class StdErrOutputHandler extends BaseHandler {
    format(logRecord, prefix = true) {
        const options = {
            newline: true,
            colorize: true,
            ...logRecord.args[0]
        };
        let msg = super.format(logRecord);
        if (prefix && logRecord.level >= LogLevels.WARNING) {
            msg = `${logRecord.levelName}: ${msg}`;
        }
        switch(logRecord.level){
            case LogLevels.INFO:
            case LogLevels.DEBUG:
                msg = applyMsgOptions(msg, options);
                break;
            case LogLevels.WARNING:
                if (options.colorize) {
                    msg = yellow(msg);
                }
                break;
            case LogLevels.ERROR:
                if (options.colorize) {
                    msg = brightRed(msg);
                }
                break;
            case LogLevels.CRITICAL:
                if (options.colorize) {
                    msg = bold(red(msg));
                }
                break;
            default:
                break;
        }
        if (options.newline) {
            msg = msg + "\n";
        }
        return msg;
    }
    log(msg) {
        Deno.stderr.writeSync(new TextEncoder().encode(msg));
    }
}
class LogEventsHandler extends StdErrOutputHandler {
    constructor(levelName){
        super(levelName, {
            formatter: "{msg}"
        });
    }
    handle(logRecord) {
        LogEventsHandler.handlers_.forEach((handler)=>handler(logRecord, super.format(logRecord, false))
        );
    }
    static onLog(handler) {
        LogEventsHandler.handlers_.push(handler);
    }
    static handlers_ = new Array();
}
class LogFileHandler extends FileHandler {
    constructor(levelName, options){
        super(levelName, options);
        this.msgFormat = options.format;
    }
    msgFormat;
    format(logRecord) {
        if (logRecord.msg.startsWith("\r")) {
            return "";
        }
        if (this.msgFormat === undefined || this.msgFormat === "plain") {
            const options = {
                newline: true,
                ...logRecord.args[0],
                bold: false,
                dim: false,
                format: undefined
            };
            let msg = applyMsgOptions(logRecord.msg, options);
            if (options.newline) {
                msg = msg + "\n";
            }
            if (logRecord.level >= LogLevels.WARNING) {
                return `(${logRecord.levelName}) ${msg}`;
            } else {
                return msg;
            }
        } else {
            return JSON.stringify(logRecord, undefined, 0) + "\n";
        }
    }
    log(msg) {
        if (msg !== "") {
            msg = stripColor(msg);
            this._buf.writeSync(this._encoder.encode(msg));
            this._buf.flush();
        }
    }
}
async function initializeLogger(logOptions2) {
    const handlers = {};
    const defaultHandlers = [];
    const file = logOptions2.log;
    const logLevel = logOptions2.level ? parseLevel(logOptions2.level) : "INFO";
    handlers["events"] = new LogEventsHandler(logLevel);
    defaultHandlers.push("events");
    if (!logOptions2.quiet) {
        handlers["console"] = new StdErrOutputHandler(logLevel, {
            formatter: "{msg}"
        });
        defaultHandlers.push("console");
    }
    if (file) {
        handlers["file"] = new LogFileHandler(logLevel, {
            filename: file,
            mode: "w",
            format: logOptions2.format
        });
        defaultHandlers.push("file");
    }
    await setup({
        handlers,
        loggers: {
            default: {
                level: "DEBUG",
                handlers: defaultHandlers
            }
        }
    });
}
async function cleanupLogger() {
    const logger = getLogger();
    for (const handler of logger.handlers){
        await handler.destroy();
    }
    logger.handlers = [];
}
function logError(e) {
    const err = asErrorEx(e);
    let message = err.printName ? `${err.name}: ${err.message}` : err.message;
    const isDebug = getenv("QUARTO_DEBUG", "false") === "true";
    if (isDebug && err.stack && err.printStack) {
        message = message + "\n\n" + err.stack;
    }
    if (message) {
        error(message);
    }
}
function errorOnce(msg) {
    if (!errors[msg]) {
        errors[msg] = true;
        error(msg);
        return true;
    }
    return false;
}
const errors = {};
function warnOnce(msg) {
    if (!warnings[msg]) {
        warnings[msg] = true;
        warning(msg);
    }
}
const warnings = {};
function applyMsgOptions(msg1, options) {
    if (options.indent) {
        const pad = " ".repeat(options.indent);
        msg1 = lines(msg1).map((msg)=>pad + msg
        ).join("\n");
    }
    if (options.bold) {
        msg1 = bold(msg1);
    }
    if (options.dim) {
        msg1 = dim(msg1);
    }
    if (options.format) {
        msg1 = options.format(msg1);
    }
    return msg1;
}
function parseFormat(format8) {
    if (format8) {
        format8 = format8.toLowerCase();
        switch(format8){
            case "plain":
            case "json-stream":
                return format8;
            default:
                return "plain";
        }
    } else {
        return "plain";
    }
}
function parseLevel(level) {
    const lvl = levelMap[level.toLowerCase()];
    if (lvl) {
        return lvl;
    } else {
        return "WARNING";
    }
}
const levelMap = {
    debug: "DEBUG",
    info: "INFO",
    warning: "WARNING",
    error: "ERROR",
    critical: "CRITICAL"
};
function readAnnotatedYamlFromMappedString(mappedYaml) {
    const yml = mappedYaml.value;
    const stack = [];
    const results = [];
    function listener(what, state37) {
        const { result , position , kind  } = state37;
        if (what === "close") {
            const { position: openPosition  } = stack.pop();
            if (results.length > 0) {
                const last = results[results.length - 1];
                if (last.start === openPosition && last.end === position) {
                    return;
                }
            }
            const components = [];
            while(results.length > 0){
                const last = results[results.length - 1];
                if (last.end <= openPosition) {
                    break;
                }
                components.push(results.pop());
            }
            components.reverse();
            const rawRange = yml.substring(openPosition, position);
            const leftTrim = rawRange.length - rawRange.trimLeft().length;
            const rightTrim = rawRange.length - rawRange.trimRight().length;
            if (rawRange.trim().length === 0) {
                results.push({
                    start: position - rightTrim,
                    end: position - rightTrim,
                    result: result,
                    components,
                    kind,
                    source: mappedString(mappedYaml, [
                        {
                            start: position - rightTrim,
                            end: position - rightTrim
                        }
                    ])
                });
            } else {
                results.push({
                    start: openPosition + leftTrim,
                    end: position - rightTrim,
                    result: result,
                    components,
                    kind,
                    source: mappedString(mappedYaml, [
                        {
                            start: position + leftTrim,
                            end: position - rightTrim
                        }
                    ])
                });
            }
        } else {
            stack.push({
                position
            });
        }
    }
    parse3(yml, {
        listener,
        schema: json
    });
    if (results.length === 0) {
        return {
            start: 0,
            end: 0,
            result: null,
            kind: "null",
            components: [],
            source: mappedString(mappedYaml, [
                {
                    start: 0,
                    end: 0
                }
            ])
        };
    }
    if (results.length !== 1) {
        throw new Error(`Internal Error - expected a single result, got ${results.length} instead`);
    }
    JSON.stringify(results[0]);
    return results[0];
}
function listCacheClear() {
    this.__data__ = [];
    this.size = 0;
}
var __VIRTUAL_FILE = listCacheClear;
function eq(value, other) {
    return value === other || value !== value && other !== other;
}
var __VIRTUAL_FILE1 = eq;
function assocIndexOf(array, key) {
    var length = array.length;
    while(length--){
        if (__VIRTUAL_FILE1(array[length][0], key)) {
            return length;
        }
    }
    return -1;
}
var __VIRTUAL_FILE2 = assocIndexOf;
var arrayProto = Array.prototype;
var splice = arrayProto.splice;
function listCacheDelete(key) {
    var data31 = this.__data__, index = __VIRTUAL_FILE2(data31, key);
    if (index < 0) {
        return false;
    }
    var lastIndex = data31.length - 1;
    if (index == lastIndex) {
        data31.pop();
    } else {
        splice.call(data31, index, 1);
    }
    --this.size;
    return true;
}
var __VIRTUAL_FILE3 = listCacheDelete;
function listCacheGet(key) {
    var data32 = this.__data__, index = __VIRTUAL_FILE2(data32, key);
    return index < 0 ? void 0 : data32[index][1];
}
var __VIRTUAL_FILE4 = listCacheGet;
function listCacheHas(key) {
    return __VIRTUAL_FILE2(this.__data__, key) > -1;
}
var __VIRTUAL_FILE5 = listCacheHas;
function listCacheSet(key, value) {
    var data33 = this.__data__, index = __VIRTUAL_FILE2(data33, key);
    if (index < 0) {
        ++this.size;
        data33.push([
            key,
            value
        ]);
    } else {
        data33[index][1] = value;
    }
    return this;
}
var __VIRTUAL_FILE6 = listCacheSet;
function ListCache(entries) {
    var index = -1, length = entries == null ? 0 : entries.length;
    this.clear();
    while(++index < length){
        var entry = entries[index];
        this.set(entry[0], entry[1]);
    }
}
ListCache.prototype.clear = __VIRTUAL_FILE;
ListCache.prototype["delete"] = __VIRTUAL_FILE3;
ListCache.prototype.get = __VIRTUAL_FILE4;
ListCache.prototype.has = __VIRTUAL_FILE5;
ListCache.prototype.set = __VIRTUAL_FILE6;
var __VIRTUAL_FILE7 = ListCache;
function stackClear() {
    this.__data__ = new __VIRTUAL_FILE7();
    this.size = 0;
}
var __VIRTUAL_FILE8 = stackClear;
function stackDelete(key) {
    var data34 = this.__data__, result = data34["delete"](key);
    this.size = data34.size;
    return result;
}
var __VIRTUAL_FILE9 = stackDelete;
function stackGet(key) {
    return this.__data__.get(key);
}
var __VIRTUAL_FILE10 = stackGet;
function stackHas(key) {
    return this.__data__.has(key);
}
var __VIRTUAL_FILE11 = stackHas;
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var __VIRTUAL_FILE12 = freeGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = __VIRTUAL_FILE12 || freeSelf || Function("return this")();
var __VIRTUAL_FILE13 = root;
var Symbol1 = __VIRTUAL_FILE13.Symbol;
var __VIRTUAL_FILE14 = Symbol1;
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
var nativeObjectToString = objectProto.toString;
var symToStringTag = __VIRTUAL_FILE14 ? __VIRTUAL_FILE14.toStringTag : void 0;
function getRawTag(value) {
    var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
    try {
        value[symToStringTag] = void 0;
        var unmasked = true;
    } catch (e) {}
    var result = nativeObjectToString.call(value);
    if (unmasked) {
        if (isOwn) {
            value[symToStringTag] = tag;
        } else {
            delete value[symToStringTag];
        }
    }
    return result;
}
var __VIRTUAL_FILE15 = getRawTag;
var objectProto1 = Object.prototype;
var nativeObjectToString1 = objectProto1.toString;
function objectToString(value) {
    return nativeObjectToString1.call(value);
}
var __VIRTUAL_FILE16 = objectToString;
var nullTag = "[object Null]", undefinedTag = "[object Undefined]";
var symToStringTag1 = __VIRTUAL_FILE14 ? __VIRTUAL_FILE14.toStringTag : void 0;
function baseGetTag(value) {
    if (value == null) {
        return value === void 0 ? undefinedTag : nullTag;
    }
    return symToStringTag1 && symToStringTag1 in Object(value) ? __VIRTUAL_FILE15(value) : __VIRTUAL_FILE16(value);
}
var __VIRTUAL_FILE17 = baseGetTag;
function isObject1(value) {
    var type = typeof value;
    return value != null && (type == "object" || type == "function");
}
var __VIRTUAL_FILE18 = isObject1;
var asyncTag = "[object AsyncFunction]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
function isFunction(value) {
    if (!__VIRTUAL_FILE18(value)) {
        return false;
    }
    var tag = __VIRTUAL_FILE17(value);
    return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var __VIRTUAL_FILE19 = isFunction;
var coreJsData = __VIRTUAL_FILE13["__core-js_shared__"];
var __VIRTUAL_FILE20 = coreJsData;
var maskSrcKey = function() {
    var uid = /[^.]+$/.exec(__VIRTUAL_FILE20 && __VIRTUAL_FILE20.keys && __VIRTUAL_FILE20.keys.IE_PROTO || "");
    return uid ? "Symbol(src)_1." + uid : "";
}();
function isMasked(func) {
    return !!maskSrcKey && maskSrcKey in func;
}
var __VIRTUAL_FILE21 = isMasked;
var funcProto = Function.prototype;
var funcToString = funcProto.toString;
function toSource(func) {
    if (func != null) {
        try {
            return funcToString.call(func);
        } catch (e) {}
        try {
            return func + "";
        } catch (e1) {}
    }
    return "";
}
var __VIRTUAL_FILE22 = toSource;
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var funcProto1 = Function.prototype, objectProto2 = Object.prototype;
var funcToString1 = funcProto1.toString;
var hasOwnProperty1 = objectProto2.hasOwnProperty;
var reIsNative = RegExp("^" + funcToString1.call(hasOwnProperty1).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
function baseIsNative(value) {
    if (!__VIRTUAL_FILE18(value) || __VIRTUAL_FILE21(value)) {
        return false;
    }
    var pattern = __VIRTUAL_FILE19(value) ? reIsNative : reIsHostCtor;
    return pattern.test(__VIRTUAL_FILE22(value));
}
var __VIRTUAL_FILE23 = baseIsNative;
function getValue(object, key) {
    return object == null ? void 0 : object[key];
}
var __VIRTUAL_FILE24 = getValue;
function getNative(object, key) {
    var value = __VIRTUAL_FILE24(object, key);
    return __VIRTUAL_FILE23(value) ? value : void 0;
}
var __VIRTUAL_FILE25 = getNative;
var Map1 = __VIRTUAL_FILE25(__VIRTUAL_FILE13, "Map");
var __VIRTUAL_FILE26 = Map1;
var nativeCreate = __VIRTUAL_FILE25(Object, "create");
var __VIRTUAL_FILE27 = nativeCreate;
function hashClear() {
    this.__data__ = __VIRTUAL_FILE27 ? __VIRTUAL_FILE27(null) : {};
    this.size = 0;
}
var __VIRTUAL_FILE28 = hashClear;
function hashDelete(key) {
    var result = this.has(key) && delete this.__data__[key];
    this.size -= result ? 1 : 0;
    return result;
}
var __VIRTUAL_FILE29 = hashDelete;
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var objectProto3 = Object.prototype;
var hasOwnProperty2 = objectProto3.hasOwnProperty;
function hashGet(key) {
    var data35 = this.__data__;
    if (__VIRTUAL_FILE27) {
        var result = data35[key];
        return result === HASH_UNDEFINED ? void 0 : result;
    }
    return hasOwnProperty2.call(data35, key) ? data35[key] : void 0;
}
var __VIRTUAL_FILE30 = hashGet;
var objectProto4 = Object.prototype;
var hasOwnProperty3 = objectProto4.hasOwnProperty;
function hashHas(key) {
    var data36 = this.__data__;
    return __VIRTUAL_FILE27 ? data36[key] !== void 0 : hasOwnProperty3.call(data36, key);
}
var __VIRTUAL_FILE31 = hashHas;
var HASH_UNDEFINED1 = "__lodash_hash_undefined__";
function hashSet(key, value) {
    var data37 = this.__data__;
    this.size += this.has(key) ? 0 : 1;
    data37[key] = __VIRTUAL_FILE27 && value === void 0 ? HASH_UNDEFINED1 : value;
    return this;
}
var __VIRTUAL_FILE32 = hashSet;
function Hash(entries) {
    var index = -1, length = entries == null ? 0 : entries.length;
    this.clear();
    while(++index < length){
        var entry = entries[index];
        this.set(entry[0], entry[1]);
    }
}
Hash.prototype.clear = __VIRTUAL_FILE28;
Hash.prototype["delete"] = __VIRTUAL_FILE29;
Hash.prototype.get = __VIRTUAL_FILE30;
Hash.prototype.has = __VIRTUAL_FILE31;
Hash.prototype.set = __VIRTUAL_FILE32;
var __VIRTUAL_FILE33 = Hash;
function mapCacheClear() {
    this.size = 0;
    this.__data__ = {
        hash: new __VIRTUAL_FILE33(),
        map: new (__VIRTUAL_FILE26 || __VIRTUAL_FILE7)(),
        string: new __VIRTUAL_FILE33()
    };
}
var __VIRTUAL_FILE34 = mapCacheClear;
function isKeyable(value) {
    var type = typeof value;
    return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
var __VIRTUAL_FILE35 = isKeyable;
function getMapData(map6, key) {
    var data38 = map6.__data__;
    return __VIRTUAL_FILE35(key) ? data38[typeof key == "string" ? "string" : "hash"] : data38.map;
}
var __VIRTUAL_FILE36 = getMapData;
function mapCacheDelete(key) {
    var result = __VIRTUAL_FILE36(this, key)["delete"](key);
    this.size -= result ? 1 : 0;
    return result;
}
var __VIRTUAL_FILE37 = mapCacheDelete;
function mapCacheGet(key) {
    return __VIRTUAL_FILE36(this, key).get(key);
}
var __VIRTUAL_FILE38 = mapCacheGet;
function mapCacheHas(key) {
    return __VIRTUAL_FILE36(this, key).has(key);
}
var __VIRTUAL_FILE39 = mapCacheHas;
function mapCacheSet(key, value) {
    var data39 = __VIRTUAL_FILE36(this, key), size = data39.size;
    data39.set(key, value);
    this.size += data39.size == size ? 0 : 1;
    return this;
}
var __VIRTUAL_FILE40 = mapCacheSet;
function MapCache(entries) {
    var index = -1, length = entries == null ? 0 : entries.length;
    this.clear();
    while(++index < length){
        var entry = entries[index];
        this.set(entry[0], entry[1]);
    }
}
MapCache.prototype.clear = __VIRTUAL_FILE34;
MapCache.prototype["delete"] = __VIRTUAL_FILE37;
MapCache.prototype.get = __VIRTUAL_FILE38;
MapCache.prototype.has = __VIRTUAL_FILE39;
MapCache.prototype.set = __VIRTUAL_FILE40;
var __VIRTUAL_FILE41 = MapCache;
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
    var data40 = this.__data__;
    if (data40 instanceof __VIRTUAL_FILE7) {
        var pairs1 = data40.__data__;
        if (!__VIRTUAL_FILE26 || pairs1.length < LARGE_ARRAY_SIZE - 1) {
            pairs1.push([
                key,
                value
            ]);
            this.size = ++data40.size;
            return this;
        }
        data40 = this.__data__ = new __VIRTUAL_FILE41(pairs1);
    }
    data40.set(key, value);
    this.size = data40.size;
    return this;
}
var __VIRTUAL_FILE42 = stackSet;
function Stack(entries) {
    var data41 = this.__data__ = new __VIRTUAL_FILE7(entries);
    this.size = data41.size;
}
Stack.prototype.clear = __VIRTUAL_FILE8;
Stack.prototype["delete"] = __VIRTUAL_FILE9;
Stack.prototype.get = __VIRTUAL_FILE10;
Stack.prototype.has = __VIRTUAL_FILE11;
Stack.prototype.set = __VIRTUAL_FILE42;
var __VIRTUAL_FILE43 = Stack;
function arrayEach(array, iteratee) {
    var index = -1, length = array == null ? 0 : array.length;
    while(++index < length){
        if (iteratee(array[index], index, array) === false) {
            break;
        }
    }
    return array;
}
var __VIRTUAL_FILE44 = arrayEach;
var defineProperty = function() {
    try {
        var func = __VIRTUAL_FILE25(Object, "defineProperty");
        func({}, "", {});
        return func;
    } catch (e) {}
}();
var __VIRTUAL_FILE45 = defineProperty;
function baseAssignValue(object, key, value) {
    if (key == "__proto__" && __VIRTUAL_FILE45) {
        __VIRTUAL_FILE45(object, key, {
            configurable: true,
            enumerable: true,
            value,
            writable: true
        });
    } else {
        object[key] = value;
    }
}
var __VIRTUAL_FILE46 = baseAssignValue;
var objectProto5 = Object.prototype;
var hasOwnProperty4 = objectProto5.hasOwnProperty;
function assignValue(object, key, value) {
    var objValue = object[key];
    if (!(hasOwnProperty4.call(object, key) && __VIRTUAL_FILE1(objValue, value)) || value === void 0 && !(key in object)) {
        __VIRTUAL_FILE46(object, key, value);
    }
}
var __VIRTUAL_FILE47 = assignValue;
function copyObject(source, props, object, customizer) {
    var isNew = !object;
    object || (object = {});
    var index = -1, length = props.length;
    while(++index < length){
        var key = props[index];
        var newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
        if (newValue === void 0) {
            newValue = source[key];
        }
        if (isNew) {
            __VIRTUAL_FILE46(object, key, newValue);
        } else {
            __VIRTUAL_FILE47(object, key, newValue);
        }
    }
    return object;
}
var __VIRTUAL_FILE48 = copyObject;
function baseTimes(n3, iteratee) {
    var index = -1, result = Array(n3);
    while(++index < n3){
        result[index] = iteratee(index);
    }
    return result;
}
var __VIRTUAL_FILE49 = baseTimes;
function isObjectLike(value) {
    return value != null && typeof value == "object";
}
var __VIRTUAL_FILE50 = isObjectLike;
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
    return __VIRTUAL_FILE50(value) && __VIRTUAL_FILE17(value) == argsTag;
}
var __VIRTUAL_FILE51 = baseIsArguments;
var objectProto6 = Object.prototype;
var hasOwnProperty5 = objectProto6.hasOwnProperty;
var propertyIsEnumerable = objectProto6.propertyIsEnumerable;
var isArguments = __VIRTUAL_FILE51(function() {
    return arguments;
}()) ? __VIRTUAL_FILE51 : function(value) {
    return __VIRTUAL_FILE50(value) && hasOwnProperty5.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
var __VIRTUAL_FILE52 = isArguments;
var isArray = Array.isArray;
var __VIRTUAL_FILE53 = isArray;
function stubFalse() {
    return false;
}
var __VIRTUAL_FILE54 = stubFalse;
function createCommonjsModule(fn) {
    var module = {
        exports: {}
    };
    return fn(module, module.exports), module.exports;
}
var __VIRTUAL_FILE55 = createCommonjsModule(function(module, exports) {
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module && !module.nodeType && module;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var Buffer1 = moduleExports ? __VIRTUAL_FILE13.Buffer : void 0;
    var nativeIsBuffer = Buffer1 ? Buffer1.isBuffer : void 0;
    var isBuffer = nativeIsBuffer || __VIRTUAL_FILE54;
    module.exports = isBuffer;
});
var MAX_SAFE_INTEGER = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
    var type = typeof value;
    length = length == null ? MAX_SAFE_INTEGER : length;
    return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
var __VIRTUAL_FILE56 = isIndex;
var MAX_SAFE_INTEGER1 = 9007199254740991;
function isLength(value) {
    return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER1;
}
var __VIRTUAL_FILE57 = isLength;
var argsTag1 = "[object Arguments]", arrayTag = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag1 = "[object Function]", mapTag = "[object Map]", numberTag = "[object Number]", objectTag = "[object Object]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", weakMapTag = "[object WeakMap]";
var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
function baseIsTypedArray(value) {
    return __VIRTUAL_FILE50(value) && __VIRTUAL_FILE57(value.length) && !!typedArrayTags[__VIRTUAL_FILE17(value)];
}
var __VIRTUAL_FILE58 = baseIsTypedArray;
function baseUnary(func) {
    return function(value) {
        return func(value);
    };
}
var __VIRTUAL_FILE59 = baseUnary;
function createCommonjsModule1(fn) {
    var module = {
        exports: {}
    };
    return fn(module, module.exports), module.exports;
}
var __VIRTUAL_FILE60 = createCommonjsModule1(function(module, exports) {
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module && !module.nodeType && module;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && __VIRTUAL_FILE12.process;
    var nodeUtil = function() {
        try {
            var types10 = freeModule && freeModule.require && freeModule.require("util").types;
            if (types10) {
                return types10;
            }
            return freeProcess && freeProcess.binding && freeProcess.binding("util");
        } catch (e) {}
    }();
    module.exports = nodeUtil;
});
var nodeIsTypedArray = __VIRTUAL_FILE60 && __VIRTUAL_FILE60.isTypedArray;
var isTypedArray = nodeIsTypedArray ? __VIRTUAL_FILE59(nodeIsTypedArray) : __VIRTUAL_FILE58;
var __VIRTUAL_FILE61 = isTypedArray;
var objectProto7 = Object.prototype;
var hasOwnProperty6 = objectProto7.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
    var isArr = __VIRTUAL_FILE53(value), isArg = !isArr && __VIRTUAL_FILE52(value), isBuff = !isArr && !isArg && __VIRTUAL_FILE55(value), isType = !isArr && !isArg && !isBuff && __VIRTUAL_FILE61(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? __VIRTUAL_FILE49(value.length, String) : [], length = result.length;
    for(var key in value){
        if ((inherited || hasOwnProperty6.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || __VIRTUAL_FILE56(key, length)))) {
            result.push(key);
        }
    }
    return result;
}
var __VIRTUAL_FILE62 = arrayLikeKeys;
var objectProto8 = Object.prototype;
function isPrototype(value) {
    var Ctor = value && value.constructor, proto1 = typeof Ctor == "function" && Ctor.prototype || objectProto8;
    return value === proto1;
}
var __VIRTUAL_FILE63 = isPrototype;
function overArg(func, transform) {
    return function(arg) {
        return func(transform(arg));
    };
}
var __VIRTUAL_FILE64 = overArg;
var nativeKeys = __VIRTUAL_FILE64(Object.keys, Object);
var __VIRTUAL_FILE65 = nativeKeys;
var objectProto9 = Object.prototype;
var hasOwnProperty7 = objectProto9.hasOwnProperty;
function baseKeys(object) {
    if (!__VIRTUAL_FILE63(object)) {
        return __VIRTUAL_FILE65(object);
    }
    var result = [];
    for(var key in Object(object)){
        if (hasOwnProperty7.call(object, key) && key != "constructor") {
            result.push(key);
        }
    }
    return result;
}
var __VIRTUAL_FILE66 = baseKeys;
function isArrayLike(value) {
    return value != null && __VIRTUAL_FILE57(value.length) && !__VIRTUAL_FILE19(value);
}
var __VIRTUAL_FILE67 = isArrayLike;
function keys(object) {
    return __VIRTUAL_FILE67(object) ? __VIRTUAL_FILE62(object) : __VIRTUAL_FILE66(object);
}
var __VIRTUAL_FILE68 = keys;
function baseAssign(object, source) {
    return object && __VIRTUAL_FILE48(source, __VIRTUAL_FILE68(source), object);
}
var __VIRTUAL_FILE69 = baseAssign;
function nativeKeysIn(object) {
    var result = [];
    if (object != null) {
        for(var key in Object(object)){
            result.push(key);
        }
    }
    return result;
}
var __VIRTUAL_FILE70 = nativeKeysIn;
var objectProto10 = Object.prototype;
var hasOwnProperty8 = objectProto10.hasOwnProperty;
function baseKeysIn(object) {
    if (!__VIRTUAL_FILE18(object)) {
        return __VIRTUAL_FILE70(object);
    }
    var isProto = __VIRTUAL_FILE63(object), result = [];
    for(var key in object){
        if (!(key == "constructor" && (isProto || !hasOwnProperty8.call(object, key)))) {
            result.push(key);
        }
    }
    return result;
}
var __VIRTUAL_FILE71 = baseKeysIn;
function keysIn(object) {
    return __VIRTUAL_FILE67(object) ? __VIRTUAL_FILE62(object, true) : __VIRTUAL_FILE71(object);
}
var __VIRTUAL_FILE72 = keysIn;
function baseAssignIn(object, source) {
    return object && __VIRTUAL_FILE48(source, __VIRTUAL_FILE72(source), object);
}
var __VIRTUAL_FILE73 = baseAssignIn;
function createCommonjsModule2(fn) {
    var module = {
        exports: {}
    };
    return fn(module, module.exports), module.exports;
}
var __VIRTUAL_FILE74 = createCommonjsModule2(function(module, exports) {
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module && !module.nodeType && module;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var Buffer2 = moduleExports ? __VIRTUAL_FILE13.Buffer : void 0, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : void 0;
    function cloneBuffer(buffer, isDeep) {
        if (isDeep) {
            return buffer.slice();
        }
        var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
        buffer.copy(result);
        return result;
    }
    module.exports = cloneBuffer;
});
function copyArray(source, array) {
    var index = -1, length = source.length;
    array || (array = Array(length));
    while(++index < length){
        array[index] = source[index];
    }
    return array;
}
var __VIRTUAL_FILE75 = copyArray;
function arrayFilter(array, predicate) {
    var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
    while(++index < length){
        var value = array[index];
        if (predicate(value, index, array)) {
            result[resIndex++] = value;
        }
    }
    return result;
}
var __VIRTUAL_FILE76 = arrayFilter;
function stubArray() {
    return [];
}
var __VIRTUAL_FILE77 = stubArray;
var objectProto11 = Object.prototype;
var propertyIsEnumerable1 = objectProto11.propertyIsEnumerable;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbols = !nativeGetSymbols ? __VIRTUAL_FILE77 : function(object) {
    if (object == null) {
        return [];
    }
    object = Object(object);
    return __VIRTUAL_FILE76(nativeGetSymbols(object), function(symbol) {
        return propertyIsEnumerable1.call(object, symbol);
    });
};
var __VIRTUAL_FILE78 = getSymbols;
function copySymbols(source, object) {
    return __VIRTUAL_FILE48(source, __VIRTUAL_FILE78(source), object);
}
var __VIRTUAL_FILE79 = copySymbols;
function arrayPush(array, values4) {
    var index = -1, length = values4.length, offset = array.length;
    while(++index < length){
        array[offset + index] = values4[index];
    }
    return array;
}
var __VIRTUAL_FILE80 = arrayPush;
var getPrototype = __VIRTUAL_FILE64(Object.getPrototypeOf, Object);
var __VIRTUAL_FILE81 = getPrototype;
var nativeGetSymbols1 = Object.getOwnPropertySymbols;
var getSymbolsIn = !nativeGetSymbols1 ? __VIRTUAL_FILE77 : function(object) {
    var result = [];
    while(object){
        __VIRTUAL_FILE80(result, __VIRTUAL_FILE78(object));
        object = __VIRTUAL_FILE81(object);
    }
    return result;
};
var __VIRTUAL_FILE82 = getSymbolsIn;
function copySymbolsIn(source, object) {
    return __VIRTUAL_FILE48(source, __VIRTUAL_FILE82(source), object);
}
var __VIRTUAL_FILE83 = copySymbolsIn;
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
    var result = keysFunc(object);
    return __VIRTUAL_FILE53(object) ? result : __VIRTUAL_FILE80(result, symbolsFunc(object));
}
var __VIRTUAL_FILE84 = baseGetAllKeys;
function getAllKeys(object) {
    return __VIRTUAL_FILE84(object, __VIRTUAL_FILE68, __VIRTUAL_FILE78);
}
var __VIRTUAL_FILE85 = getAllKeys;
function getAllKeysIn(object) {
    return __VIRTUAL_FILE84(object, __VIRTUAL_FILE72, __VIRTUAL_FILE82);
}
var __VIRTUAL_FILE86 = getAllKeysIn;
var DataView1 = __VIRTUAL_FILE25(__VIRTUAL_FILE13, "DataView");
var __VIRTUAL_FILE87 = DataView1;
var Promise1 = __VIRTUAL_FILE25(__VIRTUAL_FILE13, "Promise");
var __VIRTUAL_FILE88 = Promise1;
var Set1 = __VIRTUAL_FILE25(__VIRTUAL_FILE13, "Set");
var __VIRTUAL_FILE89 = Set1;
var WeakMap = __VIRTUAL_FILE25(__VIRTUAL_FILE13, "WeakMap");
var __VIRTUAL_FILE90 = WeakMap;
var mapTag1 = "[object Map]", objectTag1 = "[object Object]", promiseTag = "[object Promise]", setTag1 = "[object Set]", weakMapTag1 = "[object WeakMap]";
var dataViewTag1 = "[object DataView]";
var dataViewCtorString = __VIRTUAL_FILE22(__VIRTUAL_FILE87), mapCtorString = __VIRTUAL_FILE22(__VIRTUAL_FILE26), promiseCtorString = __VIRTUAL_FILE22(__VIRTUAL_FILE88), setCtorString = __VIRTUAL_FILE22(__VIRTUAL_FILE89), weakMapCtorString = __VIRTUAL_FILE22(__VIRTUAL_FILE90);
var getTag = __VIRTUAL_FILE17;
if (__VIRTUAL_FILE87 && getTag(new __VIRTUAL_FILE87(new ArrayBuffer(1))) != dataViewTag1 || __VIRTUAL_FILE26 && getTag(new __VIRTUAL_FILE26()) != mapTag1 || __VIRTUAL_FILE88 && getTag(__VIRTUAL_FILE88.resolve()) != promiseTag || __VIRTUAL_FILE89 && getTag(new __VIRTUAL_FILE89()) != setTag1 || __VIRTUAL_FILE90 && getTag(new __VIRTUAL_FILE90()) != weakMapTag1) {
    getTag = function(value) {
        var result = __VIRTUAL_FILE17(value), Ctor = result == objectTag1 ? value.constructor : void 0, ctorString = Ctor ? __VIRTUAL_FILE22(Ctor) : "";
        if (ctorString) {
            switch(ctorString){
                case dataViewCtorString:
                    return dataViewTag1;
                case mapCtorString:
                    return mapTag1;
                case promiseCtorString:
                    return promiseTag;
                case setCtorString:
                    return setTag1;
                case weakMapCtorString:
                    return weakMapTag1;
            }
        }
        return result;
    };
}
var __VIRTUAL_FILE91 = getTag;
var objectProto12 = Object.prototype;
var hasOwnProperty9 = objectProto12.hasOwnProperty;
function initCloneArray(array) {
    var length = array.length, result = new array.constructor(length);
    if (length && typeof array[0] == "string" && hasOwnProperty9.call(array, "index")) {
        result.index = array.index;
        result.input = array.input;
    }
    return result;
}
var __VIRTUAL_FILE92 = initCloneArray;
var Uint8Array1 = __VIRTUAL_FILE13.Uint8Array;
var __VIRTUAL_FILE93 = Uint8Array1;
function cloneArrayBuffer(arrayBuffer) {
    var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
    new __VIRTUAL_FILE93(result).set(new __VIRTUAL_FILE93(arrayBuffer));
    return result;
}
var __VIRTUAL_FILE94 = cloneArrayBuffer;
function cloneDataView(dataView, isDeep) {
    var buffer = isDeep ? __VIRTUAL_FILE94(dataView.buffer) : dataView.buffer;
    return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var __VIRTUAL_FILE95 = cloneDataView;
var reFlags = /\w*$/;
function cloneRegExp(regexp4) {
    var result = new regexp4.constructor(regexp4.source, reFlags.exec(regexp4));
    result.lastIndex = regexp4.lastIndex;
    return result;
}
var __VIRTUAL_FILE96 = cloneRegExp;
var symbolProto = __VIRTUAL_FILE14 ? __VIRTUAL_FILE14.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
function cloneSymbol(symbol) {
    return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var __VIRTUAL_FILE97 = cloneSymbol;
function cloneTypedArray(typedArray, isDeep) {
    var buffer = isDeep ? __VIRTUAL_FILE94(typedArray.buffer) : typedArray.buffer;
    return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var __VIRTUAL_FILE98 = cloneTypedArray;
var boolTag1 = "[object Boolean]", dateTag1 = "[object Date]", mapTag2 = "[object Map]", numberTag1 = "[object Number]", regexpTag1 = "[object RegExp]", setTag2 = "[object Set]", stringTag1 = "[object String]", symbolTag = "[object Symbol]";
var arrayBufferTag1 = "[object ArrayBuffer]", dataViewTag2 = "[object DataView]", float32Tag1 = "[object Float32Array]", float64Tag1 = "[object Float64Array]", int8Tag1 = "[object Int8Array]", int16Tag1 = "[object Int16Array]", int32Tag1 = "[object Int32Array]", uint8Tag1 = "[object Uint8Array]", uint8ClampedTag1 = "[object Uint8ClampedArray]", uint16Tag1 = "[object Uint16Array]", uint32Tag1 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
    var Ctor = object.constructor;
    switch(tag){
        case arrayBufferTag1:
            return __VIRTUAL_FILE94(object);
        case boolTag1:
        case dateTag1:
            return new Ctor(+object);
        case dataViewTag2:
            return __VIRTUAL_FILE95(object, isDeep);
        case float32Tag1:
        case float64Tag1:
        case int8Tag1:
        case int16Tag1:
        case int32Tag1:
        case uint8Tag1:
        case uint8ClampedTag1:
        case uint16Tag1:
        case uint32Tag1:
            return __VIRTUAL_FILE98(object, isDeep);
        case mapTag2:
            return new Ctor();
        case numberTag1:
        case stringTag1:
            return new Ctor(object);
        case regexpTag1:
            return __VIRTUAL_FILE96(object);
        case setTag2:
            return new Ctor();
        case symbolTag:
            return __VIRTUAL_FILE97(object);
    }
}
var __VIRTUAL_FILE99 = initCloneByTag;
var objectCreate = Object.create;
var baseCreate = function() {
    function object() {}
    return function(proto2) {
        if (!__VIRTUAL_FILE18(proto2)) {
            return {};
        }
        if (objectCreate) {
            return objectCreate(proto2);
        }
        object.prototype = proto2;
        var result = new object();
        object.prototype = void 0;
        return result;
    };
}();
var __VIRTUAL_FILE100 = baseCreate;
function initCloneObject(object) {
    return typeof object.constructor == "function" && !__VIRTUAL_FILE63(object) ? __VIRTUAL_FILE100(__VIRTUAL_FILE81(object)) : {};
}
var __VIRTUAL_FILE101 = initCloneObject;
var mapTag3 = "[object Map]";
function baseIsMap(value) {
    return __VIRTUAL_FILE50(value) && __VIRTUAL_FILE91(value) == mapTag3;
}
var __VIRTUAL_FILE102 = baseIsMap;
var nodeIsMap = __VIRTUAL_FILE60 && __VIRTUAL_FILE60.isMap;
var isMap = nodeIsMap ? __VIRTUAL_FILE59(nodeIsMap) : __VIRTUAL_FILE102;
var __VIRTUAL_FILE103 = isMap;
var setTag3 = "[object Set]";
function baseIsSet(value) {
    return __VIRTUAL_FILE50(value) && __VIRTUAL_FILE91(value) == setTag3;
}
var __VIRTUAL_FILE104 = baseIsSet;
var nodeIsSet = __VIRTUAL_FILE60 && __VIRTUAL_FILE60.isSet;
var isSet = nodeIsSet ? __VIRTUAL_FILE59(nodeIsSet) : __VIRTUAL_FILE104;
var __VIRTUAL_FILE105 = isSet;
var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4;
var argsTag2 = "[object Arguments]", arrayTag1 = "[object Array]", boolTag2 = "[object Boolean]", dateTag2 = "[object Date]", errorTag1 = "[object Error]", funcTag2 = "[object Function]", genTag1 = "[object GeneratorFunction]", mapTag4 = "[object Map]", numberTag2 = "[object Number]", objectTag2 = "[object Object]", regexpTag2 = "[object RegExp]", setTag4 = "[object Set]", stringTag2 = "[object String]", symbolTag1 = "[object Symbol]", weakMapTag2 = "[object WeakMap]";
var arrayBufferTag2 = "[object ArrayBuffer]", dataViewTag3 = "[object DataView]", float32Tag2 = "[object Float32Array]", float64Tag2 = "[object Float64Array]", int8Tag2 = "[object Int8Array]", int16Tag2 = "[object Int16Array]", int32Tag2 = "[object Int32Array]", uint8Tag2 = "[object Uint8Array]", uint8ClampedTag2 = "[object Uint8ClampedArray]", uint16Tag2 = "[object Uint16Array]", uint32Tag2 = "[object Uint32Array]";
var cloneableTags = {};
cloneableTags[argsTag2] = cloneableTags[arrayTag1] = cloneableTags[arrayBufferTag2] = cloneableTags[dataViewTag3] = cloneableTags[boolTag2] = cloneableTags[dateTag2] = cloneableTags[float32Tag2] = cloneableTags[float64Tag2] = cloneableTags[int8Tag2] = cloneableTags[int16Tag2] = cloneableTags[int32Tag2] = cloneableTags[mapTag4] = cloneableTags[numberTag2] = cloneableTags[objectTag2] = cloneableTags[regexpTag2] = cloneableTags[setTag4] = cloneableTags[stringTag2] = cloneableTags[symbolTag1] = cloneableTags[uint8Tag2] = cloneableTags[uint8ClampedTag2] = cloneableTags[uint16Tag2] = cloneableTags[uint32Tag2] = true;
cloneableTags[errorTag1] = cloneableTags[funcTag2] = cloneableTags[weakMapTag2] = false;
function baseClone(value, bitmask, customizer, key, object, stack) {
    var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
    if (customizer) {
        result = object ? customizer(value, key, object, stack) : customizer(value);
    }
    if (result !== void 0) {
        return result;
    }
    if (!__VIRTUAL_FILE18(value)) {
        return value;
    }
    var isArr = __VIRTUAL_FILE53(value);
    if (isArr) {
        result = __VIRTUAL_FILE92(value);
        if (!isDeep) {
            return __VIRTUAL_FILE75(value, result);
        }
    } else {
        var tag = __VIRTUAL_FILE91(value), isFunc = tag == funcTag2 || tag == genTag1;
        if (__VIRTUAL_FILE55(value)) {
            return __VIRTUAL_FILE74(value, isDeep);
        }
        if (tag == objectTag2 || tag == argsTag2 || isFunc && !object) {
            result = isFlat || isFunc ? {} : __VIRTUAL_FILE101(value);
            if (!isDeep) {
                return isFlat ? __VIRTUAL_FILE83(value, __VIRTUAL_FILE73(result, value)) : __VIRTUAL_FILE79(value, __VIRTUAL_FILE69(result, value));
            }
        } else {
            if (!cloneableTags[tag]) {
                return object ? value : {};
            }
            result = __VIRTUAL_FILE99(value, tag, isDeep);
        }
    }
    stack || (stack = new __VIRTUAL_FILE43());
    var stacked = stack.get(value);
    if (stacked) {
        return stacked;
    }
    stack.set(value, result);
    if (__VIRTUAL_FILE105(value)) {
        value.forEach(function(subValue) {
            result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
        });
    } else if (__VIRTUAL_FILE103(value)) {
        value.forEach(function(subValue, key2) {
            result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
        });
    }
    var keysFunc = isFull ? isFlat ? __VIRTUAL_FILE86 : __VIRTUAL_FILE85 : isFlat ? __VIRTUAL_FILE72 : __VIRTUAL_FILE68;
    var props = isArr ? void 0 : keysFunc(value);
    __VIRTUAL_FILE44(props || value, function(subValue, key2) {
        if (props) {
            key2 = subValue;
            subValue = value[key2];
        }
        __VIRTUAL_FILE47(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
    });
    return result;
}
var __VIRTUAL_FILE106 = baseClone;
var CLONE_DEEP_FLAG1 = 1, CLONE_SYMBOLS_FLAG1 = 4;
function cloneDeep(value) {
    return __VIRTUAL_FILE106(value, CLONE_DEEP_FLAG1 | CLONE_SYMBOLS_FLAG1);
}
var __VIRTUAL_FILE107 = cloneDeep;
var now = function() {
    return __VIRTUAL_FILE13.Date.now();
};
var __VIRTUAL_FILE108 = now;
var reWhitespace1 = /\s/;
function trimmedEndIndex(string13) {
    var index = string13.length;
    while(index-- && reWhitespace1.test(string13.charAt(index))){}
    return index;
}
var __VIRTUAL_FILE109 = trimmedEndIndex;
var reTrimStart = /^\s+/;
function baseTrim(string14) {
    return string14 ? string14.slice(0, __VIRTUAL_FILE109(string14) + 1).replace(reTrimStart, "") : string14;
}
var __VIRTUAL_FILE110 = baseTrim;
var symbolTag2 = "[object Symbol]";
function isSymbol(value) {
    return typeof value == "symbol" || __VIRTUAL_FILE50(value) && __VIRTUAL_FILE17(value) == symbolTag2;
}
var __VIRTUAL_FILE111 = isSymbol;
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber(value) {
    if (typeof value == "number") {
        return value;
    }
    if (__VIRTUAL_FILE111(value)) {
        return NAN;
    }
    if (__VIRTUAL_FILE18(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = __VIRTUAL_FILE18(other) ? other + "" : other;
    }
    if (typeof value != "string") {
        return value === 0 ? value : +value;
    }
    value = __VIRTUAL_FILE110(value);
    var isBinary1 = reIsBinary.test(value);
    return isBinary1 || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary1 ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
var __VIRTUAL_FILE112 = toNumber;
var FUNC_ERROR_TEXT = "Expected a function";
var nativeMax = Math.max, nativeMin = Math.min;
function debounce(func, wait, options) {
    var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
    if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
    }
    wait = __VIRTUAL_FILE112(wait) || 0;
    if (__VIRTUAL_FILE18(options)) {
        leading = !!options.leading;
        maxing = "maxWait" in options;
        maxWait = maxing ? nativeMax(__VIRTUAL_FILE112(options.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options ? !!options.trailing : trailing;
    }
    function invokeFunc(time) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time;
        result = func.apply(thisArg, args);
        return result;
    }
    function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result;
    }
    function remainingWait(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
        return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
    }
    function shouldInvoke(time) {
        var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
    }
    function timerExpired() {
        var time = __VIRTUAL_FILE108();
        if (shouldInvoke(time)) {
            return trailingEdge(time);
        }
        timerId = setTimeout(timerExpired, remainingWait(time));
    }
    function trailingEdge(time) {
        timerId = void 0;
        if (trailing && lastArgs) {
            return invokeFunc(time);
        }
        lastArgs = lastThis = void 0;
        return result;
    }
    function cancel() {
        if (timerId !== void 0) {
            clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
    }
    function flush() {
        return timerId === void 0 ? result : trailingEdge(__VIRTUAL_FILE108());
    }
    function debounced() {
        var time = __VIRTUAL_FILE108(), isInvoking = shouldInvoke(time);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time;
        if (isInvoking) {
            if (timerId === void 0) {
                return leadingEdge(lastCallTime);
            }
            if (maxing) {
                clearTimeout(timerId);
                timerId = setTimeout(timerExpired, wait);
                return invokeFunc(lastCallTime);
            }
        }
        if (timerId === void 0) {
            timerId = setTimeout(timerExpired, wait);
        }
        return result;
    }
    debounced.cancel = cancel;
    debounced.flush = flush;
    return debounced;
}
var __VIRTUAL_FILE113 = debounce;
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function setCacheAdd(value) {
    this.__data__.set(value, HASH_UNDEFINED2);
    return this;
}
var __VIRTUAL_FILE114 = setCacheAdd;
function setCacheHas(value) {
    return this.__data__.has(value);
}
var __VIRTUAL_FILE115 = setCacheHas;
function SetCache(values5) {
    var index = -1, length = values5 == null ? 0 : values5.length;
    this.__data__ = new __VIRTUAL_FILE41();
    while(++index < length){
        this.add(values5[index]);
    }
}
SetCache.prototype.add = SetCache.prototype.push = __VIRTUAL_FILE114;
SetCache.prototype.has = __VIRTUAL_FILE115;
var __VIRTUAL_FILE116 = SetCache;
function baseFindIndex(array, predicate, fromIndex, fromRight) {
    var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
    while(fromRight ? index-- : ++index < length){
        if (predicate(array[index], index, array)) {
            return index;
        }
    }
    return -1;
}
var __VIRTUAL_FILE117 = baseFindIndex;
function baseIsNaN(value) {
    return value !== value;
}
var __VIRTUAL_FILE118 = baseIsNaN;
function strictIndexOf(array, value, fromIndex) {
    var index = fromIndex - 1, length = array.length;
    while(++index < length){
        if (array[index] === value) {
            return index;
        }
    }
    return -1;
}
var __VIRTUAL_FILE119 = strictIndexOf;
function baseIndexOf(array, value, fromIndex) {
    return value === value ? __VIRTUAL_FILE119(array, value, fromIndex) : __VIRTUAL_FILE117(array, __VIRTUAL_FILE118, fromIndex);
}
var __VIRTUAL_FILE120 = baseIndexOf;
function arrayIncludes(array, value) {
    var length = array == null ? 0 : array.length;
    return !!length && __VIRTUAL_FILE120(array, value, 0) > -1;
}
var __VIRTUAL_FILE121 = arrayIncludes;
function arrayIncludesWith(array, value, comparator) {
    var index = -1, length = array == null ? 0 : array.length;
    while(++index < length){
        if (comparator(value, array[index])) {
            return true;
        }
    }
    return false;
}
var __VIRTUAL_FILE122 = arrayIncludesWith;
function arrayMap(array, iteratee) {
    var index = -1, length = array == null ? 0 : array.length, result = Array(length);
    while(++index < length){
        result[index] = iteratee(array[index], index, array);
    }
    return result;
}
var __VIRTUAL_FILE123 = arrayMap;
function cacheHas(cache, key) {
    return cache.has(key);
}
var __VIRTUAL_FILE124 = cacheHas;
var LARGE_ARRAY_SIZE1 = 200;
function baseDifference(array, values6, iteratee, comparator) {
    var index = -1, includes = __VIRTUAL_FILE121, isCommon = true, length = array.length, result = [], valuesLength = values6.length;
    if (!length) {
        return result;
    }
    if (iteratee) {
        values6 = __VIRTUAL_FILE123(values6, __VIRTUAL_FILE59(iteratee));
    }
    if (comparator) {
        includes = __VIRTUAL_FILE122;
        isCommon = false;
    } else if (values6.length >= LARGE_ARRAY_SIZE1) {
        includes = __VIRTUAL_FILE124;
        isCommon = false;
        values6 = new __VIRTUAL_FILE116(values6);
    }
    outer: while(++index < length){
        var value = array[index], computed = iteratee == null ? value : iteratee(value);
        value = comparator || value !== 0 ? value : 0;
        if (isCommon && computed === computed) {
            var valuesIndex = valuesLength;
            while(valuesIndex--){
                if (values6[valuesIndex] === computed) {
                    continue outer;
                }
            }
            result.push(value);
        } else if (!includes(values6, computed, comparator)) {
            result.push(value);
        }
    }
    return result;
}
var __VIRTUAL_FILE125 = baseDifference;
var spreadableSymbol = __VIRTUAL_FILE14 ? __VIRTUAL_FILE14.isConcatSpreadable : void 0;
function isFlattenable(value) {
    return __VIRTUAL_FILE53(value) || __VIRTUAL_FILE52(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
var __VIRTUAL_FILE126 = isFlattenable;
function baseFlatten(array, depth, predicate, isStrict, result) {
    var index = -1, length = array.length;
    predicate || (predicate = __VIRTUAL_FILE126);
    result || (result = []);
    while(++index < length){
        var value = array[index];
        if (depth > 0 && predicate(value)) {
            if (depth > 1) {
                baseFlatten(value, depth - 1, predicate, isStrict, result);
            } else {
                __VIRTUAL_FILE80(result, value);
            }
        } else if (!isStrict) {
            result[result.length] = value;
        }
    }
    return result;
}
var __VIRTUAL_FILE127 = baseFlatten;
function identity(value) {
    return value;
}
var __VIRTUAL_FILE128 = identity;
function apply(func, thisArg, args) {
    switch(args.length){
        case 0:
            return func.call(thisArg);
        case 1:
            return func.call(thisArg, args[0]);
        case 2:
            return func.call(thisArg, args[0], args[1]);
        case 3:
            return func.call(thisArg, args[0], args[1], args[2]);
    }
    return func.apply(thisArg, args);
}
var __VIRTUAL_FILE129 = apply;
var nativeMax1 = Math.max;
function overRest(func, start, transform) {
    start = nativeMax1(start === void 0 ? func.length - 1 : start, 0);
    return function() {
        var args = arguments, index = -1, length = nativeMax1(args.length - start, 0), array = Array(length);
        while(++index < length){
            array[index] = args[start + index];
        }
        index = -1;
        var otherArgs = Array(start + 1);
        while(++index < start){
            otherArgs[index] = args[index];
        }
        otherArgs[start] = transform(array);
        return __VIRTUAL_FILE129(func, this, otherArgs);
    };
}
var __VIRTUAL_FILE130 = overRest;
function constant(value) {
    return function() {
        return value;
    };
}
var __VIRTUAL_FILE131 = constant;
var baseSetToString = !__VIRTUAL_FILE45 ? __VIRTUAL_FILE128 : function(func, string15) {
    return __VIRTUAL_FILE45(func, "toString", {
        configurable: true,
        enumerable: false,
        value: __VIRTUAL_FILE131(string15),
        writable: true
    });
};
var __VIRTUAL_FILE132 = baseSetToString;
var HOT_COUNT = 800, HOT_SPAN = 16;
var nativeNow = Date.now;
function shortOut(func) {
    var count = 0, lastCalled = 0;
    return function() {
        var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
        lastCalled = stamp;
        if (remaining > 0) {
            if (++count >= HOT_COUNT) {
                return arguments[0];
            }
        } else {
            count = 0;
        }
        return func.apply(void 0, arguments);
    };
}
var __VIRTUAL_FILE133 = shortOut;
var setToString = __VIRTUAL_FILE133(__VIRTUAL_FILE132);
var __VIRTUAL_FILE134 = setToString;
function baseRest(func, start) {
    return __VIRTUAL_FILE134(__VIRTUAL_FILE130(func, start, __VIRTUAL_FILE128), func + "");
}
var __VIRTUAL_FILE135 = baseRest;
function isArrayLikeObject(value) {
    return __VIRTUAL_FILE50(value) && __VIRTUAL_FILE67(value);
}
var __VIRTUAL_FILE136 = isArrayLikeObject;
var difference = __VIRTUAL_FILE135(function(array, values7) {
    return __VIRTUAL_FILE136(array) ? __VIRTUAL_FILE125(array, __VIRTUAL_FILE127(values7, 1, __VIRTUAL_FILE136, true)) : [];
});
var __VIRTUAL_FILE137 = difference;
function createBaseFor(fromRight) {
    return function(object, iteratee, keysFunc) {
        var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
        while(length--){
            var key = props[fromRight ? length : ++index];
            if (iteratee(iterable[key], key, iterable) === false) {
                break;
            }
        }
        return object;
    };
}
var __VIRTUAL_FILE138 = createBaseFor;
var baseFor = __VIRTUAL_FILE138();
var __VIRTUAL_FILE139 = baseFor;
function baseForOwn(object, iteratee) {
    return object && __VIRTUAL_FILE139(object, iteratee, __VIRTUAL_FILE68);
}
var __VIRTUAL_FILE140 = baseForOwn;
function createBaseEach(eachFunc, fromRight) {
    return function(collection, iteratee) {
        if (collection == null) {
            return collection;
        }
        if (!__VIRTUAL_FILE67(collection)) {
            return eachFunc(collection, iteratee);
        }
        var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection);
        while(fromRight ? index-- : ++index < length){
            if (iteratee(iterable[index], index, iterable) === false) {
                break;
            }
        }
        return collection;
    };
}
var __VIRTUAL_FILE141 = createBaseEach;
var baseEach = __VIRTUAL_FILE141(__VIRTUAL_FILE140);
var __VIRTUAL_FILE142 = baseEach;
function castFunction(value) {
    return typeof value == "function" ? value : __VIRTUAL_FILE128;
}
var __VIRTUAL_FILE143 = castFunction;
function forEach(collection, iteratee) {
    var func = __VIRTUAL_FILE53(collection) ? __VIRTUAL_FILE44 : __VIRTUAL_FILE142;
    return func(collection, __VIRTUAL_FILE143(iteratee));
}
var __VIRTUAL_FILE144 = forEach;
var __VIRTUAL_FILE145 = __VIRTUAL_FILE144;
function assignMergeValue(object, key, value) {
    if (value !== void 0 && !__VIRTUAL_FILE1(object[key], value) || value === void 0 && !(key in object)) {
        __VIRTUAL_FILE46(object, key, value);
    }
}
var __VIRTUAL_FILE146 = assignMergeValue;
var objectTag3 = "[object Object]";
var funcProto2 = Function.prototype, objectProto13 = Object.prototype;
var funcToString2 = funcProto2.toString;
var hasOwnProperty10 = objectProto13.hasOwnProperty;
var objectCtorString = funcToString2.call(Object);
function isPlainObject(value) {
    if (!__VIRTUAL_FILE50(value) || __VIRTUAL_FILE17(value) != objectTag3) {
        return false;
    }
    var proto3 = __VIRTUAL_FILE81(value);
    if (proto3 === null) {
        return true;
    }
    var Ctor = hasOwnProperty10.call(proto3, "constructor") && proto3.constructor;
    return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString2.call(Ctor) == objectCtorString;
}
var __VIRTUAL_FILE147 = isPlainObject;
function safeGet(object, key) {
    if (key === "constructor" && typeof object[key] === "function") {
        return;
    }
    if (key == "__proto__") {
        return;
    }
    return object[key];
}
var __VIRTUAL_FILE148 = safeGet;
function toPlainObject(value) {
    return __VIRTUAL_FILE48(value, __VIRTUAL_FILE72(value));
}
var __VIRTUAL_FILE149 = toPlainObject;
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
    var objValue = __VIRTUAL_FILE148(object, key), srcValue = __VIRTUAL_FILE148(source, key), stacked = stack.get(srcValue);
    if (stacked) {
        __VIRTUAL_FILE146(object, key, stacked);
        return;
    }
    var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : void 0;
    var isCommon = newValue === void 0;
    if (isCommon) {
        var isArr = __VIRTUAL_FILE53(srcValue), isBuff = !isArr && __VIRTUAL_FILE55(srcValue), isTyped = !isArr && !isBuff && __VIRTUAL_FILE61(srcValue);
        newValue = srcValue;
        if (isArr || isBuff || isTyped) {
            if (__VIRTUAL_FILE53(objValue)) {
                newValue = objValue;
            } else if (__VIRTUAL_FILE136(objValue)) {
                newValue = __VIRTUAL_FILE75(objValue);
            } else if (isBuff) {
                isCommon = false;
                newValue = __VIRTUAL_FILE74(srcValue, true);
            } else if (isTyped) {
                isCommon = false;
                newValue = __VIRTUAL_FILE98(srcValue, true);
            } else {
                newValue = [];
            }
        } else if (__VIRTUAL_FILE147(srcValue) || __VIRTUAL_FILE52(srcValue)) {
            newValue = objValue;
            if (__VIRTUAL_FILE52(objValue)) {
                newValue = __VIRTUAL_FILE149(objValue);
            } else if (!__VIRTUAL_FILE18(objValue) || __VIRTUAL_FILE19(objValue)) {
                newValue = __VIRTUAL_FILE101(srcValue);
            }
        } else {
            isCommon = false;
        }
    }
    if (isCommon) {
        stack.set(srcValue, newValue);
        mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
        stack["delete"](srcValue);
    }
    __VIRTUAL_FILE146(object, key, newValue);
}
var __VIRTUAL_FILE150 = baseMergeDeep;
function baseMerge(object, source, srcIndex, customizer, stack) {
    if (object === source) {
        return;
    }
    __VIRTUAL_FILE139(source, function(srcValue, key) {
        stack || (stack = new __VIRTUAL_FILE43());
        if (__VIRTUAL_FILE18(srcValue)) {
            __VIRTUAL_FILE150(object, source, key, srcIndex, baseMerge, customizer, stack);
        } else {
            var newValue = customizer ? customizer(__VIRTUAL_FILE148(object, key), srcValue, key + "", object, source, stack) : void 0;
            if (newValue === void 0) {
                newValue = srcValue;
            }
            __VIRTUAL_FILE146(object, key, newValue);
        }
    }, __VIRTUAL_FILE72);
}
var __VIRTUAL_FILE151 = baseMerge;
function isIterateeCall(value, index, object) {
    if (!__VIRTUAL_FILE18(object)) {
        return false;
    }
    var type = typeof index;
    if (type == "number" ? __VIRTUAL_FILE67(object) && __VIRTUAL_FILE56(index, object.length) : type == "string" && index in object) {
        return __VIRTUAL_FILE1(object[index], value);
    }
    return false;
}
var __VIRTUAL_FILE152 = isIterateeCall;
function createAssigner(assigner) {
    return __VIRTUAL_FILE135(function(object, sources) {
        var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0;
        customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0;
        if (guard && __VIRTUAL_FILE152(sources[0], sources[1], guard)) {
            customizer = length < 3 ? void 0 : customizer;
            length = 1;
        }
        object = Object(object);
        while(++index < length){
            var source = sources[index];
            if (source) {
                assigner(object, source, index, customizer);
            }
        }
        return object;
    });
}
var __VIRTUAL_FILE153 = createAssigner;
var mergeWith = __VIRTUAL_FILE153(function(object, source, srcIndex, customizer) {
    __VIRTUAL_FILE151(object, source, srcIndex, customizer);
});
var __VIRTUAL_FILE154 = mergeWith;
var nativeFloor = Math.floor, nativeRandom = Math.random;
function baseRandom(lower, upper) {
    return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
var __VIRTUAL_FILE155 = baseRandom;
function shuffleSelf(array, size) {
    var index = -1, length = array.length, lastIndex = length - 1;
    size = size === void 0 ? length : size;
    while(++index < size){
        var rand = __VIRTUAL_FILE155(index, lastIndex), value = array[rand];
        array[rand] = array[index];
        array[index] = value;
    }
    array.length = size;
    return array;
}
var __VIRTUAL_FILE156 = shuffleSelf;
function arrayShuffle(array) {
    return __VIRTUAL_FILE156(__VIRTUAL_FILE75(array));
}
var __VIRTUAL_FILE157 = arrayShuffle;
function baseValues(object, props) {
    return __VIRTUAL_FILE123(props, function(key) {
        return object[key];
    });
}
var __VIRTUAL_FILE158 = baseValues;
function values(object) {
    return object == null ? [] : __VIRTUAL_FILE158(object, __VIRTUAL_FILE68(object));
}
var __VIRTUAL_FILE159 = values;
function baseShuffle(collection) {
    return __VIRTUAL_FILE156(__VIRTUAL_FILE159(collection));
}
var __VIRTUAL_FILE160 = baseShuffle;
function shuffle(collection) {
    var func = __VIRTUAL_FILE53(collection) ? __VIRTUAL_FILE157 : __VIRTUAL_FILE160;
    return func(collection);
}
var __VIRTUAL_FILE161 = shuffle;
var assignInWith = __VIRTUAL_FILE153(function(object, source, srcIndex, customizer) {
    __VIRTUAL_FILE48(source, __VIRTUAL_FILE72(source), object, customizer);
});
var __VIRTUAL_FILE162 = assignInWith;
var domExcTag = "[object DOMException]", errorTag2 = "[object Error]";
function isError(value) {
    if (!__VIRTUAL_FILE50(value)) {
        return false;
    }
    var tag = __VIRTUAL_FILE17(value);
    return tag == errorTag2 || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !__VIRTUAL_FILE147(value);
}
var __VIRTUAL_FILE163 = isError;
var attempt = __VIRTUAL_FILE135(function(func, args) {
    try {
        return __VIRTUAL_FILE129(func, void 0, args);
    } catch (e) {
        return __VIRTUAL_FILE163(e) ? e : new Error(e);
    }
});
var __VIRTUAL_FILE164 = attempt;
var objectProto14 = Object.prototype;
var hasOwnProperty11 = objectProto14.hasOwnProperty;
function customDefaultsAssignIn(objValue, srcValue, key, object) {
    if (objValue === void 0 || __VIRTUAL_FILE1(objValue, objectProto14[key]) && !hasOwnProperty11.call(object, key)) {
        return srcValue;
    }
    return objValue;
}
var __VIRTUAL_FILE165 = customDefaultsAssignIn;
var stringEscapes = {
    "\\": "\\",
    "'": "'",
    "\n": "n",
    "\r": "r",
    "\u2028": "u2028",
    "\u2029": "u2029"
};
function escapeStringChar(chr) {
    return "\\" + stringEscapes[chr];
}
var __VIRTUAL_FILE166 = escapeStringChar;
var reInterpolate = /<%=([\s\S]+?)%>/g;
var __VIRTUAL_FILE167 = reInterpolate;
function basePropertyOf(object) {
    return function(key) {
        return object == null ? void 0 : object[key];
    };
}
var __VIRTUAL_FILE168 = basePropertyOf;
var htmlEscapes = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#39;"
};
var escapeHtmlChar = __VIRTUAL_FILE168(htmlEscapes);
var __VIRTUAL_FILE169 = escapeHtmlChar;
var INFINITY = 1 / 0;
var symbolProto1 = __VIRTUAL_FILE14 ? __VIRTUAL_FILE14.prototype : void 0, symbolToString = symbolProto1 ? symbolProto1.toString : void 0;
function baseToString(value) {
    if (typeof value == "string") {
        return value;
    }
    if (__VIRTUAL_FILE53(value)) {
        return __VIRTUAL_FILE123(value, baseToString) + "";
    }
    if (__VIRTUAL_FILE111(value)) {
        return symbolToString ? symbolToString.call(value) : "";
    }
    var result = value + "";
    return result == "0" && 1 / value == -INFINITY ? "-0" : result;
}
var __VIRTUAL_FILE170 = baseToString;
function toString(value) {
    return value == null ? "" : __VIRTUAL_FILE170(value);
}
var __VIRTUAL_FILE171 = toString;
var reUnescapedHtml = /[&<>"']/g, reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
function escape(string16) {
    string16 = __VIRTUAL_FILE171(string16);
    return string16 && reHasUnescapedHtml.test(string16) ? string16.replace(reUnescapedHtml, __VIRTUAL_FILE169) : string16;
}
var __VIRTUAL_FILE172 = escape;
var reEscape = /<%-([\s\S]+?)%>/g;
var __VIRTUAL_FILE173 = reEscape;
var reEvaluate = /<%([\s\S]+?)%>/g;
var __VIRTUAL_FILE174 = reEvaluate;
var templateSettings = {
    escape: __VIRTUAL_FILE173,
    evaluate: __VIRTUAL_FILE174,
    interpolate: __VIRTUAL_FILE167,
    variable: "",
    imports: {
        _: {
            escape: __VIRTUAL_FILE172
        }
    }
};
var __VIRTUAL_FILE175 = templateSettings;
var INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`";
var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
var reNoMatch = /($^)/;
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
var objectProto15 = Object.prototype;
var hasOwnProperty12 = objectProto15.hasOwnProperty;
function template(string17, options, guard) {
    var settings = __VIRTUAL_FILE175.imports._.templateSettings || __VIRTUAL_FILE175;
    if (guard && __VIRTUAL_FILE152(string17, options, guard)) {
        options = void 0;
    }
    string17 = __VIRTUAL_FILE171(string17);
    options = __VIRTUAL_FILE162({}, options, settings, __VIRTUAL_FILE165);
    var imports = __VIRTUAL_FILE162({}, options.imports, settings.imports, __VIRTUAL_FILE165), importsKeys = __VIRTUAL_FILE68(imports), importsValues = __VIRTUAL_FILE158(imports, importsKeys);
    var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '";
    var reDelimiters = RegExp((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === __VIRTUAL_FILE167 ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g");
    var sourceURL = hasOwnProperty12.call(options, "sourceURL") ? "//# sourceURL=" + (options.sourceURL + "").replace(/\s/g, " ") + "\n" : "";
    string17.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
        interpolateValue || (interpolateValue = esTemplateValue);
        source += string17.slice(index, offset).replace(reUnescapedString, __VIRTUAL_FILE166);
        if (escapeValue) {
            isEscaping = true;
            source += "' +\n__e(" + escapeValue + ") +\n'";
        }
        if (evaluateValue) {
            isEvaluating = true;
            source += "';\n" + evaluateValue + ";\n__p += '";
        }
        if (interpolateValue) {
            source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
        }
        index = offset + match.length;
        return match;
    });
    source += "';\n";
    var variable = hasOwnProperty12.call(options, "variable") && options.variable;
    if (!variable) {
        source = "with (obj) {\n" + source + "\n}\n";
    } else if (reForbiddenIdentifierChars.test(variable)) {
        throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
    }
    source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;");
    source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}";
    var result = __VIRTUAL_FILE164(function() {
        return Function(importsKeys, sourceURL + "return " + source).apply(void 0, importsValues);
    });
    result.source = source;
    if (__VIRTUAL_FILE163(result)) {
        throw result;
    }
    return result;
}
var __VIRTUAL_FILE176 = template;
function noop() {}
var __VIRTUAL_FILE177 = noop;
function setToArray(set1) {
    var index = -1, result = Array(set1.size);
    set1.forEach(function(value) {
        result[++index] = value;
    });
    return result;
}
var __VIRTUAL_FILE178 = setToArray;
var INFINITY1 = 1 / 0;
var createSet = !(__VIRTUAL_FILE89 && 1 / __VIRTUAL_FILE178(new __VIRTUAL_FILE89([
    ,
    -0
]))[1] == INFINITY1) ? __VIRTUAL_FILE177 : function(values8) {
    return new __VIRTUAL_FILE89(values8);
};
var __VIRTUAL_FILE179 = createSet;
var LARGE_ARRAY_SIZE2 = 200;
function baseUniq(array, iteratee, comparator) {
    var index = -1, includes = __VIRTUAL_FILE121, length = array.length, isCommon = true, result = [], seen = result;
    if (comparator) {
        isCommon = false;
        includes = __VIRTUAL_FILE122;
    } else if (length >= LARGE_ARRAY_SIZE2) {
        var set2 = iteratee ? null : __VIRTUAL_FILE179(array);
        if (set2) {
            return __VIRTUAL_FILE178(set2);
        }
        isCommon = false;
        includes = __VIRTUAL_FILE124;
        seen = new __VIRTUAL_FILE116();
    } else {
        seen = iteratee ? [] : result;
    }
    outer: while(++index < length){
        var value = array[index], computed = iteratee ? iteratee(value) : value;
        value = comparator || value !== 0 ? value : 0;
        if (isCommon && computed === computed) {
            var seenIndex = seen.length;
            while(seenIndex--){
                if (seen[seenIndex] === computed) {
                    continue outer;
                }
            }
            if (iteratee) {
                seen.push(computed);
            }
            result.push(value);
        } else if (!includes(seen, computed, comparator)) {
            if (seen !== result) {
                seen.push(computed);
            }
            result.push(value);
        }
    }
    return result;
}
var __VIRTUAL_FILE180 = baseUniq;
function uniq(array) {
    return array && array.length ? __VIRTUAL_FILE180(array) : [];
}
var __VIRTUAL_FILE181 = uniq;
function arraySome(array, predicate) {
    var index = -1, length = array == null ? 0 : array.length;
    while(++index < length){
        if (predicate(array[index], index, array)) {
            return true;
        }
    }
    return false;
}
var __VIRTUAL_FILE182 = arraySome;
var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
    var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
    if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
        return false;
    }
    var arrStacked = stack.get(array);
    var othStacked = stack.get(other);
    if (arrStacked && othStacked) {
        return arrStacked == other && othStacked == array;
    }
    var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new __VIRTUAL_FILE116() : void 0;
    stack.set(array, other);
    stack.set(other, array);
    while(++index < arrLength){
        var arrValue = array[index], othValue = other[index];
        if (customizer) {
            var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
        }
        if (compared !== void 0) {
            if (compared) {
                continue;
            }
            result = false;
            break;
        }
        if (seen) {
            if (!__VIRTUAL_FILE182(other, function(othValue2, othIndex) {
                if (!__VIRTUAL_FILE124(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
                    return seen.push(othIndex);
                }
            })) {
                result = false;
                break;
            }
        } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
            result = false;
            break;
        }
    }
    stack["delete"](array);
    stack["delete"](other);
    return result;
}
var __VIRTUAL_FILE183 = equalArrays;
function mapToArray(map7) {
    var index = -1, result = Array(map7.size);
    map7.forEach(function(value, key) {
        result[++index] = [
            key,
            value
        ];
    });
    return result;
}
var __VIRTUAL_FILE184 = mapToArray;
var COMPARE_PARTIAL_FLAG1 = 1, COMPARE_UNORDERED_FLAG1 = 2;
var boolTag3 = "[object Boolean]", dateTag3 = "[object Date]", errorTag3 = "[object Error]", mapTag5 = "[object Map]", numberTag3 = "[object Number]", regexpTag3 = "[object RegExp]", setTag5 = "[object Set]", stringTag3 = "[object String]", symbolTag3 = "[object Symbol]";
var arrayBufferTag3 = "[object ArrayBuffer]", dataViewTag4 = "[object DataView]";
var symbolProto2 = __VIRTUAL_FILE14 ? __VIRTUAL_FILE14.prototype : void 0, symbolValueOf1 = symbolProto2 ? symbolProto2.valueOf : void 0;
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
    switch(tag){
        case dataViewTag4:
            if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
                return false;
            }
            object = object.buffer;
            other = other.buffer;
        case arrayBufferTag3:
            if (object.byteLength != other.byteLength || !equalFunc(new __VIRTUAL_FILE93(object), new __VIRTUAL_FILE93(other))) {
                return false;
            }
            return true;
        case boolTag3:
        case dateTag3:
        case numberTag3:
            return __VIRTUAL_FILE1(+object, +other);
        case errorTag3:
            return object.name == other.name && object.message == other.message;
        case regexpTag3:
        case stringTag3:
            return object == other + "";
        case mapTag5:
            var convert = __VIRTUAL_FILE184;
        case setTag5:
            var isPartial = bitmask & COMPARE_PARTIAL_FLAG1;
            convert || (convert = __VIRTUAL_FILE178);
            if (object.size != other.size && !isPartial) {
                return false;
            }
            var stacked = stack.get(object);
            if (stacked) {
                return stacked == other;
            }
            bitmask |= COMPARE_UNORDERED_FLAG1;
            stack.set(object, other);
            var result = __VIRTUAL_FILE183(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
            stack["delete"](object);
            return result;
        case symbolTag3:
            if (symbolValueOf1) {
                return symbolValueOf1.call(object) == symbolValueOf1.call(other);
            }
    }
    return false;
}
var __VIRTUAL_FILE185 = equalByTag;
var COMPARE_PARTIAL_FLAG2 = 1;
var objectProto16 = Object.prototype;
var hasOwnProperty13 = objectProto16.hasOwnProperty;
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
    var isPartial = bitmask & COMPARE_PARTIAL_FLAG2, objProps = __VIRTUAL_FILE85(object), objLength = objProps.length, othProps = __VIRTUAL_FILE85(other), othLength = othProps.length;
    if (objLength != othLength && !isPartial) {
        return false;
    }
    var index = objLength;
    while(index--){
        var key = objProps[index];
        if (!(isPartial ? key in other : hasOwnProperty13.call(other, key))) {
            return false;
        }
    }
    var objStacked = stack.get(object);
    var othStacked = stack.get(other);
    if (objStacked && othStacked) {
        return objStacked == other && othStacked == object;
    }
    var result = true;
    stack.set(object, other);
    stack.set(other, object);
    var skipCtor = isPartial;
    while(++index < objLength){
        key = objProps[index];
        var objValue = object[key], othValue = other[key];
        if (customizer) {
            var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
        }
        if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
            result = false;
            break;
        }
        skipCtor || (skipCtor = key == "constructor");
    }
    if (result && !skipCtor) {
        var objCtor = object.constructor, othCtor = other.constructor;
        if (objCtor != othCtor && "constructor" in object && "constructor" in other && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
            result = false;
        }
    }
    stack["delete"](object);
    stack["delete"](other);
    return result;
}
var __VIRTUAL_FILE186 = equalObjects;
var COMPARE_PARTIAL_FLAG3 = 1;
var argsTag3 = "[object Arguments]", arrayTag2 = "[object Array]", objectTag4 = "[object Object]";
var objectProto17 = Object.prototype;
var hasOwnProperty14 = objectProto17.hasOwnProperty;
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
    var objIsArr = __VIRTUAL_FILE53(object), othIsArr = __VIRTUAL_FILE53(other), objTag = objIsArr ? arrayTag2 : __VIRTUAL_FILE91(object), othTag = othIsArr ? arrayTag2 : __VIRTUAL_FILE91(other);
    objTag = objTag == argsTag3 ? objectTag4 : objTag;
    othTag = othTag == argsTag3 ? objectTag4 : othTag;
    var objIsObj = objTag == objectTag4, othIsObj = othTag == objectTag4, isSameTag = objTag == othTag;
    if (isSameTag && __VIRTUAL_FILE55(object)) {
        if (!__VIRTUAL_FILE55(other)) {
            return false;
        }
        objIsArr = true;
        objIsObj = false;
    }
    if (isSameTag && !objIsObj) {
        stack || (stack = new __VIRTUAL_FILE43());
        return objIsArr || __VIRTUAL_FILE61(object) ? __VIRTUAL_FILE183(object, other, bitmask, customizer, equalFunc, stack) : __VIRTUAL_FILE185(object, other, objTag, bitmask, customizer, equalFunc, stack);
    }
    if (!(bitmask & COMPARE_PARTIAL_FLAG3)) {
        var objIsWrapped = objIsObj && hasOwnProperty14.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty14.call(other, "__wrapped__");
        if (objIsWrapped || othIsWrapped) {
            var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
            stack || (stack = new __VIRTUAL_FILE43());
            return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
        }
    }
    if (!isSameTag) {
        return false;
    }
    stack || (stack = new __VIRTUAL_FILE43());
    return __VIRTUAL_FILE186(object, other, bitmask, customizer, equalFunc, stack);
}
var __VIRTUAL_FILE187 = baseIsEqualDeep;
function baseIsEqual(value, other, bitmask, customizer, stack) {
    if (value === other) {
        return true;
    }
    if (value == null || other == null || !__VIRTUAL_FILE50(value) && !__VIRTUAL_FILE50(other)) {
        return value !== value && other !== other;
    }
    return __VIRTUAL_FILE187(value, other, bitmask, customizer, baseIsEqual, stack);
}
var __VIRTUAL_FILE188 = baseIsEqual;
var COMPARE_PARTIAL_FLAG4 = 1, COMPARE_UNORDERED_FLAG2 = 2;
function baseIsMatch(object, source, matchData, customizer) {
    var index = matchData.length, length = index, noCustomizer = !customizer;
    if (object == null) {
        return !length;
    }
    object = Object(object);
    while(index--){
        var data42 = matchData[index];
        if (noCustomizer && data42[2] ? data42[1] !== object[data42[0]] : !(data42[0] in object)) {
            return false;
        }
    }
    while(++index < length){
        data42 = matchData[index];
        var key = data42[0], objValue = object[key], srcValue = data42[1];
        if (noCustomizer && data42[2]) {
            if (objValue === void 0 && !(key in object)) {
                return false;
            }
        } else {
            var stack = new __VIRTUAL_FILE43();
            if (customizer) {
                var result = customizer(objValue, srcValue, key, object, source, stack);
            }
            if (!(result === void 0 ? __VIRTUAL_FILE188(srcValue, objValue, COMPARE_PARTIAL_FLAG4 | COMPARE_UNORDERED_FLAG2, customizer, stack) : result)) {
                return false;
            }
        }
    }
    return true;
}
var __VIRTUAL_FILE189 = baseIsMatch;
function isStrictComparable(value) {
    return value === value && !__VIRTUAL_FILE18(value);
}
var __VIRTUAL_FILE190 = isStrictComparable;
function getMatchData(object) {
    var result = __VIRTUAL_FILE68(object), length = result.length;
    while(length--){
        var key = result[length], value = object[key];
        result[length] = [
            key,
            value,
            __VIRTUAL_FILE190(value)
        ];
    }
    return result;
}
var __VIRTUAL_FILE191 = getMatchData;
function matchesStrictComparable(key, srcValue) {
    return function(object) {
        if (object == null) {
            return false;
        }
        return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
    };
}
var __VIRTUAL_FILE192 = matchesStrictComparable;
function baseMatches(source) {
    var matchData = __VIRTUAL_FILE191(source);
    if (matchData.length == 1 && matchData[0][2]) {
        return __VIRTUAL_FILE192(matchData[0][0], matchData[0][1]);
    }
    return function(object) {
        return object === source || __VIRTUAL_FILE189(object, source, matchData);
    };
}
var __VIRTUAL_FILE193 = baseMatches;
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/;
function isKey(value, object) {
    if (__VIRTUAL_FILE53(value)) {
        return false;
    }
    var type = typeof value;
    if (type == "number" || type == "symbol" || type == "boolean" || value == null || __VIRTUAL_FILE111(value)) {
        return true;
    }
    return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
var __VIRTUAL_FILE194 = isKey;
var FUNC_ERROR_TEXT1 = "Expected a function";
function memoize1(func, resolver) {
    if (typeof func != "function" || resolver != null && typeof resolver != "function") {
        throw new TypeError(FUNC_ERROR_TEXT1);
    }
    var memoized = function() {
        var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
        if (cache.has(key)) {
            return cache.get(key);
        }
        var result = func.apply(this, args);
        memoized.cache = cache.set(key, result) || cache;
        return result;
    };
    memoized.cache = new (memoize1.Cache || __VIRTUAL_FILE41)();
    return memoized;
}
memoize1.Cache = __VIRTUAL_FILE41;
var __VIRTUAL_FILE195 = memoize1;
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped(func) {
    var result = __VIRTUAL_FILE195(func, function(key) {
        if (cache.size === MAX_MEMOIZE_SIZE) {
            cache.clear();
        }
        return key;
    });
    var cache = result.cache;
    return result;
}
var __VIRTUAL_FILE196 = memoizeCapped;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath = __VIRTUAL_FILE196(function(string18) {
    var result = [];
    if (string18.charCodeAt(0) === 46) {
        result.push("");
    }
    string18.replace(rePropName, function(match, number1, quote, subString) {
        result.push(quote ? subString.replace(reEscapeChar, "$1") : number1 || match);
    });
    return result;
});
var __VIRTUAL_FILE197 = stringToPath;
function castPath(value, object) {
    if (__VIRTUAL_FILE53(value)) {
        return value;
    }
    return __VIRTUAL_FILE194(value, object) ? [
        value
    ] : __VIRTUAL_FILE197(__VIRTUAL_FILE171(value));
}
var __VIRTUAL_FILE198 = castPath;
var INFINITY2 = 1 / 0;
function toKey(value) {
    if (typeof value == "string" || __VIRTUAL_FILE111(value)) {
        return value;
    }
    var result = value + "";
    return result == "0" && 1 / value == -INFINITY2 ? "-0" : result;
}
var __VIRTUAL_FILE199 = toKey;
function baseGet(object, path49) {
    path49 = __VIRTUAL_FILE198(path49, object);
    var index = 0, length = path49.length;
    while(object != null && index < length){
        object = object[__VIRTUAL_FILE199(path49[index++])];
    }
    return index && index == length ? object : void 0;
}
var __VIRTUAL_FILE200 = baseGet;
function get(object, path50, defaultValue) {
    var result = object == null ? void 0 : __VIRTUAL_FILE200(object, path50);
    return result === void 0 ? defaultValue : result;
}
var __VIRTUAL_FILE201 = get;
function baseHasIn(object, key) {
    return object != null && key in Object(object);
}
var __VIRTUAL_FILE202 = baseHasIn;
function hasPath(object, path51, hasFunc) {
    path51 = __VIRTUAL_FILE198(path51, object);
    var index = -1, length = path51.length, result = false;
    while(++index < length){
        var key = __VIRTUAL_FILE199(path51[index]);
        if (!(result = object != null && hasFunc(object, key))) {
            break;
        }
        object = object[key];
    }
    if (result || ++index != length) {
        return result;
    }
    length = object == null ? 0 : object.length;
    return !!length && __VIRTUAL_FILE57(length) && __VIRTUAL_FILE56(key, length) && (__VIRTUAL_FILE53(object) || __VIRTUAL_FILE52(object));
}
var __VIRTUAL_FILE203 = hasPath;
function hasIn(object, path52) {
    return object != null && __VIRTUAL_FILE203(object, path52, __VIRTUAL_FILE202);
}
var __VIRTUAL_FILE204 = hasIn;
var COMPARE_PARTIAL_FLAG5 = 1, COMPARE_UNORDERED_FLAG3 = 2;
function baseMatchesProperty(path53, srcValue) {
    if (__VIRTUAL_FILE194(path53) && __VIRTUAL_FILE190(srcValue)) {
        return __VIRTUAL_FILE192(__VIRTUAL_FILE199(path53), srcValue);
    }
    return function(object) {
        var objValue = __VIRTUAL_FILE201(object, path53);
        return objValue === void 0 && objValue === srcValue ? __VIRTUAL_FILE204(object, path53) : __VIRTUAL_FILE188(srcValue, objValue, COMPARE_PARTIAL_FLAG5 | COMPARE_UNORDERED_FLAG3);
    };
}
var __VIRTUAL_FILE205 = baseMatchesProperty;
function baseProperty(key) {
    return function(object) {
        return object == null ? void 0 : object[key];
    };
}
var __VIRTUAL_FILE206 = baseProperty;
function basePropertyDeep(path54) {
    return function(object) {
        return __VIRTUAL_FILE200(object, path54);
    };
}
var __VIRTUAL_FILE207 = basePropertyDeep;
function property(path55) {
    return __VIRTUAL_FILE194(path55) ? __VIRTUAL_FILE206(__VIRTUAL_FILE199(path55)) : __VIRTUAL_FILE207(path55);
}
var __VIRTUAL_FILE208 = property;
function baseIteratee(value) {
    if (typeof value == "function") {
        return value;
    }
    if (value == null) {
        return __VIRTUAL_FILE128;
    }
    if (typeof value == "object") {
        return __VIRTUAL_FILE53(value) ? __VIRTUAL_FILE205(value[0], value[1]) : __VIRTUAL_FILE193(value);
    }
    return __VIRTUAL_FILE208(value);
}
var __VIRTUAL_FILE209 = baseIteratee;
function uniqBy(array, iteratee) {
    return array && array.length ? __VIRTUAL_FILE180(array, __VIRTUAL_FILE209(iteratee, 2)) : [];
}
var __VIRTUAL_FILE210 = uniqBy;
function isEqual(value, other) {
    return __VIRTUAL_FILE188(value, other);
}
var __VIRTUAL_FILE211 = isEqual;
function baseMap(collection, iteratee) {
    var index = -1, result = __VIRTUAL_FILE67(collection) ? Array(collection.length) : [];
    __VIRTUAL_FILE142(collection, function(value, key, collection2) {
        result[++index] = iteratee(value, key, collection2);
    });
    return result;
}
var __VIRTUAL_FILE212 = baseMap;
function baseSortBy(array, comparer) {
    var length = array.length;
    array.sort(comparer);
    while(length--){
        array[length] = array[length].value;
    }
    return array;
}
var __VIRTUAL_FILE213 = baseSortBy;
function compareAscending(value, other) {
    if (value !== other) {
        var valIsDefined = value !== void 0, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = __VIRTUAL_FILE111(value);
        var othIsDefined = other !== void 0, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = __VIRTUAL_FILE111(other);
        if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
            return 1;
        }
        if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
            return -1;
        }
    }
    return 0;
}
var __VIRTUAL_FILE214 = compareAscending;
function compareMultiple(object, other, orders) {
    var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
    while(++index < length){
        var result = __VIRTUAL_FILE214(objCriteria[index], othCriteria[index]);
        if (result) {
            if (index >= ordersLength) {
                return result;
            }
            var order = orders[index];
            return result * (order == "desc" ? -1 : 1);
        }
    }
    return object.index - other.index;
}
var __VIRTUAL_FILE215 = compareMultiple;
function baseOrderBy(collection, iteratees, orders) {
    if (iteratees.length) {
        iteratees = __VIRTUAL_FILE123(iteratees, function(iteratee) {
            if (__VIRTUAL_FILE53(iteratee)) {
                return function(value) {
                    return __VIRTUAL_FILE200(value, iteratee.length === 1 ? iteratee[0] : iteratee);
                };
            }
            return iteratee;
        });
    } else {
        iteratees = [
            __VIRTUAL_FILE128
        ];
    }
    var index = -1;
    iteratees = __VIRTUAL_FILE123(iteratees, __VIRTUAL_FILE59(__VIRTUAL_FILE209));
    var result = __VIRTUAL_FILE212(collection, function(value, key, collection2) {
        var criteria = __VIRTUAL_FILE123(iteratees, function(iteratee) {
            return iteratee(value);
        });
        return {
            criteria,
            index: ++index,
            value
        };
    });
    return __VIRTUAL_FILE213(result, function(object, other) {
        return __VIRTUAL_FILE215(object, other, orders);
    });
}
var __VIRTUAL_FILE216 = baseOrderBy;
function orderBy(collection, iteratees, orders, guard) {
    if (collection == null) {
        return [];
    }
    if (!__VIRTUAL_FILE53(iteratees)) {
        iteratees = iteratees == null ? [] : [
            iteratees
        ];
    }
    orders = guard ? void 0 : orders;
    if (!__VIRTUAL_FILE53(orders)) {
        orders = orders == null ? [] : [
            orders
        ];
    }
    return __VIRTUAL_FILE216(collection, iteratees, orders);
}
var __VIRTUAL_FILE217 = orderBy;
const cloneDeep1 = __VIRTUAL_FILE107;
const debounce1 = __VIRTUAL_FILE113;
const shuffle1 = __VIRTUAL_FILE161;
const toString1 = __VIRTUAL_FILE171;
const uniq1 = __VIRTUAL_FILE181;
const uniqBy1 = __VIRTUAL_FILE210;
const escape1 = __VIRTUAL_FILE172;
class ValidationError2 extends Error {
    validationErrors;
    constructor(msg, validationErrors){
        super([
            msg,
            ...validationErrors.map((e)=>tidyverseFormatError(e.niceError)
            )
        ].join("\n\n"));
        Object.setPrototypeOf(this, ValidationError2.prototype);
        this.validationErrors = validationErrors;
    }
}
function readAndValidateYamlFromFile(file, schema, errorMessage) {
    if (!existsSync(file)) {
        throw new Error(`YAML file ${file} not found.`);
    }
    let shortFileName = file;
    if (shortFileName.startsWith("/")) {
        shortFileName = relative2(Deno.cwd(), shortFileName);
    }
    const contents = asMappedString(Deno.readTextFileSync(file), shortFileName);
    return readAndValidateYamlFromMappedString(contents, schema, errorMessage);
}
async function readAndValidateYamlFromMappedString(mappedYaml, schema, errorMessage) {
    const result = await withValidator(schema, async (validator)=>{
        const annotation = readAnnotatedYamlFromMappedString(mappedYaml);
        const validateYaml = !__VIRTUAL_FILE18(annotation.result) || annotation.result["validate-yaml"] !== false;
        const yaml = annotation.result;
        if (validateYaml) {
            const valResult = await validator.validateParse(mappedYaml, annotation);
            if (valResult.errors.length) {
                validator.reportErrorsInSource({
                    result: yaml,
                    errors: valResult.errors
                }, mappedYaml, errorMessage, (msg)=>{
                    if (!errorOnce(msg)) {
                        info("");
                    }
                }, (a)=>{
                    error(tidyverseFormatError(a), {
                        colorize: false
                    });
                });
            }
            return {
                yaml: yaml,
                yamlValidationErrors: valResult.errors
            };
        } else {
            return {
                yaml: yaml,
                yamlValidationErrors: []
            };
        }
    });
    if (result.yamlValidationErrors.length > 0) {
        throw new ValidationError2(errorMessage, result.yamlValidationErrors);
    }
    return result.yaml;
}
const kRegExBeginYAML = /^---[ \t]*$/;
const kRegExEndYAML = /^(?:---|\.\.\.)([ \t]*)$/;
const kRegExYAML = /(^)(---[ \t]*[\r\n]+(?![ \t]*[\r\n]+)[\W\w]*?[\r\n]+(?:---|\.\.\.))([ \t]*)$/gm;
const kRegxHTMLComment = /<!--[\W\w]*?-->/gm;
const kRegexFencedCode = /^([\t >]*`{3,})[^`\n]*\n[\W\w]*?\n\1\s*$/gm;
function isYamlPath(file) {
    return [
        ".yaml",
        ".yml"
    ].includes(extname2(file));
}
function readYaml(file) {
    if (existsSync(file)) {
        const decoder = new TextDecoder("utf-8");
        const yml = Deno.readFileSync(file);
        const result = parse3(decoder.decode(yml), {
            schema: json
        });
        try {
            JSON.stringify(result);
            return result;
        } catch (e) {
            throw new Error(`Circular structures not allowed.\nFile ${file}\n${e.message.split("\n").slice(1).join("\n")}`);
        }
    } else {
        throw new Error(`YAML file ${file} not found.`);
    }
}
function readYamlFromString(yml) {
    return parse3(yml, {
        schema: json
    });
}
function readYamlFromMarkdown(markdown) {
    if (markdown) {
        markdown = normalizeNewlines(markdown);
        markdown = markdown.replaceAll(kRegxHTMLComment, "");
        markdown = markdown.replaceAll(kRegexFencedCode, "");
        let yaml = "";
        kRegExYAML.lastIndex = 0;
        let match = kRegExYAML.exec(markdown);
        while(match != null){
            const yamlBlock = removeYamlDelimiters(match[2]);
            if (!yamlBlock.startsWith("\n\n") && !yamlBlock.startsWith("\n---") && yamlBlock.trim().length > 0) {
                parse3(yamlBlock, {
                    json: true,
                    schema: json
                });
                yaml += yamlBlock;
            }
            match = kRegExYAML.exec(markdown);
        }
        kRegExYAML.lastIndex = 0;
        const metadata = parse3(yaml, {
            json: true,
            schema: json
        });
        return metadata || {};
    } else {
        return {};
    }
}
async function readAndValidateYamlFromMarkdown(eitherMarkdown) {
    let markdown = asMappedString(eitherMarkdown);
    if (!markdown.value) {
        return {};
    }
    markdown = mappedNormalizeNewlines(markdown);
    markdown = skipRegexpAll(markdown, kRegxHTMLComment);
    markdown = skipRegexpAll(markdown, kRegexFencedCode);
    const yaml = [];
    kRegExYAML.lastIndex = 0;
    for (const match of matchAll(markdown.value, kRegExYAML)){
        const yamlBlock = removeYamlDelimitersMapped(match[2]);
        const yamlBlockValue = yamlBlock.value;
        if (!yamlBlockValue.startsWith("\n\n") && !yamlBlockValue.startsWith("\n---") && yamlBlockValue.trim().length > 0) {
            parse3(yamlBlockValue, {
                json: true,
                schema: json
            });
            yaml.push(yamlBlock);
        }
    }
    kRegExYAML.lastIndex = 0;
    if (yaml.length === 0) {
        return {};
    }
    const mappedYaml = mappedConcat(yaml);
    const metadata = parse3(mappedYaml.value, {
        json: true,
        schema: json
    });
    if (metadata?.["validate-yaml"] === false) {
        return readAndValidateYamlFromMappedString(mappedYaml, await getFrontMatterSchema(), "YAML front matter validation failed");
    }
    return metadata;
}
async function readYamlFromMarkdownFile(file) {
    const markdown = Deno.readTextFileSync(file);
    const result = await readAndValidateYamlFromMarkdown(markdown);
    return result;
}
function partitionYamlFrontMatter(markdown) {
    const mdLines = lines(markdown.trimLeft());
    if (mdLines.length < 3 || !mdLines[0].match(kRegExBeginYAML)) {
        return null;
    } else if (mdLines[1].trim().length === 0 || mdLines[1].match(kRegExEndYAML)) {
        return null;
    } else {
        const endYamlPos = mdLines.findIndex((line, index)=>index > 0 && line.match(kRegExEndYAML)
        );
        if (endYamlPos === -1) {
            return null;
        } else {
            return {
                yaml: mdLines.slice(0, endYamlPos + 1).join("\n"),
                markdown: "\n" + mdLines.slice(endYamlPos + 1).join("\n")
            };
        }
    }
}
function removeYamlDelimiters(yaml) {
    return yaml.replace(/^---/, "").replace(/---\s*$/, "");
}
function removeYamlDelimitersMapped(eitherYaml) {
    let yaml = asMappedString(eitherYaml);
    yaml = skipRegexp(yaml, /^---/);
    yaml = skipRegexp(yaml, /---\s*$/);
    return yaml;
}
class YAMLValidationError extends ErrorEx {
    constructor(message){
        super("YAMLValidationError", message, false, false);
    }
}
function generate() {
    return crypto.randomUUID();
}
function mergeConfigs(config, ...configs) {
    config = cloneDeep1(config);
    configs = cloneDeep1(configs);
    return __VIRTUAL_FILE154(config, ...configs, mergeArrayCustomizer);
}
function mergeArrayCustomizer(objValue, srcValue) {
    if (__VIRTUAL_FILE53(objValue) || __VIRTUAL_FILE53(srcValue)) {
        if (!objValue) {
            return srcValue;
        } else if (!srcValue) {
            return objValue;
        } else {
            if (!__VIRTUAL_FILE53(objValue)) {
                objValue = [
                    objValue
                ];
            }
            if (!__VIRTUAL_FILE53(srcValue)) {
                srcValue = [
                    srcValue
                ];
            }
        }
        const combined = objValue.concat(srcValue);
        return __VIRTUAL_FILE210(combined, (value)=>{
            if (typeof value === "function") {
                return generate();
            } else {
                return JSON.stringify(value);
            }
        });
    }
}
function camelToKebab(camel) {
    const kebab = [];
    for(let i47 = 0; i47 < camel.length; i47++){
        const ch = camel.charAt(i47);
        if (ch === ch.toUpperCase() && !/^\d+/.test(ch)) {
            if (i47 > 0) {
                kebab.push("-");
            }
            kebab.push(ch.toLowerCase());
        } else {
            kebab.push(ch);
        }
    }
    return kebab.join("");
}
function kebabToCamel(kebab, leadingUppercase = false) {
    const camel = [];
    for(let i48 = 0; i48 < kebab.length; i48++){
        const ch = kebab.charAt(i48);
        if (ch === "-") {
            camel.push(kebab.charAt(++i48).toUpperCase());
        } else if (i48 === 0 && leadingUppercase) {
            camel.push(ch.toUpperCase());
        } else {
            camel.push(ch);
        }
    }
    return camel.join("");
}
const kMetadataFormat = "format";
const kRenderDefaults = "render";
const kExecuteDefaults = "execute";
const kPandocDefaults = "pandoc";
const kLanguageDefaults = "language";
const kPandocMetadata = "metadata";
const kFigWidth = "fig-width";
const kFigHeight = "fig-height";
const kFigFormat = "fig-format";
const kFigDpi = "fig-dpi";
const kCache = "cache";
const kFreeze = "freeze";
const kEngine = "engine";
const kEval = "eval";
const kEcho = "echo";
const kOutput = "output";
const kWarning = "warning";
const kError = "error";
const kInclude = "include";
const kResources = "resources";
const kKeepHidden = "keep-hidden";
const kExecuteEnabled = "enabled";
const kExecuteIpynb = "ipynb";
const kExecuteDaemon = "daemon";
const kExecuteDaemonRestart = "daemon-restart";
const kExecuteDebug = "debug";
const kKeepMd = "keep-md";
const kKeepTex = "keep-tex";
const kKeepYaml = "keep-yaml";
const kKeepIpynb = "keep-ipynb";
const kKeepSource = "keep-source";
const kVariant = "variant";
const kOutputExt = "output-ext";
const kOutputDivs = "output-divs";
const kPageWidth = "page-width";
const kFigAlign = "fig-align";
const kFigEnv = "fig-env";
const kFigPos = "fig-pos";
const kCodeFold = "code-fold";
const kCodeLineNumbers = "code-line-numbers";
const kCodeOverflow = "code-overflow";
const kCodeLink = "code-link";
const kCodeTools = "code-tools";
const kTblColwidths = "tbl-colwidths";
const kMergeIncludes = "merge-includes";
const kPreferHtml = "prefer-html";
const kSelfContainedMath = "self-contained-math";
const kLatexAutoMk = "latex-auto-mk";
const kLatexAutoInstall = "latex-auto-install";
const kLatexMinRuns = "latex-min-runs";
const kLatexMaxRuns = "latex-max-runs";
const kLatexClean = "latex-clean";
const kLatexMakeIndex = "latex-makeindex";
const kLatexMakeIndexOpts = "latex-makeindex-opts";
const kLatexTlmgrOpts = "latex-tlmgr-opts";
const kLatexOutputDir = "latex-output-dir";
const kLinkExternalIcon = "link-external-icon";
const kLinkExternalNewwindow = "link-external-newwindow";
const kLinkExternalFilter = "link-external-filter";
const kExecuteDefaultsKeys = [
    kFigWidth,
    kFigHeight,
    kFigFormat,
    kFigDpi,
    kError,
    kEval,
    kEngine,
    kCache,
    kFreeze,
    kEcho,
    kOutput,
    kWarning,
    kInclude,
    kKeepMd,
    kKeepIpynb,
    kExecuteEnabled,
    kExecuteIpynb,
    kExecuteDaemon,
    kExecuteDaemonRestart,
    kExecuteDebug, 
];
const kRenderDefaultsKeys = [
    kKeepTex,
    kKeepYaml,
    kKeepSource,
    kKeepHidden,
    kVariant,
    kOutputExt,
    kOutputDivs,
    kPreferHtml,
    kPageWidth,
    kFigAlign,
    kFigPos,
    kFigEnv,
    kCodeFold,
    kCodeLink,
    kCodeLineNumbers,
    kCodeOverflow,
    kCodeTools,
    kTblColwidths,
    kSelfContainedMath,
    kLatexAutoMk,
    kLatexAutoInstall,
    kLatexMinRuns,
    kLatexMaxRuns,
    kLatexClean,
    kLatexMakeIndex,
    kLatexMakeIndexOpts,
    kLatexTlmgrOpts,
    kLatexOutputDir,
    kLinkExternalIcon,
    kLinkExternalNewwindow,
    kLinkExternalFilter, 
];
const kTocTitleDocument = "toc-title-document";
const kTocTitleWebsite = "toc-title-website";
const kCalloutTipCaption = "callout-tip-caption";
const kCalloutNoteCaption = "callout-note-caption";
const kCalloutWarningCaption = "callout-warning-caption";
const kCalloutImportantCaption = "callout-important-caption";
const kCalloutDangerCaption = "callout-danger-caption";
const kSectionTitleAbstract = "section-title-abstract";
const kSectionTitleFootnotes = "section-title-footnotes";
const kSectionTitleReferences = "section-title-references";
const kSectionTitleAppendices = "section-title-appendices";
const kSectionTitleReuse = "section-title-reuse";
const kSectionTitleCitation = "section-title-citation";
const kAppendixAttributionBibTex = "appendix-attribution-bibtex";
const kAppendixAttributionCiteAs = "appendix-attribution-cite-as";
const kTitleBlockAuthorSingle = "title-block-author-single";
const kTitleBlockAuthorPlural = "title-block-author-plural";
const kTitleBlockAffiliationSingle = "title-block-affiliation-single";
const kTitleBlockAffiliationPlural = "title-block-affiliation-plural";
const kTitleBlockPublished = "title-block-published";
const kCodeSummary = "code-summary";
const kCodeToolsMenuCaption = "code-tools-menu-caption";
const kCodeToolsShowAllCode = "code-tools-show-all-code";
const kCodeToolsHideAllCode = "code-tools-hide-all-code";
const kCodeToolsViewSource = "code-tools-view-source";
const kCodeToolsSourceCode = "code-tools-source-code";
const kSearchNoResultsText = "search-no-results-text";
const kCopyButtonTooltip = "copy-button-tooltip";
const kRepoActionLinksEdit = "repo-action-links-edit";
const kRepoActionLinksSource = "repo-action-links-source";
const kRepoActionLinksIssue = "repo-action-links-issue";
const kSearchMatchingDocumentsText = "search-matching-documents-text";
const kSearchCopyLinkTitle = "search-copy-link-title";
const kSearchHideMatchesText = "search-hide-matches-text";
const kSearchMoreMatchText = "search-more-match-text";
const kSearchMoreMatchesText = "search-more-matches-text";
const kSearchClearButtonTitle = "search-clear-button-title";
const kSearchDetatchedCancelButtonTitle = "search-detached-cancel-button-title";
const kSearchSubmitButtonTitle = "search-submit-button-title";
const kCrossrefFigTitle = "crossref-fig-title";
const kCrossrefTblTitle = "crossref-tbl-title";
const kCrossrefLstTitle = "crossref-lst-title";
const kCrossrefThmTitle = "crossref-thm-title";
const kCrossrefLemTitle = "crossref-lem-title";
const kCrossrefCorTitle = "crossref-cor-title";
const kCrossrefPrfTitle = "crossref-prp-title";
const kCrossrefCnjTitle = "crossref-cnj-title";
const kCrossrefDefTitle = "crossref-def-title";
const kCrossrefExmTitle = "crossref-exm-title";
const kCrossrefExrTitle = "crossref-exr-title";
const kCrossrefFigPrefix = "crossref-fig-prefix";
const kCrossrefTblPrefix = "crossref-tbl-prefix";
const kCrossrefLstPrefix = "crossref-lst-prefix";
const kCrossrefSecPrefix = "crossref-sec-prefix";
const kCrossrefEqPrefix = "crossref-eq-prefix";
const kCrossrefThmPrefix = "crossref-thm-prefix";
const kCrossrefLemPrefix = "crossref-lem-prefix";
const kCrossrefCorPrefix = "crossref-cor-prefix";
const kCrossrefPrpPrefix = "crossref-prp-prefix";
const kCrossrefCnjPrefix = "crossref-cnj-prefix";
const kCrossrefDefPrefix = "crossref-def-prefix";
const kCrossrefExmPrefix = "crossref-exm-prefix";
const kCrossrefExrPrefix = "crossref-exr-prefix";
const kCrossrefLofTitle = "crossref-lof-title";
const kCrossrefLotTitle = "crossref-lot-title";
const kCrossrefLolTitle = "crossref-lol-title";
const kListingPageOrderBy = "listing-page-order-by";
const kListingPageOrderByDefault = "listing-page-order-by-default";
const kListingPageOrderByDateAsc = "listing-page-order-by-date-asc";
const kListingPageOrderByDateDesc = "listing-page-order-by-date-desc";
const kListingPageOrderByNumberAsc = "listing-page-order-by-number-asc";
const kListingPageOrderByNumberDesc = "listing-page-order-by-number-desc";
const kListingPageFieldDate = "listing-page-field-date";
const kListingPageFieldTitle = "listing-page-field-title";
const kListingPageFieldDescription = "listing-page-field-description";
const kListingPageFieldAuthor = "listing-page-field-author";
const kListingPageFieldFileName = "listing-page-field-filename";
const kListingPageFieldFileModified = "listing-page-field-filemodified";
const kListingPageFieldSubtitle = "listing-page-field-subtitle";
const kListingPageFieldReadingTime = "listing-page-field-readingtime";
const kListingPageFieldCategories = "listing-page-field-categories";
const kListingPageMinutesCompact = "listing-page-minutes-compact";
const kListingPageCategoryAll = "listing-page-category-all";
const kListingPageNoMatches = "listing-page-no-matches";
const kLanguageDefaultsKeys = [
    kTocTitleDocument,
    kTocTitleWebsite,
    kCalloutTipCaption,
    kCalloutNoteCaption,
    kCalloutWarningCaption,
    kCalloutImportantCaption,
    kCalloutDangerCaption,
    kSectionTitleAbstract,
    kSectionTitleFootnotes,
    kSectionTitleReferences,
    kSectionTitleAppendices,
    kSectionTitleReuse,
    kSectionTitleCitation,
    kAppendixAttributionBibTex,
    kAppendixAttributionCiteAs,
    kTitleBlockAuthorSingle,
    kTitleBlockPublished,
    kCodeSummary,
    kCodeToolsMenuCaption,
    kCodeToolsShowAllCode,
    kCodeToolsHideAllCode,
    kCodeToolsViewSource,
    kCodeToolsSourceCode,
    kSearchNoResultsText,
    kCopyButtonTooltip,
    kRepoActionLinksEdit,
    kRepoActionLinksSource,
    kRepoActionLinksIssue,
    kSearchMatchingDocumentsText,
    kSearchCopyLinkTitle,
    kSearchHideMatchesText,
    kSearchMoreMatchText,
    kSearchMoreMatchesText,
    kSearchClearButtonTitle,
    kSearchDetatchedCancelButtonTitle,
    kSearchSubmitButtonTitle,
    kCrossrefFigTitle,
    kCrossrefTblTitle,
    kCrossrefLstTitle,
    kCrossrefThmTitle,
    kCrossrefLemTitle,
    kCrossrefCorTitle,
    kCrossrefPrfTitle,
    kCrossrefCnjTitle,
    kCrossrefDefTitle,
    kCrossrefExmTitle,
    kCrossrefExrTitle,
    kCrossrefFigPrefix,
    kCrossrefTblPrefix,
    kCrossrefLstPrefix,
    kCrossrefSecPrefix,
    kCrossrefEqPrefix,
    kCrossrefThmPrefix,
    kCrossrefLemPrefix,
    kCrossrefCorPrefix,
    kCrossrefPrpPrefix,
    kCrossrefCnjPrefix,
    kCrossrefDefPrefix,
    kCrossrefExmPrefix,
    kCrossrefExrPrefix,
    kCrossrefLofTitle,
    kCrossrefLotTitle,
    kCrossrefLolTitle,
    kListingPageOrderBy,
    kListingPageOrderByDefault,
    kListingPageOrderByDateAsc,
    kListingPageOrderByDateDesc,
    kListingPageOrderByNumberAsc,
    kListingPageOrderByNumberDesc,
    kListingPageFieldDate,
    kListingPageFieldTitle,
    kListingPageFieldDescription,
    kListingPageFieldAuthor,
    kListingPageFieldFileName,
    kListingPageFieldFileModified,
    kListingPageFieldSubtitle,
    kListingPageFieldReadingTime,
    kListingPageFieldCategories,
    kListingPageMinutesCompact,
    kListingPageCategoryAll,
    kListingPageNoMatches,
    kTitleBlockAuthorSingle,
    kTitleBlockAuthorPlural,
    kTitleBlockAffiliationSingle,
    kTitleBlockAffiliationPlural,
    kTitleBlockPublished, 
];
const kTo = "to";
const kFrom = "from";
const kReader = "reader";
const kWriter = "writer";
const kOutputFile = "output-file";
const kInputFiles = "input-files";
const kAtxHeaders = "atx-headers";
const kMarkdownHeadings = "markdown-headings";
const kTemplate = "template";
const kStandalone = "standalone";
const kWrap = "wrap";
const kSelfContained = "self-contained";
const kIncludeBeforeBody = "include-before-body";
const kIncludeAfterBody = "include-after-body";
const kIncludeInHeader = "include-in-header";
const kCiteproc = "citeproc";
const kCiteMethod = "cite-method";
const kFilters = "filters";
const kFilterParams = "filter-params";
const kPdfEngine = "pdf-engine";
const kPdfEngineOpts = "pdf-engine-opts";
const kPdfEngineOpt = "pdf-engine-opt";
const kListings = "listings";
const kNumberSections = "number-sections";
const kNumberOffset = "number-offset";
const kShiftHeadingLevelBy = "shift-heading-level-by";
const kNumberDepth = "number-depth";
const kTopLevelDivision = "top-level-division";
const kPaperSize = "papersize";
const kLogFile = "log-file";
const kHighlightStyle = "highlight-style";
const kDefaultImageExtension = "default-image-extension";
const kLinkColor = "linkcolor";
const kColorLinks = "colorlinks";
const kVariables = "variables";
const kMetadataFile = "metadata-file";
const kMetadataFiles = "metadata-files";
const kSyntaxDefinitions = "syntax-definitions";
const kSyntaxDefinition = "syntax-definition";
const kReferenceDoc = "reference-doc";
const kHtmlMathMethod = "html-math-method";
const kToc = "toc";
const kTableOfContents = "table-of-contents";
const kSectionDivs = "section-divs";
const kEPubCoverImage = "epub-cover-image";
const kReferenceLocation = "reference-location";
const kCitationLocation = "citation-location";
const kQuartoVarsKey = "_quarto-vars";
const kTitle = "title";
const kSubtitle = "subtitle";
const kAuthor = "author";
const kDate = "date";
const kDoi = "doi";
const kAbstract = "abstract";
const kAbstractTitle = "abstract-title";
const kDescription = "description";
const kTocTitle = "toc-title";
const kTocLocation = "toc-location";
const kLang = "lang";
const kServer = "server";
const kPageTitle = "pagetitle";
const kTitlePrefix = "title-prefix";
const kCsl = "csl";
const kCss = "css";
const kBibliography = "bibliography";
const kHeaderIncludes = "header-includes";
const kIncludeBefore = "include-before";
const kIncludeAfter = "include-after";
const kLinkCitations = "link-citations";
const kDocumentClass = "documentclass";
const kClassOption = "classoption";
const kSlideLevel = "slide-level";
const kTheme = "theme";
const kCrossref = "crossref";
const kCrossrefChapters = "chapters";
const kCrossrefLabels = "labels";
const kCrossrefAppendixTitle = "appendix-title";
const kCrossrefAppendixDelim = "appendix-delim";
const kCrossrefChaptersAlpha = "chapters-alpha";
const kCrossrefChapterId = "chapter-id";
const kFigResponsive = "fig-responsive";
const kCapLoc = "cap-location";
const kFigCapLoc = "fig-cap-location";
const kTblCapLoc = "tbl-cap-location";
const kCapTop = "top";
const kCapBottom = "bottom";
const kPandocDefaultsKeys = [
    kTo,
    kFrom,
    kReader,
    kWriter,
    kOutputFile,
    kInputFiles,
    "defaults",
    kTemplate,
    kStandalone,
    kSelfContained,
    kVariables,
    "metadata",
    kMetadataFiles,
    kMetadataFile,
    kIncludeBeforeBody,
    kIncludeAfterBody,
    kIncludeInHeader,
    "resource-path",
    kCiteproc,
    kCiteMethod,
    "citation-abbreviations",
    "filters",
    "file-scope",
    "data-dir",
    "verbosity",
    kLogFile,
    kTopLevelDivision,
    "abbreviations",
    kPdfEngine,
    kPdfEngineOpts,
    kPdfEngineOpt,
    kWrap,
    "columns",
    "dpi",
    "extract-media",
    kToc,
    kTableOfContents,
    "toc-depth",
    kNumberSections,
    kNumberOffset,
    kShiftHeadingLevelBy,
    kSectionDivs,
    "identifier-prefix",
    kTitlePrefix,
    "strip-empty-paragraphs",
    "eol",
    "strip-comments",
    "indented-code-classes",
    "ascii",
    kDefaultImageExtension,
    kHighlightStyle,
    kSyntaxDefinitions,
    kSyntaxDefinition,
    kListings,
    kReferenceDoc,
    kHtmlMathMethod,
    "email-obfuscation",
    "tab-stop",
    "preserve-tabs",
    "incremental",
    kSlideLevel,
    "epub-subdirectory",
    "epub-metadata",
    "epub-fonts",
    "epub-chapter-level",
    kEPubCoverImage,
    "reference-links",
    kReferenceLocation,
    kAtxHeaders,
    kMarkdownHeadings,
    "track-changes",
    "html-q-tags",
    "css",
    "ipynb-output",
    "request-headers",
    "fail-if-warnings",
    "dump-args",
    "ignore-args",
    "trace", 
];
const kCellCollapsed = "collapsed";
const kCellAutoscroll = "autoscroll";
const kCellDeletable = "deletable";
const kCellFormat = "format";
const kCellName = "name";
const kCellLinesToNext = "lines_to_next_cell";
const kCellSlideshow = "slideshow";
const kCellSlideshowSlideType = "slide_type";
const kCellRawMimeType = "raw_mimetype";
const kCellId = "id";
const kCellLabel = "label";
const kCellFigCap = "fig-cap";
const kCellFigSubCap = "fig-subcap";
const kCellFigScap = "fig-scap";
const kCellFigColumn = "fig-column";
const kCellTblColumn = "tbl-column";
const kCellFigLink = "fig-link";
const kCellFigAlign = "fig-align";
const kCellFigEnv = "fig-env";
const kCellFigPos = "fig-pos";
const kCellFigAlt = "fig-alt";
const kCellLstLabel = "lst-label";
const kCellLstCap = "lst-cap";
const kCellClasses = "classes";
const kCellPanel = "panel";
const kCellColumn = "column";
const kCellOutWidth = "out-width";
const kCellOutHeight = "out-height";
const kCellMdIndent = "md-indent";
const kCellColab = "colab";
const kCellColabType = "colab_type";
const kCellColbOutputId = "outputId";
const kLayoutAlign = "layout-align";
const kLayoutVAlign = "layout-valign";
const kLayoutNcol = "layout-ncol";
const kLayoutNrow = "layout-nrow";
const kLayout = "layout";
async function includedMetadata(dir, baseMetadata, schema) {
    const yamlFiles = [];
    const metadataFile = baseMetadata[kMetadataFile];
    if (metadataFile) {
        yamlFiles.push(join3(dir, metadataFile));
    }
    const metadataFiles = baseMetadata[kMetadataFiles];
    if (metadataFiles && Array.isArray(metadataFiles)) {
        metadataFiles.forEach((file)=>yamlFiles.push(join3(dir, file))
        );
    }
    const filesMetadata = await Promise.all(yamlFiles.map(async (yamlFile)=>{
        if (await exists(yamlFile)) {
            try {
                const yaml = await readAndValidateYamlFromFile(yamlFile, schema, `Validation of metadata file ${yamlFile} failed.`);
                return yaml;
            } catch (e) {
                error("\nError reading metadata file from " + yamlFile + "\n");
                throw e;
            }
        } else {
            return undefined;
        }
    }));
    return {
        metadata: mergeFormatMetadata({}, ...filesMetadata),
        files: yamlFiles
    };
}
function formatFromMetadata(baseFormat, to, debug1) {
    const typedFormat = {
        render: {},
        execute: {},
        pandoc: {},
        language: {},
        metadata: {}
    };
    let format9 = typedFormat;
    const configFormats = baseFormat.metadata[kMetadataFormat];
    if (configFormats instanceof Object) {
        const configFormat = configFormats[to];
        if (configFormat === "default" || configFormat === true) {
            format9 = metadataAsFormat({});
        } else if (configFormat instanceof Object) {
            format9 = metadataAsFormat(configFormat);
        }
    }
    const mergedFormat = mergeFormatMetadata(baseFormat, format9);
    if (debug1) {
        mergedFormat.execute[kKeepMd] = true;
        mergedFormat.render[kKeepTex] = true;
    }
    return mergedFormat;
}
function formatKeys(metadata) {
    if (typeof metadata[kMetadataFormat] === "string") {
        return [
            metadata[kMetadataFormat]
        ];
    } else if (metadata[kMetadataFormat] instanceof Object) {
        return Object.keys(metadata[kMetadataFormat]).filter((key)=>{
            const format10 = metadata[kMetadataFormat][key];
            return format10 !== null && format10 !== false;
        });
    } else {
        return [];
    }
}
function isQuartoMetadata(key) {
    return kRenderDefaultsKeys.includes(key) || kExecuteDefaultsKeys.includes(key) || kPandocDefaultsKeys.includes(key) || kLanguageDefaultsKeys.includes(key);
}
function isIncludeMetadata(key) {
    return [
        kHeaderIncludes,
        kIncludeBefore,
        kIncludeAfter
    ].includes(key);
}
function metadataAsFormat(metadata) {
    const typedFormat = {
        render: {},
        execute: {},
        pandoc: {},
        language: {},
        metadata: {}
    };
    const format11 = typedFormat;
    Object.keys(metadata).forEach((key)=>{
        if ([
            kRenderDefaults,
            kExecuteDefaults,
            kPandocDefaults,
            kLanguageDefaults,
            kPandocMetadata, 
        ].includes(key)) {
            if (typeof metadata[key] == "boolean") {
                if (key === kExecuteDefaults) {
                    format11[key] = format11[key] || {};
                    format11[kExecuteDefaults][kExecuteEnabled] = metadata[key];
                }
            } else {
                format11[key] = {
                    ...format11[key],
                    ...metadata[key]
                };
            }
        } else {
            if (kRenderDefaultsKeys.includes(key)) {
                format11.render[key] = metadata[key];
            } else if (kExecuteDefaultsKeys.includes(key)) {
                format11.execute[key] = metadata[key];
            } else if (kPandocDefaultsKeys.includes(key)) {
                format11.pandoc[key] = metadata[key];
            } else if (kLanguageDefaultsKeys.includes(key)) {
                format11.language[key] = metadata[key];
            } else {
                format11.metadata[key] = metadata[key];
            }
        }
    });
    return typedFormat;
}
function metadataGetDeep(metadata, property1) {
    let values9 = [];
    __VIRTUAL_FILE145(metadata, (value, key)=>{
        if (key === property1) {
            values9.push(value);
        } else if (__VIRTUAL_FILE18(value)) {
            values9 = values9.concat(metadataGetDeep(value, property1));
        }
    });
    return values9;
}
const kUnmergeableKeys = [
    kTblColwidths
];
function mergeFormatMetadata(config, ...configs) {
    config = cloneDeep1(config);
    configs = cloneDeep1(configs);
    return __VIRTUAL_FILE154(config, ...configs, (objValue, srcValue, key)=>{
        if (kUnmergeableKeys.includes(key)) {
            return srcValue;
        } else {
            return mergeArrayCustomizer(objValue, srcValue);
        }
    });
}
const kStdOut = "-";
function parseRenderFlags(args) {
    const flags = {};
    const argsStack = [
        ...args
    ];
    let arg = argsStack.shift();
    while(arg !== undefined){
        switch(arg){
            case "-t":
            case "--to":
                arg = argsStack.shift();
                if (arg && !arg.startsWith("-")) {
                    flags.to = arg;
                }
                break;
            case "-o":
            case "--output":
                arg = argsStack.shift();
                if (!arg || arg.startsWith("-")) {
                    flags.output = kStdOut;
                } else {
                    flags.output = arg;
                }
                break;
            case "--output-dir":
                arg = argsStack.shift();
                flags.outputDir = arg;
                break;
            case "--self-contained":
                flags[kSelfContained] = true;
                arg = argsStack.shift();
                break;
            case "--pdf-engine":
                arg = argsStack.shift();
                flags.pdfEngine = arg;
                break;
            case "--pdf-engine-opt":
                arg = argsStack.shift();
                if (arg) {
                    flags.pdfEngineOpts = flags.pdfEngineOpts || [];
                    flags.pdfEngineOpts.push(arg);
                }
                break;
            case "--latex-makeindex-opt":
                arg = argsStack.shift();
                if (arg) {
                    flags.makeIndexOpts = flags.makeIndexOpts || [];
                    flags.makeIndexOpts.push(arg);
                }
                break;
            case "--latex-tlmgr-opt":
                arg = argsStack.shift();
                if (arg) {
                    flags.tlmgrOpts = flags.tlmgrOpts || [];
                    flags.tlmgrOpts.push(arg);
                }
                break;
            case "--natbib":
                arg = argsStack.shift();
                flags.natbib = true;
                break;
            case "--biblatex":
                arg = argsStack.shift();
                flags.biblatex = true;
                break;
            case `--${kToc}`:
            case `--${kTableOfContents}`:
                arg = argsStack.shift();
                flags.toc = true;
                break;
            case "--listings":
                arg = argsStack.shift();
                flags[kListings] = true;
                break;
            case "--number-sections":
                arg = argsStack.shift();
                flags[kNumberSections] = true;
                break;
            case "--number-offset":
                arg = argsStack.shift();
                flags[kNumberSections] = true;
                flags[kNumberOffset] = parseNumbers("--number-offset", arg);
                break;
            case "--top-level-division":
                arg = argsStack.shift();
                flags[kTopLevelDivision] = arg;
                break;
            case "--shift-heading-level-by":
                arg = argsStack.shift();
                flags[kShiftHeadingLevelBy] = arg;
                break;
            case "--include-in-header":
            case "--include-before-body":
            case "--include-after-body":
                {
                    const include1 = arg.replace("^--", "");
                    const includeFlags = flags;
                    includeFlags[include1] = includeFlags[include1] || [];
                    arg = argsStack.shift();
                    includeFlags[include1].push(arg);
                    break;
                }
            case "--mathjax":
                flags.mathjax = true;
                arg = argsStack.shift();
                break;
            case "--katex":
                flags.katex = true;
                arg = argsStack.shift();
                break;
            case "--mathml":
                flags.mathml = true;
                arg = argsStack.shift();
                break;
            case "--gladtex":
                flags.gladtex = true;
                arg = argsStack.shift();
                break;
            case "--webtex":
                flags.webtex = true;
                arg = argsStack.shift();
                break;
            case "--execute":
                flags.execute = true;
                arg = argsStack.shift();
                break;
            case "--no-execute":
                flags.execute = false;
                arg = argsStack.shift();
                break;
            case "--execute-params":
                arg = argsStack.shift();
                flags.paramsFile = arg;
                break;
            case "--execute-dir":
                arg = argsStack.shift();
                flags.executeDir = arg;
                break;
            case "--execute-daemon":
                arg = argsStack.shift();
                flags.executeDaemon = parseInt(arg, 10);
                if (isNaN(flags.executeDaemon)) {
                    delete flags.executeDaemon;
                }
                break;
            case "--no-execute-daemon":
                arg = argsStack.shift();
                flags.executeDaemon = 0;
                break;
            case "--execute-daemon-restart":
                arg = argsStack.shift();
                flags.executeDaemonRestart = true;
                break;
            case "--execute-debug":
                arg = argsStack.shift();
                flags.executeDebug = true;
                break;
            case "--use-freezer":
                arg = argsStack.shift();
                flags.useFreezer = true;
                break;
            case "--cache":
                arg = argsStack.shift();
                flags.executeCache = true;
                break;
            case "--no-cache":
                arg = argsStack.shift();
                flags.executeCache = false;
                break;
            case "--cache-refresh":
                arg = argsStack.shift();
                flags.executeCache = "refresh";
                break;
            case "--clean":
                arg = argsStack.shift();
                flags.clean = true;
                break;
            case "--no-clean":
                arg = argsStack.shift();
                flags.clean = false;
                break;
            case "--debug":
                flags.debug = true;
                arg = argsStack.shift();
                break;
            case "-P":
            case "--execute-param":
                arg = argsStack.shift();
                if (arg) {
                    const param = parseMetadataFlagValue(arg);
                    if (param) {
                        if (param.value !== undefined) {
                            flags.params = flags.params || {};
                            flags.params[param.name] = param.value;
                        }
                    }
                }
                break;
            case "-M":
            case "--metadata":
                arg = argsStack.shift();
                if (arg) {
                    const metadata = parseMetadataFlagValue(arg);
                    if (metadata) {
                        if (metadata.value !== undefined) {
                            if (isQuartoMetadata(metadata.name)) {
                                flags.metadata = flags.metadata || {};
                                flags.metadata[metadata.name] = metadata.value;
                            } else {
                                flags.pandocMetadata = flags.pandocMetadata || {};
                                flags.pandocMetadata[metadata.name] = metadata.value;
                            }
                        }
                    }
                }
                break;
            case "--metadata-file":
                arg = argsStack.shift();
                if (arg) {
                    if (existsSync(arg)) {
                        const metadata = readYamlFromMarkdownFile(arg);
                        flags.metadata = {
                            ...flags.metadata,
                            ...metadata
                        };
                    }
                }
                break;
            case "--reference-location":
                arg = argsStack.shift();
                if (arg) {
                    flags[kReferenceLocation] = arg;
                }
                break;
            default:
                arg = argsStack.shift();
                break;
        }
    }
    if (flags.clean === undefined) {
        flags.clean = true;
    }
    return flags;
}
function havePandocArg(pandocArgs, arg) {
    return pandocArgs.indexOf(arg) !== -1;
}
function replacePandocArg(pandocArgs, arg, value) {
    const newArgs = [
        ...pandocArgs
    ];
    const argIndex = pandocArgs.indexOf(arg);
    if (argIndex !== -1) {
        newArgs[argIndex + 1] = value;
    } else {
        newArgs.push(arg);
        newArgs.push(value);
    }
    return newArgs;
}
function replacePandocOutputArg(pandocArgs, output) {
    if (havePandocArg(pandocArgs, "--output")) {
        return replacePandocArg(pandocArgs, "--output", output);
    } else if (havePandocArg(pandocArgs, "-o")) {
        return replacePandocArg(pandocArgs, "-o", output);
    } else {
        return pandocArgs;
    }
}
function fixupPandocArgs(pandocArgs, flags) {
    pandocArgs = pandocArgs.reduce((args, arg, index)=>{
        args.push(arg);
        if (flags.output === kStdOut && pandocArgs[index + 1] !== kStdOut && (arg === "-o" || arg === "--output")) {
            args.push(kStdOut);
        }
        return args;
    }, new Array());
    const removeArgs = new Map();
    removeArgs.set("--output-dir", true);
    removeArgs.set("--execute", false);
    removeArgs.set("--no-execute", false);
    removeArgs.set("-P", true);
    removeArgs.set("--execute-param", true);
    removeArgs.set("--execute-params", true);
    removeArgs.set("--execute-dir", true);
    removeArgs.set("--execute-daemon", true);
    removeArgs.set("--no-execute-daemon", false);
    removeArgs.set("--execute-daemon-restart", false);
    removeArgs.set("--execute-debug", false);
    removeArgs.set("--use-freezer", false);
    removeArgs.set("--cache", false);
    removeArgs.set("--no-cache", false);
    removeArgs.set("--cache-refresh", false);
    removeArgs.set("--clean", false);
    removeArgs.set("--no-clean", false);
    removeArgs.set("--debug", false);
    removeArgs.set("--metadata-file", true);
    removeArgs.set("--latex-makeindex-opt", true);
    removeArgs.set("--latex-tlmgr-opt", true);
    removeArgs.set("--log", true);
    removeArgs.set("--l", true);
    removeArgs.set("--log-level", true);
    removeArgs.set("--ll", true);
    removeArgs.set("--log-format", true);
    removeArgs.set("--lf", true);
    removeArgs.set("--quiet", false);
    removeArgs.set("--q", false);
    pandocArgs = removePandocArgs(pandocArgs, removeArgs);
    return removeQuartoMetadataFlags(pandocArgs);
}
function removePandocArgs(pandocArgs, removeArgs) {
    let removeNext = false;
    return pandocArgs.reduce((args, arg)=>{
        if (!removeArgs.has(arg)) {
            if (!removeNext) {
                args.push(arg);
            }
            removeNext = false;
        } else {
            removeNext = removeArgs.get(arg);
        }
        return args;
    }, new Array());
}
function removePandocToArg(args) {
    const removeArgs = new Map();
    removeArgs.set("--to", true);
    removeArgs.set("-t", true);
    return removePandocArgs(args, removeArgs);
}
function removeQuartoMetadataFlags(pandocArgs) {
    const args = [];
    for(let i49 = 0; i49 < pandocArgs.length; i49++){
        const arg = pandocArgs[i49];
        if (arg === "--metadata" || arg === "-M") {
            const flagValue = parseMetadataFlagValue(pandocArgs[i49 + 1] || "");
            if (flagValue !== undefined && isQuartoMetadata(flagValue.name)) {
                i49++;
            } else {
                args.push(arg);
            }
        } else {
            args.push(arg);
        }
    }
    return args;
}
function parseMetadataFlagValue(arg) {
    const match = arg.match(/^([^=:]+)[=:](.*)$/);
    if (match) {
        return {
            name: match[1],
            value: readYamlFromString(match[2])
        };
    }
    return undefined;
}
function resolveParams(params, paramsFile) {
    if (params || paramsFile) {
        params = params || {};
        if (paramsFile) {
            params = mergeConfigs(readYaml(paramsFile), params);
        }
        return params;
    } else {
        return undefined;
    }
}
function parseNumbers(flag, value) {
    if (value) {
        const numbers = value.split(/,/).map((number2)=>parseInt(number2.trim(), 10)
        ).filter((number3)=>!isNaN(number3)
        );
        if (numbers.length > 0) {
            return numbers;
        }
    }
    throw new Error(`Invalid value for ${flag} (should be a comma separated list of numbers)`);
}
const kDependencies = "dependencies";
const kSassBundles = "sass-bundles";
const kHtmlPostprocessors = "html-postprocessors";
const kHtmlFinalizers = "html-finalizers";
const kTemplatePatches = "template-patches";
const kBodyEnvelope = "body-envelope";
const kTextHighlightingMode = "text-highlighting-mode";
const kQuartoCssVariables = "css-variables";
const kMarkdownAfterBody = "render-after-body";
const kTextHtml = "text/html";
const kTextMarkdown = "text/markdown";
const kTextLatex = "text/latex";
const kTextPlain = "text/plain";
const kImagePng = "image/png";
const kImageJpeg = "image/jpeg";
const kImageSvg = "image/svg+xml";
const kApplicationPdf = "application/pdf";
const kApplicationJavascript = "application/javascript";
const kApplicationJupyterWidgetState = "application/vnd.jupyter.widget-state+json";
const kApplicationJupyterWidgetView = "application/vnd.jupyter.widget-view+json";
const kRestructuredText = "text/restructuredtext";
const kApplicationRtf = "application/rtf";
function extensionForMimeImageType(mimeType) {
    switch(mimeType){
        case kImagePng:
            return "png";
        case kImageJpeg:
            return "jpeg";
        case kImageSvg:
            return "svg";
        case kApplicationPdf:
            return "pdf";
        default:
            return "bin";
    }
}
function contentType(path56) {
    return MEDIA_TYPES[extname2(path56.toLowerCase())];
}
function isPdfContent(path57) {
    return path57 && contentType(path57) === kApplicationPdf;
}
function isHtmlContent(path58) {
    return path58 && contentType(path58) === kTextHtml;
}
const MEDIA_TYPES = {
    ".md": kTextMarkdown,
    ".html": kTextHtml,
    ".htm": kTextHtml,
    ".json": "application/json",
    ".map": "application/json",
    ".txt": kTextPlain,
    ".ts": "text/typescript",
    ".tsx": "text/tsx",
    ".js": "application/javascript",
    ".jsx": "text/jsx",
    ".gz": "application/gzip",
    ".css": "text/css",
    ".wasm": "application/wasm",
    ".mjs": "application/javascript",
    ".svg": kImageSvg,
    ".png": kImagePng,
    ".jpg": kImageJpeg,
    ".jpeg": kImageJpeg,
    ".pdf": kApplicationPdf,
    ".gif": "image/gif",
    ".wav": "audio/wav",
    ".mp4": "video/mp4",
    ".woff": "application/font-woff",
    ".ttf": "application/font-ttf",
    ".eot": "application/vnd.ms-fontobject",
    ".otf": "application/font-otf"
};
function deferred() {
    let methods;
    let state38 = "pending";
    const promise = new Promise((resolve3, reject)=>{
        methods = {
            async resolve (value) {
                await value;
                state38 = "fulfilled";
                resolve3(value);
            },
            reject (reason) {
                state38 = "rejected";
                reject(reason);
            }
        };
    });
    Object.defineProperty(promise, "state", {
        get: ()=>state38
    });
    return Object.assign(promise, methods);
}
class MuxAsyncIterator {
    iteratorCount = 0;
    yields = [];
    throws = [];
    signal = deferred();
    add(iterable) {
        ++this.iteratorCount;
        this.callIteratorNext(iterable[Symbol.asyncIterator]());
    }
    async callIteratorNext(iterator) {
        try {
            const { value , done  } = await iterator.next();
            if (done) {
                --this.iteratorCount;
            } else {
                this.yields.push({
                    iterator,
                    value
                });
            }
        } catch (e) {
            this.throws.push(e);
        }
        this.signal.resolve();
    }
    async *iterate() {
        while(this.iteratorCount > 0){
            await this.signal;
            for(let i50 = 0; i50 < this.yields.length; i50++){
                const { iterator , value  } = this.yields[i50];
                yield value;
                this.callIteratorNext(iterator);
            }
            if (this.throws.length) {
                for (const e of this.throws){
                    throw e;
                }
                this.throws.length = 0;
            }
            this.yields.length = 0;
            this.signal = deferred();
        }
    }
    [Symbol.asyncIterator]() {
        return this.iterate();
    }
}
function pooledMap(poolLimit, array, iteratorFn) {
    const res = new TransformStream({
        async transform (p, controller) {
            controller.enqueue(await p);
        }
    });
    (async ()=>{
        const writer = res.writable.getWriter();
        const executing = [];
        try {
            for await (const item of array){
                const p = Promise.resolve().then(()=>iteratorFn(item)
                );
                p.then((v)=>writer.write(Promise.resolve(v))
                ).catch(()=>{});
                const e = p.then(()=>executing.splice(executing.indexOf(e), 1)
                );
                executing.push(e);
                if (executing.length >= poolLimit) {
                    await Promise.race(executing);
                }
            }
            await Promise.all(executing);
            writer.close();
        } catch  {
            const errors3 = [];
            for (const result of (await Promise.allSettled(executing))){
                if (result.status == "rejected") {
                    errors3.push(result.reason);
                }
            }
            writer.write(Promise.reject(new AggregateError(errors3, "Threw while mapping."))).catch(()=>{});
        }
    })();
    return res.readable[Symbol.asyncIterator]();
}
const DEFAULT_BUFFER_SIZE = 32 * 1024;
function readAllSync(r) {
    const buf = new Buffer();
    buf.readFromSync(r);
    return buf.bytes();
}
async function writeAll(w, arr) {
    let nwritten = 0;
    while(nwritten < arr.length){
        nwritten += await w.write(arr.subarray(nwritten));
    }
}
function writeAllSync(w, arr) {
    let nwritten = 0;
    while(nwritten < arr.length){
        nwritten += w.writeSync(arr.subarray(nwritten));
    }
}
async function* iterateReader(r, options) {
    const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
    const b = new Uint8Array(bufSize);
    while(true){
        const result = await r.read(b);
        if (result === null) {
            break;
        }
        yield b.subarray(0, result);
    }
}
"\r".charCodeAt(0);
"\n".charCodeAt(0);
async function ensureValidCopy(src, dest, options) {
    let destStat;
    try {
        destStat = await Deno.lstat(dest);
    } catch (err) {
        if (err instanceof Deno.errors.NotFound) {
            return;
        }
        throw err;
    }
    if (options.isFolder && !destStat.isDirectory) {
        throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);
    }
    if (!options.overwrite) {
        throw new Error(`'${dest}' already exists.`);
    }
    return destStat;
}
function ensureValidCopySync(src, dest, options) {
    let destStat;
    try {
        destStat = Deno.lstatSync(dest);
    } catch (err) {
        if (err instanceof Deno.errors.NotFound) {
            return;
        }
        throw err;
    }
    if (options.isFolder && !destStat.isDirectory) {
        throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`);
    }
    if (!options.overwrite) {
        throw new Error(`'${dest}' already exists.`);
    }
    return destStat;
}
async function copyFile(src, dest, options) {
    await ensureValidCopy(src, dest, options);
    await Deno.copyFile(src, dest);
    if (options.preserveTimestamps) {
        const statInfo = await Deno.stat(src);
        assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`);
        assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
        await Deno.utime(dest, statInfo.atime, statInfo.mtime);
    }
}
function copyFileSync(src, dest, options) {
    ensureValidCopySync(src, dest, options);
    Deno.copyFileSync(src, dest);
    if (options.preserveTimestamps) {
        const statInfo = Deno.statSync(src);
        assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`);
        assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
        Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
    }
}
async function copySymLink(src, dest, options) {
    await ensureValidCopy(src, dest, options);
    const originSrcFilePath = await Deno.readLink(src);
    const type = getFileInfoType(await Deno.lstat(src));
    if (isWindows) {
        await Deno.symlink(originSrcFilePath, dest, {
            type: type === "dir" ? "dir" : "file"
        });
    } else {
        await Deno.symlink(originSrcFilePath, dest);
    }
    if (options.preserveTimestamps) {
        const statInfo = await Deno.lstat(src);
        assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`);
        assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
        await Deno.utime(dest, statInfo.atime, statInfo.mtime);
    }
}
function copySymlinkSync(src, dest, options) {
    ensureValidCopySync(src, dest, options);
    const originSrcFilePath = Deno.readLinkSync(src);
    const type = getFileInfoType(Deno.lstatSync(src));
    if (isWindows) {
        Deno.symlinkSync(originSrcFilePath, dest, {
            type: type === "dir" ? "dir" : "file"
        });
    } else {
        Deno.symlinkSync(originSrcFilePath, dest);
    }
    if (options.preserveTimestamps) {
        const statInfo = Deno.lstatSync(src);
        assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`);
        assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
        Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
    }
}
async function copyDir(src, dest, options) {
    const destStat = await ensureValidCopy(src, dest, {
        ...options,
        isFolder: true
    });
    if (!destStat) {
        await ensureDir(dest);
    }
    if (options.preserveTimestamps) {
        const srcStatInfo = await Deno.stat(src);
        assert(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`);
        assert(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
        await Deno.utime(dest, srcStatInfo.atime, srcStatInfo.mtime);
    }
    for await (const entry of Deno.readDir(src)){
        const srcPath = join3(src, entry.name);
        const destPath = join3(dest, basename2(srcPath));
        if (entry.isSymlink) {
            await copySymLink(srcPath, destPath, options);
        } else if (entry.isDirectory) {
            await copyDir(srcPath, destPath, options);
        } else if (entry.isFile) {
            await copyFile(srcPath, destPath, options);
        }
    }
}
function copyDirSync(src, dest, options) {
    const destStat = ensureValidCopySync(src, dest, {
        ...options,
        isFolder: true
    });
    if (!destStat) {
        ensureDirSync(dest);
    }
    if (options.preserveTimestamps) {
        const srcStatInfo = Deno.statSync(src);
        assert(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`);
        assert(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`);
        Deno.utimeSync(dest, srcStatInfo.atime, srcStatInfo.mtime);
    }
    for (const entry of Deno.readDirSync(src)){
        assert(entry.name != null, "file.name must be set");
        const srcPath = join3(src, entry.name);
        const destPath = join3(dest, basename2(srcPath));
        if (entry.isSymlink) {
            copySymlinkSync(srcPath, destPath, options);
        } else if (entry.isDirectory) {
            copyDirSync(srcPath, destPath, options);
        } else if (entry.isFile) {
            copyFileSync(srcPath, destPath, options);
        }
    }
}
async function copy1(src, dest, options = {}) {
    src = resolve2(src);
    dest = resolve2(dest);
    if (src === dest) {
        throw new Error("Source and destination cannot be the same.");
    }
    const srcStat = await Deno.lstat(src);
    if (srcStat.isDirectory && isSubdir(src, dest)) {
        throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`);
    }
    if (srcStat.isSymlink) {
        await copySymLink(src, dest, options);
    } else if (srcStat.isDirectory) {
        await copyDir(src, dest, options);
    } else if (srcStat.isFile) {
        await copyFile(src, dest, options);
    }
}
function copySync(src, dest, options = {}) {
    src = resolve2(src);
    dest = resolve2(dest);
    if (src === dest) {
        throw new Error("Source and destination cannot be the same.");
    }
    const srcStat = Deno.lstatSync(src);
    if (srcStat.isDirectory && isSubdir(src, dest)) {
        throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`);
    }
    if (srcStat.isSymlink) {
        copySymlinkSync(src, dest, options);
    } else if (srcStat.isDirectory) {
        copyDirSync(src, dest, options);
    } else if (srcStat.isFile) {
        copyFileSync(src, dest, options);
    }
}
const kSkipHidden = /[/\\][\.]/;
async function execProcess(options, stdin, mergeOutput, stderrFilter) {
    try {
        const process = Deno.run({
            ...options,
            stdin: stdin !== undefined ? "piped" : options.stdin,
            stdout: typeof options.stdout === "number" ? options.stdout : "piped",
            stderr: typeof options.stderr === "number" ? options.stderr : "piped"
        });
        if (stdin !== undefined) {
            if (!process.stdin) {
                throw new Error("Process stdin not available");
            }
            const buffer = new TextEncoder().encode(stdin);
            let offset = 0;
            while(offset < buffer.length){
                const end = Math.min(offset + 4096, buffer.length);
                const window = buffer.subarray(offset, end);
                const written = await process.stdin.write(window);
                offset += written;
            }
            process.stdin.close();
        }
        let stdoutText = "";
        let stderrText = "";
        if (mergeOutput) {
            const multiplexIterator = new MuxAsyncIterator();
            const addStream = (stream, filter2)=>{
                if (stream !== null) {
                    const streamIter = filter2 ? filteredAsyncIterator(iterateReader(stream), filter2) : iterateReader(stream);
                    multiplexIterator.add(streamIter);
                }
            };
            addStream(process.stdout);
            addStream(process.stderr, stderrFilter);
            const allOutput = await processOutput(multiplexIterator, mergeOutput === "stderr>stdout" ? options.stdout : options.stderr);
            if (mergeOutput === "stderr>stdout") {
                stdoutText = allOutput;
            } else {
                stderrText = allOutput;
            }
            const closeStream = (stream)=>{
                if (stream) {
                    stream.close();
                }
            };
            closeStream(process.stdout);
            closeStream(process.stderr);
        } else {
            if (process.stdout !== null) {
                stdoutText = await processOutput(iterateReader(process.stdout), options.stdout);
                process.stdout.close();
            }
            if (process.stderr != null) {
                const iterator = stderrFilter ? filteredAsyncIterator(iterateReader(process.stderr), stderrFilter) : iterateReader(process.stderr);
                stderrText = await processOutput(iterator, options.stderr);
                process.stderr.close();
            }
        }
        const status = await process.status();
        process.close();
        return {
            success: status.success,
            code: status.code,
            stdout: stdoutText,
            stderr: stderrText
        };
    } catch (e) {
        throw new Error(`Error executing '${options.cmd[0]}': ${e.message}`);
    }
}
function removeIfExists(file) {
    if (existsSync(file)) {
        Deno.removeSync(file, {
            recursive: true
        });
    }
}
function removeIfEmptyDir(dir) {
    if (existsSync(dir)) {
        let empty2 = true;
        for (const _entry of Deno.readDirSync(dir)){
            empty2 = false;
            break;
        }
        if (empty2) {
            Deno.removeSync(dir, {
                recursive: true
            });
        }
    }
}
function isModifiedAfter(file, otherFile) {
    if (!existsSync(file)) {
        throw new Error(`${file} does not exist`);
    }
    if (!existsSync(otherFile)) {
        return true;
    }
    const fileInfo = Deno.statSync(file);
    const otherfileInfo = Deno.statSync(otherFile);
    if (fileInfo.mtime === null || otherfileInfo.mtime === null) {
        return true;
    } else {
        return fileInfo.mtime > otherfileInfo.mtime;
    }
}
function dirAndStem(file) {
    return [
        dirname2(file),
        basename2(file, extname2(file)), 
    ];
}
function expandPath(path59) {
    if (path59 === "~") {
        return getenv("HOME", "~");
    } else {
        return path59.replace(/^~\//, getenv("HOME", "~") + "/");
    }
}
function safeExistsSync(path60) {
    try {
        return existsSync(path60);
    } catch  {
        return false;
    }
}
async function which(cmd) {
    const args = Deno.build.os === "windows" ? [
        "CMD",
        "/C",
        "where",
        cmd
    ] : [
        "which",
        cmd
    ];
    const result = await execProcess({
        cmd: args,
        stderr: "piped",
        stdout: "piped"
    });
    if (result.code === 0) {
        return result.stdout?.trim();
    } else {
        return undefined;
    }
}
function filterPaths(root4, paths, globs) {
    const expandGlobs = (targetGlobs)=>{
        const expanded = [];
        for (const glob of targetGlobs){
            const regex = globToRegExp(`${root4}/${glob}`);
            const matchingFiles = paths.filter((path61)=>{
                return regex.test(path61);
            });
            expanded.push(...matchingFiles);
        }
        return __VIRTUAL_FILE181(expanded);
    };
    return resolveGlobs(root4, globs, expandGlobs);
}
function resolvePathGlobs(root5, globs, exclude) {
    const expandGlobs = (targetGlobs)=>{
        const expanded = [];
        for (const glob of targetGlobs){
            for (const file of expandGlobSync(glob, {
                root: root5,
                exclude,
                includeDirs: true,
                extended: true,
                globstar: true
            })){
                expanded.push(file.path);
            }
        }
        return __VIRTUAL_FILE181(expanded);
    };
    return resolveGlobs(root5, globs, expandGlobs);
}
function pathWithForwardSlashes(path62) {
    return path62.replace(/\\/g, "/");
}
function copyMinimal(srcDir, destDir, skip, filter3) {
    skip = [
        ...skip || [],
        /\.DS_Store/
    ];
    const srcFiles = [];
    for (const walk1 of walkSync(srcDir, {
        includeDirs: false,
        followSymlinks: false,
        skip
    })){
        const srcFile = walk1.path;
        if (filter3 && !filter3(srcFile)) {
            continue;
        }
        srcFiles.push(srcFile);
    }
    for (const srcFile of srcFiles){
        if (!existsSync(srcFile)) {
            continue;
        }
        const destFile = join3(destDir, relative2(srcDir, srcFile));
        copyFileIfNewer(srcFile, destFile);
    }
}
function copyFileIfNewer(srcFile, destFile) {
    ensureDirSync(dirname2(destFile));
    if (existsSync(destFile)) {
        const srcInfo = Deno.statSync(srcFile);
        const destInfo = Deno.statSync(destFile);
        if (!srcInfo.mtime || !destInfo.mtime || destInfo.mtime < srcInfo.mtime) {
            copySync(srcFile, destFile, {
                overwrite: true,
                preserveTimestamps: true
            });
        }
    } else {
        copySync(srcFile, destFile, {
            overwrite: true,
            preserveTimestamps: true
        });
    }
}
function resolveGlobs(root6, globs, expandGlobs) {
    const includeGlobs = [];
    const excludeGlobs = [];
    const asFullGlob = (glob)=>{
        if (glob.startsWith("\\!")) {
            glob = glob.slice(1);
        }
        if (glob.endsWith("/")) {
            glob = glob + "**/*";
        } else {
            const fullPath = join3(root6, glob);
            try {
                if (Deno.statSync(fullPath).isDirectory) {
                    glob = glob + "/**/*";
                }
            } catch  {}
        }
        if (!glob.startsWith("/")) {
            return "**/" + glob;
        } else {
            return join3(root6, glob.slice(1));
        }
    };
    for (const glob1 of globs){
        if (glob1.startsWith("!")) {
            excludeGlobs.push(asFullGlob(glob1.slice(1)));
        } else {
            includeGlobs.push(asFullGlob(glob1));
        }
    }
    const includeFiles = expandGlobs(includeGlobs);
    const excludeFiles = expandGlobs(excludeGlobs);
    return {
        include: includeFiles,
        exclude: excludeFiles
    };
}
function processSuccessResult() {
    return {
        success: true,
        code: 0
    };
}
function filteredAsyncIterator(iterator, filter4) {
    const encoder = new TextEncoder();
    const decoder = new TextDecoder();
    return pooledMap(1, iterator, (data43)=>{
        return Promise.resolve(encoder.encode(filter4(decoder.decode(data43))));
    });
}
async function processOutput(iterator, output) {
    const decoder = new TextDecoder();
    let outputText = "";
    for await (const chunk of iterator){
        if (output === "inherit" || output === undefined) {
            info(decoder.decode(chunk), {
                newline: false
            });
        }
        const text = decoder.decode(chunk);
        outputText += text;
    }
    return outputText;
}
async function safeWindowsExec(program, args, fnExec) {
    const tempFile = Deno.makeTempFileSync({
        prefix: "quarto-safe-exec",
        suffix: ".bat"
    });
    try {
        Deno.writeTextFileSync(tempFile, [
            program,
            ...args
        ].join(" ") + "\n");
        return await fnExec([
            "cmd",
            "/c",
            tempFile
        ]);
    } finally{
        removeIfExists(tempFile);
    }
}
function isAbsoluteRef(href) {
    return /^(?:http|https)\:\/\/.+/.test(href);
}
function isFileRef(href) {
    return !/^\w+:/.test(href) && !href.startsWith("#");
}
function httpFileRequestHandler(options) {
    async function serveFile(filePath, req) {
        let fileContents;
        if (options.onFile) {
            fileContents = await options.onFile(filePath, req);
        }
        if (!fileContents) {
            fileContents = Deno.readFileSync(filePath);
        }
        return httpContentResponse(fileContents, contentType(filePath));
    }
    function serveFallback(req, e, fsPath) {
        const encoder = new TextEncoder();
        if (e instanceof URIError) {
            return Promise.resolve(new Response(encoder.encode("BadRequest"), {
                status: 400
            }));
        } else if (e instanceof Deno.errors.NotFound) {
            const url = normalizeURL(req.url);
            const handle404 = options.on404 ? options.on404(url, req) : {
                print: true,
                body: encoder.encode("Not Found")
            };
            handle404.print = handle404.print && !!options.printUrls && (!fsPath || basename2(fsPath) !== "favicon.ico" && extname2(fsPath) !== ".map");
            if (handle404.print) {
                printUrl(url, false);
            }
            return Promise.resolve(new Response(handle404.body, {
                status: 404,
                headers: {
                    "Content-Type": kTextHtml
                }
            }));
        } else {
            error(`500 (Internal Error): ${e.message}`, {
                bold: true
            });
            return Promise.resolve(new Response(encoder.encode("Internal server error"), {
                status: 500
            }));
        }
    }
    return async (req)=>{
        if (options.onRequest) {
            const response = await options.onRequest(req);
            if (response) {
                return response;
            }
        }
        let response;
        let fsPath;
        try {
            const baseDir = pathWithForwardSlashes(options.baseDir);
            const normalizedUrl = normalizeURL(req.url);
            fsPath = pathWithForwardSlashes(baseDir + normalizedUrl);
            if (fsPath.indexOf(baseDir) !== 0) {
                fsPath = baseDir;
            }
            const fileInfo = existsSync(fsPath) ? Deno.statSync(fsPath) : undefined;
            if (fileInfo && fileInfo.isDirectory) {
                fsPath = join3(fsPath, options.defaultFile || "index.html");
            }
            if (fileInfo?.isDirectory && !normalizedUrl.endsWith("/")) {
                response = serveRedirect(normalizedUrl + "/");
            } else {
                response = await serveFile(fsPath, req);
                if (options.printUrls === "all") {
                    printUrl(normalizedUrl);
                }
            }
        } catch (e) {
            response = await serveFallback(req, e, fsPath);
        }
        return response;
    };
}
function httpContentResponse(content, contentType1) {
    if (typeof content === "string") {
        content = new TextEncoder().encode(content);
    }
    const headers = new Headers();
    headers.set("Content-Length", content.byteLength.toString());
    if (contentType1) {
        headers.set("Content-Type", contentType1);
    }
    headers.set("Cache-Control", "no-store, max-age=0");
    return new Response(content, {
        status: 200,
        headers
    });
}
function normalizeURL(url) {
    let normalizedUrl = url;
    try {
        normalizedUrl = decodeURI(normalizedUrl);
    } catch (e) {
        if (!(e instanceof URIError)) {
            throw e;
        }
    }
    try {
        const absoluteURI = new URL(normalizedUrl);
        normalizedUrl = decodeURI(absoluteURI.pathname);
    } catch (e1) {
        if (!(e1 instanceof TypeError)) {
            throw e1;
        }
    }
    if (normalizedUrl[0] !== "/") {
        throw new URIError("The request URI is malformed.");
    }
    normalizedUrl = posix.normalize(normalizedUrl);
    const startOfParams = normalizedUrl.indexOf("?");
    return startOfParams > -1 ? normalizedUrl.slice(0, startOfParams) : normalizedUrl;
}
function maybeDisplaySocketError(e) {
    if (!(e instanceof Deno.errors.BrokenPipe) && !(e instanceof Deno.errors.ConnectionAborted) && !(e instanceof Deno.errors.ConnectionReset) && !(e instanceof DOMException)) {
        logError(e);
    }
}
function serveRedirect(url) {
    const headers = new Headers();
    headers.set("Location", url);
    return new Response(null, {
        status: 301,
        headers
    });
}
function printUrl(url, found = true) {
    const format12 = !found ? red : undefined;
    const urlDisplay = url + (found ? "" : " (404: Not Found)");
    if (isHtmlContent(url) || url.endsWith("/") || extname2(url) === "") {
        info(`GET: ${urlDisplay}`, {
            bold: false,
            format: format12 || green
        });
    } else if (!found) {
        info(urlDisplay, {
            dim: found,
            format: format12,
            indent: 2
        });
    }
}
const kLocalDevelopment = "99.9.9";
const quartoConfig = {
    binPath: ()=>getenv("QUARTO_BIN_PATH")
    ,
    sharePath: ()=>getenv("QUARTO_SHARE_PATH")
    ,
    isDebug: ()=>getenv("QUARTO_DEBUG", "false") === "true"
    ,
    version: ()=>{
        const versionPath = join3(getenv("QUARTO_SHARE_PATH"), "version");
        if (existsSync(versionPath)) {
            return Deno.readTextFileSync(versionPath);
        } else {
            return kLocalDevelopment;
        }
    }
};
const kHKeyCurrentUser = "HKCU";
const kHKeyLocalMachine = "HKLM";
async function registryReadString(root7, key, value) {
    if (Array.isArray(root7)) {
        for (const r of root7){
            const val = registryReadString(r, key, value);
            if (val !== undefined) {
                return val;
            }
        }
        return undefined;
    }
    const kTypeString = "REG_SZ";
    const cmd = [
        "reg",
        "query",
        `${root7}\\${key}`,
        "/v",
        value, 
    ];
    const result = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "null"
    });
    if (result.success && result.stdout) {
        const typePos = result.stdout?.indexOf(kTypeString);
        if (typePos !== -1) {
            return result.stdout.substring(typePos + kTypeString.length).trim();
        }
    }
    return undefined;
}
function resourcePath(resource) {
    const sharePath = quartoConfig.sharePath();
    if (resource) {
        return join3(sharePath, resource);
    } else {
        return sharePath;
    }
}
function formatResourcePath(format13, resource) {
    return join3(resourcePath("formats"), format13, resource);
}
function binaryPath(binary1) {
    return join3(quartoConfig.binPath(), binary1);
}
function pandocBinaryPath() {
    const quartoPandoc = Deno.env.get("QUARTO_PANDOC");
    if (quartoPandoc) {
        if (!existsSync(quartoPandoc)) {
            warnOnce("Specified QUARTO_PANDOC does not exist, using built in Pandoc");
        }
        if (Deno.statSync(quartoPandoc).isFile) {
            return quartoPandoc;
        } else {
            return join3(quartoPandoc, "pandoc");
        }
    }
    return binaryPath("pandoc");
}
async function rBinaryPath(binary2) {
    const rHome = Deno.env.get("R_HOME");
    if (rHome) {
        return join3(rHome, "bin", binary2);
    }
    const path63 = await which(binary2);
    if (path63) {
        return path63;
    }
    if (Deno.build.os === "windows") {
        const version6 = await registryReadString([
            kHKeyLocalMachine,
            kHKeyCurrentUser
        ], "Software\\R-core\\R", "Current Version");
        if (version6) {
            const installPath = await registryReadString([
                kHKeyLocalMachine,
                kHKeyCurrentUser
            ], `Software\\R-core\\R\\${version6}`, "InstallPath");
            if (installPath) {
                return join3(installPath, "bin", binary2);
            }
        }
        const progFiles = Deno.env.get("programfiles");
        if (progFiles) {
            for (const entry of Deno.readDirSync(progFiles)){
                if (entry.isDirectory && entry.name === "R") {
                    for (const walk2 of walkSync(join3(progFiles, "R"))){
                        if (walk2.isDirectory && walk2.name === "bin") {
                            return join3(walk2.path, binary2);
                        }
                    }
                }
            }
        }
    }
    return binary2;
}
function projectTypeResourcePath(projectType1) {
    return resourcePath(join3("projects", projectType1));
}
const kDarkSuffix = "dark";
const kLightSuffix = "light";
function textHighlightThemePath(theme, style) {
    const names = [
        `${theme}-${style === "dark" ? kDarkSuffix : kLightSuffix}`,
        theme, 
    ];
    const themePath = names.map((name81)=>{
        return resourcePath(join3("pandoc", "highlight-styles", `${name81}.theme`));
    }).find((path64)=>existsSync(path64)
    );
    return themePath;
}
function quartoDataDir(subdir, roaming = false) {
    return quartoDir(userDataDir, subdir, roaming);
}
function quartoCacheDir(subdir) {
    return quartoDir(userCacheDir, subdir);
}
function quartoRuntimeDir(subdir) {
    return quartoDir(userRuntimeDir, subdir);
}
function quartoDir(sourceFn, subdir, roaming) {
    const dir = sourceFn("quarto", roaming);
    const fullDir = subdir ? join3(dir, subdir) : dir;
    ensureDirSync(fullDir);
    return fullDir;
}
function userDataDir(appName, roaming = false) {
    switch(Deno.build.os){
        case "darwin":
            return darwinUserDataDir(appName);
        case "linux":
            return xdgUserDataDir(appName);
        case "windows":
            return windowsUserDataDir(appName, roaming);
    }
}
function userCacheDir(appName) {
    switch(Deno.build.os){
        case "darwin":
            return darwinUserCacheDir(appName);
        case "linux":
            return xdgUserCacheDir(appName);
        case "windows":
            return windowsUserDataDir(appName);
    }
}
function userRuntimeDir(appName) {
    switch(Deno.build.os){
        case "darwin":
            return darwinUserCacheDir(appName);
        case "linux":
            return xdgUserRuntimeDir(appName);
        case "windows":
            return windowsUserDataDir(appName);
    }
}
function darwinUserDataDir(appName) {
    return join3(Deno.env.get("HOME") || "", "Library", "Application Support", appName);
}
function darwinUserCacheDir(appName) {
    return join3(Deno.env.get("HOME") || "", "Library", "Caches", appName);
}
function xdgUserDataDir(appName) {
    const dataHome = Deno.env.get("XDG_DATA_HOME") || join3(Deno.env.get("HOME") || "", ".local", "share");
    return join3(dataHome, appName);
}
function xdgUserCacheDir(appName) {
    const cacheHome = Deno.env.get("XDG_CACHE_HOME") || join3(Deno.env.get("HOME") || "", ".cache");
    return join3(cacheHome, appName);
}
function xdgUserRuntimeDir(appName) {
    const runtimeDir = Deno.env.get("XDG_RUNTIME_DIR");
    if (runtimeDir) {
        return runtimeDir;
    } else {
        return xdgUserDataDir(appName);
    }
}
function windowsUserDataDir(appName, roaming = false) {
    const dir = (roaming ? Deno.env.get("APPDATA") : Deno.env.get("LOCALAPPDATA")) || "";
    return join3(dir, appName);
}
async function dartCompile(input, outputFilePath, temp, loadPaths, compressed) {
    const inputFilePath = temp.createFile({
        suffix: "scss"
    });
    Deno.writeTextFileSync(inputFilePath, input);
    const args = [
        inputFilePath,
        outputFilePath,
        "--style",
        compressed ? "compressed" : "expanded", 
    ];
    if (loadPaths) {
        loadPaths.forEach((loadPath)=>{
            args.push(`--load-path=${loadPath}`);
        });
    }
    await dartCommand(args);
    return outputFilePath;
}
async function dartCommand(args) {
    const command = Deno.build.os === "windows" ? "sass.bat" : "sass";
    const sass = binaryPath(join3("dart-sass", command));
    const cmd = [
        sass,
        ...args, 
    ];
    const result = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "piped"
    });
    if (result.success) {
        return result.stdout;
    } else {
        const errLines = lines(result.stderr || "");
        const errMsg = errLines.slice(0, errLines.length - 2).join("\n");
        throw new Error("Theme file compilation failed:\n\n" + errMsg);
    }
}
var commonjsGlobal1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function createCommonjsModule3(fn, basedir, module) {
    return module = {
        path: basedir,
        exports: {},
        require: function(path65, base4) {
            return commonjsRequire(path65, base4 === void 0 || base4 === null ? module.path : base4);
        }
    }, fn(module, module.exports), module.exports;
}
function commonjsRequire() {
    throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
var md5 = createCommonjsModule3(function(module) {
    (function($) {
        function safeAdd(x, y) {
            var lsw = (x & 65535) + (y & 65535);
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
            return msw << 16 | lsw & 65535;
        }
        function bitRotateLeft(num, cnt) {
            return num << cnt | num >>> 32 - cnt;
        }
        function md5cmn(q, a, b, x, s, t) {
            return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
        }
        function md5ff(a, b, c, d, x, s, t) {
            return md5cmn(b & c | ~b & d, a, b, x, s, t);
        }
        function md5gg(a, b, c, d, x, s, t) {
            return md5cmn(b & d | c & ~d, a, b, x, s, t);
        }
        function md5hh(a, b, c, d, x, s, t) {
            return md5cmn(b ^ c ^ d, a, b, x, s, t);
        }
        function md5ii(a, b, c, d, x, s, t) {
            return md5cmn(c ^ (b | ~d), a, b, x, s, t);
        }
        function binlMD5(x, len2) {
            x[len2 >> 5] |= 128 << len2 % 32;
            x[(len2 + 64 >>> 9 << 4) + 14] = len2;
            var i51;
            var olda;
            var oldb;
            var oldc;
            var oldd;
            var a = 1732584193;
            var b = -271733879;
            var c = -1732584194;
            var d = 271733878;
            for(i51 = 0; i51 < x.length; i51 += 16){
                olda = a;
                oldb = b;
                oldc = c;
                oldd = d;
                a = md5ff(a, b, c, d, x[i51], 7, -680876936);
                d = md5ff(d, a, b, c, x[i51 + 1], 12, -389564586);
                c = md5ff(c, d, a, b, x[i51 + 2], 17, 606105819);
                b = md5ff(b, c, d, a, x[i51 + 3], 22, -1044525330);
                a = md5ff(a, b, c, d, x[i51 + 4], 7, -176418897);
                d = md5ff(d, a, b, c, x[i51 + 5], 12, 1200080426);
                c = md5ff(c, d, a, b, x[i51 + 6], 17, -1473231341);
                b = md5ff(b, c, d, a, x[i51 + 7], 22, -45705983);
                a = md5ff(a, b, c, d, x[i51 + 8], 7, 1770035416);
                d = md5ff(d, a, b, c, x[i51 + 9], 12, -1958414417);
                c = md5ff(c, d, a, b, x[i51 + 10], 17, -42063);
                b = md5ff(b, c, d, a, x[i51 + 11], 22, -1990404162);
                a = md5ff(a, b, c, d, x[i51 + 12], 7, 1804603682);
                d = md5ff(d, a, b, c, x[i51 + 13], 12, -40341101);
                c = md5ff(c, d, a, b, x[i51 + 14], 17, -1502002290);
                b = md5ff(b, c, d, a, x[i51 + 15], 22, 1236535329);
                a = md5gg(a, b, c, d, x[i51 + 1], 5, -165796510);
                d = md5gg(d, a, b, c, x[i51 + 6], 9, -1069501632);
                c = md5gg(c, d, a, b, x[i51 + 11], 14, 643717713);
                b = md5gg(b, c, d, a, x[i51], 20, -373897302);
                a = md5gg(a, b, c, d, x[i51 + 5], 5, -701558691);
                d = md5gg(d, a, b, c, x[i51 + 10], 9, 38016083);
                c = md5gg(c, d, a, b, x[i51 + 15], 14, -660478335);
                b = md5gg(b, c, d, a, x[i51 + 4], 20, -405537848);
                a = md5gg(a, b, c, d, x[i51 + 9], 5, 568446438);
                d = md5gg(d, a, b, c, x[i51 + 14], 9, -1019803690);
                c = md5gg(c, d, a, b, x[i51 + 3], 14, -187363961);
                b = md5gg(b, c, d, a, x[i51 + 8], 20, 1163531501);
                a = md5gg(a, b, c, d, x[i51 + 13], 5, -1444681467);
                d = md5gg(d, a, b, c, x[i51 + 2], 9, -51403784);
                c = md5gg(c, d, a, b, x[i51 + 7], 14, 1735328473);
                b = md5gg(b, c, d, a, x[i51 + 12], 20, -1926607734);
                a = md5hh(a, b, c, d, x[i51 + 5], 4, -378558);
                d = md5hh(d, a, b, c, x[i51 + 8], 11, -2022574463);
                c = md5hh(c, d, a, b, x[i51 + 11], 16, 1839030562);
                b = md5hh(b, c, d, a, x[i51 + 14], 23, -35309556);
                a = md5hh(a, b, c, d, x[i51 + 1], 4, -1530992060);
                d = md5hh(d, a, b, c, x[i51 + 4], 11, 1272893353);
                c = md5hh(c, d, a, b, x[i51 + 7], 16, -155497632);
                b = md5hh(b, c, d, a, x[i51 + 10], 23, -1094730640);
                a = md5hh(a, b, c, d, x[i51 + 13], 4, 681279174);
                d = md5hh(d, a, b, c, x[i51], 11, -358537222);
                c = md5hh(c, d, a, b, x[i51 + 3], 16, -722521979);
                b = md5hh(b, c, d, a, x[i51 + 6], 23, 76029189);
                a = md5hh(a, b, c, d, x[i51 + 9], 4, -640364487);
                d = md5hh(d, a, b, c, x[i51 + 12], 11, -421815835);
                c = md5hh(c, d, a, b, x[i51 + 15], 16, 530742520);
                b = md5hh(b, c, d, a, x[i51 + 2], 23, -995338651);
                a = md5ii(a, b, c, d, x[i51], 6, -198630844);
                d = md5ii(d, a, b, c, x[i51 + 7], 10, 1126891415);
                c = md5ii(c, d, a, b, x[i51 + 14], 15, -1416354905);
                b = md5ii(b, c, d, a, x[i51 + 5], 21, -57434055);
                a = md5ii(a, b, c, d, x[i51 + 12], 6, 1700485571);
                d = md5ii(d, a, b, c, x[i51 + 3], 10, -1894986606);
                c = md5ii(c, d, a, b, x[i51 + 10], 15, -1051523);
                b = md5ii(b, c, d, a, x[i51 + 1], 21, -2054922799);
                a = md5ii(a, b, c, d, x[i51 + 8], 6, 1873313359);
                d = md5ii(d, a, b, c, x[i51 + 15], 10, -30611744);
                c = md5ii(c, d, a, b, x[i51 + 6], 15, -1560198380);
                b = md5ii(b, c, d, a, x[i51 + 13], 21, 1309151649);
                a = md5ii(a, b, c, d, x[i51 + 4], 6, -145523070);
                d = md5ii(d, a, b, c, x[i51 + 11], 10, -1120210379);
                c = md5ii(c, d, a, b, x[i51 + 2], 15, 718787259);
                b = md5ii(b, c, d, a, x[i51 + 9], 21, -343485551);
                a = safeAdd(a, olda);
                b = safeAdd(b, oldb);
                c = safeAdd(c, oldc);
                d = safeAdd(d, oldd);
            }
            return [
                a,
                b,
                c,
                d
            ];
        }
        function binl2rstr(input) {
            var i52;
            var output = "";
            var length32 = input.length * 32;
            for(i52 = 0; i52 < length32; i52 += 8){
                output += String.fromCharCode(input[i52 >> 5] >>> i52 % 32 & 255);
            }
            return output;
        }
        function rstr2binl(input) {
            var i53;
            var output = [];
            output[(input.length >> 2) - 1] = void 0;
            for(i53 = 0; i53 < output.length; i53 += 1){
                output[i53] = 0;
            }
            var length8 = input.length * 8;
            for(i53 = 0; i53 < length8; i53 += 8){
                output[i53 >> 5] |= (input.charCodeAt(i53 / 8) & 255) << i53 % 32;
            }
            return output;
        }
        function rstrMD5(s) {
            return binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
        }
        function rstrHMACMD5(key, data44) {
            var i54;
            var bkey = rstr2binl(key);
            var ipad = [];
            var opad = [];
            var hash;
            ipad[15] = opad[15] = void 0;
            if (bkey.length > 16) {
                bkey = binlMD5(bkey, key.length * 8);
            }
            for(i54 = 0; i54 < 16; i54 += 1){
                ipad[i54] = bkey[i54] ^ 909522486;
                opad[i54] = bkey[i54] ^ 1549556828;
            }
            hash = binlMD5(ipad.concat(rstr2binl(data44)), 512 + data44.length * 8);
            return binl2rstr(binlMD5(opad.concat(hash), 512 + 128));
        }
        function rstr2hex(input) {
            var hexTab = "0123456789abcdef";
            var output = "";
            var x;
            var i55;
            for(i55 = 0; i55 < input.length; i55 += 1){
                x = input.charCodeAt(i55);
                output += hexTab.charAt(x >>> 4 & 15) + hexTab.charAt(x & 15);
            }
            return output;
        }
        function str2rstrUTF8(input) {
            return unescape(encodeURIComponent(input));
        }
        function rawMD5(s) {
            return rstrMD5(str2rstrUTF8(s));
        }
        function hexMD5(s) {
            return rstr2hex(rawMD5(s));
        }
        function rawHMACMD5(k, d) {
            return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d));
        }
        function hexHMACMD5(k, d) {
            return rstr2hex(rawHMACMD5(k, d));
        }
        function md52(string19, key, raw) {
            if (!key) {
                if (!raw) {
                    return hexMD5(string19);
                }
                return rawMD5(string19);
            }
            if (!raw) {
                return hexHMACMD5(key, string19);
            }
            return rawHMACMD5(key, string19);
        }
        if (module.exports) {
            module.exports = md52;
        } else {
            $.md5 = md52;
        }
    })(commonjsGlobal1);
});
function md5Hash(content) {
    return md5(content);
}
function sassVariable(name82, value, formatter) {
    return {
        name: name82,
        value: formatter ? formatter(value) : value
    };
}
function outputVariable(variable, isDefault = true) {
    return `$${variable.name}: ${variable.value}${isDefault ? " !default" : ""};`;
}
async function compileSass(bundles, temp, minified = true) {
    const frameWorkUses = bundles.map((bundle)=>bundle.framework?.uses || ""
    );
    const frameworkFunctions = bundles.map((bundle)=>bundle.framework?.functions || ""
    );
    const frameworkDefaults = bundles.map((bundle)=>bundle.framework?.defaults || ""
    );
    const frameworkRules = bundles.map((bundle)=>bundle.framework?.rules || ""
    );
    const frameworkMixins = bundles.map((bundle)=>bundle.framework?.mixins || ""
    );
    const quartoUses1 = bundles.map((bundle)=>bundle.quarto?.uses || ""
    );
    const quartoFunctions1 = bundles.map((bundle)=>bundle.quarto?.functions || ""
    );
    const quartoDefaults1 = bundles.map((bundle)=>bundle.quarto?.defaults || ""
    );
    const quartoRules1 = bundles.map((bundle)=>bundle.quarto?.rules || ""
    );
    const quartoMixins = bundles.map((bundle)=>bundle.quarto?.mixins || ""
    );
    const userUses = bundles.map((bundle)=>bundle.user?.uses || ""
    );
    const userFunctions = bundles.map((bundle)=>bundle.user?.functions || ""
    );
    const userDefaults = bundles.map((bundle)=>bundle.user?.defaults || ""
    );
    const userRules = bundles.map((bundle)=>bundle.user?.rules || ""
    );
    const userMixins = bundles.map((bundle)=>bundle.user?.mixins || ""
    );
    const loadPaths = [];
    bundles.forEach((bundle)=>{
        if (bundle.loadPaths) {
            loadPaths.push(...bundle.loadPaths);
        }
    });
    const scssInput = [
        ...frameWorkUses,
        ...quartoUses1,
        ...userUses,
        ...frameworkFunctions,
        ...quartoFunctions1,
        ...userFunctions,
        ...userDefaults.reverse(),
        ...quartoDefaults1.reverse(),
        ...frameworkDefaults.reverse(),
        ...frameworkMixins,
        ...quartoMixins,
        ...userMixins,
        ...frameworkRules,
        ...quartoRules1,
        ...userRules, 
    ].join("\n\n");
    const cacheKey = bundles.map((bundle)=>bundle.key
    ).join("|") + "-" + (minified ? "min" : "nomin");
    return await compileWithCache(scssInput, loadPaths, temp, minified, cacheKey);
}
const layoutBoundary = "^\/\\*\\-\\-[ \\t]*scss:(uses|functions|rules|defaults|mixins)[ \\t]*\\-\\-\\*\\/$";
const kLayerBoundaryLine = RegExp(layoutBoundary);
const kLayerBoundaryTest = RegExp(layoutBoundary, "m");
function mergeLayers(...layers) {
    const themeUses = [];
    const themeDefaults = [];
    const themeRules = [];
    const themeFunctions = [];
    const themeMixins = [];
    layers.forEach((theme)=>{
        if (theme.uses) {
            themeUses.push(theme.uses);
        }
        if (theme.defaults) {
            themeDefaults.unshift(theme.defaults);
        }
        if (theme.rules) {
            themeRules.push(theme.rules);
        }
        if (theme.functions) {
            themeFunctions.push(theme.functions);
        }
        if (theme.mixins) {
            themeMixins.push(theme.mixins);
        }
    });
    return {
        uses: themeUses.join("\n"),
        defaults: themeDefaults.join("\n"),
        functions: themeFunctions.join("\n"),
        mixins: themeMixins.join("\n"),
        rules: themeRules.join("\n")
    };
}
function sassLayer(path66) {
    if (Deno.statSync(path66).isFile) {
        return sassLayerFile(path66);
    } else {
        return sassLayerDir(path66, {
            uses: "_use.scss",
            functions: "_functions.scss",
            defaults: "_defaults.scss",
            mixins: "_mixins.scss",
            rules: "_rules.scss"
        });
    }
}
function sassLayerFile(theme) {
    const rawContents = Deno.readTextFileSync(theme);
    return sassLayerStr(rawContents, theme);
}
function sassLayerStr(rawContents, errorHint) {
    if (!kLayerBoundaryTest.test(rawContents)) {
        throw new Error(`The file ${errorHint} doesn't contain at least one layer boundary (/*-- scss:defaults --*/, /*-- scss:rules --*/, /*-- scss:mixins --*/, /*-- scss:functions --*/, or /*-- scss:uses --*/)`);
    }
    const uses = [];
    const defaults = [];
    const rules = [];
    const functions = [];
    const mixins = [];
    let accum = defaults;
    lines(rawContents).forEach((line)=>{
        const scopeMatch = line.match(kLayerBoundaryLine);
        if (scopeMatch) {
            const scope = scopeMatch[1];
            switch(scope){
                case "uses":
                    accum = uses;
                    break;
                case "defaults":
                    accum = defaults;
                    break;
                case "rules":
                    accum = rules;
                    break;
                case "functions":
                    accum = functions;
                    break;
                case "mixins":
                    accum = mixins;
                    break;
            }
        } else {
            accum.push(line);
        }
    });
    return {
        uses: uses.join("\n"),
        defaults: defaults.join("\n"),
        rules: rules.join("\n"),
        mixins: mixins.join("\n"),
        functions: functions.join("\n")
    };
}
function sassLayerDir(dir, names) {
    const read = (path67)=>{
        if (path67) {
            path67 = join3(dir, path67);
            if (existsSync(path67)) {
                return Deno.readTextFileSync(path67);
            } else {
                return "";
            }
        } else {
            return "";
        }
    };
    return {
        uses: read(names.uses),
        defaults: read(names.defaults),
        rules: read(names.rules),
        mixins: read(names.mixins),
        functions: read(names.functions)
    };
}
async function compileWithCache(input, loadPaths, temp, compressed, cacheIdentifier) {
    if (cacheIdentifier) {
        const identifierHash = md5Hash(cacheIdentifier);
        const inputHash = md5Hash(input);
        const cacheDir = quartoCacheDir("sass");
        const cacheIdxPath = join3(cacheDir, "index.json");
        const outputFile = `${identifierHash}.css`;
        const outputFilePath = join3(cacheDir, outputFile);
        let cacheIndex = {};
        let writeCache = true;
        if (existsSync(outputFilePath)) {
            cacheIndex = JSON.parse(Deno.readTextFileSync(cacheIdxPath));
            const existingEntry = cacheIndex[identifierHash];
            writeCache = !existingEntry || existingEntry.hash !== inputHash;
        }
        if (writeCache) {
            await dartCompile(input, outputFilePath, temp, loadPaths, compressed);
            cacheIndex[identifierHash] = {
                key: cacheIdentifier,
                hash: inputHash
            };
            Deno.writeTextFileSync(cacheIdxPath, JSON.stringify(cacheIndex));
        }
        return outputFilePath;
    } else {
        const outputFilePath = temp.createFile({
            suffix: "css"
        });
        await dartCompile(input, outputFilePath, temp, __VIRTUAL_FILE181(loadPaths), compressed);
        return outputFilePath;
    }
}
const kMarkdownBlockSeparator = "\n\n<!-- -->\n\n";
const kDefaultHighlightStyle = "arrow";
const kHtmlEmptyPostProcessResult = {
    resources: [],
    supporting: []
};
const kCssUrlRegex = /url\((?!['"]?(?:data|https?):)(['"])?([^'"]*?)\1\)/g;
const kCssImportRegex = /@import\s(?!['"](?:data|https?):)(['"])([^'"]*?)\1/g;
function cssFileResourceReferences(files) {
    return files.reduce((allRefs, file)=>{
        if (extname2(file).toLowerCase() === ".css") {
            if (existsSync(file)) {
                file = Deno.realPathSync(file);
                const css = Deno.readTextFileSync(file);
                const cssRefs = cssFileRefs(css).map((ref1)=>join3(dirname2(file), ref1)
                );
                allRefs.push(...cssRefs);
                allRefs.push(...cssFileResourceReferences(cssRefs));
            }
        }
        return allRefs;
    }, []);
}
function cssFileRefs(css) {
    return cssImports(css).concat(cssResources(css)).filter(isFileRef);
}
function cssResources(css) {
    return matchCss(css, kCssUrlRegex);
}
function cssImports(css) {
    return matchCss(css, kCssImportRegex);
}
function matchCss(css, regex) {
    const matches = [];
    regex.lastIndex = 0;
    let match = regex.exec(css);
    while(match != null){
        matches.push(match[2]);
        match = regex.exec(css);
    }
    regex.lastIndex = 0;
    return matches;
}
function asCssFont(value) {
    if (!value) {
        return undefined;
    } else {
        const fontFamily = String(value).split(",").map((font)=>{
            font = font.trim();
            if (font.includes(" ")) {
                font = `"${font}"`;
            }
            return font;
        }).filter((font)=>font.length > 0
        ).join(", ");
        return `${fontFamily}`;
    }
}
function asCssNumber(value) {
    if (typeof value === "number") {
        return String(value);
    } else if (!value) {
        return undefined;
    } else {
        const str67 = String(value);
        const match = str67.match(/(^[0-9]*)/);
        if (match) {
            return match[1];
        } else {
            return undefined;
        }
    }
}
function asCssSize(value) {
    if (typeof value === "number") {
        if (value === 0) {
            return "0";
        } else {
            return value + "px";
        }
    } else if (!value) {
        return undefined;
    } else {
        const str68 = String(value);
        if (str68 !== "0" && !str68.match(/\w$/)) {
            return str68 + "px";
        } else {
            return str68;
        }
    }
}
function asCssColor(value) {
    if (typeof value === "string") {
        if (value === "none") {
            return "transparent";
        } else {
            return value;
        }
    }
}
const kBootstrapColors = [
    "primary",
    "secondary",
    "success",
    "info",
    "warning",
    "danger",
    "light",
    "dark", 
];
const kBootstrapPaletteRegex = RegExp(`gray\-[1-9]00`);
function asBootstrapColor(value) {
    if (typeof value === "string") {
        if (kBootstrapColors.includes(value) || value.match(kBootstrapPaletteRegex)) {
            return `$${value}`;
        } else {
            return asCssColor(value);
        }
    }
}
function renderEjs(file, data45, removeEmptyLines = true, cache = true) {
    const template1 = compileTemplate(file, removeEmptyLines, cache);
    return lines(template1(data45).trimLeft()).filter((line)=>!removeEmptyLines || line.trim().length > 0
    ).join("\n") + "\n";
}
const compiledTemplates = new Map();
function compileTemplate(file, removeEmptyLines, cache = true) {
    if (!cache || !compiledTemplates.has(file)) {
        const template2 = `<% const partial = (file, data) => print(include(file, data)); %>
      ${Deno.readTextFileSync(file)}`;
        compiledTemplates.set(file, __VIRTUAL_FILE176(template2, {
            imports: {
                include: (includeFile, includeData)=>{
                    return renderEjs(join3(dirname2(file), includeFile), includeData, removeEmptyLines);
                }
            }
        }));
    }
    return compiledTemplates.get(file);
}
function isPdfOutput(format14) {
    if (typeof format14 !== "string") {
        format14 = format14?.to || "html";
    }
    return format14 === "pdf" || format14 === "beamer";
}
function isLatexOutput(format15) {
    return [
        "pdf",
        "latex",
        "beamer"
    ].includes(format15.to || "");
}
function isBeamerOutput(format16) {
    return [
        "beamer"
    ].includes(format16.to || "");
}
function isEpubOutput(format17) {
    if (typeof format17 !== "string") {
        format17 = format17?.to || "html";
    }
    return [
        "epub",
        "epub2",
        "epub3"
    ].includes(format17 || "");
}
function isHtmlFileOutput(format18) {
    if (typeof format18 !== "string") {
        format18 = format18?.to || "html";
    }
    return isHtmlDocOutput(format18) || isHtmlSlideOutput(format18);
}
function isHtmlOutput(format19, strict) {
    if (typeof format19 !== "string") {
        format19 = format19?.to;
    }
    format19 = format19 || "html";
    if (isHtmlDocOutput(format19)) {
        return true;
    } else if (!strict) {
        return isHtmlSlideOutput(format19) || isEpubOutput(format19);
    } else {
        return false;
    }
}
function isHtmlDocOutput(format20) {
    if (typeof format20 !== "string") {
        format20 = format20?.to || "html";
    }
    return [
        "html",
        "html4",
        "html5", 
    ].includes(format20);
}
function isHtmlSlideOutput(format21) {
    return [
        "s5",
        "dzslides",
        "slidy",
        "slideous",
        "revealjs", 
    ].includes(format21);
}
function isPresentationOutput(format22) {
    if (format22.to) {
        return [
            "s5",
            "dzslides",
            "slidy",
            "slideous",
            "revealjs",
            "beamer",
            "pptx"
        ].some((to)=>format22.to?.startsWith(to)
        );
    } else {
        return false;
    }
}
function isRevealjsOutput(format23) {
    if (typeof format23 !== "string") {
        format23 = format23?.to;
    }
    format23 = format23 || "html";
    return format23.startsWith("revealjs");
}
function isIpynbOutput(format24) {
    return !!format24.to && format24.to.startsWith("ipynb");
}
function isMarkdownOutput(format25, flavors = [
    "markdown",
    "gfm",
    "commonmark"
]) {
    const to = (format25.to || "").replace(/[\+\-_].*$/, "");
    return flavors.includes(to) || isIpynbOutput(format25);
}
function isHtmlCompatible(format26) {
    return isHtmlOutput(format26.pandoc) || isMarkdownOutput(format26.pandoc) && format26.render[kPreferHtml] || isIpynbOutput(format26.pandoc);
}
function isJavascriptCompatible(format27) {
    return isHtmlCompatible(format27) && !isEpubOutput(format27.pandoc);
}
const base64abc = [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    "g",
    "h",
    "i",
    "j",
    "k",
    "l",
    "m",
    "n",
    "o",
    "p",
    "q",
    "r",
    "s",
    "t",
    "u",
    "v",
    "w",
    "x",
    "y",
    "z",
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "+",
    "/", 
];
function encode(data46) {
    const uint8 = typeof data46 === "string" ? new TextEncoder().encode(data46) : data46 instanceof Uint8Array ? data46 : new Uint8Array(data46);
    let result = "", i56;
    const l = uint8.length;
    for(i56 = 2; i56 < l; i56 += 3){
        result += base64abc[uint8[i56 - 2] >> 2];
        result += base64abc[(uint8[i56 - 2] & 3) << 4 | uint8[i56 - 1] >> 4];
        result += base64abc[(uint8[i56 - 1] & 15) << 2 | uint8[i56] >> 6];
        result += base64abc[uint8[i56] & 63];
    }
    if (i56 === l + 1) {
        result += base64abc[uint8[i56 - 2] >> 2];
        result += base64abc[(uint8[i56 - 2] & 3) << 4];
        result += "==";
    }
    if (i56 === l) {
        result += base64abc[uint8[i56 - 2] >> 2];
        result += base64abc[(uint8[i56 - 2] & 3) << 4 | uint8[i56 - 1] >> 4];
        result += base64abc[(uint8[i56 - 1] & 15) << 2];
        result += "=";
    }
    return result;
}
function decode(b64) {
    const binString = atob(b64);
    const size = binString.length;
    const bytes = new Uint8Array(size);
    for(let i57 = 0; i57 < size; i57++){
        bytes[i57] = binString.charCodeAt(i57);
    }
    return bytes;
}
function mappedSource(source, substrs) {
    const params = [];
    for (const { range  } of substrs){
        params.push(range);
    }
    return mappedString(source, params);
}
async function partitionCellOptionsMapped(language, source, _validate = false, _engine = "") {
    const commentChars = langCommentChars(language);
    const optionPrefix = optionCommentPrefix(commentChars[0]);
    const optionSuffix = commentChars[1] || "";
    const optionsSource = [];
    const yamlLines = [];
    let endOfYaml = 0;
    for (const line of rangedLines(source.value, true)){
        if (line.substring.startsWith(optionPrefix)) {
            if (!optionSuffix || line.substring.trimRight().endsWith(optionSuffix)) {
                let yamlOption = line.substring.substring(optionPrefix.length);
                if (optionSuffix) {
                    yamlOption = yamlOption.trimRight();
                    yamlOption = yamlOption.substring(0, yamlOption.length - optionSuffix.length);
                }
                endOfYaml = line.range.start + optionPrefix.length + yamlOption.length - optionSuffix.length;
                const rangedYamlOption = {
                    substring: yamlOption,
                    range: {
                        start: line.range.start + optionPrefix.length,
                        end: endOfYaml
                    }
                };
                yamlLines.push(rangedYamlOption);
                optionsSource.push(line);
                continue;
            }
        }
        break;
    }
    const mappedYaml = yamlLines.length ? mappedSource(source, yamlLines) : undefined;
    return {
        yaml: mappedYaml,
        optionsSource,
        source: mappedString(source, [
            {
                start: endOfYaml,
                end: source.value.length
            }
        ]),
        sourceStartLine: yamlLines.length
    };
}
function langCommentChars(lang) {
    const chars = kLangCommentChars[lang] || "#";
    if (!Array.isArray(chars)) {
        return [
            chars
        ];
    } else {
        return chars;
    }
}
function optionCommentPrefix(comment) {
    return comment + "| ";
}
const kLangCommentChars = {
    r: "#",
    python: "#",
    julia: "#",
    scala: "//",
    matlab: "%",
    csharp: "//",
    fsharp: "//",
    c: [
        "/*",
        "*/"
    ],
    css: [
        "/*",
        "*/"
    ],
    sas: [
        "*",
        ";"
    ],
    powershell: "#",
    bash: "#",
    sql: "--",
    mysql: "--",
    psql: "--",
    lua: "--",
    cpp: "//",
    cc: "//",
    stan: "#",
    octave: "#",
    fortran: "!",
    fortran95: "!",
    awk: "#",
    gawk: "#",
    stata: "*",
    java: "//",
    groovy: "//",
    sed: "#",
    perl: "#",
    ruby: "#",
    tikz: "%",
    js: "//",
    d3: "//",
    node: "//",
    sass: "//",
    coffee: "#",
    go: "//",
    asy: "//",
    haskell: "--",
    dot: "//",
    ojs: "//"
};
function checkForEqualsInChunk(error27, _parse, _schema) {
    if (typeof error27.violatingObject.result !== "string") {
        return error27;
    }
    const badObject = error27.source.value.substring(error27.violatingObject.start, error27.violatingObject.end);
    if (errorKeyword(error27) !== "type") {
        return error27;
    }
    let m;
    const heading = `${error27.location}: ${quotedStringColor(badObject)} must be a YAML mapping.`;
    const errorMsg = [
        `${quotedStringColor(badObject)} is a string.`
    ];
    const newError = {
        heading,
        error: errorMsg,
        info: {}
    };
    addFileInfo(newError, error27.source);
    addInstancePathInfo(newError, error27.instancePath);
    if (m = badObject.match(/= *TRUE/i)) {
        newError.info["suggestion-fix"] = `Try using ${quotedStringColor(": true")} instead of ${quotedStringColor(m[0])}.`;
    } else if (m = badObject.match(/= *FALSE/i)) {
        newError.info["suggestion-fix"] = `Try using ${quotedStringColor(": false")} instead of ${quotedStringColor(m[0])}.`;
    } else if (badObject.match("=")) {
        newError.info["suggestion-fix"] = `Try using ${quotedStringColor(":")} instead of ${quotedStringColor("=")}.`;
    } else {
        return error27;
    }
    return {
        ...error27,
        message: tidyverseFormatError(newError)
    };
}
const makeEngineSchema = (engine)=>idSchema(objectRefSchemaFromContextGlob("cell-*", (field, _path)=>{
        const engineTag = field && field.tags && field.tags.engine;
        switch(typeof engineTag){
            case "undefined":
                return true;
            case "string":
                return engineTag === engine;
            case "object":
                return engineTag.indexOf(engine) !== -1;
            default:
                throw new Error(`Internal Error: bad engine tag ${engineTag}`);
        }
    }), `engine-${engine}`)
;
const markdownEngineSchema = defineCached(async ()=>{
    return {
        schema: makeEngineSchema("markdown"),
        errorHandlers: []
    };
}, "engine-markdown");
const knitrEngineSchema = defineCached(async ()=>{
    const result = await makeEngineSchema("knitr");
    return {
        schema: result,
        errorHandlers: [
            checkForEqualsInChunk
        ]
    };
}, "engine-knitr");
const jupyterEngineSchema = defineCached(async ()=>{
    return {
        schema: makeEngineSchema("jupyter"),
        errorHandlers: []
    };
}, "engine-jupyter");
async function getEngineOptionsSchema() {
    const obj = {
        markdown: await markdownEngineSchema(),
        knitr: await knitrEngineSchema(),
        jupyter: await jupyterEngineSchema()
    };
    return obj;
}
function guessChunkOptionsFormat(options) {
    const noIndentOrColon = /^[^:\s]+[^:]+$/;
    const chunkLines = lines(options);
    if (chunkLines.filter((l)=>l.match(noIndentOrColon)
    ).length === 0) {
        return "yaml";
    }
    if (chunkLines.some((l)=>l.trim() !== "" && !l.trimRight().endsWith(",") && l.indexOf("=") === -1
    )) {
        return "yaml";
    }
    return "knitr";
}
function partitionCellOptions(language, source) {
    const commentChars = langCommentChars(language);
    const optionPrefix = optionCommentPrefix(commentChars[0]);
    const optionSuffix = commentChars[1] || "";
    const optionsSource = [];
    const yamlLines = [];
    for (const line of source){
        if (line.startsWith(optionPrefix)) {
            if (!optionSuffix || line.trimRight().endsWith(optionSuffix)) {
                let yamlOption = line.substring(optionPrefix.length);
                if (optionSuffix) {
                    yamlOption = yamlOption.trimRight();
                    yamlOption = yamlOption.substring(0, yamlOption.length - optionSuffix.length);
                }
                yamlLines.push(yamlOption);
                optionsSource.push(line);
                continue;
            }
        }
        break;
    }
    if (guessChunkOptionsFormat(yamlLines.join("\n")) === "knitr") {
        return {
            yaml: undefined,
            optionsSource,
            source: source.slice(yamlLines.length),
            sourceStartLine: yamlLines.length
        };
    }
    let yaml = yamlLines.length > 0 ? readYamlFromString(yamlLines.join("\n")) : undefined;
    if (yaml !== undefined && (typeof yaml !== "object" || Array.isArray(yaml))) {
        warnOnce("Invalid YAML option format in cell:\n" + yamlLines.join("\n"));
        yaml = undefined;
    }
    return {
        yaml: yaml,
        optionsSource,
        source: source.slice(yamlLines.length),
        sourceStartLine: yamlLines.length
    };
}
async function parseAndValidateCellOptions(mappedYaml, _language, validate1 = false, engine = "") {
    if (mappedYaml.value.trim().length === 0) {
        return undefined;
    }
    const engineOptionsSchema = await getEngineOptionsSchema();
    const schema = engineOptionsSchema[engine];
    if (schema === undefined || !validate1) {
        return readYamlFromString(mappedYaml.value);
    }
    return readAndValidateYamlFromMappedString(mappedYaml, schema, `Validation of YAML chunk options for engine ${engine} failed`);
}
async function partitionCellOptionsMapped1(language, outerSource, validate2 = false, engine = "") {
    const { yaml: mappedYaml , optionsSource , source , sourceStartLine ,  } = await partitionCellOptionsMapped(language, outerSource);
    if (guessChunkOptionsFormat((mappedYaml ?? asMappedString("")).value) === "yaml") {
        const yaml = await parseAndValidateCellOptions(mappedYaml ?? asMappedString(""), language, validate2, engine);
        return {
            yaml: yaml,
            optionsSource,
            source,
            sourceStartLine
        };
    } else {
        return {
            yaml: undefined,
            optionsSource,
            source,
            sourceStartLine
        };
    }
}
function shortUuid() {
    return generate().replaceAll("-", "").slice(0, 8);
}
class PngImage {
    content = [];
    width = -1;
    height = -1;
    dpiX = -1;
    dpiY = -1;
    bitDepth = -1;
    colourType = -1;
    compressionMethod = -1;
    filterMethod = -1;
    interlaceMethod = -1;
    constructor(bytes, sizeOnly = true){
        const magicNumberBytes = bytes.slice(0, 8);
        const magicNumber = bytesToString(magicNumberBytes);
        if (magicNumber !== "13780787113102610") {
            throw new Error("Not a png file");
        }
        let pos = 8;
        while(pos < bytes.length){
            const chunk = new PngChunk(bytes.slice(pos));
            switch(chunk.type){
                case "IHDR":
                    this.parseIHDRChunk(chunk, sizeOnly);
                    break;
                case "pHYs":
                    this.parsePHYSChunk(chunk);
                    break;
                case "IDAT":
                    return;
            }
            pos += chunk.totalLength;
        }
    }
    parseIHDRChunk(chunk, sizeOnly) {
        this.width = bytesToUint32(chunk.data, 0, 4);
        this.height = bytesToUint32(chunk.data, 4, 4);
        if (sizeOnly) {
            return;
        }
        this.bitDepth = chunk.data.slice(8, 9)[0];
        if (this.bitDepth !== 8) throw new Error("bitDepth not supported");
        this.colourType = chunk.data.slice(9, 10)[0];
        if (this.colourType !== 6) throw new Error("colourType not supported");
        this.compressionMethod = chunk.data.slice(10, 11)[0];
        if (this.compressionMethod !== 0) {
            throw new Error("compressionMethod not supported");
        }
        this.filterMethod = chunk.data.slice(11, 12)[0];
        if (this.filterMethod !== 0) throw new Error("filterMethod not supported");
        this.interlaceMethod = chunk.data.slice(12, 13)[0];
        if (this.interlaceMethod !== 0) {
            throw new Error("Interlacing not supported");
        }
    }
    parsePHYSChunk(chunk) {
        const meter = chunk.data[8];
        if (meter === 1) {
            const x = bytesToUint32(chunk.data, 0, 4);
            const y = bytesToUint32(chunk.data, 4, 4);
            const kMetersPerInch = 0.0254;
            this.dpiX = Math.round(x * kMetersPerInch);
            this.dpiY = Math.round(y * kMetersPerInch);
        }
    }
}
class PngChunk {
    totalLength;
    dataLength;
    type;
    data;
    crc;
    constructor(bytes){
        this.dataLength = this.getLength(bytes);
        this.type = this.getType(bytes);
        this.data = this.getData(bytes);
        this.crc = this.getCRC(bytes);
        this.totalLength = this.dataLength + 12;
    }
    getLength(bytes) {
        const lengthBytes = bytes.slice(0, 4);
        return bytesToUint32(lengthBytes);
    }
    getType(bytes) {
        const typeByte = bytes.slice(4, 8);
        return new TextDecoder("ascii").decode(typeByte);
    }
    getData(bytes) {
        return bytes.slice(8, 8 + this.dataLength);
    }
    getCRC(bytes) {
        return bytes.slice(8 + this.dataLength, 8 + this.dataLength + 4);
    }
}
const MAX_SIGNIFICANT_SIZE = 127;
function bytesToUint32(byteArray, start = 0, count) {
    if (count === undefined) {
        count = byteArray.length;
    }
    if (count > 4) {
        throw new Error("Length cannot be greater than 4");
    }
    let position = start;
    let value = 0;
    if (count === 4) {
        let sigValue = byteArray[position];
        if (sigValue > 127) {
            value += MAX_SIGNIFICANT_SIZE << 24;
            sigValue -= MAX_SIGNIFICANT_SIZE;
        }
        value += sigValue << 24;
        position++;
    }
    for(let i58 = position; i58 < start + count; i58++){
        value += byteArray[i58] << 8 * (count - (i58 - start) - 1);
    }
    return value;
}
function bytesToString(byteArray, start = 0, count) {
    if (count === undefined) {
        count = byteArray.length;
    }
    let result = "";
    for(let i59 = start; i59 < start + count; i59++){
        const __byte = byteArray[i59];
        if (__byte === 0) {
            result += "00";
        } else if (__byte < 10) {
            result += `0${__byte.toString()}`;
        } else {
            result += __byte.toString();
        }
    }
    return result;
}
function hideCell(cell, options) {
    return shouldHide(cell, options, kInclude);
}
function hideCode(cell, options) {
    return shouldHide(cell, options, kEcho);
}
function hideOutput(cell, options) {
    return shouldHide(cell, options, kOutput);
}
function hideWarnings(cell, options) {
    if (options.execute[kOutput] === false && cell.options[kOutput] !== false) {
        return cell.options[kWarning] || false;
    } else {
        return shouldHide(cell, options, kWarning);
    }
}
function includeCell(cell, options) {
    return shouldInclude(cell, options, kInclude);
}
function includeCode(cell, options) {
    return shouldInclude(cell, options, kEcho);
}
function echoFenced(cell, options) {
    const fenced = cell.options.echo === "fenced" || cell.options.echo === undefined && options.execute.echo === "fenced";
    return fenced;
}
function includeOutput(cell, options) {
    return shouldInclude(cell, options, kOutput);
}
function includeWarnings(cell, options) {
    if (options.execute[kOutput] === false && cell.options[kOutput] !== false) {
        return cell.options[kWarning] || false;
    } else {
        return shouldInclude(cell, options, kWarning);
    }
}
function shouldHide(cell, options, context) {
    if (cell.options[context] !== undefined) {
        return !cell.options[context] && options.keepHidden;
    } else {
        return !options.execute[context] && options.keepHidden;
    }
}
function shouldInclude(cell, options, context) {
    if (cell.options[context] !== undefined) {
        return !!(cell.options[context] || options.keepHidden);
    } else {
        return !!(options.execute[context] || options.keepHidden);
    }
}
function pandocAutoIdentifier(text, asciify) {
    if (asciify) {
        text = pandocAsciify(text);
    }
    return text.replace(/[!"#$%&')*+,\/:;<=>?@\[\\\]^`{|}~]/g, "").replace(/\s/g, "-").toLowerCase().replace(/^[^A-Za-z]+/, "");
}
function pandocAsciify(text) {
    const chars = [];
    const len3 = text.length;
    let newch;
    for(let i60 = 0; i60 < len3; i60++){
        newch = "";
        const ch = text.charCodeAt(i60);
        switch(ch){
            case 192:
            case 193:
            case 194:
            case 195:
            case 196:
            case 197:
            case 256:
            case 258:
            case 260:
            case 461:
            case 512:
            case 514:
            case 550:
            case 7680:
            case 7840:
            case 7842:
                newch = "A";
                break;
            case 7682:
            case 7684:
            case 7686:
                newch = "B";
                break;
            case 199:
            case 262:
            case 264:
            case 266:
            case 268:
                newch = "C";
                break;
            case 270:
            case 7690:
            case 7692:
            case 7694:
            case 7696:
            case 7698:
                newch = "D";
                break;
            case 200:
            case 201:
            case 203:
            case 274:
            case 276:
            case 278:
            case 280:
            case 282:
            case 516:
            case 518:
            case 552:
            case 7704:
            case 7706:
            case 7864:
            case 7866:
            case 7868:
                newch = "E";
                break;
            case 7710:
                newch = "F";
                break;
            case 284:
            case 286:
            case 288:
            case 290:
            case 486:
            case 500:
            case 7712:
                newch = "G";
                break;
            case 292:
            case 542:
            case 7714:
            case 7716:
            case 7718:
            case 7720:
            case 7722:
                newch = "H";
                break;
            case 204:
            case 205:
            case 206:
            case 207:
            case 296:
            case 298:
            case 300:
            case 302:
            case 304:
            case 463:
            case 520:
            case 522:
            case 7724:
            case 7880:
            case 7882:
                newch = "I";
                break;
            case 308:
                newch = "J";
                break;
            case 310:
            case 488:
            case 7728:
            case 7730:
            case 7732:
            case 8490:
                newch = "K";
                break;
            case 313:
            case 315:
            case 317:
            case 7734:
            case 7738:
            case 7740:
                newch = "L";
                break;
            case 7742:
            case 7744:
            case 7746:
                newch = "M";
                break;
            case 209:
            case 323:
            case 325:
            case 327:
            case 504:
            case 7748:
            case 7750:
            case 7752:
            case 7754:
                newch = "N";
                break;
            case 210:
            case 211:
            case 212:
            case 213:
            case 214:
            case 332:
            case 334:
            case 336:
            case 416:
            case 465:
            case 490:
            case 524:
            case 526:
            case 558:
            case 7884:
            case 7886:
                newch = "O";
                break;
            case 7764:
            case 7766:
                newch = "P";
                break;
            case 340:
            case 342:
            case 344:
            case 528:
            case 530:
            case 7768:
            case 7770:
            case 7774:
                newch = "R";
                break;
            case 346:
            case 348:
            case 350:
            case 352:
            case 536:
            case 7776:
            case 7778:
                newch = "S";
                break;
            case 354:
            case 356:
            case 538:
            case 7786:
            case 7788:
            case 7790:
            case 7792:
                newch = "T";
                break;
            case 217:
            case 218:
            case 219:
            case 220:
            case 360:
            case 362:
            case 364:
            case 366:
            case 368:
            case 370:
            case 431:
            case 467:
            case 532:
            case 534:
            case 7794:
            case 7796:
            case 7798:
            case 7908:
            case 7910:
                newch = "U";
                break;
            case 7804:
            case 7806:
                newch = "V";
                break;
            case 372:
            case 7808:
            case 7810:
            case 7812:
            case 7814:
            case 7816:
                newch = "W";
                break;
            case 7818:
            case 7820:
                newch = "X";
                break;
            case 221:
            case 374:
            case 376:
            case 562:
            case 7822:
            case 7922:
            case 7924:
            case 7926:
            case 7928:
                newch = "Y";
                break;
            case 377:
            case 379:
            case 381:
            case 7824:
            case 7826:
            case 7828:
                newch = "Z";
                break;
            case 224:
            case 225:
            case 226:
            case 227:
            case 228:
            case 229:
            case 257:
            case 259:
            case 261:
            case 462:
            case 513:
            case 515:
            case 551:
            case 553:
            case 7681:
            case 7841:
            case 7843:
                newch = "a";
                break;
            case 7683:
            case 7685:
            case 7687:
                newch = "b";
                break;
            case 231:
            case 263:
            case 265:
            case 267:
            case 269:
                newch = "c";
                break;
            case 271:
            case 7691:
            case 7693:
            case 7695:
            case 7697:
            case 7699:
                newch = "d";
                break;
            case 232:
            case 233:
            case 234:
            case 235:
            case 275:
            case 277:
            case 279:
            case 281:
            case 283:
            case 517:
            case 519:
            case 7705:
            case 7707:
            case 7865:
            case 7867:
            case 7869:
                newch = "e";
                break;
            case 7711:
                newch = "f";
                break;
            case 285:
            case 287:
            case 289:
            case 291:
            case 487:
            case 501:
            case 7713:
                newch = "g";
                break;
            case 293:
            case 543:
            case 7715:
            case 7717:
            case 7719:
            case 7721:
            case 7723:
            case 7830:
                newch = "h";
                break;
            case 236:
            case 237:
            case 238:
            case 239:
            case 297:
            case 299:
            case 301:
            case 303:
            case 305:
            case 464:
            case 521:
            case 523:
            case 7725:
            case 7881:
            case 7883:
                newch = "i";
                break;
            case 309:
            case 496:
                newch = "j";
                break;
            case 311:
            case 489:
            case 7729:
            case 7731:
            case 7733:
                newch = "k";
                break;
            case 314:
            case 316:
            case 318:
            case 7735:
            case 7739:
            case 7741:
                newch = "l";
                break;
            case 7743:
            case 7745:
            case 7747:
                newch = "m";
                break;
            case 241:
            case 324:
            case 326:
            case 328:
            case 505:
            case 7749:
            case 7751:
            case 7753:
            case 7755:
                newch = "n";
                break;
            case 242:
            case 243:
            case 244:
            case 245:
            case 246:
            case 333:
            case 335:
            case 337:
            case 417:
            case 432:
            case 466:
            case 491:
            case 525:
            case 527:
            case 559:
            case 7885:
            case 7887:
                newch = "o";
                break;
            case 7765:
            case 7767:
                newch = "p";
                break;
            case 341:
            case 343:
            case 345:
            case 529:
            case 531:
            case 7769:
            case 7771:
            case 7775:
                newch = "r";
                break;
            case 347:
            case 349:
            case 351:
            case 353:
            case 537:
            case 7777:
            case 7779:
                newch = "s";
                break;
            case 355:
            case 357:
            case 539:
            case 7787:
            case 7789:
            case 7791:
            case 7793:
            case 7831:
                newch = "t";
                break;
            case 249:
            case 250:
            case 251:
            case 252:
            case 361:
            case 363:
            case 365:
            case 367:
            case 369:
            case 371:
            case 468:
            case 533:
            case 535:
            case 7795:
            case 7797:
            case 7799:
            case 7909:
            case 7911:
                newch = "u";
                break;
            case 7805:
            case 7807:
                newch = "v";
                break;
            case 373:
            case 7809:
            case 7811:
            case 7813:
            case 7815:
            case 7817:
            case 7832:
                newch = "w";
                break;
            case 7819:
            case 7821:
                newch = "x";
                break;
            case 253:
            case 255:
            case 375:
            case 563:
            case 7833:
            case 7923:
            case 7925:
            case 7927:
            case 7929:
                newch = "y";
                break;
            case 378:
            case 380:
            case 382:
            case 7825:
            case 7827:
            case 7829:
                newch = "z";
                break;
            case 894:
                newch = ";";
                break;
            case 8175:
                newch = "`";
                break;
            case 8800:
                newch = "=";
                break;
            case 8814:
                newch = "<";
                break;
            case 8815:
                newch = ">";
                break;
        }
        if (newch) {
            chars.push(newch.charCodeAt(0));
        } else if (ch < 128) {
            chars.push(ch);
        }
    }
    return String.fromCharCode(...chars);
}
function asHtmlId(text) {
    return pandocAutoIdentifier(text, false);
}
function getDecodedAttribute(element, attrib) {
    const value = element.getAttribute(attrib);
    if (value) {
        return decodeURI(value);
    } else {
        return value;
    }
}
const kAttrReplacements = {
    '"': "&quot;",
    "<": "&lt;",
    ">": "&gt;",
    "&": "&amp;"
};
function encodeAttributeValue(value) {
    if (typeof value === "string") {
        let result = value;
        Object.keys(kAttrReplacements).forEach((key)=>{
            result = result.replace(key, kAttrReplacements[key]);
        });
        return result;
    } else {
        return value;
    }
}
function findParent(el, match) {
    let targetEl = el;
    do {
        if (targetEl.parentElement) {
            if (match(targetEl.parentElement)) {
                return targetEl.parentElement;
            } else {
                targetEl = targetEl.parentElement;
            }
        } else {
            return undefined;
        }
    }while (targetEl !== null && targetEl.nodeType === 1)
    return undefined;
}
const kHtmlResourceTags = {
    "a": [
        "href"
    ],
    "img": [
        "src",
        "data-src"
    ],
    "link": [
        "href"
    ],
    "script": [
        "src"
    ],
    "embed": [
        "src"
    ],
    "iframe": [
        "src"
    ],
    "section": [
        "data-background-image",
        "data-background-video"
    ]
};
function discoverResourceRefs(doc) {
    const refs = [];
    Object.keys(kHtmlResourceTags).forEach((tag)=>{
        for (const attrib of kHtmlResourceTags[tag]){
            refs.push(...resolveResourceTag(doc, tag, attrib));
        }
    });
    const styles = doc.querySelectorAll("style");
    for(let i61 = 0; i61 < styles.length; i61++){
        const style = styles[i61];
        if (style.innerHTML) {
            refs.push(...cssFileRefs(style.innerHTML));
        }
    }
    return Promise.resolve({
        resources: refs,
        supporting: []
    });
}
function processFileResourceRefs(doc, tag, attrib, onRef) {
    const tags = doc.querySelectorAll(tag);
    for(let i62 = 0; i62 < tags.length; i62++){
        const tag = tags[i62];
        const href = getDecodedAttribute(tag, attrib);
        if (href !== null && href.length > 0 && isFileRef(href)) {
            onRef(tag, href);
        }
    }
}
function resolveResourceTag(doc, tag, attrib) {
    const refs = [];
    processFileResourceRefs(doc, tag, attrib, (_tag, ref2)=>refs.push(ref2)
    );
    return refs;
}
function isDisplayData(output) {
    return [
        "display_data",
        "execute_result"
    ].includes(output.output_type);
}
function isCaptionableData(output) {
    if (isDisplayData(output)) {
        const displayData = output;
        return !displayData.noCaption;
    } else {
        return false;
    }
}
function displayDataMimeType(output, options) {
    const displayPriority = [
        kTextMarkdown,
        kImageSvg,
        kImagePng,
        kImageJpeg, 
    ];
    if (options.toHtml) {
        const htmlFormats = [
            kApplicationJupyterWidgetState,
            kApplicationJupyterWidgetView,
            kApplicationJavascript,
            kTextHtml, 
        ];
        if (options.toMarkdown) {
            displayPriority.unshift(...htmlFormats);
        } else {
            displayPriority.push(...htmlFormats);
        }
        displayPriority.unshift(kApplicationJupyterWidgetState, kApplicationJupyterWidgetView, kApplicationJavascript, kTextHtml);
    } else if (options.toLatex) {
        displayPriority.push(kTextLatex, kApplicationPdf);
    } else if (options.toMarkdown) {
        displayPriority.push(kTextHtml);
    }
    displayPriority.push(kTextPlain);
    const availDisplay = Object.keys(output.data);
    for (const display of displayPriority){
        if (availDisplay.includes(display)) {
            return display;
        }
    }
    return null;
}
function displayDataIsImage(mimeType) {
    return [
        kImagePng,
        kImageJpeg,
        kImageSvg,
        kApplicationPdf
    ].includes(mimeType);
}
function displayDataIsTextPlain(mimeType) {
    return [
        kTextPlain
    ].includes(mimeType);
}
function displayDataIsMarkdown(mimeType) {
    return [
        kTextMarkdown
    ].includes(mimeType);
}
function displayDataIsLatex(mimeType) {
    return [
        kTextLatex
    ].includes(mimeType);
}
function displayDataIsHtml(mimeType) {
    return [
        kTextHtml
    ].includes(mimeType);
}
function displayDataIsJson(mimeType) {
    return [
        kApplicationJupyterWidgetState,
        kApplicationJupyterWidgetView
    ].includes(mimeType);
}
function displayDataIsJavascript(mimeType) {
    return [
        kApplicationJavascript
    ].includes(mimeType);
}
function cellLabel(cell) {
    const label = asHtmlId(cell.options[kCellLabel] || cell.metadata[kCellName] || "");
    if (label && !label.startsWith("#")) {
        return "#" + label;
    } else {
        return label;
    }
}
function cellLabelValidator() {
    const cellLabels = new Set();
    return function(cell) {
        const label = cellLabel(cell);
        if (label) {
            if (cellLabels.has(label)) {
                throw new Error("Cell label names must be unique (found duplicate '" + label + "')");
            } else {
                cellLabels.add(label);
            }
        }
    };
}
function shouldLabelCellContainer(cell, outputs, options) {
    if (!outputs) {
        return true;
    }
    if (!includeOutput(cell, options)) {
        return true;
    }
    const displayDataOutputs = outputs.filter(isDisplayData);
    if (displayDataOutputs.length === 0) {
        return true;
    }
    if (displayDataOutputs.length > 1 && !Array.isArray(cell.options[kCellFigCap])) {
        return true;
    }
    if (hasTableLabel(cell.options)) {
        return true;
    }
    return false;
}
function hasTableLabel(options) {
    return typeof options[kCellLabel] === "string" && options[kCellLabel]?.startsWith("tbl-");
}
function shouldLabelOutputContainer(output, cellOptions, options) {
    if (isDisplayData(output)) {
        if (hasTableLabel(cellOptions)) {
            return false;
        }
        if (!isCaptionableData(output)) {
            return false;
        }
        const mimeType = displayDataMimeType(output, options);
        if (mimeType) {
            if (displayDataIsImage(mimeType)) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}
function resolveCaptions(cell) {
    if (Array.isArray(cell.options[kCellFigCap])) {
        const figCap = cell.options[kCellFigCap];
        if (cell.outputs && cell.outputs.filter(isCaptionableData).length > 0) {
            return {
                cellCaption: undefined,
                outputCaptions: figCap
            };
        } else {
            return {
                cellCaption: undefined,
                outputCaptions: []
            };
        }
    } else if (cell.options[kCellFigCap]) {
        if (cell.options[kCellFigSubCap] !== undefined) {
            let subCap = cell.options[kCellFigSubCap];
            if (subCap === true) {
                subCap = [
                    ""
                ];
            }
            if (!Array.isArray(subCap)) {
                subCap = [
                    String(subCap)
                ];
            }
            return {
                cellCaption: cell.options[kCellFigCap],
                outputCaptions: subCap
            };
        } else {
            return {
                cellCaption: undefined,
                outputCaptions: [
                    cell.options[kCellFigCap]
                ]
            };
        }
    } else {
        return {
            cellCaption: undefined,
            outputCaptions: []
        };
    }
}
function extractJupyterWidgetDependencies(nb) {
    const jsWidgets = haveOutputType(nb, [
        kApplicationJavascript,
        kTextHtml
    ]);
    const jupyterWidgets = haveOutputType(nb, [
        kApplicationJupyterWidgetView
    ]);
    const htmlLibraries = [];
    nb.cells.forEach((cell)=>{
        if (cell.cell_type === "code") {
            cell.outputs = cell.outputs?.filter((output)=>{
                if (isDisplayData(output)) {
                    const displayOutput = output;
                    const html = displayOutput.data[kTextHtml];
                    const htmlText = Array.isArray(html) ? html.join("") : html;
                    if (html && isWidgetIncludeHtml(htmlText)) {
                        htmlLibraries.push(htmlText);
                        return false;
                    }
                }
                return true;
            });
        }
    });
    return {
        jsWidgets,
        jupyterWidgets,
        htmlLibraries,
        widgetsState: nb.metadata.widgets?.[kApplicationJupyterWidgetState]
    };
}
function includesForJupyterWidgetDependencies(dependencies, tempDir1) {
    let haveJavascriptWidgets = false;
    let haveJupyterWidgets = false;
    const htmlLibraries = [];
    let widgetsState;
    for (const dependency of dependencies){
        haveJavascriptWidgets = haveJavascriptWidgets || dependency.jsWidgets;
        haveJupyterWidgets = haveJupyterWidgets || dependency.jupyterWidgets;
        for (const htmlLib of dependency.htmlLibraries){
            if (!htmlLibraries.includes(htmlLib)) {
                htmlLibraries.push(htmlLib);
            }
        }
        if (dependency.widgetsState) {
            if (!widgetsState) {
                widgetsState = dependency.widgetsState;
            } else {
                widgetsState = mergeConfigs(widgetsState, dependency.widgetsState);
            }
        }
    }
    const head = [];
    if (haveJavascriptWidgets || haveJupyterWidgets) {
        head.push('<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>');
        head.push('<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>');
        head.push("<script type=\"application/javascript\">define('jquery', [],function() {return window.jQuery;})</script>");
    }
    head.push(...htmlLibraries);
    if (haveJupyterWidgets) {
        head.push('<script src="https://unpkg.com/@jupyter-widgets/html-manager@*/dist/embed-amd.js" crossorigin="anonymous"></script>');
    }
    const afterBody = [];
    if (haveJupyterWidgets && widgetsState) {
        afterBody.push(`<script type=${kApplicationJupyterWidgetState}>`);
        afterBody.push(JSON.stringify(widgetsState));
        afterBody.push("</script>");
    }
    const widgetTempFile = (lines1)=>{
        const tempFile = Deno.makeTempFileSync({
            dir: tempDir1,
            prefix: "jupyter-widgets-",
            suffix: ".html"
        });
        Deno.writeTextFileSync(tempFile, lines1.join("\n") + "\n");
        return tempFile;
    };
    const result = {
        inHeader: "",
        afterBody: ""
    };
    if (head.length > 0) {
        result.inHeader = widgetTempFile(head);
    }
    if (afterBody.length > 0) {
        result.afterBody = widgetTempFile(afterBody);
    }
    return result;
}
function haveOutputType(nb, mimeTypes) {
    return nb.cells.some((cell)=>{
        if (cell.cell_type === "code" && cell.outputs) {
            return cell.outputs.some((output)=>{
                if (isDisplayData(output)) {
                    const outputTypes = Object.keys(output.data);
                    return outputTypes.some((type)=>mimeTypes.includes(type)
                    );
                } else {
                    return false;
                }
            });
        } else {
            return false;
        }
    });
}
function isWidgetIncludeHtml(html) {
    return isPlotlyLibrary(html);
}
function isPlotlyLibrary(html) {
    return /^\s*<script type="text\/javascript">/.test(html) && (/require\.undef\(["']plotly["']\)/.test(html) || /define\('plotly'/.test(html));
}
function removeAndPreserveHtml(nb) {
    const htmlPreserve = {};
    nb.cells.forEach((cell)=>{
        if (cell.cell_type === "code") {
            cell.outputs?.forEach((output)=>{
                if (isDisplayData(output)) {
                    const displayOutput = output;
                    const html = displayOutput.data[kTextHtml];
                    const htmlText = Array.isArray(html) ? html.join("") : html;
                    if (html && isPreservedHtml(htmlText)) {
                        const key = "preserve" + generate().replaceAll("-", "");
                        htmlPreserve[key] = htmlText;
                        displayOutput.data[kTextMarkdown] = [
                            key
                        ];
                        displayOutput.noCaption = true;
                        delete displayOutput.data[kTextHtml];
                    }
                }
            });
        }
    });
    if (Object.keys(htmlPreserve).length > 0) {
        return htmlPreserve;
    } else {
        return undefined;
    }
}
function restorePreservedHtml(html, preserve) {
    if (preserve) {
        Object.keys(preserve).forEach((key)=>{
            const keyLoc = html.indexOf(key);
            html = html.slice(0, keyLoc) + preserve[key] + html.slice(keyLoc + key.length);
        });
    }
    return html;
}
function isPreservedHtml(_html) {
    return false;
}
function isWindows1() {
    return Deno.build.os === "windows";
}
function isMac() {
    return Deno.build.os === "darwin";
}
function isRStudio() {
    return !!Deno.env.get("RSTUDIO");
}
function isRStudioTerminal() {
    return !!Deno.env.get("RSTUDIO_TERM");
}
function isRStudioServer() {
    return isRStudio() && Deno.env.get("RSTUDIO_PROGRAM_MODE") === "server";
}
function isRStudioPreview() {
    return isRStudio() && !isRStudioTerminal();
}
function isJupyterHubServer() {
    return jupyterHubUser() !== undefined;
}
function jupyterHubHttpReferrer() {
    return Deno.env.get("JUPYTERHUB_HTTP_REFERER");
}
function jupyterHubUser() {
    return Deno.env.get("JUPYTERHUB_USER");
}
function isInteractiveTerminal() {
    return Deno.isatty(Deno.stderr.rid);
}
function isInteractiveSession() {
    return isRStudio() || isInteractiveTerminal();
}
let cachedJupyterCaps;
async function jupyterCapabilities() {
    if (!cachedJupyterCaps) {
        cachedJupyterCaps = await getQuartoJupyterCapabilities();
        if (cachedJupyterCaps) {
            return cachedJupyterCaps;
        }
        if (isWindows1() && pyPython()) {
            cachedJupyterCaps = await getPyLauncherJupyterCapabilities();
        }
        if (!cachedJupyterCaps) {
            cachedJupyterCaps = await getJupyterCapabilities([
                "python"
            ]);
            if (!cachedJupyterCaps?.conda) {
                const caps = isWindows1() ? await getPyLauncherJupyterCapabilities() : await getJupyterCapabilities([
                    "python3"
                ]);
                if (caps) {
                    cachedJupyterCaps = caps;
                }
            }
        }
    }
    return cachedJupyterCaps;
}
function getQuartoJupyterCapabilities() {
    const quartoJupyter = Deno.env.get("QUARTO_PYTHON");
    if (quartoJupyter) {
        if (existsSync(quartoJupyter)) {
            let quartoJupyterBin = quartoJupyter;
            if (Deno.statSync(quartoJupyter).isDirectory) {
                const bin1 = [
                    "python3",
                    "python",
                    "python3.exe",
                    "python.exe"
                ].find((bin)=>{
                    return existsSync(join3(quartoJupyter, bin));
                });
                if (bin1) {
                    quartoJupyterBin = join3(quartoJupyter, bin1);
                } else {
                    quartoJupyterBin = undefined;
                }
            }
            if (quartoJupyterBin) {
                return getJupyterCapabilities([
                    quartoJupyterBin
                ]);
            }
        }
        warning("Specified QUARTO_JUPYTER '" + quartoJupyter + "' does not exist.");
        return undefined;
    } else {
        return undefined;
    }
}
async function jupyterCapabilitiesNoConda() {
    const caps = await getQuartoJupyterCapabilities();
    if (caps && !caps.conda) {
        return caps;
    }
    if (isWindows1()) {
        return await getPyLauncherJupyterCapabilities();
    } else {
        const caps = await getJupyterCapabilities([
            "python3"
        ]);
        if (caps) {
            if (caps?.conda) {
                return await getJupyterCapabilities([
                    "/usr/local/bin/python3"
                ]) || await getJupyterCapabilities([
                    "/usr/bin/python3"
                ]);
            } else {
                return caps;
            }
        } else {
            return undefined;
        }
    }
}
function isEnvDir(dir) {
    return existsSync(join3(dir, "pyvenv.cfg")) || existsSync(join3(dir, "conda-meta"));
}
function pyPython() {
    return Deno.env.get("PY_PYTHON");
}
function getPyLauncherJupyterCapabilities() {
    return getJupyterCapabilities([
        "py"
    ], true);
}
async function getJupyterCapabilities(cmd, pyLauncher = false) {
    try {
        const result = await execProcess({
            cmd: [
                ...cmd,
                resourcePath("capabilities/jupyter.py"), 
            ],
            stdout: "piped",
            stderr: "piped"
        });
        if (result.success && result.stdout) {
            const caps = readYamlFromString(result.stdout);
            if (caps.versionMajor >= 3) {
                caps.pyLauncher = pyLauncher;
                return caps;
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    } catch  {
        return undefined;
    }
}
async function pythonExec(binaryOnly = false) {
    const caps = await jupyterCapabilities();
    if (caps?.pyLauncher) {
        return [
            "py"
        ];
    } else if (isWindows1()) {
        return [
            binaryOnly ? "python" : caps?.executable || "python"
        ];
    } else {
        return [
            binaryOnly ? "python3" : caps?.executable || "python3"
        ];
    }
}
async function jupyterExec() {
    return [
        ...await pythonExec(),
        "-m",
        "jupyter", 
    ];
}
function isJupyterKernelspec(x) {
    if (x && typeof x === "object") {
        return typeof x.name === "string" && typeof x.language === "string" && typeof x.display_name === "string";
    } else {
        return false;
    }
}
async function jupyterKernelspec(name83) {
    const kernelspecs = await jupyterKernelspecs();
    return kernelspecs.get(name83);
}
async function jupyterKernelspecs() {
    try {
        const result = await execProcess({
            cmd: [
                ...await jupyterExec(),
                "--paths",
                "--json"
            ],
            stdout: "piped",
            stderr: "piped"
        });
        if (result.success) {
            const kernelmap = new Map();
            const dataPaths = JSON.parse(result.stdout).data;
            for (const path68 of dataPaths){
                if (!existsSync(path68)) {
                    continue;
                }
                const kernels = join3(path68, "kernels");
                if (!existsSync(kernels)) {
                    continue;
                }
                for (const walk3 of walkSync(kernels, {
                    maxDepth: 1
                })){
                    if (walk3.path === kernels || !walk3.isDirectory) {
                        continue;
                    }
                    const kernelConfig = join3(walk3.path, "kernel.json");
                    if (existsSync(kernelConfig)) {
                        const config = JSON.parse(Deno.readTextFileSync(kernelConfig));
                        const name84 = basename2(walk3.path);
                        kernelmap.set(name84, {
                            name: name84,
                            language: config.language,
                            display_name: config.display_name
                        });
                    }
                }
            }
            if (kernelmap.size > 0) {
                return kernelmap;
            } else {
                return kDefaultKernelspecs;
            }
        } else {
            return kDefaultKernelspecs;
        }
    } catch (e) {
        debug("Error reading kernelspecs: " + e.message);
        return kDefaultKernelspecs;
    }
}
const kDefaultKernelspecs = new Map();
kDefaultKernelspecs.set("python3", {
    "display_name": "Python 3",
    "language": "python",
    "name": "python3"
});
function inputFilesDir(input) {
    const [_, stem] = dirAndStem(input);
    return stem + "_files";
}
function figuresDir(pandocTo) {
    if (pandocTo === "html4") {
        pandocTo = "html";
    }
    pandocTo = (pandocTo || "html").replace(/[\+\-].*$/, "");
    return "figure-" + pandocTo;
}
const kJupyterNotebookExtensions = [
    ".ipynb", 
];
function isJupyterNotebook(file) {
    return kJupyterNotebookExtensions.includes(extname2(file).toLowerCase());
}
const kJupyterCellInternalOptionKeys = [
    kEval,
    kEcho,
    kWarning,
    kOutput,
    kInclude,
    kCellLabel,
    kCellClasses,
    kCellPanel,
    kCellColumn,
    kCellFigCap,
    kCellFigSubCap,
    kCellFigScap,
    kFigCapLoc,
    kTblCapLoc,
    kCapLoc,
    kCellFigColumn,
    kCellTblColumn,
    kCellFigLink,
    kCellFigAlign,
    kCellFigAlt,
    kCellFigEnv,
    kCellFigPos,
    kCellLstLabel,
    kCellLstCap,
    kCellOutWidth,
    kCellOutHeight,
    kCellMdIndent,
    kCodeFold,
    kCodeLineNumbers,
    kCodeSummary,
    kCodeOverflow, 
];
const kJupyterCellOptionKeys = kJupyterCellInternalOptionKeys.concat([
    kLayoutAlign,
    kLayoutVAlign,
    kLayoutNcol,
    kLayoutNrow,
    kLayout,
    kTblColwidths, 
]);
const kJupyterCellStandardMetadataKeys = [
    kCellCollapsed,
    kCellAutoscroll,
    kCellDeletable,
    kCellFormat,
    kCellName, 
];
const kJupyterCellThirdPartyMetadataKeys = [
    kCellId,
    kCellColab,
    kCellColabType,
    kCellColbOutputId,
    kCellLinesToNext, 
];
async function quartoMdToJupyter(input, includeIds) {
    const [kernelspec, metadata] = await jupyterKernelspecFromFile(input);
    const nb = {
        cells: [],
        metadata: {
            kernelspec,
            ...metadata
        },
        nbformat: 4,
        nbformat_minor: includeIds ? 5 : 4
    };
    const yamlRegEx = /^---\s*$/;
    const startCodeCellRegEx = new RegExp("^(\\s*)```+\\s*\\{" + kernelspec.language.toLowerCase() + "( *[ ,].*)?\\}\\s*$");
    const startCodeRegEx = /^(\s*)```/;
    const endCodeRegEx = (indent = "")=>{
        return new RegExp("^" + indent + "```\\s*$");
    };
    const inputContent = Deno.readTextFileSync(input);
    let codeIndent = "";
    const lineBuffer = [];
    const flushLineBuffer = (cell_type, frontMatter)=>{
        if (lineBuffer.length) {
            if (lineBuffer[0] === "") {
                lineBuffer.splice(0, 1);
            }
            if (lineBuffer[lineBuffer.length - 1] === "") {
                lineBuffer.splice(lineBuffer.length - 1, 1);
            }
            if (cell_type !== "code") {
                codeIndent = "";
            }
            const cell = {
                cell_type,
                metadata: codeIndent.length > 0 ? {
                    [kCellMdIndent]: codeIndent
                } : {},
                source: lineBuffer.map((line, index)=>{
                    if (codeIndent.length > 0) {
                        line = line.replace(codeIndent, "");
                    }
                    return line + (index < lineBuffer.length - 1 ? "\n" : "");
                })
            };
            if (includeIds) {
                cell.id = shortUuid();
            }
            if (cell_type === "raw" && frontMatter) {
                const yaml = readYamlFromMarkdown(cell.source.join(""));
                if (yaml.jupyter) {
                    delete yaml.jupyter;
                    if (Object.keys(yaml).length > 0) {
                        const yamlFrontMatter = mdTrimEmptyLines(lines(stringify(yaml, {
                            indent: 2,
                            sortKeys: false,
                            skipInvalid: true
                        })));
                        cell.source = [
                            "---\n",
                            ...yamlFrontMatter.map((line)=>line + "\n"
                            ),
                            "---", 
                        ];
                    } else {
                        cell.source = [];
                    }
                }
            } else if (cell_type === "code") {
                const { yaml , source  } = partitionCellOptions(kernelspec.language.toLowerCase(), cell.source);
                if (yaml) {
                    if (includeIds && yaml[kCellLabel] && !yaml[kCellId]) {
                        yaml[kCellId] = jupyterAutoIdentifier(String(yaml[kCellLabel]));
                    }
                    const yamlKeys = Object.keys(yaml);
                    yamlKeys.forEach((key)=>{
                        if (key === kCellId) {
                            if (includeIds) {
                                cell.id = String(yaml[key]);
                            }
                            delete yaml[key];
                        } else {
                            if (!kJupyterCellOptionKeys.includes(key)) {
                                cell.metadata[key] = yaml[key];
                                delete yaml[key];
                            }
                        }
                    });
                    if (Object.keys(yaml).length < yamlKeys.length) {
                        const yamlOutput = jupyterCellOptionsAsComment(kernelspec.language.toLowerCase(), yaml);
                        cell.source = yamlOutput.concat(source);
                    }
                }
                cell.execution_count = null;
                cell.outputs = [];
            }
            cell.source = mdTrimEmptyLines(cell.source);
            if (cell.source.length > 0) {
                nb.cells.push(cell);
            }
            lineBuffer.splice(0, lineBuffer.length);
        }
    };
    let parsedFrontMatter = false, inYaml = false, inCodeCell = false, inCode = false;
    for (const line1 of lines(inputContent)){
        if (yamlRegEx.test(line1) && !inCodeCell && !inCode) {
            if (inYaml) {
                lineBuffer.push(line1);
                flushLineBuffer("raw", !parsedFrontMatter);
                parsedFrontMatter = true;
                inYaml = false;
            } else {
                flushLineBuffer("markdown");
                lineBuffer.push(line1);
                inYaml = true;
            }
        } else if (startCodeCellRegEx.test(line1)) {
            flushLineBuffer("markdown");
            inCodeCell = true;
            codeIndent = line1.match(startCodeCellRegEx)[1];
        } else if (endCodeRegEx(codeIndent).test(line1)) {
            if (inCodeCell) {
                inCodeCell = false;
                flushLineBuffer("code");
                codeIndent = "";
            } else {
                inCode = !inCode;
                codeIndent = "";
                lineBuffer.push(line1);
            }
        } else if (startCodeRegEx.test(line1)) {
            codeIndent = line1.match(startCodeRegEx)[1];
            inCode = true;
            lineBuffer.push(line1);
        } else {
            lineBuffer.push(line1);
        }
    }
    flushLineBuffer("markdown");
    return nb;
}
async function jupyterKernelspecFromFile(file) {
    const yaml = await readYamlFromMarkdownFile(file);
    const yamlJupyter = yaml.jupyter;
    if (!yamlJupyter) {
        const languages = languagesInMarkdownFile(file);
        languages.add("python");
        const kernelspecs = await jupyterKernelspecs();
        for (const language of languages){
            for (const kernelspec of kernelspecs.values()){
                if (kernelspec.language.toLowerCase() === language) {
                    return [
                        kernelspec,
                        {}
                    ];
                }
            }
        }
    }
    if (typeof yamlJupyter === "string") {
        const kernel = yamlJupyter;
        const kernelspec = await jupyterKernelspec(kernel);
        if (kernelspec) {
            return [
                kernelspec,
                {}
            ];
        } else {
            return Promise.reject(new Error("Jupyter kernel '" + kernel + "' not found."));
        }
    } else if (typeof yamlJupyter === "object") {
        const jupyter = {
            ...yamlJupyter
        };
        if (isJupyterKernelspec(jupyter.kernelspec)) {
            const kernelspec = jupyter.kernelspec;
            delete jupyter.kernelspec;
            return [
                kernelspec,
                jupyter
            ];
        } else if (typeof jupyter.kernel === "string") {
            const kernelspec = await jupyterKernelspec(jupyter.kernel);
            if (kernelspec) {
                delete jupyter.kernel;
                return [
                    kernelspec,
                    jupyter
                ];
            } else {
                return Promise.reject(new Error("Jupyter kernel '" + jupyter.kernel + "' not found."));
            }
        } else {
            return Promise.reject(new Error("Invalid Jupyter kernelspec (must include name, language, & display_name)"));
        }
    } else {
        return Promise.reject(new Error("Invalid jupyter YAML metadata found in file (must be string or object)"));
    }
}
function jupyterFromFile(input) {
    const nbContents = Deno.readTextFileSync(input);
    const nbJSON = JSON.parse(nbContents);
    const nb = nbJSON;
    if (!nb.metadata.kernelspec.language) {
        nb.metadata.kernelspec.language = nbJSON.metadata.language_info?.name;
    }
    if (!nb.metadata.kernelspec.language) {
        throw new Error("No langage set for Jupyter notebook " + input);
    }
    if (!nb.cells) {
        throw new Error("No cells available in Jupyter notebook " + input);
    }
    return nb;
}
function languagesInMarkdownFile(file) {
    return languagesInMarkdown(Deno.readTextFileSync(file));
}
function languagesInMarkdown(markdown) {
    const languages = new Set();
    const kChunkRegex = /^[\t >]*```+\s*\{([a-zA-Z0-9_]+)( *[ ,].*)?\}\s*$/gm;
    kChunkRegex.lastIndex = 0;
    let match = kChunkRegex.exec(markdown);
    while(match){
        const language = match[1].toLowerCase();
        if (!languages.has(language)) {
            languages.add(language);
        }
        match = kChunkRegex.exec(markdown);
    }
    kChunkRegex.lastIndex = 0;
    return languages;
}
function jupyterAutoIdentifier(label) {
    label = pandocAsciify(label);
    label = label.replace(/\s/g, "-").replace(/[^a-zA-Z0-9-_]/g, "").replace(/^[^A-Za-z]+/, "");
    if (label.length > 0) {
        return label.slice(0, 64);
    } else {
        return shortUuid();
    }
}
function jupyterAssets(input, to) {
    input = Deno.realPathSync(input);
    const files_dir = join3(dirname2(input), inputFilesDir(input));
    const figures_dir = join3(files_dir, figuresDir(to));
    ensureDirSync(figures_dir);
    let supporting_dir = files_dir;
    for (const walk4 of walkSync(join3(files_dir), {
        maxDepth: 1
    })){
        if (walk4.path !== files_dir && walk4.path !== figures_dir) {
            supporting_dir = figures_dir;
            break;
        }
    }
    const base_dir = dirname2(input);
    return {
        base_dir,
        files_dir: relative2(base_dir, files_dir),
        figures_dir: relative2(base_dir, figures_dir),
        supporting_dir: relative2(base_dir, supporting_dir)
    };
}
function jupyterToMarkdown(nb, options) {
    const isHtml = options.toHtml && !options.toIpynb;
    const dependencies = isHtml ? extractJupyterWidgetDependencies(nb) : undefined;
    const htmlPreserve = isHtml ? removeAndPreserveHtml(nb) : undefined;
    const md = [];
    const validateCellLabel = cellLabelValidator();
    let codeCellIndex = 0;
    for(let i63 = 0; i63 < nb.cells.length; i63++){
        const cell = jupyterCellWithOptions(nb.metadata.kernelspec.language.toLowerCase(), nb.cells[i63]);
        validateCellLabel(cell);
        const slideType = options.toPresentation ? cell.metadata[kCellSlideshow]?.[kCellSlideshowSlideType] : undefined;
        if (slideType) {
            if (slideType === "skip") {
                continue;
            } else if (slideType == "slide" || slideType === "subslide") {
                md.push("\n---\n\n");
            } else if (slideType == "fragment") {
                md.push("\n. . .\n\n");
            } else if (slideType == "notes") {
                md.push("\n:::::::::: notes\n\n");
            }
        }
        switch(cell.cell_type){
            case "markdown":
                md.push(...mdFromContentCell(cell));
                break;
            case "raw":
                md.push(...mdFromRawCell(cell));
                break;
            case "code":
                md.push(...mdFromCodeCell(cell, ++codeCellIndex, options));
                break;
            default:
                throw new Error("Unexpected cell type " + cell.cell_type);
        }
        if (slideType === "notes") {
            md.push("\n::::::::::\n");
        }
        md.push("\n");
    }
    if (options.toIpynb) {
        md.push("---\n");
        const jupyterMetadata = {
            jupyter: {
                ...nb.metadata
            }
        };
        const yamlText = stringify(jupyterMetadata, {
            indent: 2,
            sortKeys: false,
            skipInvalid: true
        });
        md.push(yamlText);
        md.push("---\n");
    }
    return {
        markdown: md.join(""),
        dependencies,
        htmlPreserve
    };
}
function jupyterCellWithOptions(language, cell) {
    const { yaml , optionsSource , source  } = partitionCellOptions(language, cell.source);
    const metadataOptions = kJupyterCellOptionKeys.reduce((options, key)=>{
        if (cell.metadata[key]) {
            options[key] = cell.metadata[key];
        }
        return options;
    }, {});
    const options1 = {
        ...metadataOptions,
        ...yaml
    };
    [
        kLayout,
        kTblColwidths
    ].forEach((option)=>{
        if (options1[option] && typeof options1[option] !== "string") {
            options1[option] = JSON.stringify(options1[option]);
        }
    });
    return {
        ...cell,
        source,
        optionsSource,
        options: options1
    };
}
function jupyterCellOptionsAsComment(language, options, stringifyOptions) {
    if (Object.keys(options).length > 0) {
        const cellYaml = stringify(options, {
            indent: 2,
            sortKeys: false,
            skipInvalid: true,
            ...stringifyOptions
        });
        const commentChars = langCommentChars1(language);
        const yamlOutput = mdTrimEmptyLines(lines(cellYaml)).map((line)=>{
            line = optionCommentPrefix1(commentChars[0]) + line + optionCommentSuffix(commentChars[1]);
            return line + "\n";
        });
        return yamlOutput;
    } else {
        return [];
    }
}
function mdFromContentCell(cell) {
    return mdEnsureTrailingNewline(cell.source);
}
function mdFromRawCell(cell) {
    const mimeType = cell.metadata?.[kCellRawMimeType];
    if (mimeType) {
        switch(mimeType){
            case kTextHtml:
                return mdHtmlOutput(cell.source);
            case kTextLatex:
                return mdLatexOutput(cell.source);
            case kRestructuredText:
                return mdFormatOutput("rst", cell.source);
            case kApplicationRtf:
                return mdFormatOutput("rtf", cell.source);
            case kApplicationJavascript:
                return mdScriptOutput(mimeType, cell.source);
        }
    }
    return mdFromContentCell(cell);
}
function mdEnsureTrailingNewline(source) {
    if (source.length > 0 && !source[source.length - 1].endsWith("\n")) {
        return source.slice(0, source.length - 1).concat([
            source[source.length - 1] + "\n"
        ]);
    } else {
        return source;
    }
}
function optionCommentPrefix1(comment) {
    return comment + "| ";
}
function optionCommentSuffix(comment) {
    if (comment) {
        return " " + comment;
    } else {
        return "";
    }
}
function langCommentChars1(lang) {
    const chars = kLangCommentChars1[lang] || "#";
    if (!Array.isArray(chars)) {
        return [
            chars
        ];
    } else {
        return chars;
    }
}
const kLangCommentChars1 = {
    r: "#",
    python: "#",
    julia: "#",
    scala: "//",
    matlab: "%",
    csharp: "//",
    fsharp: "//",
    c: [
        "/*",
        "*/"
    ],
    css: [
        "/*",
        "*/"
    ],
    sas: [
        "*",
        ";"
    ],
    powershell: "#",
    bash: "#",
    sql: "--",
    mysql: "--",
    psql: "--",
    lua: "--",
    cpp: "//",
    cc: "//",
    stan: "#",
    octave: "#",
    fortran: "!",
    fortran95: "!",
    awk: "#",
    gawk: "#",
    stata: "*",
    java: "//",
    groovy: "//",
    sed: "#",
    perl: "#",
    ruby: "#",
    tikz: "%",
    js: "//",
    d3: "//",
    node: "//",
    sass: "//",
    coffee: "#",
    go: "//",
    asy: "//",
    haskell: "--",
    dot: "//"
};
function mdFromCodeCell(cell, cellIndex, options) {
    if (!includeCell(cell, options)) {
        return [];
    }
    const outputs = (cell.outputs || []).filter((output)=>{
        if (output.output_type === "stream" && output.name === "stderr" && !includeWarnings(cell, options)) {
            return false;
        }
        if (output.output_type === "execute_result") {
            const textPlain = output.data?.[kTextPlain];
            if (textPlain && textPlain[0].startsWith("[<matplotlib")) {
                return false;
            }
        }
        return true;
    });
    if (!cell.source.length && !outputs.length) {
        return [];
    }
    const asis = cell.options[kOutput] === "asis" || options.execute[kOutput] === "asis" && cell.options[kOutput] === undefined;
    const md = [];
    const divMd = [
        `::: {`
    ];
    const kCellOptionsFilter = kJupyterCellInternalOptionKeys.concat(kJupyterCellStandardMetadataKeys, kJupyterCellThirdPartyMetadataKeys);
    const label = cellLabel(cell);
    const labelCellContainer = shouldLabelCellContainer(cell, outputs, options);
    if (label && labelCellContainer) {
        divMd.push(`${label} `);
    }
    const { cellCaption , outputCaptions  } = resolveCaptions(cell);
    divMd.push(`.cell `);
    if (hideCell(cell, options)) {
        divMd.push(`.hidden `);
    }
    if (cell.options[kCellClasses] || cell.options[kCellPanel] || cell.options[kCellColumn]) {
        const cellClasses = cell.options[kCellClasses] || new Array();
        const classes = Array.isArray(cellClasses) ? cellClasses : [
            cellClasses
        ];
        if (typeof cell.options[kCellPanel] === "string") {
            classes.push(`panel-${cell.options[kCellPanel]}`);
        }
        if (typeof cell.options[kCellColumn] === "string") {
            classes.push(`column-${cell.options[kCellColumn]}`);
        }
        if (typeof cell.options[kCellFigColumn] === "string") {
            classes.push(`fig-column-${cell.options[kCellFigColumn]}`);
        }
        if (typeof cell.options[kCellTblColumn] === "string") {
            classes.push(`tbl-column-${cell.options[kCellTblColumn]}`);
        }
        if (typeof cell.options[kCapLoc] === "string") {
            classes.push(`caption-${cell.options[kFigCapLoc]}`);
        }
        if (typeof cell.options[kFigCapLoc] === "string") {
            classes.push(`fig-cap-location-${cell.options[kFigCapLoc]}`);
        }
        if (typeof cell.options[kTblCapLoc] === "string") {
            classes.push(`tbl-cap-location-${cell.options[kTblCapLoc]}`);
        }
        const classText = classes.map((clz)=>{
            clz = toString1(clz);
            return clz.startsWith(".") ? clz : "." + clz;
        }).join(" ");
        divMd.push(classText + " ");
    }
    const cellOptions = {
        ...cell.metadata,
        ...cell.options
    };
    for (const key of Object.keys(cellOptions)){
        if (!kCellOptionsFilter.includes(key.toLowerCase())) {
            let value = cellOptions[key];
            if (value) {
                if (typeof value !== "string") {
                    value = JSON.stringify(value);
                }
                value = value.replaceAll("'", `\\'`);
                divMd.push(`${key}='${value}' `);
            }
        }
    }
    if (typeof cell.execution_count === "number") {
        divMd.push(`execution_count=${cell.execution_count} `);
    }
    const divBeginMd = divMd.join("").replace(/ $/, "").concat("}\n");
    if (includeCode(cell, options)) {
        const fenced = echoFenced(cell, options);
        const ticks = fenced ? "````" : "```";
        md.push(ticks + " {");
        if (typeof cell.options[kCellLstLabel] === "string") {
            let label = cell.options[kCellLstLabel];
            if (!label.startsWith("#")) {
                label = "#" + label;
            }
            md.push(label + " ");
        }
        if (!fenced) {
            md.push("." + options.language);
        }
        md.push(" .cell-code");
        if (hideCode(cell, options)) {
            md.push(" .hidden");
        }
        if (cell.options[kCodeOverflow] === "wrap") {
            md.push(" .code-overflow-wrap");
        } else if (cell.options[kCodeOverflow] === "scroll") {
            md.push(" .code-overflow-scroll");
        }
        if (typeof cell.options[kCellLstCap] === "string") {
            md.push(` caption=\"${cell.options[kCellLstCap]}\"`);
        }
        if (typeof cell.options[kCodeFold] !== "undefined") {
            md.push(` code-fold=\"${cell.options[kCodeFold]}\"`);
        }
        if (typeof cell.options[kCodeSummary] !== "undefined") {
            md.push(` code-summary=\"${cell.options[kCodeSummary]}\"`);
        }
        if (typeof cell.options[kCodeLineNumbers] !== "undefined") {
            md.push(` code-line-numbers=\"${cell.options[kCodeLineNumbers]}\"`);
        }
        md.push("}\n");
        let source = __VIRTUAL_FILE107(cell.source);
        if (fenced) {
            const optionsSource = cell.optionsSource.filter((line)=>line.search(/echo:\s+fenced/) === -1
            );
            if (optionsSource.length > 0) {
                source = mdTrimEmptyLines(source, "trailing");
            } else {
                source = mdTrimEmptyLines(source, "all");
            }
            source.unshift(...optionsSource);
            source.unshift("```{{" + options.language + "}}\n");
            source.push("\n```\n");
        } else if (cell.optionsSource.length > 0) {
            source = mdTrimEmptyLines(source, "leading");
        }
        md.push(...source, "\n");
        md.push(ticks + "\n");
    }
    if (includeOutput(cell, options)) {
        const labelName = label ? label.replace(/^#/, "").replaceAll(":", "-") : "cell-" + (cellIndex + 1);
        const outputName = pandocAutoIdentifier(labelName, true) + "-output";
        let nextOutputSuffix = 1;
        for (const { index: index1 , output  } of outputs.map((value, index)=>({
                index,
                output: value
            })
        )){
            const outputLabel = label && labelCellContainer && isDisplayData(output) ? label + "-" + nextOutputSuffix++ : label;
            if (!asis) {
                md.push("\n::: {");
                if (outputLabel && shouldLabelOutputContainer(output, cell.options, options)) {
                    md.push(outputLabel + " ");
                }
                if (output.output_type === "stream") {
                    const stream = output;
                    md.push(`.cell-output-${stream.name}`);
                } else {
                    md.push(`.${outputTypeCssClass(output.output_type)}`);
                }
                if (hideOutput(cell, options) || isWarningOutput(output) && hideWarnings(cell, options)) {
                    md.push(` .hidden`);
                }
                if (typeof output.execution_count === "number") {
                    md.push(` execution_count=${output.execution_count}`);
                }
                md.push("}\n");
            }
            if (options.toLatex && !options.figPos && !cell.options[kCellFigPos] && !hasLayoutOptions(cell) && includeCode(cell, options)) {
                cell.options[kCellFigPos] = "H";
            }
            const figureOptions = {};
            const broadcastFigureOption = (name85)=>{
                const value = cell.options[name85];
                if (value) {
                    if (Array.isArray(value)) {
                        return value[index1];
                    } else {
                        return value;
                    }
                } else {
                    return null;
                }
            };
            figureOptions[kCellFigAlign] = broadcastFigureOption(kCellFigAlign);
            figureOptions[kCellFigScap] = broadcastFigureOption(kCellFigScap);
            figureOptions[kCellFigLink] = broadcastFigureOption(kCellFigLink);
            figureOptions[kCellFigEnv] = broadcastFigureOption(kCellFigEnv);
            figureOptions[kCellFigPos] = broadcastFigureOption(kCellFigPos);
            figureOptions[kCellFigAlt] = broadcastFigureOption(kCellFigAlt);
            if (output.output_type === "stream") {
                const stream = output;
                if (asis && stream.name === "stdout") {
                    md.push(stream.text.join(""));
                } else {
                    md.push(mdOutputStream(stream));
                }
            } else if (output.output_type === "error") {
                md.push(mdOutputError(output));
            } else if (isDisplayData(output)) {
                const caption = isCaptionableData(output) ? outputCaptions.shift() || null : null;
                md.push(mdOutputDisplayData(outputLabel, caption, outputName + "-" + (index1 + 1), output, options, figureOptions));
                if (caption && !isImage(output, options)) {
                    md.push(`\n${caption}\n`);
                }
            } else {
                throw new Error("Unexpected output type " + output.output_type);
            }
            if (!asis) {
                md.push(`:::\n`);
            }
        }
    } else if (cell.outputs) {
        cell.outputs.filter(isDisplayData).filter((output)=>output.metadata.ojs_define
        ).forEach((ojs_define)=>{
            const ojs_html = ojs_define.data[kTextHtml];
            md.push("\n" + mdHtmlOutput(ojs_html));
        });
    }
    if (md.length > 0 && !asis) {
        md.unshift(divBeginMd);
        if (cellCaption) {
            md.push("\n" + cellCaption + "\n");
        }
        md.push(":::\n");
    }
    md.push("\n".repeat(cell.metadata.lines_to_next_cell || 1));
    if (cell.options[kCellMdIndent]) {
        const indent = String(cell.options[kCellMdIndent]);
        const mdWithIndent = md.join("").split("\n").map((line)=>indent + line
        ).join("\n");
        md.splice(0, md.length - 1);
        md.push(...mdWithIndent);
    }
    return md;
}
function hasLayoutOptions(cell) {
    return Object.keys(cell.options).some((key)=>key.startsWith("layout")
    );
}
function isDisplayDataType(output, options, checkFn) {
    if (isDisplayData(output)) {
        const mimeType = displayDataMimeType(output, options);
        if (mimeType) {
            if (checkFn(mimeType)) {
                return true;
            }
        }
    }
    return false;
}
function isImage(output, options) {
    return isDisplayDataType(output, options, displayDataIsImage);
}
function mdOutputStream(output) {
    if (output.name === "stderr") {
        if (output.text[0]) {
            const firstLine = output.text[0].replace(/<ipython-input.*?>:\d+:\s+/, "");
            return mdCodeOutput([
                firstLine,
                ...output.text.slice(1)
            ]);
        }
    }
    return mdCodeOutput(output.text);
}
function mdOutputError(output) {
    return mdCodeOutput([
        output.ename + ": " + output.evalue
    ]);
}
function mdOutputDisplayData(label, caption, filename, output, options, figureOptions) {
    const mimeType = displayDataMimeType(output, options);
    if (mimeType) {
        if (displayDataIsImage(mimeType)) {
            return mdImageOutput(label, caption, filename, mimeType, output, options, figureOptions);
        } else if (displayDataIsMarkdown(mimeType)) {
            return mdMarkdownOutput(output.data[mimeType]);
        } else if (displayDataIsLatex(mimeType)) {
            return mdLatexOutput(output.data[mimeType]);
        } else if (displayDataIsHtml(mimeType)) {
            return mdHtmlOutput(output.data[mimeType]);
        } else if (displayDataIsJson(mimeType)) {
            return mdJsonOutput(mimeType, output.data[mimeType], options);
        } else if (displayDataIsJavascript(mimeType)) {
            return mdScriptOutput(mimeType, output.data[mimeType]);
        } else if (displayDataIsTextPlain(mimeType)) {
            const lines1 = output.data[mimeType];
            if (lines1.length === 1 && lines1[0].startsWith("'<table") && lines1[0].endsWith("</table>'")) {
                lines1[0] = lines1[0].slice(1, -1);
                return mdMarkdownOutput(lines1);
            } else {
                return mdCodeOutput(lines1);
            }
        }
    }
    return mdWarningOutput("Unable to display output for mime type(s): " + Object.keys(output.data).join(", "));
}
function mdImageOutput(label, caption, filename, mimeType, output, options, figureOptions) {
    const data47 = output.data[mimeType];
    const metadata = output.metadata[mimeType];
    function metadataValue(key, defaultValue) {
        return metadata && metadata[key] ? metadata["key"] : defaultValue;
    }
    let width = metadataValue(kCellOutWidth, 0);
    let height = metadataValue(kCellOutHeight, 0);
    const alt = caption || "";
    const ext = extensionForMimeImageType(mimeType);
    const imageFile = options.assets.figures_dir + "/" + filename + "." + ext;
    const imageText = Array.isArray(data47) ? data47.join("") : data47;
    const outputFile = join3(options.assets.base_dir, imageFile);
    if (mimeType !== kImageSvg) {
        const imageData = decode(imageText);
        if (mimeType === kImagePng && options.figFormat === "retina" && options.figDpi) {
            const png = new PngImage(imageData);
            if (png.dpiX === options.figDpi * 2 && png.dpiY === options.figDpi * 2) {
                width = Math.round(png.width / 2);
                height = Math.round(png.height / 2);
            }
        }
        Deno.writeFileSync(outputFile, imageData);
    } else {
        Deno.writeTextFileSync(outputFile, imageText);
    }
    let image1 = `![${alt}](${imageFile})`;
    if (label || width || height) {
        image1 += "{";
        if (label) {
            image1 += `${label} `;
        }
        if (width) {
            image1 += `width=${width} `;
        }
        if (height) {
            image1 += `height=${height} `;
        }
        [
            kCellFigAlign,
            kCellFigEnv,
            kCellFigAlt,
            kCellFigPos,
            kCellFigScap
        ].forEach((attrib)=>{
            const value = figureOptions[attrib];
            if (value) {
                image1 += `${attrib}='${value}' `;
            }
        });
        image1 = image1.trimRight() + "}";
    }
    if (figureOptions[kCellFigLink]) {
        image1 = `[${image1}](${figureOptions[kCellFigLink]})`;
    }
    return mdMarkdownOutput([
        image1
    ]);
}
function mdMarkdownOutput(md) {
    return md.join("") + "\n";
}
function mdFormatOutput(format28, source) {
    return mdEnclosedOutput("```{=" + format28 + "}", source, "```");
}
function mdLatexOutput(latex) {
    return mdFormatOutput("tex", latex);
}
function mdHtmlOutput(html) {
    return mdFormatOutput("html", html);
}
function mdJsonOutput(mimeType, json2, options) {
    if (options.toIpynb) {
        return mdCodeOutput([
            JSON.stringify(json2)
        ], "json");
    } else {
        return mdScriptOutput(mimeType, [
            JSON.stringify(json2)
        ]);
    }
}
function mdScriptOutput(mimeType, script) {
    const scriptTag = [
        `<script type="${mimeType}">\n`,
        ...script,
        "\n</script>", 
    ];
    return mdHtmlOutput(scriptTag);
}
function mdTrimEmptyLines(lines2, trim = "all") {
    if (trim === "all" || trim === "leading") {
        const firstNonEmpty = lines2.findIndex((line)=>line.trim().length > 0
        );
        if (firstNonEmpty === -1) {
            return [];
        }
        lines2 = lines2.slice(firstNonEmpty);
    }
    if (trim === "all" || trim === "trailing") {
        let lastNonEmpty = -1;
        for(let i64 = lines2.length - 1; i64 >= 0; i64--){
            if (lines2[i64].trim().length > 0) {
                lastNonEmpty = i64;
                break;
            }
        }
        if (lastNonEmpty > -1) {
            lines2 = lines2.slice(0, lastNonEmpty + 1);
        }
    }
    return lines2;
}
function mdCodeOutput(code20, clz) {
    const open = "```" + (clz ? `{.${clz}}` : "");
    return mdEnclosedOutput(open, code20, "```");
}
function mdEnclosedOutput(begin, text, end) {
    const output = text.join("");
    const md = [
        begin + "\n",
        output + (output.endsWith("\n") ? "" : "\n"),
        end + "\n", 
    ];
    return md.join("");
}
function mdWarningOutput(msg) {
    return mdOutputStream({
        output_type: "stream",
        name: "stderr",
        text: [
            msg
        ]
    });
}
function isWarningOutput(output) {
    if (output.output_type === "stream") {
        const stream = output;
        return stream.name === "stderr";
    } else {
        return false;
    }
}
function outputTypeCssClass(output_type) {
    if ([
        "display_data",
        "execute_result"
    ].includes(output_type)) {
        output_type = "display";
    }
    return `cell-output-${output_type}`;
}
function pandocAttrParseText(attr) {
    attr = attr.trim();
    let id = "";
    const classes = [];
    let remainder = "";
    let current = "";
    const resolveCurrent = ()=>{
        const resolve4 = current;
        current = "";
        if (resolve4.length === 0) {
            return true;
        } else if (resolve4.startsWith("#")) {
            if (id.length === 0 && resolve4.length > 1) {
                id = resolve4.substr(1);
                return true;
            } else {
                return false;
            }
        } else if (resolve4.startsWith(".")) {
            if (resolve4.length > 1) {
                classes.push(resolve4.substr(1));
                return true;
            } else {
                return false;
            }
        } else if (resolve4 === "-") {
            classes.push("unnumbered");
            return true;
        } else {
            remainder = resolve4;
            return true;
        }
    };
    for(let i65 = 0; i65 < attr.length; i65++){
        let inQuotes = false;
        const ch = attr[i65];
        inQuotes = ch === '"' ? !inQuotes : inQuotes;
        if (ch !== " " && !inQuotes) {
            current += ch;
        } else if (resolveCurrent()) {
            if (remainder.length > 0) {
                remainder = remainder + attr.substr(i65);
                break;
            }
        } else {
            return null;
        }
    }
    if (resolveCurrent()) {
        if (id.length === 0 && classes.length === 0) {
            remainder = attr;
        }
        return {
            id,
            classes,
            keyvalue: remainder.length > 0 ? pandocAttrKeyvalueFromText(remainder, " ") : []
        };
    } else {
        return null;
    }
}
function pandocAttrKeyvalueFromText(text, separator) {
    if (separator === " ") {
        let convertedText = "";
        let inQuotes = false;
        for(let i66 = 0; i66 < text.length; i66++){
            let ch = text.charAt(i66);
            if (ch === '"') {
                inQuotes = !inQuotes;
            } else if (ch === " " && !inQuotes) {
                ch = "\n";
            }
            convertedText += ch;
        }
        text = convertedText;
    }
    const lines2 = text.trim().split("\n");
    return lines2.map((line)=>{
        const parts = line.trim().split("=");
        return [
            parts[0],
            (parts[1] || "").replace(/^"/, "").replace(/"$/, "")
        ];
    });
}
function parsePandocTitle(title1) {
    title1 = title1 ? title1.trim() : title1;
    let beginAttrPos = -1;
    let previousCh = undefined;
    let state39 = "none";
    for(let i67 = title1.length - 1; i67 > -1; i67--){
        const ch = title1.charAt(i67);
        if (previousCh === undefined && ch !== "}") {
            break;
        }
        if (previousCh === undefined && ch === "}") {
            state39 = "scanning";
            previousCh = ch;
            continue;
        }
        if (state39 === "scanning") {
            if ([
                "/",
                "}",
                "]"
            ].includes(ch)) {
                break;
            }
            state39 = "reading";
            previousCh = ch;
            continue;
        }
        if (state39 === "reading") {
            if (![
                "/"
            ].includes(ch) && previousCh === "{") {
                beginAttrPos = i67 + 1;
                break;
            }
            previousCh = ch;
        }
    }
    let markdownHeading = beginAttrPos !== -1 ? title1.slice(0, beginAttrPos) : title1;
    markdownHeading = markdownHeading.trim().replace(/^#{1,}\s*/, "");
    let markdownHeadingAttr;
    if (beginAttrPos !== -1) {
        const endAttrPos = title1.lastIndexOf("}");
        if (endAttrPos !== -1) {
            const attr = title1.slice(beginAttrPos + 1, endAttrPos);
            const parsed = pandocAttrParseText(attr);
            if (parsed) {
                markdownHeadingAttr = parsed;
            }
        }
    }
    return {
        heading: markdownHeading,
        attr: markdownHeadingAttr
    };
}
function partitionMarkdown(markdown) {
    const markdownLines = [];
    let markdownHeading;
    let markdownHeadingAttr;
    let markdownContainsRefs = false;
    const partitioned = partitionYamlFrontMatter(markdown);
    markdown = partitioned ? partitioned.markdown : markdown;
    for (const line of lines(markdown)){
        if (!markdownContainsRefs) {
            markdownContainsRefs = /^:::\s*{#refs([\s}]|.*?})\s*$/.test(line);
        }
        if (!markdownHeading) {
            if (line.startsWith("#")) {
                const parsedHeading = parsePandocTitle(line);
                markdownHeading = parsedHeading.heading;
                markdownHeadingAttr = parsedHeading.attr;
            } else if (line.match(/^=+\s*$/) || line.match(/^-+\s*$/)) {
                const prevLine = markdownLines[markdownLines.length - 1];
                if (prevLine) {
                    markdownHeading = prevLine;
                    markdownLines.splice(markdownLines.length - 1);
                } else {
                    markdownLines.push(line);
                }
            } else {
                markdownLines.push(line);
            }
        } else {
            markdownLines.push(line);
        }
    }
    return {
        yaml: partitioned ? readYamlFromMarkdown(partitioned.yaml) : undefined,
        headingText: markdownHeading,
        headingAttr: markdownHeadingAttr,
        containsRefs: markdownContainsRefs,
        markdown: markdownLines.join("\n")
    };
}
async function knitrCapabilities() {
    try {
        const result = await execProcess({
            cmd: [
                await rBinaryPath("Rscript"),
                resourcePath("capabilities/knitr.R"), 
            ],
            stdout: "piped"
        });
        if (result.success && result.stdout) {
            const caps = readYamlFromString(result.stdout);
            return caps;
        } else {
            return undefined;
        }
    } catch  {
        return undefined;
    }
}
function knitrCapabilitiesMessage(caps, indent = "") {
    const lines3 = [
        `Version: ${caps.versionMajor}.${caps.versionMinor}.${caps.versionPatch}`,
        `Path: ${caps.home}`,
        `LibPaths:`, 
    ];
    for (const path69 of caps.libPaths){
        lines3.push(`  - ${path69}`);
    }
    lines3.push(`rmarkdown: ${caps.rmarkdown || "(None)"}`);
    return lines3.map((line)=>`${indent}${line}`
    ).join("\n");
}
function knitrInstallationMessage(indent = "") {
    const lines4 = [
        "The rmarkdown package is not available in this R installation.",
        "Install with " + bold('install.packages("rmarkdown")'), 
    ];
    return lines4.map((line)=>`${indent}${line}`
    ).join("\n");
}
function rInstallationMessage(indent = "") {
    const lines5 = [
        "Unable to locate an installed version of R.",
        "Install R from " + bold("https://cloud.r-project.org/"), 
    ];
    return lines5.map((line)=>`${indent}${line}`
    ).join("\n");
}
const kQmdExtensions = [
    ".qmd"
];
const kMarkdownEngine = "markdown";
const kKnitrEngine = "knitr";
const kJupyterEngine = "jupyter";
function postProcessRestorePreservedHtml(options) {
    const outputPath = join3(dirname2(options.target.input), options.output);
    let output = Deno.readTextFileSync(outputPath);
    output = restorePreservedHtml(output, options.preserve);
    Deno.writeTextFileSync(outputPath, output);
}
const kRmdExtensions = [
    ".rmd",
    ".rmarkdown"
];
const knitrEngine = {
    name: kKnitrEngine,
    defaultExt: ".qmd",
    defaultYaml: ()=>[]
    ,
    defaultContent: ()=>[
            "```{r}",
            "1 + 1",
            "```", 
        ]
    ,
    validExtensions: ()=>kRmdExtensions.concat(kRmdExtensions)
    ,
    claimsExtension: (ext)=>{
        return kRmdExtensions.includes(ext.toLowerCase());
    },
    claimsLanguage: (language)=>{
        return language.toLowerCase() === "r";
    },
    target: (file, _quiet)=>{
        const markdown = Deno.readTextFileSync(file);
        return Promise.resolve({
            source: file,
            input: file,
            markdown,
            metadata: readYamlFromMarkdown(markdown)
        });
    },
    partitionedMarkdown: (file)=>{
        return Promise.resolve(partitionMarkdown(Deno.readTextFileSync(file)));
    },
    execute: (options)=>{
        return callR("execute", {
            ...options,
            target: undefined,
            input: options.target.input
        }, options.tempDir, options.quiet);
    },
    dependencies: (options)=>{
        return callR("dependencies", {
            ...options,
            target: undefined,
            input: options.target.input
        }, options.tempDir, options.quiet);
    },
    postprocess: async (options)=>{
        postProcessRestorePreservedHtml(options);
        if (options.format.render?.[kCodeLink]) {
            await callR("postprocess", {
                ...options,
                target: undefined,
                preserve: undefined,
                input: options.target.input
            }, options.tempDir, options.quiet, false).then(()=>{
                return Promise.resolve();
            }, ()=>{
                warning(`Unable to perform code-link (code-link requires R and the downlit package)`);
                return Promise.resolve();
            });
        }
    },
    canFreeze: true,
    generatesFigures: true,
    ignoreDirs: ()=>{
        return [
            "renv",
            "packrat",
            "rsconnect"
        ];
    },
    run: (options)=>{
        return callR("run", options, options.tempDir);
    }
};
async function callR(action, params, tempDir2, quiet, reportError = true) {
    const resultsFile = Deno.makeTempFileSync({
        dir: tempDir2,
        prefix: "r-results",
        suffix: ".json"
    });
    const input = JSON.stringify({
        action,
        params,
        results: resultsFile
    });
    try {
        const result = await execProcess({
            cmd: [
                await rBinaryPath("Rscript"),
                resourcePath("rmd/rmd.R"), 
            ],
            stderr: quiet ? "piped" : "inherit"
        }, input, "stdout>stderr", red);
        if (result.success) {
            const results = await Deno.readTextFile(resultsFile);
            await Deno.remove(resultsFile);
            const resultsJson = JSON.parse(results);
            return resultsJson;
        } else {
            if (quiet) {
                error(result.stderr || "");
            }
            if (reportError) {
                await printCallRDiagnostics();
            }
            return Promise.reject();
        }
    } catch (e) {
        if (reportError) {
            if (e?.message) {
                info("");
                error(e.message);
            }
            await printCallRDiagnostics();
        }
        return Promise.reject();
    }
}
async function printCallRDiagnostics() {
    const caps = await knitrCapabilities();
    if (caps && !caps.rmarkdown) {
        info("");
        info("R installation:");
        info(knitrCapabilitiesMessage(caps, "  "));
        info("");
        info(knitrInstallationMessage());
        info("");
    } else if (!caps) {
        info("");
        info(rInstallationMessage());
        info("");
    }
}
function runningInCI() {
    if ([
        "CI",
        "CONTINUOUS_INTEGRATION",
        "BUILD_NUMBER",
        "RUN_ID"
    ].some(checkEnv)) {
        return true;
    }
    return vendors.some((vendor)=>{
        const envs = Array.isArray(vendor.env) ? vendor.env : [
            vendor.env
        ];
        return envs.some(checkEnv);
    });
}
function checkEnv(obj) {
    if (typeof obj === "string") {
        return !!Deno.env.get(obj);
    } else {
        return Object.keys(obj).every(function(k) {
            return Deno.env.get(k) === obj[k];
        });
    }
}
const vendors = [
    {
        "name": "AppVeyor",
        "constant": "APPVEYOR",
        "env": "APPVEYOR",
        "pr": "APPVEYOR_PULL_REQUEST_NUMBER"
    },
    {
        "name": "Azure Pipelines",
        "constant": "AZURE_PIPELINES",
        "env": "SYSTEM_TEAMFOUNDATIONCOLLECTIONURI",
        "pr": "SYSTEM_PULLREQUEST_PULLREQUESTID"
    },
    {
        "name": "Appcircle",
        "constant": "APPCIRCLE",
        "env": "AC_APPCIRCLE"
    },
    {
        "name": "Bamboo",
        "constant": "BAMBOO",
        "env": "bamboo_planKey"
    },
    {
        "name": "Bitbucket Pipelines",
        "constant": "BITBUCKET",
        "env": "BITBUCKET_COMMIT",
        "pr": "BITBUCKET_PR_ID"
    },
    {
        "name": "Bitrise",
        "constant": "BITRISE",
        "env": "BITRISE_IO",
        "pr": "BITRISE_PULL_REQUEST"
    },
    {
        "name": "Buddy",
        "constant": "BUDDY",
        "env": "BUDDY_WORKSPACE_ID",
        "pr": "BUDDY_EXECUTION_PULL_REQUEST_ID"
    },
    {
        "name": "Buildkite",
        "constant": "BUILDKITE",
        "env": "BUILDKITE",
        "pr": {
            "env": "BUILDKITE_PULL_REQUEST",
            "ne": "false"
        }
    },
    {
        "name": "CircleCI",
        "constant": "CIRCLE",
        "env": "CIRCLECI",
        "pr": "CIRCLE_PULL_REQUEST"
    },
    {
        "name": "Cirrus CI",
        "constant": "CIRRUS",
        "env": "CIRRUS_CI",
        "pr": "CIRRUS_PR"
    },
    {
        "name": "AWS CodeBuild",
        "constant": "CODEBUILD",
        "env": "CODEBUILD_BUILD_ARN"
    },
    {
        "name": "Codefresh",
        "constant": "CODEFRESH",
        "env": "CF_BUILD_ID",
        "pr": {
            "any": [
                "CF_PULL_REQUEST_NUMBER",
                "CF_PULL_REQUEST_ID"
            ]
        }
    },
    {
        "name": "Codeship",
        "constant": "CODESHIP",
        "env": {
            "CI_NAME": "codeship"
        }
    },
    {
        "name": "Drone",
        "constant": "DRONE",
        "env": "DRONE",
        "pr": {
            "DRONE_BUILD_EVENT": "pull_request"
        }
    },
    {
        "name": "dsari",
        "constant": "DSARI",
        "env": "DSARI"
    },
    {
        "name": "GitHub Actions",
        "constant": "GITHUB_ACTIONS",
        "env": "GITHUB_ACTIONS",
        "pr": {
            "GITHUB_EVENT_NAME": "pull_request"
        }
    },
    {
        "name": "GitLab CI",
        "constant": "GITLAB",
        "env": "GITLAB_CI",
        "pr": "CI_MERGE_REQUEST_ID"
    },
    {
        "name": "GoCD",
        "constant": "GOCD",
        "env": "GO_PIPELINE_LABEL"
    },
    {
        "name": "LayerCI",
        "constant": "LAYERCI",
        "env": "LAYERCI",
        "pr": "LAYERCI_PULL_REQUEST"
    },
    {
        "name": "Hudson",
        "constant": "HUDSON",
        "env": "HUDSON_URL"
    },
    {
        "name": "Jenkins",
        "constant": "JENKINS",
        "env": [
            "JENKINS_URL",
            "BUILD_ID"
        ],
        "pr": {
            "any": [
                "ghprbPullId",
                "CHANGE_ID"
            ]
        }
    },
    {
        "name": "Magnum CI",
        "constant": "MAGNUM",
        "env": "MAGNUM"
    },
    {
        "name": "Netlify CI",
        "constant": "NETLIFY",
        "env": "NETLIFY",
        "pr": {
            "env": "PULL_REQUEST",
            "ne": "false"
        }
    },
    {
        "name": "Nevercode",
        "constant": "NEVERCODE",
        "env": "NEVERCODE",
        "pr": {
            "env": "NEVERCODE_PULL_REQUEST",
            "ne": "false"
        }
    },
    {
        "name": "Render",
        "constant": "RENDER",
        "env": "RENDER",
        "pr": {
            "IS_PULL_REQUEST": "true"
        }
    },
    {
        "name": "Sail CI",
        "constant": "SAIL",
        "env": "SAILCI",
        "pr": "SAIL_PULL_REQUEST_NUMBER"
    },
    {
        "name": "Semaphore",
        "constant": "SEMAPHORE",
        "env": "SEMAPHORE",
        "pr": "PULL_REQUEST_NUMBER"
    },
    {
        "name": "Screwdriver",
        "constant": "SCREWDRIVER",
        "env": "SCREWDRIVER",
        "pr": {
            "env": "SD_PULL_REQUEST",
            "ne": "false"
        }
    },
    {
        "name": "Shippable",
        "constant": "SHIPPABLE",
        "env": "SHIPPABLE",
        "pr": {
            "IS_PULL_REQUEST": "true"
        }
    },
    {
        "name": "Solano CI",
        "constant": "SOLANO",
        "env": "TDDIUM",
        "pr": "TDDIUM_PR_ID"
    },
    {
        "name": "Strider CD",
        "constant": "STRIDER",
        "env": "STRIDER"
    },
    {
        "name": "TaskCluster",
        "constant": "TASKCLUSTER",
        "env": [
            "TASK_ID",
            "RUN_ID"
        ]
    },
    {
        "name": "TeamCity",
        "constant": "TEAMCITY",
        "env": "TEAMCITY_VERSION"
    },
    {
        "name": "Travis CI",
        "constant": "TRAVIS",
        "env": "TRAVIS",
        "pr": {
            "env": "TRAVIS_PULL_REQUEST",
            "ne": "false"
        }
    },
    {
        "name": "Vercel",
        "constant": "VERCEL",
        "env": "NOW_BUILDER"
    },
    {
        "name": "Visual Studio App Center",
        "constant": "APPCENTER",
        "env": "APPCENTER_BUILD_ID"
    }, 
];
const sleep = (delay)=>{
    return new Promise((resolve5)=>{
        setTimeout(resolve5, delay);
    });
};
async function jupyterCapabilitiesMessage(caps, indent = "") {
    const lines6 = [
        `Version: ${caps.versionMajor}.${caps.versionMinor}.${caps.versionPatch}${caps.conda ? " (Conda)" : ""}`,
        `Path: ${caps.executable}`,
        `Jupyter: ${caps.jupyter_core || "(None)"}`, 
    ];
    if (caps.jupyter_core) {
        const kernels = Array.from((await jupyterKernelspecs()).values()).map((kernel)=>kernel.name
        ).join(", ");
        lines6.push(`Kernels: ${kernels}`);
    }
    return lines6.map((line)=>`${indent}${line}`
    ).join("\n");
}
async function jupyterInstallationMessage(caps, indent = "") {
    const lines7 = [
        "Jupyter is not available in this Python installation.",
        "Install with " + bold(`${caps.conda ? "conda" : (await pythonExec(true)).join(" ") + " -m pip"} install jupyter`), 
    ];
    return lines7.map((line)=>`${indent}${line}`
    ).join("\n");
}
function jupyterUnactivatedEnvMessage(caps, indent = "") {
    for (const path70 of Deno.readDirSync(Deno.cwd())){
        if (path70.isDirectory) {
            const targetPath = join3(Deno.cwd(), path70.name);
            if (isEnvDir(targetPath)) {
                try {
                    if (!pathWithForwardSlashes(caps.executable).startsWith(pathWithForwardSlashes(targetPath))) {
                        return indent + "There is an unactivated Python environment in " + bold(path70.name) + ". Did you forget to activate it?";
                    }
                } catch  {
                    return undefined;
                }
            }
        }
    }
    const kRequirementsTxt = "requirements.txt";
    const kEnvironmentYaml = "environment.yml";
    for (const envFile of [
        kRequirementsTxt,
        kEnvironmentYaml
    ]){
        if (existsSync(join3(Deno.cwd(), envFile))) {
            return indent + "There is a " + bold(envFile) + " file in this directory. " + "Is this for a " + (envFile === kRequirementsTxt ? "venv" : "conda env") + " that you need to restore?";
        }
    }
    return undefined;
}
function pythonInstallationMessage(indent = "") {
    const lines8 = [
        "Unable to locate an installed version of Python 3.",
        "Install Python 3 from " + bold("https://www.python.org/downloads/"), 
    ];
    return lines8.map((line)=>`${indent}${line}`
    ).join("\n");
}
async function executeKernelOneshot(options) {
    await abortKernel(options);
    if (!options.quiet) {
        messageStartingKernel();
    }
    trace(options, "Executing notebook with oneshot kernel");
    const debug2 = !!options.format.execute[kExecuteDebug];
    const result = await execJupyter("execute", {
        ...options,
        debug: debug2
    });
    if (!result.success) {
        return Promise.reject();
    }
}
async function executeKernelKeepalive(options) {
    let serverLogProcess;
    if (options.format.execute[kExecuteDebug]) {
        if (Deno.build.os !== "windows") {
            serverLogProcess = Deno.run({
                cmd: [
                    "tail",
                    "-F",
                    "-n",
                    "0",
                    kernelLogFile()
                ]
            });
        }
    }
    if (options.format.execute[kExecuteDaemonRestart]) {
        await abortKernel(options);
    }
    trace(options, "Connecting to kernel");
    const [conn, transport] = await connectToKernel(options);
    trace(options, "Kernel connection successful");
    try {
        trace(options, "Sending execute command to kernel");
        await writeKernelCommand(conn, "execute", transport.secret, {
            ...options
        });
        trace(options, "Execute command sent, reading response");
        let leftover = "";
        while(true){
            const buffer = new Uint8Array(512);
            const bytesRead = await conn.read(buffer);
            if (bytesRead === null) {
                break;
            }
            if (bytesRead > 0) {
                const payload = new TextDecoder().decode(buffer.slice(0, bytesRead));
                const jsonMessages = payload.split("\n");
                for (let jsonMessage of jsonMessages){
                    if (!jsonMessage) {
                        continue;
                    }
                    if (leftover) {
                        jsonMessage = leftover + jsonMessage;
                        leftover = "";
                    }
                    try {
                        const msg = JSON.parse(jsonMessage);
                        if (msg.type === "error") {
                            trace(options, "Error response received");
                            error(msg.data, {
                                colorize: false
                            });
                            printExecDiagnostics(msg.data);
                            return Promise.reject();
                        } else if (msg.type == "restart") {
                            trace(options, "Restart request received");
                            return executeKernelKeepalive(options);
                        } else {
                            info(msg.data, {
                                newline: false
                            });
                        }
                    } catch  {
                        leftover = jsonMessage;
                    }
                }
            }
        }
        trace(options, "Server request complete\n\n");
    } catch (e) {
        trace(options, "Error occurred receiving response from server");
        const transportFile = kernelTransportFile(options.target.input);
        if (existsSync(transportFile)) {
            Deno.removeSync(transportFile);
        }
        throw e;
    } finally{
        conn.close();
        if (serverLogProcess) {
            serverLogProcess.kill("SIGKILL");
        }
    }
}
async function abortKernel(options) {
    try {
        trace(options, "Checking for existing kernel");
        const [conn, transport] = await connectToKernel(options, false);
        trace(options, "Existing kernel found");
        try {
            trace(options, "Sending kernel abort request");
            await writeKernelCommand(conn, "abort", transport.secret, {});
            trace(options, "Abort request successful");
        } finally{
            const transportFile = kernelTransportFile(options.target.input);
            if (existsSync(transportFile)) {
                Deno.removeSync(transportFile);
            }
            conn.close();
        }
    } catch  {
        trace(options, "No existing kernel found");
    }
}
async function execJupyter(command, options) {
    try {
        const result = await execProcess({
            cmd: [
                ...await pythonExec(),
                resourcePath("jupyter/jupyter.py"), 
            ],
            stdout: "piped"
        }, kernelCommand(command, "", options));
        if (!result.success) {
            await printExecDiagnostics(result.stderr);
        }
        return result;
    } catch (e) {
        if (e?.message) {
            info("");
            error(e.message);
        }
        await printExecDiagnostics();
        return Promise.reject();
    }
}
async function printExecDiagnostics(stderr) {
    const caps = await jupyterCapabilities();
    if (caps && !caps.jupyter_core) {
        info("Python 3 installation:");
        info(await jupyterCapabilitiesMessage(caps, "  "));
        info("");
        info(await jupyterInstallationMessage(caps));
        info("");
        maybePrintUnactivatedEnvMessage(caps);
    } else if (!caps) {
        info(pythonInstallationMessage());
        info("");
    } else if (stderr && stderr.indexOf("ModuleNotFoundError") !== -1) {
        maybePrintUnactivatedEnvMessage(caps);
    }
}
function maybePrintUnactivatedEnvMessage(caps) {
    const envMessage = jupyterUnactivatedEnvMessage(caps);
    if (envMessage) {
        info(envMessage);
        info("");
    }
}
async function writeKernelCommand(conn, command, secret, options) {
    await conn.write(new TextEncoder().encode(kernelCommand(command, secret, options) + "\n"));
}
function kernelCommand(command, secret, options) {
    return JSON.stringify({
        command,
        secret,
        options: {
            ...options,
            log: kernelLogFile()
        }
    });
}
function kernelTransportFile(target) {
    const transportsDir = quartoRuntimeDir("jt");
    const targetFile = Deno.realPathSync(target);
    const hash = md5Hash(targetFile).slice(0, 20);
    return join3(transportsDir, hash);
}
function kernelLogFile() {
    const logsDir = quartoDataDir("logs");
    const kernelLog = join3(logsDir, "jupyter-kernel.log");
    if (!existsSync(kernelLog)) {
        Deno.writeTextFileSync(kernelLog, "");
    }
    return kernelLog;
}
function readKernelTransportFile(transportFile, type) {
    if (existsSync(transportFile)) {
        if (type === "tcp") {
            try {
                const transport = JSON.parse(Deno.readTextFileSync(transportFile));
                if (transport.port && transport.secret) {
                    return {
                        ...transport,
                        type
                    };
                } else {
                    throw new Error("Invalid file format");
                }
            } catch (e) {
                error("Error reading kernel transport file: " + e.toString() + "(removing file)");
                Deno.removeSync(transportFile);
                return null;
            }
        } else {
            return {
                port: transportFile,
                secret: "",
                type
            };
        }
    } else {
        return null;
    }
}
async function connectToKernel(options, startIfRequired = true) {
    const debug3 = !!options.format.execute[kExecuteDebug];
    const transportFile = kernelTransportFile(options.target.input);
    const type = "tcp";
    const transport = readKernelTransportFile(transportFile, type);
    if (transport) {
        try {
            return await denoConnectToKernel(transport);
        } catch  {
            Deno.removeSync(transportFile);
        }
    }
    if (!startIfRequired) {
        return Promise.reject();
    }
    if (!options.quiet) {
        messageStartingKernel();
    }
    const keepAlive = options.format.execute[kExecuteDaemon];
    const timeout = keepAlive === true || keepAlive === null || keepAlive === undefined ? 300 : keepAlive === false ? 0 : keepAlive;
    const result = await execJupyter("start", {
        transport: transportFile,
        timeout,
        type,
        debug: debug3
    });
    if (!result.success) {
        return Promise.reject();
    }
    for(let i68 = 1; i68 < 20; i68++){
        await sleep(i68 * 100);
        const kernelTransport = readKernelTransportFile(transportFile, type);
        if (kernelTransport) {
            try {
                return await denoConnectToKernel(kernelTransport);
            } catch (e) {
                Deno.removeSync(transportFile);
                error("Error connecting to Jupyter kernel: " + e.toString());
                return Promise.reject();
            }
        }
    }
    warning("Unable to start Jupyter kernel for " + options.target.input);
    return Promise.reject();
}
async function denoConnectToKernel(transport) {
    if (transport.type === "tcp") {
        const tcpConnectOptions = {
            transport: transport.type,
            hostname: "127.0.0.1",
            port: transport.port
        };
        return [
            await Deno.connect(tcpConnectOptions),
            transport, 
        ];
    } else {
        const unixConnectOptions = {
            transport: transport.type,
            path: transport.port
        };
        return [
            await Deno.connect(unixConnectOptions),
            transport, 
        ];
    }
}
function messageStartingKernel() {
    info("\nStarting Jupyter kernel...", {
        newline: false
    });
}
function trace(options, msg) {
    if (options.format.execute[kExecuteDebug]) {
        info("- " + msg, {
            bold: true
        });
    }
}
const jupyterEngine = {
    name: kJupyterEngine,
    defaultExt: ".qmd",
    defaultYaml: (kernel)=>[
            `jupyter: ${kernel || "python3"}`, 
        ]
    ,
    defaultContent: (kernel)=>{
        kernel = kernel || "python3";
        const lang = kernel.startsWith("python") ? "python" : kernel.startsWith("julia") ? "julia" : undefined;
        if (lang) {
            return [
                "```{" + lang + "}",
                "1 + 1",
                "```", 
            ];
        } else {
            return [];
        }
    },
    validExtensions: ()=>kJupyterNotebookExtensions.concat(kQmdExtensions)
    ,
    claimsExtension: (ext)=>{
        return kJupyterNotebookExtensions.includes(ext.toLowerCase());
    },
    claimsLanguage: (_language)=>{
        return false;
    },
    target: async (file)=>{
        const markdown = isJupyterNotebook(file) ? await markdownFromNotebook(file) : Deno.readTextFileSync(file);
        const metadata = readYamlFromMarkdown(markdown);
        if (isQmdFile(file)) {
            const [fileDir, fileStem] = dirAndStem(file);
            const notebook = join3(fileDir, fileStem + ".ipynb");
            const target = {
                source: file,
                input: notebook,
                markdown,
                metadata,
                data: {
                    transient: true
                }
            };
            await createNotebookforTarget(target);
            return target;
        } else if (isJupyterNotebook(file)) {
            return {
                source: file,
                input: file,
                markdown,
                metadata,
                data: {
                    transient: false
                }
            };
        } else {
            return undefined;
        }
    },
    partitionedMarkdown: async (file)=>{
        if (isJupyterNotebook(file)) {
            return partitionMarkdown(await markdownFromNotebook(file));
        } else {
            return partitionMarkdown(Deno.readTextFileSync(file));
        }
    },
    filterFormat: (source, options, format29)=>{
        if (isJupyterNotebook(source)) {
            let executeEnabled;
            if (options.devServerReload) {
                executeEnabled = false;
            } else if (typeof format29.execute[kExecuteIpynb] === "boolean") {
                executeEnabled = format29.execute[kExecuteIpynb];
            } else if (typeof format29.execute[kExecuteEnabled] == "boolean") {
                executeEnabled = format29.execute[kExecuteEnabled];
            } else {
                executeEnabled = false;
            }
            if (executeEnabled !== undefined) {
                return {
                    ...format29,
                    execute: {
                        ...format29.execute,
                        [kExecuteEnabled]: executeEnabled
                    }
                };
            } else {
                return format29;
            }
        } else {
            return format29;
        }
    },
    execute: async (options)=>{
        if (isQmdFile(options.target.source) && !existsSync(options.target.input)) {
            await createNotebookforTarget(options.target);
        }
        const execute = options.format.execute[kExecuteEnabled] !== false;
        if (execute) {
            const execOptions = {
                ...options,
                target: {
                    ...options.target,
                    input: Deno.realPathSync(options.target.input)
                }
            };
            let executeDaemon = options.format.execute[kExecuteDaemon];
            if (executeDaemon === null || executeDaemon === undefined) {
                executeDaemon = isInteractiveSession() && !runningInCI();
            }
            if (executeDaemon === false || executeDaemon === 0) {
                await executeKernelOneshot(execOptions);
            } else {
                await executeKernelKeepalive(execOptions);
            }
        }
        const nb = jupyterFromFile(options.target.input);
        const assets = jupyterAssets(options.target.input, options.format.pandoc.to);
        const result = jupyterToMarkdown(nb, {
            language: nb.metadata.kernelspec.language.toLowerCase(),
            assets,
            execute: options.format.execute,
            keepHidden: options.format.render[kKeepHidden],
            toHtml: isHtmlCompatible(options.format),
            toLatex: isLatexOutput(options.format.pandoc),
            toMarkdown: isMarkdownOutput(options.format.pandoc),
            toIpynb: isIpynbOutput(options.format.pandoc),
            toPresentation: isPresentationOutput(options.format.pandoc),
            figFormat: options.format.execute[kFigFormat],
            figDpi: options.format.execute[kFigDpi],
            figPos: options.format.render[kFigPos]
        });
        let includes;
        let engineDependencies;
        if (options.dependencies) {
            includes = executeResultIncludes(options.tempDir, result.dependencies);
        } else {
            const dependencies = executeResultEngineDependencies(result.dependencies);
            if (dependencies) {
                engineDependencies = {
                    [kJupyterEngine]: dependencies
                };
            }
        }
        cleanupNotebook(options.target, options.format);
        return {
            markdown: result.markdown,
            supporting: [
                join3(assets.base_dir, assets.supporting_dir)
            ],
            filters: [],
            pandoc: result.pandoc,
            includes,
            engineDependencies,
            preserve: result.htmlPreserve,
            postProcess: result.htmlPreserve && Object.keys(result.htmlPreserve).length > 0
        };
    },
    executeTargetSkipped: cleanupNotebook,
    dependencies: (options)=>{
        const includes = {};
        if (options.dependencies) {
            const includeFiles = includesForJupyterWidgetDependencies(options.dependencies, options.tempDir);
            if (includeFiles.inHeader) {
                includes[kIncludeInHeader] = [
                    includeFiles.inHeader
                ];
            }
            if (includeFiles.afterBody) {
                includes[kIncludeAfterBody] = [
                    includeFiles.afterBody
                ];
            }
        }
        return Promise.resolve({
            includes
        });
    },
    postprocess: (options)=>{
        postProcessRestorePreservedHtml(options);
        return Promise.resolve();
    },
    canFreeze: true,
    generatesFigures: true,
    ignoreDirs: ()=>{
        return [
            "venv",
            "env"
        ];
    },
    canKeepSource: (target)=>{
        return !isJupyterNotebook(target.source);
    },
    keepFiles: (input)=>{
        if (!isJupyterNotebook(input) && !input.endsWith(`.${kJupyterEngine}.md`)) {
            const [fileDir, fileStem] = dirAndStem(input);
            return [
                join3(fileDir, fileStem + ".ipynb")
            ];
        }
    }
};
function isQmdFile(file) {
    const ext = extname2(file);
    return kQmdExtensions.includes(ext);
}
async function createNotebookforTarget(target) {
    const nb = await quartoMdToJupyter(target.source, true);
    Deno.writeTextFileSync(target.input, JSON.stringify(nb, null, 2));
}
function cleanupNotebook(target, format30) {
    const data48 = target.data;
    if (data48.transient) {
        if (!format30.execute[kKeepIpynb]) {
            removeIfExists(target.input);
        }
    }
}
function executeResultIncludes(tempDir3, widgetDependencies) {
    if (widgetDependencies) {
        const includes = {};
        const includeFiles = includesForJupyterWidgetDependencies([
            widgetDependencies
        ], tempDir3);
        if (includeFiles.inHeader) {
            includes[kIncludeInHeader] = [
                includeFiles.inHeader
            ];
        }
        if (includeFiles.afterBody) {
            includes[kIncludeAfterBody] = [
                includeFiles.afterBody
            ];
        }
        return includes;
    } else {
        return undefined;
    }
}
function executeResultEngineDependencies(widgetDependencies) {
    if (widgetDependencies) {
        return [
            widgetDependencies
        ];
    } else {
        return undefined;
    }
}
async function markdownFromNotebook(file) {
    const decoder = new TextDecoder("utf-8");
    const nbContents = await Deno.readFile(file);
    const nb = JSON.parse(decoder.decode(nbContents));
    const cells = nb.cells;
    const markdown = cells.reduce((md, cell)=>{
        if ([
            "markdown",
            "raw"
        ].includes(cell.cell_type)) {
            return md + "\n" + cell.source.join("") + "\n";
        } else {
            return md;
        }
    }, "");
    return markdown;
}
const kMdExtensions = [
    ".md",
    ".markdown"
];
const markdownEngine = {
    name: kMarkdownEngine,
    defaultExt: ".qmd",
    defaultYaml: ()=>[]
    ,
    defaultContent: ()=>[]
    ,
    validExtensions: ()=>kQmdExtensions.concat(kMdExtensions)
    ,
    claimsExtension: (ext)=>{
        return kMdExtensions.includes(ext.toLowerCase());
    },
    claimsLanguage: (_language)=>{
        return false;
    },
    target: (file)=>{
        const markdown = Deno.readTextFileSync(file);
        return Promise.resolve({
            source: file,
            input: file,
            markdown,
            metadata: readYamlFromMarkdown(markdown)
        });
    },
    partitionedMarkdown: (file)=>{
        return Promise.resolve(partitionMarkdown(Deno.readTextFileSync(file)));
    },
    execute: (options)=>{
        const markdown = Deno.readTextFileSync(options.target.input);
        return Promise.resolve({
            markdown,
            supporting: [],
            filters: []
        });
    },
    dependencies: (_options)=>{
        return Promise.resolve({
            includes: {}
        });
    },
    postprocess: (_options)=>Promise.resolve()
    ,
    canFreeze: false,
    generatesFigures: false
};
const kEngines = [
    knitrEngine,
    jupyterEngine,
    markdownEngine, 
];
function executionEngines() {
    return kEngines.map((engine)=>engine.name
    );
}
function executionEngine(name86) {
    for (const engine of kEngines){
        if (engine.name === name86) {
            return engine;
        }
    }
}
function executionEngineKeepMd(input) {
    const keepSuffix = `.md`;
    if (!input.endsWith(keepSuffix)) {
        const [dir, stem] = dirAndStem(input);
        return join3(dir, stem + keepSuffix);
    }
}
function executionEngineCanKeepSource(engine, target) {
    return !engine.canKeepSource || engine.canKeepSource(target);
}
function executionEngineKeepFiles(engine, input) {
    const files = [];
    const keep = executionEngineKeepMd(input);
    if (keep) {
        files.push(keep);
    }
    const engineKeepFiles = engine.keepFiles ? engine.keepFiles(input) : undefined;
    if (engineKeepFiles) {
        return files.concat(engineKeepFiles);
    } else {
        return files;
    }
}
function engineValidExtensions() {
    return __VIRTUAL_FILE181(kEngines.flatMap((engine)=>engine.validExtensions()
    ));
}
function fileExecutionEngine(file) {
    const ext = extname2(file).toLowerCase();
    if (!kEngines.some((engine)=>engine.validExtensions().includes(ext)
    )) {
        return undefined;
    }
    for (const engine1 of kEngines){
        if (engine1.claimsExtension(ext)) {
            return engine1;
        }
    }
    const markdown = Deno.readTextFileSync(file);
    const result = partitionYamlFrontMatter(markdown);
    if (result) {
        const yaml = readYamlFromMarkdown(result.yaml);
        if (yaml) {
            for (const engine of kEngines){
                if (yaml[engine.name]) {
                    return engine;
                }
                const format31 = metadataAsFormat(yaml);
                if (format31.execute?.[kEngine] === engine.name) {
                    return engine;
                }
            }
        }
    }
    const languages = languagesInMarkdown(markdown);
    if (languages.size > 0) {
        for (const language of languages){
            for (const engine of kEngines){
                if (engine.claimsLanguage(language)) {
                    return engine;
                }
            }
        }
        if (languages.size === 0 || languages.size == 1 && languages.has("ojs")) {
            return engineForMarkdownWithNoLanguages(markdown);
        } else {
            return jupyterEngine;
        }
    } else {
        return engineForMarkdownWithNoLanguages(markdown);
    }
}
async function fileExecutionEngineAndTarget(file, quiet) {
    const engine = fileExecutionEngine(file);
    if (!engine) {
        throw new Error("Unable to render " + file);
    }
    const target = await engine.target(file, quiet);
    if (!target) {
        throw new Error("Unable to render " + file);
    }
    return {
        engine,
        target
    };
}
function engineForMarkdownWithNoLanguages(markdown) {
    if (markdown.match(/`r[ #]([^`]+)\s*`/)) {
        return knitrEngine;
    } else {
        return markdownEngine;
    }
}
function engineIgnoreDirs() {
    const ignoreDirs = [
        "node_modules"
    ];
    executionEngines().forEach((name87)=>{
        const engine = executionEngine(name87);
        if (engine && engine.ignoreDirs) {
            const ignores = engine.ignoreDirs();
            if (ignores) {
                ignoreDirs.push(...ignores);
            }
        }
    });
    return ignoreDirs;
}
function engineIgnoreGlobs() {
    return engineIgnoreDirs().map((ignore1)=>`**/${ignore1}/**`
    );
}
function hasTableOfContents(flags, format32) {
    return !!(flags[kToc] || format32.pandoc[kToc] || format32.pandoc[kTableOfContents]);
}
function disabledTableOfContents(format33) {
    return format33.pandoc[kToc] === false || format33.pandoc[kTableOfContents] === false;
}
const kTabsets = "tabsets";
const kCodeCopy = "code-copy";
const kAnchorSections = "anchor-sections";
const kCitationsHover = "citations-hover";
const kFootnotesHover = "footnotes-hover";
const kMinimal = "minimal";
const kPageLayout = "page-layout";
const kPageLayoutArticle = "article";
const kPageLayoutCustom = "custom";
const kPageLayoutFull = "full";
const kComments = "comments";
const kHypothesis = "hypothesis";
const kUtterances = "utterances";
const kGiscus = "giscus";
const kGiscusRepoId = "repo-id";
const kGiscusCategoryId = "category-id";
const kDraft = "draft";
const kAppendixStyle = "appendix-style";
const kLicense = "license";
const kCitation = "citation";
const kDocumentCss = "document-css";
const kBootstrapDependencyName = "bootstrap";
const clipboardDependency = ()=>{
    const dependency = {
        name: "clipboard"
    };
    dependency.scripts = [];
    dependency.scripts.push({
        name: "clipboard.min.js",
        path: formatResourcePath("html", join3("clipboard", "clipboard.min.js"))
    });
    return dependency;
};
const bootstrapFunctions = ()=>{
    return Deno.readTextFileSync(join3(bootstrapResourceDir(), "_functions.scss"));
};
const bootstrapMixins = ()=>{
    return Deno.readTextFileSync(join3(bootstrapResourceDir(), "_mixins.scss"));
};
const bootstrapVariables = ()=>{
    return Deno.readTextFileSync(join3(bootstrapResourceDir(), "_variables.scss"));
};
const bootstrapRules = ()=>{
    return Deno.readTextFileSync(join3(bootstrapResourceDir(), "bootstrap.scss"));
};
const bootstrapResourceDir = ()=>{
    return formatResourcePath("html", join3("bootstrap", "dist", "scss"));
};
const sassUtilFunctions = (name88)=>{
    const bootstrapDistDir = formatResourcePath("html", join3("bootstrap", "dist"));
    const path71 = join3(bootstrapDistDir, "sass-utils", name88);
    return Deno.readTextFileSync(path71);
};
const quartoRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules.scss"))
;
const quartoCopyCodeRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules-copy-code.scss"))
;
const quartoLinkExternalRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules-link-external.scss"))
;
const quartoTabbyRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules-tabby.scss"))
;
const quartoFigResponsiveRules = ()=>{
    return [
        ".img-fluid {",
        "  max-width: 100%;",
        "  height: auto;",
        "}", 
    ].join("\n");
};
const quartoGlobalCssVariableRules = ()=>{
    return `
  $font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
  /*! quarto-variables-start */
  :root {
    --quarto-font-monospace: #{inspect($font-family-monospace)};
  }
  /*! quarto-variables-end */
  `;
};
const quartoBootstrapCustomizationLayer = ()=>{
    const path72 = formatResourcePath("html", join3("bootstrap", "_bootstrap-customize.scss"));
    return sassLayer(path72);
};
const quartoBootstrapRules = ()=>Deno.readTextFileSync(formatResourcePath("html", join3("bootstrap", "_bootstrap-rules.scss")))
;
const quartoBootstrapMixins = ()=>Deno.readTextFileSync(formatResourcePath("html", join3("bootstrap", "_bootstrap-mixins.scss")))
;
const quartoBootstrapFunctions = ()=>Deno.readTextFileSync(formatResourcePath("html", join3("bootstrap", "_bootstrap-functions.scss")))
;
const quartoBaseLayer = (format34, codeCopy = false, tabby = false, figResponsive = false)=>{
    const rules = [
        quartoRules()
    ];
    if (codeCopy) {
        rules.push(quartoCopyCodeRules());
    }
    if (tabby) {
        rules.push(quartoTabbyRules());
    }
    if (figResponsive) {
        rules.push(quartoFigResponsiveRules());
    }
    if (format34.render[kLinkExternalIcon]) {
        rules.push(quartoLinkExternalRules());
    }
    return {
        uses: quartoUses(),
        defaults: [
            quartoDefaults(format34), 
        ].join("\n"),
        functions: quartoFunctions(),
        mixins: "",
        rules: rules.join("\n")
    };
};
const quartoUses = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-uses.scss"))
;
const quartoFunctions = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-functions.scss"))
;
const quartoDefaults = (format35)=>{
    const defaults = [];
    defaults.push(outputVariable(sassVariable("code-copy-selector", format35.metadata[kCodeCopy] === undefined || format35.metadata[kCodeCopy] === "hover" ? '"pre.sourceCode:hover > "' : '""')));
    defaults.push(outputVariable(sassVariable("code-white-space", format35.render[kCodeOverflow] === "wrap" ? "pre-wrap" : "pre")));
    defaults.push(outputVariable(sassVariable(kTblCapLoc, format35.metadata[kTblCapLoc] || format35.metadata[kCapLoc] || kCapTop)));
    return defaults.join("\n");
};
function insertFootnotesTitle(doc, footnotesEl, language, level = 2, classes = []) {
    prependHeading(doc, footnotesEl, language[kSectionTitleFootnotes], level, classes);
}
function insertReferencesTitle(doc, refsEl, language, level = 2, classes = []) {
    prependHeading(doc, refsEl, language[kSectionTitleReferences], level, classes);
}
function insertTitle(doc, el, title2, level = 2, headingClasses = []) {
    prependHeading(doc, el, title2, level, headingClasses);
}
function prependHeading(doc, el, title3, level, classes) {
    const heading = doc.createElement("h" + level);
    if (typeof title3 == "string" && title3 !== "none") {
        heading.innerHTML = title3;
    }
    if (classes) {
        classes.forEach((clz)=>{
            heading.classList.add(clz);
        });
    }
    el.insertBefore(heading, el.firstChild);
    const hr = el.querySelector("hr");
    if (hr) {
        hr.remove();
    }
}
function removeFootnoteBacklinks(footnotesEl) {
    const backlinks = footnotesEl.querySelectorAll(".footnote-back");
    for (const backlink of backlinks){
        backlink.remove();
    }
}
function setMainColumn(doc, column) {
    const selectors = [
        "main.content",
        ".page-navigation",
        ".quarto-banner-title-block .quarto-title", 
    ];
    selectors.forEach((selector)=>{
        const el = doc.querySelector(selector);
        if (el) {
            for (const clz of el.classList){
                if (clz.startsWith("column-")) {
                    el.classList.remove(clz);
                }
            }
            el.classList.add(column);
        }
    });
}
function hasMarginRefs(format36, flags) {
    return format36.pandoc[kReferenceLocation] === "margin" || flags[kReferenceLocation] === "margin";
}
function hasMarginCites(format37) {
    return format37.metadata[kCitationLocation] === "margin";
}
function createCodeCopyButton(doc, format38) {
    const copyButton = doc.createElement("button");
    const title4 = format38.language[kCopyButtonTooltip];
    copyButton.setAttribute("title", title4);
    copyButton.classList.add("code-copy-button");
    const copyIcon = doc.createElement("i");
    copyIcon.classList.add("bi");
    copyButton.appendChild(copyIcon);
    return copyButton;
}
function createCodeBlock(doc, htmlContents, language) {
    const preEl = doc.createElement("PRE");
    preEl.classList.add("sourceCode");
    preEl.classList.add("code-with-copy");
    const codeEl = doc.createElement("CODE");
    codeEl.classList.add("sourceCode");
    if (language) {
        codeEl.classList.add(language);
    }
    codeEl.innerHTML = htmlContents;
    preEl.appendChild(codeEl);
    return preEl;
}
function writeMetaTag(name89, content, doc) {
    const m = doc.createElement("META");
    if (name89.startsWith("og:")) {
        m.setAttribute("property", name89);
    } else {
        m.setAttribute("name", name89);
    }
    m.setAttribute("content", content);
    const nl = doc.createTextNode("\n");
    doc.querySelector("head")?.appendChild(m);
    doc.querySelector("head")?.appendChild(nl);
}
const kWebsite = "website";
const kSiteUrl = "site-url";
const kSitePath = "site-path";
const kSiteTitle = "title";
const kSiteFavicon = "favicon";
const kSiteRepoUrl = "repo-url";
const kSiteRepoBranch = "repo-branch";
const kSiteRepoActions = "repo-actions";
const kSiteReaderMode = "reader-mode";
const kSiteNavbar = "navbar";
const kSiteSidebar = "sidebar";
const kSiteSidebarStyle = "style";
const kSiteSidebarHeader = "header";
const kSiteSidebarFooter = "footer";
const kSitePageNavigation = "page-navigation";
const kPageFooter = "page-footer";
const kMarginHeader = "margin-header";
const kMarginFooter = "margin-footer";
const kBodyHeader = "body-header";
const kBodyFooter = "body-footer";
const kContents = "contents";
const kTwitterCard = "twitter-card";
const kOpenGraph = "open-graph";
const kCardStyle = "card-style";
const kImage = "image";
const kImageWidth = "image-width";
const kImageHeight = "image-height";
const kCreator = "creator";
const kLocale = "locale";
const kSiteName = "site-name";
function websiteConfigBoolean(name90, defaultValue, project) {
    const config = websiteConfig(name90, project);
    if (typeof config === "string") {
        return !!config;
    } else if (typeof config == "boolean") {
        return config;
    } else {
        return defaultValue;
    }
}
function websiteConfigString(name91, project) {
    const config = websiteConfig(name91, project);
    if (typeof config === "string") {
        return config;
    } else {
        return undefined;
    }
}
function websiteConfigMetadata(name92, project) {
    const config = websiteConfig(name92, project);
    if (typeof config === "object" && !Array.isArray(config)) {
        return config;
    } else {
        return undefined;
    }
}
function websiteConfigArray(name93, project) {
    const config = websiteConfig(name93, project);
    if (Array.isArray(config)) {
        return config;
    } else {
        return undefined;
    }
}
function websiteConfig(name94, project) {
    const site = project?.[kWebsite];
    if (site) {
        return site[name94];
    } else {
        return undefined;
    }
}
function websiteTitle(project) {
    return websiteConfigString(kSiteTitle, project);
}
function websiteBaseurl(project) {
    return websiteConfigString(kSiteUrl, project);
}
function websiteImage(project) {
    return websiteConfigString(kImage, project);
}
function websiteDescription(project) {
    return websiteConfigString(kDescription, project);
}
function websitePath(project) {
    let path73 = websiteConfigString(kSitePath, project);
    if (path73) {
        if (!path73.endsWith("/")) {
            path73 = path73 + "/";
        }
        return path73;
    } else {
        const baseUrl = websiteBaseurl(project);
        if (baseUrl) {
            try {
                const url = new URL(baseUrl);
                let path74 = url.pathname;
                if (!path74.endsWith("/")) {
                    path74 = path74 + "/";
                }
                return path74;
            } catch  {
                return "/";
            }
        } else {
            return "/";
        }
    }
}
function websiteRepoUrl(project) {
    const repoUrl = websiteConfigString(kSiteRepoUrl, project);
    if (repoUrl) {
        if (!repoUrl.endsWith("/")) {
            return repoUrl + "/";
        } else {
            return repoUrl;
        }
    } else {
        return undefined;
    }
}
function websiteRepoBranch(project) {
    return websiteConfigString(kSiteRepoBranch, project) || "main";
}
function websiteMetadataFields() {
    return [
        kWebsite,
        "site"
    ];
}
function isGithubRepoUrl(url) {
    return !!url.match(/^http[s]?:\/\/github\.com/);
}
function websiteConfigActions(key, subkey, project) {
    const book = project?.[subkey];
    if (book) {
        const value = book[key];
        if (typeof value === "string") {
            if (value === "none") {
                return [];
            } else {
                return [
                    value
                ];
            }
        } else if (Array.isArray(value)) {
            return value.map((x)=>String(x)
            );
        } else {
            return [];
        }
    } else {
        return [];
    }
}
function websiteProjectConfig(_projectDir, config, forceHtml) {
    config = cloneDeep1(config);
    const format110 = config[kMetadataFormat];
    if (format110 !== undefined) {
        if (typeof format110 === "string") {
            if (!isHtmlOutput(format110, true) && forceHtml) {
                config[kMetadataFormat] = {
                    html: "default",
                    [format110]: "default"
                };
            }
        } else {
            const formats2 = Object.keys(format110);
            const orderedFormats = {};
            if (forceHtml) {
                const htmlFormatPos = formats2.findIndex((format39)=>isHtmlOutput(format39, true)
                );
                if (htmlFormatPos !== -1) {
                    const htmlFormatName = formats2.splice(htmlFormatPos, 1)[0];
                    orderedFormats[htmlFormatName] = format110[htmlFormatName];
                } else {
                    orderedFormats["html"] = "default";
                }
            }
            for (const formatName of formats2){
                orderedFormats[formatName] = format110[formatName];
            }
            config[kMetadataFormat] = orderedFormats;
        }
    } else {
        config[kMetadataFormat] = "html";
    }
    const ensureArray = (val)=>{
        if (Array.isArray(val)) {
            return val;
        } else if (typeof val === "string") {
            return [
                val
            ];
        }
    };
    const siteMeta = config[kWebsite] || {};
    if (siteMeta[kBodyHeader]) {
        siteMeta[kBodyHeader] = ensureArray(siteMeta[kBodyHeader]);
    }
    if (siteMeta[kBodyFooter]) {
        siteMeta[kBodyFooter] = ensureArray(siteMeta[kBodyFooter]);
    }
    if (siteMeta[kMarginHeader]) {
        siteMeta[kMarginHeader] = ensureArray(siteMeta[kMarginHeader]);
    }
    if (siteMeta[kMarginFooter]) {
        siteMeta[kMarginFooter] = ensureArray(siteMeta[kMarginFooter]);
    }
    config[kWebsite] = siteMeta;
    const sidebarRaw = siteMeta[kSiteSidebar];
    const sidebars = Array.isArray(sidebarRaw) ? sidebarRaw : typeof sidebarRaw == "object" ? [
        sidebarRaw
    ] : undefined;
    sidebars?.forEach((sidebar)=>{
        const headerRaw = sidebar[kSiteSidebarHeader];
        if (headerRaw) {
            sidebar[kSiteSidebarHeader] = ensureArray(sidebar[kSiteSidebarHeader]);
        }
    });
    sidebars?.forEach((sidebar)=>{
        const footerRaw = sidebar[kSiteSidebarFooter];
        if (footerRaw) {
            sidebar[kSiteSidebarFooter] = ensureArray(sidebar[kSiteSidebarFooter]);
        }
    });
    if (websiteConfigMetadata(kComments, config) && config[kComments] === undefined) {
        config[kComments] = websiteConfigMetadata(kComments, config);
    }
    return Promise.resolve(config);
}
function websiteHtmlFormat(project) {
    const projConfig = project.config || {};
    const baseFormat = metadataAsFormat(projConfig);
    const format40 = formatFromMetadata(baseFormat, formatKeys(projConfig)[0]);
    return mergeConfigs(baseFormat, format40);
}
function layerQuartoScss(key, dependency, sassLayer1, format41, darkLayer, darkDefault, loadPaths) {
    const frameworkFunctions = [
        bootstrapFunctions(),
        sassUtilFunctions("color-contrast.scss"), 
    ].join("\n");
    const frameworkVariables = [
        bootstrapVariables(),
        pandocVariablesToThemeScss(format41.metadata), 
    ].join("\n");
    return {
        dependency,
        key,
        user: sassLayer1,
        quarto: {
            uses: quartoUses(),
            defaults: [
                quartoDefaults(format41),
                quartoBootstrapDefaults(format41.metadata), 
            ].join("\n"),
            functions: [
                quartoFunctions(),
                quartoBootstrapFunctions()
            ].join("\n"),
            mixins: quartoBootstrapMixins(),
            rules: [
                quartoRules(),
                quartoCopyCodeRules(),
                quartoBootstrapRules(),
                quartoGlobalCssVariableRules(),
                quartoLinkExternalRules(), 
            ].join("\n")
        },
        framework: {
            uses: "",
            defaults: frameworkVariables,
            functions: frameworkFunctions,
            mixins: bootstrapMixins(),
            rules: bootstrapRules()
        },
        loadPaths: [
            bootstrapResourceDir(),
            ...loadPaths || []
        ],
        dark: darkLayer ? {
            user: darkLayer,
            default: darkDefault
        } : undefined
    };
}
function resolveBootstrapScss(input, format42) {
    const quartoThemesDir = formatResourcePath("html", join3("bootstrap", "themes"));
    const theme = format42.metadata[kTheme] || [];
    const [themeSassLayers, defaultDark, loadPaths] = resolveThemeLayer(input, theme, quartoThemesDir);
    const sassBundles = [];
    sassBundles.push(layerQuartoScss("quarto-theme", kBootstrapDependencyName, themeSassLayers.light, format42, themeSassLayers.dark, defaultDark, loadPaths));
    return sassBundles;
}
function layerTheme(input, themes1, quartoThemesDir) {
    let injectedCustomization = false;
    const loadPaths = [];
    const layers = themes1.flatMap((theme)=>{
        const resolvedThemePath = join3(quartoThemesDir, `${theme}.scss`);
        if (existsSync(resolvedThemePath)) {
            const themeLayer1 = sassLayer(resolvedThemePath);
            injectedCustomization = true;
            return [
                themeLayer1,
                quartoBootstrapCustomizationLayer()
            ];
        } else {
            const themePath = join3(dirname2(input), theme);
            if (existsSync(themePath)) {
                const themeDir = dirname2(themePath);
                loadPaths.push(themeDir);
                return sassLayer(themePath);
            } else {
                return {
                    uses: "",
                    defaults: "",
                    functions: "",
                    mixins: "",
                    rules: ""
                };
            }
        }
    });
    if (!injectedCustomization) {
        layers.unshift(quartoBootstrapCustomizationLayer());
    }
    return {
        layers,
        loadPaths
    };
}
function resolveThemeLayer(input, themes1, quartoThemesDir) {
    let theme1 = undefined;
    let defaultDark = false;
    if (typeof themes1 === "string") {
        theme1 = {
            light: [
                themes1
            ]
        };
    } else if (Array.isArray(themes1)) {
        theme1 = {
            light: themes1
        };
    } else if (typeof themes1 === "object") {
        const themeArr = (theme)=>{
            const themes2 = [];
            if (theme) {
                if (typeof theme === "string") {
                    themes2.push(theme);
                } else if (Array.isArray(theme)) {
                    themes2.push(...theme);
                }
            }
            return themes2;
        };
        const themeObj = themes1;
        const keyList = Object.keys(themeObj);
        defaultDark = keyList.length > 1 && keyList[0] === "dark";
        theme1 = {
            light: themeArr(themeObj.light),
            dark: themeObj.dark ? themeArr(themeObj.dark) : undefined
        };
    } else {
        theme1 = {
            light: []
        };
    }
    const lightLayerContext = layerTheme(input, theme1.light, quartoThemesDir);
    const darkLayerContext = theme1.dark ? layerTheme(input, theme1.dark, quartoThemesDir) : undefined;
    const themeSassLayer = {
        light: mergeLayers(...lightLayerContext.layers),
        dark: darkLayerContext?.layers ? mergeLayers(...darkLayerContext?.layers) : undefined
    };
    const loadPaths = [
        ...lightLayerContext.loadPaths,
        ...darkLayerContext?.loadPaths || [], 
    ];
    return [
        themeSassLayer,
        defaultDark,
        loadPaths
    ];
}
function pandocVariablesToThemeDefaults(metadata) {
    const explicitVars = [];
    const add = (defaults, name95, value, formatter)=>{
        if (value) {
            const sassVar = sassVariable(name95, value, formatter);
            defaults.push(sassVar);
        }
    };
    add(explicitVars, "line-height-base", metadata["linestretch"], asCssNumber);
    add(explicitVars, "font-size-root", metadata["fontsize"]);
    add(explicitVars, "body-bg", metadata["backgroundcolor"]);
    add(explicitVars, "body-color", metadata["fontcolor"]);
    add(explicitVars, "link-color", metadata["linkcolor"]);
    add(explicitVars, "font-family-base", metadata["mainfont"], asCssFont);
    add(explicitVars, "font-family-code", metadata["monofont"], asCssFont);
    add(explicitVars, "mono-background-color", metadata["monobackgroundcolor"]);
    const explicitSizes = [
        "max-width",
        "margin-top",
        "margin-bottom",
        "margin-left",
        "margin-right", 
    ];
    explicitSizes.forEach((attrib)=>{
        add(explicitVars, attrib, metadata[attrib], asCssSize);
    });
    return explicitVars;
}
function pandocVariablesToThemeScss(metadata, asDefaults = false) {
    return pandocVariablesToThemeDefaults(metadata).map((variable)=>{
        return outputVariable(variable, asDefaults);
    }).join("\n");
}
const kCodeBorderLeft = "code-block-border-left";
const kCodeBlockBackground = "code-block-bg";
const kBackground = "background";
const kForeground = "foreground";
const kColor = "color";
const kBorder = "border";
const quartoBootstrapDefaults = (metadata)=>{
    const varFilePath = formatResourcePath("html", join3("bootstrap", "_bootstrap-variables.scss"));
    const variables = [
        Deno.readTextFileSync(varFilePath)
    ];
    const navbar = metadata[kWebsite]?.[kSiteNavbar];
    if (navbar && typeof navbar === "object") {
        const navbarBackground = navbar[kBackground];
        if (navbarBackground !== undefined) {
            variables.push(outputVariable(sassVariable("navbar-bg", navbarBackground, typeof navbarBackground === "string" ? asBootstrapColor : undefined)));
        }
        const navbarForeground = navbar[kForeground];
        if (navbarForeground !== undefined) {
            variables.push(outputVariable(sassVariable("navbar-fg", navbarForeground, typeof navbarForeground === "string" ? asBootstrapColor : undefined)));
        }
    }
    const sidebars = metadata[kWebsite]?.[kSiteSidebar];
    const sidebar = Array.isArray(sidebars) ? sidebars[0] : typeof sidebars === "object" ? sidebars : undefined;
    if (sidebar) {
        const sidebarBackground = sidebar[kBackground];
        if (sidebarBackground !== undefined) {
            variables.push(outputVariable(sassVariable("sidebar-bg", sidebarBackground, typeof sidebarBackground === "string" ? asBootstrapColor : undefined)));
        } else if (sidebar.style === "floating" || navbar) {
            variables.push(`$sidebar-bg: if(variable-exists(body-bg), $body-bg, #fff) !default;`);
        }
        const sidebarForeground = sidebar[kForeground];
        if (sidebarForeground !== undefined) {
            variables.push(outputVariable(sassVariable("sidebar-fg", sidebarForeground, typeof sidebarForeground === "string" ? asBootstrapColor : undefined)));
        }
        const sidebarBorder = sidebar[kBorder];
        variables.push(outputVariable(sassVariable("sidebar-border", sidebarBorder !== undefined ? sidebarBorder : sidebar.style === "docked")));
    } else {
        variables.push(`$sidebar-bg: if(variable-exists(body-bg), $body-bg, #fff) !default;`);
    }
    const footer = metadata[kWebsite]?.[kPageFooter];
    if (footer !== undefined && typeof footer === "object") {
        const footerBg = footer[kBackground];
        if (footerBg !== undefined) {
            variables.push(outputVariable(sassVariable("footer-bg", footerBg, typeof footerBg === "string" ? asBootstrapColor : undefined)));
        }
        const footerFg = footer[kForeground];
        if (footerFg !== undefined) {
            variables.push(outputVariable(sassVariable("footer-fg", footerFg, typeof footerFg === "string" ? asBootstrapColor : undefined)));
        }
        const footerBorder = footer[kBorder];
        if (footerBorder !== false) {
            variables.push(outputVariable(sassVariable("footer-border", true)));
        }
        if (footerBorder !== undefined && typeof footerBorder === "string") {
            variables.push(outputVariable(sassVariable("footer-border-color", footerBorder, asBootstrapColor)));
        }
        const footerColor = footer[kColor];
        if (footerColor && typeof footerColor === "string") {
            variables.push(outputVariable(sassVariable("footer-color", footerColor, asBootstrapColor)));
        }
    }
    const codeblockLeftBorder = metadata[kCodeBorderLeft];
    const codeblockBackground = metadata[kCodeBlockBackground];
    if (codeblockLeftBorder !== undefined) {
        variables.push(outputVariable(sassVariable(kCodeBorderLeft, codeblockLeftBorder, typeof codeblockLeftBorder === "string" ? asBootstrapColor : undefined)));
        if (codeblockBackground === undefined && codeblockLeftBorder !== false) {
            variables.push(outputVariable(sassVariable(kCodeBlockBackground, false)));
        }
    }
    if (codeblockBackground !== undefined) {
        variables.push(outputVariable(sassVariable(kCodeBlockBackground, codeblockBackground, typeof codeblockBackground === "string" ? asBootstrapColor : undefined)));
    }
    return variables.reverse().join("\n");
};
async function bibliographyCslJson(input, format43) {
    const bibliography = format43.metadata[kBibliography];
    if (bibliography) {
        const references = await renderToCSLJSON(dirname2(input), bibliography);
        return references;
    }
}
async function renderHtml(entry, csl) {
    const cmd = [
        pandocBinaryPath()
    ];
    cmd.push("-f");
    cmd.push("csljson");
    cmd.push("-t");
    cmd.push("html5");
    cmd.push("--citeproc");
    if (csl) {
        cmd.push("--csl");
        cmd.push(csl);
    }
    const cslStr = JSON.stringify([
        entry
    ], undefined, 2);
    const result = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "piped"
    }, cslStr);
    if (result.success) {
        return result.stdout;
    } else {
        throw new Error(`Failed to render citation: error code ${result.code}\n${result.stderr}`);
    }
}
async function renderBibTex(entry) {
    const cmd = [
        pandocBinaryPath()
    ];
    cmd.push("-f");
    cmd.push("csljson");
    cmd.push("-t");
    cmd.push("biblatex");
    cmd.push("--citeproc");
    const cslStr = JSON.stringify([
        entry
    ], undefined, 2);
    const result = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "piped"
    }, cslStr);
    if (result.success) {
        return result.stdout;
    } else {
        throw new Error(`Failed to generate bibtex, rendering failed with code ${result.code}\n${result.stderr}`);
    }
}
async function renderToCSLJSON(dir, biblios) {
    const bibloEntries = [];
    for (const biblio of biblios){
        const cmd = [
            pandocBinaryPath()
        ];
        cmd.push(join3(dir, biblio));
        cmd.push("-t");
        cmd.push("csljson");
        cmd.push("--citeproc");
        const result = await execProcess({
            cmd,
            stdout: "piped",
            stderr: "piped",
            cwd: dir
        });
        if (result.success) {
            if (result.stdout) {
                const entries = JSON.parse(result.stdout);
                bibloEntries.push(...entries);
            }
        } else {
            throw new Error(`Failed to generate bibliography, rendering failed with code ${result.code}\n${result.stderr}`);
        }
    }
    return bibloEntries;
}
const kName = "name";
const kAffiliation = "affiliation";
const kAfilliationUrl = "affiliation-url";
const kOrcid = "orcid";
const kUrl = "url";
function parseAuthor(authorRaw) {
    if (authorRaw) {
        const parsed = [];
        const authors = Array.isArray(authorRaw) ? authorRaw : [
            authorRaw
        ];
        authors.forEach((author)=>{
            if (typeof author === "string") {
                parsed.push({
                    name: author
                });
            } else if (typeof author === "object") {
                const name96 = author[kName];
                if (name96) {
                    const auth = {
                        name: name96
                    };
                    const affilation = author[kAffiliation];
                    if (affilation) {
                        auth.affilliation = {
                            name: affilation
                        };
                        if (author[kAfilliationUrl]) {
                            auth.affilliation.url = author[kAfilliationUrl];
                        }
                    }
                    const orcid = author[kOrcid];
                    if (orcid) {
                        auth.orcid = orcid;
                    }
                    const url = author[kUrl];
                    if (url) {
                        auth.url = url;
                    }
                    parsed.push(auth);
                }
            }
        });
        return parsed;
    } else {
        return undefined;
    }
}
class Tokenizer {
    rules;
    constructor(rules = []){
        this.rules = rules;
    }
    addRule(test, fn) {
        this.rules.push({
            test,
            fn
        });
        return this;
    }
    tokenize(string20, receiver = (token)=>token
    ) {
        function* generator(rules) {
            let index = 0;
            for (const rule of rules){
                const result = rule.test(string20);
                if (result) {
                    const { value , length  } = result;
                    index += length;
                    string20 = string20.slice(length);
                    const token = {
                        ...rule.fn(value),
                        index
                    };
                    yield receiver(token);
                    yield* generator(rules);
                }
            }
        }
        const tokenGenerator = generator(this.rules);
        const tokens = [];
        for (const token1 of tokenGenerator){
            tokens.push(token1);
        }
        if (string20.length) {
            throw new Error(`parser error: string not fully parsed! ${string20.slice(0, 25)}`);
        }
        return tokens;
    }
}
function digits(value, count = 2) {
    return String(value).padStart(count, "0");
}
function createLiteralTestFunction(value) {
    return (string21)=>{
        return string21.startsWith(value) ? {
            value,
            length: value.length
        } : undefined;
    };
}
function createMatchTestFunction(match) {
    return (string22)=>{
        const result = match.exec(string22);
        if (result) return {
            value: result,
            length: result[0].length
        };
    };
}
const defaultRules = [
    {
        test: createLiteralTestFunction("yyyy"),
        fn: ()=>({
                type: "year",
                value: "numeric"
            })
    },
    {
        test: createLiteralTestFunction("yy"),
        fn: ()=>({
                type: "year",
                value: "2-digit"
            })
    },
    {
        test: createLiteralTestFunction("MM"),
        fn: ()=>({
                type: "month",
                value: "2-digit"
            })
    },
    {
        test: createLiteralTestFunction("M"),
        fn: ()=>({
                type: "month",
                value: "numeric"
            })
    },
    {
        test: createLiteralTestFunction("dd"),
        fn: ()=>({
                type: "day",
                value: "2-digit"
            })
    },
    {
        test: createLiteralTestFunction("d"),
        fn: ()=>({
                type: "day",
                value: "numeric"
            })
    },
    {
        test: createLiteralTestFunction("HH"),
        fn: ()=>({
                type: "hour",
                value: "2-digit"
            })
    },
    {
        test: createLiteralTestFunction("H"),
        fn: ()=>({
                type: "hour",
                value: "numeric"
            })
    },
    {
        test: createLiteralTestFunction("hh"),
        fn: ()=>({
                type: "hour",
                value: "2-digit",
                hour12: true
            })
    },
    {
        test: createLiteralTestFunction("h"),
        fn: ()=>({
                type: "hour",
                value: "numeric",
                hour12: true
            })
    },
    {
        test: createLiteralTestFunction("mm"),
        fn: ()=>({
                type: "minute",
                value: "2-digit"
            })
    },
    {
        test: createLiteralTestFunction("m"),
        fn: ()=>({
                type: "minute",
                value: "numeric"
            })
    },
    {
        test: createLiteralTestFunction("ss"),
        fn: ()=>({
                type: "second",
                value: "2-digit"
            })
    },
    {
        test: createLiteralTestFunction("s"),
        fn: ()=>({
                type: "second",
                value: "numeric"
            })
    },
    {
        test: createLiteralTestFunction("SSS"),
        fn: ()=>({
                type: "fractionalSecond",
                value: 3
            })
    },
    {
        test: createLiteralTestFunction("SS"),
        fn: ()=>({
                type: "fractionalSecond",
                value: 2
            })
    },
    {
        test: createLiteralTestFunction("S"),
        fn: ()=>({
                type: "fractionalSecond",
                value: 1
            })
    },
    {
        test: createLiteralTestFunction("a"),
        fn: (value)=>({
                type: "dayPeriod",
                value: value
            })
    },
    {
        test: createMatchTestFunction(/^(')(?<value>\\.|[^\']*)\1/),
        fn: (match)=>({
                type: "literal",
                value: match.groups.value
            })
    },
    {
        test: createMatchTestFunction(/^.+?\s*/),
        fn: (match)=>({
                type: "literal",
                value: match[0]
            })
    }, 
];
class DateTimeFormatter {
    #format;
    constructor(formatString, rules = defaultRules){
        const tokenizer = new Tokenizer(rules);
        this.#format = tokenizer.tokenize(formatString, ({ type , value , hour12  })=>{
            const result = {
                type,
                value
            };
            if (hour12) result.hour12 = hour12;
            return result;
        });
    }
    format(date, options = {}) {
        let string23 = "";
        const utc = options.timeZone === "UTC";
        for (const token of this.#format){
            const type = token.type;
            switch(type){
                case "year":
                    {
                        const value = utc ? date.getUTCFullYear() : date.getFullYear();
                        switch(token.value){
                            case "numeric":
                                {
                                    string23 += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string23 += digits(value, 2).slice(-2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "month":
                    {
                        const value = (utc ? date.getUTCMonth() : date.getMonth()) + 1;
                        switch(token.value){
                            case "numeric":
                                {
                                    string23 += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string23 += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "day":
                    {
                        const value = utc ? date.getUTCDate() : date.getDate();
                        switch(token.value){
                            case "numeric":
                                {
                                    string23 += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string23 += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "hour":
                    {
                        let value = utc ? date.getUTCHours() : date.getHours();
                        value -= token.hour12 && date.getHours() > 12 ? 12 : 0;
                        switch(token.value){
                            case "numeric":
                                {
                                    string23 += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string23 += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "minute":
                    {
                        const value = utc ? date.getUTCMinutes() : date.getMinutes();
                        switch(token.value){
                            case "numeric":
                                {
                                    string23 += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string23 += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "second":
                    {
                        const value = utc ? date.getUTCSeconds() : date.getSeconds();
                        switch(token.value){
                            case "numeric":
                                {
                                    string23 += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string23 += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "fractionalSecond":
                    {
                        const value = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
                        string23 += digits(value, Number(token.value));
                        break;
                    }
                case "timeZoneName":
                    {
                        break;
                    }
                case "dayPeriod":
                    {
                        string23 += token.value ? date.getHours() >= 12 ? "PM" : "AM" : "";
                        break;
                    }
                case "literal":
                    {
                        string23 += token.value;
                        break;
                    }
                default:
                    throw Error(`FormatterError: { ${token.type} ${token.value} }`);
            }
        }
        return string23;
    }
    parseToParts(string24) {
        const parts = [];
        for (const token of this.#format){
            const type = token.type;
            let value = "";
            switch(token.type){
                case "year":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,4}/.exec(string24)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{1,2}/.exec(string24)?.[0];
                                    break;
                                }
                        }
                        break;
                    }
                case "month":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,2}/.exec(string24)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string24)?.[0];
                                    break;
                                }
                            case "narrow":
                                {
                                    value = /^[a-zA-Z]+/.exec(string24)?.[0];
                                    break;
                                }
                            case "short":
                                {
                                    value = /^[a-zA-Z]+/.exec(string24)?.[0];
                                    break;
                                }
                            case "long":
                                {
                                    value = /^[a-zA-Z]+/.exec(string24)?.[0];
                                    break;
                                }
                            default:
                                throw Error(`ParserError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "day":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,2}/.exec(string24)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string24)?.[0];
                                    break;
                                }
                            default:
                                throw Error(`ParserError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "hour":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,2}/.exec(string24)?.[0];
                                    if (token.hour12 && parseInt(value) > 12) {
                                        console.error(`Trying to parse hour greater than 12. Use 'H' instead of 'h'.`);
                                    }
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string24)?.[0];
                                    if (token.hour12 && parseInt(value) > 12) {
                                        console.error(`Trying to parse hour greater than 12. Use 'HH' instead of 'hh'.`);
                                    }
                                    break;
                                }
                            default:
                                throw Error(`ParserError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "minute":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,2}/.exec(string24)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string24)?.[0];
                                    break;
                                }
                            default:
                                throw Error(`ParserError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "second":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,2}/.exec(string24)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string24)?.[0];
                                    break;
                                }
                            default:
                                throw Error(`ParserError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "fractionalSecond":
                    {
                        value = new RegExp(`^\\d{${token.value}}`).exec(string24)?.[0];
                        break;
                    }
                case "timeZoneName":
                    {
                        value = token.value;
                        break;
                    }
                case "dayPeriod":
                    {
                        value = /^(A|P)M/.exec(string24)?.[0];
                        break;
                    }
                case "literal":
                    {
                        if (!string24.startsWith(token.value)) {
                            throw Error(`Literal "${token.value}" not found "${string24.slice(0, 25)}"`);
                        }
                        value = token.value;
                        break;
                    }
                default:
                    throw Error(`${token.type} ${token.value}`);
            }
            if (!value) {
                throw Error(`value not valid for token { ${type} ${value} } ${string24.slice(0, 25)}`);
            }
            parts.push({
                type,
                value
            });
            string24 = string24.slice(value.length);
        }
        if (string24.length) {
            throw Error(`datetime string was not fully parsed! ${string24.slice(0, 25)}`);
        }
        return parts;
    }
    sortDateTimeFormatPart(parts) {
        let result = [];
        const typeArray = [
            "year",
            "month",
            "day",
            "hour",
            "minute",
            "second",
            "fractionalSecond", 
        ];
        for (const type of typeArray){
            const current = parts.findIndex((el)=>el.type === type
            );
            if (current !== -1) {
                result = result.concat(parts.splice(current, 1));
            }
        }
        result = result.concat(parts);
        return result;
    }
    partsToDate(parts) {
        const date = new Date();
        const utc = parts.find((part)=>part.type === "timeZoneName" && part.value === "UTC"
        );
        const dayPart = parts.find((part)=>part.type === "day"
        );
        utc ? date.setUTCHours(0, 0, 0, 0) : date.setHours(0, 0, 0, 0);
        for (const part1 of parts){
            switch(part1.type){
                case "year":
                    {
                        const value = Number(part1.value.padStart(4, "20"));
                        utc ? date.setUTCFullYear(value) : date.setFullYear(value);
                        break;
                    }
                case "month":
                    {
                        const value = Number(part1.value) - 1;
                        if (dayPart) {
                            utc ? date.setUTCMonth(value, Number(dayPart.value)) : date.setMonth(value, Number(dayPart.value));
                        } else {
                            utc ? date.setUTCMonth(value) : date.setMonth(value);
                        }
                        break;
                    }
                case "day":
                    {
                        const value = Number(part1.value);
                        utc ? date.setUTCDate(value) : date.setDate(value);
                        break;
                    }
                case "hour":
                    {
                        let value = Number(part1.value);
                        const dayPeriod = parts.find((part)=>part.type === "dayPeriod"
                        );
                        if (dayPeriod?.value === "PM") value += 12;
                        utc ? date.setUTCHours(value) : date.setHours(value);
                        break;
                    }
                case "minute":
                    {
                        const value = Number(part1.value);
                        utc ? date.setUTCMinutes(value) : date.setMinutes(value);
                        break;
                    }
                case "second":
                    {
                        const value = Number(part1.value);
                        utc ? date.setUTCSeconds(value) : date.setSeconds(value);
                        break;
                    }
                case "fractionalSecond":
                    {
                        const value = Number(part1.value);
                        utc ? date.setUTCMilliseconds(value) : date.setMilliseconds(value);
                        break;
                    }
            }
        }
        return date;
    }
    parse(string25) {
        const parts = this.parseToParts(string25);
        const sortParts = this.sortDateTimeFormatPart(parts);
        return this.partsToDate(sortParts);
    }
}
var Day;
(function(Day1) {
    Day1[Day1["Sun"] = 0] = "Sun";
    Day1[Day1["Mon"] = 1] = "Mon";
    Day1[Day1["Tue"] = 2] = "Tue";
    Day1[Day1["Wed"] = 3] = "Wed";
    Day1[Day1["Thu"] = 4] = "Thu";
    Day1[Day1["Fri"] = 5] = "Fri";
    Day1[Day1["Sat"] = 6] = "Sat";
})(Day || (Day = {}));
function parse4(dateString, formatString) {
    const formatter = new DateTimeFormatter(formatString);
    const parts = formatter.parseToParts(dateString);
    const sortParts = formatter.sortDateTimeFormatPart(parts);
    return formatter.partsToDate(sortParts);
}
function format3(date, formatString) {
    const formatter = new DateTimeFormatter(formatString);
    return formatter.format(date);
}
function suggestId(author, date) {
    let citeIdLeading = "";
    if (author && author.length > 0) {
        if (author[0].family) {
            citeIdLeading = author[0].family;
        } else if (author[0].literal) {
            citeIdLeading = author[0].literal;
        }
    }
    let datePart = "";
    if (date && date["date-parts"] && date["date-parts"].length > 0) {
        const yearIssued = date["date-parts"][0][0];
        if (yearIssued) {
            datePart = yearIssued + "";
        }
    }
    let suggestedId = `${citeIdLeading.toLowerCase()}${datePart}`;
    if (suggestedId.length === 0) {
        suggestedId = "untitled";
    }
    return suggestedId;
}
function cslDateToEDTFDate(date) {
    if (date["date-parts"]) {
        const paddedParts = date["date-parts"][0].map((part)=>{
            const partStr = part?.toString();
            if (partStr?.length === 1) {
                return `0${partStr}`;
            }
            return partStr;
        });
        return paddedParts.join("-");
    }
}
function cslNames(authors) {
    const cslNames1 = [];
    const authorList = Array.isArray(authors) ? authors : [
        authors
    ];
    authorList.forEach((auth)=>{
        if (auth) {
            const name97 = authorToCslName(auth);
            if (name97) {
                cslNames1.push(name97);
            }
        }
    });
    return cslNames1;
}
function cslDate(dateRaw) {
    const toDateArray = (dateArr)=>{
        if (dateArr.length === 0) {
            return undefined;
        } else if (dateArr.length === 1) {
            return {
                "date-parts": [
                    [
                        dateArr[0], 
                    ]
                ]
            };
        } else if (dateArr.length === 2) {
            return {
                "date-parts": [
                    [
                        dateArr[0],
                        dateArr[1], 
                    ]
                ]
            };
        } else if (dateArr.length >= 3) {
            return {
                "date-parts": [
                    [
                        dateArr[0],
                        dateArr[1],
                        dateArr[2], 
                    ]
                ]
            };
        }
    };
    if (Array.isArray(dateRaw)) {
        const dateArr = dateRaw;
        return toDateArray(dateArr);
    } else if (typeof dateRaw === "number") {
        const parseNumeric = (dateStr)=>{
            let dateParsed = dateStr;
            const chomps = [
                4,
                2,
                2
            ];
            const date = [];
            for (const chomp of chomps){
                if (dateParsed.length >= chomp) {
                    const part = dateParsed.substring(0, chomp);
                    if (!isNaN(+part)) {
                        date.push(+part);
                        dateParsed = dateParsed.substring(chomp);
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
            if (date.length > 0) {
                return date;
            } else {
                return undefined;
            }
        };
        const dateStr1 = String(dateRaw);
        const dateArr = parseNumeric(dateStr1);
        if (dateArr) {
            return toDateArray(dateArr);
        }
    } else if (typeof dateRaw === "string") {
        const formats3 = [
            "MM/dd/yyyy",
            "MM-dd-yyyy",
            "MM/dd/yy",
            "MM-dd-yy",
            "yyyy-MM-dd",
            "dd MM yyyy",
            "MM dd, yyyy", 
        ];
        const parseFormat1 = (dateStr)=>{
            for (const format44 of formats3){
                try {
                    const date = parse4(dateStr, format44);
                    return date;
                } catch  {}
            }
            try {
                return new Date(dateStr);
            } catch  {
                return undefined;
            }
        };
        const date1 = parseFormat1(dateRaw);
        if (date1) {
            return {
                "date-parts": [
                    [
                        date1.getFullYear(),
                        date1.getMonth() + 1,
                        date1.getDate(), 
                    ]
                ],
                raw: dateRaw
            };
        }
        return undefined;
    }
}
function authorToCslName(author) {
    const parts = author.split(" ");
    if (parts.length > 0) {
        const given = parts.shift() || "";
        const family = parts.length > 0 ? parts.join("") : "";
        return {
            family,
            given,
            literal: author
        };
    }
}
function cslType(type) {
    if (types.includes(type)) {
        return type;
    } else {
        if (type === "journal") {
            return "article-journal";
        } else if (type === "conference") {
            return "paper-conference";
        } else if (type === "dissertation") {
            return "thesis";
        }
        return "article";
    }
}
const types = [
    "article",
    "article-journal",
    "article-magazine",
    "article-newspaper",
    "bill",
    "book",
    "broadcast",
    "chapter",
    "classic",
    "collection",
    "dataset",
    "document",
    "entry",
    "entry-dictionary",
    "entry-encyclopedia",
    "event",
    "figure",
    "graphic",
    "hearing",
    "interview",
    "legal_case",
    "legislation",
    "manuscript",
    "map",
    "motion_picture",
    "musical_score",
    "pamphlet",
    "paper-conference",
    "patent",
    "performance",
    "periodical",
    "personal_communication",
    "post",
    "post-weblog",
    "regulation",
    "report",
    "review",
    "review-book",
    "software",
    "song",
    "speech",
    "standard",
    "thesis",
    "treaty",
    "webpage", 
];
const formatDate = (date, locale, dateStyle, timeStyle)=>{
    if (dateStyle === "full" || dateStyle === "long" || dateStyle === "medium" || dateStyle === "short") {
        const options = {
            dateStyle
        };
        if (timeStyle) {
            options.timeStyle = timeStyle;
        }
        return date.toLocaleString(locale, options);
    } else {
        return format3(date, dateStyle);
    }
};
const kDateFormat = "date-format";
const kDOI = "DOI";
const kCitation1 = "citation";
const kURL = "URL";
const kId = "id";
const kCitationKey = "citation-key";
const kType = "type";
const kCategories = "categories";
const kLanguage = "language";
const kAvailableDate = "available-date";
const kIssued = "issued";
const kDate1 = "date";
const kPublisher = "publisher";
const kContainerTitle = "container-title";
const kVolume = "volume";
const kIssue = "issue";
const kISSN = "issn";
const kISBN = "isbn";
const kPMCID = "pmcid";
const kPMID = "pmid";
const kFirstPage = "firstpage";
const kLastPage = "lastpage";
const kPage = "page";
const kNumber = "number";
const kCustom = "custom";
const kArchiveCollection = "archive_collection";
const kArchiveLocation = "archive_location";
const getCSLPath = (input, format45)=>{
    const cslPath = format45.metadata[kCsl];
    if (cslPath) {
        if (isAbsolute2(cslPath)) {
            return cslPath;
        } else {
            return join3(dirname2(input), cslPath);
        }
    } else {
        return undefined;
    }
};
const formattedDocumentDate = (format46, defaultDateFormat)=>{
    const dateStr = format46.metadata[kDate1];
    if (dateStr) {
        const date = new Date(dateStr);
        if (date) {
            const dateFormat = format46.metadata[kDateFormat] || defaultDateFormat;
            if (dateFormat) {
                const formatted = formatDate(date, format46.metadata[kLang], dateFormat);
                return formatted;
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
};
function documentCSL(input, format47, defaultType, offset) {
    const citationMetadata = citationMeta(format47);
    const type = citationMetadata[kType] ? cslType(citationMetadata[kType]) : defaultType;
    const title5 = citationMetadata[kTitle] || format47.metadata[kTitle];
    const csl = {
        title: title5,
        type
    };
    const key1 = citationMetadata[kCitationKey];
    if (key1) {
        csl[kCitationKey] = key1;
    }
    const authors1 = parseAuthor(format47.metadata[kAuthor] || citationMetadata[kAuthor]);
    csl.author = cslNames(authors1?.filter((auth)=>auth !== undefined
    ).map((auth)=>auth?.name
    ));
    const categories = citationMetadata[kCategories] || format47.metadata[kCategories];
    if (categories) {
        csl.categories = Array.isArray(categories) ? categories : [
            categories
        ];
    }
    const language = citationMetadata[kLanguage] || format47.metadata[kLang];
    if (language) {
        csl.language = language;
    }
    const availableDate = citationMetadata[kAvailableDate] || format47.metadata[kDate1];
    if (availableDate) {
        csl[kAvailableDate] = cslDate(availableDate);
    }
    const issued = citationMetadata[kIssued] || format47.metadata[kDate1];
    if (issued) {
        csl.issued = cslDate(issued);
    }
    const __abstract = citationMetadata[kAbstract] || format47.metadata[kAbstract];
    if (__abstract) {
        csl.abstract = __abstract;
    }
    const publisher = citationMetadata[kPublisher];
    if (publisher) {
        csl.publisher = publisher;
    }
    const containerTitle = citationMetadata[kContainerTitle];
    if (containerTitle) {
        csl[kContainerTitle] = containerTitle;
    }
    csl.id = citationMetadata[kId] || suggestId(csl.author, csl.issued);
    const findValue = (baseKey, metadata, transform)=>{
        const keys8 = [
            baseKey,
            transform(baseKey)
        ];
        for (const key of keys8){
            for (const md of metadata){
                const value = md[key];
                if (value) {
                    return value;
                }
            }
        }
    };
    const lowercase = (key)=>{
        return key.toLocaleLowerCase();
    };
    const kebabcase = (key)=>{
        return key.replaceAll("_", "_");
    };
    const url = findValue(kURL, [
        citationMetadata
    ], lowercase);
    if (url) {
        csl.URL = url;
    } else {
        csl.URL = synthesizeCitationUrl(input, format47, offset);
    }
    const doi = findValue(kDOI, [
        citationMetadata,
        format47.metadata
    ], lowercase);
    if (doi) {
        csl.DOI = doi;
    }
    const issue = citationMetadata[kIssue];
    if (issue) {
        csl.issue = issue;
    }
    const volume = citationMetadata[kVolume];
    if (volume) {
        csl.volume = volume;
    }
    const number4 = citationMetadata[kNumber];
    if (number4) {
        csl.number = number4;
    }
    const isbn = findValue(kISBN, [
        citationMetadata
    ], lowercase);
    if (isbn) {
        csl.ISBN = isbn;
    }
    const issn = findValue(kISSN, [
        citationMetadata
    ], lowercase);
    if (issn) {
        csl.ISSN = issn;
    }
    const pmcid = findValue(kPMCID, [
        citationMetadata
    ], lowercase);
    if (pmcid) {
        csl.PMCID = pmcid;
    }
    const pmid = findValue(kPMID, [
        citationMetadata
    ], lowercase);
    if (pmid) {
        csl.PMID = pmid;
    }
    const pageRange = pages(citationMetadata);
    if (pageRange.firstPage) {
        csl["page-first"] = pageRange.firstPage;
    }
    if (pageRange.lastPage) {
        csl["page-last"] = pageRange.lastPage;
    }
    if (pageRange.page) {
        csl.page = pageRange.page;
    }
    const archiveCollection = findValue(kArchiveCollection, [
        citationMetadata
    ], kebabcase);
    if (archiveCollection) {
        csl[kArchiveCollection] = archiveCollection;
    }
    const archiveLocation = findValue(kArchiveLocation, [
        citationMetadata
    ], kebabcase);
    if (archiveLocation) {
        csl[kArchiveLocation] = archiveLocation;
    }
    const forwardStringValue = (key)=>{
        if (citationMetadata[key] !== undefined) {
            csl[key] = citationMetadata[key];
        }
    };
    [
        "title-short",
        "annote",
        "archive",
        "archive-place",
        "authority",
        "call-number",
        "chapter-number",
        "citation-number",
        "citation-label",
        "collection-number",
        "collection-title",
        "container-title-short",
        "dimensions",
        "division",
        "edition",
        "event-title",
        "event-place",
        "first-reference-note-number",
        "genre",
        "jurisdiction",
        "keyword",
        "locator",
        "medium",
        "note",
        "number",
        "number-of-pages",
        "number-of-volumes",
        "original-publisher",
        "original-publisher-place",
        "original-title",
        "part",
        "part-title",
        "printing",
        "publisher-place",
        "references",
        "reviewed-genre",
        "reviewed-title",
        "scale",
        "section",
        "source",
        "status",
        "supplement",
        "version",
        "volume-title",
        "volume-title-short",
        "year-suffix", 
    ].forEach(forwardStringValue);
    const forwardCSLNameValue = (key)=>{
        if (citationMetadata[key]) {
            const authors = parseAuthor(citationMetadata[key]);
            csl[key] = cslNames(authors?.filter((auth)=>auth !== undefined
            ).map((auth)=>auth?.name
            ));
        }
    };
    [
        "chair",
        "collection-editor",
        "compiler",
        "composer",
        "container-author",
        "contributor",
        "curator",
        "director",
        "editor",
        "editorial-director",
        "executive-producer",
        "guest",
        "host",
        "interviewer",
        "illustrator",
        "narrator",
        "organizer",
        "original-author",
        "performer",
        "producer",
        "recipient",
        "reviewed-author",
        "script-writer",
        "series-creator",
        "translator", 
    ].forEach(forwardCSLNameValue);
    const forwardCSLDateValue = (key)=>{
        if (citationMetadata[key]) {
            csl[key] = cslDate(citationMetadata[key]);
        }
    };
    [
        "accessed",
        "event-date",
        "original-date",
        "submitted"
    ].forEach(forwardCSLDateValue);
    const custom = citationMetadata[kCustom];
    if (custom) {
        csl[kCustom] = custom;
    }
    return csl;
}
function citationMeta(format48) {
    if (typeof format48.metadata[kCitation1] === "object") {
        return format48.metadata[kCitation1];
    } else {
        return {};
    }
}
function synthesizeCitationUrl(input, format49, offset) {
    const siteMeta = format49.metadata[kWebsite];
    const baseUrl = siteMeta?.[kSiteUrl];
    const outputFile = format49.pandoc[kOutputFile];
    if (baseUrl && outputFile && offset) {
        const rootDir = Deno.realPathSync(join3(dirname2(input), offset));
        if (outputFile === "index.html") {
            return `${baseUrl}/${relative2(rootDir, dirname2(input))}`;
        } else {
            return `${baseUrl}/${relative2(rootDir, join3(dirname2(input), outputFile))}`;
        }
    } else {
        return undefined;
    }
}
function pages(citationMetadata) {
    let firstPage = citationMetadata[kFirstPage];
    let lastPage = citationMetadata[kLastPage];
    let pages1 = citationMetadata[kPage];
    if (pages1 && pages1.includes("-")) {
        const pagesSplit = pages1.split("-");
        if (!firstPage) {
            firstPage = pagesSplit[0];
        }
        if (!lastPage) {
            lastPage = pagesSplit[1];
        }
    } else if (pages1 && !firstPage) {
        firstPage = pages1;
    } else if (!pages1) {
        if (firstPage && lastPage) {
            pages1 = `${firstPage} - ${lastPage}`;
        } else if (firstPage) {
            pages1 = `${firstPage}`;
        }
    }
    return {
        firstPage: firstPage,
        lastPage: lastPage,
        page: pages1
    };
}
const kAppendixCreativeCommonsLic = [
    "CC BY",
    "CC BY-SA",
    "CC BY-ND",
    "CC BY-NC", 
];
const kStylePlain = "plain";
const kStyleDefault = "default";
const kAppendixHeadingClass = "quarto-appendix-heading";
const kAppendixContentsClass = "quarto-appendix-contents";
const kQuartoSecondaryLabelClass = "quarto-appendix-secondary-label";
const kQuartoCiteAsClass = "quarto-appendix-citeas";
const kQuartoCiteBibtexClass = "quarto-appendix-bibtex";
const kAppendixId = "quarto-appendix";
async function processDocumentAppendix(input, format50, flags, doc, offset) {
    if (format50.metadata.book || format50.metadata[kAppendixStyle] === false || format50.metadata[kAppendixStyle] === "none") {
        return;
    }
    const appendixStyle = parseStyle(format50.metadata[kAppendixStyle]);
    const mainEl = doc.querySelector("main.content");
    if (mainEl) {
        const appendixEl = doc.createElement("DIV");
        appendixEl.setAttribute("id", kAppendixId);
        if (appendixStyle !== kStylePlain) {
            appendixEl.classList.add(appendixStyle);
        }
        const headingClasses = [
            "anchored",
            kAppendixHeadingClass
        ];
        const appendixSections = [];
        const addSection = (fn, title6)=>{
            const containerEl = doc.createElement("SECTION");
            containerEl.classList.add(kAppendixContentsClass);
            fn(containerEl);
            if (title6) {
                insertTitle(doc, containerEl, title6, 2, headingClasses);
            }
            appendixSections.push(containerEl);
        };
        if (!hasMarginCites(format50)) {
            const refsEl1 = doc.getElementById("refs");
            if (refsEl1) {
                const findRefTitle = (refsEl)=>{
                    const parentEl = refsEl.parentElement;
                    if (parentEl && parentEl.tagName === "SECTION" && parentEl.childElementCount === 2) {
                        const headingEl = parentEl.querySelector("h2, h3, h4, h5, h6");
                        if (headingEl) {
                            headingEl.remove();
                            return headingEl.innerText;
                        }
                    }
                };
                const existingTitle = findRefTitle(refsEl1);
                addSection((sectionEl)=>{
                    sectionEl.setAttribute("role", "doc-bibliography");
                    sectionEl.appendChild(refsEl1);
                    if (existingTitle) {
                        insertTitle(doc, sectionEl, existingTitle, 2, headingClasses);
                    } else {
                        insertReferencesTitle(doc, sectionEl, format50.language, 2, headingClasses);
                    }
                });
            }
        }
        if (!hasMarginRefs(format50, flags)) {
            const footnoteEls = doc.querySelectorAll('section[role="doc-endnotes"]');
            if (footnoteEls && footnoteEls.length === 1) {
                const footnotesEl = footnoteEls.item(0);
                insertFootnotesTitle(doc, footnotesEl, format50.language, 2, headingClasses);
                appendixSections.push(footnotesEl);
            }
        }
        if (format50.metadata[kLicense]) {
            addSection((sectionEl)=>{
                const contentsDiv = doc.createElement("DIV");
                contentsDiv.id = "quarto-reuse";
                contentsDiv.classList.add(kAppendixContentsClass);
                const creativeCommons = creativeCommonsLicense(format50.metadata[kLicense]);
                if (creativeCommons) {
                    const licenseUrl = creativeCommonsUrl(creativeCommons, format50.metadata[kLang]);
                    const linkEl = doc.createElement("A");
                    linkEl.innerText = licenseUrl;
                    linkEl.setAttribute("rel", "license");
                    linkEl.setAttribute("href", licenseUrl);
                    contentsDiv.appendChild(linkEl);
                } else {
                    const licenseEl = doc.createElement("DIV");
                    licenseEl.innerText = format50.metadata[kLicense];
                    contentsDiv.appendChild(licenseEl);
                }
                sectionEl.appendChild(contentsDiv);
            }, format50.language[kSectionTitleReuse] || "Usage");
        }
        if (format50.metadata[kCitation]) {
            const cite = await generateCite(input, format50, offset);
            if (cite?.bibtex || cite?.html) {
                addSection((sectionEl)=>{
                    const contentsDiv = doc.createElement("DIV");
                    sectionEl.appendChild(contentsDiv);
                    if (cite?.bibtex) {
                        const bibTexLabelEl = doc.createElement("DIV");
                        bibTexLabelEl.classList.add(kQuartoSecondaryLabelClass);
                        bibTexLabelEl.innerText = format50.language[kAppendixAttributionBibTex] || "BibTeX citation";
                        contentsDiv.appendChild(bibTexLabelEl);
                        const bibTexDiv = createCodeBlock(doc, cite.bibtex, "bibtex");
                        bibTexDiv.classList.add(kQuartoCiteBibtexClass);
                        contentsDiv.appendChild(bibTexDiv);
                        const copyButton = createCodeCopyButton(doc, format50);
                        bibTexDiv.appendChild(copyButton);
                    }
                    if (cite?.html) {
                        const citeLabelEl = doc.createElement("DIV");
                        citeLabelEl.classList.add(kQuartoSecondaryLabelClass);
                        citeLabelEl.innerText = format50.language[kAppendixAttributionCiteAs] || "For attribution, please cite this work as:";
                        contentsDiv.appendChild(citeLabelEl);
                        const entry = extractCiteEl(cite.html, doc);
                        if (entry) {
                            entry.classList.add(kQuartoCiteAsClass);
                            contentsDiv.appendChild(entry);
                        }
                    }
                }, format50.language[kSectionTitleCitation] || "Citation");
            }
        }
        const appendixSectionNodes = doc.querySelectorAll("section.appendix");
        const appendixSectionEls = [];
        for (const appendixSectionNode of appendixSectionNodes){
            const appendSectionEl = appendixSectionNode;
            if (appendSectionEl) {
                const extractHeaderEl = ()=>{
                    const headerEl = appendSectionEl.querySelector("h1, h2, h3, h4, h5, h6");
                    if (headerEl) {
                        headerEl.remove();
                        const h2 = doc.createElement("h2");
                        h2.innerHTML = headerEl.innerHTML;
                        return h2;
                    } else {
                        const h2 = doc.createElement("h2");
                        return h2;
                    }
                };
                const headerEl1 = extractHeaderEl();
                headerEl1.classList.add(kAppendixHeadingClass);
                const containerDivEl = doc.createElement("DIV");
                containerDivEl.classList.add(kAppendixContentsClass);
                while(appendSectionEl.childNodes.length > 0){
                    containerDivEl.appendChild(appendSectionEl.childNodes[0]);
                }
                appendSectionEl.appendChild(headerEl1);
                appendSectionEl.appendChild(containerDivEl);
                appendixSectionEls.push(appendSectionEl);
            }
        }
        if (appendixSectionEls.length > 0) {
            appendixSections.unshift(...appendixSectionEls);
        }
        appendixSections.forEach((el)=>{
            appendixEl.appendChild(el);
        });
        if (appendixEl.childElementCount > 0) {
            mainEl.appendChild(appendixEl);
        }
    }
}
function parseStyle(style) {
    switch(style){
        case "plain":
            return "plain";
        default:
            return kStyleDefault;
    }
}
function creativeCommonsLicense(license) {
    if (license && kAppendixCreativeCommonsLic.includes(license)) {
        return license;
    } else {
        return undefined;
    }
}
function creativeCommonsUrl(license, lang) {
    const licenseType = license.substring(3);
    if (lang && lang !== "en") {
        return `https://creativecommons.org/licenses/${licenseType.toLowerCase()}/4.0/deed.${lang.toLowerCase().replace("-", "_")}`;
    } else {
        return `https://creativecommons.org/licenses/${licenseType.toLowerCase()}/4.0/`;
    }
}
async function generateCite(input, format51, offset) {
    const entry = documentCSL(input, format51, "webpage", offset);
    if (entry) {
        const cslPath = getCSLPath(input, format51);
        const html = await renderHtml(entry, cslPath);
        const bibtex = await renderBibTex(entry);
        return {
            html,
            bibtex
        };
    } else {
        return undefined;
    }
}
function extractCiteEl(html, doc) {
    const htmlDiv = doc.createElement("DIV");
    htmlDiv.innerHTML = html;
    const entry = htmlDiv.querySelector(".csl-entry");
    if (entry) {
        const leftMarginEl = entry.querySelector(".csl-left-margin");
        if (leftMarginEl) {
            leftMarginEl.remove();
            const rightEl = entry.querySelector(".csl-right-inline");
            if (rightEl) {
                rightEl.classList.remove("csl-right-inline");
            }
        }
        return entry;
    } else {
        return undefined;
    }
}
function localizedString(format52, key, options) {
    if (options) {
        let formattedStr = format52.language[key];
        for(let i69 = 0; i69 < options.length; i69++){
            const option = options[i69];
            formattedStr = formattedStr.replace(`{${i69}}`, option);
        }
        return formattedStr;
    } else {
        return format52.language[key];
    }
}
const kFields = "fields";
const kFieldDisplayNames = "field-display-names";
const kFieldTypes = "field-types";
const kFieldLinks = "field-links";
const kFieldRequired = "field-required";
const kFieldSort = "field-sort";
const kFieldFilter = "field-filter";
const kPageSize = "page-size";
const kFilterUi = "filter-ui";
const kSortUi = "sort-ui";
const kImageHeight1 = "image-height";
const kImageAlign = "image-align";
const kGridColumns = "grid-columns";
const kMaxDescLength = "max-description-length";
const kTableStriped = "table-striped";
const kTableHover = "table-hover";
const kFieldTitle = "title";
const kFieldSubtitle = "subtitle";
const kFieldAuthor = "author";
const kFieldFileName = "filename";
const kFieldFileModified = "file-modified";
const kFieldDate = "date";
const kFieldImage = "image";
const kFieldDescription = "description";
const kFieldReadingTime = "reading-time";
const kFieldCategories = "categories";
const kCategoryStyle = "category-style";
const kSortAsc = "asc";
const kSortDesc = "desc";
const kFeed = "feed";
const kItems = "items";
const kDescription1 = "description";
var ListingType;
(function(ListingType1) {
    ListingType1["Default"] = "default";
    ListingType1["Grid"] = "grid";
    ListingType1["Table"] = "table";
    ListingType1["Custom"] = "custom";
})(ListingType || (ListingType = {}));
var ListingItemSource;
(function(ListingItemSource1) {
    ListingItemSource1["document"] = "document";
    ListingItemSource1["metadata"] = "metadata";
    ListingItemSource1["rawfile"] = "rawfile";
})(ListingItemSource || (ListingItemSource = {}));
const kTitleBlockStyle = "title-block-style";
const kTitleBlockBanner = "title-block-banner";
const ktitleBlockColor = "title-block-banner-color";
const kTitleBlockCategories = "title-block-categories";
const orcidData = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA2ZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo1N0NEMjA4MDI1MjA2ODExOTk0QzkzNTEzRjZEQTg1NyIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDozM0NDOEJGNEZGNTcxMUUxODdBOEVCODg2RjdCQ0QwOSIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDozM0NDOEJGM0ZGNTcxMUUxODdBOEVCODg2RjdCQ0QwOSIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IE1hY2ludG9zaCI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkZDN0YxMTc0MDcyMDY4MTE5NUZFRDc5MUM2MUUwNEREIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjU3Q0QyMDgwMjUyMDY4MTE5OTRDOTM1MTNGNkRBODU3Ii8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+84NovQAAAR1JREFUeNpiZEADy85ZJgCpeCB2QJM6AMQLo4yOL0AWZETSqACk1gOxAQN+cAGIA4EGPQBxmJA0nwdpjjQ8xqArmczw5tMHXAaALDgP1QMxAGqzAAPxQACqh4ER6uf5MBlkm0X4EGayMfMw/Pr7Bd2gRBZogMFBrv01hisv5jLsv9nLAPIOMnjy8RDDyYctyAbFM2EJbRQw+aAWw/LzVgx7b+cwCHKqMhjJFCBLOzAR6+lXX84xnHjYyqAo5IUizkRCwIENQQckGSDGY4TVgAPEaraQr2a4/24bSuoExcJCfAEJihXkWDj3ZAKy9EJGaEo8T0QSxkjSwORsCAuDQCD+QILmD1A9kECEZgxDaEZhICIzGcIyEyOl2RkgwAAhkmC+eAm0TAAAAABJRU5ErkJggg==";
function processDocumentTitle(input, format111, _flags, doc, offset) {
    if (format111.metadata.book || format111.metadata[kTitleBlockStyle] === false || format111.metadata[kTitleBlockStyle] === "none") {
        return [];
    }
    const resources = [];
    const computeTitleBlockStyle = (format53)=>{
        const titleBlockStyle = format53.metadata[kTitleBlockStyle];
        if (titleBlockStyle) {
            return titleBlockStyle;
        } else {
            return "default";
        }
    };
    const titleBlockStyle1 = computeTitleBlockStyle(format111);
    const csl = documentCSL(input, format111, "webpage", offset);
    const headerEl = doc.querySelector("header#title-block-header");
    const titleEl = headerEl?.querySelector(".title");
    const subTitleEl = headerEl?.querySelector(".subtitle");
    const dateEl = headerEl?.querySelector(".date");
    const doiEl = headerEl?.querySelector(".doi");
    doiEl?.remove();
    const authorNodeList = headerEl?.querySelectorAll(".author");
    authorNodeList?.forEach((node)=>{
        node.remove();
    });
    const titleContainerEl = doc.createElement("div");
    titleContainerEl.classList.add("quarto-title");
    if (titleEl) {
        titleContainerEl.appendChild(titleEl);
    }
    if (subTitleEl) {
        titleContainerEl.appendChild(subTitleEl);
    }
    if (format111.metadata[kDescription1]) {
        titleContainerEl.appendChild(createDescriptionEl(doc, format111));
    }
    const metadataContainerEl = doc.createElement("div");
    metadataContainerEl.classList.add("quarto-title-meta");
    const authorMeta = format111.metadata[kAuthor] || citationMeta(format111)[kAuthor];
    const authors = [];
    if (authorMeta) {
        const parsedAuthors = parseAuthor(authorMeta);
        if (parsedAuthors) {
            authors.push(...parsedAuthors);
        }
    }
    if (authors.length > 0) {
        const hasAffiliations = authors.find((auth)=>auth.affilliation !== undefined
        );
        const authorEl = doc.createElement("div");
        authorEl.classList.add("quarto-title-authors");
        for (const author of authors){
            const authorP = doc.createElement("p");
            const authorContentsNode = maybeLinkedNode(doc, author.name, author.url);
            authorP.appendChild(authorContentsNode);
            if (author.orcid) {
                const orcidImg = doc.createElement("img");
                orcidImg.setAttribute("src", orcidData);
                const orcidLink = doc.createElement("a");
                orcidLink.classList.add("quarto-title-author-orcid");
                orcidLink.setAttribute("href", `https://orcid.org/${author.orcid}`);
                orcidLink.appendChild(doc.createTextNode(" "));
                orcidLink.appendChild(orcidImg);
                authorP.appendChild(orcidLink);
            }
            authorEl.appendChild(authorP);
        }
        const authorTitle = authors.length === 1 ? localizedString(format111, kTitleBlockAuthorSingle) : localizedString(format111, kTitleBlockAuthorPlural);
        const authorContainer = metadataEl(doc, authorTitle, [
            authorEl
        ]);
        metadataContainerEl.appendChild(authorContainer);
        if (hasAffiliations) {
            const affiliationEl = doc.createElement("div");
            affiliationEl.classList.add("quarto-title-affiliations");
            for (const author of authors){
                const affiliationP = doc.createElement("p");
                const affiliationText = author.affilliation !== undefined ? author.affilliation.name : "";
                const affiliationNode = maybeLinkedNode(doc, affiliationText, author.affilliation?.url);
                affiliationP.appendChild(affiliationNode);
                affiliationEl.appendChild(affiliationP);
            }
            const affiliationContainer = metadataEl(doc, authors.length === 1 ? localizedString(format111, kTitleBlockAffiliationSingle) : localizedString(format111, kTitleBlockAffiliationPlural), [
                affiliationEl, 
            ]);
            metadataContainerEl.appendChild(affiliationContainer);
        }
    }
    if (dateEl) {
        const formatted = formattedDocumentDate(format111, "long");
        if (formatted) {
            dateEl.innerText = formatted;
        }
        const dateContainer = metadataEl(doc, localizedString(format111, kTitleBlockPublished), [
            dateEl
        ]);
        metadataContainerEl.appendChild(dateContainer);
    }
    if (csl.DOI) {
        metadataContainerEl.appendChild(createDOIMetadataEl(doc, csl.DOI, false));
    }
    headerEl?.classList.add("quarto-title-block");
    headerEl?.classList.add(titleBlockStyle1);
    const banner = format111.metadata[kTitleBlockBanner];
    if (banner) {
        const bannerStyles = [];
        const titleColor = (block)=>{
            if (block === "body" || block === "body-bg") {
                return undefined;
            } else {
                return block;
            }
        };
        const titleColorClass = (block)=>{
            if (block === "body") {
                return "body";
            } else if (block === "body-bg" || block === undefined) {
                return "body-bg";
            } else {
                return "none";
            }
        };
        const titleBlockColor = titleColor(format111.metadata[ktitleBlockColor]);
        if (titleBlockColor) {
            bannerStyles.push(`color: ${titleBlockColor};`);
        }
        headerEl?.setAttribute("data-sidebar-align", "true");
        if (banner === true) {
            headerEl?.appendChild(createBannerEl(doc, titleContainerEl, "navbar"));
        } else if (isBannerImage(input, banner)) {
            resources.push(banner);
            headerEl?.appendChild(createBannerEl(doc, titleContainerEl, "body-bg", `background-image: url('${banner}'); background-size: cover;`));
        } else {
            headerEl?.appendChild(createBannerEl(doc, titleContainerEl, titleColorClass(format111.metadata[ktitleBlockColor])));
            bannerStyles.push(`background-color: ${banner};`);
        }
        if (bannerStyles.length > 0) {
            createTitleBannerStyleInHead(doc, bannerStyles);
        }
    } else {
        headerEl?.appendChild(titleContainerEl);
    }
    const categoriesEnabled = format111.metadata[kTitleBlockCategories] !== undefined ? format111.metadata[kTitleBlockCategories] : true;
    if (categoriesEnabled) {
        const categories = format111.metadata?.categories ? Array.isArray(format111.metadata?.categories) ? format111.metadata?.categories : [
            format111.metadata?.categories
        ] : undefined;
        if (categories) {
            if (banner) {
                titleContainerEl?.appendChild(createCategoriesEl(doc, categories));
            } else {
                headerEl?.appendChild(createCategoriesEl(doc, categories));
            }
        }
    }
    if (metadataContainerEl.hasChildNodes()) {
        headerEl?.appendChild(metadataContainerEl);
    }
    const abstractEl = headerEl?.querySelector(".abstract");
    if (abstractEl) {
        abstractEl.remove();
        headerEl?.appendChild(abstractEl);
    }
    return resources;
}
function createDescriptionEl(doc, format54) {
    const descriptionEl = doc.createElement("div");
    descriptionEl.classList.add("quarto-description");
    const descriptionP = doc.createElement("p");
    descriptionP.innerText = format54.metadata[kDescription1];
    descriptionEl.appendChild(descriptionP);
    return descriptionEl;
}
function createCategoriesEl(doc, categories) {
    const categoryContainerEl = doc.createElement("div");
    categoryContainerEl.classList.add("quarto-categories");
    categories.forEach((category)=>{
        const categoryEl = doc.createElement("div");
        categoryEl.classList.add("quarto-category");
        categoryEl.innerText = category;
        categoryContainerEl.appendChild(categoryEl);
    });
    return categoryContainerEl;
}
function createDOIMetadataEl(doc, doi, badge) {
    const doiUrl = `https://doi.org/${doi}`;
    const doiLinkEl = doc.createElement("a");
    doiLinkEl.setAttribute("href", doiUrl);
    if (badge) {
        const doiBadge = doc.createElement("img");
        doiBadge.setAttribute("src", `https://zenodo.org/badge/DOI/${doi}.svg`);
        doiLinkEl.appendChild(doiBadge);
    } else {
        doiLinkEl.innerText = doi;
    }
    return metadataEl(doc, false ? "" : "DOI", [
        doiLinkEl
    ]);
}
function isBannerImage(input, banner) {
    if (typeof banner === "string") {
        let path75;
        if (isAbsolute2(banner)) {
            path75 = banner;
        } else {
            path75 = join3(dirname2(input), banner);
        }
        return existsSync(path75);
    } else {
        return false;
    }
}
function createTitleBannerStyleInHead(doc, styles) {
    const bannerStyle = doc.createElement("style");
    bannerStyle.setAttribute("type", "text/css");
    bannerStyle.innerText = `
  main.quarto-banner-title-block .quarto-title-banner {
    ${styles.join("\n")}
  }`;
    const head = doc.querySelector("head");
    head?.appendChild(bannerStyle);
}
function createBannerEl(doc, titleContainerEl, color, style) {
    const mainEl = doc.querySelector("main.content");
    mainEl?.classList.add("quarto-banner-title-block");
    const bannerDiv = doc.createElement("div");
    bannerDiv.classList.add("quarto-title-banner");
    if (color === "navbar") {
        bannerDiv.classList.add("color-navbar");
    } else if (color === "body-bg" || color === "body") {
        bannerDiv.classList.add(`color-${color}`);
    }
    if (style) {
        bannerDiv.setAttribute("style", style);
    }
    titleContainerEl.classList.add("column-body");
    bannerDiv.appendChild(titleContainerEl);
    return bannerDiv;
}
function maybeLinkedNode(doc, text, url) {
    if (url) {
        const affiliationA = doc.createElement("a");
        affiliationA.setAttribute("href", url);
        affiliationA.innerText = text;
        return affiliationA;
    } else {
        return doc.createTextNode(text);
    }
}
function metadataEl(doc, title7, els) {
    const divEl = doc.createElement("div");
    const titleEl = doc.createElement("div");
    titleEl.classList.add("quarto-title-meta-heading");
    titleEl.innerText = title7;
    const contentsEl = doc.createElement("div");
    contentsEl.classList.add("quarto-title-meta-contents");
    for (const el of els){
        contentsEl.appendChild(el);
    }
    divEl.appendChild(titleEl);
    divEl.appendChild(contentsEl);
    return divEl;
}
function formatHasBootstrap(format55) {
    if (format55 && isHtmlOutput(format55.pandoc, true)) {
        return hasBootstrapTheme(format55.metadata);
    } else {
        return false;
    }
}
function hasBootstrapTheme(metadata) {
    const theme = metadata[kTheme];
    return theme !== "none" && theme !== "pandoc";
}
function formatDarkMode(format56) {
    const isBootstrap = formatHasBootstrap(format56);
    if (isBootstrap) {
        return darkModeDefault(format56.metadata);
    }
    return undefined;
}
function darkModeDefault(metadata) {
    if (metadata !== undefined) {
        const theme = metadata[kTheme];
        if (theme && typeof theme === "object") {
            const keys9 = Object.keys(theme);
            if (keys9.includes("dark")) {
                if (keys9[0] === "dark") {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }
    return undefined;
}
function formatPageLayout(format57) {
    return format57.metadata[kPageLayout] || kPageLayoutArticle;
}
function formatHasFullLayout(format58) {
    return format58.metadata[kPageLayout] === kPageLayoutFull;
}
function formatHasArticleLayout(format59) {
    return format59.metadata[kPageLayout] === undefined || format59.metadata[kPageLayout] === kPageLayoutArticle || format59.metadata[kPageLayout] === kPageLayoutFull;
}
function bootstrapFormatDependency() {
    const boostrapResource = (resource)=>formatResourcePath("html", join3("bootstrap", "dist", resource))
    ;
    const bootstrapDependency = (resource)=>({
            name: resource,
            path: boostrapResource(resource)
        })
    ;
    return {
        name: kBootstrapDependencyName,
        stylesheets: [
            bootstrapDependency("bootstrap-icons.css"), 
        ],
        scripts: [
            bootstrapDependency("bootstrap.min.js"), 
        ],
        resources: [
            bootstrapDependency("bootstrap-icons.woff"), 
        ]
    };
}
function boostrapExtras(input, flags, format60, offset) {
    const toc = hasTableOfContents(flags, format60);
    const renderTemplate = (template3, pageLayout)=>{
        return renderEjs(formatResourcePath("html", `templates/${template3}`), {
            toc,
            pageLayout
        });
    };
    const pageLayout1 = formatPageLayout(format60);
    const bodyEnvelope = formatHasArticleLayout(format60) ? {
        before: renderTemplate("before-body-article.ejs", pageLayout1),
        afterPreamble: renderTemplate("after-body-article-preamble.ejs", kPageLayoutArticle),
        afterPostamble: renderTemplate("after-body-article-postamble.ejs", kPageLayoutArticle)
    } : {
        before: renderTemplate("before-body-custom.ejs", kPageLayoutCustom),
        afterPreamble: renderTemplate("after-body-custom-preamble.ejs", kPageLayoutCustom),
        afterPostamble: renderTemplate("after-body-custom-postamble.ejs", kPageLayoutCustom)
    };
    return {
        pandoc: {
            [kSectionDivs]: true,
            [kHtmlMathMethod]: "mathjax"
        },
        metadata: {
            [kDocumentCss]: false,
            [kLinkCitations]: true
        },
        html: {
            [kSassBundles]: resolveBootstrapScss(input, format60),
            [kDependencies]: [
                bootstrapFormatDependency()
            ],
            [kBodyEnvelope]: bodyEnvelope,
            [kHtmlPostprocessors]: [
                bootstrapHtmlPostprocessor(input, format60, flags, offset), 
            ],
            [kHtmlFinalizers]: [
                bootstrapHtmlFinalizer(format60, flags), 
            ]
        }
    };
}
const getColumnLayoutElements = (doc)=>{
    return doc.querySelectorAll('[class^="column-"], [class*=" column-"], aside, [class*="margin-caption"], [class*=" margin-caption"], [class*="margin-ref"], [class*=" margin-ref"]');
};
function bootstrapHtmlPostprocessor(input, format61, flags, offset) {
    return async (doc)=>{
        const title8 = doc.querySelector("header > .title");
        if (title8) {
            title8.classList.add("display-7");
        }
        const subtitle = doc.querySelector("header > .subtitle");
        if (subtitle) {
            subtitle.classList.add("lead");
        }
        const blockquotes = doc.querySelectorAll("blockquote");
        for(let i70 = 0; i70 < blockquotes.length; i70++){
            const classList = blockquotes[i70].classList;
            classList.add("blockquote");
        }
        const figures = doc.querySelectorAll("figure");
        for(let i1 = 0; i1 < figures.length; i1++){
            const figure = figures[i1];
            figure.classList.add("figure");
            const images = figure.querySelectorAll("img");
            for(let j = 0; j < images.length; j++){
                images[j].classList.add("figure-img");
            }
            const captions = figure.querySelectorAll("figcaption");
            for(let j1 = 0; j1 < captions.length; j1++){
                captions[j1].classList.add("figure-caption");
            }
        }
        const toc = doc.querySelector('nav[role="doc-toc"]');
        const tocTarget = doc.getElementById("quarto-toc-target");
        if (toc && tocTarget) {
            const tocLinks = doc.querySelectorAll('nav[role="doc-toc"] > ul a');
            for(let i71 = 0; i71 < tocLinks.length; i71++){
                const tocLink = tocLinks[i71];
                tocLink.classList.add("nav-link");
                if (i71 === 0) {
                    tocLink.classList.add("active");
                }
                if (!tocLink.hasAttribute("data-scroll-target")) {
                    tocLink.setAttribute("data-scroll-target", tocLink.getAttribute("href")?.replaceAll(":", "\\:"));
                }
            }
            const nestedUls = toc.querySelectorAll("ul ul");
            for(let i5 = 0; i5 < nestedUls.length; i5++){
                const ul = nestedUls[i5];
                ul.classList.add("collapse");
            }
            toc.remove();
            tocTarget.replaceWith(toc);
        } else {
            tocTarget?.remove();
        }
        const addTableClasses = (table, computational = false)=>{
            table.classList.add("table");
            if (computational) {
                table.classList.add("table-sm").add("table-striped");
            }
        };
        const tableHeaders = doc.querySelectorAll("tbody > tr:first-child.odd");
        for(let i2 = 0; i2 < tableHeaders.length; i2++){
            const th = tableHeaders[i2];
            if (th.parentNode?.parentNode) {
                const table = th.parentNode.parentNode;
                table.removeAttribute("style");
                addTableClasses(table, !!findParent(table, (el)=>el.classList.contains("cell")
                ));
            }
        }
        const pandasTables = doc.querySelectorAll("table.dataframe");
        for(let i3 = 0; i3 < pandasTables.length; i3++){
            const table = pandasTables[i3];
            table.removeAttribute("border");
            addTableClasses(table, true);
            const headerRows = table.querySelectorAll("tr");
            for(let r = 0; r < headerRows.length; r++){
                headerRows[r].removeAttribute("style");
            }
            if (table.previousElementSibling && table.previousElementSibling.tagName === "STYLE") {
                table.previousElementSibling.remove();
            }
        }
        const sections = doc.querySelectorAll('section[class^="level"]');
        for(let i4 = 0; i4 < sections.length; i4++){
            const section = sections[i4];
            const heading = section.querySelector("h2") || section.querySelector("h3") || section.querySelector("h4") || section.querySelector("h5") || section.querySelector("h6");
            if (heading) {
                heading.setAttribute("data-anchor-id", section.id);
            }
        }
        const resources = [];
        const titleResourceFiles = processDocumentTitle(input, format61, flags, doc, offset);
        resources.push(...titleResourceFiles);
        if (format61.metadata[kAppendixStyle] !== false && format61.metadata[kAppendixStyle] !== "none") {
            await processDocumentAppendix(input, format61, flags, doc, offset);
        }
        return Promise.resolve({
            resources,
            supporting: []
        });
    };
}
function bootstrapHtmlFinalizer(format62, flags) {
    return (doc)=>{
        const { citesInMargin , refsInMargin  } = processColumnElements(doc, format62, flags);
        if (refsInMargin) {
            const footNoteSectionEl = doc.querySelector("section.footnotes");
            if (footNoteSectionEl) {
                footNoteSectionEl.remove();
            }
        }
        if (citesInMargin) {
            const bibliographyDiv = doc.querySelector("div#refs");
            if (bibliographyDiv) {
                bibliographyDiv.remove();
            }
        }
        const fullLayout = formatHasFullLayout(format62);
        if (fullLayout) {
            const column = suggestColumn(doc);
            setMainColumn(doc, column);
        }
        const leftSidebar = doc.getElementById("quarto-sidebar");
        const hasLeftContent = leftSidebar && leftSidebar.children.length > 0;
        const rightSidebar = doc.getElementById("quarto-margin-sidebar");
        const hasRightContent = rightSidebar && rightSidebar.children.length > 0;
        const hasMarginContent = doc.querySelectorAll(".column-margin").length > 0 || doc.querySelectorAll(".margin-caption").length > 0 || doc.querySelectorAll(".margin-ref").length > 0;
        if (rightSidebar && !hasRightContent && !hasMarginContent) {
            rightSidebar.remove();
        }
        const hasColumnElements = getColumnLayoutElements(doc).length > 0;
        if (hasColumnElements) {
            if (hasLeftContent && hasMarginContent) {
                doc.body.classList.add("slimcontent");
            } else if (hasRightContent || hasMarginContent || fullLayout) {} else {
                doc.body.classList.add("fullcontent");
            }
        } else {
            if (!hasRightContent && !hasMarginContent) {
                doc.body.classList.add("fullcontent");
            } else {}
        }
        return Promise.resolve();
    };
}
function processColumnElements(doc, format63, flags) {
    if (!formatHasArticleLayout(format63)) {
        return {
            citesInMargin: false,
            refsInMargin: false
        };
    }
    processMarginCaptions(doc);
    const marginProcessors = [
        simpleMarginProcessor, 
    ];
    const refsInMargin = hasMarginRefs(format63, flags);
    if (refsInMargin) {
        marginProcessors.unshift(footnoteMarginProcessor);
    }
    const citesInMargin = hasMarginCites(format63);
    if (citesInMargin) {
        marginProcessors.push(referenceMarginProcessor);
    }
    processMarginNodes(doc, marginProcessors);
    const columnLayouts = getColumnLayoutElements(doc);
    if (columnLayouts && columnLayouts.length > 0) {
        const processEl = (el)=>{
            if (el.tagName === "DIV" && el.id === "quarto-content") {
                return false;
            } else if (el.tagName === "BODY") {
                return false;
            } else {
                return true;
            }
        };
        const ensureInGrid = (el, setLayout)=>{
            if (processEl(el)) {
                if (!el.classList.contains("page-columns")) {
                    el.classList.add("page-columns");
                }
                if (setLayout && !el.classList.contains("page-full")) {
                    el.classList.add("page-full");
                }
                const parent = el.parentElement;
                if (parent) {
                    ensureInGrid(parent, true);
                }
            }
        };
        columnLayouts.forEach((node)=>{
            const el = node;
            if (el.parentElement) {
                ensureInGrid(el.parentElement, true);
            }
        });
    }
    return {
        citesInMargin,
        refsInMargin
    };
}
const processMarginNodes = (doc, processors)=>{
    const marginSelector = processors.map((proc)=>proc.selector
    ).join(", ");
    const marginNodes = doc.querySelectorAll(marginSelector);
    marginNodes.forEach((marginNode)=>{
        const marginEl = marginNode;
        for (const processor of processors){
            if (processor.canProcess(marginEl)) {
                processor.process(marginEl, doc);
                break;
            }
        }
        marginEl.classList.remove("column-margin");
    });
};
const findQuartoFigure = (el)=>{
    if (el.classList.contains("quarto-figure")) {
        return el;
    } else if (el.parentElement) {
        return findQuartoFigure(el.parentElement);
    } else {
        return undefined;
    }
};
const moveClassToCaption = (container, sel)=>{
    const target = container.querySelector(sel);
    if (target) {
        target.classList.add("margin-caption");
        return true;
    } else {
        return false;
    }
};
const removeCaptionClass = (el)=>{
    el.classList.remove("margin-caption");
};
const processLayoutPanelMarginCaption = (captionContainer)=>{
    const figure = captionContainer.querySelector("figure");
    if (figure) {
        for (const child of figure.children){
            if (child.tagName === "FIGCAPTION") {
                child.classList.add("margin-caption");
                removeCaptionClass(captionContainer);
                break;
            }
        }
    } else {
        const caption = captionContainer.querySelector(".panel-caption");
        if (caption) {
            caption.classList.add("margin-caption");
            removeCaptionClass(captionContainer);
        }
    }
};
const processFigureMarginCaption = (captionContainer, doc)=>{
    const foundCaption = moveClassToCaption(captionContainer, "figcaption");
    if (!foundCaption) {
        const captionEl = captionContainer.querySelector("caption");
        if (captionEl) {
            const parentDivEl = captionEl?.parentElement?.parentElement;
            if (parentDivEl) {
                captionEl.classList.add("hidden");
                const divCopy = doc.createElement("div");
                divCopy.classList.add("figure-caption");
                divCopy.classList.add("margin-caption");
                divCopy.innerHTML = captionEl.innerHTML;
                parentDivEl.appendChild(divCopy);
                removeCaptionClass(captionContainer);
            }
        }
    } else {
        removeCaptionClass(captionContainer);
    }
};
const processMarginCaptions = (doc)=>{
    const marginCaptions = doc.querySelectorAll(".margin-caption");
    marginCaptions.forEach((node)=>{
        const figureEl = node;
        const captionContainer = findQuartoFigure(figureEl);
        if (captionContainer) {
            const isLayoutPanel = captionContainer.classList.contains("quarto-layout-panel");
            if (isLayoutPanel) {
                processLayoutPanelMarginCaption(captionContainer);
            } else {
                processFigureMarginCaption(captionContainer, doc);
            }
        }
        removeCaptionClass(figureEl);
    });
};
const simpleMarginProcessor = {
    selector: ".column-margin:not(.column-container)",
    canProcess (el) {
        return el.classList.contains("column-margin") && !el.classList.contains("column-container");
    },
    process (el, doc) {
        el.classList.remove("column-margin");
        addContentToMarginContainerForEl(el, el, doc);
    }
};
const footnoteMarginProcessor = {
    selector: ".footnote-ref",
    canProcess (el) {
        return el.classList.contains("footnote-ref");
    },
    process (el, doc) {
        if (el.hasAttribute("href")) {
            const target = el.getAttribute("href");
            if (target) {
                const refId = target.slice(1);
                const refContentsEl = doc.getElementById(refId);
                if (refContentsEl) {
                    const backLinkEl = refContentsEl.querySelector(".footnote-back");
                    if (backLinkEl) {
                        backLinkEl.remove();
                    }
                    if (refContentsEl.childNodes.length > 0) {
                        const firstChild = refContentsEl.childNodes[0];
                        firstChild.insertBefore(doc.createTextNode("\u00A0"), firstChild.firstChild);
                        firstChild.insertBefore(el.firstChild.cloneNode(true), firstChild.firstChild);
                    }
                    addContentToMarginContainerForEl(el, refContentsEl, doc);
                }
            }
        }
    }
};
const referenceMarginProcessor = {
    selector: "a[role='doc-biblioref']",
    canProcess (el) {
        return el.hasAttribute("role") && el.getAttribute("role") === "doc-biblioref";
    },
    process (el1, doc) {
        if (el1.hasAttribute("href")) {
            const target = el1.getAttribute("href");
            if (target) {
                const refId = target.slice(1);
                const refContentsEl = doc.getElementById(refId);
                const findCaptionEl = (el)=>{
                    if (el.parentElement?.tagName === "FIGCAPTION") {
                        return el.parentElement;
                    } else if (el.parentElement) {
                        return findCaptionEl(el.parentElement);
                    } else {
                        return undefined;
                    }
                };
                const findNonSpanParentEl = (el)=>{
                    if (el.parentElement && el.parentElement.tagName !== "SPAN") {
                        return el.parentElement;
                    } else if (el.parentElement) {
                        return findNonSpanParentEl(el.parentElement);
                    } else {
                        return undefined;
                    }
                };
                const parentCaptionEl = findCaptionEl(el1);
                if (refContentsEl && parentCaptionEl) {
                    addContentToMarginContainerForEl(parentCaptionEl, refContentsEl.cloneNode(true), doc);
                } else if (refContentsEl) {
                    const nonSpanParent = findNonSpanParentEl(el1);
                    if (nonSpanParent) {
                        addContentToMarginContainerForEl(nonSpanParent, refContentsEl, doc);
                    }
                }
            }
        }
    }
};
const isContainer = (el)=>{
    return el && el.tagName === "DIV" && el.classList.contains("column-container") && el.classList.contains("column-margin");
};
const isAlreadyInMargin = (el)=>{
    const elInMargin = el.classList.contains("column-margin") || el.classList.contains("aside") || el.classList.contains("margin-caption");
    if (elInMargin) {
        return true;
    } else if (el.parentElement !== null) {
        return isAlreadyInMargin(el.parentElement);
    } else {
        return false;
    }
};
const createMarginContainer = (doc)=>{
    const container = doc.createElement("div");
    container.classList.add("no-row-height");
    container.classList.add("column-margin");
    container.classList.add("column-container");
    return container;
};
const marginContainerForEl = (el, doc)=>{
    if (el.parentElement && isAlreadyInMargin(el.parentElement)) {
        return el.parentElement;
    }
    if (el.nextElementSibling && isContainer(el.nextElementSibling)) {
        return el.nextElementSibling;
    }
    if (el.previousElementSibling && isContainer(el.previousElementSibling)) {
        return el.previousElementSibling;
    }
    const list = findOutermostParentElOfType(el, [
        "OL",
        "UL",
        "TABLE"
    ]);
    if (list) {
        if (list.nextElementSibling && isContainer(list.nextElementSibling)) {
            return list.nextElementSibling;
        } else {
            const container = createMarginContainer(doc);
            if (list.parentNode) {
                list.parentNode.insertBefore(container, list.nextElementSibling);
            }
            return container;
        }
    }
    const parentEl = el.parentElement;
    const cantContainBlockTags = [
        "P"
    ];
    if (parentEl && cantContainBlockTags.includes(parentEl.tagName)) {
        if (parentEl.parentElement && parentEl.parentElement.tagName === "DIV" && parentEl.nextElementSibling && isContainer(parentEl.nextElementSibling)) {
            return parentEl.nextElementSibling;
        } else {
            const container = createMarginContainer(doc);
            const wrapper = doc.createElement("div");
            parentEl.replaceWith(wrapper);
            wrapper.appendChild(parentEl);
            wrapper.appendChild(container);
            return container;
        }
    }
    const container = createMarginContainer(doc);
    el.parentNode?.insertBefore(container, el.nextElementSibling);
    return container;
};
const addContentToMarginContainerForEl = (el, content, doc)=>{
    const container = marginContainerForEl(el, doc);
    if (container) {
        container.appendChild(content);
    }
};
const findOutermostParentElOfType = (el, tagNames)=>{
    let outEl = undefined;
    if (el.parentElement) {
        if (el.parentElement.tagName === "MAIN") {
            return outEl;
        } else {
            if (tagNames.includes(el.parentElement.tagName)) {
                outEl = el.parentElement;
            }
            outEl = findOutermostParentElOfType(el.parentElement, tagNames) || outEl;
            return outEl;
        }
    } else {
        return undefined;
    }
};
function suggestColumn(doc) {
    const hasContents = (id)=>{
        const el = doc.getElementById(id);
        if (el === null) {
            return false;
        }
        if (el.children.length > 0) {
            return true;
        }
        return !!el.innerText.trim();
    };
    const leftSidebar = hasContents(kSidebarId);
    const rightSidebar = hasContents(kMarginSidebarId);
    const columnClasses = getColumnClasses(doc);
    const leftContent = [
        ...fullOccludeClz,
        ...leftOccludeClz
    ].some((clz)=>{
        return columnClasses.has(clz);
    });
    const rightContent = [
        ...fullOccludeClz,
        ...rightOccludeClz
    ].some((clz)=>{
        return columnClasses.has(clz);
    });
    const leftUsed = leftSidebar || leftContent;
    const rightUsed = rightSidebar || rightContent;
    if (leftUsed && rightUsed) {
        return "column-body";
    } else if (leftUsed) {
        return "column-page-right";
    } else if (rightUsed) {
        return "column-page-left";
    } else {
        return "column-page";
    }
}
const kSidebarId = "quarto-sidebar";
const kMarginSidebarId = "quarto-margin-sidebar";
const fullOccludeClz = [
    "column-page",
    "column-screen",
    "column-screen-inset", 
];
const leftOccludeClz = [
    "column-page-left",
    "column-screen-inset-left",
    "column-screen-left", 
];
const rightOccludeClz = [
    "column-margin",
    "column-page-right",
    "column-screen-inset-right",
    "column-screen-right",
    "margin-caption",
    "margin-ref", 
];
const getColumnClasses = (doc)=>{
    const classes = new Set();
    const colNodes = getColumnLayoutElements(doc);
    for (const colNode of colNodes){
        const colEl = colNode;
        colEl.classList.forEach((clz)=>{
            if (clz === "margin-caption" || clz === "margin-ref" || clz.startsWith("column-")) {
                classes.add(clz);
            }
        });
    }
    return classes;
};
const kHideAllCodeLinkId = "quarto-hide-all-code";
const kShowAllCodeLinkId = "quarto-show-all-code";
const kViewSourceLinkId = "quarto-view-source";
const kEmbeddedSourceClass = "quarto-embedded-source-code";
const kEmbeddedSourceModalId = kEmbeddedSourceClass + "-modal";
const kEmbeddedSourceModalLabelId = kEmbeddedSourceClass + "-modal-label";
const kKeepSourceSentinel = "quarto-executable-code-5450563D";
const kCodeToolsSourceButtonId = "quarto-code-tools-source";
const kCodeToolsMenuButtonId = "quarto-code-tools-menu";
const kDataQuartoSourceUrl = "data-quarto-source-url";
function formatHasCodeTools(format64) {
    const codeTools = format64.render?.[kCodeTools];
    return !!codeTools && isHtmlOutput(format64.pandoc, true) && formatHasBootstrap(format64);
}
function resolveKeepSource(format65, engine, target) {
    const codeTools = format65.render?.[kCodeTools];
    if (codeTools === true || typeof codeTools === "object" && (codeTools?.source === undefined || codeTools?.source === true)) {
        format65.render[kKeepSource] = true;
    }
    format65.render[kKeepSource] = format65.render[kKeepSource] && isHtmlOutput(format65.pandoc, true) && formatHasBootstrap(format65) && executionEngineCanKeepSource(engine, target);
}
function keepSourceBlock(format66, source) {
    if (format66.render[kKeepSource]) {
        let code21 = Deno.readTextFileSync(source).trimLeft();
        if (!code21.endsWith("\n")) {
            code21 = code21 + "\n";
        }
        code21 = code21.replaceAll(/\n```{(\w+)}\s*\n/g, "\n" + kKeepSourceSentinel + "\n\n```$1\n");
        const kKeepSourceBackticks = "```````````````````";
        return `${kMarkdownBlockSeparator}::: {.${kEmbeddedSourceClass}}\n${kKeepSourceBackticks}` + `{.markdown shortcodes="false"}\n${code21}` + `${kKeepSourceBackticks}\n:::\n`;
    } else {
        return "";
    }
}
function codeToolsPostprocessor(format67) {
    return (doc)=>{
        if (format67.render[kKeepSource]) {
            const lines9 = doc.querySelectorAll(`.${kEmbeddedSourceClass} > div.sourceCode > pre > code > span`);
            if (lines9.length > 0) {
                const newLines = [];
                for(let i72 = 0; i72 < lines9.length; i72++){
                    const line = lines9[i72];
                    if (line.innerText === kKeepSourceSentinel) {
                        i72 += 2;
                        const codeBlockLine = lines9[i72];
                        const codeSpan = codeBlockLine.lastChild;
                        if (codeSpan.innerHTML) {
                            codeSpan.innerHTML = codeSpan.innerHTML.replace(/```(\w+)/, "```{$1}");
                        }
                        newLines.push(codeBlockLine);
                    } else {
                        newLines.push(line);
                    }
                }
                if (newLines.length !== lines9.length) {
                    const parent = lines9[0].parentElement;
                    parent.innerHTML = "";
                    newLines.forEach((line)=>{
                        parent.appendChild(line);
                        parent.appendChild(doc.createTextNode("\n"));
                    });
                }
            }
        }
        if (formatHasCodeTools(format67)) {
            const codeTools = resolveCodeTools(format67, doc);
            if (codeTools.source || codeTools.toggle) {
                const title9 = doc.querySelector("#title-block-header > h1");
                if (title9) {
                    const header = title9.parentElement;
                    const titleDiv = doc.createElement("div");
                    titleDiv.classList.add("quarto-title-block");
                    const layoutDiv = doc.createElement("div");
                    titleDiv.appendChild(layoutDiv);
                    header?.replaceChild(titleDiv, title9);
                    layoutDiv.appendChild(title9);
                    const button = doc.createElement("button");
                    button.setAttribute("type", "button");
                    button.classList.add("btn").add("code-tools-button");
                    const icon = doc.createElement("i");
                    icon.classList.add("bi");
                    button.appendChild(icon);
                    if (codeTools.caption !== "none") {
                        button.appendChild(doc.createTextNode(" " + codeTools.caption));
                    }
                    layoutDiv.appendChild(button);
                    header.appendChild(titleDiv);
                    if (codeTools.toggle) {
                        button.setAttribute("id", kCodeToolsMenuButtonId);
                        button.classList.add("dropdown-toggle");
                        button.setAttribute("data-bs-toggle", "dropdown");
                        button.setAttribute("aria-expanded", "false");
                        const ul = doc.createElement("ul");
                        ul.classList.add("dropdown-menu").add("dropdown-menu-end");
                        ul.setAttribute("aria-labelelledby", kCodeToolsMenuButtonId);
                        const addListItem = (id, text)=>{
                            const a = doc.createElement("a");
                            a.setAttribute("id", id);
                            a.classList.add("dropdown-item");
                            a.setAttribute("href", "javascript:void(0)");
                            a.setAttribute("role", "button");
                            a.appendChild(doc.createTextNode(text));
                            const li = doc.createElement("li");
                            li.appendChild(a);
                            ul.appendChild(li);
                            return li;
                        };
                        const addDivider = ()=>{
                            const hr = doc.createElement("hr");
                            hr.classList.add("dropdown-divider");
                            const li = doc.createElement("li");
                            li.appendChild(hr);
                            ul.appendChild(li);
                        };
                        addListItem(kShowAllCodeLinkId, format67.language[kCodeToolsShowAllCode]);
                        addListItem(kHideAllCodeLinkId, format67.language[kCodeToolsHideAllCode]);
                        if (codeTools.source) {
                            addDivider();
                            const vsLi = addListItem(kViewSourceLinkId, format67.language[kCodeToolsViewSource]);
                            if (typeof codeTools.source === "string") {
                                vsLi.firstChild.setAttribute(kDataQuartoSourceUrl, codeTools.source);
                            }
                        }
                        layoutDiv.appendChild(ul);
                    } else {
                        button.setAttribute("id", kCodeToolsSourceButtonId);
                        if (typeof codeTools.source === "string") {
                            button.setAttribute(kDataQuartoSourceUrl, codeTools.source);
                        }
                    }
                }
                if (codeTools.source) {
                    const embeddedCode = doc.querySelector(`.${kEmbeddedSourceClass}`);
                    if (embeddedCode) {
                        const modalDiv = doc.createElement("div");
                        modalDiv.classList.add("modal").add("fade");
                        modalDiv.setAttribute("id", kEmbeddedSourceModalId);
                        modalDiv.setAttribute("tabindex", "-1");
                        modalDiv.setAttribute("aria-labelledby", kEmbeddedSourceModalLabelId);
                        modalDiv.setAttribute("aria-hidden", "true");
                        const modalDialogDiv = doc.createElement("div");
                        modalDialogDiv.classList.add("modal-dialog").add("modal-dialog-scrollable");
                        const modalContentDiv = doc.createElement("div");
                        modalContentDiv.classList.add("modal-content");
                        const modalDialogHeader = doc.createElement("div");
                        modalDialogHeader.classList.add("modal-header");
                        const h5 = doc.createElement("h5");
                        h5.classList.add("modal-title");
                        h5.setAttribute("id", kEmbeddedSourceModalLabelId);
                        h5.appendChild(doc.createTextNode(format67.language[kCodeToolsSourceCode]));
                        modalDialogHeader.appendChild(h5);
                        const button = doc.createElement("button");
                        button.classList.add("btn-close");
                        button.setAttribute("data-bs-dismiss", "modal");
                        modalDialogHeader.appendChild(button);
                        modalContentDiv.appendChild(modalDialogHeader);
                        const modalBody = doc.createElement("div");
                        modalBody.classList.add("modal-body");
                        modalContentDiv.appendChild(modalBody);
                        modalDialogDiv.appendChild(modalContentDiv);
                        modalDiv.appendChild(modalDialogDiv);
                        embeddedCode.parentElement?.insertBefore(modalDiv, embeddedCode);
                        modalBody.appendChild(embeddedCode);
                        embeddedCode.classList.delete(kEmbeddedSourceClass);
                    }
                }
            }
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function resolveCodeTools(format68, doc) {
    const kCodeCaption = format68.language[kCodeToolsMenuCaption];
    const codeTools = format68?.render[kCodeTools];
    const codeToolsResolved = {
        source: typeof codeTools === "boolean" ? codeTools : codeTools?.source !== undefined ? codeTools?.source : true,
        toggle: typeof codeTools === "boolean" ? codeTools : codeTools?.toggle !== undefined ? !!codeTools?.toggle : true,
        caption: typeof codeTools === "boolean" ? kCodeCaption : codeTools?.caption || kCodeCaption
    };
    if (codeToolsResolved.source) {
        codeToolsResolved.source = !!format68.render[kKeepSource];
    }
    if (codeToolsResolved.toggle) {
        const codeDetails = doc.querySelector(".cell > details > .sourceCode");
        const codeHidden = doc.querySelector(".cell .sourceCode.hidden");
        codeToolsResolved.toggle = codeToolsResolved.toggle && (!!codeDetails || !!codeHidden);
    }
    return codeToolsResolved;
}
function createFormat(ext, ...formats4) {
    return mergeConfigs(defaultFormat(), ...formats4, {
        render: {
            [kOutputExt]: ext
        }
    });
}
function createHtmlFormat(figwidth, figheight) {
    return createFormat("html", {
        metadata: {
            [kLang]: "en",
            [kFigResponsive]: true
        },
        execute: {
            [kFigFormat]: "retina",
            [kFigWidth]: figwidth,
            [kFigHeight]: figheight
        },
        render: {
            [kTblColwidths]: "auto"
        },
        pandoc: {
            [kStandalone]: true,
            [kWrap]: "none",
            [kDefaultImageExtension]: "png"
        }
    });
}
function createHtmlPresentationFormat(figwidth, figheight) {
    return mergeConfigs(createHtmlFormat(figwidth, figheight), {
        metadata: {
            [kFigResponsive]: false
        },
        execute: {
            [kEcho]: false,
            [kWarning]: false
        }
    });
}
function createEbookFormat(ext) {
    return createFormat(ext, {
        formatExtras: ()=>{
            return {
                [kIncludeInHeader]: [
                    formatResourcePath("html", "styles-callout.html"),
                    formatResourcePath("epub", "styles.html"), 
                ]
            };
        },
        render: {
            [kMergeIncludes]: false
        },
        execute: {
            [kFigWidth]: 5,
            [kFigHeight]: 4
        },
        pandoc: {
            [kDefaultImageExtension]: "png"
        }
    });
}
function createWordprocessorFormat(ext) {
    return createFormat(ext, {
        render: {
            [kPageWidth]: 6.5
        },
        execute: {
            [kFigWidth]: 5,
            [kFigHeight]: 4
        },
        pandoc: {
            [kDefaultImageExtension]: "png"
        }
    });
}
function defaultFormat() {
    return {
        execute: {
            [kFigWidth]: 7,
            [kFigHeight]: 5,
            [kFigFormat]: "png",
            [kFigDpi]: 96,
            [kError]: false,
            [kEval]: true,
            [kCache]: null,
            [kFreeze]: false,
            [kEcho]: true,
            [kOutput]: true,
            [kWarning]: true,
            [kInclude]: true,
            [kKeepMd]: false,
            [kKeepIpynb]: false,
            [kExecuteIpynb]: null,
            [kExecuteEnabled]: null,
            [kExecuteDaemon]: null,
            [kExecuteDaemonRestart]: false,
            [kExecuteDebug]: false
        },
        render: {
            [kKeepTex]: false,
            [kKeepYaml]: false,
            [kKeepSource]: false,
            [kKeepHidden]: false,
            [kPreferHtml]: false,
            [kOutputDivs]: true,
            [kOutputExt]: "html",
            [kFigAlign]: "default",
            [kFigPos]: null,
            [kFigEnv]: null,
            [kCodeFold]: "none",
            [kCodeOverflow]: "scroll",
            [kCodeLink]: false,
            [kCodeLineNumbers]: false,
            [kCodeTools]: false,
            [kTblColwidths]: true,
            [kMergeIncludes]: true,
            [kSelfContainedMath]: false,
            [kLatexAutoMk]: true,
            [kLatexAutoInstall]: true,
            [kLatexClean]: true,
            [kLatexMaxRuns]: 1,
            [kLatexMaxRuns]: 10,
            [kLatexMakeIndex]: "makeindex",
            [kLatexMakeIndexOpts]: [],
            [kLatexTlmgrOpts]: [],
            [kLatexOutputDir]: null,
            [kLinkExternalIcon]: false,
            [kLinkExternalNewwindow]: false
        },
        pandoc: {},
        language: {},
        metadata: {}
    };
}
function getDiscussionCategoryId(categoryName, metadata) {
    if (metadata.categories) {
        for (const category of metadata.categories){
            if (category.name === categoryName) {
                return category.id;
            }
        }
    }
    return undefined;
}
async function getGithubDiscussionsMetadata(repo) {
    const url = encodeURI(`https://giscus.app/api/discussions/categories?repo=${repo}`);
    const response = await fetch(url);
    const jsonObj = await response.json();
    return jsonObj;
}
const kGoogleScholar = "google-scholar";
function metadataPostProcessor(input, format69, offset) {
    return async (doc)=>{
        if (googleScholarEnabled(format69)) {
            const csl = documentCSL(input, format69, "webpage", offset);
            const documentMetadata = googleScholarMeta(csl);
            const referenceMetadata = await googleScholarReferences(input, format69);
            [
                ...documentMetadata,
                ...referenceMetadata
            ].forEach((meta)=>{
                writeMetaTag(meta.name, meta.content, doc);
            });
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function googleScholarEnabled(format70) {
    if (format70.metadata[kGoogleScholar] === true) {
        return true;
    }
    const siteMeta = format70.metadata[kWebsite];
    if (siteMeta && siteMeta[kGoogleScholar] === true) {
        return true;
    }
    return false;
}
function googleScholarMeta(csl) {
    const scholarMeta = [];
    const write = metadataWriter(scholarMeta);
    if (csl.title) {
        write("citation_title", csl.title);
    }
    if (csl.author) {
        csl.author.forEach((author)=>{
            write("citation_author", author.literal || `${author.given} ${author.family}`);
        });
    }
    if (csl["available-date"]) {
        write("citation_online_date", cslDateToEDTFDate(csl["available-date"]));
    }
    if (csl.URL) {
        write("citation_fulltext_html_url", csl.URL);
    }
    if (csl.issued) {
        write("citation_publication_date", cslDateToEDTFDate(csl.issued));
    }
    if (csl.issue) {
        write("citation_issue", csl.issue);
    }
    if (csl.ISBN) {
        write("citation_isbn", csl.ISBN);
    }
    if (csl.ISSN) {
        write("citation_issn", csl.ISSN);
    }
    if (csl.volume) {
        write("citation_volume", csl.volume);
    }
    if (csl["page-first"]) {
        write("citation_firstpage", csl["page-first"]);
    }
    if (csl["page-last"]) {
        write("citation_lastpage", csl["page-last"]);
    }
    const type = csl.type;
    if (type === "paper-conference") {
        write("citation_conference_title", csl["container-title"]);
    } else if (type === "thesis") {
        write("citation_dissertation_institution", csl.publisher);
    } else if (type === "report") {
        if (csl.publisher) {
            write("citation_technical_report_institution", csl.publisher);
        }
        if (csl.number) {
            write("citation_technical_report_number", csl.number);
        }
    } else {
        write("citation_journal_title", csl["container-title"]);
    }
    return scholarMeta;
}
async function googleScholarReferences(input, format71) {
    const scholarMeta = [];
    const write = metadataWriter(scholarMeta);
    const references = await bibliographyCslJson(input, format71);
    if (references) {
        references.forEach((reference)=>{
            const refMetas = googleScholarMeta(reference);
            const metaStrs = refMetas.map((refMeta)=>{
                return `${refMeta.name}=${refMeta.content};`;
            });
            write("citation_reference", metaStrs.join());
        });
    }
    return scholarMeta;
}
function metadataWriter(metadata) {
    const write = (key, value)=>{
        metadata.push({
            name: key,
            content: encodeAttributeValue(value)
        });
    };
    return write;
}
function htmlFormat(figwidth, figheight) {
    return mergeConfigs(createHtmlFormat(figwidth, figheight), {
        resolveFormat: (format72)=>{
            if (format72.metadata[kMinimal] === true) {
                if (format72.metadata[kFigResponsive] === undefined) {
                    format72.metadata[kFigResponsive] = false;
                }
                if (format72.metadata[kTheme] === undefined) {
                    format72.metadata[kTheme] = "none";
                }
            }
        },
        formatExtras: async (input, flags, format73, _libDir, temp, offset)=>{
            const htmlFilterParams = htmlFormatFilterParams(format73);
            return mergeConfigs(await htmlFormatExtras(input, offset, format73, temp), themeFormatExtras(input, flags, format73, offset), {
                [kFilterParams]: htmlFilterParams
            });
        },
        extensions: {
            book: {
                multiFile: true
            }
        }
    });
}
const kQuartoHtmlDependency = "quarto-html";
async function htmlFormatExtras(input, offset, format74, temp, featureDefaults, tippyOptions, scssOptions) {
    const bootstrap = formatHasBootstrap(format74);
    if (!featureDefaults) {
        featureDefaults = htmlFormatFeatureDefaults(format74);
    }
    if (!tippyOptions) {
        tippyOptions = {};
    }
    if (!tippyOptions.config) {
        tippyOptions.config = {};
    }
    if (!scssOptions) {
        scssOptions = {};
    }
    if (scssOptions.quartoBase === undefined) {
        scssOptions.quartoBase = true;
    }
    if (scssOptions.quartoCssVars === undefined) {
        scssOptions.quartoCssVars = true;
    }
    const scripts = [];
    const stylesheets = [];
    const sassBundles = [];
    const dependencies = [];
    const options = format74.metadata[kComments] ? {
        [kHypothesis]: format74.metadata[kComments][kHypothesis] || false,
        [kUtterances]: format74.metadata[kComments][kUtterances] || false,
        [kGiscus]: format74.metadata[kComments][kGiscus] || false
    } : {};
    options.codeLink = format74.metadata[kCodeLink] || false;
    if (featureDefaults.tabby) {
        options.tabby = format74.metadata[kTabsets] !== false;
    } else {
        options.tabby = format74.metadata[kTabsets] || false;
    }
    if (featureDefaults.copyCode) {
        options.copyCode = format74.metadata[kCodeCopy] !== false;
    } else {
        options.copyCode = format74.metadata[kCodeCopy] || false;
    }
    if (featureDefaults.anchors) {
        options.anchors = format74.metadata[kAnchorSections] !== false;
    } else {
        options.anchors = format74.metadata[kAnchorSections] || false;
    }
    if (featureDefaults.hoverCitations) {
        options.hoverCitations = format74.metadata[kCitationsHover] !== false;
    } else {
        options.hoverCitations = format74.metadata[kCitationsHover] || false;
    }
    if (featureDefaults.hoverFootnotes) {
        options.hoverFootnotes = format74.metadata[kFootnotesHover] !== false;
    } else {
        options.hoverFootnotes = format74.metadata[kFootnotesHover] || false;
    }
    if (featureDefaults.figResponsive) {
        options.figResponsive = format74.metadata[kFigResponsive] !== false;
    } else {
        options.figResponsive = format74.metadata[kFigResponsive] || false;
    }
    options.codeTools = formatHasCodeTools(format74);
    options.darkMode = formatDarkMode(format74);
    options.darkModeDefault = darkModeDefault(format74.metadata);
    options.linkExternalIcon = format74.render[kLinkExternalIcon];
    options.linkExternalNewwindow = format74.render[kLinkExternalNewwindow];
    options.linkExternalFilter = format74.render[kLinkExternalFilter];
    const siteMetadata = format74.metadata[kWebsite];
    if (!options.linkExternalFilter && siteMetadata) {
        const siteUrl = siteMetadata[kSiteUrl];
        if (siteUrl) {
            options.linkExternalFilter = siteUrl.replaceAll(".", "\\.").replaceAll("/", "\\/");
        }
    }
    if (bootstrap) {
        scripts.push({
            name: "quarto.js",
            path: formatResourcePath("html", "quarto.js")
        });
    }
    if (options.tabby) {
        scripts.push({
            name: "tabby.min.js",
            path: formatResourcePath("html", join3("tabby", "js", "tabby.js"))
        });
    }
    options.tippy = options.hoverCitations || options.hoverFootnotes;
    if (bootstrap || options.tippy) {
        scripts.push({
            name: "popper.min.js",
            path: formatResourcePath("html", join3("popper", "popper.min.js"))
        });
    }
    if (options.tippy) {
        scripts.push({
            name: "tippy.umd.min.js",
            path: formatResourcePath("html", join3("tippy", "tippy.umd.min.js"))
        });
        stylesheets.push({
            name: "tippy.css",
            path: formatResourcePath("html", join3("tippy", "tippy.css"))
        });
        if (tippyOptions.theme === undefined) {
            if (bootstrap) {
                tippyOptions.theme = "quarto";
                sassBundles.push({
                    key: "tippy.scss",
                    dependency: kBootstrapDependencyName,
                    quarto: {
                        uses: "",
                        functions: "",
                        defaults: "",
                        mixins: "",
                        rules: Deno.readTextFileSync(formatResourcePath("html", join3("tippy", "_tippy.scss")))
                    }
                });
            } else {
                tippyOptions.theme = "light-border";
                stylesheets.push({
                    name: "light-border.css",
                    path: formatResourcePath("html", join3("tippy", "light-border.css"))
                });
            }
        }
    }
    options.tippyOptions = tippyOptions;
    if (options.copyCode) {
        dependencies.push(clipboardDependency());
    }
    if (options.anchors) {
        scripts.push({
            name: "anchor.min.js",
            path: formatResourcePath("html", join3("anchor", "anchor.min.js"))
        });
        options.anchors = typeof options.anchors === "string" ? options.anchors : true;
    }
    if (!bootstrap) {
        if (scssOptions.quartoBase) {
            sassBundles.push({
                dependency: kQuartoHtmlDependency,
                key: kQuartoHtmlDependency,
                quarto: quartoBaseLayer(format74, !!options.copyCode, !!options.tabby, !!options.figResponsive)
            });
        }
        if (scssOptions.quartoCssVars) {
            sassBundles.push({
                dependency: kQuartoHtmlDependency,
                key: kQuartoHtmlDependency,
                quarto: {
                    uses: "",
                    defaults: "",
                    functions: "",
                    mixins: "",
                    rules: quartoGlobalCssVariableRules()
                }
            });
        }
    }
    const includeInHeader = [];
    if (options.hypothesis) {
        const hypothesisHeader = temp.createFile({
            suffix: ".html"
        });
        Deno.writeTextFileSync(hypothesisHeader, renderEjs(formatResourcePath("html", join3("hypothesis", "hypothesis.ejs")), {
            hypothesis: options.hypothesis
        }));
        includeInHeader.push(hypothesisHeader);
    }
    const includeAfterBody = [];
    const quartoHtmlRequired = Object.keys(options).some((option)=>!!options[option]
    );
    if (quartoHtmlRequired) {
        const quartoHtmlScript = temp.createFile();
        Deno.writeTextFileSync(quartoHtmlScript, renderEjs(formatResourcePath("html", join3("templates", "quarto-html.ejs")), options));
        includeAfterBody.push(quartoHtmlScript);
    }
    if (options.utterances) {
        if (typeof options.utterances !== "object") {
            throw new Error("Invalid utterances configuration (must provide a repo");
        }
        const utterances = options.utterances;
        if (!utterances["repo"]) {
            throw new Error("Invalid utterances coniguration (must provide a repo)");
        }
        utterances["issue-term"] = utterances["issue-term"] || "pathname";
        utterances["theme"] = utterances["theme"] || "github-light";
        const utterancesAfterBody = temp.createFile({
            suffix: ".html"
        });
        Deno.writeTextFileSync(utterancesAfterBody, renderEjs(formatResourcePath("html", join3("utterances", "utterances.ejs")), {
            utterances
        }));
        includeAfterBody.push(utterancesAfterBody);
    }
    if (options.giscus) {
        const giscus = options.giscus;
        giscus.category = giscus.category || "General";
        giscus.theme = giscus.theme || "light";
        giscus.mapping = giscus.mapping || "title";
        giscus["reactions-enabled"] = giscus["reactions-enabled"] !== undefined ? giscus["reactions-enabled"] : true;
        giscus["input-position"] = giscus["input-position"] || "top";
        giscus.language = giscus.language || "en";
        if (giscus[kGiscusRepoId] === undefined || giscus[kGiscusCategoryId] === undefined) {
            const discussionData = await getGithubDiscussionsMetadata(giscus.repo);
            if (giscus[kGiscusRepoId] === undefined && discussionData.repositoryId) {
                giscus[kGiscusRepoId] = discussionData.repositoryId;
            }
            const categoryId = getDiscussionCategoryId(giscus.category, discussionData);
            if (giscus[kGiscusCategoryId] === undefined && categoryId) {
                giscus[kGiscusCategoryId] = categoryId;
            }
        }
        const giscusAfterBody = temp.createFile({
            suffix: ".html"
        });
        Deno.writeTextFileSync(giscusAfterBody, renderEjs(formatResourcePath("html", join3("giscus", "giscus.ejs")), {
            giscus
        }));
        includeAfterBody.push(giscusAfterBody);
    }
    dependencies.push({
        name: kQuartoHtmlDependency,
        scripts,
        stylesheets
    });
    return {
        [kIncludeInHeader]: includeInHeader,
        [kIncludeAfterBody]: includeAfterBody,
        html: {
            [kDependencies]: dependencies,
            [kSassBundles]: sassBundles,
            [kHtmlPostprocessors]: [
                htmlFormatPostprocessor(format74, featureDefaults),
                metadataPostProcessor(input, format74, offset), 
            ]
        }
    };
}
const kFormatHasBootstrap = "has-bootstrap";
function htmlFormatFilterParams(format75) {
    return {
        [kFormatHasBootstrap]: formatHasBootstrap(format75)
    };
}
function htmlFormatFeatureDefaults(format76) {
    const bootstrap = formatHasBootstrap(format76);
    const minimal = format76.metadata[kMinimal] === true;
    return {
        tabby: !minimal && !bootstrap,
        copyCode: !minimal,
        anchors: !minimal,
        hoverCitations: !minimal,
        hoverFootnotes: !minimal,
        figResponsive: !minimal
    };
}
function htmlFormatPostprocessor(format77, featureDefaults) {
    const haveBootstrap = formatHasBootstrap(format77);
    if (!featureDefaults) {
        featureDefaults = htmlFormatFeatureDefaults(format77);
    }
    const codeCopy = featureDefaults.copyCode ? format77.metadata[kCodeCopy] !== false : format77.metadata[kCodeCopy] || false;
    const anchors = featureDefaults.anchors ? format77.metadata[kAnchorSections] !== false : format77.metadata[kAnchorSections] || false;
    return (doc)=>{
        const codeBlocks = doc.querySelectorAll("pre.sourceCode");
        for(let i2 = 0; i2 < codeBlocks.length; i2++){
            const code22 = codeBlocks[i2];
            if (code22.classList.contains("hidden")) {
                code22.classList.delete("hidden");
                code22.parentElement?.classList.add("hidden");
            }
            if (codeCopy) {
                code22.classList.add("code-with-copy");
                const copyButton = createCodeCopyButton(doc, format77);
                code22.appendChild(copyButton);
            }
            if (code22.parentElement?.getAttribute("data-code-preview")) {
                const codeExample = doc.createElement("iframe");
                for (const parentClass of code22.classList){
                    codeExample.classList.add(parentClass);
                }
                codeExample.setAttribute("src", code22.parentElement.getAttribute("data-code-preview").replace(/\.qmd$/, ".html"));
                code22.parentElement.removeAttribute("data-code-preview");
                code22.parentElement.appendChild(codeExample);
            }
        }
        if (anchors) {
            const container = haveBootstrap ? doc.querySelector("main") : doc.querySelector("body");
            if (container) {
                [
                    "h2",
                    "h3",
                    "h4",
                    "h5",
                    "h6",
                    ".quarto-figure[id]",
                    "div[id^=tbl-]"
                ].forEach((selector)=>{
                    const headings = container.querySelectorAll(selector);
                    for(let i73 = 0; i73 < headings.length; i73++){
                        const heading = headings[i73];
                        if (heading.id !== "toc-title") {
                            if (!heading.classList.contains("no-anchor")) {
                                heading.classList.add("anchored");
                            }
                        }
                    }
                });
            }
        }
        const headerSections = doc.querySelectorAll(".header-section-number");
        for(let i1 = 0; i1 < headerSections.length; i1++){
            const secNumber = headerSections[i1];
            const prevElement = secNumber.previousElementSibling;
            if (prevElement && prevElement.classList.contains("toc-section-number")) {
                prevElement.remove();
            }
        }
        const doi = format77.metadata[kDoi];
        if (typeof doi === "string") {
            const header = doc.getElementById("title-block-header");
            if (header) {
                const p = doc.createElement("p");
                p.classList.add("doi");
                const doiUrl = `https://doi.org/${doi}`;
                const a = doc.createElement("a");
                a.innerHTML = doiUrl;
                a.setAttribute("href", doiUrl);
                p.appendChild(a);
                header.appendChild(p);
            }
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function themeFormatExtras(input, flags, format78, offset) {
    const theme = format78.metadata[kTheme];
    if (theme === "none") {
        return {
            metadata: {
                [kDocumentCss]: false
            }
        };
    } else if (theme === "pandoc") {
        return pandocExtras(format78);
    } else {
        return boostrapExtras(input, flags, format78, offset);
    }
}
function pandocExtras(format79) {
    const maxWidth = format79.metadata["max-width"];
    const headerIncludes = maxWidth ? `<style type="text/css">body { max-width: ${asCssSize(maxWidth)};}</style>` : undefined;
    return {
        metadata: {
            [kDocumentCss]: true,
            [kHeaderIncludes]: headerIncludes
        }
    };
}
async function resolveSassBundles(extras, pandoc, temp, formatBundles, projectBundles, project) {
    extras = cloneDeep1(extras);
    const mergedBundles = {};
    const group = (bundles, groupedBundles)=>{
        bundles.forEach((bundle)=>{
            if (!groupedBundles[bundle.dependency]) {
                groupedBundles[bundle.dependency] = [];
            }
            groupedBundles[bundle.dependency].push(bundle);
        });
    };
    if (projectBundles) {
        group(projectBundles, mergedBundles);
    }
    if (formatBundles) {
        group(formatBundles, mergedBundles);
    }
    let hasDarkStyles = false;
    let defaultStyle = undefined;
    for (const dependency of Object.keys(mergedBundles)){
        const bundles = mergedBundles[dependency];
        const hasDark = bundles.some((bundle)=>bundle.dark !== undefined
        );
        defaultStyle = bundles.some((bundle)=>bundle.dark !== undefined && bundle.dark.default
        ) ? "dark" : "light";
        const targets = [
            {
                name: `${dependency}.min.css`,
                bundles,
                attribs: {}
            }
        ];
        if (hasDark) {
            targets[0].attribs = {
                ...targets[0].attribs,
                ...attribForThemeStyle("light", defaultStyle)
            };
            const darkBundles = bundles.map((bundle)=>{
                bundle = cloneDeep1(bundle);
                bundle.user = bundle.dark?.user || bundle.user;
                bundle.quarto = bundle.dark?.quarto || bundle.quarto;
                bundle.framework = bundle.dark?.framework || bundle.framework;
                bundle.key = bundle.key + "-dark";
                return bundle;
            });
            targets.push({
                name: `${dependency}-dark.min.css`,
                bundles: darkBundles,
                attribs: attribForThemeStyle("dark", defaultStyle)
            });
            hasDarkStyles = true;
        }
        for (const target of targets){
            let cssPath = await compileSass(target.bundles, temp);
            cssPath = processCssIntoExtras(cssPath, extras, temp);
            const css = Deno.readTextFileSync(cssPath);
            const toDependencies = (paths)=>{
                return paths.map((path76)=>{
                    return {
                        name: path76,
                        path: project ? join3(project.dir, path76) : path76,
                        attribs: target.attribs
                    };
                });
            };
            const resources = toDependencies(cssResources(css));
            const imports = toDependencies(cssImports(css));
            const extraDeps = extras.html?.[kDependencies];
            if (extraDeps) {
                const existingDependency = extraDeps.find((extraDep)=>extraDep.name === dependency
                );
                if (existingDependency) {
                    if (!existingDependency.stylesheets) {
                        existingDependency.stylesheets = [];
                    }
                    existingDependency.stylesheets.push({
                        name: target.name,
                        path: cssPath,
                        attribs: target.attribs
                    });
                    existingDependency.stylesheets.push(...imports);
                    existingDependency.resources?.push(...resources);
                } else {
                    extraDeps.push({
                        name: dependency,
                        stylesheets: [
                            {
                                name: target.name,
                                path: cssPath,
                                attribs: target.attribs
                            },
                            ...imports
                        ],
                        resources
                    });
                }
            }
        }
    }
    extras = await resolveQuartoSyntaxHighlighting(extras, pandoc, temp, hasDarkStyles ? "light" : "default", defaultStyle);
    if (hasDarkStyles) {
        extras = await resolveQuartoSyntaxHighlighting(extras, pandoc, temp, "dark", defaultStyle);
    }
    setTextHighlightStyle("none", extras);
    return extras;
}
function cssHasDarkModeSentinel(css) {
    return !!css.match(/\/\*! dark \*\//g);
}
async function resolveQuartoSyntaxHighlighting(extras, pandoc, temp, style, defaultStyle) {
    extras = cloneDeep1(extras);
    const mediaAttr = attribForThemeStyle(style, defaultStyle);
    if (style === "default") {
        if (extras.html?.[kTextHighlightingMode] === "dark") {
            style = "dark";
        }
    }
    const cssFileName = `quarto-syntax-highlighting${style === "dark" ? "-dark" : ""}.css`;
    const theme = pandoc[kHighlightStyle] || kDefaultHighlightStyle;
    if (theme) {
        const themeRaw = readTheme(theme, style);
        if (themeRaw) {
            const themeJson = JSON.parse(themeRaw);
            const extraVariables = extras.html?.[kQuartoCssVariables] || [];
            const highlightCss = generateThemeCssVars(themeJson);
            if (highlightCss) {
                const rules = [
                    highlightCss,
                    "",
                    "/* other quarto variables */",
                    ...extraVariables, 
                ];
                const textHighlightCssRules = generateThemeCssClasses(themeJson);
                if (textHighlightCssRules) {
                    rules.push(...textHighlightCssRules);
                }
                const highlightCssPath = await compileSass([
                    {
                        key: cssFileName,
                        quarto: {
                            uses: "",
                            defaults: "",
                            functions: "",
                            mixins: "",
                            rules: rules.join("\n")
                        }
                    }
                ], temp, false);
                const extraDeps = extras.html?.[kDependencies];
                if (extraDeps) {
                    const existingDependency = extraDeps.find((extraDep)=>extraDep.name === kQuartoHtmlDependency
                    );
                    if (existingDependency) {
                        existingDependency.stylesheets = existingDependency.stylesheets || [];
                        existingDependency.stylesheets.push({
                            name: cssFileName,
                            path: highlightCssPath,
                            attribs: mediaAttr
                        });
                    }
                }
            }
        }
    }
    return extras;
}
function generateThemeCssVars(themeJson) {
    const textStyles = themeJson["text-styles"];
    if (textStyles) {
        const lines10 = [];
        lines10.push("/* quarto syntax highlight colors */");
        lines10.push(":root {");
        Object.keys(textStyles).forEach((styleName)=>{
            const abbr = kAbbrevs[styleName];
            if (abbr) {
                const textValues = textStyles[styleName];
                Object.keys(textValues).forEach((textAttr)=>{
                    switch(textAttr){
                        case "text-color":
                            lines10.push(`  --quarto-hl-${abbr}-color: ${textValues[textAttr] || "inherit"};`);
                            break;
                    }
                });
            }
        });
        lines10.push("}");
        return lines10.join("\n");
    }
    return undefined;
}
function generateThemeCssClasses(themeJson) {
    const textStyles = themeJson["text-styles"];
    if (textStyles) {
        const lines11 = [];
        Object.keys(textStyles).forEach((styleName)=>{
            const abbr = kAbbrevs[styleName];
            if (abbr !== undefined) {
                const textValues = textStyles[styleName];
                const cssValues = generateCssKeyValues(textValues);
                if (abbr !== "") {
                    lines11.push(`\ncode span.${abbr} {`);
                    lines11.push(...cssValues);
                    lines11.push("}\n");
                } else {
                    [
                        "code span",
                        "div.sourceCode"
                    ].forEach((selector)=>{
                        lines11.push(`\n${selector} {`);
                        lines11.push(...cssValues);
                        lines11.push("}\n");
                    });
                }
            }
        });
        return lines11;
    }
    return undefined;
}
function processCssIntoExtras(cssPath, extras, temp) {
    extras.html = extras.html || {};
    const css = Deno.readTextFileSync(cssPath);
    if (!extras.html[kTextHighlightingMode] && cssHasDarkModeSentinel(css)) {
        setTextHighlightStyle("dark", extras);
    }
    const matches = css.matchAll(kVariablesRegex);
    if (matches) {
        extras.html[kQuartoCssVariables] = extras.html[kQuartoCssVariables] || [];
        let dirty = false;
        for (const match of matches){
            const variables = match[1];
            extras.html[kQuartoCssVariables]?.push(variables);
            dirty = true;
        }
        extras.html[kQuartoCssVariables] = uniqBy1(extras.html[kQuartoCssVariables], (val)=>{
            return val;
        });
        if (dirty) {
            const cleanedCss = css.replaceAll(kVariablesRegex, "");
            const newCssPath = temp.createFile({
                suffix: ".css"
            });
            Deno.writeTextFileSync(newCssPath, cleanedCss);
            return newCssPath;
        }
    }
    return cssPath;
}
const kVariablesRegex = /\/\*\! quarto-variables-start \*\/([\S\s]*)\/\*\! quarto-variables-end \*\//g;
function generateCssKeyValues(textValues) {
    const lines12 = [];
    Object.keys(textValues).forEach((textAttr)=>{
        switch(textAttr){
            case "text-color":
                lines12.push(`color: ${textValues[textAttr]};`);
                break;
            case "background":
                lines12.push(`background-color: ${textValues[textAttr]};`);
                break;
            case "bold":
                if (textValues[textAttr]) {
                    lines12.push("font-weight: bold;");
                }
                break;
            case "italic":
                if (textValues[textAttr]) {
                    lines12.push("font-style: italic;");
                }
                break;
            case "underline":
                if (textValues[textAttr]) {
                    lines12.push("text-decoration: underline;");
                }
                break;
        }
    });
    return lines12;
}
function defaultSyntaxHighlightingClassMap() {
    const classToStyleMapping = {};
    const themeRaw = readTheme(kDefaultHighlightStyle, "default");
    if (themeRaw) {
        const themeJson = JSON.parse(themeRaw);
        const textStyles = themeJson["text-styles"];
        if (textStyles) {
            Object.keys(textStyles).forEach((styleName)=>{
                const abbr = kAbbrevs[styleName];
                if (abbr !== undefined) {
                    const textValues = textStyles[styleName];
                    const cssValues = generateCssKeyValues(textValues);
                    classToStyleMapping[abbr] = cssValues;
                }
            });
        }
    }
    return classToStyleMapping;
}
const kAbbrevs = {
    "Keyword": "kw",
    "DataType": "dt",
    "DecVal": "dv",
    "BaseN": "bn",
    "Float": "fl",
    "Char": "ch",
    "String": "st",
    "Comment": "co",
    "Other": "ot",
    "Alert": "al",
    "Function": "fu",
    "RegionMarker": "re",
    "Error": "er",
    "Constant": "cn",
    "SpecialChar": "sc",
    "VerbatimString": "vs",
    "SpecialString": "ss",
    "Import": "im",
    "Documentation": "do",
    "Annotation": "an",
    "CommentVar": "cv",
    "Variable": "va",
    "ControlFlow": "cf",
    "Operator": "op",
    "BuiltIn": "bu",
    "Extension": "ex",
    "Preprocessor": "pp",
    "Attribute": "at",
    "Information": "in",
    "Warning": "wa",
    "Normal": ""
};
function attribForThemeStyle(style, defaultStyle) {
    const colorModeAttrs = (mode, disabled)=>{
        const attr = {
            class: `quarto-color-scheme${mode === "dark" ? " quarto-color-alternate" : ""}`
        };
        if (disabled) {
            attr.rel = "prefetch";
        }
        return attr;
    };
    switch(style){
        case "dark":
            return colorModeAttrs("dark", defaultStyle !== "dark");
        case "light":
            return colorModeAttrs("light", false);
        case "default":
        default:
            return {};
    }
}
function setTextHighlightStyle(style, extras) {
    extras.html = extras.html || {};
    extras.html[kTextHighlightingMode] = style;
}
function readTheme(theme, style) {
    const themeFile = textHighlightThemePath(theme, style === "default" ? undefined : style);
    if (themeFile && existsSync(themeFile)) {
        return Deno.readTextFileSync(themeFile);
    } else {
        return undefined;
    }
}
const importMeta = {
    url: "https://deno.land/x/deno_dom@v0.1.20-alpha/build/deno-wasm/deno-wasm.js",
    main: false
};
let wasm;
let WASM_VECTOR_LEN = 0;
let cachegetUint8Memory0 = null;
function getUint8Memory0() {
    if (cachegetUint8Memory0 === null || cachegetUint8Memory0.buffer !== wasm.memory.buffer) {
        cachegetUint8Memory0 = new Uint8Array(wasm.memory.buffer);
    }
    return cachegetUint8Memory0;
}
let cachedTextEncoder = new TextEncoder('utf-8');
const encodeString = typeof cachedTextEncoder.encodeInto === 'function' ? function(arg, view) {
    return cachedTextEncoder.encodeInto(arg, view);
} : function(arg, view) {
    const buf = cachedTextEncoder.encode(arg);
    view.set(buf);
    return {
        read: arg.length,
        written: buf.length
    };
};
function passStringToWasm0(arg, malloc, realloc) {
    if (realloc === undefined) {
        const buf = cachedTextEncoder.encode(arg);
        const ptr = malloc(buf.length);
        getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf);
        WASM_VECTOR_LEN = buf.length;
        return ptr;
    }
    let len4 = arg.length;
    let ptr = malloc(len4);
    const mem = getUint8Memory0();
    let offset = 0;
    for(; offset < len4; offset++){
        const code23 = arg.charCodeAt(offset);
        if (code23 > 127) break;
        mem[ptr + offset] = code23;
    }
    if (offset !== len4) {
        if (offset !== 0) {
            arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len4, len4 = offset + arg.length * 3);
        const view = getUint8Memory0().subarray(ptr + offset, ptr + len4);
        const ret = encodeString(arg, view);
        offset += ret.written;
    }
    WASM_VECTOR_LEN = offset;
    return ptr;
}
let cachegetInt32Memory0 = null;
function getInt32Memory0() {
    if (cachegetInt32Memory0 === null || cachegetInt32Memory0.buffer !== wasm.memory.buffer) {
        cachegetInt32Memory0 = new Int32Array(wasm.memory.buffer);
    }
    return cachegetInt32Memory0;
}
let cachedTextDecoder = new TextDecoder('utf-8', {
    ignoreBOM: true,
    fatal: true
});
cachedTextDecoder.decode();
function getStringFromWasm0(ptr, len5) {
    return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len5));
}
function parse5(html) {
    try {
        const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
        var ptr0 = passStringToWasm0(html, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        var len0 = WASM_VECTOR_LEN;
        wasm.parse(retptr, ptr0, len0);
        var r0 = getInt32Memory0()[retptr / 4 + 0];
        var r1 = getInt32Memory0()[retptr / 4 + 1];
        return getStringFromWasm0(r0, r1);
    } finally{
        wasm.__wbindgen_add_to_stack_pointer(16);
        wasm.__wbindgen_free(r0, r1);
    }
}
function parse_frag(html) {
    try {
        const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
        var ptr0 = passStringToWasm0(html, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
        var len0 = WASM_VECTOR_LEN;
        wasm.parse_frag(retptr, ptr0, len0);
        var r0 = getInt32Memory0()[retptr / 4 + 0];
        var r1 = getInt32Memory0()[retptr / 4 + 1];
        return getStringFromWasm0(r0, r1);
    } finally{
        wasm.__wbindgen_add_to_stack_pointer(16);
        wasm.__wbindgen_free(r0, r1);
    }
}
async function load1(module, imports) {
    if (typeof Response === 'function' && module instanceof Response) {
        if (typeof WebAssembly.instantiateStreaming === 'function') {
            try {
                return await WebAssembly.instantiateStreaming(module, imports);
            } catch (e) {
                if (module.headers.get('Content-Type') != 'application/wasm') {
                    console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
                } else {
                    throw e;
                }
            }
        }
        const bytes = await module.arrayBuffer();
        return await WebAssembly.instantiate(bytes, imports);
    } else {
        const instance = await WebAssembly.instantiate(module, imports);
        if (instance instanceof WebAssembly.Instance) {
            return {
                instance,
                module
            };
        } else {
            return instance;
        }
    }
}
async function init(input) {
    if (typeof input === 'undefined') {
        input = new URL('deno-wasm_bg.wasm', importMeta.url);
    }
    const imports = {};
    imports.env = {
        now () {}
    };
    input = Uint8Array.from(atob(" "), (c)=>c.charCodeAt(0)
    );
    const { instance , module  } = await load1(input, imports);
    wasm = instance.exports;
    init.__wbindgen_wasm_module = module;
    return wasm;
}
let parse6 = (_html)=>{
    console.error("Error: deno-dom: No parser registered");
    Deno.exit(1);
};
let parseFrag = (_html)=>{
    console.error("Error: deno-dom: No parser registered");
    Deno.exit(1);
};
const originalParse = parse6;
function register(func, fragFunc) {
    if (parse6 !== originalParse) {
        return;
    }
    parse6 = func;
    parseFrag = fragFunc;
}
(()=>{
    return class HTMLCollection {
        constructor(){
            throw new TypeError("Illegal constructor");
        }
        static [Symbol.hasInstance](value) {
            return value.constructor === HTMLCollectionClass;
        }
    };
})();
const HTMLCollectionMutatorSym = Symbol();
const HTMLCollectionClass = (()=>{
    class HTMLCollection1 extends Array {
        forEach(cb, thisArg = undefined) {
            super.forEach(cb, thisArg);
        }
        item(index) {
            return this[index] ?? null;
        }
        [HTMLCollectionMutatorSym]() {
            return {
                push: Array.prototype.push.bind(this),
                splice: Array.prototype.splice.bind(this),
                indexOf: Array.prototype.indexOf.bind(this)
            };
        }
        toString() {
            return "[object HTMLCollection]";
        }
    }
    return HTMLCollection1;
})();
for (const staticMethod of [
    "from",
    "isArray",
    "of", 
]){
    HTMLCollectionClass[staticMethod] = undefined;
}
for (const instanceMethod of [
    "concat",
    "copyWithin",
    "every",
    "fill",
    "filter",
    "find",
    "findIndex",
    "flat",
    "flatMap",
    "includes",
    "indexOf",
    "join",
    "lastIndexOf",
    "map",
    "pop",
    "push",
    "reduce",
    "reduceRight",
    "reverse",
    "shift",
    "slice",
    "some",
    "sort",
    "splice",
    "toLocaleString",
    "unshift",
    "entries",
    "forEach",
    "keys",
    "values", 
]){
    HTMLCollectionClass.prototype[instanceMethod] = undefined;
}
const HTMLCollection = HTMLCollectionClass;
const CTOR_KEY = Symbol();
class EventTarget {
    addEventListener() {}
    removeEventListener() {}
    dispatchEvent() {}
}
(()=>{
    return class NodeList {
        constructor(){
            throw new TypeError("Illegal constructor");
        }
        static [Symbol.hasInstance](value) {
            return value.constructor === NodeListClass;
        }
    };
})();
var NodeType;
(function(NodeType1) {
    NodeType1[NodeType1["ELEMENT_NODE"] = 1] = "ELEMENT_NODE";
    NodeType1[NodeType1["ATTRIBUTE_NODE"] = 2] = "ATTRIBUTE_NODE";
    NodeType1[NodeType1["TEXT_NODE"] = 3] = "TEXT_NODE";
    NodeType1[NodeType1["CDATA_SECTION_NODE"] = 4] = "CDATA_SECTION_NODE";
    NodeType1[NodeType1["ENTITY_REFERENCE_NODE"] = 5] = "ENTITY_REFERENCE_NODE";
    NodeType1[NodeType1["ENTITY_NODE"] = 6] = "ENTITY_NODE";
    NodeType1[NodeType1["PROCESSING_INSTRUCTION_NODE"] = 7] = "PROCESSING_INSTRUCTION_NODE";
    NodeType1[NodeType1["COMMENT_NODE"] = 8] = "COMMENT_NODE";
    NodeType1[NodeType1["DOCUMENT_NODE"] = 9] = "DOCUMENT_NODE";
    NodeType1[NodeType1["DOCUMENT_TYPE_NODE"] = 10] = "DOCUMENT_TYPE_NODE";
    NodeType1[NodeType1["DOCUMENT_FRAGMENT_NODE"] = 11] = "DOCUMENT_FRAGMENT_NODE";
    NodeType1[NodeType1["NOTATION_NODE"] = 12] = "NOTATION_NODE";
})(NodeType || (NodeType = {}));
const nodesAndTextNodes = (nodes, parentNode)=>{
    return nodes.map((n4)=>{
        const node = n4 instanceof Node ? n4 : new Text("" + n4);
        node.remove();
        node._setParent(parentNode, true);
        return node;
    });
};
const nodeListMutatorSym = Symbol();
const nodeListCachedMutator = Symbol();
const { push , splice: splice1 , slice , indexOf , filter  } = Array.prototype;
class Node extends EventTarget {
    nodeName;
    nodeType;
    nodeValue;
    childNodes;
    parentNode = null;
    parentElement;
    #childNodesMutator;
    #ownerDocument = null;
    _ancestors = new Set();
    static ELEMENT_NODE = NodeType.ELEMENT_NODE;
    static ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE;
    static TEXT_NODE = NodeType.TEXT_NODE;
    static CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE;
    static ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE;
    static ENTITY_NODE = NodeType.ENTITY_NODE;
    static PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE;
    static COMMENT_NODE = NodeType.COMMENT_NODE;
    static DOCUMENT_NODE = NodeType.DOCUMENT_NODE;
    static DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE;
    static DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE;
    static NOTATION_NODE = NodeType.NOTATION_NODE;
    constructor(nodeName, nodeType, parentNode, key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor.");
        }
        super();
        this.nodeName = nodeName;
        this.nodeType = nodeType;
        this.nodeValue = null;
        this.childNodes = new NodeList();
        this.#childNodesMutator = this.childNodes[nodeListMutatorSym]();
        this.parentElement = parentNode;
        if (parentNode) {
            parentNode.appendChild(this);
        }
    }
    _getChildNodesMutator() {
        return this.#childNodesMutator;
    }
    _setParent(newParent, force = false) {
        const sameParent = this.parentNode === newParent;
        const shouldUpdateParentAndAncestors = !sameParent || force;
        if (shouldUpdateParentAndAncestors) {
            this.parentNode = newParent;
            if (newParent) {
                if (!sameParent) {
                    if (newParent.nodeType === NodeType.ELEMENT_NODE) {
                        this.parentElement = newParent;
                    } else {
                        this.parentElement = null;
                    }
                    this._setOwnerDocument(newParent.#ownerDocument);
                }
                this._ancestors = new Set(newParent._ancestors);
                this._ancestors.add(newParent);
            } else {
                this.parentElement = null;
                this._ancestors.clear();
            }
            for (const child of this.childNodes){
                child._setParent(this, shouldUpdateParentAndAncestors);
            }
        }
    }
    _assertNotAncestor(child) {
        if (child.contains(this)) {
            throw new DOMException("The new child is an ancestor of the parent");
        }
    }
    _setOwnerDocument(document) {
        if (this.#ownerDocument !== document) {
            this.#ownerDocument = document;
            for (const child of this.childNodes){
                child._setOwnerDocument(document);
            }
        }
    }
    contains(child) {
        return child._ancestors.has(this) || child === this;
    }
    get ownerDocument() {
        return this.#ownerDocument;
    }
    get textContent() {
        let out = "";
        for (const child of this.childNodes){
            switch(child.nodeType){
                case NodeType.TEXT_NODE:
                    out += child.nodeValue;
                    break;
                case NodeType.ELEMENT_NODE:
                    out += child.textContent;
                    break;
            }
        }
        return out;
    }
    set textContent(content) {
        for (const child of this.childNodes){
            child._setParent(null);
        }
        this._getChildNodesMutator().splice(0, this.childNodes.length);
        this.appendChild(new Text(content));
    }
    get firstChild() {
        return this.childNodes[0] || null;
    }
    get lastChild() {
        return this.childNodes[this.childNodes.length - 1] || null;
    }
    hasChildNodes() {
        return this.firstChild !== null;
    }
    cloneNode(deep = false) {
        const copy2 = this._shallowClone();
        copy2._setOwnerDocument(this.ownerDocument);
        if (deep) {
            for (const child of this.childNodes){
                copy2.appendChild(child.cloneNode(true));
            }
        }
        return copy2;
    }
    _shallowClone() {
        throw new Error("Illegal invocation");
    }
    remove() {
        const parent = this.parentNode;
        if (parent) {
            const nodeList = parent._getChildNodesMutator();
            const idx = nodeList.indexOf(this);
            nodeList.splice(idx, 1);
            this._setParent(null);
        }
    }
    appendChild(child) {
        return child._appendTo(this);
    }
    _appendTo(parentNode) {
        parentNode._assertNotAncestor(this);
        const oldParentNode = this.parentNode;
        if (oldParentNode === parentNode) {
            if (parentNode._getChildNodesMutator().indexOf(this) !== -1) {
                return this;
            }
        } else if (oldParentNode) {
            this.remove();
        }
        this._setParent(parentNode, true);
        parentNode._getChildNodesMutator().push(this);
        return this;
    }
    removeChild(child) {
        if (child && typeof child === "object") {
            if (child.parentNode === this) {
                return child.remove();
            } else {
                throw new DOMException("Node.removeChild: The node to be removed is not a child of this node");
            }
        } else {
            throw new TypeError("Node.removeChild: Argument 1 is not an object.");
        }
    }
    replaceChild(newChild, oldChild) {
        if (oldChild.parentNode !== this) {
            throw new Error("Old child's parent is not the current node.");
        }
        oldChild.replaceWith(newChild);
        return oldChild;
    }
    insertBeforeAfter(nodes, side) {
        const parentNode = this.parentNode;
        const mutator = parentNode._getChildNodesMutator();
        const index = mutator.indexOf(this);
        nodes = nodesAndTextNodes(nodes, parentNode);
        mutator.splice(index + side, 0, ...nodes);
    }
    before(...nodes) {
        if (this.parentNode) {
            this.insertBeforeAfter(nodes, 0);
        }
    }
    after(...nodes) {
        if (this.parentNode) {
            this.insertBeforeAfter(nodes, 1);
        }
    }
    insertBefore(newNode, refNode) {
        this._assertNotAncestor(newNode);
        const mutator = this._getChildNodesMutator();
        if (refNode === null) {
            this.appendChild(newNode);
            return newNode;
        }
        const index = mutator.indexOf(refNode);
        if (index === -1) {
            throw new Error("DOMException: Child to insert before is not a child of this node");
        }
        const oldParentNode = newNode.parentNode;
        newNode._setParent(this, oldParentNode !== this);
        mutator.splice(index, 0, newNode);
        return newNode;
    }
    replaceWith(...nodes) {
        if (this.parentNode) {
            const parentNode = this.parentNode;
            const mutator = parentNode._getChildNodesMutator();
            const index = mutator.indexOf(this);
            nodes = nodesAndTextNodes(nodes, parentNode);
            mutator.splice(index, 1, ...nodes);
            this._setParent(null);
        }
    }
    get nextSibling() {
        const parent = this.parentNode;
        if (!parent) {
            return null;
        }
        const index = parent._getChildNodesMutator().indexOf(this);
        const next = parent.childNodes[index + 1] || null;
        return next;
    }
    get previousSibling() {
        const parent = this.parentNode;
        if (!parent) {
            return null;
        }
        const index = parent._getChildNodesMutator().indexOf(this);
        const prev = parent.childNodes[index - 1] || null;
        return prev;
    }
    static DOCUMENT_POSITION_DISCONNECTED = 1;
    static DOCUMENT_POSITION_PRECEDING = 2;
    static DOCUMENT_POSITION_FOLLOWING = 4;
    static DOCUMENT_POSITION_CONTAINS = 8;
    static DOCUMENT_POSITION_CONTAINED_BY = 16;
    static DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
    compareDocumentPosition(other) {
        if (other === this) {
            return 0;
        }
        if (!(other instanceof Node)) {
            throw new TypeError("Node.compareDocumentPosition: Argument 1 does not implement interface Node.");
        }
        let node1Root = other;
        let node2Root = this;
        const node1Hierarchy = [
            node1Root
        ];
        const node2Hierarchy = [
            node2Root
        ];
        while(node1Root.parentNode ?? node2Root.parentNode){
            node1Root = node1Root.parentNode ? (node1Hierarchy.push(node1Root.parentNode), node1Root.parentNode) : node1Root;
            node2Root = node2Root.parentNode ? (node2Hierarchy.push(node2Root.parentNode), node2Root.parentNode) : node2Root;
        }
        if (node1Root !== node2Root) {
            return Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | Node.DOCUMENT_POSITION_PRECEDING;
        }
        const longerHierarchy = node1Hierarchy.length > node2Hierarchy.length ? node1Hierarchy : node2Hierarchy;
        const shorterHierarchy = longerHierarchy === node1Hierarchy ? node2Hierarchy : node1Hierarchy;
        if (longerHierarchy[longerHierarchy.length - shorterHierarchy.length] === shorterHierarchy[0]) {
            return longerHierarchy === node1Hierarchy ? Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING;
        }
        const longerStart = longerHierarchy.length - shorterHierarchy.length;
        for(let i74 = shorterHierarchy.length - 1; i74 >= 0; i74--){
            const shorterHierarchyNode = shorterHierarchy[i74];
            const longerHierarchyNode = longerHierarchy[longerStart + i74];
            if (longerHierarchyNode !== shorterHierarchyNode) {
                const siblings1 = shorterHierarchyNode.parentNode._getChildNodesMutator();
                if (siblings1.indexOf(shorterHierarchyNode) < siblings1.indexOf(longerHierarchyNode)) {
                    if (shorterHierarchy === node1Hierarchy) {
                        return Node.DOCUMENT_POSITION_PRECEDING;
                    } else {
                        return Node.DOCUMENT_POSITION_FOLLOWING;
                    }
                } else {
                    if (longerHierarchy === node1Hierarchy) {
                        return Node.DOCUMENT_POSITION_PRECEDING;
                    } else {
                        return Node.DOCUMENT_POSITION_FOLLOWING;
                    }
                }
            }
        }
        return Node.DOCUMENT_POSITION_FOLLOWING;
    }
}
Node.prototype.ELEMENT_NODE = NodeType.ELEMENT_NODE;
Node.prototype.ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE;
Node.prototype.TEXT_NODE = NodeType.TEXT_NODE;
Node.prototype.CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE;
Node.prototype.ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE;
Node.prototype.ENTITY_NODE = NodeType.ENTITY_NODE;
Node.prototype.PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE;
Node.prototype.COMMENT_NODE = NodeType.COMMENT_NODE;
Node.prototype.DOCUMENT_NODE = NodeType.DOCUMENT_NODE;
Node.prototype.DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE;
Node.prototype.DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE;
Node.prototype.NOTATION_NODE = NodeType.NOTATION_NODE;
class NodeListMutatorImpl {
    arrayInstance;
    elementViews = [];
    constructor(arrayInstance){
        this.arrayInstance = arrayInstance;
    }
    push(...items) {
        for (const view of this.elementViews){
            for (const item of items){
                if (item.nodeType === Node.ELEMENT_NODE) {
                    push.call(view, item);
                }
            }
        }
        return push.call(this.arrayInstance, ...items);
    }
    splice(index, deleteCount = 0, ...items) {
        for (const view of this.elementViews){
            const toDelete = filter.call(slice.call(this.arrayInstance, index, index + deleteCount), (item)=>item.nodeType === Node.ELEMENT_NODE
            );
            const toInsert = items.filter((item)=>item.nodeType === Node.ELEMENT_NODE
            );
            let elementViewSpliceIndex = -1;
            for(let idx = index; idx < this.arrayInstance.length; idx++){
                const item = this.arrayInstance[idx];
                if (item.nodeType === Node.ELEMENT_NODE) {
                    elementViewSpliceIndex = indexOf.call(view, item);
                    break;
                }
            }
            if (elementViewSpliceIndex === -1) {
                elementViewSpliceIndex = view.length;
            }
            if (toDelete.length) {
                splice1.call(view, elementViewSpliceIndex, toDelete.length);
            }
            splice1.call(view, elementViewSpliceIndex, 0, ...toInsert);
        }
        return splice1.call(this.arrayInstance, index, deleteCount, ...items);
    }
    indexOf(item) {
        return indexOf.call(this.arrayInstance, item);
    }
    elementsView() {
        let view = this.elementViews[0];
        if (!view) {
            view = new HTMLCollection();
            this.elementViews.push(view);
            push.call(view, ...filter.call(this.arrayInstance, (item)=>item.nodeType === Node.ELEMENT_NODE
            ));
        }
        return view;
    }
}
const NodeListClass = (()=>{
    class NodeList1 extends Array {
        forEach(cb, thisArg = undefined) {
            super.forEach(cb, thisArg);
        }
        item(index) {
            return this[index] ?? null;
        }
        [nodeListMutatorSym]() {
            const cachedMutator = this[nodeListCachedMutator];
            if (cachedMutator) {
                return cachedMutator;
            } else {
                const cachedMutator = new NodeListMutatorImpl(this);
                this[nodeListCachedMutator] = cachedMutator;
                return cachedMutator;
            }
        }
        toString() {
            return "[object NodeList]";
        }
    }
    return NodeList1;
})();
for (const staticMethod1 of [
    "from",
    "isArray",
    "of", 
]){
    NodeListClass[staticMethod1] = undefined;
}
for (const instanceMethod1 of [
    "concat",
    "copyWithin",
    "every",
    "fill",
    "filter",
    "find",
    "findIndex",
    "flat",
    "flatMap",
    "includes",
    "indexOf",
    "join",
    "lastIndexOf",
    "map",
    "pop",
    "push",
    "reduce",
    "reduceRight",
    "reverse",
    "shift",
    "slice",
    "some",
    "sort",
    "splice",
    "toLocaleString",
    "unshift", 
]){
    NodeListClass.prototype[instanceMethod1] = undefined;
}
const NodeList = NodeListClass;
class CharacterData extends Node {
    data;
    constructor(data49, nodeName, nodeType, parentNode, key){
        super(nodeName, nodeType, parentNode, key);
        this.data = data49;
        this.nodeValue = data49;
    }
    get length() {
        return this.data.length;
    }
}
class Text extends CharacterData {
    constructor(text = ""){
        super(text, "#text", NodeType.TEXT_NODE, null, CTOR_KEY);
        this.nodeValue = text;
    }
    _shallowClone() {
        return new Text(this.textContent);
    }
    get textContent() {
        return this.nodeValue;
    }
}
class Comment extends CharacterData {
    constructor(text = ""){
        super(text, "#comment", NodeType.COMMENT_NODE, null, CTOR_KEY);
        this.nodeValue = text;
    }
    _shallowClone() {
        return new Comment(this.textContent);
    }
    get textContent() {
        return this.nodeValue;
    }
}
const __default = (document)=>{
    const NW = Factory({
        document,
        DOMException
    }, "null");
    NW.configure({
        IDS_DUPES: false,
        LOGERRORS: false
    });
    return NW;
};
function Factory(global, Export) {
    var version7 = 'nwsapi-2.2.0', doc1 = global.document, root8 = doc1.documentElement, slice2 = Array.prototype.slice, WSP = '[\\x20\\t\\r\\n\\f]', CFG = {
        operators: '[~*^$|]=|=',
        combinators: '[\\x20\\t>+~](?=[^>+~])'
    }, NOT = {
        double_enc: '(?=(?:[^"]*["][^"]*["])*[^"]*$)',
        single_enc: "(?=(?:[^']*['][^']*['])*[^']*$)",
        parens_enc: '(?![^\\x28]*\\x29)',
        square_enc: '(?![^\\x5b]*\\x5d)'
    }, REX = {
        HasEscapes: RegExp('\\\\'),
        HexNumbers: RegExp('^[0-9a-fA-F]'),
        EscOrQuote: RegExp('^\\\\|[\\x22\\x27]'),
        RegExpChar: RegExp('(?:(?!\\\\)[\\\\^$.*+?()[\\]{}|\\/])', 'g'),
        TrimSpaces: RegExp('[\\r\\n\\f]|^' + WSP + '+|' + WSP + '+$', 'g'),
        CommaGroup: RegExp('(\\s*,\\s*)' + NOT.square_enc + NOT.parens_enc, 'g'),
        SplitGroup: RegExp('((?:\\x28[^\\x29]*\\x29|\\[[^\\]]*\\]|\\\\.|[^,])+)', 'g'),
        FixEscapes: RegExp('\\\\([0-9a-fA-F]{1,6}' + WSP + '?|.)|([\\x22\\x27])', 'g'),
        CombineWSP: RegExp('[\\n\\r\\f\\x20]+' + NOT.single_enc + NOT.double_enc, 'g'),
        TabCharWSP: RegExp('(\\x20?\\t+\\x20?)' + NOT.single_enc + NOT.double_enc, 'g'),
        PseudosWSP: RegExp('\\s+([-+])\\s+' + NOT.square_enc, 'g')
    }, STD = {
        combinator: RegExp('\\s?([>+~])\\s?', 'g'),
        apimethods: RegExp('^(?:[a-z]+|\\*)\\|', 'i'),
        namespaces: RegExp('(\\*|[a-z]+)\\|[-a-z]+', 'i')
    }, GROUPS = {
        linguistic: '(dir|lang)\\x28\\s?([-\\w]{2,})\\s?(?:\\x29|$)',
        logicalsel: '(matches|not)\\x28\\s?([^()]*|[^\\x28]*\\x28[^\\x29]*\\x29)\\s?(?:\\x29|$)',
        treestruct: '(nth(?:-last)?(?:-child|-of-type))(?:\\x28\\s?(even|odd|(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)?)\\s?(?:\\x29|$))',
        locationpc: '(link|visited|target)\\b',
        useraction: '(hover|active|focus|focus-within)\\b',
        structural: '(root|empty|(?:(?:first|last|only)(?:-child|-of-type)))\\b',
        inputstate: '(enabled|disabled|read-only|read-write|placeholder-shown|default)\\b',
        inputvalue: '(checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range)\\b',
        pseudo_sng: '(after|before|first-letter|first-line)\\b',
        pseudo_dbl: ':(after|before|first-letter|first-line|selection|placeholder|-webkit-[-a-zA-Z0-9]{2,})\\b'
    }, Patterns = {
        treestruct: RegExp('^:(?:' + GROUPS.treestruct + ')(.*)', 'i'),
        structural: RegExp('^:(?:' + GROUPS.structural + ')(.*)', 'i'),
        linguistic: RegExp('^:(?:' + GROUPS.linguistic + ')(.*)', 'i'),
        useraction: RegExp('^:(?:' + GROUPS.useraction + ')(.*)', 'i'),
        inputstate: RegExp('^:(?:' + GROUPS.inputstate + ')(.*)', 'i'),
        inputvalue: RegExp('^:(?:' + GROUPS.inputvalue + ')(.*)', 'i'),
        locationpc: RegExp('^:(?:' + GROUPS.locationpc + ')(.*)', 'i'),
        logicalsel: RegExp('^:(?:' + GROUPS.logicalsel + ')(.*)', 'i'),
        pseudo_dbl: RegExp('^:(?:' + GROUPS.pseudo_dbl + ')(.*)', 'i'),
        pseudo_sng: RegExp('^:(?:' + GROUPS.pseudo_sng + ')(.*)', 'i'),
        children: RegExp('^' + WSP + '?\\>' + WSP + '?(.*)'),
        adjacent: RegExp('^' + WSP + '?\\+' + WSP + '?(.*)'),
        relative: RegExp('^' + WSP + '?\\~' + WSP + '?(.*)'),
        ancestor: RegExp('^' + WSP + '+(.*)'),
        universal: RegExp('^\\*(.*)'),
        namespace: RegExp('^(\\w+|\\*)?\\|(.*)')
    }, RTL = RegExp('^[\\u0591-\\u08ff\\ufb1d-\\ufdfd\\ufe70-\\ufefc ]+$'), qsNotArgs = 'Not enough arguments', qsInvalid = ' is not a valid selector', reNthElem = RegExp('(:nth(?:-last)?-child)', 'i'), reNthType = RegExp('(:nth(?:-last)?-of-type)', 'i'), reOptimizer, reValidator, Config = {
        IDS_DUPES: true,
        MIXEDCASE: true,
        LOGERRORS: true,
        VERBOSITY: true
    }, NAMESPACE, QUIRKS_MODE, HTML_DOCUMENT, ATTR_STD_OPS = {
        '=': 1,
        '^=': 1,
        '$=': 1,
        '|=': 1,
        '*=': 1,
        '~=': 1
    }, HTML_TABLE = {
        'accept': 1,
        'accept-charset': 1,
        'align': 1,
        'alink': 1,
        'axis': 1,
        'bgcolor': 1,
        'charset': 1,
        'checked': 1,
        'clear': 1,
        'codetype': 1,
        'color': 1,
        'compact': 1,
        'declare': 1,
        'defer': 1,
        'dir': 1,
        'direction': 1,
        'disabled': 1,
        'enctype': 1,
        'face': 1,
        'frame': 1,
        'hreflang': 1,
        'http-equiv': 1,
        'lang': 1,
        'language': 1,
        'link': 1,
        'media': 1,
        'method': 1,
        'multiple': 1,
        'nohref': 1,
        'noresize': 1,
        'noshade': 1,
        'nowrap': 1,
        'readonly': 1,
        'rel': 1,
        'rev': 1,
        'rules': 1,
        'scope': 1,
        'scrolling': 1,
        'selected': 1,
        'shape': 1,
        'target': 1,
        'text': 1,
        'type': 1,
        'valign': 1,
        'valuetype': 1,
        'vlink': 1
    }, Combinators = {}, Selectors = {}, Operators = {
        '=': {
            p1: '^',
            p2: '$',
            p3: 'true'
        },
        '^=': {
            p1: '^',
            p2: '',
            p3: 'true'
        },
        '$=': {
            p1: '',
            p2: '$',
            p3: 'true'
        },
        '*=': {
            p1: '',
            p2: '',
            p3: 'true'
        },
        '|=': {
            p1: '^',
            p2: '(-|$)',
            p3: 'true'
        },
        '~=': {
            p1: '(^|\\s)',
            p2: '(\\s|$)',
            p3: 'true'
        }
    }, concatCall = function(nodes, callback) {
        var i75 = 0, l = nodes.length, list = Array(l);
        while(l > i75){
            if (false === callback(list[i75] = nodes[i75])) break;
            ++i75;
        }
        return list;
    }, concatList = function(list, nodes) {
        var i76 = -1, l = nodes.length;
        while(l--){
            list[list.length] = nodes[++i76];
        }
        return list;
    }, documentOrder = function(a, b) {
        if (!hasDupes && a === b) {
            hasDupes = true;
            return 0;
        }
        return a.compareDocumentPosition(b) & 4 ? -1 : 1;
    }, hasDupes = false, unique = function(nodes) {
        var i77 = 0, j = -1, l = nodes.length + 1, list = [];
        while(--l){
            if (nodes[i77++] === nodes[i77]) continue;
            list[++j] = nodes[i77 - 1];
        }
        hasDupes = false;
        return list;
    }, hasMixedCaseTagNames = function(context) {
        var ns, api = 'getElementsByTagNameNS';
        context = context.ownerDocument || context;
        ns = context.documentElement.namespaceURI || 'http://www.w3.org/1999/xhtml';
        return context[api]('*', '*').length - context[api](ns, '*').length > 0;
    }, switchContext = function(context, force) {
        var oldDoc = doc1;
        doc1 = context.ownerDocument || context;
        if (force || oldDoc !== doc1) {
            root8 = doc1.documentElement;
            HTML_DOCUMENT = isHTML(doc1);
            QUIRKS_MODE = HTML_DOCUMENT && doc1.compatMode.indexOf('CSS') < 0;
            NAMESPACE = root8 && root8.namespaceURI;
            Snapshot.doc = doc1;
            Snapshot.root = root8;
        }
        return Snapshot.from = context;
    }, codePointToUTF16 = function(codePoint) {
        if (codePoint < 1 || codePoint > 1114111 || codePoint > 55295 && codePoint < 57344) {
            return '\\ufffd';
        }
        if (codePoint < 65536) {
            var lowHex = '000' + codePoint.toString(16);
            return '\\u' + lowHex.substr(lowHex.length - 4);
        }
        return '\\u' + ((codePoint - 65536 >> 10) + 55296).toString(16) + '\\u' + ((codePoint - 65536) % 1024 + 56320).toString(16);
    }, stringFromCodePoint = function(codePoint) {
        if (codePoint < 1 || codePoint > 1114111 || codePoint > 55295 && codePoint < 57344) {
            return '\ufffd';
        }
        if (codePoint < 65536) {
            return String.fromCharCode(codePoint);
        }
        return String.fromCodePoint ? String.fromCodePoint(codePoint) : String.fromCharCode((codePoint - 65536 >> 10) + 55296, (codePoint - 65536) % 1024 + 56320);
    }, convertEscapes = function(str69) {
        return REX.HasEscapes.test(str69) ? str69.replace(REX.FixEscapes, function(substring, p1, p2) {
            return p2 ? '\\' + p2 : REX.HexNumbers.test(p1) ? codePointToUTF16(parseInt(p1, 16)) : REX.EscOrQuote.test(p1) ? substring : p1;
        }) : str69;
    }, unescapeIdentifier = function(str70) {
        return REX.HasEscapes.test(str70) ? str70.replace(REX.FixEscapes, function(substring, p1, p2) {
            return p2 ? p2 : REX.HexNumbers.test(p1) ? stringFromCodePoint(parseInt(p1, 16)) : REX.EscOrQuote.test(p1) ? substring : p1;
        }) : str70;
    }, method = {
        '#': 'getElementById',
        '*': 'getElementsByTagNameNS',
        '.': 'getElementsByClassName'
    }, compat1 = {
        '#': function(c, n5) {
            REX.HasEscapes.test(n5) && (n5 = unescapeIdentifier(n5));
            return function(e, f) {
                return byId(n5, c);
            };
        },
        '*': function(c, n6) {
            REX.HasEscapes.test(n6) && (n6 = unescapeIdentifier(n6));
            return function(e, f) {
                return byTag(n6, c);
            };
        },
        '.': function(c, n7) {
            REX.HasEscapes.test(n7) && (n7 = unescapeIdentifier(n7));
            return function(e, f) {
                return byClass(n7, c);
            };
        }
    }, byIdRaw = function(id, context) {
        var node = context, nodes = [], next = node.firstElementChild;
        while(node = next){
            node.id == id && (nodes[nodes.length] = node);
            if (next = node.firstElementChild || node.nextElementSibling) continue;
            while(!next && (node = node.parentElement) && node !== context){
                next = node.nextElementSibling;
            }
        }
        return nodes;
    }, byId = function(id, context) {
        var e, nodes, api = method['#'];
        if (Config.IDS_DUPES === false) {
            if (api in context) {
                return (e = context[api](id)) ? [
                    e
                ] : none;
            }
        } else {
            if ('all' in context) {
                if (e = context.all[id]) {
                    if (e.nodeType == 1) return e.getAttribute('id') != id ? [] : [
                        e
                    ];
                    else if (id == 'length') return (e = context[api](id)) ? [
                        e
                    ] : none;
                    for(i = 0, l = e.length, nodes = []; l > i; ++i){
                        if (e[i].id == id) nodes[nodes.length] = e[i];
                    }
                    return nodes && nodes.length ? nodes : [
                        nodes
                    ];
                } else return none;
            }
        }
        return byIdRaw(id, context);
    }, byTag = function(tag, context) {
        var e, nodes, api = method['*'];
        if (api in context) {
            return slice2.call(context[api]('*', tag));
        } else {
            if (e = context.firstElementChild) {
                tag = tag.toLowerCase();
                if (!(e.nextElementSibling || tag == '*' || e.nodeName.toLowerCase() == tag)) {
                    return slice2.call(e[api]('*', tag));
                } else {
                    nodes = [];
                    do {
                        if (tag == '*' || e.nodeName.toLowerCase() == tag) nodes[nodes.length] = e;
                        concatList(nodes, e[api]('*', tag));
                    }while (e = e.nextElementSibling)
                }
            } else nodes = none;
        }
        return nodes;
    }, byClass = function(cls, context) {
        var e, nodes, api = method['.'], reCls;
        if (api in context) {
            return slice2.call(context[api](cls));
        } else {
            if (e = context.firstElementChild) {
                reCls = RegExp('(^|\\s)' + cls + '(\\s|$)', QUIRKS_MODE ? 'i' : '');
                if (!(e.nextElementSibling || reCls.test(e.className))) {
                    return slice2.call(e[api](cls));
                } else {
                    nodes = [];
                    do {
                        if (reCls.test(e.className)) nodes[nodes.length] = e;
                        concatList(nodes, e[api](cls));
                    }while (e = e.nextElementSibling)
                }
            } else nodes = none;
        }
        return nodes;
    }, hasAttributeNS = function(e, name98) {
        var i, l, attr = e.getAttributeNames();
        name98 = RegExp(':?' + name98 + '$', HTML_DOCUMENT ? 'i' : '');
        for(i = 0, l = attr.length; l > i; ++i){
            if (name98.test(attr[i])) return true;
        }
        return false;
    }, nthElement = function() {
        var idx = 0, len6 = 0, set3 = 0, parent = undefined, parents = Array(), nodes = Array();
        return function(element, dir) {
            if (dir == 2) {
                idx = 0;
                len6 = 0;
                set3 = 0;
                nodes.length = 0;
                parents.length = 0;
                parent = undefined;
                return -1;
            }
            var e, i, j, k, l;
            if (parent === element.parentElement) {
                i = set3;
                j = idx;
                l = len6;
            } else {
                l = parents.length;
                parent = element.parentElement;
                for(i = -1, j = 0, k = l - 1; l > j; ++j, --k){
                    if (parents[j] === parent) {
                        i = j;
                        break;
                    }
                    if (parents[k] === parent) {
                        i = k;
                        break;
                    }
                }
                if (i < 0) {
                    parents[i = l] = parent;
                    l = 0;
                    nodes[i] = Array();
                    e = parent && parent.firstElementChild || element;
                    while(e){
                        nodes[i][l] = e;
                        if (e === element) j = l;
                        e = e.nextElementSibling;
                        ++l;
                    }
                    set3 = i;
                    idx = 0;
                    len6 = l;
                    if (l < 2) return l;
                } else {
                    l = nodes[i].length;
                    set3 = i;
                }
            }
            if (element !== nodes[i][j] && element !== nodes[i][j = 0]) {
                for(j = 0, e = nodes[i], k = l - 1; l > j; ++j, --k){
                    if (e[j] === element) {
                        break;
                    }
                    if (e[k] === element) {
                        j = k;
                        break;
                    }
                }
            }
            idx = j + 1;
            len6 = l;
            return dir ? l - j : idx;
        };
    }(), nthOfType = function() {
        var idx = 0, len7 = 0, set4 = 0, parent = undefined, parents = Array(), nodes = Array();
        return function(element, dir) {
            if (dir == 2) {
                idx = 0;
                len7 = 0;
                set4 = 0;
                nodes.length = 0;
                parents.length = 0;
                parent = undefined;
                return -1;
            }
            var e, i, j, k, l, name99 = element.nodeName;
            if (nodes[set4] && nodes[set4][name99] && parent === element.parentElement) {
                i = set4;
                j = idx;
                l = len7;
            } else {
                l = parents.length;
                parent = element.parentElement;
                for(i = -1, j = 0, k = l - 1; l > j; ++j, --k){
                    if (parents[j] === parent) {
                        i = j;
                        break;
                    }
                    if (parents[k] === parent) {
                        i = k;
                        break;
                    }
                }
                if (i < 0 || !nodes[i][name99]) {
                    parents[i = l] = parent;
                    nodes[i] || (nodes[i] = Object());
                    l = 0;
                    nodes[i][name99] = Array();
                    e = parent && parent.firstElementChild || element;
                    while(e){
                        if (e === element) j = l;
                        if (e.nodeName == name99) {
                            nodes[i][name99][l] = e;
                            ++l;
                        }
                        e = e.nextElementSibling;
                    }
                    set4 = i;
                    idx = j;
                    len7 = l;
                    if (l < 2) return l;
                } else {
                    l = nodes[i][name99].length;
                    set4 = i;
                }
            }
            if (element !== nodes[i][name99][j] && element !== nodes[i][name99][j = 0]) {
                for(j = 0, e = nodes[i][name99], k = l - 1; l > j; ++j, --k){
                    if (e[j] === element) {
                        break;
                    }
                    if (e[k] === element) {
                        j = k;
                        break;
                    }
                }
            }
            idx = j + 1;
            len7 = l;
            return dir ? l - j : idx;
        };
    }(), isHTML = function(node) {
        var doc = node.ownerDocument || node;
        return doc.nodeType == 9 && 'contentType' in doc ? doc.contentType.indexOf('/html') > 0 : doc.createElement('DiV').nodeName == 'DIV';
    }, configure = function(option, clear) {
        if (typeof option == 'string') {
            return !!Config[option];
        }
        if (typeof option != 'object') {
            return Config;
        }
        for(var i in option){
            Config[i] = !!option[i];
        }
        if (clear) {
            matchResolvers = {};
            selectResolvers = {};
        }
        setIdentifierSyntax();
        return true;
    }, emit = function(message, proto4) {
        var err;
        if (Config.VERBOSITY) {
            if (proto4) {
                err = new proto4(message);
            } else {
                err = new global.DOMException(message, 'SyntaxError');
            }
            throw err;
        }
        if (Config.LOGERRORS && console && console.log) {
            console.log(message);
        }
    }, initialize = function(doc) {
        setIdentifierSyntax();
        lastContext = switchContext(doc, true);
    }, setIdentifierSyntax = function() {
        var identifier = '(?=[^0-9])' + '(?:-{2}' + '|[a-zA-Z0-9-_]' + '|[^\\x00-\\x9f]' + '|\\\\[^\\r\\n\\f0-9a-fA-F]' + '|\\\\[0-9a-fA-F]{1,6}(?:\\r\\n|\\s)?' + '|\\\\.' + ')+', pseudonames = '[-\\w]+', pseudoparms = '(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)', doublequote = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*(?:"|$)', singlequote = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*(?:'|$)", attrparser = identifier + '|' + doublequote + '|' + singlequote, attrvalues = '([\\x22\\x27]?)((?!\\3)*|(?:\\\\?.)*?)(?:\\3|$)', attributes = '\\[' + '(?:\\*\\|)?' + WSP + '?' + '(' + identifier + '(?::' + identifier + ')?)' + WSP + '?' + '(?:' + '(' + CFG.operators + ')' + WSP + '?' + '(?:' + attrparser + ')' + ')?' + WSP + '?' + '(i)?' + WSP + '?' + '(?:\\]|$)', attrmatcher = attributes.replace(attrparser, attrvalues), pseudoclass = '(?:\\x28' + WSP + '*' + '(?:' + pseudoparms + '?)?|' + '(?:\\*|\\|)|' + '(?:' + '(?::' + pseudonames + '(?:\\x28' + pseudoparms + '?(?:\\x29|$))?|' + ')|' + '(?:[.#]?' + identifier + ')|' + '(?:' + attributes + ')' + ')+|' + '(?:' + WSP + '?,' + WSP + '?)|' + '(?:' + WSP + '?)|' + '(?:\\x29|$))*', standardValidator = '(?=' + WSP + '?[^>+~(){}<>])' + '(?:' + '(?:\\*|\\|)|' + '(?:[.#]?' + identifier + ')+|' + '(?:' + attributes + ')+|' + '(?:::?' + pseudonames + pseudoclass + ')|' + '(?:' + WSP + '?' + CFG.combinators + WSP + '?)|' + '(?:' + WSP + '?,' + WSP + '?)|' + '(?:' + WSP + '?)' + ')+';
        reOptimizer = RegExp('(?:([.:#*]?)' + '(' + identifier + ')' + '(?:' + ':[-\\w]+|' + '\\[[^\\]]+(?:\\]|$)|' + '\\x28[^\\x29]+(?:\\x29|$)' + ')*)$');
        reValidator = RegExp(standardValidator, 'g');
        Patterns.id = RegExp('^#(' + identifier + ')(.*)');
        Patterns.tagName = RegExp('^(' + identifier + ')(.*)');
        Patterns.className = RegExp('^\\.(' + identifier + ')(.*)');
        Patterns.attribute = RegExp('^(?:' + attrmatcher + ')(.*)');
    }, F_INIT = '"use strict";return function Resolver(c,f,x,r)', S_HEAD = 'var e,n,o,j=r.length-1,k=-1', M_HEAD = 'var e,n,o', S_LOOP = 'main:while((e=c[++k]))', N_LOOP = 'main:while((e=c.item(++k)))', M_LOOP = 'e=c;', S_BODY = 'r[++j]=c[k];', N_BODY = 'r[++j]=c.item(k);', M_BODY = '', S_TAIL = 'continue main;', M_TAIL = 'r=true;', S_TEST = 'if(f(c[k])){break main;}', N_TEST = 'if(f(c.item(k))){break main;}', M_TEST = 'f(c);', S_VARS = [], M_VARS = [], compile = function(selector, mode, callback) {
        var factory3, head = '', loop = '', macro = '', source = '', vars = '';
        switch(mode){
            case true:
                if (selectLambdas[selector]) {
                    return selectLambdas[selector];
                }
                macro = S_BODY + (callback ? S_TEST : '') + S_TAIL;
                head = S_HEAD;
                loop = S_LOOP;
                break;
            case false:
                if (matchLambdas[selector]) {
                    return matchLambdas[selector];
                }
                macro = M_BODY + (callback ? M_TEST : '') + M_TAIL;
                head = M_HEAD;
                loop = M_LOOP;
                break;
            case null:
                if (selectLambdas[selector]) {
                    return selectLambdas[selector];
                }
                macro = N_BODY + (callback ? N_TEST : '') + S_TAIL;
                head = S_HEAD;
                loop = N_LOOP;
                break;
            default:
                break;
        }
        source = compileSelector(selector, macro, mode, callback, false);
        loop += mode || mode === null ? '{' + source + '}' : source;
        if (mode || mode === null && selector.includes(':nth')) {
            loop += reNthElem.test(selector) ? 's.nthElement(null, 2);' : '';
            loop += reNthType.test(selector) ? 's.nthOfType(null, 2);' : '';
        }
        if (S_VARS[0] || M_VARS[0]) {
            vars = ',' + (S_VARS.join(',') || M_VARS.join(','));
            S_VARS.length = 0;
            M_VARS.length = 0;
        }
        factory3 = Function('s', F_INIT + '{' + head + vars + ';' + loop + 'return r;}')(Snapshot);
        return mode || mode === null ? selectLambdas[selector] = factory3 : matchLambdas[selector] = factory3;
    }, compileSelector = function(expression, source, mode, callback, not) {
        var a, b, n8, f, i, l, name100, nested, NS, N = not ? '!' : '', D = not ? '' : '!', compat, expr, match, result, status, symbol, test, type, selector = expression, selector_string, vars;
        selector_string = mode ? lastSelected : lastMatched;
        selector = selector.replace(STD.combinator, '$1');
        while(selector){
            symbol = STD.apimethods.test(selector) ? '|' : selector[0];
            switch(symbol){
                case '*':
                    match = selector.match(Patterns.universal);
                    if (N == '!') {
                        source = 'if(' + N + 'true' + '){' + source + '}';
                    }
                    break;
                case '#':
                    match = selector.match(Patterns.id);
                    source = 'if(' + N + '(/^' + match[1] + '$/.test(e.getAttribute("id"))' + ')){' + source + '}';
                    break;
                case '.':
                    match = selector.match(Patterns.className);
                    compat = (QUIRKS_MODE ? 'i' : '') + '.test(e.getAttribute("class"))';
                    source = 'if(' + N + '(/(^|\\s)' + match[1] + '(\\s|$)/' + compat + ')){' + source + '}';
                    break;
                case /[a-z]/i.test(symbol) ? symbol : undefined:
                    match = selector.match(Patterns.tagName);
                    source = 'if(' + N + '(e.nodeName' + (Config.MIXEDCASE || hasMixedCaseTagNames(doc1) ? '.toLowerCase()=="' + match[1].toLowerCase() + '"' : '=="' + match[1].toUpperCase() + '"') + ')){' + source + '}';
                    break;
                case '|':
                    match = selector.match(Patterns.namespace);
                    if (match[1] == '*') {
                        source = 'if(' + N + 'true){' + source + '}';
                    } else if (!match[1]) {
                        source = 'if(' + N + '(!e.namespaceURI)){' + source + '}';
                    } else if (typeof match[1] == 'string' && root8.prefix == match[1]) {
                        source = 'if(' + N + '(e.namespaceURI=="' + NAMESPACE + '")){' + source + '}';
                    } else {
                        emit('\'' + selector_string + '\'' + qsInvalid);
                    }
                    break;
                case '[':
                    match = selector.match(Patterns.attribute);
                    NS = match[0].match(STD.namespaces);
                    name100 = match[1];
                    expr = name100.split(':');
                    expr = expr.length == 2 ? expr[1] : expr[0];
                    if (match[2] && !(test = Operators[match[2]])) {
                        emit('\'' + selector_string + '\'' + qsInvalid);
                        return '';
                    }
                    if (match[4] === '') {
                        test = match[2] == '~=' ? {
                            p1: '^\\s',
                            p2: '+$',
                            p3: 'true'
                        } : match[2] in ATTR_STD_OPS && match[2] != '~=' ? {
                            p1: '^',
                            p2: '$',
                            p3: 'true'
                        } : test;
                    } else if (match[2] == '~=' && match[4].includes(' ')) {
                        source = 'if(' + N + 'false){' + source + '}';
                        break;
                    } else if (match[4]) {
                        match[4] = convertEscapes(match[4]).replace(REX.RegExpChar, '\\$&');
                    }
                    type = match[5] == 'i' || HTML_DOCUMENT && HTML_TABLE[expr.toLowerCase()] ? 'i' : '';
                    source = 'if(' + N + '(' + (!match[2] ? NS ? 's.hasAttributeNS(e,"' + name100 + '")' : 'e.hasAttribute("' + name100 + '")' : !match[4] && ATTR_STD_OPS[match[2]] && match[2] != '~=' ? 'e.getAttribute("' + name100 + '")==""' : '(/' + test.p1 + match[4] + test.p2 + '/' + type + ').test(e.getAttribute("' + name100 + '"))==' + test.p3) + ')){' + source + '}';
                    break;
                case '~':
                    match = selector.match(Patterns.relative);
                    source = 'n=e;while((e=e.previousElementSibling)){' + source + '}e=n;';
                    break;
                case '+':
                    match = selector.match(Patterns.adjacent);
                    source = 'n=e;if((e=e.previousElementSibling)){' + source + '}e=n;';
                    break;
                case '\x09':
                case '\x20':
                    match = selector.match(Patterns.ancestor);
                    source = 'n=e;while((e=e.parentElement)){' + source + '}e=n;';
                    break;
                case '>':
                    match = selector.match(Patterns.children);
                    source = 'n=e;if((e=e.parentElement)){' + source + '}e=n;';
                    break;
                case symbol in Combinators ? symbol : undefined:
                    match[match.length - 1] = '*';
                    source = Combinators[symbol](match) + source;
                    break;
                case ':':
                    if (match = selector.match(Patterns.structural)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'root':
                                source = 'if(' + N + '(e===s.root)){' + source + (mode ? 'break main;' : '') + '}';
                                break;
                            case 'empty':
                                source = 'n=e.firstChild;while(n&&!(/1|3/).test(n.nodeType)){n=n.nextSibling}if(' + D + 'n){' + source + '}';
                                break;
                            case 'only-child':
                                source = 'if(' + N + '(!e.nextElementSibling&&!e.previousElementSibling)){' + source + '}';
                                break;
                            case 'last-child':
                                source = 'if(' + N + '(!e.nextElementSibling)){' + source + '}';
                                break;
                            case 'first-child':
                                source = 'if(' + N + '(!e.previousElementSibling)){' + source + '}';
                                break;
                            case 'only-of-type':
                                source = 'o=e.nodeName;' + 'n=e;while((n=n.nextElementSibling)&&n.nodeName!=o);if(!n){' + 'n=e;while((n=n.previousElementSibling)&&n.nodeName!=o);}if(' + D + 'n){' + source + '}';
                                break;
                            case 'last-of-type':
                                source = 'n=e;o=e.nodeName;while((n=n.nextElementSibling)&&n.nodeName!=o);if(' + D + 'n){' + source + '}';
                                break;
                            case 'first-of-type':
                                source = 'n=e;o=e.nodeName;while((n=n.previousElementSibling)&&n.nodeName!=o);if(' + D + 'n){' + source + '}';
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.treestruct)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'nth-child':
                            case 'nth-of-type':
                            case 'nth-last-child':
                            case 'nth-last-of-type':
                                expr = /-of-type/i.test(match[1]);
                                if (match[1] && match[2]) {
                                    type = /last/i.test(match[1]);
                                    if (match[2] == 'n') {
                                        source = 'if(' + N + 'true){' + source + '}';
                                        break;
                                    } else if (match[2] == '1') {
                                        test = type ? 'next' : 'previous';
                                        source = expr ? 'n=e;o=e.nodeName;' + 'while((n=n.' + test + 'ElementSibling)&&n.nodeName!=o);if(' + D + 'n){' + source + '}' : 'if(' + N + '!e.' + test + 'ElementSibling){' + source + '}';
                                        break;
                                    } else if (match[2] == 'even' || match[2] == '2n0' || match[2] == '2n+0' || match[2] == '2n') {
                                        test = 'n%2==0';
                                    } else if (match[2] == 'odd' || match[2] == '2n1' || match[2] == '2n+1') {
                                        test = 'n%2==1';
                                    } else {
                                        f = /n/i.test(match[2]);
                                        n8 = match[2].split('n');
                                        a = parseInt(n8[0], 10) || 0;
                                        b = parseInt(n8[1], 10) || 0;
                                        if (n8[0] == '-') {
                                            a = -1;
                                        }
                                        if (n8[0] == '+') {
                                            a = +1;
                                        }
                                        test = (b ? '(n' + (b > 0 ? '-' : '+') + Math.abs(b) + ')' : 'n') + '%' + a + '==0';
                                        test = a >= +1 ? f ? 'n>' + (b - 1) + (Math.abs(a) != 1 ? '&&' + test : '') : 'n==' + a : a <= -1 ? f ? 'n<' + (b + 1) + (Math.abs(a) != 1 ? '&&' + test : '') : 'n==' + a : a === 0 ? n8[0] ? 'n==' + b : 'n>' + (b - 1) : 'false';
                                    }
                                    expr = expr ? 'OfType' : 'Element';
                                    type = type ? 'true' : 'false';
                                    source = 'n=s.nth' + expr + '(e,' + type + ');if(' + N + '(' + test + ')){' + source + '}';
                                } else {
                                    emit('\'' + selector_string + '\'' + qsInvalid);
                                }
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.logicalsel)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'matches':
                                if (not === true || nested === true) {
                                    emit(':matches() pseudo-class cannot be nested');
                                }
                                nested = true;
                                expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
                                expr = match[2].match(REX.SplitGroup);
                                for(i = 0, l = expr.length; l > i; ++i){
                                    expr[i] = expr[i].replace(REX.TrimSpaces, '');
                                    source = 'if(s.match("' + expr[i].replace(/\x22/g, '\\"') + '",e)){' + source + '}';
                                }
                                break;
                            case 'not':
                                if (not === true || nested === true) {
                                    emit(':not() pseudo-class cannot be nested');
                                }
                                expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
                                expr = match[2].match(REX.SplitGroup);
                                for(i = 0, l = expr.length; l > i; ++i){
                                    expr[i] = expr[i].replace(REX.TrimSpaces, '');
                                    source = compileSelector(expr[i], source, false, callback, true);
                                }
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.linguistic)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'dir':
                                source = 'var p;if(' + N + '(' + '(/' + match[2] + '/i.test(e.dir))||(p=s.ancestor("[dir]", e))&&' + '(/' + match[2] + '/i.test(p.dir))||(e.dir==""||e.dir=="auto")&&' + '(' + (match[2] == 'ltr' ? '!' : '') + RTL + '.test(e.textContent)))' + '){' + source + '};';
                                break;
                            case 'lang':
                                expr = '(?:^|-)' + match[2] + '(?:-|$)';
                                source = 'var p;if(' + N + '(' + '(e.isConnected&&(e.lang==""&&(p=s.ancestor("[lang]",e)))&&' + '(p.lang=="' + match[2] + '")||/' + expr + '/i.test(e.lang)))' + '){' + source + '};';
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.locationpc)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'link':
                                source = 'if(' + N + '(/^a|area|link$/i.test(e.nodeName)&&e.hasAttribute("href"))){' + source + '}';
                                break;
                            case 'visited':
                                source = 'if(' + N + '(/^a|area|link$/i.test(e.nodeName)&&e.hasAttribute("href")&&e.visited)){' + source + '}';
                                break;
                            case 'target':
                                source = 'if(' + N + '((s.doc.compareDocumentPosition(e)&16)&&s.doc.location.hash&&e.id==s.doc.location.hash.slice(1))){' + source + '}';
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.useraction)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'hover':
                                source = 'hasFocus' in doc1 && doc1.hasFocus() ? 'if(' + N + '(e===s.doc.hoverElement)){' + source + '}' : 'if(' + D + 'true){' + source + '}';
                                break;
                            case 'active':
                                source = 'hasFocus' in doc1 && doc1.hasFocus() ? 'if(' + N + '(e===s.doc.activeElement)){' + source + '}' : 'if(' + D + 'true){' + source + '}';
                                break;
                            case 'focus':
                                source = 'hasFocus' in doc1 ? 'if(' + N + '(e===s.doc.activeElement&&s.doc.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number"))){' + source + '}' : 'if(' + N + '(e===s.doc.activeElement&&(e.type||e.href))){' + source + '}';
                                break;
                            case 'focus-within':
                                source = 'hasFocus' in doc1 ? 'n=s.doc.activeElement;while(e){if(e===n||e.parentNode===n)break;}' + 'if(' + N + '(e===n&&s.doc.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number"))){' + source + '}' : source;
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.inputstate)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'enabled':
                                source = 'if(' + N + '(("form" in e||/^optgroup$/i.test(e.nodeName))&&"disabled" in e &&e.disabled===false' + ')){' + source + '}';
                                break;
                            case 'disabled':
                                source = 'if(' + N + '(("form" in e||/^optgroup$/i.test(e.nodeName))&&"disabled" in e&&' + '(e.disabled===true||(n=s.ancestor("fieldset",e))&&(n=s.first("legend",n))&&!n.contains(e))' + ')){' + source + '}';
                                break;
                            case 'read-only':
                                source = 'if(' + N + '(' + '(/^textarea$/i.test(e.nodeName)&&(e.readOnly||e.disabled))||' + '("|password|text|".includes("|"+e.type+"|")&&e.readOnly)' + ')){' + source + '}';
                                break;
                            case 'read-write':
                                source = 'if(' + N + '(' + '((/^textarea$/i.test(e.nodeName)&&!e.readOnly&&!e.disabled)||' + '("|password|text|".includes("|"+e.type+"|")&&!e.readOnly&&!e.disabled))||' + '(e.hasAttribute("contenteditable")||(s.doc.designMode=="on"))' + ')){' + source + '}';
                                break;
                            case 'placeholder-shown':
                                source = 'if(' + N + '(' + '(/^input|textarea$/i.test(e.nodeName))&&e.hasAttribute("placeholder")&&' + '("|textarea|password|number|search|email|text|tel|url|".includes("|"+e.type+"|"))&&' + '(!s.match(":focus",e))' + ')){' + source + '}';
                                break;
                            case 'default':
                                source = 'if(' + N + '("form" in e && e.form)){' + 'var x=0;n=[];' + 'if(e.type=="image")n=e.form.getElementsByTagName("input");' + 'if(e.type=="submit")n=e.form.elements;' + 'while(n[x]&&e!==n[x]){' + 'if(n[x].type=="image")break;' + 'if(n[x].type=="submit")break;' + 'x++;' + '}' + '}' + 'if(' + N + '(e.form&&(e===n[x]&&"|image|submit|".includes("|"+e.type+"|"))||' + '((/^option$/i.test(e.nodeName))&&e.defaultSelected)||' + '(("|radio|checkbox|".includes("|"+e.type+"|"))&&e.defaultChecked)' + ')){' + source + '}';
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.inputvalue)) {
                        match[1] = match[1].toLowerCase();
                        switch(match[1]){
                            case 'checked':
                                source = 'if(' + N + '(/^input$/i.test(e.nodeName)&&' + '("|radio|checkbox|".includes("|"+e.type+"|")&&e.checked)||' + '(/^option$/i.test(e.nodeName)&&(e.selected||e.checked))' + ')){' + source + '}';
                                break;
                            case 'indeterminate':
                                source = 'if(' + N + '(/^progress$/i.test(e.nodeName)&&!e.hasAttribute("value"))||' + '(/^input$/i.test(e.nodeName)&&("checkbox"==e.type&&e.indeterminate)||' + '("radio"==e.type&&e.name&&!s.first("input[name="+e.name+"]:checked",e.form))' + ')){' + source + '}';
                                break;
                            case 'required':
                                source = 'if(' + N + '(/^input|select|textarea$/i.test(e.nodeName)&&e.required)' + '){' + source + '}';
                                break;
                            case 'optional':
                                source = 'if(' + N + '(/^input|select|textarea$/i.test(e.nodeName)&&!e.required)' + '){' + source + '}';
                                break;
                            case 'invalid':
                                source = 'if(' + N + '((' + '(/^form$/i.test(e.nodeName)&&!e.noValidate)||' + '(e.willValidate&&!e.formNoValidate))&&!e.checkValidity())||' + '(/^fieldset$/i.test(e.nodeName)&&s.first(":invalid",e))' + '){' + source + '}';
                                break;
                            case 'valid':
                                source = 'if(' + N + '((' + '(/^form$/i.test(e.nodeName)&&!e.noValidate)||' + '(e.willValidate&&!e.formNoValidate))&&e.checkValidity())||' + '(/^fieldset$/i.test(e.nodeName)&&s.first(":valid",e))' + '){' + source + '}';
                                break;
                            case 'in-range':
                                source = 'if(' + N + '(/^input$/i.test(e.nodeName))&&' + '(e.willValidate&&!e.formNoValidate)&&' + '(!e.validity.rangeUnderflow&&!e.validity.rangeOverflow)&&' + '("|date|datetime-local|month|number|range|time|week|".includes("|"+e.type+"|"))&&' + '("range"==e.type||e.getAttribute("min")||e.getAttribute("max"))' + '){' + source + '}';
                                break;
                            case 'out-of-range':
                                source = 'if(' + N + '(/^input$/i.test(e.nodeName))&&' + '(e.willValidate&&!e.formNoValidate)&&' + '(e.validity.rangeUnderflow||e.validity.rangeOverflow)&&' + '("|date|datetime-local|month|number|range|time|week|".includes("|"+e.type+"|"))&&' + '("range"==e.type||e.getAttribute("min")||e.getAttribute("max"))' + '){' + source + '}';
                                break;
                            default:
                                emit('\'' + selector_string + '\'' + qsInvalid);
                                break;
                        }
                    } else if (match = selector.match(Patterns.pseudo_sng)) {
                        source = 'if(' + D + '(e.nodeType==1)){' + source + '}';
                    } else if (match = selector.match(Patterns.pseudo_dbl)) {
                        source = 'if(' + D + '(e.nodeType==1)){' + source + '}';
                    } else {
                        expr = false;
                        status = false;
                        for(expr in Selectors){
                            if (match = selector.match(Selectors[expr].Expression)) {
                                result = Selectors[expr].Callback(match, source, mode, callback);
                                if ('match' in result) {
                                    match = result.match;
                                }
                                vars = result.modvar;
                                if (mode) {
                                    vars && S_VARS.indexOf(vars) < 0 && (S_VARS[S_VARS.length] = vars);
                                } else {
                                    vars && M_VARS.indexOf(vars) < 0 && (M_VARS[M_VARS.length] = vars);
                                }
                                source = result.source;
                                status = result.status;
                                if (status) {
                                    break;
                                }
                            }
                        }
                        if (!status) {
                            emit('unknown pseudo-class selector \'' + selector + '\'');
                            return '';
                        }
                        if (!expr) {
                            emit('unknown token in selector \'' + selector + '\'');
                            return '';
                        }
                    }
                    break;
                default:
                    emit('\'' + selector_string + '\'' + qsInvalid);
                    break;
            }
            if (!match) {
                emit('\'' + selector_string + '\'' + qsInvalid);
                return '';
            }
            selector = match.pop();
        }
        return source;
    }, makeref = function(selectors, element) {
        return selectors.replace(/:scope/ig, element.nodeName.toLowerCase() + (element.id ? '#' + element.id : '') + (element.className ? '.' + element.classList[0] : ''));
    }, ancestor1 = function _closest(selectors, element, callback) {
        if (/:scope/i.test(selectors)) {
            selectors = makeref(selectors, element);
        }
        while(element){
            if (match1(selectors, element, callback)) break;
            element = element.parentElement;
        }
        return element;
    }, match_assert = function(f, element, callback) {
        for(var i = 0, l = f.length, r = false; l > i; ++i)f[i](element, callback, null, false) && (r = true);
        return r;
    }, match_collect = function(selectors, callback) {
        for(var i = 0, l = selectors.length, f = []; l > i; ++i)f[i] = compile(selectors[i], false, callback);
        return {
            factory: f
        };
    }, match1 = function _matches(selectors, element, callback) {
        var expressions, parsed;
        if (element && matchResolvers[selectors]) {
            return match_assert(matchResolvers[selectors].factory, element, callback);
        }
        lastMatched = selectors;
        if (arguments.length === 0) {
            emit(qsNotArgs, TypeError);
            return Config.VERBOSITY ? undefined : false;
        } else if (arguments[0] === '') {
            emit('\'\'' + qsInvalid);
            return Config.VERBOSITY ? undefined : false;
        }
        if (typeof selectors != 'string') {
            selectors = '' + selectors;
        }
        if (/:scope/i.test(selectors)) {
            selectors = makeref(selectors, element);
        }
        parsed = selectors.replace(/\x00|\\$/g, '\ufffd').replace(REX.CombineWSP, '\x20').replace(REX.PseudosWSP, '$1').replace(REX.TabCharWSP, '\t').replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
        if ((expressions = parsed.match(reValidator)) && expressions.join('') == parsed) {
            expressions = parsed.match(REX.SplitGroup);
            if (parsed[parsed.length - 1] == ',') {
                emit(qsInvalid);
                return Config.VERBOSITY ? undefined : false;
            }
        } else {
            emit('\'' + selectors + '\'' + qsInvalid);
            return Config.VERBOSITY ? undefined : false;
        }
        matchResolvers[selectors] = match_collect(expressions, callback);
        return match_assert(matchResolvers[selectors].factory, element, callback);
    }, first = function _querySelector(selectors, context, callback) {
        if (arguments.length === 0) {
            emit(qsNotArgs, TypeError);
        }
        return select(selectors, context, typeof callback == 'function' ? function firstMatch(element) {
            callback(element);
            return false;
        } : function firstMatch() {
            return false;
        })[0] || null;
    }, select = function _querySelectorAll(selectors, context, callback) {
        var expressions, nodes, parsed, resolver;
        context || (context = doc1);
        if (selectors) {
            if (resolver = selectResolvers[selectors]) {
                if (resolver.context === context && resolver.callback === callback) {
                    var f = resolver.factory, h = resolver.htmlset, n9 = resolver.nodeset, nodes = [];
                    if (n9.length > 1) {
                        for(var i = 0, l = n9.length, list; l > i; ++i){
                            list = compat1[n9[i][0]](context, n9[i].slice(1))();
                            if (f[i] !== null) {
                                f[i](list, callback, context, nodes);
                            } else {
                                nodes = nodes.concat(list);
                            }
                        }
                        if (l > 1 && nodes.length > 1) {
                            nodes.sort(documentOrder);
                            hasDupes && (nodes = unique(nodes));
                        }
                    } else {
                        if (f[0]) {
                            nodes = f[0](h[0](), callback, context, nodes);
                        } else {
                            nodes = h[0]();
                        }
                    }
                    return typeof callback == 'function' ? concatCall(nodes, callback) : nodes;
                }
            }
        }
        lastSelected = selectors;
        if (arguments.length === 0) {
            emit(qsNotArgs, TypeError);
            return Config.VERBOSITY ? undefined : none;
        } else if (arguments[0] === '') {
            emit('\'\'' + qsInvalid);
            return Config.VERBOSITY ? undefined : none;
        } else if (lastContext !== context) {
            lastContext = switchContext(context);
        }
        if (typeof selectors != 'string') {
            selectors = '' + selectors;
        }
        if (/:scope/i.test(selectors)) {
            selectors = makeref(selectors, context);
        }
        parsed = selectors.replace(/\x00|\\$/g, '\ufffd').replace(REX.CombineWSP, '\x20').replace(REX.PseudosWSP, '$1').replace(REX.TabCharWSP, '\t').replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
        if ((expressions = parsed.match(reValidator)) && expressions.join('') == parsed) {
            expressions = parsed.match(REX.SplitGroup);
            if (parsed[parsed.length - 1] == ',') {
                emit(qsInvalid);
                return Config.VERBOSITY ? undefined : false;
            }
        } else {
            emit('\'' + selectors + '\'' + qsInvalid);
            return Config.VERBOSITY ? undefined : false;
        }
        selectResolvers[selectors] = collect(expressions, context, callback);
        nodes = selectResolvers[selectors].results;
        return typeof callback == 'function' ? concatCall(nodes, callback) : nodes;
    }, optimize = function(selector, token) {
        var index = token.index, length = token[1].length + token[2].length;
        return selector.slice(0, index) + (' >+~'.indexOf(selector.charAt(index - 1)) > -1 ? ':['.indexOf(selector.charAt(index + length + 1)) > -1 ? '*' : '' : '') + selector.slice(index + length - (token[1] == '*' ? 1 : 0));
    }, collect = function(selectors, context, callback) {
        var i, l, seen = {}, token = [
            '',
            '*',
            '*'
        ], optimized = selectors, factory4 = [], htmlset = [], nodeset = [], results = [], type;
        for(i = 0, l = selectors.length; l > i; ++i){
            if (!seen[selectors[i]] && (seen[selectors[i]] = true)) {
                type = selectors[i].match(reOptimizer);
                if (type && type[1] != ':' && (token = type)) {
                    token[1] || (token[1] = '*');
                    optimized[i] = optimize(optimized[i], token);
                } else {
                    token = [
                        '',
                        '*',
                        '*'
                    ];
                }
            }
            nodeset[i] = token[1] + token[2];
            htmlset[i] = compat1[token[1]](context, token[2]);
            factory4[i] = compile(optimized[i], true, null);
            factory4[i] ? factory4[i](htmlset[i](), callback, context, results) : result.concat(htmlset[i]());
        }
        if (l > 1) {
            results.sort(documentOrder);
            hasDupes && (results = unique(results));
        }
        return {
            callback: callback,
            context: context,
            factory: factory4,
            htmlset: htmlset,
            nodeset: nodeset,
            results: results
        };
    }, _closest, _matches, _querySelector, _querySelectorAll, install1 = function(all) {
        _closest = Element.prototype.closest;
        _matches = Element.prototype.matches;
        _querySelector = Document.prototype.querySelector;
        _querySelectorAll = Document.prototype.querySelectorAll;
        Element.prototype.closest = function closest() {
            var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
            if (!('nodeType' in this)) {
                emit('\'closest\' called on an object that does not implement interface ' + ctor + '.', TypeError);
            }
            return arguments.length < 1 ? ancestor1.apply(this, []) : arguments.length < 2 ? ancestor1.apply(this, [
                arguments[0],
                this
            ]) : ancestor1.apply(this, [
                arguments[0],
                this,
                typeof arguments[1] == 'function' ? arguments[1] : undefined
            ]);
        };
        Element.prototype.matches = function matches() {
            var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
            if (!('nodeType' in this)) {
                emit('\'matches\' called on an object that does not implement interface ' + ctor + '.', TypeError);
            }
            return arguments.length < 1 ? match1.apply(this, []) : arguments.length < 2 ? match1.apply(this, [
                arguments[0],
                this
            ]) : match1.apply(this, [
                arguments[0],
                this,
                typeof arguments[1] == 'function' ? arguments[1] : undefined
            ]);
        };
        Element.prototype.querySelector = Document.prototype.querySelector = DocumentFragment.prototype.querySelector = function querySelector() {
            var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
            if (!('nodeType' in this)) {
                emit('\'querySelector\' called on an object that does not implement interface ' + ctor + '.', TypeError);
            }
            return arguments.length < 1 ? first.apply(this, []) : arguments.length < 2 ? first.apply(this, [
                arguments[0],
                this
            ]) : first.apply(this, [
                arguments[0],
                this,
                typeof arguments[1] == 'function' ? arguments[1] : undefined
            ]);
        };
        Element.prototype.querySelectorAll = Document.prototype.querySelectorAll = DocumentFragment.prototype.querySelectorAll = function querySelectorAll() {
            var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
            if (!('nodeType' in this)) {
                emit('\'querySelectorAll\' called on an object that does not implement interface ' + ctor + '.', TypeError);
            }
            return arguments.length < 1 ? select.apply(this, []) : arguments.length < 2 ? select.apply(this, [
                arguments[0],
                this
            ]) : select.apply(this, [
                arguments[0],
                this,
                typeof arguments[1] == 'function' ? arguments[1] : undefined
            ]);
        };
        if (all) {
            document.addEventListener('load', function(e) {
                var c, d, r, s, t = e.target;
                if (/iframe/i.test(t.nodeName)) {
                    c = '(' + Export + ')(this, ' + Factory + ');';
                    d = t.contentDocument;
                    s = d.createElement('script');
                    s.textContent = c + 'NW.Dom.install()';
                    r = d.documentElement;
                    r.removeChild(r.insertBefore(s, r.firstChild));
                }
            }, true);
        }
    }, uninstall1 = function() {
        Element.prototype.closest = _closest;
        Element.prototype.matches = _matches;
        Element.prototype.querySelector = Document.prototype.querySelector = DocumentFragment.prototype.querySelector = _querySelector;
        Element.prototype.querySelectorAll = Document.prototype.querySelectorAll = DocumentFragment.prototype.querySelectorAll = _querySelectorAll;
    }, none = Array(), lastContext, lastMatched, lastSelected, matchLambdas = {}, selectLambdas = {}, matchResolvers = {}, selectResolvers = {}, Snapshot = {
        doc: doc1,
        from: doc1,
        root: root8,
        byTag: byTag,
        first: first,
        match: match1,
        ancestor: ancestor1,
        nthOfType: nthOfType,
        nthElement: nthElement,
        hasAttributeNS: hasAttributeNS
    }, Dom = {
        lastMatched: lastMatched,
        lastSelected: lastSelected,
        matchLambdas: matchLambdas,
        selectLambdas: selectLambdas,
        matchResolvers: matchResolvers,
        selectResolvers: selectResolvers,
        CFG: CFG,
        M_BODY: M_BODY,
        S_BODY: S_BODY,
        M_TEST: M_TEST,
        S_TEST: S_TEST,
        byId: byId,
        byTag: byTag,
        byClass: byClass,
        match: match1,
        first: first,
        select: select,
        closest: ancestor1,
        compile: compile,
        configure: configure,
        emit: emit,
        Config: Config,
        Snapshot: Snapshot,
        Version: version7,
        install: install1,
        uninstall: uninstall1,
        Operators: Operators,
        Selectors: Selectors,
        registerCombinator: function(combinator, resolver) {
            var i = 0, l = combinator.length, symbol;
            for(; l > i; ++i){
                if (combinator[i] != '=') {
                    symbol = combinator[i];
                    break;
                }
            }
            if (CFG.combinators.indexOf(symbol) < 0) {
                CFG.combinators = CFG.combinators.replace('](', symbol + '](');
                CFG.combinators = CFG.combinators.replace('])', symbol + '])');
                Combinators[combinator] = resolver;
                setIdentifierSyntax();
            } else {
                console.warn('Warning: the \'' + combinator + '\' combinator is already registered.');
            }
        },
        registerOperator: function(operator, resolver) {
            var i = 0, l = operator.length, symbol;
            for(; l > i; ++i){
                if (operator[i] != '=') {
                    symbol = operator[i];
                    break;
                }
            }
            if (CFG.operators.indexOf(symbol) < 0 && !Operators[operator]) {
                CFG.operators = CFG.operators.replace(']=', symbol + ']=');
                Operators[operator] = resolver;
                setIdentifierSyntax();
            } else {
                console.warn('Warning: the \'' + operator + '\' operator is already registered.');
            }
        },
        registerSelector: function(name101, rexp, func) {
            Selectors[name101] || (Selectors[name101] = {
                Expression: rexp,
                Callback: func
            });
        }
    };
    initialize(doc1);
    return Dom;
}
class DOMTokenList extends Set {
    #onChange;
    constructor(onChange){
        super();
        this.#onChange = onChange;
    }
    add(token) {
        if (token === "" || /[\t\n\f\r ]/.test(token)) {
            throw new Error(`DOMTokenList.add: Invalid class token "${token}"`);
        }
        super.add(token);
        this.#onChange([
            ...this
        ].join(" "));
        return this;
    }
    clear() {
        super.clear();
        this.#onChange("");
    }
    remove(...tokens) {
        for (const token of tokens){
            super.delete(token);
        }
        this.#onChange([
            ...this
        ].join(" "));
        return this;
    }
    delete(token) {
        const deleted = super.delete(token);
        if (deleted) {
            this.#onChange([
                ...this
            ].join(" "));
        }
        return deleted;
    }
    contains(token) {
        return this.has(token);
    }
    _update(value) {
        super.clear();
        if (value !== null) {
            for (const token of value.split(/[\t\n\f\r ]+/g)){
                if (token === "") continue;
                super.add(token);
            }
        }
    }
}
class Attr {
    #namedNodeMap = null;
    #name = "";
    constructor(map8, name102, key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor");
        }
        this.#name = name102;
        this.#namedNodeMap = map8;
    }
    get name() {
        return this.#name;
    }
    get value() {
        return this.#namedNodeMap[this.#name];
    }
}
class NamedNodeMap {
    #attrObjCache = {};
    newAttr(attribute) {
        return new Attr(this, attribute, CTOR_KEY);
    }
    getNamedItem(attribute) {
        return this.#attrObjCache[attribute] ?? (this.#attrObjCache[attribute] = this.newAttr(attribute));
    }
    setNamedItem(...args) {}
}
class Element2 extends Node {
    tagName;
    #classList = new DOMTokenList((className)=>{
        if (this.hasAttribute("class") || className !== "") {
            this.attributes["class"] = className;
        }
    });
    attributes = new NamedNodeMap();
    #currentId = "";
    constructor(tagName, parentNode, attributes, key){
        super(tagName, NodeType.ELEMENT_NODE, parentNode, key);
        this.tagName = tagName;
        for (const attr of attributes){
            this.attributes[attr[0]] = attr[1];
            switch(attr[0]){
                case "class":
                    this.#classList._update(attr[1]);
                    break;
                case "id":
                    this.#currentId = attr[1];
                    break;
            }
        }
        this.tagName = this.nodeName = tagName.toUpperCase();
    }
    _shallowClone() {
        const attributes = [];
        for (const attribute of this.getAttributeNames()){
            attributes.push([
                attribute,
                this.attributes[attribute]
            ]);
        }
        return new Element2(this.nodeName, null, attributes, CTOR_KEY);
    }
    get childElementCount() {
        let count = 0;
        for (const { nodeType  } of this.childNodes){
            if (nodeType === NodeType.ELEMENT_NODE) {
                count++;
            }
        }
        return count;
    }
    get className() {
        return this.getAttribute("class") ?? "";
    }
    get classList() {
        return this.#classList;
    }
    set className(className) {
        this.setAttribute("class", className);
        this.#classList._update(className);
    }
    get outerHTML() {
        const tagName = this.tagName.toLowerCase();
        const attributes = this.attributes;
        let out = "<" + tagName;
        for (const attribute of this.getAttributeNames()){
            out += ` ${attribute.toLowerCase()}`;
            if (attributes[attribute] != null) {
                out += `="${attributes[attribute].replace(/&/g, "&amp;").replace(/\xA0/g, "&nbsp;").replace(/"/g, "&quot;")}"`;
            }
        }
        switch(tagName){
            case "area":
            case "base":
            case "br":
            case "col":
            case "embed":
            case "hr":
            case "img":
            case "input":
            case "link":
            case "meta":
            case "param":
            case "source":
            case "track":
            case "wbr":
                out += ">";
                break;
            default:
                out += ">" + this.innerHTML + `</${tagName}>`;
                break;
        }
        return out;
    }
    set outerHTML(html) {}
    get innerHTML() {
        let out = "";
        for (const child of this.childNodes){
            switch(child.nodeType){
                case NodeType.ELEMENT_NODE:
                    out += child.outerHTML;
                    break;
                case NodeType.COMMENT_NODE:
                    out += `<!--${child.data}-->`;
                    break;
                case NodeType.TEXT_NODE:
                    switch(this.tagName.toLowerCase()){
                        case "style":
                        case "script":
                        case "xmp":
                        case "iframe":
                        case "noembed":
                        case "noframes":
                        case "plaintext":
                            out += child.data;
                            break;
                        default:
                            out += child.data.replace(/&/g, "&amp;").replace(/\xA0/g, "&nbsp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                            break;
                    }
                    break;
            }
        }
        return out;
    }
    set innerHTML(html) {
        for (const child of this.childNodes){
            child._setParent(null);
        }
        const mutator = this._getChildNodesMutator();
        mutator.splice(0, this.childNodes.length);
        if (html.length) {
            const parsed = fragmentNodesFromString(html);
            mutator.push(...parsed.childNodes[0].childNodes);
            for (const child of this.childNodes){
                child._setParent(this);
                child._setOwnerDocument(this.ownerDocument);
            }
        }
    }
    get innerText() {
        return this.textContent;
    }
    set innerText(text) {
        this.textContent = text;
    }
    get children() {
        return this._getChildNodesMutator().elementsView();
    }
    get id() {
        return this.#currentId || "";
    }
    set id(id) {
        this.setAttribute(id, this.#currentId = id);
    }
    getAttributeNames() {
        return Object.getOwnPropertyNames(this.attributes);
    }
    getAttribute(name103) {
        return this.attributes[name103?.toLowerCase()] ?? null;
    }
    setAttribute(rawName, value) {
        const name104 = rawName?.toLowerCase();
        const strValue = String(value);
        this.attributes[name104] = strValue;
        if (name104 === "id") {
            this.#currentId = strValue;
        } else if (name104 === "class") {
            this.#classList._update(strValue);
        }
    }
    removeAttribute(rawName) {
        const name105 = rawName?.toLowerCase();
        delete this.attributes[name105];
        if (name105 === "class") {
            this.#classList._update(null);
        }
    }
    hasAttribute(name106) {
        return this.attributes.hasOwnProperty(name106?.toLowerCase());
    }
    hasAttributeNS(_namespace, name107) {
        return this.attributes.hasOwnProperty(name107?.toLowerCase());
    }
    get firstElementChild() {
        for (const node of this.childNodes){
            if (node.nodeType === Node.ELEMENT_NODE) {
                return node;
            }
        }
        return null;
    }
    get lastElementChild() {
        const { childNodes  } = this;
        for(let i = childNodes.length - 1; i >= 0; i--){
            const node = childNodes[i];
            if (node.nodeType === Node.ELEMENT_NODE) {
                return node;
            }
        }
        return null;
    }
    get nextElementSibling() {
        const parent = this.parentNode;
        if (!parent) {
            return null;
        }
        const index = parent._getChildNodesMutator().indexOf(this);
        const childNodes = parent.childNodes;
        let next = null;
        for(let i = index + 1; i < childNodes.length; i++){
            const sibling = childNodes[i];
            if (sibling.nodeType === NodeType.ELEMENT_NODE) {
                next = sibling;
                break;
            }
        }
        return next;
    }
    get previousElementSibling() {
        const parent = this.parentNode;
        if (!parent) {
            return null;
        }
        const index = parent._getChildNodesMutator().indexOf(this);
        const childNodes = parent.childNodes;
        let prev = null;
        for(let i = index - 1; i >= 0; i--){
            const sibling = childNodes[i];
            if (sibling.nodeType === NodeType.ELEMENT_NODE) {
                prev = sibling;
                break;
            }
        }
        return prev;
    }
    querySelector(selectors) {
        if (!this.ownerDocument) {
            throw new Error("Element must have an owner document");
        }
        return this.ownerDocument._nwapi.first(selectors, this);
    }
    querySelectorAll(selectors) {
        if (!this.ownerDocument) {
            throw new Error("Element must have an owner document");
        }
        const nodeList = new NodeList();
        const mutator = nodeList[nodeListMutatorSym]();
        mutator.push(...this.ownerDocument._nwapi.select(selectors, this));
        return nodeList;
    }
    matches(selectorString) {
        return this.ownerDocument._nwapi.match(selectorString, this);
    }
    getElementById(id) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                if (child.id === id) {
                    return child;
                }
                const search = child.getElementById(id);
                if (search) {
                    return search;
                }
            }
        }
        return null;
    }
    getElementsByTagName(tagName) {
        return this._getElementsByTagName(tagName.toUpperCase(), []);
    }
    _getElementsByTagNameWildcard(search) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                search.push(child);
                child._getElementsByTagNameWildcard(search);
            }
        }
        return search;
    }
    _getElementsByTagName(tagName, search) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                if (child.tagName === tagName) {
                    search.push(child);
                }
                child._getElementsByTagName(tagName, search);
            }
        }
        return search;
    }
    getElementsByClassName(className) {
        return this._getElementsByClassName(className, []);
    }
    getElementsByTagNameNS(_namespace, localName) {
        return this.getElementsByTagName(localName);
    }
    _getElementsByClassName(className, search) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                if (child.classList.contains(className)) {
                    search.push(child);
                }
                child._getElementsByClassName(className, search);
            }
        }
        return search;
    }
}
class DOMImplementation {
    constructor(key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor.");
        }
    }
    createDocument() {
        throw new Error("Unimplemented");
    }
    createHTMLDocument(titleStr) {
        titleStr += "";
        const doc = new HTMLDocument(CTOR_KEY);
        const docType = new DocumentType("html", "", "", CTOR_KEY);
        doc.appendChild(docType);
        const html = new Element2("html", doc, [], CTOR_KEY);
        html._setOwnerDocument(doc);
        const head = new Element2("head", html, [], CTOR_KEY);
        const body = new Element2("body", html, [], CTOR_KEY);
        const title10 = new Element2("title", head, [], CTOR_KEY);
        const titleText = new Text(titleStr);
        title10.appendChild(titleText);
        doc.head = head;
        doc.body = body;
        return doc;
    }
    createDocumentType(qualifiedName, publicId, systemId) {
        const doctype = new DocumentType(qualifiedName, publicId, systemId, CTOR_KEY);
        return doctype;
    }
}
function nodesFromString(html) {
    const parsed = JSON.parse(parse6(html));
    const node = nodeFromArray(parsed, null);
    return node;
}
class DocumentType extends Node {
    #qualifiedName = "";
    #publicId = "";
    #systemId = "";
    constructor(name108, publicId, systemId, key){
        super("html", NodeType.DOCUMENT_TYPE_NODE, null, key);
        this.#qualifiedName = name108;
        this.#publicId = publicId;
        this.#systemId = systemId;
    }
    get name() {
        return this.#qualifiedName;
    }
    get publicId() {
        return this.#publicId;
    }
    get systemId() {
        return this.#systemId;
    }
    _shallowClone() {
        return new DocumentType(this.#qualifiedName, this.#publicId, this.#systemId, CTOR_KEY);
    }
}
class Document1 extends Node {
    head = null;
    body = null;
    implementation;
    #lockState = false;
    #documentURI = "about:blank";
    #title = "";
    #nwapi = __default(this);
    constructor(){
        super("#document", NodeType.DOCUMENT_NODE, null, CTOR_KEY);
        this.implementation = new DOMImplementation(CTOR_KEY);
    }
    _shallowClone() {
        return new Document1();
    }
    get _nwapi() {
        return this.#nwapi;
    }
    get documentURI() {
        return this.#documentURI;
    }
    get title() {
        return this.querySelector("title")?.textContent || "";
    }
    get cookie() {
        return "";
    }
    set cookie(newCookie) {}
    get visibilityState() {
        return "visible";
    }
    get hidden() {
        return false;
    }
    get compatMode() {
        return "CSS1Compat";
    }
    get documentElement() {
        for (const node of this.childNodes){
            if (node.nodeType === NodeType.ELEMENT_NODE) {
                return node;
            }
        }
        return null;
    }
    get doctype() {
        for (const node of this.childNodes){
            if (node.nodeType === NodeType.DOCUMENT_TYPE_NODE) {
                return node;
            }
        }
        return null;
    }
    get childElementCount() {
        let count = 0;
        for (const { nodeType  } of this.childNodes){
            if (nodeType === NodeType.ELEMENT_NODE) {
                count++;
            }
        }
        return count;
    }
    appendChild(child) {
        super.appendChild(child);
        child._setOwnerDocument(this);
        return child;
    }
    createElement(tagName, options) {
        tagName = tagName.toUpperCase();
        const elm = new Element2(tagName, null, [], CTOR_KEY);
        elm._setOwnerDocument(this);
        return elm;
    }
    createElementNS(namespace, qualifiedName, options) {
        if (namespace === "http://www.w3.org/1999/xhtml") {
            return this.createElement(qualifiedName, options);
        } else {
            throw new Error(`createElementNS: "${namespace}" namespace unimplemented`);
        }
    }
    createTextNode(data50) {
        return new Text(data50);
    }
    createComment(data51) {
        return new Comment(data51);
    }
    importNode(node, deep = false) {
        const copy3 = node.cloneNode(deep);
        copy3._setOwnerDocument(this);
        return copy3;
    }
    adoptNode(node) {
        node._setParent(null);
        node._setOwnerDocument(this);
        return node;
    }
    querySelector(selectors) {
        return this.#nwapi.first(selectors, this);
    }
    querySelectorAll(selectors) {
        const nodeList = new NodeList();
        const mutator = nodeList[nodeListMutatorSym]();
        mutator.push(...this.#nwapi.select(selectors, this));
        return nodeList;
    }
    getElementById(id) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                if (child.id === id) {
                    return child;
                }
                const search = child.getElementById(id);
                if (search) {
                    return search;
                }
            }
        }
        return null;
    }
    getElementsByTagName(tagName) {
        if (tagName === "*") {
            return this.documentElement ? this._getElementsByTagNameWildcard(this.documentElement, []) : [];
        } else {
            return this._getElementsByTagName(tagName.toUpperCase(), []);
        }
    }
    _getElementsByTagNameWildcard(node, search) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                search.push(child);
                child._getElementsByTagNameWildcard(search);
            }
        }
        return search;
    }
    _getElementsByTagName(tagName, search) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                if (child.tagName === tagName) {
                    search.push(child);
                }
                child._getElementsByTagName(tagName, search);
            }
        }
        return search;
    }
    getElementsByTagNameNS(_namespace, localName) {
        return this.getElementsByTagName(localName);
    }
    getElementsByClassName(className) {
        return this._getElementsByClassName(className, []);
    }
    _getElementsByClassName(className, search) {
        for (const child of this.childNodes){
            if (child.nodeType === NodeType.ELEMENT_NODE) {
                if (child.classList.contains(className)) {
                    search.push(child);
                }
                child._getElementsByClassName(className, search);
            }
        }
        return search;
    }
    hasFocus() {
        return true;
    }
}
class HTMLDocument extends Document1 {
    constructor(key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor.");
        }
        super();
    }
    _shallowClone() {
        return new HTMLDocument(CTOR_KEY);
    }
}
function fragmentNodesFromString(html) {
    const parsed = JSON.parse(parseFrag(html));
    const node = nodeFromArray(parsed, null);
    return node;
}
function nodeFromArray(data52, parentNode) {
    const elm = new Element2(data52[1], parentNode, data52[2], CTOR_KEY);
    const childNodes = elm._getChildNodesMutator();
    let childNode;
    for (const child of data52.slice(3)){
        switch(child[0]){
            case NodeType.TEXT_NODE:
                childNode = new Text(child[1]);
                childNode.parentNode = childNode.parentElement = elm;
                childNodes.push(childNode);
                break;
            case NodeType.COMMENT_NODE:
                childNode = new Comment(child[1]);
                childNode.parentNode = childNode.parentElement = elm;
                childNodes.push(childNode);
                break;
            case NodeType.DOCUMENT_NODE:
            case NodeType.ELEMENT_NODE:
                nodeFromArray(child, elm);
                break;
            case NodeType.DOCUMENT_TYPE_NODE:
                childNode = new DocumentType(child[1], child[2], child[3], CTOR_KEY);
                childNode.parentNode = childNode.parentElement = elm;
                childNodes.push(childNode);
                break;
        }
    }
    return elm;
}
class DOMParser {
    parseFromString(source, mimeType) {
        if (mimeType !== "text/html") {
            throw new Error(`DOMParser: "${mimeType}" unimplemented`);
        }
        const doc = new HTMLDocument(CTOR_KEY);
        const fakeDoc = nodesFromString(source);
        let htmlNode = null;
        let hasDoctype = false;
        for (const child of [
            ...fakeDoc.childNodes
        ]){
            doc.appendChild(child);
            if (child instanceof DocumentType) {
                hasDoctype = true;
            } else if (child.nodeName === "HTML") {
                htmlNode = child;
            }
        }
        if (!hasDoctype) {
            const docType = new DocumentType("html", "", "", CTOR_KEY);
            if (doc.childNodes.length === 0) {
                doc.appendChild(docType);
            } else {
                doc.childNodes[0].before(docType);
            }
        }
        if (htmlNode) {
            for (const child of htmlNode.childNodes){
                switch(child.tagName){
                    case "HEAD":
                        doc.head = child;
                        break;
                    case "BODY":
                        doc.body = child;
                        break;
                }
            }
        }
        return doc;
    }
}
const oldHasInstance = Array[Symbol.hasInstance];
Object.defineProperty(Array, Symbol.hasInstance, {
    value (value) {
        switch(value?.constructor){
            case HTMLCollection:
            case NodeList:
                return false;
            default:
                return oldHasInstance.call(this, value);
        }
    }
});
const oldIsArray = Array.isArray;
Object.defineProperty(Array, "isArray", {
    value: (value)=>{
        switch(value?.constructor){
            case HTMLCollection:
            case NodeList:
                return false;
            default:
                return oldIsArray.call(Array, value);
        }
    }
});
async function initParser() {
    await init();
    register(parse5, parse_frag);
}
let s_DenoDomInitialized = false;
async function initDenoDom() {
    if (!s_DenoDomInitialized) {
        try {
            const denoNativePluginPath = Deno.env.get("DENO_DOM_PLUGIN");
            if (denoNativePluginPath) {
                const _symbols = {
                    deno_dom_usize_len: {
                        parameters: [],
                        result: "usize"
                    },
                    deno_dom_parse_sync: {
                        parameters: [
                            "pointer",
                            "usize",
                            "pointer"
                        ],
                        result: "void"
                    },
                    deno_dom_parse_frag_sync: {
                        parameters: [
                            "pointer",
                            "usize",
                            "pointer"
                        ],
                        result: "void"
                    },
                    deno_dom_is_big_endian: {
                        parameters: [],
                        result: "u32"
                    },
                    deno_dom_copy_buf: {
                        parameters: [
                            "pointer",
                            "pointer"
                        ],
                        result: "void"
                    }
                };
                const symbols = _symbols;
                const dylib = Deno.dlopen(denoNativePluginPath, symbols);
                const utf8Encoder = new TextEncoder();
                const utf8Decoder = new TextDecoder();
                const usizeBytes = dylib.symbols.deno_dom_usize_len();
                const isBigEndian = Boolean(dylib.symbols.deno_dom_is_big_endian());
                const dylibParseSync = dylib.symbols.deno_dom_parse_sync.bind(dylib.symbols);
                const dylibParseFragSync = dylib.symbols.deno_dom_parse_frag_sync.bind(dylib.symbols);
                const returnBufSizeLenRaw = new ArrayBuffer(usizeBytes * 2);
                const returnBufSizeLen = new Uint8Array(returnBufSizeLenRaw);
                const genericParse = (parser, srcHtml)=>{
                    const encodedHtml = utf8Encoder.encode(srcHtml);
                    parser(encodedHtml, encodedHtml.length, returnBufSizeLen);
                    const outBufSize = Number(new DataView(returnBufSizeLenRaw).getBigUint64(0, !isBigEndian));
                    const outBuf = new Uint8Array(outBufSize);
                    dylib.symbols.deno_dom_copy_buf(returnBufSizeLen.slice(usizeBytes), outBuf);
                    return utf8Decoder.decode(outBuf);
                };
                const parse17 = (html)=>{
                    return genericParse(dylibParseSync, html);
                };
                const parseFrag1 = (html)=>{
                    return genericParse(dylibParseFragSync, html);
                };
                debug("Loaded deno-dom-native");
                register(parse17, parseFrag1);
                return;
            }
        } catch (e) {
            debug("Error loading deno-dom-native: " + e.message);
        }
    }
    await initParser();
    s_DenoDomInitialized = true;
}
const kProjectType = "type";
const kProjectRender = "render";
const kProjectPreRender = "pre-render";
const kProjectPostRender = "post-render";
const kProjectExecuteDir = "execute-dir";
const kProjectOutputDir = "output-dir";
const kProjectLibDir = "lib-dir";
const kProjectResources = "resources";
const kProject404File = "404.html";
function projectOutputDir(context) {
    let outputDir = context.config?.project[kProjectOutputDir];
    if (outputDir) {
        outputDir = join3(context.dir, outputDir);
    } else {
        outputDir = context.dir;
    }
    if (existsSync(outputDir)) {
        return Deno.realPathSync(outputDir);
    } else {
        return outputDir;
    }
}
function isProjectInputFile(path77, context) {
    const renderPath = Deno.realPathSync(path77);
    return context.files.input.map((file)=>Deno.realPathSync(file)
    ).includes(renderPath);
}
function projectConfigFile(dir) {
    return [
        "_quarto.yml",
        "_quarto.yaml"
    ].map((file)=>join3(dir, file)
    ).find(existsSync);
}
function projectVarsFile(dir) {
    return [
        "_variables.yml",
        "_variables.yaml"
    ].map((file)=>join3(dir, file)
    ).find(existsSync);
}
function projectOffset(context, input) {
    const projDir = Deno.realPathSync(context.dir);
    const inputDir = Deno.realPathSync(dirname2(input));
    const offset = relative2(inputDir, projDir) || ".";
    return pathWithForwardSlashes(offset);
}
const kQuartoScratch = ".quarto";
function projectScratchPath(dir, path78 = "") {
    const scratchDir = join3(dir, kQuartoScratch);
    ensureDirSync(scratchDir);
    if (path78) {
        path78 = join3(scratchDir, path78);
        ensureDirSync(dirname2(path78));
        return path78;
    } else {
        return Deno.realPathSync(scratchDir);
    }
}
const kCrossrefIndexFile = "crossref-index-file";
const kCrossrefResolveRefs = "crossref-resolve-refs";
const kCrossrefDir = "crossref";
function projectCrossrefDir(dir) {
    return projectScratchPath(dir, kCrossrefDir);
}
function crossrefIndexForOutputFile(projectDir, input, output) {
    if (isAbsolute2(input)) {
        input = relative2(projectDir, input);
    }
    return projectScratchPath(projectDir, join3(kCrossrefDir, input, `${basename2(output)}.json`));
}
function deleteCrossrefMetadata(metadata) {
    const crossref = metadata[kCrossref];
    if (crossref) {
        delete crossref[kCrossrefChaptersAlpha];
        delete crossref[kCrossrefChapterId];
        if (Object.keys(crossref).length === 0) {
            delete metadata[kCrossref];
        }
    }
}
const kBook = "book";
const kBookCoverImage = "cover-image";
function bookConfig(name109, project) {
    const book = project?.[kBook];
    if (book) {
        return book[name109];
    } else {
        return undefined;
    }
}
function isBookIndexPage(target) {
    return target !== undefined && target.startsWith("index.");
}
function isNumberedChapter(partitioned) {
    if (partitioned?.yaml) {
        const yaml = partitioned?.yaml;
        if (typeof yaml[kTitle] === "string") {
            const parsedTitle = parsePandocTitle(yaml[kTitle]);
            return !parsedTitle.attr?.classes.includes("unnumbered");
        }
    }
    return !partitioned.headingAttr || !partitioned.headingAttr.classes.includes("unnumbered");
}
function isMultiFileBookFormat(format80) {
    const extension = format80.extensions?.book;
    if (extension) {
        return !!extension.multiFile;
    } else {
        return false;
    }
}
function texSafeFilename(file) {
    return file.replaceAll(/[ <>()|\:&;#?*']/g, "-");
}
const kGoogleAnalytics = "google-analytics";
const kTrackingId = "tracking-id";
const kStorage = "storage";
const kAnonymizeIp = "anonymize-ip";
const kVersion = "version";
const kCookieConsent = "cookie-consent";
const kCookieConsentType = "type";
const kCookieConsentStyle = "style";
const kCookieConsentPalette = "palette";
const kCookieConsentPolicyUrl = "policy-url";
const kCookiePrefsText = "prefs-text";
function scriptTagWithConsent(consentRequired, consentlevel, contents, src) {
    const srcAttr = src ? ` src="${src}"` : "";
    if (consentRequired) {
        return `
<script type="text/plain" cookie-consent="${consentlevel}"${srcAttr}>
${contents}
</script>`;
    } else {
        return `
<script type="text/javascript"${srcAttr}>
${contents}
</script>`;
    }
}
function websiteAnalyticsScriptFile(project, temp) {
    const siteMeta = project.config?.[kWebsite];
    let gaConfig = undefined;
    if (siteMeta) {
        const siteGa = siteMeta[kGoogleAnalytics];
        if (typeof siteGa === "object") {
            const siteGaMeta = siteGa;
            const trackingId = siteGaMeta[kTrackingId];
            const storage = siteGaMeta[kStorage];
            const anonymizedIp = siteGaMeta[kAnonymizeIp];
            const version8 = siteGaMeta[kVersion];
            gaConfig = googleAnalyticsConfig(project, trackingId, storage, anonymizedIp, version8);
        } else if (siteGa && typeof siteGa === "string") {
            gaConfig = googleAnalyticsConfig(project, siteGa);
        }
    }
    if (gaConfig) {
        const script = analyticsScript(gaConfig);
        if (script) {
            return scriptFile(script, temp);
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function cookieConsentDependencies(project, temp) {
    const siteMeta = project.config?.[kWebsite];
    if (siteMeta) {
        const title11 = siteMeta[kTitle] || "";
        let configuration = undefined;
        let changePrefsText = undefined;
        const consent = siteMeta[kCookieConsent];
        if (typeof consent === "object") {
            const cookieMeta = consent;
            configuration = cookieConsentConfiguration(title11, cookieMeta[kCookieConsentType], cookieMeta[kCookieConsentStyle], cookieMeta[kCookieConsentPalette], cookieMeta[kCookieConsentPolicyUrl]);
            changePrefsText = cookieMeta[kCookiePrefsText];
        } else if (consent) {
            configuration = cookieConsentConfiguration(title11);
        }
        if (configuration) {
            const consentResourcesDir = join3(projectTypeResourcePath("website"), "cookie-consent");
            const name110 = "cookie-consent.js";
            const path79 = join3(consentResourcesDir, name110);
            const cssName = "cookie-consent.css";
            const cssPath = join3(consentResourcesDir, cssName);
            return {
                scriptFile: scriptFile(cookieConsentScript(configuration), temp),
                dependency: {
                    name: "cookie-consent",
                    scripts: [
                        {
                            name: name110,
                            path: path79
                        }
                    ],
                    stylesheets: [
                        {
                            name: cssName,
                            path: cssPath
                        }
                    ]
                },
                htmlPostProcessor: (doc)=>{
                    const anchorId = "open_preferences_center";
                    const prefsAnchor = doc.getElementById(anchorId);
                    if (!prefsAnchor) {
                        const footer = doc.querySelector("div.nav-footer .nav-footer-center");
                        if (footer) {
                            const anchor = doc.createElement("a");
                            anchor.setAttribute("href", "#");
                            anchor.setAttribute("id", anchorId);
                            anchor.innerHTML = changePrefsText || "Cookie Preferences";
                            const anchorContainer = doc.createElement("div");
                            anchorContainer.setAttribute("class", "cookie-consent-footer");
                            anchorContainer.appendChild(anchor);
                            footer.appendChild(anchorContainer);
                        }
                    }
                    return Promise.resolve(kHtmlEmptyPostProcessResult);
                }
            };
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function cookieConsentEnabled(project) {
    const siteMeta = project.config?.[kWebsite];
    if (siteMeta) {
        return !!siteMeta[kCookieConsent];
    } else {
        return false;
    }
}
function cookieConsentConfiguration(_siteName, type, style, palette, policyUrl) {
    return {
        siteName: "",
        type: type || "implied",
        style: style || "simple",
        palette: palette || "light",
        policyUrl
    };
}
function googleAnalyticsConfig(project, trackingId, storage, anoymizeIp, version9) {
    return {
        trackingId,
        consent: cookieConsentEnabled(project),
        storage: storage || "cookies",
        anonymizeIp: anoymizeIp === undefined ? true : !!anoymizeIp,
        version: version9 || (trackingId.startsWith("UA-") ? 3 : 4)
    };
}
function analyticsScript(config) {
    if (config.version === 3) {
        return ga3Script(config);
    } else if (config.version === 4) {
        return ga4Script(config);
    } else {
        return undefined;
    }
}
function ga3Script(config) {
    const scripts = [];
    scripts.push(`
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');`);
    if (config.storage === "none") {
        scripts.push(`ga('create', '${config.trackingId}', { 'storage': 'none' });`);
    } else {
        scripts.push(`ga('create', '${config.trackingId}', 'auto');`);
    }
    scripts.push(`
ga('send', {
  hitType: 'pageview',
  'anonymizeIp': ${config.anonymizeIp},
});`);
    return scriptTagWithConsent(!!config.consent, "tracking", scripts.join("\n"));
}
function ga4Script(config) {
    const scripts = [];
    scripts.push(`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());`);
    if (config.storage === "none") {
        scripts.push(` 
  gtag('consent', 'default', {
    'ad_storage': 'denied',
    'analytics_storage': 'denied'
  });`);
    }
    scripts.push(`gtag('config', '${config.trackingId}', { 'anonymize_ip': ${config.anonymizeIp}});`);
    return [
        `<script async src="https://www.googletagmanager.com/gtag/js?id=${config.trackingId}"></script>`,
        scriptTagWithConsent(!!config.consent, "tracking", scripts.join("\n")), 
    ].join("\n");
}
function cookieConsentScript(config) {
    const consentLevels = config.type === "implied" ? `["strictly-necessary","functionality","tracking","targeting"]` : `["strictly-necessary"]`;
    const privacyJs = config.policyUrl !== undefined ? `,\n"website_privacy_policy_url":"${config.policyUrl}"` : "";
    return `
<script type="text/javascript" charset="UTF-8">
document.addEventListener('DOMContentLoaded', function () {
cookieconsent.run({
  "notice_banner_type":"${config.style}",
  "consent_type":"${config.type}",
  "palette":"${config.palette === "dark" ? "dark" : "light"}",
  "language":"en",
  "page_load_consent_levels":${consentLevels},
  "notice_banner_reject_button_hide":false,
  "preferences_center_close_button_hide":false,
  "website_name":"${config.siteName}"${privacyJs}
  });
});
</script> 
  `;
}
function scriptFile(script, temp) {
    const gaScriptFile = temp.createFile({
        suffix: ".js"
    });
    Deno.writeTextFileSync(gaScriptFile, script);
    return gaScriptFile;
}
async function readLanguageTranslations(translationFile, lang) {
    const files = [];
    const maybeReadYaml = async (file)=>{
        if (existsSync(file)) {
            files.push(Deno.realPathSync(file));
            const errMsg = "Validation of format language object failed.";
            const formatLanguageSchema = getSchemaDefinition("format-language");
            const result = await readAndValidateYamlFromFile(file, formatLanguageSchema, errMsg);
            return result;
        } else {
            return {};
        }
    };
    const language = await maybeReadYaml(translationFile);
    const ext = extname2(translationFile);
    const [dir, stem] = dirAndStem(translationFile);
    const variations = [];
    if (lang) {
        const subtags = lang.split("-");
        for(let i = 0; i < subtags.length; i++){
            variations.push(subtags.slice(0, i + 1).join("-"));
        }
    } else {
        const glob = stem + "-*" + ext;
        const variationRe = new RegExp("^" + stem + "-(.*?)" + ext);
        for (const entry of expandGlobSync(glob, {
            root: dir,
            includeDirs: false,
            caseInsensitive: true
        })){
            const match = entry.name.match(variationRe);
            if (match) {
                variations.push(match[1]);
            }
        }
    }
    for (const variation of variations){
        const translations = await maybeReadYaml(join3(dir, stem + "-" + variation + ext));
        Object.keys(translations).forEach((key)=>{
            if (kLanguageDefaultsKeys.includes(key)) {
                language[variation] = language[variation] || {};
                language[variation][key] = translations[key];
            } else if (typeof translations[key] === "object") {
                const targetKey = variation + "-" + key;
                language[targetKey] = language[targetKey] || {};
                language[targetKey] = {
                    ...language[targetKey],
                    ...translations[key]
                };
            }
        });
    }
    return {
        language,
        files
    };
}
function readDefaultLanguageTranslations(lang) {
    return readLanguageTranslations(resourcePath(join3("language", "_language.yml")), lang);
}
async function resolveLanguageMetadata(metadata, dir) {
    if (typeof metadata[kLanguageDefaults] === "string") {
        const translationsFile = join3(dir, metadata[kLanguageDefaults]);
        if (!existsSync(translationsFile)) {
            throw new Error("Specified 'language' file does not exist: " + translationsFile);
        }
        const translations = await readLanguageTranslations(translationsFile);
        metadata[kLanguageDefaults] = translations.language;
        return translations.files;
    } else if (typeof metadata[kLanguageDefaults] !== "object") {
        metadata[kLanguageDefaults] = {};
        return [];
    } else {
        return [];
    }
}
function translationsForLang(language, lang) {
    let translations = {};
    Object.keys(language).forEach((key)=>{
        if (kLanguageDefaultsKeys.includes(key)) {
            translations[key] = language[key];
        }
    });
    const subtags = lang.split("-");
    for(let i = 0; i < subtags.length; i++){
        const variation = subtags.slice(0, i + 1).join("-");
        if (typeof language[variation] === "object") {
            translations = mergeConfigs(translations, language[variation]);
        }
    }
    return translations;
}
async function formatLanguage(metadata, language, flags) {
    const langCode = flags?.pandocMetadata?.[kLang] || metadata[kLang] || "en";
    const defaultLanguge = translationsForLang((await readDefaultLanguageTranslations(langCode)).language, langCode);
    language = mergeConfigs(defaultLanguge, language);
    return translationsForLang(language, langCode);
}
const ESC = "\x1B";
const CSI = `${ESC}[`;
const OSC = `${ESC}]`;
const SEP1 = ";";
const bel = "\u0007";
const cursorPosition = `${CSI}6n`;
function cursorTo(x, y) {
    if (typeof y !== "number") {
        return `${CSI}${x}G`;
    }
    return `${CSI}${y};${x}H`;
}
function cursorMove(x, y) {
    let ret = "";
    if (x < 0) {
        ret += `${CSI}${-x}D`;
    } else if (x > 0) {
        ret += `${CSI}${x}C`;
    }
    if (y < 0) {
        ret += `${CSI}${-y}A`;
    } else if (y > 0) {
        ret += `${CSI}${y}B`;
    }
    return ret;
}
function cursorUp(count = 1) {
    return `${CSI}${count}A`;
}
function cursorDown(count = 1) {
    return `${CSI}${count}B`;
}
function cursorForward(count = 1) {
    return `${CSI}${count}C`;
}
function cursorBackward(count = 1) {
    return `${CSI}${count}D`;
}
function cursorNextLine(count = 1) {
    return `${CSI}E`.repeat(count);
}
function cursorPrevLine(count = 1) {
    return `${CSI}F`.repeat(count);
}
const cursorLeft = `${CSI}G`;
const cursorHide = `${CSI}?25l`;
const cursorShow = `${CSI}?25h`;
const cursorSave = `${ESC}7`;
const cursorRestore = `${ESC}8`;
function scrollUp(count = 1) {
    return `${CSI}S`.repeat(count);
}
function scrollDown(count = 1) {
    return `${CSI}T`.repeat(count);
}
const eraseScreen = `${CSI}2J`;
function eraseUp(count = 1) {
    return `${CSI}1J`.repeat(count);
}
function eraseDown(count = 1) {
    return `${CSI}0J`.repeat(count);
}
const eraseLine = `${CSI}2K`;
const eraseLineEnd = `${CSI}0K`;
const eraseLineStart = `${CSI}1K`;
function eraseLines(count) {
    let clear = "";
    for(let i = 0; i < count; i++){
        clear += eraseLine + (i < count - 1 ? cursorUp() : "");
    }
    clear += cursorLeft;
    return clear;
}
const clearScreen = "\u001Bc";
const clearTerminal = Deno.build.os === "windows" ? `${eraseScreen}${CSI}0f` : `${eraseScreen}${CSI}3J${CSI}H`;
function link(text, url) {
    return [
        OSC,
        "8",
        SEP1,
        SEP1,
        url,
        bel,
        text,
        OSC,
        "8",
        SEP1,
        SEP1,
        bel, 
    ].join("");
}
function image(buffer, options) {
    let ret = `${OSC}1337;File=inline=1`;
    if (options?.width) {
        ret += `;width=${options.width}`;
    }
    if (options?.height) {
        ret += `;height=${options.height}`;
    }
    if (options?.preserveAspectRatio === false) {
        ret += ";preserveAspectRatio=0";
    }
    return ret + ":" + encode(buffer) + bel;
}
const mod3 = {
    bel: bel,
    cursorPosition: cursorPosition,
    cursorTo: cursorTo,
    cursorMove: cursorMove,
    cursorUp: cursorUp,
    cursorDown: cursorDown,
    cursorForward: cursorForward,
    cursorBackward: cursorBackward,
    cursorNextLine: cursorNextLine,
    cursorPrevLine: cursorPrevLine,
    cursorLeft: cursorLeft,
    cursorHide: cursorHide,
    cursorShow: cursorShow,
    cursorSave: cursorSave,
    cursorRestore: cursorRestore,
    scrollUp: scrollUp,
    scrollDown: scrollDown,
    eraseScreen: eraseScreen,
    eraseUp: eraseUp,
    eraseDown: eraseDown,
    eraseLine: eraseLine,
    eraseLineEnd: eraseLineEnd,
    eraseLineStart: eraseLineStart,
    eraseLines: eraseLines,
    clearScreen: clearScreen,
    clearTerminal: clearTerminal,
    link: link,
    image: image
};
const ansi = factory();
function factory() {
    let result = [];
    let stack = [];
    const ansi1 = function(...args) {
        if (this) {
            if (args.length) {
                update(args);
                return this;
            }
            return this.toString();
        }
        return factory();
    };
    ansi1.text = function(text) {
        stack.push([
            text,
            []
        ]);
        return this;
    };
    ansi1.toString = function() {
        update();
        const str71 = result.join("");
        result = [];
        return str71;
    };
    ansi1.toBuffer = function() {
        return new TextEncoder().encode(this.toString());
    };
    const methodList = Object.entries(mod3);
    for (const [name111, method] of methodList){
        Object.defineProperty(ansi1, name111, {
            get () {
                stack.push([
                    method,
                    []
                ]);
                return this;
            }
        });
    }
    return ansi1;
    function update(args1) {
        if (!stack.length) {
            return;
        }
        if (args1) {
            stack[stack.length - 1][1] = args1;
        }
        result.push(...stack.map(([prop, args])=>typeof prop === "string" ? prop : prop.call(ansi1, ...args)
        ));
        stack = [];
    }
}
const proto = Object.create(null);
const methodNames = Object.keys(mod);
for (const name of methodNames){
    if (name === "setColorEnabled" || name === "getColorEnabled") {
        continue;
    }
    Object.defineProperty(proto, name, {
        get () {
            return factory1([
                ...this._stack,
                name
            ]);
        }
    });
}
factory1();
function factory1(stack = []) {
    const colors1 = function(str1, ...args) {
        if (str1) {
            const lastIndex = stack.length - 1;
            return stack.reduce((str72, name1, index)=>index === lastIndex ? mod[name1](str72, ...args) : mod[name1](str72)
            , str1);
        }
        const tmp = stack.slice();
        stack = [];
        return factory1(tmp);
    };
    Object.setPrototypeOf(colors1, proto);
    colors1._stack = stack;
    return colors1;
}
function getCursorPosition({ stdin =Deno.stdin , stdout =Deno.stdout  } = {}) {
    const data53 = new Uint8Array(8);
    Deno.setRaw(stdin.rid, true);
    stdout.writeSync(new TextEncoder().encode(cursorPosition));
    stdin.readSync(data53);
    Deno.setRaw(stdin.rid, false);
    const [y, x] = new TextDecoder().decode(data53).match(/\[(\d+);(\d+)R/)?.slice(1, 3).map(Number) ?? [
        0,
        0
    ];
    return {
        x,
        y
    };
}
const tty = factory2();
function factory2(options) {
    let result = "";
    let stack = [];
    const stdout = options?.stdout ?? Deno.stdout;
    const stdin = options?.stdin ?? Deno.stdin;
    const tty1 = function(...args) {
        if (this) {
            update(args);
            stdout.writeSync(new TextEncoder().encode(result));
            return this;
        }
        return factory2(args[0] ?? options);
    };
    tty1.text = function(text) {
        stack.push([
            text,
            []
        ]);
        update();
        stdout.writeSync(new TextEncoder().encode(result));
        return this;
    };
    tty1.getCursorPosition = ()=>getCursorPosition({
            stdout,
            stdin
        })
    ;
    const methodList = Object.entries(mod3);
    for (const [name112, method] of methodList){
        if (name112 === "cursorPosition") {
            continue;
        }
        Object.defineProperty(tty1, name112, {
            get () {
                stack.push([
                    method,
                    []
                ]);
                return this;
            }
        });
    }
    return tty1;
    function update(args1) {
        if (!stack.length) {
            return;
        }
        if (args1) {
            stack[stack.length - 1][1] = args1;
        }
        result = stack.reduce((prev, [cur, args])=>prev + (typeof cur === "string" ? cur : cur.call(tty1, ...args))
        , "");
        stack = [];
    }
}
var DiffType;
(function(DiffType1) {
    DiffType1["removed"] = "removed";
    DiffType1["common"] = "common";
    DiffType1["added"] = "added";
})(DiffType || (DiffType = {}));
BigInt(Number.MAX_SAFE_INTEGER);
new TextDecoder();
const kSpinnerChars = [
    "|",
    "/",
    "-",
    "\\"
];
const kSpinerContainerChars = [
    "(",
    ")"
];
const kSpinerCompleteContainerChars = [
    "[",
    "]"
];
const kSpinnerCompleteChar = Deno.build.os !== "windows" ? "✓" : ">";
const kProgressIncrementChar = "#";
const kProgressContainerChars = [
    "[",
    "]"
];
function progressBar(total, prefixMessage) {
    const updateProgress = (progress, status)=>{
        const progressBar1 = `${asciiProgressBar(progress / total * 100, 35)}`;
        const progressText = `\r${prefixMessage ? prefixMessage + " " : ""}${progressBar1}${status ? " " + status : ""}`;
        clearLine();
        info(progressText, {
            newline: false
        });
    };
    return {
        update: updateProgress,
        complete: (finalMsg)=>{
            clearLine();
            if (typeof finalMsg === "string") {
                updateProgress(total, finalMsg);
            } else {
                if (finalMsg !== false && prefixMessage) {
                    completeMessage(prefixMessage);
                } else if (finalMsg !== false) {
                    updateProgress(total);
                }
            }
        }
    };
}
async function withSpinner(options, op) {
    const cancel = spinner(options.message);
    try {
        await op();
    } finally{
        cancel(options.doneMessage);
    }
}
function spinner(status, timeInterval = 100) {
    let spin = 0;
    const id = setInterval(()=>{
        const __char = kSpinnerChars[spin % kSpinnerChars.length];
        const msg = `${spinContainer(__char)} ${status}`;
        info(`\r${msg}`, {
            newline: false
        });
        spin = spin + 1;
    }, timeInterval);
    return (finalMsg)=>{
        clearInterval(id);
        clearLine();
        if (typeof finalMsg === "string") {
            completeMessage(finalMsg);
        } else {
            if (finalMsg !== false) {
                completeMessage(status);
            }
        }
    };
}
function spinContainer(body) {
    return `${kSpinerContainerChars[0]}${body}${kSpinerContainerChars[1]}`;
}
function completeMessage(msg) {
    info(`\r${kSpinerCompleteContainerChars[0]}${kSpinnerCompleteChar}${kSpinerCompleteContainerChars[1]} ${msg}`, {
        newline: true
    });
}
function formatLine(values10, lengths) {
    const line = [];
    values10.forEach((value, i)=>{
        const len8 = lengths[i];
        if (value.length === len8) {
            line.push(value);
        } else if (value.length > len8) {
            line.push(value.substr(0, len8));
        } else {
            line.push(value.padEnd(len8, " "));
        }
    });
    return line.join("");
}
function writeFileToStdout(file) {
    const df = Deno.openSync(file, {
        read: true
    });
    const contents = readAllSync(df);
    writeAllSync(Deno.stdout, contents);
    Deno.close(df.rid);
}
function clearLine() {
    info(ansi.eraseLine.cursorLeft(), {
        newline: false
    });
}
function asciiProgressBar(percent, width = 25) {
    const segsComplete = Math.floor(percent / (100 / width));
    let progressBar2 = kProgressContainerChars[0];
    for(let i = 0; i < width; i++){
        progressBar2 = progressBar2 + (i < segsComplete ? kProgressIncrementChar : " ");
    }
    progressBar2 = progressBar2 + kProgressContainerChars[1];
    return progressBar2;
}
function bibEngine(defaults, flags) {
    return flags?.natbib ? "natbib" : flags?.biblatex ? "biblatex" : defaults[kCiteMethod] === "natbib" ? "natbib" : defaults[kCiteMethod] == "biblatex" ? "biblatex" : undefined;
}
function pdfEngine(defaults, render1, flags) {
    const pdfEngine1 = flags?.pdfEngine || defaults[kPdfEngine] || "pdflatex";
    const pdfEngineOpts = defaults[kPdfEngineOpts] || [];
    if (defaults[kPdfEngineOpt]) {
        pdfEngineOpts.push(defaults[kPdfEngineOpt]);
    }
    if (flags?.pdfEngineOpts) {
        pdfEngineOpts.push(...flags?.pdfEngineOpts);
    }
    const indexEngine = render1[kLatexMakeIndex];
    const indexEngineOpts = render1[kLatexMakeIndexOpts] || [];
    if (flags?.makeIndexOpts) {
        indexEngineOpts?.push(...flags?.makeIndexOpts);
    }
    const tlmgrOpts = render1[kLatexTlmgrOpts] || [];
    if (flags?.tlmgrOpts) {
        tlmgrOpts?.push(...flags?.tlmgrOpts);
    }
    return {
        pdfEngine: pdfEngine1,
        pdfEngineOpts,
        bibEngine: bibEngine(defaults, flags),
        indexEngine,
        indexEngineOpts,
        tlmgrOpts
    };
}
const kLatexHeaderMessageOptions = {
    bold: true
};
const kLatexBodyMessageOptions = {
    indent: 2
};
async function hasTexLive() {
    try {
        const result = await tlmgrCommand("--version", []);
        return result.code === 0;
    } catch  {
        return false;
    }
}
async function findPackages(searchTerms, opts, quiet) {
    const results = [];
    const args = [
        "--file",
        "--global"
    ];
    for (const searchTerm of searchTerms){
        if (!quiet) {
            info(`finding package for ${searchTerm}`, kLatexHeaderMessageOptions);
        }
        if (searchTerm === "fandol") {
            results.push("fandol");
        } else {
            const result = await tlmgrCommand("search", [
                ...args,
                ...opts || [],
                searchTerm
            ], true);
            if (result.code === 0 && result.stdout) {
                const text = result.stdout;
                const packageNameRegex = /^(.+)\:$/;
                const searchTermRegex = new RegExp(`\/${searchTerm}$`);
                let currentPackage = undefined;
                lines(text).forEach((line)=>{
                    const packageMatch = line.match(packageNameRegex);
                    if (packageMatch) {
                        const packageName = packageMatch[1];
                        if (packageName.includes(".")) {
                            currentPackage = packageName.split(".")[0];
                        } else {
                            currentPackage = packageName;
                        }
                    } else {
                        if (currentPackage) {
                            const searchTermMatch = line.match(searchTermRegex);
                            if (searchTermMatch) {
                                results.push(currentPackage);
                                currentPackage = undefined;
                            }
                        }
                    }
                });
            }
        }
    }
    return __VIRTUAL_FILE181(results);
}
function updatePackages(all, self, opts, quiet) {
    const args = [];
    if (opts) {
        args.push(...opts);
    }
    if (all) {
        args.push("--all");
    }
    if (self) {
        args.push("--self");
    }
    return tlmgrCommand("update", args || [], quiet);
}
async function installPackages(pkgs, opts, quiet) {
    if (!quiet) {
        info(`> ${pkgs.length} ${pkgs.length === 1 ? "package" : "packages"} to install`, kLatexHeaderMessageOptions);
    }
    let count = 1;
    for (const pkg of pkgs){
        if (!quiet) {
            info(`> installing ${pkg} (${count} of ${pkgs.length})`, kLatexHeaderMessageOptions);
        }
        await installPackage(pkg, opts, quiet);
        count = count + 1;
    }
    await addPath();
}
function addPath(opts) {
    return tlmgrCommand("path", [
        "add",
        ...opts || []
    ], true);
}
function removePath(opts, quiet) {
    return tlmgrCommand("path", [
        "remove",
        ...opts || []
    ], quiet);
}
async function installPackage(pkg, opts, quiet) {
    let installResult = await tlmgrCommand("install", [
        ...opts || [],
        pkg
    ], quiet);
    if (installResult.code !== 0 && installResult.code !== 255) {
        return Promise.reject(`tlmgr returned a non zero status code\n${installResult.stderr}`);
    }
    const isInstalled = await verifyPackageInstalled(pkg);
    if (!isInstalled) {
        const updateResult = await updatePackages(false, true, opts, quiet);
        if (updateResult.code !== 0) {
            return Promise.reject();
        }
        installResult = await tlmgrCommand("install", [
            ...opts || [],
            pkg
        ], quiet);
    }
    return installResult;
}
async function verifyPackageInstalled(pkg, opts) {
    const result = await tlmgrCommand("info", [
        "--list",
        "--only-installed",
        "--data",
        "name",
        ...opts || [],
        pkg, 
    ]);
    return result.stdout?.trim() === pkg;
}
function requireQuoting(args) {
    let requireQuoting1 = false;
    if (Deno.build.os === "windows") {
        const shellCharReg = new RegExp("[ <>()|\\:&;#?*']");
        args = args.map((a)=>{
            if (shellCharReg.test(a)) {
                requireQuoting1 = true;
                return `"${a}"`;
            } else {
                return a;
            }
        });
    }
    return {
        status: requireQuoting1,
        args: args
    };
}
function tlmgrCommand(tlmgrCmd1, args, _quiet) {
    const execTlmgr = (tlmgrCmd)=>{
        return execProcess({
            cmd: tlmgrCmd,
            stdout: "piped",
            stderr: "piped"
        });
    };
    const tlmgr = Deno.build.os === "windows" ? [
        "cmd",
        "/c",
        "tlmgr"
    ] : [
        "tlmgr"
    ];
    const safeExecNeeded = requireQuoting(args);
    try {
        return safeExecNeeded.status ? safeWindowsExec("tlmgr", [
            tlmgrCmd1,
            ...safeExecNeeded.args
        ], execTlmgr) : execTlmgr([
            ...tlmgr,
            tlmgrCmd1,
            ...args
        ]);
    } catch  {
        return Promise.reject();
    }
}
async function hasLatexDistribution() {
    try {
        const result = await execProcess({
            cmd: [
                "pdftex",
                "--version"
            ],
            stdout: "piped",
            stderr: "piped"
        });
        return result.code === 0;
    } catch  {
        return false;
    }
}
async function runPdfEngine(input, engine, outputDir, pkgMgr, quiet) {
    const [cwd, stem] = dirAndStem(input);
    const targetDir = outputDir ? join3(cwd, outputDir) : cwd;
    const output = join3(targetDir, `${stem}.pdf`);
    const log = join3(targetDir, `${stem}.log`);
    [
        log,
        output
    ].forEach((file)=>{
        if (existsSync(file)) {
            Deno.removeSync(file);
        }
    });
    const args = [
        "-interaction=batchmode",
        "-halt-on-error"
    ];
    if (outputDir !== undefined) {
        args.push(`-output-directory=${outputDir}`);
    }
    if (engine.pdfEngineOpts) {
        args.push(...engine.pdfEngineOpts);
    }
    args.push(basename2(input));
    const result = await runLatexCommand(engine.pdfEngine, args, pkgMgr, quiet, cwd);
    return {
        result,
        output,
        log
    };
}
async function runIndexEngine(input, engine, args, pkgMgr, quiet) {
    const [cwd, stem] = dirAndStem(input);
    const log = join3(cwd, `${stem}.ilg`);
    if (existsSync(log)) {
        Deno.removeSync(log);
    }
    const result = await runLatexCommand(engine || "makeindex", [
        ...args || [],
        basename2(input)
    ], pkgMgr, quiet, cwd);
    return {
        result,
        log
    };
}
async function runBibEngine(engine, input, cwd, pkgMgr, quiet) {
    const [dir, stem] = dirAndStem(input);
    const log = join3(dir, `${stem}.blg`);
    if (existsSync(log)) {
        Deno.removeSync(log);
    }
    const result = await runLatexCommand(engine, [
        input
    ], pkgMgr, quiet, cwd);
    return {
        result,
        log
    };
}
async function runLatexCommand(latexCmd, args, pkMgr, quiet, cwd) {
    const runOptions = {
        cmd: [
            latexCmd,
            ...args
        ],
        cwd,
        stdout: "piped",
        stderr: "piped"
    };
    const runCmd = async ()=>{
        const result = await execProcess(runOptions, undefined, "stdout>stderr");
        if (!quiet && result.stderr) {
            info(result.stderr, kLatexBodyMessageOptions);
        }
        return result;
    };
    try {
        return await runCmd();
    } catch (_e) {
        const tex = await hasLatexDistribution();
        if (!tex) {
            info("\nNo TeX installation was detected.\n\nPlease run 'quarto tools install tinytex' to install TinyTex.\nIf you prefer, you may install TexLive or another TeX distribution.\n");
            return Promise.reject();
        } else if (pkMgr && pkMgr.autoInstall) {
            if (!quiet) {
                info(`command ${latexCmd} not found, attempting install`, kLatexHeaderMessageOptions);
            }
            const packageForCommand = await pkMgr.searchPackages([
                latexCmd
            ]);
            if (packageForCommand) {
                await pkMgr.installPackages(packagesForCommand(latexCmd));
            }
            return await runCmd();
        } else {
            error(`Error executing ${latexCmd}`, kLatexHeaderMessageOptions);
            return Promise.reject();
        }
    }
}
function packagesForCommand(cmd) {
    if (cmd === "texindy") {
        return [
            "xindy"
        ];
    } else {
        return [
            cmd
        ];
    }
}
function packageManager(mkOptions) {
    let lastPkgs = [];
    return {
        autoInstall: mkOptions.autoInstall === undefined ? true : mkOptions.autoInstall,
        installPackages: async (pkgs)=>{
            const difference1 = __VIRTUAL_FILE137(pkgs, lastPkgs);
            if (difference1.length > 0) {
                await installPackages(pkgs, mkOptions.engine.tlmgrOpts, mkOptions.quiet);
                lastPkgs = pkgs;
                return true;
            } else {
                return false;
            }
        },
        updatePackages: (all, self)=>{
            return updatePackages(all, self, mkOptions.engine.tlmgrOpts, mkOptions.quiet);
        },
        searchPackages: (searchTerms)=>{
            return findPackages(searchTerms, mkOptions.engine.tlmgrOpts, mkOptions.quiet);
        }
    };
}
const kMissingFontLog = "missfont.log";
function findMissingFontsAndPackages(logText, dir) {
    const missingFonts = findMissingFonts(dir);
    const missingPackages = findMissingPackages(logText);
    return __VIRTUAL_FILE181([
        ...missingPackages,
        ...missingFonts
    ]);
}
function needsRecompilation(log) {
    if (existsSync(log)) {
        const logContents = Deno.readTextFileSync(log);
        const explicitMatches = explicitMatchers.some((matcher)=>{
            return logContents.match(matcher);
        });
        if (explicitMatches) {
            return true;
        } else {
            const unresolvedMatches1 = resolvingMatchers.some((resolvingMatcher)=>{
                resolvingMatcher.unresolvedMatch.lastIndex = 0;
                let unresolvedMatch = resolvingMatcher.unresolvedMatch.exec(logContents);
                const unresolvedMatches = [];
                while(unresolvedMatch){
                    const resolvedRegex = new RegExp(resolvingMatcher.resolvedMatch.replace(kCaptureToken, unresolvedMatch[1]), "gm");
                    if (!logContents.match(resolvedRegex)) {
                        unresolvedMatches.push(unresolvedMatch[1]);
                    }
                    unresolvedMatch = resolvingMatcher.unresolvedMatch.exec(logContents);
                }
                if (unresolvedMatches.length > 0) {
                    return true;
                } else {
                    return false;
                }
            });
            return !!unresolvedMatches1;
        }
    }
    return false;
}
const explicitMatchers = [
    /(Rerun to get |Please \(re\)run | Rerun LaTeX\.)/
];
const kCaptureToken = "${unresolvedCapture}";
const resolvingMatchers = [
    {
        unresolvedMatch: /^.*xpos seems to be \\@mn@currxpos.*?line ([0-9]*)\.$/gm,
        resolvedMatch: `^.*xpos seems to be [0-9]*\.[0-9]*pt.*?line ${kCaptureToken}\.$`
    }, 
];
function findMissingHyphenationFiles(logText) {
    const babelWarningRegex = /^Package babel Warning:/m;
    const hasWarning = logText.match(babelWarningRegex);
    if (hasWarning) {
        const languageRegex = /^\(babel\).* language `(\S+)'.*$/m;
        const languageMatch = logText.match(languageRegex);
        if (languageMatch) {
            const language = languageMatch[1];
            return `hyphen-${language.toLowerCase()}`;
        }
    }
}
const kErrorRegex = /^\!\s([\s\S]+)?Here is how much/m;
function findLatexError(logText, stderr) {
    const match = logText.match(kErrorRegex);
    if (match) {
        const hint = suggestHint(logText, stderr);
        if (hint) {
            return `${match[1]}\n${hint}`;
        } else {
            return match[1];
        }
    } else {
        return undefined;
    }
}
const kIndexErrorRegex = /^\s\s\s--\s(.*)/m;
function findIndexError(logText) {
    const match = logText.match(kIndexErrorRegex);
    if (match) {
        return match[1];
    } else {
        return undefined;
    }
}
function findMissingFonts(dir) {
    const missingFonts = [];
    const missFontLog = join3(dir, kMissingFontLog);
    if (existsSync(missFontLog)) {
        const missFontLogText = Deno.readTextFileSync(missFontLog);
        const fontSearchTerms = findInMissingFontLog(missFontLogText);
        missingFonts.push(...fontSearchTerms);
    }
    return missingFonts;
}
const formatFontFilter = (match, _text)=>{
    const base5 = basename2(match);
    return fontSearchTerm(base5);
};
const estoPdfFilter = (_match, _text)=>{
    return "epstopdf";
};
const packageMatchers = [
    {
        regex: /.*! Font [^=]+=([^ ]+).+ not loadable.*/g,
        filter: formatFontFilter
    },
    {
        regex: /.*! .*The font "([^"]+)" cannot be found.*/g,
        filter: formatFontFilter
    },
    {
        regex: /.*!.+ error:.+\(file ([^)]+)\): .*/g,
        filter: formatFontFilter
    },
    {
        regex: /.*Package widetext error: Install the ([^ ]+) package.*/g,
        filter: (match, _text)=>{
            return `${match}.sty`;
        }
    },
    {
        regex: /.*Unable to find TFM file "([^"]+)".*/g,
        filter: formatFontFilter
    },
    {
        regex: /.* File `(.+eps-converted-to.pdf)'.*/g,
        filter: estoPdfFilter
    },
    {
        regex: /.*xdvipdfmx:fatal: pdf_ref_obj.*/g,
        filter: estoPdfFilter
    },
    {
        regex: /.* (tikzlibrary[^ ]+?[.]code[.]tex).*/g,
        filter: (match, text)=>{
            if (text.match(/! Package tikz Error:/)) {
                return match;
            } else {
                return undefined;
            }
        }
    },
    {
        regex: /module 'lua-uni-normalize' not found:/g,
        filter: (_match, _text)=>{
            return "lua-uni-algos.lua";
        }
    },
    {
        regex: /.*! LaTeX Error: File `([^']+)' not found.*/g
    },
    {
        regex: /.* file ['`]?([^' ]+)'? not found.*/g
    },
    {
        regex: /.*the language definition file ([^ ]+) .*/g
    },
    {
        regex: /.* \\(file ([^)]+)\\): cannot open .*/g
    },
    {
        regex: /.*file `([^']+)' .*is missing.*/g
    },
    {
        regex: /.*! CTeX fontset `([^']+)' is unavailable.*/g
    },
    {
        regex: /.*: ([^:]+): command not found.*/g
    },
    {
        regex: /.*! I can't find file `([^']+)'.*/g
    }, 
];
function fontSearchTerm(font) {
    return `${font}(-(Bold|Italic|Regular).*)?[.](tfm|afm|mf|otf|ttf)`;
}
function findMissingPackages(logFileText) {
    const toInstall = [];
    packageMatchers.forEach((packageMatcher)=>{
        packageMatcher.regex.lastIndex = 0;
        let match = packageMatcher.regex.exec(logFileText);
        while(match != null){
            const file = match[1];
            const filteredFile = packageMatcher.filter ? packageMatcher.filter(file, logFileText) : file;
            if (filteredFile) {
                toInstall.push(filteredFile);
            }
            match = packageMatcher.regex.exec(logFileText);
        }
        packageMatcher.regex.lastIndex = 0;
    });
    return __VIRTUAL_FILE181(toInstall);
}
function findInMissingFontLog(missFontLogText) {
    const toInstall = [];
    lines(missFontLogText).forEach((line)=>{
        line = line.trim();
        const fontMatch = line.match(/([^\s]*)$/);
        if (fontMatch && fontMatch[1].trim() !== "") {
            toInstall.push(fontMatch[1]);
        }
        const commandMatch = line.match(/^([^\s]*)/);
        if (commandMatch && commandMatch[1].trim() !== "") {
            toInstall.push(commandMatch[1]);
        }
    });
    return __VIRTUAL_FILE181(toInstall);
}
const kUnicodePattern = {
    regex: /\! Package inputenc Error: Unicode character/,
    hint: "Possible unsupported unicode character in this configuration. Perhaps try another LaTeX engine (e.g. XeLaTeX)."
};
const kInlinePattern = {
    regex: /Missing \$ inserted\./,
    hint: "You may need to $ $ around an expression in this file."
};
const kGhostPattern = {
    regex: /^\!\!\! Error: Cannot open Ghostscript for piped input/m,
    hint: "GhostScript is likely required to compile this document. Please be sure GhostScript (https://ghostscript.com) is installed and try again."
};
const kGhostCorruptPattern = {
    regex: /^GPL Ghostscript .*: Can't find initialization file gs_init.ps/m,
    hint: "GhostScript is likely required to compile this document. Please be sure GhostScript (https://ghostscript.com) is installed and configured properly and try again."
};
const kLogOutputPatterns = [
    kUnicodePattern,
    kInlinePattern
];
const kStdErrPatterns = [
    kGhostPattern,
    kGhostCorruptPattern
];
function suggestHint(logText, stderr) {
    const stderrHint = kStdErrPatterns.find((errPattern)=>stderr?.match(errPattern.regex)
    );
    if (stderrHint) {
        return stderrHint.hint;
    } else {
        const logHint = kLogOutputPatterns.find((logPattern)=>logText.match(logPattern.regex)
        );
        if (logHint) {
            return logHint.hint;
        } else {
            return undefined;
        }
    }
}
async function generatePdf(mkOptions) {
    if (!mkOptions.quiet) {
        info(`runnning ${mkOptions.engine.pdfEngine} - 1`, kLatexHeaderMessageOptions);
    }
    const [cwd, stem] = dirAndStem(mkOptions.input);
    const workingDir = mkOptions.outputDir ? join3(cwd, mkOptions.outputDir) : cwd;
    if (!existsSync(workingDir)) {
        Deno.mkdirSync(workingDir);
    } else {
        cleanup(workingDir, stem);
    }
    const allowUpdate = await hasTexLive();
    mkOptions.autoInstall = mkOptions.autoInstall && allowUpdate;
    const pkgMgr = packageManager(mkOptions);
    const response = await initialCompileLatex(mkOptions.input, mkOptions.engine, pkgMgr, mkOptions.outputDir, mkOptions.quiet);
    const initialCompileNeedsRerun = needsRecompilation(response.log);
    const indexCreated = await makeIndexIntermediates(workingDir, stem, pkgMgr, mkOptions.engine.indexEngine, mkOptions.engine.indexEngineOpts, mkOptions.quiet);
    const bibliographyCreated = await makeBibliographyIntermediates(mkOptions.input, mkOptions.engine.bibEngine || "citeproc", pkgMgr, mkOptions.outputDir, mkOptions.quiet);
    const minRuns = (mkOptions.minRuns || 1) - 1;
    const maxRuns = (mkOptions.maxRuns || 10) - 1;
    if ((indexCreated || bibliographyCreated || minRuns || initialCompileNeedsRerun) && maxRuns > 0) {
        await recompileLatexUntilComplete(mkOptions.input, mkOptions.engine, pkgMgr, mkOptions.minRuns || 1, maxRuns, mkOptions.outputDir, mkOptions.quiet);
    }
    if (mkOptions.clean) {
        cleanup(workingDir, stem);
    }
    if (!mkOptions.quiet) {
        info("");
    }
    return mkOptions.outputDir ? join3(mkOptions.outputDir, stem + ".pdf") : join3(cwd, stem + ".pdf");
}
async function initialCompileLatex(input, engine, pkgMgr, outputDir, quiet) {
    let packagesUpdated = false;
    while(true){
        const response = await runPdfEngine(input, engine, outputDir, pkgMgr, quiet);
        const success = response.result.code === 0 && (!response.output || existsSync(response.output));
        if (success) {
            const logText = Deno.readTextFileSync(response.log);
            const missingHyphenationFile = findMissingHyphenationFiles(logText);
            if (missingHyphenationFile) {
                if (await pkgMgr.installPackages([
                    missingHyphenationFile
                ])) {
                    continue;
                } else {
                    writeError("missing hyphenation file", "", response.log);
                    return Promise.reject();
                }
            }
        } else if (pkgMgr.autoInstall) {
            if (!packagesUpdated) {
                if (!quiet) {
                    info("updating tlmgr", kLatexHeaderMessageOptions);
                }
                await pkgMgr.updatePackages(false, true);
                info("");
                if (!quiet) {
                    info("updating existing packages", kLatexHeaderMessageOptions);
                }
                await pkgMgr.updatePackages(true, false);
                packagesUpdated = true;
            }
            const packagesInstalled = await findAndInstallPackages(pkgMgr, response.log, response.result.stderr, quiet);
            if (packagesInstalled) {
                continue;
            } else {
                displayError("missing packages (automatic installation failed)", response.log, response.result);
                return Promise.reject();
            }
        } else {
            displayError("missing packages (automatic installed disabled)", response.log, response.result);
            return Promise.reject();
        }
        return Promise.resolve(response);
    }
}
function displayError(title12, log, result) {
    if (existsSync(log)) {
        const logText = Deno.readTextFileSync(log);
        writeError(title12, findLatexError(logText, result.stderr), log);
    } else {
        writeError(title12);
    }
}
async function makeIndexIntermediates(dir, stem, pkgMgr, engine, args, quiet) {
    const indexFile = join3(dir, `${stem}.idx`);
    if (existsSync(indexFile)) {
        if (!quiet) {
            info("making index", kLatexHeaderMessageOptions);
        }
        try {
            const response = await runIndexEngine(indexFile, engine, args, pkgMgr, quiet);
            const indexLogExists = existsSync(response.log);
            if (response.result.code !== 0) {
                writeError(`result code ${response.result.code}`, "", response.log);
                return Promise.reject();
            } else if (indexLogExists) {
                const logText = Deno.readTextFileSync(response.log);
                const error28 = findIndexError(logText);
                if (error28) {
                    writeError(`error generating index`, error28, response.log);
                    return Promise.reject();
                }
            }
            return true;
        } catch  {
            writeError(`error generating index`);
            return Promise.reject();
        }
    } else {
        return false;
    }
}
async function makeBibliographyIntermediates(input, engine, pkgMgr, outputDir, quiet) {
    const bibCommand = engine === "natbib" ? "bibtex" : "biber";
    const [cwd, stem] = dirAndStem(input);
    while(true){
        const auxBibFile = bibCommand === "biber" ? `${stem}.bcf` : `${stem}.aux`;
        const auxBibPath = outputDir ? join3(outputDir, auxBibFile) : auxBibFile;
        const auxBibFullPath = join3(cwd, auxBibPath);
        if (existsSync(auxBibFullPath)) {
            const auxFileData = Deno.readTextFileSync(auxBibFullPath);
            const requiresProcessing = bibCommand === "biber" ? true : containsBiblioData(auxFileData);
            if (requiresProcessing) {
                if (!quiet) {
                    info("generating bibliography", kLatexHeaderMessageOptions);
                }
                if (Deno.build.os === "windows") {
                    if (bibCommand !== "biber" && !hasTexLive()) {
                        const fixedAuxFileData = auxFileData.replaceAll(/(^\\bibdata{.+)\.bib(.*})$/gm, (_substr, prefix, postfix)=>{
                            return prefix + postfix;
                        });
                        Deno.writeTextFileSync(auxBibFullPath, fixedAuxFileData);
                    }
                }
                const response = await runBibEngine(bibCommand, auxBibPath, cwd, pkgMgr, quiet);
                if (response.result.code !== 0 && pkgMgr.autoInstall) {
                    const log = join3(dirname2(auxBibFullPath), `${stem}.blg`);
                    if (existsSync(log)) {
                        const logOutput = Deno.readTextFileSync(log);
                        const match = logOutput.match(/.* open style file ([^ ]+).*/);
                        if (match) {
                            const file = match[1];
                            if (await findAndInstallPackages(pkgMgr, file, response.result.stderr, quiet)) {
                                continue;
                            } else {
                                writeError(`error generating bibliography`, "", log);
                                return Promise.reject();
                            }
                        }
                    }
                }
                return true;
            }
        }
        return false;
    }
}
async function findAndInstallPackages(pkgMgr, logFile, stderr, _quiet) {
    if (existsSync(logFile)) {
        const logText = Deno.readTextFileSync(logFile);
        const searchTerms = findMissingFontsAndPackages(logText, dirname2(logFile));
        if (searchTerms.length > 0) {
            const packages = await pkgMgr.searchPackages(searchTerms);
            if (packages.length > 0) {
                const packagesInstalled = await pkgMgr.installPackages(packages);
                if (packagesInstalled) {
                    return true;
                } else {
                    writeError("package installation error", findLatexError(logText, stderr), logFile);
                    return Promise.reject();
                }
            } else {
                writeError("no matching packages", findLatexError(logText, stderr), logFile);
                return Promise.reject();
            }
        } else {
            writeError("error", findLatexError(logText, stderr), logFile);
            return Promise.reject();
        }
    }
    return false;
}
function writeError(primary, secondary, logFile) {
    info(`\ncompilation failed- ${primary}`, kLatexHeaderMessageOptions);
    if (secondary) {
        info(secondary);
    }
    if (logFile) {
        info(`see ${logFile} for more information.`);
    }
}
async function recompileLatexUntilComplete(input, engine, pkgMgr, minRuns, maxRuns, outputDir, quiet) {
    let runCount = 0;
    minRuns = minRuns - 1;
    while(true){
        if (runCount >= maxRuns) {
            if (!quiet) {
                warning(`maximum number of runs (${maxRuns}) reached`, kLatexHeaderMessageOptions);
            }
            break;
        }
        if (!quiet) {
            info(`running ${engine.pdfEngine} - ${runCount + 2}`, kLatexHeaderMessageOptions);
        }
        const result = await runPdfEngine(input, engine, outputDir, pkgMgr, quiet);
        if (!result.result.success) {
            displayError("Error compiling latex", result.log, result.result);
            return Promise.reject();
        } else {
            runCount = runCount + 1;
            if (existsSync(result.log) && needsRecompilation(result.log) || runCount < minRuns) {
                continue;
            }
            break;
        }
    }
}
function containsBiblioData(auxData) {
    return auxData.match(/^\\(bibdata|citation|bibstyle)\{/m);
}
function auxFile(stem, ext) {
    return `${stem}.${ext}`;
}
function cleanup(workingDir, stem) {
    const auxFiles = [
        "log",
        "idx",
        "aux",
        "bcf",
        "blg",
        "bbl",
        "fls",
        "out",
        "lof",
        "lot",
        "toc",
        "nav",
        "snm",
        "vrb",
        "ilg",
        "ind",
        "xwm",
        "brf",
        "run.xml", 
    ].map((aux)=>join3(workingDir, auxFile(stem, aux))
    );
    auxFiles.push(join3(workingDir, kMissingFontLog));
    auxFiles.forEach((auxFile1)=>{
        if (existsSync(auxFile1)) {
            Deno.removeSync(auxFile1);
        }
    });
}
function useQuartoLatexmk(format81, flags) {
    const to = format81.pandoc.to;
    const ext = format81.render[kOutputExt] || "html";
    if (format81.render[kLatexAutoMk] === false) {
        return false;
    }
    if ([
        "beamer",
        "pdf"
    ].includes(to || "") && ext === "pdf") {
        const engine = pdfEngine(format81.pandoc, format81.render, flags);
        return [
            "pdflatex",
            "xelatex",
            "lualatex"
        ].includes(engine.pdfEngine);
    }
    return false;
}
function quartoLatexmkOutputRecipe(input1, finalOutput, options, format82) {
    const [inputDir, inputStem] = dirAndStem(input1);
    const texStem = texSafeFilename(inputStem);
    const output1 = texStem + ".tex";
    let args = options.pandocArgs || [];
    const pandoc = {
        ...format82.pandoc
    };
    if (options.flags?.output) {
        args = replacePandocOutputArg(args, output1);
    } else {
        pandoc[kOutputFile] = output1;
    }
    const outputDir = format82.render[kLatexOutputDir];
    const complete = async (pandocOptions)=>{
        const mkOptions = {
            input: join3(inputDir, output1),
            engine: pdfEngine(format82.pandoc, format82.render, pandocOptions.flags),
            autoInstall: format82.render[kLatexAutoInstall],
            autoMk: format82.render[kLatexAutoMk],
            minRuns: format82.render[kLatexMinRuns],
            maxRuns: format82.render[kLatexMaxRuns],
            outputDir: outputDir === null ? undefined : outputDir,
            clean: !options.flags?.debug && format82.render[kLatexClean] !== false,
            quiet: pandocOptions.flags?.quiet
        };
        const pdfOutput = await generatePdf(mkOptions);
        const compileTex = join3(inputDir, output1);
        if (!format82.render[kKeepTex]) {
            Deno.removeSync(compileTex);
        }
        const normalizePath = (input, output)=>{
            if (isAbsolute2(output)) {
                return output;
            } else {
                return relative2(Deno.realPathSync(dirname2(input)), Deno.realPathSync(output));
            }
        };
        if (finalOutput) {
            if (finalOutput === kStdOut) {
                writeFileToStdout(pdfOutput);
                Deno.removeSync(pdfOutput);
            } else {
                const outputPdf = expandPath(finalOutput);
                if (normalize4(pdfOutput) !== normalize4(outputPdf)) {
                    ensureDirSync(dirname2(outputPdf));
                    Deno.renameSync(pdfOutput, outputPdf);
                }
            }
            if (outputDir) {
                try {
                    Deno.removeSync(outputDir, {
                        recursive: false
                    });
                } catch  {}
            }
            return normalizePath(input1, finalOutput);
        } else {
            return normalizePath(input1, pdfOutput);
        }
    };
    const to = format82.pandoc.to === "pdf" ? "latex" : format82.pandoc.to;
    return {
        output: output1,
        args,
        format: {
            ...format82,
            pandoc: {
                ...pandoc,
                to
            }
        },
        complete
    };
}
const kPatchedTemplateExt = ".patched";
function outputRecipe(context) {
    const input = context.target.input;
    const options = context.options;
    const format83 = context.format;
    let output1 = options.flags?.output;
    if (!output1) {
        const outputFile = format83.pandoc[kOutputFile];
        if (outputFile) {
            if (isAbsolute2(outputFile)) {
                output1 = outputFile;
            } else {
                output1 = join3(dirname2(input), outputFile);
            }
        } else {
            output1 = "";
        }
    }
    if (useQuartoLatexmk(format83, options.flags)) {
        return quartoLatexmkOutputRecipe(input, output1, options, format83);
    } else {
        const completeActions = [];
        const recipe = {
            output: output1,
            args: options.pandocArgs || [],
            format: {
                ...format83
            },
            complete: ()=>{
                completeActions.forEach((action)=>action()
                );
                return Promise.resolve();
            }
        };
        resolveKeepSource(recipe.format, context.engine, context.target);
        const updateOutput = (output)=>{
            recipe.output = output;
            if (options.flags?.output) {
                recipe.args = replacePandocOutputArg(recipe.args, output);
            } else {
                recipe.format.pandoc[kOutputFile] = output;
            }
        };
        const ext = format83.render[kOutputExt] || "html";
        const [inputDir, inputStem] = dirAndStem(input);
        if (format83.render[kVariant]) {
            recipe.format = {
                ...recipe.format,
                pandoc: {
                    ...recipe.format.pandoc,
                    to: `${format83.pandoc.to}${format83.render[kVariant]}`
                }
            };
        }
        if (format83.render[kKeepYaml]) {
            completeActions.push(()=>{
                const inputMd = partitionYamlFrontMatter(Deno.readTextFileSync(input));
                if (inputMd) {
                    const output = Deno.readTextFileSync(recipe.output);
                    const outputMd = partitionYamlFrontMatter(Deno.readTextFileSync(recipe.output));
                    const markdown = outputMd?.markdown || output;
                    Deno.writeTextFileSync(recipe.output, inputMd.yaml + "\n\n" + markdown);
                }
            });
        }
        if (!recipe.output) {
            let outputExt = ext;
            if (extname2(input) === ".md" && ext === "md") {
                outputExt = `${format83.pandoc.to}.md`;
            }
            updateOutput(inputStem + "." + outputExt);
        } else if (recipe.output === kStdOut) {
            updateOutput(options.temp.createFile({
                suffix: "." + ext
            }));
            completeActions.push(()=>{
                writeFileToStdout(recipe.output);
                Deno.removeSync(recipe.output);
            });
        } else if (!isAbsolute2(recipe.output)) {
            updateOutput(relative2(inputDir, recipe.output));
        } else {
            updateOutput(expandPath(recipe.output));
        }
        return recipe;
    }
}
async function patchHtmlTemplate(templateName, format84, temp, patches, flags) {
    return await patchTemplate(templateName, temp, (template4)=>{
        let css = "";
        let patchedTemplate = template4.replace(/\$for\(css\)\$[\W\w]+?\$endfor\$/, (match)=>{
            css = match;
            return "";
        });
        if (css) {
            let patched = false;
            patchedTemplate = patchedTemplate.replace(/^<\/head>$/m, (match)=>{
                patched = true;
                return css + "\n" + match;
            });
            if (!patched) {
                patchedTemplate = template4;
            }
        }
        if (patches) {
            for (const patch of patches){
                patchedTemplate = patch(patchedTemplate);
            }
        }
        if ((flags && flags[kSelfContained] || format84.pandoc[kSelfContained]) && !format84.render[kSelfContainedMath]) {
            const math = mathConfig(format84, flags);
            if (math) {
                const mathTemplate = math.method === "mathjax" ? mathjaxScript(math.url) : math.method == "katex" ? katexScript(math.url) : "";
                if (mathTemplate) {
                    patchedTemplate = patchedTemplate.replace(/\$math\$/, mathTemplate);
                }
            }
        }
        patchedTemplate = patchedTemplate.replace(/<meta name="generator" content="pandoc"\s*\/?>/, `<meta name="generator" content="quarto-${quartoConfig.version()}" \/>`);
        return patchedTemplate;
    });
}
function mathConfig(format85, flags) {
    if (flags?.mathjax || flags?.katex || flags?.webtex || flags?.gladtex || flags?.mathml) {
        return undefined;
    }
    const math = format85.pandoc[kHtmlMathMethod];
    if (math === undefined || math === "mathjax") {
        return {
            method: "mathjax",
            url: "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js"
        };
    } else if (math === "katex") {
        return {
            method: "katex",
            url: "https://cdn.jsdelivr.net/npm/katex@0.13.11/dist/"
        };
    } else if (__VIRTUAL_FILE18(math)) {
        const mathMethod = math;
        if ((mathMethod.method === "mathjax" || mathMethod.method === "katex") && typeof mathMethod.url === "string") {
            return mathMethod;
        }
    }
}
function mathjaxScript(url) {
    return `
  <script>
    (function () {
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src  = "${url}";
      document.getElementsByTagName("head")[0].appendChild(script);
    })();
  </script>
`;
}
function katexScript(url) {
    url = url.trim();
    if (!url.endsWith("/")) {
        url += "/";
    }
    return `
  <script>
    document.addEventListener("DOMContentLoaded", function () {
      var head = document.getElementsByTagName("head")[0];
      var link = document.createElement("link");
      link.rel = "stylesheet";
      link.href = "${url}katex.min.css";
      head.appendChild(link);

      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src  = "${url}katex.min.js";
      script.async = false;
      script.addEventListener('load', function() {
        var mathElements = document.getElementsByClassName("math");
          var macros = [];
          for (var i = 0; i < mathElements.length; i++) {
            var texText = mathElements[i].firstChild;
            if (mathElements[i].tagName == "SPAN") {
              window.katex.render(texText.data, mathElements[i], {
                displayMode: mathElements[i].classList.contains('display'),
                throwOnError: false,
                macros: macros,
                fleqn: false
              });
            }
          }
      });
      head.appendChild(script);
    });
  </script>
  `;
}
async function patchTemplate(format86, temp, patch) {
    const result = await execProcess({
        cmd: [
            pandocBinaryPath(),
            "-D",
            format86
        ],
        stdout: "piped"
    });
    if (result.success) {
        const patched = patch(result.stdout);
        const templateDir = temp.createDir();
        const template5 = await Deno.makeTempFile({
            suffix: kPatchedTemplateExt,
            dir: templateDir
        });
        await Deno.writeTextFile(template5, patched);
        return template5;
    } else {
        throw new Error();
    }
}
function layoutFilter() {
    return resourcePath("filters/layout/layout.lua");
}
function layoutFilterParams(format87) {
    const params = {};
    const pageWidth = format87.render[kPageWidth];
    if (pageWidth) {
        params[kPageWidth] = pageWidth;
    }
    return params;
}
function selectInputPostprocessor(doc) {
    const outputs = doc.querySelectorAll(".cell-output-display");
    for(let i = 0; i < outputs.length; i++){
        const output = outputs[i];
        const hasSelect = !!output.querySelector("select");
        if (hasSelect) {
            output.classList.add("no-overflow-x");
        }
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
}
const denoRunHandler = {
    canHandle: (script)=>{
        return [
            ".js",
            ".ts"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, options)=>{
        const denoDir = initDenoCache();
        options = {
            ...options,
            env: {
                ...options?.env,
                DENO_DIR: denoDir
            }
        };
        const importMap = resourcePath(join3("deno_std", "import_map.json"));
        return await execProcess({
            cmd: [
                binaryPath("deno"),
                "run",
                "--import-map",
                importMap,
                "--cached-only",
                "--allow-all",
                "--unstable",
                script,
                ...args, 
            ],
            ...options
        });
    }
};
function initDenoCache() {
    const distDenoStd = resourcePath("deno_std");
    const distLock = join3(distDenoStd, "deno_std.lock");
    const cacheDenoStd = quartoCacheDir("deno_std");
    const cacheLock = join3(cacheDenoStd, "deno_std.lock");
    if (!existsSync(cacheLock) || Deno.readTextFileSync(cacheLock) != Deno.readTextFileSync(distLock)) {
        removeIfExists(cacheDenoStd);
        copySync(distDenoStd, cacheDenoStd, {
            overwrite: true
        });
    }
    return join3(cacheDenoStd, "cache");
}
const pythonRunHandler = {
    canHandle: (script)=>{
        return [
            ".py"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, options)=>{
        return await execProcess({
            cmd: [
                ...await pythonExec(),
                script,
                ...args, 
            ],
            ...options
        });
    }
};
const rRunHandler = {
    canHandle: (script)=>{
        return [
            ".r"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, options)=>{
        return await execProcess({
            cmd: [
                await rBinaryPath("Rscript"),
                script,
                ...args, 
            ],
            ...options
        });
    }
};
function asArray(x) {
    return x ? Array.isArray(x) ? x : [
        x
    ] : [];
}
const kQuartoIgnore = [
    `/${kQuartoScratch}/`
];
async function ensureGitignore(dir, forceEnv = false) {
    const gitignorePath = join3(dir, ".gitignore");
    if (await exists(gitignorePath)) {
        const gitignore = lines(Deno.readTextFileSync(gitignorePath)).map((line)=>line.trim()
        );
        const requiredEntries = [];
        for (const requiredEntry of gitignoreEntries(dir, forceEnv)){
            if (!gitignore.includes(requiredEntry)) {
                requiredEntries.push(requiredEntry);
            }
        }
        if (requiredEntries.length > 0) {
            writeGitignore(dir, gitignore.concat(requiredEntries));
            return true;
        } else {
            return false;
        }
    } else if (forceEnv) {
        await createGitignore(dir, forceEnv);
        return true;
    } else if (await which("git")) {
        const result = await execProcess({
            cmd: [
                "git",
                "rev-parse"
            ],
            cwd: dir,
            stdout: "piped",
            stderr: "piped"
        });
        if (result.success) {
            await createGitignore(dir, forceEnv);
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
function createGitignore(dir, forceEnv = false) {
    writeGitignore(dir, gitignoreEntries(dir, forceEnv));
}
function gitignoreEntries(dir, forceEnv = false) {
    const kEnv = "env/";
    if (forceEnv || isEnvDir(join3(dir, kEnv))) {
        return [
            "/" + kEnv
        ].concat(kQuartoIgnore);
    } else {
        return kQuartoIgnore;
    }
}
function writeGitignore(dir, lines1) {
    const lineEnding = Deno.build.os === "windows" ? "\r\n" : "\n";
    Deno.writeTextFileSync(join3(dir, ".gitignore"), lines1.join(lineEnding) + lineEnding);
    const gitattributes = join3(dir, ".gitattributes");
    if (!existsSync(gitattributes)) {
        Deno.writeTextFileSync(gitattributes, "*.qmd linguist-language=RMarkdown" + lineEnding);
    }
}
function projectResourceFiles(dir, config) {
    let resourceGlobs = asArray(config.project[kProjectResources]);
    const resourceFiles = [];
    const outputDir = config.project[kProjectOutputDir];
    if (outputDir) {
        resourceGlobs = (resourceGlobs || []).concat(kQuartoIgnore.map((entry)=>`!${entry}`
        ));
        const exclude = outputDir ? [
            outputDir
        ] : [];
        const projectResourceFiles1 = resolvePathGlobs(dir, resourceGlobs, exclude);
        resourceFiles.push(...__VIRTUAL_FILE137(projectResourceFiles1.include, projectResourceFiles1.exclude));
        resourceFiles.push(...[
            "robots.txt",
            ".nojekyll",
            "CNAME",
            "_redirects",
            kProject404File
        ].map((file)=>join3(dir, file)
        ).filter(existsSync));
    }
    return __VIRTUAL_FILE181(resourceFiles);
}
function copyResourceFile(rootDir, srcFile, destFile) {
    if (!Deno.realPathSync(srcFile).startsWith(Deno.realPathSync(rootDir))) {
        return;
    }
    ensureDirSync(dirname2(destFile));
    copyFileIfNewer(srcFile, destFile);
    if (extname2(srcFile).toLowerCase() === ".css") {
        handleCssReferences(rootDir, srcFile, destFile);
    }
}
function fixupCssReferences(css, offset, onRef) {
    let destCss = css.replaceAll(kCssUrlRegex, (_match, p1, p2)=>{
        const ref3 = p2.startsWith("/") ? `${offset}${p2.slice(1)}` : p2;
        onRef(ref3);
        return `url(${p1 || ""}${ref3}${p1 || ""})`;
    });
    destCss = destCss.replaceAll(kCssImportRegex, (_match, p1, p2)=>{
        const ref4 = p2.startsWith("/") ? `${offset}${p2.slice(1)}` : p2;
        onRef(ref4);
        return `@import ${p1 || ""}${ref4}${p1 || ""}`;
    });
    return destCss;
}
function handleCssReferences(rootDir, srcFile, destFile) {
    const css = Deno.readTextFileSync(destFile);
    const offset = relative2(dirname2(srcFile), rootDir);
    const copyRef = (ref5)=>{
        const refPath = join3(dirname2(srcFile), ref5);
        if (safeExistsSync(refPath)) {
            const refDestPath = join3(dirname2(destFile), ref5);
            copyResourceFile(rootDir, refPath, refDestPath);
        }
    };
    const destCss = fixupCssReferences(css, offset, copyRef);
    if (destCss !== css) {
        Deno.writeTextFileSync(destFile, destCss);
    }
}
const kProjectFreezeDir = "_freeze";
const kOldFreezeExecuteResults = "execute";
const kFreezeExecuteResults = "execute-results";
function freezeExecuteResult(input, output, result) {
    result = cloneDeep1(result);
    const resolveIncludes = (name113)=>{
        if (result.includes) {
            if (result.includes[name113]) {
                result.includes[name113] = result.includes[name113].map((file)=>Deno.readTextFileSync(file)
                );
            }
        }
    };
    resolveIncludes(kIncludeInHeader);
    resolveIncludes(kIncludeBeforeBody);
    resolveIncludes(kIncludeAfterBody);
    result.supporting = result.supporting.map((file)=>{
        if (isAbsolute2(file)) {
            return relative2(Deno.realPathSync(dirname2(input)), file);
        } else {
            return file;
        }
    });
    const hash = freezeInputHash(input);
    const freezeJsonFile = freezeResultFile(input, output, true);
    Deno.writeTextFileSync(freezeJsonFile, JSON.stringify({
        hash,
        result
    }, undefined, 2));
    return freezeJsonFile;
}
function defrostExecuteResult(source, output, temp, force = false) {
    const resultFile = freezeResultFile(source, output);
    if (existsSync(resultFile)) {
        const { hash , result  } = JSON.parse(Deno.readTextFileSync(resultFile));
        if (force || hash === freezeInputHash(source)) {
            result.supporting = result.supporting.map((file)=>join3(Deno.realPathSync(dirname2(source)), file)
            );
            const resolveIncludes = (name114)=>{
                if (result.includes) {
                    if (result.includes[name114]) {
                        result.includes[name114] = result.includes[name114].map((content)=>{
                            const includeFile = temp.createFile();
                            Deno.writeTextFileSync(includeFile, content);
                            return includeFile;
                        });
                    }
                }
            };
            resolveIncludes(kIncludeInHeader);
            resolveIncludes(kIncludeBeforeBody);
            resolveIncludes(kIncludeAfterBody);
            return result;
        }
    }
}
function projectFreezerDir(dir, hidden30) {
    const freezeDir = hidden30 ? projectScratchPath(dir, kProjectFreezeDir) : join3(dir, kProjectFreezeDir);
    ensureDirSync(freezeDir);
    return Deno.realPathSync(freezeDir);
}
function copyToProjectFreezer(project, file, hidden31, incremental) {
    const freezerDir = projectFreezerDir(project.dir, hidden31);
    const srcFilesDir = join3(project.dir, file);
    const destFilesDir = join3(freezerDir, asFreezerDir(file));
    if (incremental) {
        for (const dir of Deno.readDirSync(srcFilesDir)){
            if (dir.name === kFreezeExecuteResults) {
                const resultsDir = join3(srcFilesDir, dir.name);
                const destResultsDir = join3(destFilesDir, kFreezeExecuteResults);
                ensureDirSync(destResultsDir);
                for (const json3 of Deno.readDirSync(resultsDir)){
                    if (json3.isFile) {
                        Deno.copyFileSync(join3(resultsDir, json3.name), join3(destResultsDir, json3.name));
                    }
                }
            } else {
                copyMinimal(join3(srcFilesDir, dir.name), join3(destFilesDir, dir.name));
            }
        }
    } else {
        copyMinimal(srcFilesDir, destFilesDir);
    }
}
function copyFromProjectFreezer(project, file, hidden32) {
    const freezerDir = projectFreezerDir(project.dir, hidden32);
    const srcFilesDir = join3(freezerDir, asFreezerDir(file));
    const destFilesDir = join3(project.dir, file);
    if (existsSync(srcFilesDir)) {
        copyMinimal(srcFilesDir, destFilesDir);
    }
}
function pruneProjectFreezerDir(project, dir, files, hidden33) {
    const freezerDir = projectFreezerDir(project.dir, hidden33);
    files.map((file)=>{
        const filePath = join3(freezerDir, dir, file);
        try {
            removeIfExists(filePath);
        } catch  {}
    });
    removeIfEmptyDir(join3(freezerDir, dir));
}
function pruneProjectFreezer(project, hidden34) {
    const freezerDir = projectFreezerDir(project.dir, hidden34);
    const libDir = project.config?.project[kProjectLibDir];
    if (libDir) {
        let remove = true;
        for (const entry of Deno.readDirSync(freezerDir)){
            if (entry.isFile || entry.name !== libDir) {
                remove = false;
                break;
            }
        }
        if (remove) {
            removeIfExists(freezerDir);
        }
    } else {
        removeIfEmptyDir(freezerDir);
    }
}
function freezerFreezeFile(project, freezeFile) {
    const filesDir = asFreezerDir(dirname2(dirname2(freezeFile)));
    return join3(project.dir, kProjectFreezeDir, filesDir, kFreezeExecuteResults, basename2(freezeFile));
}
function freezerFigsDir(project, filesDir, figsDir) {
    return join3(project.dir, kProjectFreezeDir, asFreezerDir(filesDir), figsDir);
}
function freezeResultFile(input, output, ensureDir1 = false) {
    const filesDir = join3(dirname2(input), inputFilesDir(input));
    const freezeDir = join3(filesDir, kFreezeExecuteResults);
    if (ensureDir1) {
        ensureDirSync(freezeDir);
    }
    return join3(freezeDir, extname2(output).slice(1) + ".json");
}
function removeFreezeResults(filesDir) {
    const freezeDir = join3(filesDir, kFreezeExecuteResults);
    removeIfExists(freezeDir);
    const oldFreezeDir = join3(filesDir, kOldFreezeExecuteResults);
    removeIfExists(oldFreezeDir);
    if (existsSync(filesDir)) {
        removeIfEmptyDir(filesDir);
    }
}
function freezeInputHash(input) {
    return md5Hash(Deno.readTextFileSync(input));
}
function asFreezerDir(dir) {
    return dir.replace(/_files$/, "");
}
const db = JSON.parse(`{
  "application/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "application/3gpdash-qoe-report+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/3gpp-ims+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/3gpphal+json": {
    "source": "iana",
    "compressible": true
  },
  "application/3gpphalforms+json": {
    "source": "iana",
    "compressible": true
  },
  "application/a2l": {
    "source": "iana"
  },
  "application/activemessage": {
    "source": "iana"
  },
  "application/activity+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-costmap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-costmapfilter+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-directory+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointcost+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointcostparams+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointprop+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-endpointpropparams+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-error+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-networkmap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-networkmapfilter+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-updatestreamcontrol+json": {
    "source": "iana",
    "compressible": true
  },
  "application/alto-updatestreamparams+json": {
    "source": "iana",
    "compressible": true
  },
  "application/aml": {
    "source": "iana"
  },
  "application/andrew-inset": {
    "source": "iana",
    "extensions": ["ez"]
  },
  "application/applefile": {
    "source": "iana"
  },
  "application/applixware": {
    "source": "apache",
    "extensions": ["aw"]
  },
  "application/atf": {
    "source": "iana"
  },
  "application/atfx": {
    "source": "iana"
  },
  "application/atom+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atom"]
  },
  "application/atomcat+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atomcat"]
  },
  "application/atomdeleted+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atomdeleted"]
  },
  "application/atomicmail": {
    "source": "iana"
  },
  "application/atomsvc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["atomsvc"]
  },
  "application/atsc-dwd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dwd"]
  },
  "application/atsc-dynamic-event-message": {
    "source": "iana"
  },
  "application/atsc-held+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["held"]
  },
  "application/atsc-rdt+json": {
    "source": "iana",
    "compressible": true
  },
  "application/atsc-rsat+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rsat"]
  },
  "application/atxml": {
    "source": "iana"
  },
  "application/auth-policy+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/bacnet-xdd+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/batch-smtp": {
    "source": "iana"
  },
  "application/bdoc": {
    "compressible": false,
    "extensions": ["bdoc"]
  },
  "application/beep+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/calendar+json": {
    "source": "iana",
    "compressible": true
  },
  "application/calendar+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xcs"]
  },
  "application/call-completion": {
    "source": "iana"
  },
  "application/cals-1840": {
    "source": "iana"
  },
  "application/captive+json": {
    "source": "iana",
    "compressible": true
  },
  "application/cbor": {
    "source": "iana"
  },
  "application/cbor-seq": {
    "source": "iana"
  },
  "application/cccex": {
    "source": "iana"
  },
  "application/ccmp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ccxml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ccxml"]
  },
  "application/cdfx+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["cdfx"]
  },
  "application/cdmi-capability": {
    "source": "iana",
    "extensions": ["cdmia"]
  },
  "application/cdmi-container": {
    "source": "iana",
    "extensions": ["cdmic"]
  },
  "application/cdmi-domain": {
    "source": "iana",
    "extensions": ["cdmid"]
  },
  "application/cdmi-object": {
    "source": "iana",
    "extensions": ["cdmio"]
  },
  "application/cdmi-queue": {
    "source": "iana",
    "extensions": ["cdmiq"]
  },
  "application/cdni": {
    "source": "iana"
  },
  "application/cea": {
    "source": "iana"
  },
  "application/cea-2018+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cellml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cfw": {
    "source": "iana"
  },
  "application/clr": {
    "source": "iana"
  },
  "application/clue+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/clue_info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cms": {
    "source": "iana"
  },
  "application/cnrp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/coap-group+json": {
    "source": "iana",
    "compressible": true
  },
  "application/coap-payload": {
    "source": "iana"
  },
  "application/commonground": {
    "source": "iana"
  },
  "application/conference-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cose": {
    "source": "iana"
  },
  "application/cose-key": {
    "source": "iana"
  },
  "application/cose-key-set": {
    "source": "iana"
  },
  "application/cpl+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/csrattrs": {
    "source": "iana"
  },
  "application/csta+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/cstadata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/csvm+json": {
    "source": "iana",
    "compressible": true
  },
  "application/cu-seeme": {
    "source": "apache",
    "extensions": ["cu"]
  },
  "application/cwt": {
    "source": "iana"
  },
  "application/cybercash": {
    "source": "iana"
  },
  "application/dart": {
    "compressible": true
  },
  "application/dash+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mpd"]
  },
  "application/dashdelta": {
    "source": "iana"
  },
  "application/davmount+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["davmount"]
  },
  "application/dca-rft": {
    "source": "iana"
  },
  "application/dcd": {
    "source": "iana"
  },
  "application/dec-dx": {
    "source": "iana"
  },
  "application/dialog-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/dicom": {
    "source": "iana"
  },
  "application/dicom+json": {
    "source": "iana",
    "compressible": true
  },
  "application/dicom+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/dii": {
    "source": "iana"
  },
  "application/dit": {
    "source": "iana"
  },
  "application/dns": {
    "source": "iana"
  },
  "application/dns+json": {
    "source": "iana",
    "compressible": true
  },
  "application/dns-message": {
    "source": "iana"
  },
  "application/docbook+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["dbk"]
  },
  "application/dots+cbor": {
    "source": "iana"
  },
  "application/dskpp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/dssc+der": {
    "source": "iana",
    "extensions": ["dssc"]
  },
  "application/dssc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xdssc"]
  },
  "application/dvcs": {
    "source": "iana"
  },
  "application/ecmascript": {
    "source": "iana",
    "compressible": true,
    "extensions": ["es","ecma"]
  },
  "application/edi-consent": {
    "source": "iana"
  },
  "application/edi-x12": {
    "source": "iana",
    "compressible": false
  },
  "application/edifact": {
    "source": "iana",
    "compressible": false
  },
  "application/efi": {
    "source": "iana"
  },
  "application/elm+json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/elm+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.cap+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/emergencycalldata.comment+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.control+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.deviceinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.ecall.msd": {
    "source": "iana"
  },
  "application/emergencycalldata.providerinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.serviceinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.subscriberinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emergencycalldata.veds+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/emma+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["emma"]
  },
  "application/emotionml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["emotionml"]
  },
  "application/encaprtp": {
    "source": "iana"
  },
  "application/epp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/epub+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["epub"]
  },
  "application/eshop": {
    "source": "iana"
  },
  "application/exi": {
    "source": "iana",
    "extensions": ["exi"]
  },
  "application/expect-ct-report+json": {
    "source": "iana",
    "compressible": true
  },
  "application/fastinfoset": {
    "source": "iana"
  },
  "application/fastsoap": {
    "source": "iana"
  },
  "application/fdt+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["fdt"]
  },
  "application/fhir+json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/fhir+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/fido.trusted-apps+json": {
    "compressible": true
  },
  "application/fits": {
    "source": "iana"
  },
  "application/flexfec": {
    "source": "iana"
  },
  "application/font-sfnt": {
    "source": "iana"
  },
  "application/font-tdpfr": {
    "source": "iana",
    "extensions": ["pfr"]
  },
  "application/font-woff": {
    "source": "iana",
    "compressible": false
  },
  "application/framework-attributes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/geo+json": {
    "source": "iana",
    "compressible": true,
    "extensions": ["geojson"]
  },
  "application/geo+json-seq": {
    "source": "iana"
  },
  "application/geopackage+sqlite3": {
    "source": "iana"
  },
  "application/geoxacml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/gltf-buffer": {
    "source": "iana"
  },
  "application/gml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["gml"]
  },
  "application/gpx+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["gpx"]
  },
  "application/gxf": {
    "source": "apache",
    "extensions": ["gxf"]
  },
  "application/gzip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["gz"]
  },
  "application/h224": {
    "source": "iana"
  },
  "application/held+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/hjson": {
    "extensions": ["hjson"]
  },
  "application/http": {
    "source": "iana"
  },
  "application/hyperstudio": {
    "source": "iana",
    "extensions": ["stk"]
  },
  "application/ibe-key-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ibe-pkg-reply+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ibe-pp-data": {
    "source": "iana"
  },
  "application/iges": {
    "source": "iana"
  },
  "application/im-iscomposing+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/index": {
    "source": "iana"
  },
  "application/index.cmd": {
    "source": "iana"
  },
  "application/index.obj": {
    "source": "iana"
  },
  "application/index.response": {
    "source": "iana"
  },
  "application/index.vnd": {
    "source": "iana"
  },
  "application/inkml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ink","inkml"]
  },
  "application/iotp": {
    "source": "iana"
  },
  "application/ipfix": {
    "source": "iana",
    "extensions": ["ipfix"]
  },
  "application/ipp": {
    "source": "iana"
  },
  "application/isup": {
    "source": "iana"
  },
  "application/its+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["its"]
  },
  "application/java-archive": {
    "source": "apache",
    "compressible": false,
    "extensions": ["jar","war","ear"]
  },
  "application/java-serialized-object": {
    "source": "apache",
    "compressible": false,
    "extensions": ["ser"]
  },
  "application/java-vm": {
    "source": "apache",
    "compressible": false,
    "extensions": ["class"]
  },
  "application/javascript": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["js","mjs"]
  },
  "application/jf2feed+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jose": {
    "source": "iana"
  },
  "application/jose+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jrd+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jscalendar+json": {
    "source": "iana",
    "compressible": true
  },
  "application/json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["json","map"]
  },
  "application/json-patch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/json-seq": {
    "source": "iana"
  },
  "application/json5": {
    "extensions": ["json5"]
  },
  "application/jsonml+json": {
    "source": "apache",
    "compressible": true,
    "extensions": ["jsonml"]
  },
  "application/jwk+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jwk-set+json": {
    "source": "iana",
    "compressible": true
  },
  "application/jwt": {
    "source": "iana"
  },
  "application/kpml-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/kpml-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/ld+json": {
    "source": "iana",
    "compressible": true,
    "extensions": ["jsonld"]
  },
  "application/lgr+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lgr"]
  },
  "application/link-format": {
    "source": "iana"
  },
  "application/load-control+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/lost+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lostxml"]
  },
  "application/lostsync+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/lpf+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/lxf": {
    "source": "iana"
  },
  "application/mac-binhex40": {
    "source": "iana",
    "extensions": ["hqx"]
  },
  "application/mac-compactpro": {
    "source": "apache",
    "extensions": ["cpt"]
  },
  "application/macwriteii": {
    "source": "iana"
  },
  "application/mads+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mads"]
  },
  "application/manifest+json": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["webmanifest"]
  },
  "application/marc": {
    "source": "iana",
    "extensions": ["mrc"]
  },
  "application/marcxml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mrcx"]
  },
  "application/mathematica": {
    "source": "iana",
    "extensions": ["ma","nb","mb"]
  },
  "application/mathml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mathml"]
  },
  "application/mathml-content+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mathml-presentation+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-associated-procedure-description+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-deregister+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-envelope+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-msk+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-msk-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-protection-description+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-reception-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-register+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-register-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-schedule+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbms-user-service-description+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mbox": {
    "source": "iana",
    "extensions": ["mbox"]
  },
  "application/media-policy-dataset+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/media_control+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mediaservercontrol+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mscml"]
  },
  "application/merge-patch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/metalink+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["metalink"]
  },
  "application/metalink4+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["meta4"]
  },
  "application/mets+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mets"]
  },
  "application/mf4": {
    "source": "iana"
  },
  "application/mikey": {
    "source": "iana"
  },
  "application/mipc": {
    "source": "iana"
  },
  "application/missing-blocks+cbor-seq": {
    "source": "iana"
  },
  "application/mmt-aei+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["maei"]
  },
  "application/mmt-usd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["musd"]
  },
  "application/mods+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mods"]
  },
  "application/moss-keys": {
    "source": "iana"
  },
  "application/moss-signature": {
    "source": "iana"
  },
  "application/mosskey-data": {
    "source": "iana"
  },
  "application/mosskey-request": {
    "source": "iana"
  },
  "application/mp21": {
    "source": "iana",
    "extensions": ["m21","mp21"]
  },
  "application/mp4": {
    "source": "iana",
    "extensions": ["mp4s","m4p"]
  },
  "application/mpeg4-generic": {
    "source": "iana"
  },
  "application/mpeg4-iod": {
    "source": "iana"
  },
  "application/mpeg4-iod-xmt": {
    "source": "iana"
  },
  "application/mrb-consumer+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/mrb-publish+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/msc-ivr+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/msc-mixer+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/msword": {
    "source": "iana",
    "compressible": false,
    "extensions": ["doc","dot"]
  },
  "application/mud+json": {
    "source": "iana",
    "compressible": true
  },
  "application/multipart-core": {
    "source": "iana"
  },
  "application/mxf": {
    "source": "iana",
    "extensions": ["mxf"]
  },
  "application/n-quads": {
    "source": "iana",
    "extensions": ["nq"]
  },
  "application/n-triples": {
    "source": "iana",
    "extensions": ["nt"]
  },
  "application/nasdata": {
    "source": "iana"
  },
  "application/news-checkgroups": {
    "source": "iana",
    "charset": "US-ASCII"
  },
  "application/news-groupinfo": {
    "source": "iana",
    "charset": "US-ASCII"
  },
  "application/news-transmission": {
    "source": "iana"
  },
  "application/nlsml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/node": {
    "source": "iana",
    "extensions": ["cjs"]
  },
  "application/nss": {
    "source": "iana"
  },
  "application/oauth-authz-req+jwt": {
    "source": "iana"
  },
  "application/ocsp-request": {
    "source": "iana"
  },
  "application/ocsp-response": {
    "source": "iana"
  },
  "application/octet-stream": {
    "source": "iana",
    "compressible": false,
    "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
  },
  "application/oda": {
    "source": "iana",
    "extensions": ["oda"]
  },
  "application/odm+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/odx": {
    "source": "iana"
  },
  "application/oebps-package+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["opf"]
  },
  "application/ogg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ogx"]
  },
  "application/omdoc+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["omdoc"]
  },
  "application/onenote": {
    "source": "apache",
    "extensions": ["onetoc","onetoc2","onetmp","onepkg"]
  },
  "application/opc-nodeset+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/oscore": {
    "source": "iana"
  },
  "application/oxps": {
    "source": "iana",
    "extensions": ["oxps"]
  },
  "application/p21+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/p2p-overlay+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["relo"]
  },
  "application/parityfec": {
    "source": "iana"
  },
  "application/passport": {
    "source": "iana"
  },
  "application/patch-ops-error+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xer"]
  },
  "application/pdf": {
    "source": "iana",
    "compressible": false,
    "extensions": ["pdf"]
  },
  "application/pdx": {
    "source": "iana"
  },
  "application/pem-certificate-chain": {
    "source": "iana"
  },
  "application/pgp-encrypted": {
    "source": "iana",
    "compressible": false,
    "extensions": ["pgp"]
  },
  "application/pgp-keys": {
    "source": "iana"
  },
  "application/pgp-signature": {
    "source": "iana",
    "extensions": ["asc","sig"]
  },
  "application/pics-rules": {
    "source": "apache",
    "extensions": ["prf"]
  },
  "application/pidf+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/pidf-diff+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/pkcs10": {
    "source": "iana",
    "extensions": ["p10"]
  },
  "application/pkcs12": {
    "source": "iana"
  },
  "application/pkcs7-mime": {
    "source": "iana",
    "extensions": ["p7m","p7c"]
  },
  "application/pkcs7-signature": {
    "source": "iana",
    "extensions": ["p7s"]
  },
  "application/pkcs8": {
    "source": "iana",
    "extensions": ["p8"]
  },
  "application/pkcs8-encrypted": {
    "source": "iana"
  },
  "application/pkix-attr-cert": {
    "source": "iana",
    "extensions": ["ac"]
  },
  "application/pkix-cert": {
    "source": "iana",
    "extensions": ["cer"]
  },
  "application/pkix-crl": {
    "source": "iana",
    "extensions": ["crl"]
  },
  "application/pkix-pkipath": {
    "source": "iana",
    "extensions": ["pkipath"]
  },
  "application/pkixcmp": {
    "source": "iana",
    "extensions": ["pki"]
  },
  "application/pls+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["pls"]
  },
  "application/poc-settings+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/postscript": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ai","eps","ps"]
  },
  "application/ppsp-tracker+json": {
    "source": "iana",
    "compressible": true
  },
  "application/problem+json": {
    "source": "iana",
    "compressible": true
  },
  "application/problem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/provenance+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["provx"]
  },
  "application/prs.alvestrand.titrax-sheet": {
    "source": "iana"
  },
  "application/prs.cww": {
    "source": "iana",
    "extensions": ["cww"]
  },
  "application/prs.cyn": {
    "source": "iana",
    "charset": "7-BIT"
  },
  "application/prs.hpub+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/prs.nprend": {
    "source": "iana"
  },
  "application/prs.plucker": {
    "source": "iana"
  },
  "application/prs.rdf-xml-crypt": {
    "source": "iana"
  },
  "application/prs.xsf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/pskc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["pskcxml"]
  },
  "application/pvd+json": {
    "source": "iana",
    "compressible": true
  },
  "application/qsig": {
    "source": "iana"
  },
  "application/raml+yaml": {
    "compressible": true,
    "extensions": ["raml"]
  },
  "application/raptorfec": {
    "source": "iana"
  },
  "application/rdap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/rdf+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rdf","owl"]
  },
  "application/reginfo+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rif"]
  },
  "application/relax-ng-compact-syntax": {
    "source": "iana",
    "extensions": ["rnc"]
  },
  "application/remote-printing": {
    "source": "iana"
  },
  "application/reputon+json": {
    "source": "iana",
    "compressible": true
  },
  "application/resource-lists+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rl"]
  },
  "application/resource-lists-diff+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rld"]
  },
  "application/rfc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/riscos": {
    "source": "iana"
  },
  "application/rlmi+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/rls-services+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rs"]
  },
  "application/route-apd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rapd"]
  },
  "application/route-s-tsid+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sls"]
  },
  "application/route-usd+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rusd"]
  },
  "application/rpki-ghostbusters": {
    "source": "iana",
    "extensions": ["gbr"]
  },
  "application/rpki-manifest": {
    "source": "iana",
    "extensions": ["mft"]
  },
  "application/rpki-publication": {
    "source": "iana"
  },
  "application/rpki-roa": {
    "source": "iana",
    "extensions": ["roa"]
  },
  "application/rpki-updown": {
    "source": "iana"
  },
  "application/rsd+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["rsd"]
  },
  "application/rss+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["rss"]
  },
  "application/rtf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rtf"]
  },
  "application/rtploopback": {
    "source": "iana"
  },
  "application/rtx": {
    "source": "iana"
  },
  "application/samlassertion+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/samlmetadata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sarif+json": {
    "source": "iana",
    "compressible": true
  },
  "application/sarif-external-properties+json": {
    "source": "iana",
    "compressible": true
  },
  "application/sbe": {
    "source": "iana"
  },
  "application/sbml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sbml"]
  },
  "application/scaip+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/scim+json": {
    "source": "iana",
    "compressible": true
  },
  "application/scvp-cv-request": {
    "source": "iana",
    "extensions": ["scq"]
  },
  "application/scvp-cv-response": {
    "source": "iana",
    "extensions": ["scs"]
  },
  "application/scvp-vp-request": {
    "source": "iana",
    "extensions": ["spq"]
  },
  "application/scvp-vp-response": {
    "source": "iana",
    "extensions": ["spp"]
  },
  "application/sdp": {
    "source": "iana",
    "extensions": ["sdp"]
  },
  "application/secevent+jwt": {
    "source": "iana"
  },
  "application/senml+cbor": {
    "source": "iana"
  },
  "application/senml+json": {
    "source": "iana",
    "compressible": true
  },
  "application/senml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["senmlx"]
  },
  "application/senml-etch+cbor": {
    "source": "iana"
  },
  "application/senml-etch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/senml-exi": {
    "source": "iana"
  },
  "application/sensml+cbor": {
    "source": "iana"
  },
  "application/sensml+json": {
    "source": "iana",
    "compressible": true
  },
  "application/sensml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sensmlx"]
  },
  "application/sensml-exi": {
    "source": "iana"
  },
  "application/sep+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sep-exi": {
    "source": "iana"
  },
  "application/session-info": {
    "source": "iana"
  },
  "application/set-payment": {
    "source": "iana"
  },
  "application/set-payment-initiation": {
    "source": "iana",
    "extensions": ["setpay"]
  },
  "application/set-registration": {
    "source": "iana"
  },
  "application/set-registration-initiation": {
    "source": "iana",
    "extensions": ["setreg"]
  },
  "application/sgml": {
    "source": "iana"
  },
  "application/sgml-open-catalog": {
    "source": "iana"
  },
  "application/shf+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["shf"]
  },
  "application/sieve": {
    "source": "iana",
    "extensions": ["siv","sieve"]
  },
  "application/simple-filter+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/simple-message-summary": {
    "source": "iana"
  },
  "application/simplesymbolcontainer": {
    "source": "iana"
  },
  "application/sipc": {
    "source": "iana"
  },
  "application/slate": {
    "source": "iana"
  },
  "application/smil": {
    "source": "iana"
  },
  "application/smil+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["smi","smil"]
  },
  "application/smpte336m": {
    "source": "iana"
  },
  "application/soap+fastinfoset": {
    "source": "iana"
  },
  "application/soap+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sparql-query": {
    "source": "iana",
    "extensions": ["rq"]
  },
  "application/sparql-results+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["srx"]
  },
  "application/spirits-event+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/sql": {
    "source": "iana"
  },
  "application/srgs": {
    "source": "iana",
    "extensions": ["gram"]
  },
  "application/srgs+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["grxml"]
  },
  "application/sru+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sru"]
  },
  "application/ssdl+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["ssdl"]
  },
  "application/ssml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ssml"]
  },
  "application/stix+json": {
    "source": "iana",
    "compressible": true
  },
  "application/swid+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["swidtag"]
  },
  "application/tamp-apex-update": {
    "source": "iana"
  },
  "application/tamp-apex-update-confirm": {
    "source": "iana"
  },
  "application/tamp-community-update": {
    "source": "iana"
  },
  "application/tamp-community-update-confirm": {
    "source": "iana"
  },
  "application/tamp-error": {
    "source": "iana"
  },
  "application/tamp-sequence-adjust": {
    "source": "iana"
  },
  "application/tamp-sequence-adjust-confirm": {
    "source": "iana"
  },
  "application/tamp-status-query": {
    "source": "iana"
  },
  "application/tamp-status-response": {
    "source": "iana"
  },
  "application/tamp-update": {
    "source": "iana"
  },
  "application/tamp-update-confirm": {
    "source": "iana"
  },
  "application/tar": {
    "compressible": true
  },
  "application/taxii+json": {
    "source": "iana",
    "compressible": true
  },
  "application/td+json": {
    "source": "iana",
    "compressible": true
  },
  "application/tei+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["tei","teicorpus"]
  },
  "application/tetra_isi": {
    "source": "iana"
  },
  "application/thraud+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["tfi"]
  },
  "application/timestamp-query": {
    "source": "iana"
  },
  "application/timestamp-reply": {
    "source": "iana"
  },
  "application/timestamped-data": {
    "source": "iana",
    "extensions": ["tsd"]
  },
  "application/tlsrpt+gzip": {
    "source": "iana"
  },
  "application/tlsrpt+json": {
    "source": "iana",
    "compressible": true
  },
  "application/tnauthlist": {
    "source": "iana"
  },
  "application/toml": {
    "compressible": true,
    "extensions": ["toml"]
  },
  "application/trickle-ice-sdpfrag": {
    "source": "iana"
  },
  "application/trig": {
    "source": "iana",
    "extensions": ["trig"]
  },
  "application/ttml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ttml"]
  },
  "application/tve-trigger": {
    "source": "iana"
  },
  "application/tzif": {
    "source": "iana"
  },
  "application/tzif-leap": {
    "source": "iana"
  },
  "application/ubjson": {
    "compressible": false,
    "extensions": ["ubj"]
  },
  "application/ulpfec": {
    "source": "iana"
  },
  "application/urc-grpsheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/urc-ressheet+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rsheet"]
  },
  "application/urc-targetdesc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["td"]
  },
  "application/urc-uisocketdesc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vcard+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vcard+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vemmi": {
    "source": "iana"
  },
  "application/vividence.scriptfile": {
    "source": "apache"
  },
  "application/vnd.1000minds.decision-model+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["1km"]
  },
  "application/vnd.3gpp-prose+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp-prose-pc3ch+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp-v2x-local-service-information": {
    "source": "iana"
  },
  "application/vnd.3gpp.5gnas": {
    "source": "iana"
  },
  "application/vnd.3gpp.access-transfer-events+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.bsf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.gmop+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.gtpc": {
    "source": "iana"
  },
  "application/vnd.3gpp.interworking-data": {
    "source": "iana"
  },
  "application/vnd.3gpp.lpp": {
    "source": "iana"
  },
  "application/vnd.3gpp.mc-signalling-ear": {
    "source": "iana"
  },
  "application/vnd.3gpp.mcdata-affiliation-command+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-payload": {
    "source": "iana"
  },
  "application/vnd.3gpp.mcdata-service-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-signalling": {
    "source": "iana"
  },
  "application/vnd.3gpp.mcdata-ue-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcdata-user-profile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-affiliation-command+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-floor-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-location-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-service-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-signed+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-ue-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-ue-init-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcptt-user-profile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-location-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-service-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-transmission-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-ue-config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mcvideo-user-profile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.mid-call+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.ngap": {
    "source": "iana"
  },
  "application/vnd.3gpp.pfcp": {
    "source": "iana"
  },
  "application/vnd.3gpp.pic-bw-large": {
    "source": "iana",
    "extensions": ["plb"]
  },
  "application/vnd.3gpp.pic-bw-small": {
    "source": "iana",
    "extensions": ["psb"]
  },
  "application/vnd.3gpp.pic-bw-var": {
    "source": "iana",
    "extensions": ["pvb"]
  },
  "application/vnd.3gpp.s1ap": {
    "source": "iana"
  },
  "application/vnd.3gpp.sms": {
    "source": "iana"
  },
  "application/vnd.3gpp.sms+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.srvcc-ext+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.srvcc-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.state-and-event-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp.ussd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp2.bcmcsinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.3gpp2.sms": {
    "source": "iana"
  },
  "application/vnd.3gpp2.tcap": {
    "source": "iana",
    "extensions": ["tcap"]
  },
  "application/vnd.3lightssoftware.imagescal": {
    "source": "iana"
  },
  "application/vnd.3m.post-it-notes": {
    "source": "iana",
    "extensions": ["pwn"]
  },
  "application/vnd.accpac.simply.aso": {
    "source": "iana",
    "extensions": ["aso"]
  },
  "application/vnd.accpac.simply.imp": {
    "source": "iana",
    "extensions": ["imp"]
  },
  "application/vnd.acucobol": {
    "source": "iana",
    "extensions": ["acu"]
  },
  "application/vnd.acucorp": {
    "source": "iana",
    "extensions": ["atc","acutc"]
  },
  "application/vnd.adobe.air-application-installer-package+zip": {
    "source": "apache",
    "compressible": false,
    "extensions": ["air"]
  },
  "application/vnd.adobe.flash.movie": {
    "source": "iana"
  },
  "application/vnd.adobe.formscentral.fcdt": {
    "source": "iana",
    "extensions": ["fcdt"]
  },
  "application/vnd.adobe.fxp": {
    "source": "iana",
    "extensions": ["fxp","fxpl"]
  },
  "application/vnd.adobe.partial-upload": {
    "source": "iana"
  },
  "application/vnd.adobe.xdp+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xdp"]
  },
  "application/vnd.adobe.xfdf": {
    "source": "iana",
    "extensions": ["xfdf"]
  },
  "application/vnd.aether.imp": {
    "source": "iana"
  },
  "application/vnd.afpc.afplinedata": {
    "source": "iana"
  },
  "application/vnd.afpc.afplinedata-pagedef": {
    "source": "iana"
  },
  "application/vnd.afpc.cmoca-cmresource": {
    "source": "iana"
  },
  "application/vnd.afpc.foca-charset": {
    "source": "iana"
  },
  "application/vnd.afpc.foca-codedfont": {
    "source": "iana"
  },
  "application/vnd.afpc.foca-codepage": {
    "source": "iana"
  },
  "application/vnd.afpc.modca": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-cmtable": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-formdef": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-mediummap": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-objectcontainer": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-overlay": {
    "source": "iana"
  },
  "application/vnd.afpc.modca-pagesegment": {
    "source": "iana"
  },
  "application/vnd.ah-barcode": {
    "source": "iana"
  },
  "application/vnd.ahead.space": {
    "source": "iana",
    "extensions": ["ahead"]
  },
  "application/vnd.airzip.filesecure.azf": {
    "source": "iana",
    "extensions": ["azf"]
  },
  "application/vnd.airzip.filesecure.azs": {
    "source": "iana",
    "extensions": ["azs"]
  },
  "application/vnd.amadeus+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.amazon.ebook": {
    "source": "apache",
    "extensions": ["azw"]
  },
  "application/vnd.amazon.mobi8-ebook": {
    "source": "iana"
  },
  "application/vnd.americandynamics.acc": {
    "source": "iana",
    "extensions": ["acc"]
  },
  "application/vnd.amiga.ami": {
    "source": "iana",
    "extensions": ["ami"]
  },
  "application/vnd.amundsen.maze+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.android.ota": {
    "source": "iana"
  },
  "application/vnd.android.package-archive": {
    "source": "apache",
    "compressible": false,
    "extensions": ["apk"]
  },
  "application/vnd.anki": {
    "source": "iana"
  },
  "application/vnd.anser-web-certificate-issue-initiation": {
    "source": "iana",
    "extensions": ["cii"]
  },
  "application/vnd.anser-web-funds-transfer-initiation": {
    "source": "apache",
    "extensions": ["fti"]
  },
  "application/vnd.antix.game-component": {
    "source": "iana",
    "extensions": ["atx"]
  },
  "application/vnd.apache.arrow.file": {
    "source": "iana"
  },
  "application/vnd.apache.arrow.stream": {
    "source": "iana"
  },
  "application/vnd.apache.thrift.binary": {
    "source": "iana"
  },
  "application/vnd.apache.thrift.compact": {
    "source": "iana"
  },
  "application/vnd.apache.thrift.json": {
    "source": "iana"
  },
  "application/vnd.api+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.aplextor.warrp+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.apothekende.reservation+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.apple.installer+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mpkg"]
  },
  "application/vnd.apple.keynote": {
    "source": "iana",
    "extensions": ["key"]
  },
  "application/vnd.apple.mpegurl": {
    "source": "iana",
    "extensions": ["m3u8"]
  },
  "application/vnd.apple.numbers": {
    "source": "iana",
    "extensions": ["numbers"]
  },
  "application/vnd.apple.pages": {
    "source": "iana",
    "extensions": ["pages"]
  },
  "application/vnd.apple.pkpass": {
    "compressible": false,
    "extensions": ["pkpass"]
  },
  "application/vnd.arastra.swi": {
    "source": "iana"
  },
  "application/vnd.aristanetworks.swi": {
    "source": "iana",
    "extensions": ["swi"]
  },
  "application/vnd.artisan+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.artsquare": {
    "source": "iana"
  },
  "application/vnd.astraea-software.iota": {
    "source": "iana",
    "extensions": ["iota"]
  },
  "application/vnd.audiograph": {
    "source": "iana",
    "extensions": ["aep"]
  },
  "application/vnd.autopackage": {
    "source": "iana"
  },
  "application/vnd.avalon+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.avistar+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.balsamiq.bmml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["bmml"]
  },
  "application/vnd.balsamiq.bmpr": {
    "source": "iana"
  },
  "application/vnd.banana-accounting": {
    "source": "iana"
  },
  "application/vnd.bbf.usp.error": {
    "source": "iana"
  },
  "application/vnd.bbf.usp.msg": {
    "source": "iana"
  },
  "application/vnd.bbf.usp.msg+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.bekitzur-stech+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.bint.med-content": {
    "source": "iana"
  },
  "application/vnd.biopax.rdf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.blink-idb-value-wrapper": {
    "source": "iana"
  },
  "application/vnd.blueice.multipass": {
    "source": "iana",
    "extensions": ["mpm"]
  },
  "application/vnd.bluetooth.ep.oob": {
    "source": "iana"
  },
  "application/vnd.bluetooth.le.oob": {
    "source": "iana"
  },
  "application/vnd.bmi": {
    "source": "iana",
    "extensions": ["bmi"]
  },
  "application/vnd.bpf": {
    "source": "iana"
  },
  "application/vnd.bpf3": {
    "source": "iana"
  },
  "application/vnd.businessobjects": {
    "source": "iana",
    "extensions": ["rep"]
  },
  "application/vnd.byu.uapi+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cab-jscript": {
    "source": "iana"
  },
  "application/vnd.canon-cpdl": {
    "source": "iana"
  },
  "application/vnd.canon-lips": {
    "source": "iana"
  },
  "application/vnd.capasystems-pg+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cendio.thinlinc.clientconf": {
    "source": "iana"
  },
  "application/vnd.century-systems.tcp_stream": {
    "source": "iana"
  },
  "application/vnd.chemdraw+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["cdxml"]
  },
  "application/vnd.chess-pgn": {
    "source": "iana"
  },
  "application/vnd.chipnuts.karaoke-mmd": {
    "source": "iana",
    "extensions": ["mmd"]
  },
  "application/vnd.ciedi": {
    "source": "iana"
  },
  "application/vnd.cinderella": {
    "source": "iana",
    "extensions": ["cdy"]
  },
  "application/vnd.cirpack.isdn-ext": {
    "source": "iana"
  },
  "application/vnd.citationstyles.style+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["csl"]
  },
  "application/vnd.claymore": {
    "source": "iana",
    "extensions": ["cla"]
  },
  "application/vnd.cloanto.rp9": {
    "source": "iana",
    "extensions": ["rp9"]
  },
  "application/vnd.clonk.c4group": {
    "source": "iana",
    "extensions": ["c4g","c4d","c4f","c4p","c4u"]
  },
  "application/vnd.cluetrust.cartomobile-config": {
    "source": "iana",
    "extensions": ["c11amc"]
  },
  "application/vnd.cluetrust.cartomobile-config-pkg": {
    "source": "iana",
    "extensions": ["c11amz"]
  },
  "application/vnd.coffeescript": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.document": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.document-template": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.presentation": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.presentation-template": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.spreadsheet": {
    "source": "iana"
  },
  "application/vnd.collabio.xodocuments.spreadsheet-template": {
    "source": "iana"
  },
  "application/vnd.collection+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.collection.doc+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.collection.next+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.comicbook+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.comicbook-rar": {
    "source": "iana"
  },
  "application/vnd.commerce-battelle": {
    "source": "iana"
  },
  "application/vnd.commonspace": {
    "source": "iana",
    "extensions": ["csp"]
  },
  "application/vnd.contact.cmsg": {
    "source": "iana",
    "extensions": ["cdbcmsg"]
  },
  "application/vnd.coreos.ignition+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cosmocaller": {
    "source": "iana",
    "extensions": ["cmc"]
  },
  "application/vnd.crick.clicker": {
    "source": "iana",
    "extensions": ["clkx"]
  },
  "application/vnd.crick.clicker.keyboard": {
    "source": "iana",
    "extensions": ["clkk"]
  },
  "application/vnd.crick.clicker.palette": {
    "source": "iana",
    "extensions": ["clkp"]
  },
  "application/vnd.crick.clicker.template": {
    "source": "iana",
    "extensions": ["clkt"]
  },
  "application/vnd.crick.clicker.wordbank": {
    "source": "iana",
    "extensions": ["clkw"]
  },
  "application/vnd.criticaltools.wbs+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wbs"]
  },
  "application/vnd.cryptii.pipe+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.crypto-shade-file": {
    "source": "iana"
  },
  "application/vnd.cryptomator.encrypted": {
    "source": "iana"
  },
  "application/vnd.cryptomator.vault": {
    "source": "iana"
  },
  "application/vnd.ctc-posml": {
    "source": "iana",
    "extensions": ["pml"]
  },
  "application/vnd.ctct.ws+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cups-pdf": {
    "source": "iana"
  },
  "application/vnd.cups-postscript": {
    "source": "iana"
  },
  "application/vnd.cups-ppd": {
    "source": "iana",
    "extensions": ["ppd"]
  },
  "application/vnd.cups-raster": {
    "source": "iana"
  },
  "application/vnd.cups-raw": {
    "source": "iana"
  },
  "application/vnd.curl": {
    "source": "iana"
  },
  "application/vnd.curl.car": {
    "source": "apache",
    "extensions": ["car"]
  },
  "application/vnd.curl.pcurl": {
    "source": "apache",
    "extensions": ["pcurl"]
  },
  "application/vnd.cyan.dean.root+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cybank": {
    "source": "iana"
  },
  "application/vnd.cyclonedx+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.cyclonedx+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.d2l.coursepackage1p0+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.d3m-dataset": {
    "source": "iana"
  },
  "application/vnd.d3m-problem": {
    "source": "iana"
  },
  "application/vnd.dart": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dart"]
  },
  "application/vnd.data-vision.rdz": {
    "source": "iana",
    "extensions": ["rdz"]
  },
  "application/vnd.datapackage+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dataresource+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dbf": {
    "source": "iana",
    "extensions": ["dbf"]
  },
  "application/vnd.debian.binary-package": {
    "source": "iana"
  },
  "application/vnd.dece.data": {
    "source": "iana",
    "extensions": ["uvf","uvvf","uvd","uvvd"]
  },
  "application/vnd.dece.ttml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["uvt","uvvt"]
  },
  "application/vnd.dece.unspecified": {
    "source": "iana",
    "extensions": ["uvx","uvvx"]
  },
  "application/vnd.dece.zip": {
    "source": "iana",
    "extensions": ["uvz","uvvz"]
  },
  "application/vnd.denovo.fcselayout-link": {
    "source": "iana",
    "extensions": ["fe_launch"]
  },
  "application/vnd.desmume.movie": {
    "source": "iana"
  },
  "application/vnd.dir-bi.plate-dl-nosuffix": {
    "source": "iana"
  },
  "application/vnd.dm.delegation+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dna": {
    "source": "iana",
    "extensions": ["dna"]
  },
  "application/vnd.document+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dolby.mlp": {
    "source": "apache",
    "extensions": ["mlp"]
  },
  "application/vnd.dolby.mobile.1": {
    "source": "iana"
  },
  "application/vnd.dolby.mobile.2": {
    "source": "iana"
  },
  "application/vnd.doremir.scorecloud-binary-document": {
    "source": "iana"
  },
  "application/vnd.dpgraph": {
    "source": "iana",
    "extensions": ["dpg"]
  },
  "application/vnd.dreamfactory": {
    "source": "iana",
    "extensions": ["dfac"]
  },
  "application/vnd.drive+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ds-keypoint": {
    "source": "apache",
    "extensions": ["kpxx"]
  },
  "application/vnd.dtg.local": {
    "source": "iana"
  },
  "application/vnd.dtg.local.flash": {
    "source": "iana"
  },
  "application/vnd.dtg.local.html": {
    "source": "iana"
  },
  "application/vnd.dvb.ait": {
    "source": "iana",
    "extensions": ["ait"]
  },
  "application/vnd.dvb.dvbisl+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.dvbj": {
    "source": "iana"
  },
  "application/vnd.dvb.esgcontainer": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcdftnotifaccess": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcesgaccess": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcesgaccess2": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcesgpdd": {
    "source": "iana"
  },
  "application/vnd.dvb.ipdcroaming": {
    "source": "iana"
  },
  "application/vnd.dvb.iptv.alfec-base": {
    "source": "iana"
  },
  "application/vnd.dvb.iptv.alfec-enhancement": {
    "source": "iana"
  },
  "application/vnd.dvb.notif-aggregate-root+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-container+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-generic+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-ia-msglist+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-ia-registration-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-ia-registration-response+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.notif-init+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.dvb.pfr": {
    "source": "iana"
  },
  "application/vnd.dvb.service": {
    "source": "iana",
    "extensions": ["svc"]
  },
  "application/vnd.dxr": {
    "source": "iana"
  },
  "application/vnd.dynageo": {
    "source": "iana",
    "extensions": ["geo"]
  },
  "application/vnd.dzr": {
    "source": "iana"
  },
  "application/vnd.easykaraoke.cdgdownload": {
    "source": "iana"
  },
  "application/vnd.ecdis-update": {
    "source": "iana"
  },
  "application/vnd.ecip.rlp": {
    "source": "iana"
  },
  "application/vnd.ecowin.chart": {
    "source": "iana",
    "extensions": ["mag"]
  },
  "application/vnd.ecowin.filerequest": {
    "source": "iana"
  },
  "application/vnd.ecowin.fileupdate": {
    "source": "iana"
  },
  "application/vnd.ecowin.series": {
    "source": "iana"
  },
  "application/vnd.ecowin.seriesrequest": {
    "source": "iana"
  },
  "application/vnd.ecowin.seriesupdate": {
    "source": "iana"
  },
  "application/vnd.efi.img": {
    "source": "iana"
  },
  "application/vnd.efi.iso": {
    "source": "iana"
  },
  "application/vnd.emclient.accessrequest+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.enliven": {
    "source": "iana",
    "extensions": ["nml"]
  },
  "application/vnd.enphase.envoy": {
    "source": "iana"
  },
  "application/vnd.eprints.data+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.epson.esf": {
    "source": "iana",
    "extensions": ["esf"]
  },
  "application/vnd.epson.msf": {
    "source": "iana",
    "extensions": ["msf"]
  },
  "application/vnd.epson.quickanime": {
    "source": "iana",
    "extensions": ["qam"]
  },
  "application/vnd.epson.salt": {
    "source": "iana",
    "extensions": ["slt"]
  },
  "application/vnd.epson.ssf": {
    "source": "iana",
    "extensions": ["ssf"]
  },
  "application/vnd.ericsson.quickcall": {
    "source": "iana"
  },
  "application/vnd.espass-espass+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.eszigno3+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["es3","et3"]
  },
  "application/vnd.etsi.aoc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.asic-e+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.etsi.asic-s+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.etsi.cug+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvcommand+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvdiscovery+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsad-bc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsad-cod+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsad-npvr+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvservice+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvsync+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.iptvueprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.mcid+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.mheg5": {
    "source": "iana"
  },
  "application/vnd.etsi.overload-control-policy-dataset+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.pstn+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.sci+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.simservs+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.timestamp-token": {
    "source": "iana"
  },
  "application/vnd.etsi.tsl+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.etsi.tsl.der": {
    "source": "iana"
  },
  "application/vnd.eudora.data": {
    "source": "iana"
  },
  "application/vnd.evolv.ecig.profile": {
    "source": "iana"
  },
  "application/vnd.evolv.ecig.settings": {
    "source": "iana"
  },
  "application/vnd.evolv.ecig.theme": {
    "source": "iana"
  },
  "application/vnd.exstream-empower+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.exstream-package": {
    "source": "iana"
  },
  "application/vnd.ezpix-album": {
    "source": "iana",
    "extensions": ["ez2"]
  },
  "application/vnd.ezpix-package": {
    "source": "iana",
    "extensions": ["ez3"]
  },
  "application/vnd.f-secure.mobile": {
    "source": "iana"
  },
  "application/vnd.fastcopy-disk-image": {
    "source": "iana"
  },
  "application/vnd.fdf": {
    "source": "iana",
    "extensions": ["fdf"]
  },
  "application/vnd.fdsn.mseed": {
    "source": "iana",
    "extensions": ["mseed"]
  },
  "application/vnd.fdsn.seed": {
    "source": "iana",
    "extensions": ["seed","dataless"]
  },
  "application/vnd.ffsns": {
    "source": "iana"
  },
  "application/vnd.ficlab.flb+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.filmit.zfc": {
    "source": "iana"
  },
  "application/vnd.fints": {
    "source": "iana"
  },
  "application/vnd.firemonkeys.cloudcell": {
    "source": "iana"
  },
  "application/vnd.flographit": {
    "source": "iana",
    "extensions": ["gph"]
  },
  "application/vnd.fluxtime.clip": {
    "source": "iana",
    "extensions": ["ftc"]
  },
  "application/vnd.font-fontforge-sfd": {
    "source": "iana"
  },
  "application/vnd.framemaker": {
    "source": "iana",
    "extensions": ["fm","frame","maker","book"]
  },
  "application/vnd.frogans.fnc": {
    "source": "iana",
    "extensions": ["fnc"]
  },
  "application/vnd.frogans.ltf": {
    "source": "iana",
    "extensions": ["ltf"]
  },
  "application/vnd.fsc.weblaunch": {
    "source": "iana",
    "extensions": ["fsc"]
  },
  "application/vnd.fujifilm.fb.docuworks": {
    "source": "iana"
  },
  "application/vnd.fujifilm.fb.docuworks.binder": {
    "source": "iana"
  },
  "application/vnd.fujifilm.fb.docuworks.container": {
    "source": "iana"
  },
  "application/vnd.fujifilm.fb.jfi+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.fujitsu.oasys": {
    "source": "iana",
    "extensions": ["oas"]
  },
  "application/vnd.fujitsu.oasys2": {
    "source": "iana",
    "extensions": ["oa2"]
  },
  "application/vnd.fujitsu.oasys3": {
    "source": "iana",
    "extensions": ["oa3"]
  },
  "application/vnd.fujitsu.oasysgp": {
    "source": "iana",
    "extensions": ["fg5"]
  },
  "application/vnd.fujitsu.oasysprs": {
    "source": "iana",
    "extensions": ["bh2"]
  },
  "application/vnd.fujixerox.art-ex": {
    "source": "iana"
  },
  "application/vnd.fujixerox.art4": {
    "source": "iana"
  },
  "application/vnd.fujixerox.ddd": {
    "source": "iana",
    "extensions": ["ddd"]
  },
  "application/vnd.fujixerox.docuworks": {
    "source": "iana",
    "extensions": ["xdw"]
  },
  "application/vnd.fujixerox.docuworks.binder": {
    "source": "iana",
    "extensions": ["xbd"]
  },
  "application/vnd.fujixerox.docuworks.container": {
    "source": "iana"
  },
  "application/vnd.fujixerox.hbpl": {
    "source": "iana"
  },
  "application/vnd.fut-misnet": {
    "source": "iana"
  },
  "application/vnd.futoin+cbor": {
    "source": "iana"
  },
  "application/vnd.futoin+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.fuzzysheet": {
    "source": "iana",
    "extensions": ["fzs"]
  },
  "application/vnd.genomatix.tuxedo": {
    "source": "iana",
    "extensions": ["txd"]
  },
  "application/vnd.gentics.grd+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.geo+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.geocube+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.geogebra.file": {
    "source": "iana",
    "extensions": ["ggb"]
  },
  "application/vnd.geogebra.slides": {
    "source": "iana"
  },
  "application/vnd.geogebra.tool": {
    "source": "iana",
    "extensions": ["ggt"]
  },
  "application/vnd.geometry-explorer": {
    "source": "iana",
    "extensions": ["gex","gre"]
  },
  "application/vnd.geonext": {
    "source": "iana",
    "extensions": ["gxt"]
  },
  "application/vnd.geoplan": {
    "source": "iana",
    "extensions": ["g2w"]
  },
  "application/vnd.geospace": {
    "source": "iana",
    "extensions": ["g3w"]
  },
  "application/vnd.gerber": {
    "source": "iana"
  },
  "application/vnd.globalplatform.card-content-mgt": {
    "source": "iana"
  },
  "application/vnd.globalplatform.card-content-mgt-response": {
    "source": "iana"
  },
  "application/vnd.gmx": {
    "source": "iana",
    "extensions": ["gmx"]
  },
  "application/vnd.google-apps.document": {
    "compressible": false,
    "extensions": ["gdoc"]
  },
  "application/vnd.google-apps.presentation": {
    "compressible": false,
    "extensions": ["gslides"]
  },
  "application/vnd.google-apps.spreadsheet": {
    "compressible": false,
    "extensions": ["gsheet"]
  },
  "application/vnd.google-earth.kml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["kml"]
  },
  "application/vnd.google-earth.kmz": {
    "source": "iana",
    "compressible": false,
    "extensions": ["kmz"]
  },
  "application/vnd.gov.sk.e-form+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.gov.sk.e-form+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.gov.sk.xmldatacontainer+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.grafeq": {
    "source": "iana",
    "extensions": ["gqf","gqs"]
  },
  "application/vnd.gridmp": {
    "source": "iana"
  },
  "application/vnd.groove-account": {
    "source": "iana",
    "extensions": ["gac"]
  },
  "application/vnd.groove-help": {
    "source": "iana",
    "extensions": ["ghf"]
  },
  "application/vnd.groove-identity-message": {
    "source": "iana",
    "extensions": ["gim"]
  },
  "application/vnd.groove-injector": {
    "source": "iana",
    "extensions": ["grv"]
  },
  "application/vnd.groove-tool-message": {
    "source": "iana",
    "extensions": ["gtm"]
  },
  "application/vnd.groove-tool-template": {
    "source": "iana",
    "extensions": ["tpl"]
  },
  "application/vnd.groove-vcard": {
    "source": "iana",
    "extensions": ["vcg"]
  },
  "application/vnd.hal+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hal+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["hal"]
  },
  "application/vnd.handheld-entertainment+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["zmm"]
  },
  "application/vnd.hbci": {
    "source": "iana",
    "extensions": ["hbci"]
  },
  "application/vnd.hc+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hcl-bireports": {
    "source": "iana"
  },
  "application/vnd.hdt": {
    "source": "iana"
  },
  "application/vnd.heroku+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hhe.lesson-player": {
    "source": "iana",
    "extensions": ["les"]
  },
  "application/vnd.hp-hpgl": {
    "source": "iana",
    "extensions": ["hpgl"]
  },
  "application/vnd.hp-hpid": {
    "source": "iana",
    "extensions": ["hpid"]
  },
  "application/vnd.hp-hps": {
    "source": "iana",
    "extensions": ["hps"]
  },
  "application/vnd.hp-jlyt": {
    "source": "iana",
    "extensions": ["jlt"]
  },
  "application/vnd.hp-pcl": {
    "source": "iana",
    "extensions": ["pcl"]
  },
  "application/vnd.hp-pclxl": {
    "source": "iana",
    "extensions": ["pclxl"]
  },
  "application/vnd.httphone": {
    "source": "iana"
  },
  "application/vnd.hydrostatix.sof-data": {
    "source": "iana",
    "extensions": ["sfd-hdstx"]
  },
  "application/vnd.hyper+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hyper-item+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hyperdrive+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.hzn-3d-crossword": {
    "source": "iana"
  },
  "application/vnd.ibm.afplinedata": {
    "source": "iana"
  },
  "application/vnd.ibm.electronic-media": {
    "source": "iana"
  },
  "application/vnd.ibm.minipay": {
    "source": "iana",
    "extensions": ["mpy"]
  },
  "application/vnd.ibm.modcap": {
    "source": "iana",
    "extensions": ["afp","listafp","list3820"]
  },
  "application/vnd.ibm.rights-management": {
    "source": "iana",
    "extensions": ["irm"]
  },
  "application/vnd.ibm.secure-container": {
    "source": "iana",
    "extensions": ["sc"]
  },
  "application/vnd.iccprofile": {
    "source": "iana",
    "extensions": ["icc","icm"]
  },
  "application/vnd.ieee.1905": {
    "source": "iana"
  },
  "application/vnd.igloader": {
    "source": "iana",
    "extensions": ["igl"]
  },
  "application/vnd.imagemeter.folder+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.imagemeter.image+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.immervision-ivp": {
    "source": "iana",
    "extensions": ["ivp"]
  },
  "application/vnd.immervision-ivu": {
    "source": "iana",
    "extensions": ["ivu"]
  },
  "application/vnd.ims.imsccv1p1": {
    "source": "iana"
  },
  "application/vnd.ims.imsccv1p2": {
    "source": "iana"
  },
  "application/vnd.ims.imsccv1p3": {
    "source": "iana"
  },
  "application/vnd.ims.lis.v2.result+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolproxy+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolproxy.id+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolsettings+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ims.lti.v2.toolsettings.simple+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.informedcontrol.rms+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.informix-visionary": {
    "source": "iana"
  },
  "application/vnd.infotech.project": {
    "source": "iana"
  },
  "application/vnd.infotech.project+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.innopath.wamp.notification": {
    "source": "iana"
  },
  "application/vnd.insors.igm": {
    "source": "iana",
    "extensions": ["igm"]
  },
  "application/vnd.intercon.formnet": {
    "source": "iana",
    "extensions": ["xpw","xpx"]
  },
  "application/vnd.intergeo": {
    "source": "iana",
    "extensions": ["i2g"]
  },
  "application/vnd.intertrust.digibox": {
    "source": "iana"
  },
  "application/vnd.intertrust.nncp": {
    "source": "iana"
  },
  "application/vnd.intu.qbo": {
    "source": "iana",
    "extensions": ["qbo"]
  },
  "application/vnd.intu.qfx": {
    "source": "iana",
    "extensions": ["qfx"]
  },
  "application/vnd.iptc.g2.catalogitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.conceptitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.knowledgeitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.newsitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.newsmessage+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.packageitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.iptc.g2.planningitem+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ipunplugged.rcprofile": {
    "source": "iana",
    "extensions": ["rcprofile"]
  },
  "application/vnd.irepository.package+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["irp"]
  },
  "application/vnd.is-xpr": {
    "source": "iana",
    "extensions": ["xpr"]
  },
  "application/vnd.isac.fcs": {
    "source": "iana",
    "extensions": ["fcs"]
  },
  "application/vnd.iso11783-10+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.jam": {
    "source": "iana",
    "extensions": ["jam"]
  },
  "application/vnd.japannet-directory-service": {
    "source": "iana"
  },
  "application/vnd.japannet-jpnstore-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-payment-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-registration": {
    "source": "iana"
  },
  "application/vnd.japannet-registration-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-setstore-wakeup": {
    "source": "iana"
  },
  "application/vnd.japannet-verification": {
    "source": "iana"
  },
  "application/vnd.japannet-verification-wakeup": {
    "source": "iana"
  },
  "application/vnd.jcp.javame.midlet-rms": {
    "source": "iana",
    "extensions": ["rms"]
  },
  "application/vnd.jisp": {
    "source": "iana",
    "extensions": ["jisp"]
  },
  "application/vnd.joost.joda-archive": {
    "source": "iana",
    "extensions": ["joda"]
  },
  "application/vnd.jsk.isdn-ngn": {
    "source": "iana"
  },
  "application/vnd.kahootz": {
    "source": "iana",
    "extensions": ["ktz","ktr"]
  },
  "application/vnd.kde.karbon": {
    "source": "iana",
    "extensions": ["karbon"]
  },
  "application/vnd.kde.kchart": {
    "source": "iana",
    "extensions": ["chrt"]
  },
  "application/vnd.kde.kformula": {
    "source": "iana",
    "extensions": ["kfo"]
  },
  "application/vnd.kde.kivio": {
    "source": "iana",
    "extensions": ["flw"]
  },
  "application/vnd.kde.kontour": {
    "source": "iana",
    "extensions": ["kon"]
  },
  "application/vnd.kde.kpresenter": {
    "source": "iana",
    "extensions": ["kpr","kpt"]
  },
  "application/vnd.kde.kspread": {
    "source": "iana",
    "extensions": ["ksp"]
  },
  "application/vnd.kde.kword": {
    "source": "iana",
    "extensions": ["kwd","kwt"]
  },
  "application/vnd.kenameaapp": {
    "source": "iana",
    "extensions": ["htke"]
  },
  "application/vnd.kidspiration": {
    "source": "iana",
    "extensions": ["kia"]
  },
  "application/vnd.kinar": {
    "source": "iana",
    "extensions": ["kne","knp"]
  },
  "application/vnd.koan": {
    "source": "iana",
    "extensions": ["skp","skd","skt","skm"]
  },
  "application/vnd.kodak-descriptor": {
    "source": "iana",
    "extensions": ["sse"]
  },
  "application/vnd.las": {
    "source": "iana"
  },
  "application/vnd.las.las+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.las.las+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lasxml"]
  },
  "application/vnd.laszip": {
    "source": "iana"
  },
  "application/vnd.leap+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.liberty-request+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.llamagraphics.life-balance.desktop": {
    "source": "iana",
    "extensions": ["lbd"]
  },
  "application/vnd.llamagraphics.life-balance.exchange+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["lbe"]
  },
  "application/vnd.logipipe.circuit+zip": {
    "source": "iana",
    "compressible": false
  },
  "application/vnd.loom": {
    "source": "iana"
  },
  "application/vnd.lotus-1-2-3": {
    "source": "iana",
    "extensions": ["123"]
  },
  "application/vnd.lotus-approach": {
    "source": "iana",
    "extensions": ["apr"]
  },
  "application/vnd.lotus-freelance": {
    "source": "iana",
    "extensions": ["pre"]
  },
  "application/vnd.lotus-notes": {
    "source": "iana",
    "extensions": ["nsf"]
  },
  "application/vnd.lotus-organizer": {
    "source": "iana",
    "extensions": ["org"]
  },
  "application/vnd.lotus-screencam": {
    "source": "iana",
    "extensions": ["scm"]
  },
  "application/vnd.lotus-wordpro": {
    "source": "iana",
    "extensions": ["lwp"]
  },
  "application/vnd.macports.portpkg": {
    "source": "iana",
    "extensions": ["portpkg"]
  },
  "application/vnd.mapbox-vector-tile": {
    "source": "iana",
    "extensions": ["mvt"]
  },
  "application/vnd.marlin.drm.actiontoken+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.marlin.drm.conftoken+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.marlin.drm.license+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.marlin.drm.mdcf": {
    "source": "iana"
  },
  "application/vnd.mason+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.maxmind.maxmind-db": {
    "source": "iana"
  },
  "application/vnd.mcd": {
    "source": "iana",
    "extensions": ["mcd"]
  },
  "application/vnd.medcalcdata": {
    "source": "iana",
    "extensions": ["mc1"]
  },
  "application/vnd.mediastation.cdkey": {
    "source": "iana",
    "extensions": ["cdkey"]
  },
  "application/vnd.meridian-slingshot": {
    "source": "iana"
  },
  "application/vnd.mfer": {
    "source": "iana",
    "extensions": ["mwf"]
  },
  "application/vnd.mfmp": {
    "source": "iana",
    "extensions": ["mfm"]
  },
  "application/vnd.micro+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.micrografx.flo": {
    "source": "iana",
    "extensions": ["flo"]
  },
  "application/vnd.micrografx.igx": {
    "source": "iana",
    "extensions": ["igx"]
  },
  "application/vnd.microsoft.portable-executable": {
    "source": "iana"
  },
  "application/vnd.microsoft.windows.thumbnail-cache": {
    "source": "iana"
  },
  "application/vnd.miele+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.mif": {
    "source": "iana",
    "extensions": ["mif"]
  },
  "application/vnd.minisoft-hp3000-save": {
    "source": "iana"
  },
  "application/vnd.mitsubishi.misty-guard.trustweb": {
    "source": "iana"
  },
  "application/vnd.mobius.daf": {
    "source": "iana",
    "extensions": ["daf"]
  },
  "application/vnd.mobius.dis": {
    "source": "iana",
    "extensions": ["dis"]
  },
  "application/vnd.mobius.mbk": {
    "source": "iana",
    "extensions": ["mbk"]
  },
  "application/vnd.mobius.mqy": {
    "source": "iana",
    "extensions": ["mqy"]
  },
  "application/vnd.mobius.msl": {
    "source": "iana",
    "extensions": ["msl"]
  },
  "application/vnd.mobius.plc": {
    "source": "iana",
    "extensions": ["plc"]
  },
  "application/vnd.mobius.txf": {
    "source": "iana",
    "extensions": ["txf"]
  },
  "application/vnd.mophun.application": {
    "source": "iana",
    "extensions": ["mpn"]
  },
  "application/vnd.mophun.certificate": {
    "source": "iana",
    "extensions": ["mpc"]
  },
  "application/vnd.motorola.flexsuite": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.adsi": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.fis": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.gotap": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.kmr": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.ttc": {
    "source": "iana"
  },
  "application/vnd.motorola.flexsuite.wem": {
    "source": "iana"
  },
  "application/vnd.motorola.iprm": {
    "source": "iana"
  },
  "application/vnd.mozilla.xul+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xul"]
  },
  "application/vnd.ms-3mfdocument": {
    "source": "iana"
  },
  "application/vnd.ms-artgalry": {
    "source": "iana",
    "extensions": ["cil"]
  },
  "application/vnd.ms-asf": {
    "source": "iana"
  },
  "application/vnd.ms-cab-compressed": {
    "source": "iana",
    "extensions": ["cab"]
  },
  "application/vnd.ms-color.iccprofile": {
    "source": "apache"
  },
  "application/vnd.ms-excel": {
    "source": "iana",
    "compressible": false,
    "extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
  },
  "application/vnd.ms-excel.addin.macroenabled.12": {
    "source": "iana",
    "extensions": ["xlam"]
  },
  "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
    "source": "iana",
    "extensions": ["xlsb"]
  },
  "application/vnd.ms-excel.sheet.macroenabled.12": {
    "source": "iana",
    "extensions": ["xlsm"]
  },
  "application/vnd.ms-excel.template.macroenabled.12": {
    "source": "iana",
    "extensions": ["xltm"]
  },
  "application/vnd.ms-fontobject": {
    "source": "iana",
    "compressible": true,
    "extensions": ["eot"]
  },
  "application/vnd.ms-htmlhelp": {
    "source": "iana",
    "extensions": ["chm"]
  },
  "application/vnd.ms-ims": {
    "source": "iana",
    "extensions": ["ims"]
  },
  "application/vnd.ms-lrm": {
    "source": "iana",
    "extensions": ["lrm"]
  },
  "application/vnd.ms-office.activex+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-officetheme": {
    "source": "iana",
    "extensions": ["thmx"]
  },
  "application/vnd.ms-opentype": {
    "source": "apache",
    "compressible": true
  },
  "application/vnd.ms-outlook": {
    "compressible": false,
    "extensions": ["msg"]
  },
  "application/vnd.ms-package.obfuscated-opentype": {
    "source": "apache"
  },
  "application/vnd.ms-pki.seccat": {
    "source": "apache",
    "extensions": ["cat"]
  },
  "application/vnd.ms-pki.stl": {
    "source": "apache",
    "extensions": ["stl"]
  },
  "application/vnd.ms-playready.initiator+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-powerpoint": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ppt","pps","pot"]
  },
  "application/vnd.ms-powerpoint.addin.macroenabled.12": {
    "source": "iana",
    "extensions": ["ppam"]
  },
  "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
    "source": "iana",
    "extensions": ["pptm"]
  },
  "application/vnd.ms-powerpoint.slide.macroenabled.12": {
    "source": "iana",
    "extensions": ["sldm"]
  },
  "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
    "source": "iana",
    "extensions": ["ppsm"]
  },
  "application/vnd.ms-powerpoint.template.macroenabled.12": {
    "source": "iana",
    "extensions": ["potm"]
  },
  "application/vnd.ms-printdevicecapabilities+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-printing.printticket+xml": {
    "source": "apache",
    "compressible": true
  },
  "application/vnd.ms-printschematicket+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.ms-project": {
    "source": "iana",
    "extensions": ["mpp","mpt"]
  },
  "application/vnd.ms-tnef": {
    "source": "iana"
  },
  "application/vnd.ms-windows.devicepairing": {
    "source": "iana"
  },
  "application/vnd.ms-windows.nwprinting.oob": {
    "source": "iana"
  },
  "application/vnd.ms-windows.printerpairing": {
    "source": "iana"
  },
  "application/vnd.ms-windows.wsd.oob": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.lic-chlg-req": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.lic-resp": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.meter-chlg-req": {
    "source": "iana"
  },
  "application/vnd.ms-wmdrm.meter-resp": {
    "source": "iana"
  },
  "application/vnd.ms-word.document.macroenabled.12": {
    "source": "iana",
    "extensions": ["docm"]
  },
  "application/vnd.ms-word.template.macroenabled.12": {
    "source": "iana",
    "extensions": ["dotm"]
  },
  "application/vnd.ms-works": {
    "source": "iana",
    "extensions": ["wps","wks","wcm","wdb"]
  },
  "application/vnd.ms-wpl": {
    "source": "iana",
    "extensions": ["wpl"]
  },
  "application/vnd.ms-xpsdocument": {
    "source": "iana",
    "compressible": false,
    "extensions": ["xps"]
  },
  "application/vnd.msa-disk-image": {
    "source": "iana"
  },
  "application/vnd.mseq": {
    "source": "iana",
    "extensions": ["mseq"]
  },
  "application/vnd.msign": {
    "source": "iana"
  },
  "application/vnd.multiad.creator": {
    "source": "iana"
  },
  "application/vnd.multiad.creator.cif": {
    "source": "iana"
  },
  "application/vnd.music-niff": {
    "source": "iana"
  },
  "application/vnd.musician": {
    "source": "iana",
    "extensions": ["mus"]
  },
  "application/vnd.muvee.style": {
    "source": "iana",
    "extensions": ["msty"]
  },
  "application/vnd.mynfc": {
    "source": "iana",
    "extensions": ["taglet"]
  },
  "application/vnd.ncd.control": {
    "source": "iana"
  },
  "application/vnd.ncd.reference": {
    "source": "iana"
  },
  "application/vnd.nearst.inv+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nebumind.line": {
    "source": "iana"
  },
  "application/vnd.nervana": {
    "source": "iana"
  },
  "application/vnd.netfpx": {
    "source": "iana"
  },
  "application/vnd.neurolanguage.nlu": {
    "source": "iana",
    "extensions": ["nlu"]
  },
  "application/vnd.nimn": {
    "source": "iana"
  },
  "application/vnd.nintendo.nitro.rom": {
    "source": "iana"
  },
  "application/vnd.nintendo.snes.rom": {
    "source": "iana"
  },
  "application/vnd.nitf": {
    "source": "iana",
    "extensions": ["ntf","nitf"]
  },
  "application/vnd.noblenet-directory": {
    "source": "iana",
    "extensions": ["nnd"]
  },
  "application/vnd.noblenet-sealer": {
    "source": "iana",
    "extensions": ["nns"]
  },
  "application/vnd.noblenet-web": {
    "source": "iana",
    "extensions": ["nnw"]
  },
  "application/vnd.nokia.catalogs": {
    "source": "iana"
  },
  "application/vnd.nokia.conml+wbxml": {
    "source": "iana"
  },
  "application/vnd.nokia.conml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.iptv.config+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.isds-radio-presets": {
    "source": "iana"
  },
  "application/vnd.nokia.landmark+wbxml": {
    "source": "iana"
  },
  "application/vnd.nokia.landmark+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.landmarkcollection+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.n-gage.ac+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ac"]
  },
  "application/vnd.nokia.n-gage.data": {
    "source": "iana",
    "extensions": ["ngdat"]
  },
  "application/vnd.nokia.n-gage.symbian.install": {
    "source": "iana",
    "extensions": ["n-gage"]
  },
  "application/vnd.nokia.ncd": {
    "source": "iana"
  },
  "application/vnd.nokia.pcd+wbxml": {
    "source": "iana"
  },
  "application/vnd.nokia.pcd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.nokia.radio-preset": {
    "source": "iana",
    "extensions": ["rpst"]
  },
  "application/vnd.nokia.radio-presets": {
    "source": "iana",
    "extensions": ["rpss"]
  },
  "application/vnd.novadigm.edm": {
    "source": "iana",
    "extensions": ["edm"]
  },
  "application/vnd.novadigm.edx": {
    "source": "iana",
    "extensions": ["edx"]
  },
  "application/vnd.novadigm.ext": {
    "source": "iana",
    "extensions": ["ext"]
  },
  "application/vnd.ntt-local.content-share": {
    "source": "iana"
  },
  "application/vnd.ntt-local.file-transfer": {
    "source": "iana"
  },
  "application/vnd.ntt-local.ogw_remote-access": {
    "source": "iana"
  },
  "application/vnd.ntt-local.sip-ta_remote": {
    "source": "iana"
  },
  "application/vnd.ntt-local.sip-ta_tcp_stream": {
    "source": "iana"
  },
  "application/vnd.oasis.opendocument.chart": {
    "source": "iana",
    "extensions": ["odc"]
  },
  "application/vnd.oasis.opendocument.chart-template": {
    "source": "iana",
    "extensions": ["otc"]
  },
  "application/vnd.oasis.opendocument.database": {
    "source": "iana",
    "extensions": ["odb"]
  },
  "application/vnd.oasis.opendocument.formula": {
    "source": "iana",
    "extensions": ["odf"]
  },
  "application/vnd.oasis.opendocument.formula-template": {
    "source": "iana",
    "extensions": ["odft"]
  },
  "application/vnd.oasis.opendocument.graphics": {
    "source": "iana",
    "compressible": false,
    "extensions": ["odg"]
  },
  "application/vnd.oasis.opendocument.graphics-template": {
    "source": "iana",
    "extensions": ["otg"]
  },
  "application/vnd.oasis.opendocument.image": {
    "source": "iana",
    "extensions": ["odi"]
  },
  "application/vnd.oasis.opendocument.image-template": {
    "source": "iana",
    "extensions": ["oti"]
  },
  "application/vnd.oasis.opendocument.presentation": {
    "source": "iana",
    "compressible": false,
    "extensions": ["odp"]
  },
  "application/vnd.oasis.opendocument.presentation-template": {
    "source": "iana",
    "extensions": ["otp"]
  },
  "application/vnd.oasis.opendocument.spreadsheet": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ods"]
  },
  "application/vnd.oasis.opendocument.spreadsheet-template": {
    "source": "iana",
    "extensions": ["ots"]
  },
  "application/vnd.oasis.opendocument.text": {
    "source": "iana",
    "compressible": false,
    "extensions": ["odt"]
  },
  "application/vnd.oasis.opendocument.text-master": {
    "source": "iana",
    "extensions": ["odm"]
  },
  "application/vnd.oasis.opendocument.text-template": {
    "source": "iana",
    "extensions": ["ott"]
  },
  "application/vnd.oasis.opendocument.text-web": {
    "source": "iana",
    "extensions": ["oth"]
  },
  "application/vnd.obn": {
    "source": "iana"
  },
  "application/vnd.ocf+cbor": {
    "source": "iana"
  },
  "application/vnd.oci.image.manifest.v1+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oftn.l10n+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.contentaccessdownload+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.contentaccessstreaming+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.cspg-hexbinary": {
    "source": "iana"
  },
  "application/vnd.oipf.dae.svg+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.dae.xhtml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.mippvcontrolmessage+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.pae.gem": {
    "source": "iana"
  },
  "application/vnd.oipf.spdiscovery+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.spdlist+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.ueprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oipf.userprofile+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.olpc-sugar": {
    "source": "iana",
    "extensions": ["xo"]
  },
  "application/vnd.oma-scws-config": {
    "source": "iana"
  },
  "application/vnd.oma-scws-http-request": {
    "source": "iana"
  },
  "application/vnd.oma-scws-http-response": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.drm-trigger+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.imd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.ltkm": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.notification+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.provisioningtrigger": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.sgboot": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.sgdd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.sgdu": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.simple-symbol-container": {
    "source": "iana"
  },
  "application/vnd.oma.bcast.smartcard-trigger+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.sprov+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.bcast.stkm": {
    "source": "iana"
  },
  "application/vnd.oma.cab-address-book+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-feature-handler+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-pcc+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-subs-invite+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.cab-user-prefs+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.dcd": {
    "source": "iana"
  },
  "application/vnd.oma.dcdc": {
    "source": "iana"
  },
  "application/vnd.oma.dd2+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dd2"]
  },
  "application/vnd.oma.drm.risd+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.group-usage-list+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.lwm2m+cbor": {
    "source": "iana"
  },
  "application/vnd.oma.lwm2m+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.lwm2m+tlv": {
    "source": "iana"
  },
  "application/vnd.oma.pal+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.detailed-progress-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.final-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.groups+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.invocation-descriptor+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.poc.optimized-progress-report+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.push": {
    "source": "iana"
  },
  "application/vnd.oma.scidm.messages+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oma.xcap-directory+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.omads-email+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.omads-file+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.omads-folder+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.omaloc-supl-init": {
    "source": "iana"
  },
  "application/vnd.onepager": {
    "source": "iana"
  },
  "application/vnd.onepagertamp": {
    "source": "iana"
  },
  "application/vnd.onepagertamx": {
    "source": "iana"
  },
  "application/vnd.onepagertat": {
    "source": "iana"
  },
  "application/vnd.onepagertatp": {
    "source": "iana"
  },
  "application/vnd.onepagertatx": {
    "source": "iana"
  },
  "application/vnd.openblox.game+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["obgx"]
  },
  "application/vnd.openblox.game-binary": {
    "source": "iana"
  },
  "application/vnd.openeye.oeb": {
    "source": "iana"
  },
  "application/vnd.openofficeorg.extension": {
    "source": "apache",
    "extensions": ["oxt"]
  },
  "application/vnd.openstreetmap.data+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["osm"]
  },
  "application/vnd.opentimestamps.ots": {
    "source": "iana"
  },
  "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawing+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
    "source": "iana",
    "compressible": false,
    "extensions": ["pptx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slide": {
    "source": "iana",
    "extensions": ["sldx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
    "source": "iana",
    "extensions": ["ppsx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.template": {
    "source": "iana",
    "extensions": ["potx"]
  },
  "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
    "source": "iana",
    "compressible": false,
    "extensions": ["xlsx"]
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
    "source": "iana",
    "extensions": ["xltx"]
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.theme+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.vmldrawing": {
    "source": "iana"
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
    "source": "iana",
    "compressible": false,
    "extensions": ["docx"]
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
    "source": "iana",
    "extensions": ["dotx"]
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-package.core-properties+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.openxmlformats-package.relationships+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oracle.resource+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.orange.indata": {
    "source": "iana"
  },
  "application/vnd.osa.netdeploy": {
    "source": "iana"
  },
  "application/vnd.osgeo.mapguide.package": {
    "source": "iana",
    "extensions": ["mgp"]
  },
  "application/vnd.osgi.bundle": {
    "source": "iana"
  },
  "application/vnd.osgi.dp": {
    "source": "iana",
    "extensions": ["dp"]
  },
  "application/vnd.osgi.subsystem": {
    "source": "iana",
    "extensions": ["esa"]
  },
  "application/vnd.otps.ct-kip+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.oxli.countgraph": {
    "source": "iana"
  },
  "application/vnd.pagerduty+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.palm": {
    "source": "iana",
    "extensions": ["pdb","pqa","oprc"]
  },
  "application/vnd.panoply": {
    "source": "iana"
  },
  "application/vnd.paos.xml": {
    "source": "iana"
  },
  "application/vnd.patentdive": {
    "source": "iana"
  },
  "application/vnd.patientecommsdoc": {
    "source": "iana"
  },
  "application/vnd.pawaafile": {
    "source": "iana",
    "extensions": ["paw"]
  },
  "application/vnd.pcos": {
    "source": "iana"
  },
  "application/vnd.pg.format": {
    "source": "iana",
    "extensions": ["str"]
  },
  "application/vnd.pg.osasli": {
    "source": "iana",
    "extensions": ["ei6"]
  },
  "application/vnd.piaccess.application-licence": {
    "source": "iana"
  },
  "application/vnd.picsel": {
    "source": "iana",
    "extensions": ["efif"]
  },
  "application/vnd.pmi.widget": {
    "source": "iana",
    "extensions": ["wg"]
  },
  "application/vnd.poc.group-advertisement+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.pocketlearn": {
    "source": "iana",
    "extensions": ["plf"]
  },
  "application/vnd.powerbuilder6": {
    "source": "iana",
    "extensions": ["pbd"]
  },
  "application/vnd.powerbuilder6-s": {
    "source": "iana"
  },
  "application/vnd.powerbuilder7": {
    "source": "iana"
  },
  "application/vnd.powerbuilder7-s": {
    "source": "iana"
  },
  "application/vnd.powerbuilder75": {
    "source": "iana"
  },
  "application/vnd.powerbuilder75-s": {
    "source": "iana"
  },
  "application/vnd.preminet": {
    "source": "iana"
  },
  "application/vnd.previewsystems.box": {
    "source": "iana",
    "extensions": ["box"]
  },
  "application/vnd.proteus.magazine": {
    "source": "iana",
    "extensions": ["mgz"]
  },
  "application/vnd.psfs": {
    "source": "iana"
  },
  "application/vnd.publishare-delta-tree": {
    "source": "iana",
    "extensions": ["qps"]
  },
  "application/vnd.pvi.ptid1": {
    "source": "iana",
    "extensions": ["ptid"]
  },
  "application/vnd.pwg-multiplexed": {
    "source": "iana"
  },
  "application/vnd.pwg-xhtml-print+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.qualcomm.brew-app-res": {
    "source": "iana"
  },
  "application/vnd.quarantainenet": {
    "source": "iana"
  },
  "application/vnd.quark.quarkxpress": {
    "source": "iana",
    "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
  },
  "application/vnd.quobject-quoxdocument": {
    "source": "iana"
  },
  "application/vnd.radisys.moml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-conf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-conn+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-dialog+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-audit-stream+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-conf+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-base+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-fax-detect+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-group+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-speech+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.radisys.msml-dialog-transform+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.rainstor.data": {
    "source": "iana"
  },
  "application/vnd.rapid": {
    "source": "iana"
  },
  "application/vnd.rar": {
    "source": "iana",
    "extensions": ["rar"]
  },
  "application/vnd.realvnc.bed": {
    "source": "iana",
    "extensions": ["bed"]
  },
  "application/vnd.recordare.musicxml": {
    "source": "iana",
    "extensions": ["mxl"]
  },
  "application/vnd.recordare.musicxml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["musicxml"]
  },
  "application/vnd.renlearn.rlprint": {
    "source": "iana"
  },
  "application/vnd.resilient.logic": {
    "source": "iana"
  },
  "application/vnd.restful+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.rig.cryptonote": {
    "source": "iana",
    "extensions": ["cryptonote"]
  },
  "application/vnd.rim.cod": {
    "source": "apache",
    "extensions": ["cod"]
  },
  "application/vnd.rn-realmedia": {
    "source": "apache",
    "extensions": ["rm"]
  },
  "application/vnd.rn-realmedia-vbr": {
    "source": "apache",
    "extensions": ["rmvb"]
  },
  "application/vnd.route66.link66+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["link66"]
  },
  "application/vnd.rs-274x": {
    "source": "iana"
  },
  "application/vnd.ruckus.download": {
    "source": "iana"
  },
  "application/vnd.s3sms": {
    "source": "iana"
  },
  "application/vnd.sailingtracker.track": {
    "source": "iana",
    "extensions": ["st"]
  },
  "application/vnd.sar": {
    "source": "iana"
  },
  "application/vnd.sbm.cid": {
    "source": "iana"
  },
  "application/vnd.sbm.mid2": {
    "source": "iana"
  },
  "application/vnd.scribus": {
    "source": "iana"
  },
  "application/vnd.sealed.3df": {
    "source": "iana"
  },
  "application/vnd.sealed.csf": {
    "source": "iana"
  },
  "application/vnd.sealed.doc": {
    "source": "iana"
  },
  "application/vnd.sealed.eml": {
    "source": "iana"
  },
  "application/vnd.sealed.mht": {
    "source": "iana"
  },
  "application/vnd.sealed.net": {
    "source": "iana"
  },
  "application/vnd.sealed.ppt": {
    "source": "iana"
  },
  "application/vnd.sealed.tiff": {
    "source": "iana"
  },
  "application/vnd.sealed.xls": {
    "source": "iana"
  },
  "application/vnd.sealedmedia.softseal.html": {
    "source": "iana"
  },
  "application/vnd.sealedmedia.softseal.pdf": {
    "source": "iana"
  },
  "application/vnd.seemail": {
    "source": "iana",
    "extensions": ["see"]
  },
  "application/vnd.seis+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.sema": {
    "source": "iana",
    "extensions": ["sema"]
  },
  "application/vnd.semd": {
    "source": "iana",
    "extensions": ["semd"]
  },
  "application/vnd.semf": {
    "source": "iana",
    "extensions": ["semf"]
  },
  "application/vnd.shade-save-file": {
    "source": "iana"
  },
  "application/vnd.shana.informed.formdata": {
    "source": "iana",
    "extensions": ["ifm"]
  },
  "application/vnd.shana.informed.formtemplate": {
    "source": "iana",
    "extensions": ["itp"]
  },
  "application/vnd.shana.informed.interchange": {
    "source": "iana",
    "extensions": ["iif"]
  },
  "application/vnd.shana.informed.package": {
    "source": "iana",
    "extensions": ["ipk"]
  },
  "application/vnd.shootproof+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.shopkick+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.shp": {
    "source": "iana"
  },
  "application/vnd.shx": {
    "source": "iana"
  },
  "application/vnd.sigrok.session": {
    "source": "iana"
  },
  "application/vnd.simtech-mindmapper": {
    "source": "iana",
    "extensions": ["twd","twds"]
  },
  "application/vnd.siren+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.smaf": {
    "source": "iana",
    "extensions": ["mmf"]
  },
  "application/vnd.smart.notebook": {
    "source": "iana"
  },
  "application/vnd.smart.teacher": {
    "source": "iana",
    "extensions": ["teacher"]
  },
  "application/vnd.snesdev-page-table": {
    "source": "iana"
  },
  "application/vnd.software602.filler.form+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["fo"]
  },
  "application/vnd.software602.filler.form-xml-zip": {
    "source": "iana"
  },
  "application/vnd.solent.sdkm+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["sdkm","sdkd"]
  },
  "application/vnd.spotfire.dxp": {
    "source": "iana",
    "extensions": ["dxp"]
  },
  "application/vnd.spotfire.sfs": {
    "source": "iana",
    "extensions": ["sfs"]
  },
  "application/vnd.sqlite3": {
    "source": "iana"
  },
  "application/vnd.sss-cod": {
    "source": "iana"
  },
  "application/vnd.sss-dtf": {
    "source": "iana"
  },
  "application/vnd.sss-ntf": {
    "source": "iana"
  },
  "application/vnd.stardivision.calc": {
    "source": "apache",
    "extensions": ["sdc"]
  },
  "application/vnd.stardivision.draw": {
    "source": "apache",
    "extensions": ["sda"]
  },
  "application/vnd.stardivision.impress": {
    "source": "apache",
    "extensions": ["sdd"]
  },
  "application/vnd.stardivision.math": {
    "source": "apache",
    "extensions": ["smf"]
  },
  "application/vnd.stardivision.writer": {
    "source": "apache",
    "extensions": ["sdw","vor"]
  },
  "application/vnd.stardivision.writer-global": {
    "source": "apache",
    "extensions": ["sgl"]
  },
  "application/vnd.stepmania.package": {
    "source": "iana",
    "extensions": ["smzip"]
  },
  "application/vnd.stepmania.stepchart": {
    "source": "iana",
    "extensions": ["sm"]
  },
  "application/vnd.street-stream": {
    "source": "iana"
  },
  "application/vnd.sun.wadl+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wadl"]
  },
  "application/vnd.sun.xml.calc": {
    "source": "apache",
    "extensions": ["sxc"]
  },
  "application/vnd.sun.xml.calc.template": {
    "source": "apache",
    "extensions": ["stc"]
  },
  "application/vnd.sun.xml.draw": {
    "source": "apache",
    "extensions": ["sxd"]
  },
  "application/vnd.sun.xml.draw.template": {
    "source": "apache",
    "extensions": ["std"]
  },
  "application/vnd.sun.xml.impress": {
    "source": "apache",
    "extensions": ["sxi"]
  },
  "application/vnd.sun.xml.impress.template": {
    "source": "apache",
    "extensions": ["sti"]
  },
  "application/vnd.sun.xml.math": {
    "source": "apache",
    "extensions": ["sxm"]
  },
  "application/vnd.sun.xml.writer": {
    "source": "apache",
    "extensions": ["sxw"]
  },
  "application/vnd.sun.xml.writer.global": {
    "source": "apache",
    "extensions": ["sxg"]
  },
  "application/vnd.sun.xml.writer.template": {
    "source": "apache",
    "extensions": ["stw"]
  },
  "application/vnd.sus-calendar": {
    "source": "iana",
    "extensions": ["sus","susp"]
  },
  "application/vnd.svd": {
    "source": "iana",
    "extensions": ["svd"]
  },
  "application/vnd.swiftview-ics": {
    "source": "iana"
  },
  "application/vnd.sycle+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.symbian.install": {
    "source": "apache",
    "extensions": ["sis","sisx"]
  },
  "application/vnd.syncml+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["xsm"]
  },
  "application/vnd.syncml.dm+wbxml": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["bdm"]
  },
  "application/vnd.syncml.dm+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["xdm"]
  },
  "application/vnd.syncml.dm.notification": {
    "source": "iana"
  },
  "application/vnd.syncml.dmddf+wbxml": {
    "source": "iana"
  },
  "application/vnd.syncml.dmddf+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["ddf"]
  },
  "application/vnd.syncml.dmtnds+wbxml": {
    "source": "iana"
  },
  "application/vnd.syncml.dmtnds+xml": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true
  },
  "application/vnd.syncml.ds.notification": {
    "source": "iana"
  },
  "application/vnd.tableschema+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.tao.intent-module-archive": {
    "source": "iana",
    "extensions": ["tao"]
  },
  "application/vnd.tcpdump.pcap": {
    "source": "iana",
    "extensions": ["pcap","cap","dmp"]
  },
  "application/vnd.think-cell.ppttc+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.tmd.mediaflex.api+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.tml": {
    "source": "iana"
  },
  "application/vnd.tmobile-livetv": {
    "source": "iana",
    "extensions": ["tmo"]
  },
  "application/vnd.tri.onesource": {
    "source": "iana"
  },
  "application/vnd.trid.tpt": {
    "source": "iana",
    "extensions": ["tpt"]
  },
  "application/vnd.triscape.mxs": {
    "source": "iana",
    "extensions": ["mxs"]
  },
  "application/vnd.trueapp": {
    "source": "iana",
    "extensions": ["tra"]
  },
  "application/vnd.truedoc": {
    "source": "iana"
  },
  "application/vnd.ubisoft.webplayer": {
    "source": "iana"
  },
  "application/vnd.ufdl": {
    "source": "iana",
    "extensions": ["ufd","ufdl"]
  },
  "application/vnd.uiq.theme": {
    "source": "iana",
    "extensions": ["utz"]
  },
  "application/vnd.umajin": {
    "source": "iana",
    "extensions": ["umj"]
  },
  "application/vnd.unity": {
    "source": "iana",
    "extensions": ["unityweb"]
  },
  "application/vnd.uoml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["uoml"]
  },
  "application/vnd.uplanet.alert": {
    "source": "iana"
  },
  "application/vnd.uplanet.alert-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.bearer-choice": {
    "source": "iana"
  },
  "application/vnd.uplanet.bearer-choice-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.cacheop": {
    "source": "iana"
  },
  "application/vnd.uplanet.cacheop-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.channel": {
    "source": "iana"
  },
  "application/vnd.uplanet.channel-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.list": {
    "source": "iana"
  },
  "application/vnd.uplanet.list-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.listcmd": {
    "source": "iana"
  },
  "application/vnd.uplanet.listcmd-wbxml": {
    "source": "iana"
  },
  "application/vnd.uplanet.signal": {
    "source": "iana"
  },
  "application/vnd.uri-map": {
    "source": "iana"
  },
  "application/vnd.valve.source.material": {
    "source": "iana"
  },
  "application/vnd.vcx": {
    "source": "iana",
    "extensions": ["vcx"]
  },
  "application/vnd.vd-study": {
    "source": "iana"
  },
  "application/vnd.vectorworks": {
    "source": "iana"
  },
  "application/vnd.vel+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.verimatrix.vcas": {
    "source": "iana"
  },
  "application/vnd.veritone.aion+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.veryant.thin": {
    "source": "iana"
  },
  "application/vnd.ves.encrypted": {
    "source": "iana"
  },
  "application/vnd.vidsoft.vidconference": {
    "source": "iana"
  },
  "application/vnd.visio": {
    "source": "iana",
    "extensions": ["vsd","vst","vss","vsw"]
  },
  "application/vnd.visionary": {
    "source": "iana",
    "extensions": ["vis"]
  },
  "application/vnd.vividence.scriptfile": {
    "source": "iana"
  },
  "application/vnd.vsf": {
    "source": "iana",
    "extensions": ["vsf"]
  },
  "application/vnd.wap.sic": {
    "source": "iana"
  },
  "application/vnd.wap.slc": {
    "source": "iana"
  },
  "application/vnd.wap.wbxml": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["wbxml"]
  },
  "application/vnd.wap.wmlc": {
    "source": "iana",
    "extensions": ["wmlc"]
  },
  "application/vnd.wap.wmlscriptc": {
    "source": "iana",
    "extensions": ["wmlsc"]
  },
  "application/vnd.webturbo": {
    "source": "iana",
    "extensions": ["wtb"]
  },
  "application/vnd.wfa.dpp": {
    "source": "iana"
  },
  "application/vnd.wfa.p2p": {
    "source": "iana"
  },
  "application/vnd.wfa.wsc": {
    "source": "iana"
  },
  "application/vnd.windows.devicepairing": {
    "source": "iana"
  },
  "application/vnd.wmc": {
    "source": "iana"
  },
  "application/vnd.wmf.bootstrap": {
    "source": "iana"
  },
  "application/vnd.wolfram.mathematica": {
    "source": "iana"
  },
  "application/vnd.wolfram.mathematica.package": {
    "source": "iana"
  },
  "application/vnd.wolfram.player": {
    "source": "iana",
    "extensions": ["nbp"]
  },
  "application/vnd.wordperfect": {
    "source": "iana",
    "extensions": ["wpd"]
  },
  "application/vnd.wqd": {
    "source": "iana",
    "extensions": ["wqd"]
  },
  "application/vnd.wrq-hp3000-labelled": {
    "source": "iana"
  },
  "application/vnd.wt.stf": {
    "source": "iana",
    "extensions": ["stf"]
  },
  "application/vnd.wv.csp+wbxml": {
    "source": "iana"
  },
  "application/vnd.wv.csp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.wv.ssp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.xacml+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.xara": {
    "source": "iana",
    "extensions": ["xar"]
  },
  "application/vnd.xfdl": {
    "source": "iana",
    "extensions": ["xfdl"]
  },
  "application/vnd.xfdl.webform": {
    "source": "iana"
  },
  "application/vnd.xmi+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/vnd.xmpie.cpkg": {
    "source": "iana"
  },
  "application/vnd.xmpie.dpkg": {
    "source": "iana"
  },
  "application/vnd.xmpie.plan": {
    "source": "iana"
  },
  "application/vnd.xmpie.ppkg": {
    "source": "iana"
  },
  "application/vnd.xmpie.xlim": {
    "source": "iana"
  },
  "application/vnd.yamaha.hv-dic": {
    "source": "iana",
    "extensions": ["hvd"]
  },
  "application/vnd.yamaha.hv-script": {
    "source": "iana",
    "extensions": ["hvs"]
  },
  "application/vnd.yamaha.hv-voice": {
    "source": "iana",
    "extensions": ["hvp"]
  },
  "application/vnd.yamaha.openscoreformat": {
    "source": "iana",
    "extensions": ["osf"]
  },
  "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["osfpvg"]
  },
  "application/vnd.yamaha.remote-setup": {
    "source": "iana"
  },
  "application/vnd.yamaha.smaf-audio": {
    "source": "iana",
    "extensions": ["saf"]
  },
  "application/vnd.yamaha.smaf-phrase": {
    "source": "iana",
    "extensions": ["spf"]
  },
  "application/vnd.yamaha.through-ngn": {
    "source": "iana"
  },
  "application/vnd.yamaha.tunnel-udpencap": {
    "source": "iana"
  },
  "application/vnd.yaoweme": {
    "source": "iana"
  },
  "application/vnd.yellowriver-custom-menu": {
    "source": "iana",
    "extensions": ["cmp"]
  },
  "application/vnd.youtube.yt": {
    "source": "iana"
  },
  "application/vnd.zul": {
    "source": "iana",
    "extensions": ["zir","zirz"]
  },
  "application/vnd.zzazz.deck+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["zaz"]
  },
  "application/voicexml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["vxml"]
  },
  "application/voucher-cms+json": {
    "source": "iana",
    "compressible": true
  },
  "application/vq-rtcpxr": {
    "source": "iana"
  },
  "application/wasm": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wasm"]
  },
  "application/watcherinfo+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/webpush-options+json": {
    "source": "iana",
    "compressible": true
  },
  "application/whoispp-query": {
    "source": "iana"
  },
  "application/whoispp-response": {
    "source": "iana"
  },
  "application/widget": {
    "source": "iana",
    "extensions": ["wgt"]
  },
  "application/winhlp": {
    "source": "apache",
    "extensions": ["hlp"]
  },
  "application/wita": {
    "source": "iana"
  },
  "application/wordperfect5.1": {
    "source": "iana"
  },
  "application/wsdl+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wsdl"]
  },
  "application/wspolicy+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["wspolicy"]
  },
  "application/x-7z-compressed": {
    "source": "apache",
    "compressible": false,
    "extensions": ["7z"]
  },
  "application/x-abiword": {
    "source": "apache",
    "extensions": ["abw"]
  },
  "application/x-ace-compressed": {
    "source": "apache",
    "extensions": ["ace"]
  },
  "application/x-amf": {
    "source": "apache"
  },
  "application/x-apple-diskimage": {
    "source": "apache",
    "extensions": ["dmg"]
  },
  "application/x-arj": {
    "compressible": false,
    "extensions": ["arj"]
  },
  "application/x-authorware-bin": {
    "source": "apache",
    "extensions": ["aab","x32","u32","vox"]
  },
  "application/x-authorware-map": {
    "source": "apache",
    "extensions": ["aam"]
  },
  "application/x-authorware-seg": {
    "source": "apache",
    "extensions": ["aas"]
  },
  "application/x-bcpio": {
    "source": "apache",
    "extensions": ["bcpio"]
  },
  "application/x-bdoc": {
    "compressible": false,
    "extensions": ["bdoc"]
  },
  "application/x-bittorrent": {
    "source": "apache",
    "extensions": ["torrent"]
  },
  "application/x-blorb": {
    "source": "apache",
    "extensions": ["blb","blorb"]
  },
  "application/x-bzip": {
    "source": "apache",
    "compressible": false,
    "extensions": ["bz"]
  },
  "application/x-bzip2": {
    "source": "apache",
    "compressible": false,
    "extensions": ["bz2","boz"]
  },
  "application/x-cbr": {
    "source": "apache",
    "extensions": ["cbr","cba","cbt","cbz","cb7"]
  },
  "application/x-cdlink": {
    "source": "apache",
    "extensions": ["vcd"]
  },
  "application/x-cfs-compressed": {
    "source": "apache",
    "extensions": ["cfs"]
  },
  "application/x-chat": {
    "source": "apache",
    "extensions": ["chat"]
  },
  "application/x-chess-pgn": {
    "source": "apache",
    "extensions": ["pgn"]
  },
  "application/x-chrome-extension": {
    "extensions": ["crx"]
  },
  "application/x-cocoa": {
    "source": "nginx",
    "extensions": ["cco"]
  },
  "application/x-compress": {
    "source": "apache"
  },
  "application/x-conference": {
    "source": "apache",
    "extensions": ["nsc"]
  },
  "application/x-cpio": {
    "source": "apache",
    "extensions": ["cpio"]
  },
  "application/x-csh": {
    "source": "apache",
    "extensions": ["csh"]
  },
  "application/x-deb": {
    "compressible": false
  },
  "application/x-debian-package": {
    "source": "apache",
    "extensions": ["deb","udeb"]
  },
  "application/x-dgc-compressed": {
    "source": "apache",
    "extensions": ["dgc"]
  },
  "application/x-director": {
    "source": "apache",
    "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
  },
  "application/x-doom": {
    "source": "apache",
    "extensions": ["wad"]
  },
  "application/x-dtbncx+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["ncx"]
  },
  "application/x-dtbook+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["dtb"]
  },
  "application/x-dtbresource+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["res"]
  },
  "application/x-dvi": {
    "source": "apache",
    "compressible": false,
    "extensions": ["dvi"]
  },
  "application/x-envoy": {
    "source": "apache",
    "extensions": ["evy"]
  },
  "application/x-eva": {
    "source": "apache",
    "extensions": ["eva"]
  },
  "application/x-font-bdf": {
    "source": "apache",
    "extensions": ["bdf"]
  },
  "application/x-font-dos": {
    "source": "apache"
  },
  "application/x-font-framemaker": {
    "source": "apache"
  },
  "application/x-font-ghostscript": {
    "source": "apache",
    "extensions": ["gsf"]
  },
  "application/x-font-libgrx": {
    "source": "apache"
  },
  "application/x-font-linux-psf": {
    "source": "apache",
    "extensions": ["psf"]
  },
  "application/x-font-pcf": {
    "source": "apache",
    "extensions": ["pcf"]
  },
  "application/x-font-snf": {
    "source": "apache",
    "extensions": ["snf"]
  },
  "application/x-font-speedo": {
    "source": "apache"
  },
  "application/x-font-sunos-news": {
    "source": "apache"
  },
  "application/x-font-type1": {
    "source": "apache",
    "extensions": ["pfa","pfb","pfm","afm"]
  },
  "application/x-font-vfont": {
    "source": "apache"
  },
  "application/x-freearc": {
    "source": "apache",
    "extensions": ["arc"]
  },
  "application/x-futuresplash": {
    "source": "apache",
    "extensions": ["spl"]
  },
  "application/x-gca-compressed": {
    "source": "apache",
    "extensions": ["gca"]
  },
  "application/x-glulx": {
    "source": "apache",
    "extensions": ["ulx"]
  },
  "application/x-gnumeric": {
    "source": "apache",
    "extensions": ["gnumeric"]
  },
  "application/x-gramps-xml": {
    "source": "apache",
    "extensions": ["gramps"]
  },
  "application/x-gtar": {
    "source": "apache",
    "extensions": ["gtar"]
  },
  "application/x-gzip": {
    "source": "apache"
  },
  "application/x-hdf": {
    "source": "apache",
    "extensions": ["hdf"]
  },
  "application/x-httpd-php": {
    "compressible": true,
    "extensions": ["php"]
  },
  "application/x-install-instructions": {
    "source": "apache",
    "extensions": ["install"]
  },
  "application/x-iso9660-image": {
    "source": "apache",
    "extensions": ["iso"]
  },
  "application/x-java-archive-diff": {
    "source": "nginx",
    "extensions": ["jardiff"]
  },
  "application/x-java-jnlp-file": {
    "source": "apache",
    "compressible": false,
    "extensions": ["jnlp"]
  },
  "application/x-javascript": {
    "compressible": true
  },
  "application/x-keepass2": {
    "extensions": ["kdbx"]
  },
  "application/x-latex": {
    "source": "apache",
    "compressible": false,
    "extensions": ["latex"]
  },
  "application/x-lua-bytecode": {
    "extensions": ["luac"]
  },
  "application/x-lzh-compressed": {
    "source": "apache",
    "extensions": ["lzh","lha"]
  },
  "application/x-makeself": {
    "source": "nginx",
    "extensions": ["run"]
  },
  "application/x-mie": {
    "source": "apache",
    "extensions": ["mie"]
  },
  "application/x-mobipocket-ebook": {
    "source": "apache",
    "extensions": ["prc","mobi"]
  },
  "application/x-mpegurl": {
    "compressible": false
  },
  "application/x-ms-application": {
    "source": "apache",
    "extensions": ["application"]
  },
  "application/x-ms-shortcut": {
    "source": "apache",
    "extensions": ["lnk"]
  },
  "application/x-ms-wmd": {
    "source": "apache",
    "extensions": ["wmd"]
  },
  "application/x-ms-wmz": {
    "source": "apache",
    "extensions": ["wmz"]
  },
  "application/x-ms-xbap": {
    "source": "apache",
    "extensions": ["xbap"]
  },
  "application/x-msaccess": {
    "source": "apache",
    "extensions": ["mdb"]
  },
  "application/x-msbinder": {
    "source": "apache",
    "extensions": ["obd"]
  },
  "application/x-mscardfile": {
    "source": "apache",
    "extensions": ["crd"]
  },
  "application/x-msclip": {
    "source": "apache",
    "extensions": ["clp"]
  },
  "application/x-msdos-program": {
    "extensions": ["exe"]
  },
  "application/x-msdownload": {
    "source": "apache",
    "extensions": ["exe","dll","com","bat","msi"]
  },
  "application/x-msmediaview": {
    "source": "apache",
    "extensions": ["mvb","m13","m14"]
  },
  "application/x-msmetafile": {
    "source": "apache",
    "extensions": ["wmf","wmz","emf","emz"]
  },
  "application/x-msmoney": {
    "source": "apache",
    "extensions": ["mny"]
  },
  "application/x-mspublisher": {
    "source": "apache",
    "extensions": ["pub"]
  },
  "application/x-msschedule": {
    "source": "apache",
    "extensions": ["scd"]
  },
  "application/x-msterminal": {
    "source": "apache",
    "extensions": ["trm"]
  },
  "application/x-mswrite": {
    "source": "apache",
    "extensions": ["wri"]
  },
  "application/x-netcdf": {
    "source": "apache",
    "extensions": ["nc","cdf"]
  },
  "application/x-ns-proxy-autoconfig": {
    "compressible": true,
    "extensions": ["pac"]
  },
  "application/x-nzb": {
    "source": "apache",
    "extensions": ["nzb"]
  },
  "application/x-perl": {
    "source": "nginx",
    "extensions": ["pl","pm"]
  },
  "application/x-pilot": {
    "source": "nginx",
    "extensions": ["prc","pdb"]
  },
  "application/x-pkcs12": {
    "source": "apache",
    "compressible": false,
    "extensions": ["p12","pfx"]
  },
  "application/x-pkcs7-certificates": {
    "source": "apache",
    "extensions": ["p7b","spc"]
  },
  "application/x-pkcs7-certreqresp": {
    "source": "apache",
    "extensions": ["p7r"]
  },
  "application/x-pki-message": {
    "source": "iana"
  },
  "application/x-rar-compressed": {
    "source": "apache",
    "compressible": false,
    "extensions": ["rar"]
  },
  "application/x-redhat-package-manager": {
    "source": "nginx",
    "extensions": ["rpm"]
  },
  "application/x-research-info-systems": {
    "source": "apache",
    "extensions": ["ris"]
  },
  "application/x-sea": {
    "source": "nginx",
    "extensions": ["sea"]
  },
  "application/x-sh": {
    "source": "apache",
    "compressible": true,
    "extensions": ["sh"]
  },
  "application/x-shar": {
    "source": "apache",
    "extensions": ["shar"]
  },
  "application/x-shockwave-flash": {
    "source": "apache",
    "compressible": false,
    "extensions": ["swf"]
  },
  "application/x-silverlight-app": {
    "source": "apache",
    "extensions": ["xap"]
  },
  "application/x-sql": {
    "source": "apache",
    "extensions": ["sql"]
  },
  "application/x-stuffit": {
    "source": "apache",
    "compressible": false,
    "extensions": ["sit"]
  },
  "application/x-stuffitx": {
    "source": "apache",
    "extensions": ["sitx"]
  },
  "application/x-subrip": {
    "source": "apache",
    "extensions": ["srt"]
  },
  "application/x-sv4cpio": {
    "source": "apache",
    "extensions": ["sv4cpio"]
  },
  "application/x-sv4crc": {
    "source": "apache",
    "extensions": ["sv4crc"]
  },
  "application/x-t3vm-image": {
    "source": "apache",
    "extensions": ["t3"]
  },
  "application/x-tads": {
    "source": "apache",
    "extensions": ["gam"]
  },
  "application/x-tar": {
    "source": "apache",
    "compressible": true,
    "extensions": ["tar"]
  },
  "application/x-tcl": {
    "source": "apache",
    "extensions": ["tcl","tk"]
  },
  "application/x-tex": {
    "source": "apache",
    "extensions": ["tex"]
  },
  "application/x-tex-tfm": {
    "source": "apache",
    "extensions": ["tfm"]
  },
  "application/x-texinfo": {
    "source": "apache",
    "extensions": ["texinfo","texi"]
  },
  "application/x-tgif": {
    "source": "apache",
    "extensions": ["obj"]
  },
  "application/x-ustar": {
    "source": "apache",
    "extensions": ["ustar"]
  },
  "application/x-virtualbox-hdd": {
    "compressible": true,
    "extensions": ["hdd"]
  },
  "application/x-virtualbox-ova": {
    "compressible": true,
    "extensions": ["ova"]
  },
  "application/x-virtualbox-ovf": {
    "compressible": true,
    "extensions": ["ovf"]
  },
  "application/x-virtualbox-vbox": {
    "compressible": true,
    "extensions": ["vbox"]
  },
  "application/x-virtualbox-vbox-extpack": {
    "compressible": false,
    "extensions": ["vbox-extpack"]
  },
  "application/x-virtualbox-vdi": {
    "compressible": true,
    "extensions": ["vdi"]
  },
  "application/x-virtualbox-vhd": {
    "compressible": true,
    "extensions": ["vhd"]
  },
  "application/x-virtualbox-vmdk": {
    "compressible": true,
    "extensions": ["vmdk"]
  },
  "application/x-wais-source": {
    "source": "apache",
    "extensions": ["src"]
  },
  "application/x-web-app-manifest+json": {
    "compressible": true,
    "extensions": ["webapp"]
  },
  "application/x-www-form-urlencoded": {
    "source": "iana",
    "compressible": true
  },
  "application/x-x509-ca-cert": {
    "source": "iana",
    "extensions": ["der","crt","pem"]
  },
  "application/x-x509-ca-ra-cert": {
    "source": "iana"
  },
  "application/x-x509-next-ca-cert": {
    "source": "iana"
  },
  "application/x-xfig": {
    "source": "apache",
    "extensions": ["fig"]
  },
  "application/x-xliff+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xlf"]
  },
  "application/x-xpinstall": {
    "source": "apache",
    "compressible": false,
    "extensions": ["xpi"]
  },
  "application/x-xz": {
    "source": "apache",
    "extensions": ["xz"]
  },
  "application/x-zmachine": {
    "source": "apache",
    "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
  },
  "application/x400-bp": {
    "source": "iana"
  },
  "application/xacml+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xaml+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xaml"]
  },
  "application/xcap-att+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xav"]
  },
  "application/xcap-caps+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xca"]
  },
  "application/xcap-diff+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xdf"]
  },
  "application/xcap-el+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xel"]
  },
  "application/xcap-error+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xcap-ns+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xns"]
  },
  "application/xcon-conference-info+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xcon-conference-info-diff+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xenc+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xenc"]
  },
  "application/xhtml+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xhtml","xht"]
  },
  "application/xhtml-voice+xml": {
    "source": "apache",
    "compressible": true
  },
  "application/xliff+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xlf"]
  },
  "application/xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xml","xsl","xsd","rng"]
  },
  "application/xml-dtd": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dtd"]
  },
  "application/xml-external-parsed-entity": {
    "source": "iana"
  },
  "application/xml-patch+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xmpp+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/xop+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xop"]
  },
  "application/xproc+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xpl"]
  },
  "application/xslt+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xsl","xslt"]
  },
  "application/xspf+xml": {
    "source": "apache",
    "compressible": true,
    "extensions": ["xspf"]
  },
  "application/xv+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["mxml","xhvml","xvml","xvm"]
  },
  "application/yang": {
    "source": "iana",
    "extensions": ["yang"]
  },
  "application/yang-data+json": {
    "source": "iana",
    "compressible": true
  },
  "application/yang-data+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/yang-patch+json": {
    "source": "iana",
    "compressible": true
  },
  "application/yang-patch+xml": {
    "source": "iana",
    "compressible": true
  },
  "application/yin+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["yin"]
  },
  "application/zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["zip"]
  },
  "application/zlib": {
    "source": "iana"
  },
  "application/zstd": {
    "source": "iana"
  },
  "audio/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "audio/32kadpcm": {
    "source": "iana"
  },
  "audio/3gpp": {
    "source": "iana",
    "compressible": false,
    "extensions": ["3gpp"]
  },
  "audio/3gpp2": {
    "source": "iana"
  },
  "audio/aac": {
    "source": "iana"
  },
  "audio/ac3": {
    "source": "iana"
  },
  "audio/adpcm": {
    "source": "apache",
    "extensions": ["adp"]
  },
  "audio/amr": {
    "source": "iana",
    "extensions": ["amr"]
  },
  "audio/amr-wb": {
    "source": "iana"
  },
  "audio/amr-wb+": {
    "source": "iana"
  },
  "audio/aptx": {
    "source": "iana"
  },
  "audio/asc": {
    "source": "iana"
  },
  "audio/atrac-advanced-lossless": {
    "source": "iana"
  },
  "audio/atrac-x": {
    "source": "iana"
  },
  "audio/atrac3": {
    "source": "iana"
  },
  "audio/basic": {
    "source": "iana",
    "compressible": false,
    "extensions": ["au","snd"]
  },
  "audio/bv16": {
    "source": "iana"
  },
  "audio/bv32": {
    "source": "iana"
  },
  "audio/clearmode": {
    "source": "iana"
  },
  "audio/cn": {
    "source": "iana"
  },
  "audio/dat12": {
    "source": "iana"
  },
  "audio/dls": {
    "source": "iana"
  },
  "audio/dsr-es201108": {
    "source": "iana"
  },
  "audio/dsr-es202050": {
    "source": "iana"
  },
  "audio/dsr-es202211": {
    "source": "iana"
  },
  "audio/dsr-es202212": {
    "source": "iana"
  },
  "audio/dv": {
    "source": "iana"
  },
  "audio/dvi4": {
    "source": "iana"
  },
  "audio/eac3": {
    "source": "iana"
  },
  "audio/encaprtp": {
    "source": "iana"
  },
  "audio/evrc": {
    "source": "iana"
  },
  "audio/evrc-qcp": {
    "source": "iana"
  },
  "audio/evrc0": {
    "source": "iana"
  },
  "audio/evrc1": {
    "source": "iana"
  },
  "audio/evrcb": {
    "source": "iana"
  },
  "audio/evrcb0": {
    "source": "iana"
  },
  "audio/evrcb1": {
    "source": "iana"
  },
  "audio/evrcnw": {
    "source": "iana"
  },
  "audio/evrcnw0": {
    "source": "iana"
  },
  "audio/evrcnw1": {
    "source": "iana"
  },
  "audio/evrcwb": {
    "source": "iana"
  },
  "audio/evrcwb0": {
    "source": "iana"
  },
  "audio/evrcwb1": {
    "source": "iana"
  },
  "audio/evs": {
    "source": "iana"
  },
  "audio/flexfec": {
    "source": "iana"
  },
  "audio/fwdred": {
    "source": "iana"
  },
  "audio/g711-0": {
    "source": "iana"
  },
  "audio/g719": {
    "source": "iana"
  },
  "audio/g722": {
    "source": "iana"
  },
  "audio/g7221": {
    "source": "iana"
  },
  "audio/g723": {
    "source": "iana"
  },
  "audio/g726-16": {
    "source": "iana"
  },
  "audio/g726-24": {
    "source": "iana"
  },
  "audio/g726-32": {
    "source": "iana"
  },
  "audio/g726-40": {
    "source": "iana"
  },
  "audio/g728": {
    "source": "iana"
  },
  "audio/g729": {
    "source": "iana"
  },
  "audio/g7291": {
    "source": "iana"
  },
  "audio/g729d": {
    "source": "iana"
  },
  "audio/g729e": {
    "source": "iana"
  },
  "audio/gsm": {
    "source": "iana"
  },
  "audio/gsm-efr": {
    "source": "iana"
  },
  "audio/gsm-hr-08": {
    "source": "iana"
  },
  "audio/ilbc": {
    "source": "iana"
  },
  "audio/ip-mr_v2.5": {
    "source": "iana"
  },
  "audio/isac": {
    "source": "apache"
  },
  "audio/l16": {
    "source": "iana"
  },
  "audio/l20": {
    "source": "iana"
  },
  "audio/l24": {
    "source": "iana",
    "compressible": false
  },
  "audio/l8": {
    "source": "iana"
  },
  "audio/lpc": {
    "source": "iana"
  },
  "audio/melp": {
    "source": "iana"
  },
  "audio/melp1200": {
    "source": "iana"
  },
  "audio/melp2400": {
    "source": "iana"
  },
  "audio/melp600": {
    "source": "iana"
  },
  "audio/mhas": {
    "source": "iana"
  },
  "audio/midi": {
    "source": "apache",
    "extensions": ["mid","midi","kar","rmi"]
  },
  "audio/mobile-xmf": {
    "source": "iana",
    "extensions": ["mxmf"]
  },
  "audio/mp3": {
    "compressible": false,
    "extensions": ["mp3"]
  },
  "audio/mp4": {
    "source": "iana",
    "compressible": false,
    "extensions": ["m4a","mp4a"]
  },
  "audio/mp4a-latm": {
    "source": "iana"
  },
  "audio/mpa": {
    "source": "iana"
  },
  "audio/mpa-robust": {
    "source": "iana"
  },
  "audio/mpeg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
  },
  "audio/mpeg4-generic": {
    "source": "iana"
  },
  "audio/musepack": {
    "source": "apache"
  },
  "audio/ogg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["oga","ogg","spx","opus"]
  },
  "audio/opus": {
    "source": "iana"
  },
  "audio/parityfec": {
    "source": "iana"
  },
  "audio/pcma": {
    "source": "iana"
  },
  "audio/pcma-wb": {
    "source": "iana"
  },
  "audio/pcmu": {
    "source": "iana"
  },
  "audio/pcmu-wb": {
    "source": "iana"
  },
  "audio/prs.sid": {
    "source": "iana"
  },
  "audio/qcelp": {
    "source": "iana"
  },
  "audio/raptorfec": {
    "source": "iana"
  },
  "audio/red": {
    "source": "iana"
  },
  "audio/rtp-enc-aescm128": {
    "source": "iana"
  },
  "audio/rtp-midi": {
    "source": "iana"
  },
  "audio/rtploopback": {
    "source": "iana"
  },
  "audio/rtx": {
    "source": "iana"
  },
  "audio/s3m": {
    "source": "apache",
    "extensions": ["s3m"]
  },
  "audio/scip": {
    "source": "iana"
  },
  "audio/silk": {
    "source": "apache",
    "extensions": ["sil"]
  },
  "audio/smv": {
    "source": "iana"
  },
  "audio/smv-qcp": {
    "source": "iana"
  },
  "audio/smv0": {
    "source": "iana"
  },
  "audio/sofa": {
    "source": "iana"
  },
  "audio/sp-midi": {
    "source": "iana"
  },
  "audio/speex": {
    "source": "iana"
  },
  "audio/t140c": {
    "source": "iana"
  },
  "audio/t38": {
    "source": "iana"
  },
  "audio/telephone-event": {
    "source": "iana"
  },
  "audio/tetra_acelp": {
    "source": "iana"
  },
  "audio/tetra_acelp_bb": {
    "source": "iana"
  },
  "audio/tone": {
    "source": "iana"
  },
  "audio/tsvcis": {
    "source": "iana"
  },
  "audio/uemclip": {
    "source": "iana"
  },
  "audio/ulpfec": {
    "source": "iana"
  },
  "audio/usac": {
    "source": "iana"
  },
  "audio/vdvi": {
    "source": "iana"
  },
  "audio/vmr-wb": {
    "source": "iana"
  },
  "audio/vnd.3gpp.iufp": {
    "source": "iana"
  },
  "audio/vnd.4sb": {
    "source": "iana"
  },
  "audio/vnd.audiokoz": {
    "source": "iana"
  },
  "audio/vnd.celp": {
    "source": "iana"
  },
  "audio/vnd.cisco.nse": {
    "source": "iana"
  },
  "audio/vnd.cmles.radio-events": {
    "source": "iana"
  },
  "audio/vnd.cns.anp1": {
    "source": "iana"
  },
  "audio/vnd.cns.inf1": {
    "source": "iana"
  },
  "audio/vnd.dece.audio": {
    "source": "iana",
    "extensions": ["uva","uvva"]
  },
  "audio/vnd.digital-winds": {
    "source": "iana",
    "extensions": ["eol"]
  },
  "audio/vnd.dlna.adts": {
    "source": "iana"
  },
  "audio/vnd.dolby.heaac.1": {
    "source": "iana"
  },
  "audio/vnd.dolby.heaac.2": {
    "source": "iana"
  },
  "audio/vnd.dolby.mlp": {
    "source": "iana"
  },
  "audio/vnd.dolby.mps": {
    "source": "iana"
  },
  "audio/vnd.dolby.pl2": {
    "source": "iana"
  },
  "audio/vnd.dolby.pl2x": {
    "source": "iana"
  },
  "audio/vnd.dolby.pl2z": {
    "source": "iana"
  },
  "audio/vnd.dolby.pulse.1": {
    "source": "iana"
  },
  "audio/vnd.dra": {
    "source": "iana",
    "extensions": ["dra"]
  },
  "audio/vnd.dts": {
    "source": "iana",
    "extensions": ["dts"]
  },
  "audio/vnd.dts.hd": {
    "source": "iana",
    "extensions": ["dtshd"]
  },
  "audio/vnd.dts.uhd": {
    "source": "iana"
  },
  "audio/vnd.dvb.file": {
    "source": "iana"
  },
  "audio/vnd.everad.plj": {
    "source": "iana"
  },
  "audio/vnd.hns.audio": {
    "source": "iana"
  },
  "audio/vnd.lucent.voice": {
    "source": "iana",
    "extensions": ["lvp"]
  },
  "audio/vnd.ms-playready.media.pya": {
    "source": "iana",
    "extensions": ["pya"]
  },
  "audio/vnd.nokia.mobile-xmf": {
    "source": "iana"
  },
  "audio/vnd.nortel.vbk": {
    "source": "iana"
  },
  "audio/vnd.nuera.ecelp4800": {
    "source": "iana",
    "extensions": ["ecelp4800"]
  },
  "audio/vnd.nuera.ecelp7470": {
    "source": "iana",
    "extensions": ["ecelp7470"]
  },
  "audio/vnd.nuera.ecelp9600": {
    "source": "iana",
    "extensions": ["ecelp9600"]
  },
  "audio/vnd.octel.sbc": {
    "source": "iana"
  },
  "audio/vnd.presonus.multitrack": {
    "source": "iana"
  },
  "audio/vnd.qcelp": {
    "source": "iana"
  },
  "audio/vnd.rhetorex.32kadpcm": {
    "source": "iana"
  },
  "audio/vnd.rip": {
    "source": "iana",
    "extensions": ["rip"]
  },
  "audio/vnd.rn-realaudio": {
    "compressible": false
  },
  "audio/vnd.sealedmedia.softseal.mpeg": {
    "source": "iana"
  },
  "audio/vnd.vmx.cvsd": {
    "source": "iana"
  },
  "audio/vnd.wave": {
    "compressible": false
  },
  "audio/vorbis": {
    "source": "iana",
    "compressible": false
  },
  "audio/vorbis-config": {
    "source": "iana"
  },
  "audio/wav": {
    "compressible": false,
    "extensions": ["wav"]
  },
  "audio/wave": {
    "compressible": false,
    "extensions": ["wav"]
  },
  "audio/webm": {
    "source": "apache",
    "compressible": false,
    "extensions": ["weba"]
  },
  "audio/x-aac": {
    "source": "apache",
    "compressible": false,
    "extensions": ["aac"]
  },
  "audio/x-aiff": {
    "source": "apache",
    "extensions": ["aif","aiff","aifc"]
  },
  "audio/x-caf": {
    "source": "apache",
    "compressible": false,
    "extensions": ["caf"]
  },
  "audio/x-flac": {
    "source": "apache",
    "extensions": ["flac"]
  },
  "audio/x-m4a": {
    "source": "nginx",
    "extensions": ["m4a"]
  },
  "audio/x-matroska": {
    "source": "apache",
    "extensions": ["mka"]
  },
  "audio/x-mpegurl": {
    "source": "apache",
    "extensions": ["m3u"]
  },
  "audio/x-ms-wax": {
    "source": "apache",
    "extensions": ["wax"]
  },
  "audio/x-ms-wma": {
    "source": "apache",
    "extensions": ["wma"]
  },
  "audio/x-pn-realaudio": {
    "source": "apache",
    "extensions": ["ram","ra"]
  },
  "audio/x-pn-realaudio-plugin": {
    "source": "apache",
    "extensions": ["rmp"]
  },
  "audio/x-realaudio": {
    "source": "nginx",
    "extensions": ["ra"]
  },
  "audio/x-tta": {
    "source": "apache"
  },
  "audio/x-wav": {
    "source": "apache",
    "extensions": ["wav"]
  },
  "audio/xm": {
    "source": "apache",
    "extensions": ["xm"]
  },
  "chemical/x-cdx": {
    "source": "apache",
    "extensions": ["cdx"]
  },
  "chemical/x-cif": {
    "source": "apache",
    "extensions": ["cif"]
  },
  "chemical/x-cmdf": {
    "source": "apache",
    "extensions": ["cmdf"]
  },
  "chemical/x-cml": {
    "source": "apache",
    "extensions": ["cml"]
  },
  "chemical/x-csml": {
    "source": "apache",
    "extensions": ["csml"]
  },
  "chemical/x-pdb": {
    "source": "apache"
  },
  "chemical/x-xyz": {
    "source": "apache",
    "extensions": ["xyz"]
  },
  "font/collection": {
    "source": "iana",
    "extensions": ["ttc"]
  },
  "font/otf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["otf"]
  },
  "font/sfnt": {
    "source": "iana"
  },
  "font/ttf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["ttf"]
  },
  "font/woff": {
    "source": "iana",
    "extensions": ["woff"]
  },
  "font/woff2": {
    "source": "iana",
    "extensions": ["woff2"]
  },
  "image/aces": {
    "source": "iana",
    "extensions": ["exr"]
  },
  "image/apng": {
    "compressible": false,
    "extensions": ["apng"]
  },
  "image/avci": {
    "source": "iana"
  },
  "image/avcs": {
    "source": "iana"
  },
  "image/avif": {
    "source": "iana",
    "compressible": false,
    "extensions": ["avif"]
  },
  "image/bmp": {
    "source": "iana",
    "compressible": true,
    "extensions": ["bmp"]
  },
  "image/cgm": {
    "source": "iana",
    "extensions": ["cgm"]
  },
  "image/dicom-rle": {
    "source": "iana",
    "extensions": ["drle"]
  },
  "image/emf": {
    "source": "iana",
    "extensions": ["emf"]
  },
  "image/fits": {
    "source": "iana",
    "extensions": ["fits"]
  },
  "image/g3fax": {
    "source": "iana",
    "extensions": ["g3"]
  },
  "image/gif": {
    "source": "iana",
    "compressible": false,
    "extensions": ["gif"]
  },
  "image/heic": {
    "source": "iana",
    "extensions": ["heic"]
  },
  "image/heic-sequence": {
    "source": "iana",
    "extensions": ["heics"]
  },
  "image/heif": {
    "source": "iana",
    "extensions": ["heif"]
  },
  "image/heif-sequence": {
    "source": "iana",
    "extensions": ["heifs"]
  },
  "image/hej2k": {
    "source": "iana",
    "extensions": ["hej2"]
  },
  "image/hsj2": {
    "source": "iana",
    "extensions": ["hsj2"]
  },
  "image/ief": {
    "source": "iana",
    "extensions": ["ief"]
  },
  "image/jls": {
    "source": "iana",
    "extensions": ["jls"]
  },
  "image/jp2": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jp2","jpg2"]
  },
  "image/jpeg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jpeg","jpg","jpe"]
  },
  "image/jph": {
    "source": "iana",
    "extensions": ["jph"]
  },
  "image/jphc": {
    "source": "iana",
    "extensions": ["jhc"]
  },
  "image/jpm": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jpm"]
  },
  "image/jpx": {
    "source": "iana",
    "compressible": false,
    "extensions": ["jpx","jpf"]
  },
  "image/jxr": {
    "source": "iana",
    "extensions": ["jxr"]
  },
  "image/jxra": {
    "source": "iana",
    "extensions": ["jxra"]
  },
  "image/jxrs": {
    "source": "iana",
    "extensions": ["jxrs"]
  },
  "image/jxs": {
    "source": "iana",
    "extensions": ["jxs"]
  },
  "image/jxsc": {
    "source": "iana",
    "extensions": ["jxsc"]
  },
  "image/jxsi": {
    "source": "iana",
    "extensions": ["jxsi"]
  },
  "image/jxss": {
    "source": "iana",
    "extensions": ["jxss"]
  },
  "image/ktx": {
    "source": "iana",
    "extensions": ["ktx"]
  },
  "image/ktx2": {
    "source": "iana",
    "extensions": ["ktx2"]
  },
  "image/naplps": {
    "source": "iana"
  },
  "image/pjpeg": {
    "compressible": false
  },
  "image/png": {
    "source": "iana",
    "compressible": false,
    "extensions": ["png"]
  },
  "image/prs.btif": {
    "source": "iana",
    "extensions": ["btif"]
  },
  "image/prs.pti": {
    "source": "iana",
    "extensions": ["pti"]
  },
  "image/pwg-raster": {
    "source": "iana"
  },
  "image/sgi": {
    "source": "apache",
    "extensions": ["sgi"]
  },
  "image/svg+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["svg","svgz"]
  },
  "image/t38": {
    "source": "iana",
    "extensions": ["t38"]
  },
  "image/tiff": {
    "source": "iana",
    "compressible": false,
    "extensions": ["tif","tiff"]
  },
  "image/tiff-fx": {
    "source": "iana",
    "extensions": ["tfx"]
  },
  "image/vnd.adobe.photoshop": {
    "source": "iana",
    "compressible": true,
    "extensions": ["psd"]
  },
  "image/vnd.airzip.accelerator.azv": {
    "source": "iana",
    "extensions": ["azv"]
  },
  "image/vnd.cns.inf2": {
    "source": "iana"
  },
  "image/vnd.dece.graphic": {
    "source": "iana",
    "extensions": ["uvi","uvvi","uvg","uvvg"]
  },
  "image/vnd.djvu": {
    "source": "iana",
    "extensions": ["djvu","djv"]
  },
  "image/vnd.dvb.subtitle": {
    "source": "iana",
    "extensions": ["sub"]
  },
  "image/vnd.dwg": {
    "source": "iana",
    "extensions": ["dwg"]
  },
  "image/vnd.dxf": {
    "source": "iana",
    "extensions": ["dxf"]
  },
  "image/vnd.fastbidsheet": {
    "source": "iana",
    "extensions": ["fbs"]
  },
  "image/vnd.fpx": {
    "source": "iana",
    "extensions": ["fpx"]
  },
  "image/vnd.fst": {
    "source": "iana",
    "extensions": ["fst"]
  },
  "image/vnd.fujixerox.edmics-mmr": {
    "source": "iana",
    "extensions": ["mmr"]
  },
  "image/vnd.fujixerox.edmics-rlc": {
    "source": "iana",
    "extensions": ["rlc"]
  },
  "image/vnd.globalgraphics.pgb": {
    "source": "iana"
  },
  "image/vnd.microsoft.icon": {
    "source": "iana",
    "extensions": ["ico"]
  },
  "image/vnd.mix": {
    "source": "iana"
  },
  "image/vnd.mozilla.apng": {
    "source": "iana"
  },
  "image/vnd.ms-dds": {
    "extensions": ["dds"]
  },
  "image/vnd.ms-modi": {
    "source": "iana",
    "extensions": ["mdi"]
  },
  "image/vnd.ms-photo": {
    "source": "apache",
    "extensions": ["wdp"]
  },
  "image/vnd.net-fpx": {
    "source": "iana",
    "extensions": ["npx"]
  },
  "image/vnd.pco.b16": {
    "source": "iana",
    "extensions": ["b16"]
  },
  "image/vnd.radiance": {
    "source": "iana"
  },
  "image/vnd.sealed.png": {
    "source": "iana"
  },
  "image/vnd.sealedmedia.softseal.gif": {
    "source": "iana"
  },
  "image/vnd.sealedmedia.softseal.jpg": {
    "source": "iana"
  },
  "image/vnd.svf": {
    "source": "iana"
  },
  "image/vnd.tencent.tap": {
    "source": "iana",
    "extensions": ["tap"]
  },
  "image/vnd.valve.source.texture": {
    "source": "iana",
    "extensions": ["vtf"]
  },
  "image/vnd.wap.wbmp": {
    "source": "iana",
    "extensions": ["wbmp"]
  },
  "image/vnd.xiff": {
    "source": "iana",
    "extensions": ["xif"]
  },
  "image/vnd.zbrush.pcx": {
    "source": "iana",
    "extensions": ["pcx"]
  },
  "image/webp": {
    "source": "apache",
    "extensions": ["webp"]
  },
  "image/wmf": {
    "source": "iana",
    "extensions": ["wmf"]
  },
  "image/x-3ds": {
    "source": "apache",
    "extensions": ["3ds"]
  },
  "image/x-cmu-raster": {
    "source": "apache",
    "extensions": ["ras"]
  },
  "image/x-cmx": {
    "source": "apache",
    "extensions": ["cmx"]
  },
  "image/x-freehand": {
    "source": "apache",
    "extensions": ["fh","fhc","fh4","fh5","fh7"]
  },
  "image/x-icon": {
    "source": "apache",
    "compressible": true,
    "extensions": ["ico"]
  },
  "image/x-jng": {
    "source": "nginx",
    "extensions": ["jng"]
  },
  "image/x-mrsid-image": {
    "source": "apache",
    "extensions": ["sid"]
  },
  "image/x-ms-bmp": {
    "source": "nginx",
    "compressible": true,
    "extensions": ["bmp"]
  },
  "image/x-pcx": {
    "source": "apache",
    "extensions": ["pcx"]
  },
  "image/x-pict": {
    "source": "apache",
    "extensions": ["pic","pct"]
  },
  "image/x-portable-anymap": {
    "source": "apache",
    "extensions": ["pnm"]
  },
  "image/x-portable-bitmap": {
    "source": "apache",
    "extensions": ["pbm"]
  },
  "image/x-portable-graymap": {
    "source": "apache",
    "extensions": ["pgm"]
  },
  "image/x-portable-pixmap": {
    "source": "apache",
    "extensions": ["ppm"]
  },
  "image/x-rgb": {
    "source": "apache",
    "extensions": ["rgb"]
  },
  "image/x-tga": {
    "source": "apache",
    "extensions": ["tga"]
  },
  "image/x-xbitmap": {
    "source": "apache",
    "extensions": ["xbm"]
  },
  "image/x-xcf": {
    "compressible": false
  },
  "image/x-xpixmap": {
    "source": "apache",
    "extensions": ["xpm"]
  },
  "image/x-xwindowdump": {
    "source": "apache",
    "extensions": ["xwd"]
  },
  "message/cpim": {
    "source": "iana"
  },
  "message/delivery-status": {
    "source": "iana"
  },
  "message/disposition-notification": {
    "source": "iana",
    "extensions": [
      "disposition-notification"
    ]
  },
  "message/external-body": {
    "source": "iana"
  },
  "message/feedback-report": {
    "source": "iana"
  },
  "message/global": {
    "source": "iana",
    "extensions": ["u8msg"]
  },
  "message/global-delivery-status": {
    "source": "iana",
    "extensions": ["u8dsn"]
  },
  "message/global-disposition-notification": {
    "source": "iana",
    "extensions": ["u8mdn"]
  },
  "message/global-headers": {
    "source": "iana",
    "extensions": ["u8hdr"]
  },
  "message/http": {
    "source": "iana",
    "compressible": false
  },
  "message/imdn+xml": {
    "source": "iana",
    "compressible": true
  },
  "message/news": {
    "source": "iana"
  },
  "message/partial": {
    "source": "iana",
    "compressible": false
  },
  "message/rfc822": {
    "source": "iana",
    "compressible": true,
    "extensions": ["eml","mime"]
  },
  "message/s-http": {
    "source": "iana"
  },
  "message/sip": {
    "source": "iana"
  },
  "message/sipfrag": {
    "source": "iana"
  },
  "message/tracking-status": {
    "source": "iana"
  },
  "message/vnd.si.simp": {
    "source": "iana"
  },
  "message/vnd.wfa.wsc": {
    "source": "iana",
    "extensions": ["wsc"]
  },
  "model/3mf": {
    "source": "iana",
    "extensions": ["3mf"]
  },
  "model/e57": {
    "source": "iana"
  },
  "model/gltf+json": {
    "source": "iana",
    "compressible": true,
    "extensions": ["gltf"]
  },
  "model/gltf-binary": {
    "source": "iana",
    "compressible": true,
    "extensions": ["glb"]
  },
  "model/iges": {
    "source": "iana",
    "compressible": false,
    "extensions": ["igs","iges"]
  },
  "model/mesh": {
    "source": "iana",
    "compressible": false,
    "extensions": ["msh","mesh","silo"]
  },
  "model/mtl": {
    "source": "iana",
    "extensions": ["mtl"]
  },
  "model/obj": {
    "source": "iana",
    "extensions": ["obj"]
  },
  "model/step+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["stpz"]
  },
  "model/step-xml+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["stpxz"]
  },
  "model/stl": {
    "source": "iana",
    "extensions": ["stl"]
  },
  "model/vnd.collada+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["dae"]
  },
  "model/vnd.dwf": {
    "source": "iana",
    "extensions": ["dwf"]
  },
  "model/vnd.flatland.3dml": {
    "source": "iana"
  },
  "model/vnd.gdl": {
    "source": "iana",
    "extensions": ["gdl"]
  },
  "model/vnd.gs-gdl": {
    "source": "apache"
  },
  "model/vnd.gs.gdl": {
    "source": "iana"
  },
  "model/vnd.gtw": {
    "source": "iana",
    "extensions": ["gtw"]
  },
  "model/vnd.moml+xml": {
    "source": "iana",
    "compressible": true
  },
  "model/vnd.mts": {
    "source": "iana",
    "extensions": ["mts"]
  },
  "model/vnd.opengex": {
    "source": "iana",
    "extensions": ["ogex"]
  },
  "model/vnd.parasolid.transmit.binary": {
    "source": "iana",
    "extensions": ["x_b"]
  },
  "model/vnd.parasolid.transmit.text": {
    "source": "iana",
    "extensions": ["x_t"]
  },
  "model/vnd.pytha.pyox": {
    "source": "iana"
  },
  "model/vnd.rosette.annotated-data-model": {
    "source": "iana"
  },
  "model/vnd.sap.vds": {
    "source": "iana",
    "extensions": ["vds"]
  },
  "model/vnd.usdz+zip": {
    "source": "iana",
    "compressible": false,
    "extensions": ["usdz"]
  },
  "model/vnd.valve.source.compiled-map": {
    "source": "iana",
    "extensions": ["bsp"]
  },
  "model/vnd.vtu": {
    "source": "iana",
    "extensions": ["vtu"]
  },
  "model/vrml": {
    "source": "iana",
    "compressible": false,
    "extensions": ["wrl","vrml"]
  },
  "model/x3d+binary": {
    "source": "apache",
    "compressible": false,
    "extensions": ["x3db","x3dbz"]
  },
  "model/x3d+fastinfoset": {
    "source": "iana",
    "extensions": ["x3db"]
  },
  "model/x3d+vrml": {
    "source": "apache",
    "compressible": false,
    "extensions": ["x3dv","x3dvz"]
  },
  "model/x3d+xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["x3d","x3dz"]
  },
  "model/x3d-vrml": {
    "source": "iana",
    "extensions": ["x3dv"]
  },
  "multipart/alternative": {
    "source": "iana",
    "compressible": false
  },
  "multipart/appledouble": {
    "source": "iana"
  },
  "multipart/byteranges": {
    "source": "iana"
  },
  "multipart/digest": {
    "source": "iana"
  },
  "multipart/encrypted": {
    "source": "iana",
    "compressible": false
  },
  "multipart/form-data": {
    "source": "iana",
    "compressible": false
  },
  "multipart/header-set": {
    "source": "iana"
  },
  "multipart/mixed": {
    "source": "iana"
  },
  "multipart/multilingual": {
    "source": "iana"
  },
  "multipart/parallel": {
    "source": "iana"
  },
  "multipart/related": {
    "source": "iana",
    "compressible": false
  },
  "multipart/report": {
    "source": "iana"
  },
  "multipart/signed": {
    "source": "iana",
    "compressible": false
  },
  "multipart/vnd.bint.med-plus": {
    "source": "iana"
  },
  "multipart/voice-message": {
    "source": "iana"
  },
  "multipart/x-mixed-replace": {
    "source": "iana"
  },
  "text/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "text/cache-manifest": {
    "source": "iana",
    "compressible": true,
    "extensions": ["appcache","manifest"]
  },
  "text/calendar": {
    "source": "iana",
    "extensions": ["ics","ifb"]
  },
  "text/calender": {
    "compressible": true
  },
  "text/cmd": {
    "compressible": true
  },
  "text/coffeescript": {
    "extensions": ["coffee","litcoffee"]
  },
  "text/cql": {
    "source": "iana"
  },
  "text/cql-expression": {
    "source": "iana"
  },
  "text/cql-identifier": {
    "source": "iana"
  },
  "text/css": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["css"]
  },
  "text/csv": {
    "source": "iana",
    "compressible": true,
    "extensions": ["csv"]
  },
  "text/csv-schema": {
    "source": "iana"
  },
  "text/directory": {
    "source": "iana"
  },
  "text/dns": {
    "source": "iana"
  },
  "text/ecmascript": {
    "source": "iana"
  },
  "text/encaprtp": {
    "source": "iana"
  },
  "text/enriched": {
    "source": "iana"
  },
  "text/fhirpath": {
    "source": "iana"
  },
  "text/flexfec": {
    "source": "iana"
  },
  "text/fwdred": {
    "source": "iana"
  },
  "text/gff3": {
    "source": "iana"
  },
  "text/grammar-ref-list": {
    "source": "iana"
  },
  "text/html": {
    "source": "iana",
    "compressible": true,
    "extensions": ["html","htm","shtml"]
  },
  "text/jade": {
    "extensions": ["jade"]
  },
  "text/javascript": {
    "source": "iana",
    "compressible": true
  },
  "text/jcr-cnd": {
    "source": "iana"
  },
  "text/jsx": {
    "compressible": true,
    "extensions": ["jsx"]
  },
  "text/less": {
    "compressible": true,
    "extensions": ["less"]
  },
  "text/markdown": {
    "source": "iana",
    "compressible": true,
    "extensions": ["markdown","md"]
  },
  "text/mathml": {
    "source": "nginx",
    "extensions": ["mml"]
  },
  "text/mdx": {
    "compressible": true,
    "extensions": ["mdx"]
  },
  "text/mizar": {
    "source": "iana"
  },
  "text/n3": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["n3"]
  },
  "text/parameters": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/parityfec": {
    "source": "iana"
  },
  "text/plain": {
    "source": "iana",
    "compressible": true,
    "extensions": ["txt","text","conf","def","list","log","in","ini"]
  },
  "text/provenance-notation": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/prs.fallenstein.rst": {
    "source": "iana"
  },
  "text/prs.lines.tag": {
    "source": "iana",
    "extensions": ["dsc"]
  },
  "text/prs.prop.logic": {
    "source": "iana"
  },
  "text/raptorfec": {
    "source": "iana"
  },
  "text/red": {
    "source": "iana"
  },
  "text/rfc822-headers": {
    "source": "iana"
  },
  "text/richtext": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rtx"]
  },
  "text/rtf": {
    "source": "iana",
    "compressible": true,
    "extensions": ["rtf"]
  },
  "text/rtp-enc-aescm128": {
    "source": "iana"
  },
  "text/rtploopback": {
    "source": "iana"
  },
  "text/rtx": {
    "source": "iana"
  },
  "text/sgml": {
    "source": "iana",
    "extensions": ["sgml","sgm"]
  },
  "text/shaclc": {
    "source": "iana"
  },
  "text/shex": {
    "source": "iana",
    "extensions": ["shex"]
  },
  "text/slim": {
    "extensions": ["slim","slm"]
  },
  "text/spdx": {
    "source": "iana",
    "extensions": ["spdx"]
  },
  "text/strings": {
    "source": "iana"
  },
  "text/stylus": {
    "extensions": ["stylus","styl"]
  },
  "text/t140": {
    "source": "iana"
  },
  "text/tab-separated-values": {
    "source": "iana",
    "compressible": true,
    "extensions": ["tsv"]
  },
  "text/troff": {
    "source": "iana",
    "extensions": ["t","tr","roff","man","me","ms"]
  },
  "text/turtle": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["ttl"]
  },
  "text/ulpfec": {
    "source": "iana"
  },
  "text/uri-list": {
    "source": "iana",
    "compressible": true,
    "extensions": ["uri","uris","urls"]
  },
  "text/vcard": {
    "source": "iana",
    "compressible": true,
    "extensions": ["vcard"]
  },
  "text/vnd.a": {
    "source": "iana"
  },
  "text/vnd.abc": {
    "source": "iana"
  },
  "text/vnd.ascii-art": {
    "source": "iana"
  },
  "text/vnd.curl": {
    "source": "iana",
    "extensions": ["curl"]
  },
  "text/vnd.curl.dcurl": {
    "source": "apache",
    "extensions": ["dcurl"]
  },
  "text/vnd.curl.mcurl": {
    "source": "apache",
    "extensions": ["mcurl"]
  },
  "text/vnd.curl.scurl": {
    "source": "apache",
    "extensions": ["scurl"]
  },
  "text/vnd.debian.copyright": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/vnd.dmclientscript": {
    "source": "iana"
  },
  "text/vnd.dvb.subtitle": {
    "source": "iana",
    "extensions": ["sub"]
  },
  "text/vnd.esmertec.theme-descriptor": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/vnd.ficlab.flt": {
    "source": "iana"
  },
  "text/vnd.fly": {
    "source": "iana",
    "extensions": ["fly"]
  },
  "text/vnd.fmi.flexstor": {
    "source": "iana",
    "extensions": ["flx"]
  },
  "text/vnd.gml": {
    "source": "iana"
  },
  "text/vnd.graphviz": {
    "source": "iana",
    "extensions": ["gv"]
  },
  "text/vnd.hans": {
    "source": "iana"
  },
  "text/vnd.hgl": {
    "source": "iana"
  },
  "text/vnd.in3d.3dml": {
    "source": "iana",
    "extensions": ["3dml"]
  },
  "text/vnd.in3d.spot": {
    "source": "iana",
    "extensions": ["spot"]
  },
  "text/vnd.iptc.newsml": {
    "source": "iana"
  },
  "text/vnd.iptc.nitf": {
    "source": "iana"
  },
  "text/vnd.latex-z": {
    "source": "iana"
  },
  "text/vnd.motorola.reflex": {
    "source": "iana"
  },
  "text/vnd.ms-mediapackage": {
    "source": "iana"
  },
  "text/vnd.net2phone.commcenter.command": {
    "source": "iana"
  },
  "text/vnd.radisys.msml-basic-layout": {
    "source": "iana"
  },
  "text/vnd.senx.warpscript": {
    "source": "iana"
  },
  "text/vnd.si.uricatalogue": {
    "source": "iana"
  },
  "text/vnd.sosi": {
    "source": "iana"
  },
  "text/vnd.sun.j2me.app-descriptor": {
    "source": "iana",
    "charset": "UTF-8",
    "extensions": ["jad"]
  },
  "text/vnd.trolltech.linguist": {
    "source": "iana",
    "charset": "UTF-8"
  },
  "text/vnd.wap.si": {
    "source": "iana"
  },
  "text/vnd.wap.sl": {
    "source": "iana"
  },
  "text/vnd.wap.wml": {
    "source": "iana",
    "extensions": ["wml"]
  },
  "text/vnd.wap.wmlscript": {
    "source": "iana",
    "extensions": ["wmls"]
  },
  "text/vtt": {
    "source": "iana",
    "charset": "UTF-8",
    "compressible": true,
    "extensions": ["vtt"]
  },
  "text/x-asm": {
    "source": "apache",
    "extensions": ["s","asm"]
  },
  "text/x-c": {
    "source": "apache",
    "extensions": ["c","cc","cxx","cpp","h","hh","dic"]
  },
  "text/x-component": {
    "source": "nginx",
    "extensions": ["htc"]
  },
  "text/x-fortran": {
    "source": "apache",
    "extensions": ["f","for","f77","f90"]
  },
  "text/x-gwt-rpc": {
    "compressible": true
  },
  "text/x-handlebars-template": {
    "extensions": ["hbs"]
  },
  "text/x-java-source": {
    "source": "apache",
    "extensions": ["java"]
  },
  "text/x-jquery-tmpl": {
    "compressible": true
  },
  "text/x-lua": {
    "extensions": ["lua"]
  },
  "text/x-markdown": {
    "compressible": true,
    "extensions": ["mkd"]
  },
  "text/x-nfo": {
    "source": "apache",
    "extensions": ["nfo"]
  },
  "text/x-opml": {
    "source": "apache",
    "extensions": ["opml"]
  },
  "text/x-org": {
    "compressible": true,
    "extensions": ["org"]
  },
  "text/x-pascal": {
    "source": "apache",
    "extensions": ["p","pas"]
  },
  "text/x-processing": {
    "compressible": true,
    "extensions": ["pde"]
  },
  "text/x-sass": {
    "extensions": ["sass"]
  },
  "text/x-scss": {
    "extensions": ["scss"]
  },
  "text/x-setext": {
    "source": "apache",
    "extensions": ["etx"]
  },
  "text/x-sfv": {
    "source": "apache",
    "extensions": ["sfv"]
  },
  "text/x-suse-ymp": {
    "compressible": true,
    "extensions": ["ymp"]
  },
  "text/x-uuencode": {
    "source": "apache",
    "extensions": ["uu"]
  },
  "text/x-vcalendar": {
    "source": "apache",
    "extensions": ["vcs"]
  },
  "text/x-vcard": {
    "source": "apache",
    "extensions": ["vcf"]
  },
  "text/xml": {
    "source": "iana",
    "compressible": true,
    "extensions": ["xml"]
  },
  "text/xml-external-parsed-entity": {
    "source": "iana"
  },
  "text/yaml": {
    "compressible": true,
    "extensions": ["yaml","yml"]
  },
  "video/1d-interleaved-parityfec": {
    "source": "iana"
  },
  "video/3gpp": {
    "source": "iana",
    "extensions": ["3gp","3gpp"]
  },
  "video/3gpp-tt": {
    "source": "iana"
  },
  "video/3gpp2": {
    "source": "iana",
    "extensions": ["3g2"]
  },
  "video/av1": {
    "source": "iana"
  },
  "video/bmpeg": {
    "source": "iana"
  },
  "video/bt656": {
    "source": "iana"
  },
  "video/celb": {
    "source": "iana"
  },
  "video/dv": {
    "source": "iana"
  },
  "video/encaprtp": {
    "source": "iana"
  },
  "video/ffv1": {
    "source": "iana"
  },
  "video/flexfec": {
    "source": "iana"
  },
  "video/h261": {
    "source": "iana",
    "extensions": ["h261"]
  },
  "video/h263": {
    "source": "iana",
    "extensions": ["h263"]
  },
  "video/h263-1998": {
    "source": "iana"
  },
  "video/h263-2000": {
    "source": "iana"
  },
  "video/h264": {
    "source": "iana",
    "extensions": ["h264"]
  },
  "video/h264-rcdo": {
    "source": "iana"
  },
  "video/h264-svc": {
    "source": "iana"
  },
  "video/h265": {
    "source": "iana"
  },
  "video/iso.segment": {
    "source": "iana",
    "extensions": ["m4s"]
  },
  "video/jpeg": {
    "source": "iana",
    "extensions": ["jpgv"]
  },
  "video/jpeg2000": {
    "source": "iana"
  },
  "video/jpm": {
    "source": "apache",
    "extensions": ["jpm","jpgm"]
  },
  "video/mj2": {
    "source": "iana",
    "extensions": ["mj2","mjp2"]
  },
  "video/mp1s": {
    "source": "iana"
  },
  "video/mp2p": {
    "source": "iana"
  },
  "video/mp2t": {
    "source": "iana",
    "extensions": ["ts"]
  },
  "video/mp4": {
    "source": "iana",
    "compressible": false,
    "extensions": ["mp4","mp4v","mpg4"]
  },
  "video/mp4v-es": {
    "source": "iana"
  },
  "video/mpeg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["mpeg","mpg","mpe","m1v","m2v"]
  },
  "video/mpeg4-generic": {
    "source": "iana"
  },
  "video/mpv": {
    "source": "iana"
  },
  "video/nv": {
    "source": "iana"
  },
  "video/ogg": {
    "source": "iana",
    "compressible": false,
    "extensions": ["ogv"]
  },
  "video/parityfec": {
    "source": "iana"
  },
  "video/pointer": {
    "source": "iana"
  },
  "video/quicktime": {
    "source": "iana",
    "compressible": false,
    "extensions": ["qt","mov"]
  },
  "video/raptorfec": {
    "source": "iana"
  },
  "video/raw": {
    "source": "iana"
  },
  "video/rtp-enc-aescm128": {
    "source": "iana"
  },
  "video/rtploopback": {
    "source": "iana"
  },
  "video/rtx": {
    "source": "iana"
  },
  "video/scip": {
    "source": "iana"
  },
  "video/smpte291": {
    "source": "iana"
  },
  "video/smpte292m": {
    "source": "iana"
  },
  "video/ulpfec": {
    "source": "iana"
  },
  "video/vc1": {
    "source": "iana"
  },
  "video/vc2": {
    "source": "iana"
  },
  "video/vnd.cctv": {
    "source": "iana"
  },
  "video/vnd.dece.hd": {
    "source": "iana",
    "extensions": ["uvh","uvvh"]
  },
  "video/vnd.dece.mobile": {
    "source": "iana",
    "extensions": ["uvm","uvvm"]
  },
  "video/vnd.dece.mp4": {
    "source": "iana"
  },
  "video/vnd.dece.pd": {
    "source": "iana",
    "extensions": ["uvp","uvvp"]
  },
  "video/vnd.dece.sd": {
    "source": "iana",
    "extensions": ["uvs","uvvs"]
  },
  "video/vnd.dece.video": {
    "source": "iana",
    "extensions": ["uvv","uvvv"]
  },
  "video/vnd.directv.mpeg": {
    "source": "iana"
  },
  "video/vnd.directv.mpeg-tts": {
    "source": "iana"
  },
  "video/vnd.dlna.mpeg-tts": {
    "source": "iana"
  },
  "video/vnd.dvb.file": {
    "source": "iana",
    "extensions": ["dvb"]
  },
  "video/vnd.fvt": {
    "source": "iana",
    "extensions": ["fvt"]
  },
  "video/vnd.hns.video": {
    "source": "iana"
  },
  "video/vnd.iptvforum.1dparityfec-1010": {
    "source": "iana"
  },
  "video/vnd.iptvforum.1dparityfec-2005": {
    "source": "iana"
  },
  "video/vnd.iptvforum.2dparityfec-1010": {
    "source": "iana"
  },
  "video/vnd.iptvforum.2dparityfec-2005": {
    "source": "iana"
  },
  "video/vnd.iptvforum.ttsavc": {
    "source": "iana"
  },
  "video/vnd.iptvforum.ttsmpeg2": {
    "source": "iana"
  },
  "video/vnd.motorola.video": {
    "source": "iana"
  },
  "video/vnd.motorola.videop": {
    "source": "iana"
  },
  "video/vnd.mpegurl": {
    "source": "iana",
    "extensions": ["mxu","m4u"]
  },
  "video/vnd.ms-playready.media.pyv": {
    "source": "iana",
    "extensions": ["pyv"]
  },
  "video/vnd.nokia.interleaved-multimedia": {
    "source": "iana"
  },
  "video/vnd.nokia.mp4vr": {
    "source": "iana"
  },
  "video/vnd.nokia.videovoip": {
    "source": "iana"
  },
  "video/vnd.objectvideo": {
    "source": "iana"
  },
  "video/vnd.radgamettools.bink": {
    "source": "iana"
  },
  "video/vnd.radgamettools.smacker": {
    "source": "iana"
  },
  "video/vnd.sealed.mpeg1": {
    "source": "iana"
  },
  "video/vnd.sealed.mpeg4": {
    "source": "iana"
  },
  "video/vnd.sealed.swf": {
    "source": "iana"
  },
  "video/vnd.sealedmedia.softseal.mov": {
    "source": "iana"
  },
  "video/vnd.uvvu.mp4": {
    "source": "iana",
    "extensions": ["uvu","uvvu"]
  },
  "video/vnd.vivo": {
    "source": "iana",
    "extensions": ["viv"]
  },
  "video/vnd.youtube.yt": {
    "source": "iana"
  },
  "video/vp8": {
    "source": "iana"
  },
  "video/vp9": {
    "source": "iana"
  },
  "video/webm": {
    "source": "apache",
    "compressible": false,
    "extensions": ["webm"]
  },
  "video/x-f4v": {
    "source": "apache",
    "extensions": ["f4v"]
  },
  "video/x-fli": {
    "source": "apache",
    "extensions": ["fli"]
  },
  "video/x-flv": {
    "source": "apache",
    "compressible": false,
    "extensions": ["flv"]
  },
  "video/x-m4v": {
    "source": "apache",
    "extensions": ["m4v"]
  },
  "video/x-matroska": {
    "source": "apache",
    "compressible": false,
    "extensions": ["mkv","mk3d","mks"]
  },
  "video/x-mng": {
    "source": "apache",
    "extensions": ["mng"]
  },
  "video/x-ms-asf": {
    "source": "apache",
    "extensions": ["asf","asx"]
  },
  "video/x-ms-vob": {
    "source": "apache",
    "extensions": ["vob"]
  },
  "video/x-ms-wm": {
    "source": "apache",
    "extensions": ["wm"]
  },
  "video/x-ms-wmv": {
    "source": "apache",
    "compressible": false,
    "extensions": ["wmv"]
  },
  "video/x-ms-wmx": {
    "source": "apache",
    "extensions": ["wmx"]
  },
  "video/x-ms-wvx": {
    "source": "apache",
    "extensions": ["wvx"]
  },
  "video/x-msvideo": {
    "source": "apache",
    "extensions": ["avi"]
  },
  "video/x-sgi-movie": {
    "source": "apache",
    "extensions": ["movie"]
  },
  "video/x-smv": {
    "source": "apache",
    "extensions": ["smv"]
  },
  "x-conference/x-cooltalk": {
    "source": "apache",
    "extensions": ["ice"]
  },
  "x-shader/x-fragment": {
    "compressible": true
  },
  "x-shader/x-vertex": {
    "compressible": true
  }
}`);
const extensions = new Map();
const types1 = new Map();
function populateMaps(extensions1, types11) {
    const preference = [
        "nginx",
        "apache",
        undefined,
        "iana"
    ];
    for (const type of Object.keys(db)){
        const mime = db[type];
        const exts = mime.extensions;
        if (!exts || !exts.length) {
            continue;
        }
        extensions1.set(type, exts);
        for (const ext of exts){
            const current = types11.get(ext);
            if (current) {
                const from = preference.indexOf(db[current].source);
                const to = preference.indexOf(mime.source);
                if (current !== "application/octet-stream" && (from > to || from === to && current.substr(0, 12) === "application/")) {
                    continue;
                }
            }
            types11.set(ext, type);
        }
    }
}
populateMaps(extensions, types1);
function lookup1(path80) {
    const extension1 = extname2("x." + path80).toLowerCase().substr(1);
    return types1.get(extension1);
}
var reservedWords = {
    3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
    5: "class enum extends super const export import",
    6: "enum",
    strict: "implements interface let package private protected public static yield",
    strictBind: "eval arguments"
};
var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
var keywords = {
    5: ecma5AndLessKeywords,
    "5module": ecma5AndLessKeywords + " export import",
    6: ecma5AndLessKeywords + " const class extends export import super"
};
var keywordRelationalOperator = /^in(stanceof)?$/;
var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08C7\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\u9FFC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7BF\uA7C2-\uA7CA\uA7F5-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
var nonASCIIidentifierChars = "\u200C\u200D\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF\u1AC0\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F";
var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
var astralIdentifierStartCodes = [
    0,
    11,
    2,
    25,
    2,
    18,
    2,
    1,
    2,
    14,
    3,
    13,
    35,
    122,
    70,
    52,
    268,
    28,
    4,
    48,
    48,
    31,
    14,
    29,
    6,
    37,
    11,
    29,
    3,
    35,
    5,
    7,
    2,
    4,
    43,
    157,
    19,
    35,
    5,
    35,
    5,
    39,
    9,
    51,
    157,
    310,
    10,
    21,
    11,
    7,
    153,
    5,
    3,
    0,
    2,
    43,
    2,
    1,
    4,
    0,
    3,
    22,
    11,
    22,
    10,
    30,
    66,
    18,
    2,
    1,
    11,
    21,
    11,
    25,
    71,
    55,
    7,
    1,
    65,
    0,
    16,
    3,
    2,
    2,
    2,
    28,
    43,
    28,
    4,
    28,
    36,
    7,
    2,
    27,
    28,
    53,
    11,
    21,
    11,
    18,
    14,
    17,
    111,
    72,
    56,
    50,
    14,
    50,
    14,
    35,
    349,
    41,
    7,
    1,
    79,
    28,
    11,
    0,
    9,
    21,
    107,
    20,
    28,
    22,
    13,
    52,
    76,
    44,
    33,
    24,
    27,
    35,
    30,
    0,
    3,
    0,
    9,
    34,
    4,
    0,
    13,
    47,
    15,
    3,
    22,
    0,
    2,
    0,
    36,
    17,
    2,
    24,
    85,
    6,
    2,
    0,
    2,
    3,
    2,
    14,
    2,
    9,
    8,
    46,
    39,
    7,
    3,
    1,
    3,
    21,
    2,
    6,
    2,
    1,
    2,
    4,
    4,
    0,
    19,
    0,
    13,
    4,
    159,
    52,
    19,
    3,
    21,
    2,
    31,
    47,
    21,
    1,
    2,
    0,
    185,
    46,
    42,
    3,
    37,
    47,
    21,
    0,
    60,
    42,
    14,
    0,
    72,
    26,
    230,
    43,
    117,
    63,
    32,
    7,
    3,
    0,
    3,
    7,
    2,
    1,
    2,
    23,
    16,
    0,
    2,
    0,
    95,
    7,
    3,
    38,
    17,
    0,
    2,
    0,
    29,
    0,
    11,
    39,
    8,
    0,
    22,
    0,
    12,
    45,
    20,
    0,
    35,
    56,
    264,
    8,
    2,
    36,
    18,
    0,
    50,
    29,
    113,
    6,
    2,
    1,
    2,
    37,
    22,
    0,
    26,
    5,
    2,
    1,
    2,
    31,
    15,
    0,
    328,
    18,
    190,
    0,
    80,
    921,
    103,
    110,
    18,
    195,
    2749,
    1070,
    4050,
    582,
    8634,
    568,
    8,
    30,
    114,
    29,
    19,
    47,
    17,
    3,
    32,
    20,
    6,
    18,
    689,
    63,
    129,
    74,
    6,
    0,
    67,
    12,
    65,
    1,
    2,
    0,
    29,
    6135,
    9,
    1237,
    43,
    8,
    8952,
    286,
    50,
    2,
    18,
    3,
    9,
    395,
    2309,
    106,
    6,
    12,
    4,
    8,
    8,
    9,
    5991,
    84,
    2,
    70,
    2,
    1,
    3,
    0,
    3,
    1,
    3,
    3,
    2,
    11,
    2,
    0,
    2,
    6,
    2,
    64,
    2,
    3,
    3,
    7,
    2,
    6,
    2,
    27,
    2,
    3,
    2,
    4,
    2,
    0,
    4,
    6,
    2,
    339,
    3,
    24,
    2,
    24,
    2,
    30,
    2,
    24,
    2,
    30,
    2,
    24,
    2,
    30,
    2,
    24,
    2,
    30,
    2,
    24,
    2,
    7,
    2357,
    44,
    11,
    6,
    17,
    0,
    370,
    43,
    1301,
    196,
    60,
    67,
    8,
    0,
    1205,
    3,
    2,
    26,
    2,
    1,
    2,
    0,
    3,
    0,
    2,
    9,
    2,
    3,
    2,
    0,
    2,
    0,
    7,
    0,
    5,
    0,
    2,
    0,
    2,
    0,
    2,
    2,
    2,
    1,
    2,
    0,
    3,
    0,
    2,
    0,
    2,
    0,
    2,
    0,
    2,
    0,
    2,
    1,
    2,
    0,
    3,
    3,
    2,
    6,
    2,
    3,
    2,
    3,
    2,
    0,
    2,
    9,
    2,
    16,
    6,
    2,
    2,
    4,
    2,
    16,
    4421,
    42717,
    35,
    4148,
    12,
    221,
    3,
    5761,
    15,
    7472,
    3104,
    541,
    1507,
    4938
];
var astralIdentifierCodes = [
    509,
    0,
    227,
    0,
    150,
    4,
    294,
    9,
    1368,
    2,
    2,
    1,
    6,
    3,
    41,
    2,
    5,
    0,
    166,
    1,
    574,
    3,
    9,
    9,
    370,
    1,
    154,
    10,
    176,
    2,
    54,
    14,
    32,
    9,
    16,
    3,
    46,
    10,
    54,
    9,
    7,
    2,
    37,
    13,
    2,
    9,
    6,
    1,
    45,
    0,
    13,
    2,
    49,
    13,
    9,
    3,
    2,
    11,
    83,
    11,
    7,
    0,
    161,
    11,
    6,
    9,
    7,
    3,
    56,
    1,
    2,
    6,
    3,
    1,
    3,
    2,
    10,
    0,
    11,
    1,
    3,
    6,
    4,
    4,
    193,
    17,
    10,
    9,
    5,
    0,
    82,
    19,
    13,
    9,
    214,
    6,
    3,
    8,
    28,
    1,
    83,
    16,
    16,
    9,
    82,
    12,
    9,
    9,
    84,
    14,
    5,
    9,
    243,
    14,
    166,
    9,
    71,
    5,
    2,
    1,
    3,
    3,
    2,
    0,
    2,
    1,
    13,
    9,
    120,
    6,
    3,
    6,
    4,
    0,
    29,
    9,
    41,
    6,
    2,
    3,
    9,
    0,
    10,
    10,
    47,
    15,
    406,
    7,
    2,
    7,
    17,
    9,
    57,
    21,
    2,
    13,
    123,
    5,
    4,
    0,
    2,
    1,
    2,
    6,
    2,
    0,
    9,
    9,
    49,
    4,
    2,
    1,
    2,
    4,
    9,
    9,
    330,
    3,
    19306,
    9,
    135,
    4,
    60,
    6,
    26,
    9,
    1014,
    0,
    2,
    54,
    8,
    3,
    82,
    0,
    12,
    1,
    19628,
    1,
    5319,
    4,
    4,
    5,
    9,
    7,
    3,
    6,
    31,
    3,
    149,
    2,
    1418,
    49,
    513,
    54,
    5,
    49,
    9,
    0,
    15,
    0,
    23,
    4,
    2,
    14,
    1361,
    6,
    2,
    16,
    3,
    6,
    2,
    1,
    2,
    4,
    262,
    6,
    10,
    9,
    419,
    13,
    1495,
    6,
    110,
    6,
    6,
    9,
    4759,
    9,
    787719,
    239
];
function isInAstralSet(code24, set5) {
    var pos = 65536;
    for(var i = 0; i < set5.length; i += 2){
        pos += set5[i];
        if (pos > code24) {
            return false;
        }
        pos += set5[i + 1];
        if (pos >= code24) {
            return true;
        }
    }
}
function isIdentifierStart(code25, astral) {
    if (code25 < 65) {
        return code25 === 36;
    }
    if (code25 < 91) {
        return true;
    }
    if (code25 < 97) {
        return code25 === 95;
    }
    if (code25 < 123) {
        return true;
    }
    if (code25 <= 65535) {
        return code25 >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code25));
    }
    if (astral === false) {
        return false;
    }
    return isInAstralSet(code25, astralIdentifierStartCodes);
}
function isIdentifierChar(code26, astral) {
    if (code26 < 48) {
        return code26 === 36;
    }
    if (code26 < 58) {
        return true;
    }
    if (code26 < 65) {
        return false;
    }
    if (code26 < 91) {
        return true;
    }
    if (code26 < 97) {
        return code26 === 95;
    }
    if (code26 < 123) {
        return true;
    }
    if (code26 <= 65535) {
        return code26 >= 170 && nonASCIIidentifier.test(String.fromCharCode(code26));
    }
    if (astral === false) {
        return false;
    }
    return isInAstralSet(code26, astralIdentifierStartCodes) || isInAstralSet(code26, astralIdentifierCodes);
}
var TokenType = function TokenType2(label, conf) {
    if (conf === void 0) conf = {};
    this.label = label;
    this.keyword = conf.keyword;
    this.beforeExpr = !!conf.beforeExpr;
    this.startsExpr = !!conf.startsExpr;
    this.isLoop = !!conf.isLoop;
    this.isAssign = !!conf.isAssign;
    this.prefix = !!conf.prefix;
    this.postfix = !!conf.postfix;
    this.binop = conf.binop || null;
    this.updateContext = null;
};
function binop(name115, prec) {
    return new TokenType(name115, {
        beforeExpr: true,
        binop: prec
    });
}
var beforeExpr = {
    beforeExpr: true
}, startsExpr = {
    startsExpr: true
};
var keywords$1 = {};
function kw(name116, options) {
    if (options === void 0) options = {};
    options.keyword = name116;
    return keywords$1[name116] = new TokenType(name116, options);
}
var types2 = {
    num: new TokenType("num", startsExpr),
    regexp: new TokenType("regexp", startsExpr),
    string: new TokenType("string", startsExpr),
    name: new TokenType("name", startsExpr),
    eof: new TokenType("eof"),
    bracketL: new TokenType("[", {
        beforeExpr: true,
        startsExpr: true
    }),
    bracketR: new TokenType("]"),
    braceL: new TokenType("{", {
        beforeExpr: true,
        startsExpr: true
    }),
    braceR: new TokenType("}"),
    parenL: new TokenType("(", {
        beforeExpr: true,
        startsExpr: true
    }),
    parenR: new TokenType(")"),
    comma: new TokenType(",", beforeExpr),
    semi: new TokenType(";", beforeExpr),
    colon: new TokenType(":", beforeExpr),
    dot: new TokenType("."),
    question: new TokenType("?", beforeExpr),
    questionDot: new TokenType("?."),
    arrow: new TokenType("=>", beforeExpr),
    template: new TokenType("template"),
    invalidTemplate: new TokenType("invalidTemplate"),
    ellipsis: new TokenType("...", beforeExpr),
    backQuote: new TokenType("`", startsExpr),
    dollarBraceL: new TokenType("${", {
        beforeExpr: true,
        startsExpr: true
    }),
    eq: new TokenType("=", {
        beforeExpr: true,
        isAssign: true
    }),
    assign: new TokenType("_=", {
        beforeExpr: true,
        isAssign: true
    }),
    incDec: new TokenType("++/--", {
        prefix: true,
        postfix: true,
        startsExpr: true
    }),
    prefix: new TokenType("!/~", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    }),
    logicalOR: binop("||", 1),
    logicalAND: binop("&&", 2),
    bitwiseOR: binop("|", 3),
    bitwiseXOR: binop("^", 4),
    bitwiseAND: binop("&", 5),
    equality: binop("==/!=/===/!==", 6),
    relational: binop("</>/<=/>=", 7),
    bitShift: binop("<</>>/>>>", 8),
    plusMin: new TokenType("+/-", {
        beforeExpr: true,
        binop: 9,
        prefix: true,
        startsExpr: true
    }),
    modulo: binop("%", 10),
    star: binop("*", 10),
    slash: binop("/", 10),
    starstar: new TokenType("**", {
        beforeExpr: true
    }),
    coalesce: binop("??", 1),
    _break: kw("break"),
    _case: kw("case", beforeExpr),
    _catch: kw("catch"),
    _continue: kw("continue"),
    _debugger: kw("debugger"),
    _default: kw("default", beforeExpr),
    _do: kw("do", {
        isLoop: true,
        beforeExpr: true
    }),
    _else: kw("else", beforeExpr),
    _finally: kw("finally"),
    _for: kw("for", {
        isLoop: true
    }),
    _function: kw("function", startsExpr),
    _if: kw("if"),
    _return: kw("return", beforeExpr),
    _switch: kw("switch"),
    _throw: kw("throw", beforeExpr),
    _try: kw("try"),
    _var: kw("var"),
    _const: kw("const"),
    _while: kw("while", {
        isLoop: true
    }),
    _with: kw("with"),
    _new: kw("new", {
        beforeExpr: true,
        startsExpr: true
    }),
    _this: kw("this", startsExpr),
    _super: kw("super", startsExpr),
    _class: kw("class", startsExpr),
    _extends: kw("extends", beforeExpr),
    _export: kw("export"),
    _import: kw("import", startsExpr),
    _null: kw("null", startsExpr),
    _true: kw("true", startsExpr),
    _false: kw("false", startsExpr),
    _in: kw("in", {
        beforeExpr: true,
        binop: 7
    }),
    _instanceof: kw("instanceof", {
        beforeExpr: true,
        binop: 7
    }),
    _typeof: kw("typeof", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    }),
    _void: kw("void", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    }),
    _delete: kw("delete", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    })
};
var lineBreak = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code27, ecma2019String) {
    return code27 === 10 || code27 === 13 || !ecma2019String && (code27 === 8232 || code27 === 8233);
}
var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref = Object.prototype;
var hasOwnProperty15 = ref.hasOwnProperty;
var toString2 = ref.toString;
function has(obj, propName) {
    return hasOwnProperty15.call(obj, propName);
}
var isArray1 = Array.isArray || function(obj) {
    return toString2.call(obj) === "[object Array]";
};
function wordsRegexp(words) {
    return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$");
}
var Position = function Position2(line, col) {
    this.line = line;
    this.column = col;
};
Position.prototype.offset = function offset(n10) {
    return new Position(this.line, this.column + n10);
};
var SourceLocation = function SourceLocation2(p, start, end) {
    this.start = start;
    this.end = end;
    if (p.sourceFile !== null) {
        this.source = p.sourceFile;
    }
};
function getLineInfo(input, offset2) {
    for(var line = 1, cur = 0;;){
        lineBreakG.lastIndex = cur;
        var match = lineBreakG.exec(input);
        if (match && match.index < offset2) {
            ++line;
            cur = match.index + match[0].length;
        } else {
            return new Position(line, offset2 - cur);
        }
    }
}
var defaultOptions = {
    ecmaVersion: 10,
    sourceType: "script",
    onInsertedSemicolon: null,
    onTrailingComma: null,
    allowReserved: null,
    allowReturnOutsideFunction: false,
    allowImportExportEverywhere: false,
    allowAwaitOutsideFunction: false,
    allowHashBang: false,
    locations: false,
    onToken: null,
    onComment: null,
    ranges: false,
    program: null,
    sourceFile: null,
    directSourceFile: null,
    preserveParens: false
};
function getOptions(opts) {
    var options = {};
    for(var opt in defaultOptions){
        options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
    }
    if (options.ecmaVersion >= 2015) {
        options.ecmaVersion -= 2009;
    }
    if (options.allowReserved == null) {
        options.allowReserved = options.ecmaVersion < 5;
    }
    if (isArray1(options.onToken)) {
        var tokens = options.onToken;
        options.onToken = function(token) {
            return tokens.push(token);
        };
    }
    if (isArray1(options.onComment)) {
        options.onComment = pushComment(options, options.onComment);
    }
    return options;
}
function pushComment(options, array) {
    return function(block, text, start, end, startLoc, endLoc) {
        var comment = {
            type: block ? "Block" : "Line",
            value: text,
            start,
            end
        };
        if (options.locations) {
            comment.loc = new SourceLocation(this, startLoc, endLoc);
        }
        if (options.ranges) {
            comment.range = [
                start,
                end
            ];
        }
        array.push(comment);
    };
}
var SCOPE_TOP = 1, SCOPE_FUNCTION = 2, SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, SCOPE_ASYNC = 4, SCOPE_GENERATOR = 8, SCOPE_ARROW = 16, SCOPE_SIMPLE_CATCH = 32, SCOPE_SUPER = 64, SCOPE_DIRECT_SUPER = 128;
function functionFlags(async, generator) {
    return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0);
}
var BIND_NONE = 0, BIND_VAR = 1, BIND_LEXICAL = 2, BIND_FUNCTION = 3, BIND_SIMPLE_CATCH = 4, BIND_OUTSIDE = 5;
var Parser = function Parser2(options, input, startPos) {
    this.options = options = getOptions(options);
    this.sourceFile = options.sourceFile;
    this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
    var reserved = "";
    if (options.allowReserved !== true) {
        for(var v = options.ecmaVersion;; v--){
            if (reserved = reservedWords[v]) {
                break;
            }
        }
        if (options.sourceType === "module") {
            reserved += " await";
        }
    }
    this.reservedWords = wordsRegexp(reserved);
    var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
    this.reservedWordsStrict = wordsRegexp(reservedStrict);
    this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
    this.input = String(input);
    this.containsEsc = false;
    if (startPos) {
        this.pos = startPos;
        this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
        this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
    } else {
        this.pos = this.lineStart = 0;
        this.curLine = 1;
    }
    this.type = types2.eof;
    this.value = null;
    this.start = this.end = this.pos;
    this.startLoc = this.endLoc = this.curPosition();
    this.lastTokEndLoc = this.lastTokStartLoc = null;
    this.lastTokStart = this.lastTokEnd = this.pos;
    this.context = this.initialContext();
    this.exprAllowed = true;
    this.inModule = options.sourceType === "module";
    this.strict = this.inModule || this.strictDirective(this.pos);
    this.potentialArrowAt = -1;
    this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
    this.labels = [];
    this.undefinedExports = {};
    if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
        this.skipLineComment(2);
    }
    this.scopeStack = [];
    this.enterScope(SCOPE_TOP);
    this.regexpState = null;
};
var prototypeAccessors = {
    inFunction: {
        configurable: true
    },
    inGenerator: {
        configurable: true
    },
    inAsync: {
        configurable: true
    },
    allowSuper: {
        configurable: true
    },
    allowDirectSuper: {
        configurable: true
    },
    treatFunctionsAsVar: {
        configurable: true
    }
};
Parser.prototype.parse = function parse() {
    var node = this.options.program || this.startNode();
    this.nextToken();
    return this.parseTopLevel(node);
};
prototypeAccessors.inFunction.get = function() {
    return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
};
prototypeAccessors.inGenerator.get = function() {
    return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0;
};
prototypeAccessors.inAsync.get = function() {
    return (this.currentVarScope().flags & SCOPE_ASYNC) > 0;
};
prototypeAccessors.allowSuper.get = function() {
    return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
};
prototypeAccessors.allowDirectSuper.get = function() {
    return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
};
prototypeAccessors.treatFunctionsAsVar.get = function() {
    return this.treatFunctionsAsVarInScope(this.currentScope());
};
Parser.prototype.inNonArrowFunction = function inNonArrowFunction() {
    return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
};
Parser.extend = function extend() {
    var plugins = [], len9 = arguments.length;
    while(len9--)plugins[len9] = arguments[len9];
    var cls = this;
    for(var i = 0; i < plugins.length; i++){
        cls = plugins[i](cls);
    }
    return cls;
};
Parser.parse = function parse2(input, options) {
    return new this(options, input).parse();
};
Parser.parseExpressionAt = function parseExpressionAt(input, pos, options) {
    var parser = new this(options, input, pos);
    parser.nextToken();
    return parser.parseExpression();
};
Parser.tokenizer = function tokenizer(input, options) {
    return new this(options, input);
};
Object.defineProperties(Parser.prototype, prototypeAccessors);
var pp = Parser.prototype;
var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
pp.strictDirective = function(start) {
    for(;;){
        skipWhiteSpace.lastIndex = start;
        start += skipWhiteSpace.exec(this.input)[0].length;
        var match = literal.exec(this.input.slice(start));
        if (!match) {
            return false;
        }
        if ((match[1] || match[2]) === "use strict") {
            skipWhiteSpace.lastIndex = start + match[0].length;
            var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
            var next = this.input.charAt(end);
            return next === ";" || next === "}" || lineBreak.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
        }
        start += match[0].length;
        skipWhiteSpace.lastIndex = start;
        start += skipWhiteSpace.exec(this.input)[0].length;
        if (this.input[start] === ";") {
            start++;
        }
    }
};
pp.eat = function(type) {
    if (this.type === type) {
        this.next();
        return true;
    } else {
        return false;
    }
};
pp.isContextual = function(name117) {
    return this.type === types2.name && this.value === name117 && !this.containsEsc;
};
pp.eatContextual = function(name118) {
    if (!this.isContextual(name118)) {
        return false;
    }
    this.next();
    return true;
};
pp.expectContextual = function(name119) {
    if (!this.eatContextual(name119)) {
        this.unexpected();
    }
};
pp.canInsertSemicolon = function() {
    return this.type === types2.eof || this.type === types2.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp.insertSemicolon = function() {
    if (this.canInsertSemicolon()) {
        if (this.options.onInsertedSemicolon) {
            this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
        }
        return true;
    }
};
pp.semicolon = function() {
    if (!this.eat(types2.semi) && !this.insertSemicolon()) {
        this.unexpected();
    }
};
pp.afterTrailingComma = function(tokType, notNext) {
    if (this.type === tokType) {
        if (this.options.onTrailingComma) {
            this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
        }
        if (!notNext) {
            this.next();
        }
        return true;
    }
};
pp.expect = function(type) {
    this.eat(type) || this.unexpected();
};
pp.unexpected = function(pos) {
    this.raise(pos != null ? pos : this.start, "Unexpected token");
};
function DestructuringErrors() {
    this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
}
pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
    if (!refDestructuringErrors) {
        return;
    }
    if (refDestructuringErrors.trailingComma > -1) {
        this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element");
    }
    var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
    if (parens > -1) {
        this.raiseRecoverable(parens, "Parenthesized pattern");
    }
};
pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
    if (!refDestructuringErrors) {
        return false;
    }
    var shorthandAssign = refDestructuringErrors.shorthandAssign;
    var doubleProto = refDestructuringErrors.doubleProto;
    if (!andThrow) {
        return shorthandAssign >= 0 || doubleProto >= 0;
    }
    if (shorthandAssign >= 0) {
        this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns");
    }
    if (doubleProto >= 0) {
        this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property");
    }
};
pp.checkYieldAwaitInDefaultParams = function() {
    if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) {
        this.raise(this.yieldPos, "Yield expression cannot be a default value");
    }
    if (this.awaitPos) {
        this.raise(this.awaitPos, "Await expression cannot be a default value");
    }
};
pp.isSimpleAssignTarget = function(expr) {
    if (expr.type === "ParenthesizedExpression") {
        return this.isSimpleAssignTarget(expr.expression);
    }
    return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$1 = Parser.prototype;
pp$1.parseTopLevel = function(node) {
    var exports = {};
    if (!node.body) {
        node.body = [];
    }
    while(this.type !== types2.eof){
        var stmt = this.parseStatement(null, true, exports);
        node.body.push(stmt);
    }
    if (this.inModule) {
        for(var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1){
            var name120 = list[i];
            this.raiseRecoverable(this.undefinedExports[name120].start, "Export '" + name120 + "' is not defined");
        }
    }
    this.adaptDirectivePrologue(node.body);
    this.next();
    node.sourceType = this.options.sourceType;
    return this.finishNode(node, "Program");
};
var loopLabel = {
    kind: "loop"
}, switchLabel = {
    kind: "switch"
};
pp$1.isLet = function(context) {
    if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
        return false;
    }
    skipWhiteSpace.lastIndex = this.pos;
    var skip = skipWhiteSpace.exec(this.input);
    var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
    if (nextCh === 91) {
        return true;
    }
    if (context) {
        return false;
    }
    if (nextCh === 123) {
        return true;
    }
    if (isIdentifierStart(nextCh, true)) {
        var pos = next + 1;
        while(isIdentifierChar(this.input.charCodeAt(pos), true)){
            ++pos;
        }
        var ident = this.input.slice(next, pos);
        if (!keywordRelationalOperator.test(ident)) {
            return true;
        }
    }
    return false;
};
pp$1.isAsyncFunction = function() {
    if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
        return false;
    }
    skipWhiteSpace.lastIndex = this.pos;
    var skip = skipWhiteSpace.exec(this.input);
    var next = this.pos + skip[0].length;
    return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)));
};
pp$1.parseStatement = function(context, topLevel, exports) {
    var starttype = this.type, node = this.startNode(), kind;
    if (this.isLet(context)) {
        starttype = types2._var;
        kind = "let";
    }
    switch(starttype){
        case types2._break:
        case types2._continue:
            return this.parseBreakContinueStatement(node, starttype.keyword);
        case types2._debugger:
            return this.parseDebuggerStatement(node);
        case types2._do:
            return this.parseDoStatement(node);
        case types2._for:
            return this.parseForStatement(node);
        case types2._function:
            if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
                this.unexpected();
            }
            return this.parseFunctionStatement(node, false, !context);
        case types2._class:
            if (context) {
                this.unexpected();
            }
            return this.parseClass(node, true);
        case types2._if:
            return this.parseIfStatement(node);
        case types2._return:
            return this.parseReturnStatement(node);
        case types2._switch:
            return this.parseSwitchStatement(node);
        case types2._throw:
            return this.parseThrowStatement(node);
        case types2._try:
            return this.parseTryStatement(node);
        case types2._const:
        case types2._var:
            kind = kind || this.value;
            if (context && kind !== "var") {
                this.unexpected();
            }
            return this.parseVarStatement(node, kind);
        case types2._while:
            return this.parseWhileStatement(node);
        case types2._with:
            return this.parseWithStatement(node);
        case types2.braceL:
            return this.parseBlock(true, node);
        case types2.semi:
            return this.parseEmptyStatement(node);
        case types2._export:
        case types2._import:
            if (this.options.ecmaVersion > 10 && starttype === types2._import) {
                skipWhiteSpace.lastIndex = this.pos;
                var skip = skipWhiteSpace.exec(this.input);
                var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
                if (nextCh === 40 || nextCh === 46) {
                    return this.parseExpressionStatement(node, this.parseExpression());
                }
            }
            if (!this.options.allowImportExportEverywhere) {
                if (!topLevel) {
                    this.raise(this.start, "'import' and 'export' may only appear at the top level");
                }
                if (!this.inModule) {
                    this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
                }
            }
            return starttype === types2._import ? this.parseImport(node) : this.parseExport(node, exports);
        default:
            if (this.isAsyncFunction()) {
                if (context) {
                    this.unexpected();
                }
                this.next();
                return this.parseFunctionStatement(node, true, !context);
            }
            var maybeName = this.value, expr = this.parseExpression();
            if (starttype === types2.name && expr.type === "Identifier" && this.eat(types2.colon)) {
                return this.parseLabeledStatement(node, maybeName, expr, context);
            } else {
                return this.parseExpressionStatement(node, expr);
            }
    }
};
pp$1.parseBreakContinueStatement = function(node, keyword) {
    var isBreak = keyword === "break";
    this.next();
    if (this.eat(types2.semi) || this.insertSemicolon()) {
        node.label = null;
    } else if (this.type !== types2.name) {
        this.unexpected();
    } else {
        node.label = this.parseIdent();
        this.semicolon();
    }
    var i = 0;
    for(; i < this.labels.length; ++i){
        var lab = this.labels[i];
        if (node.label == null || lab.name === node.label.name) {
            if (lab.kind != null && (isBreak || lab.kind === "loop")) {
                break;
            }
            if (node.label && isBreak) {
                break;
            }
        }
    }
    if (i === this.labels.length) {
        this.raise(node.start, "Unsyntactic " + keyword);
    }
    return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$1.parseDebuggerStatement = function(node) {
    this.next();
    this.semicolon();
    return this.finishNode(node, "DebuggerStatement");
};
pp$1.parseDoStatement = function(node) {
    this.next();
    this.labels.push(loopLabel);
    node.body = this.parseStatement("do");
    this.labels.pop();
    this.expect(types2._while);
    node.test = this.parseParenExpression();
    if (this.options.ecmaVersion >= 6) {
        this.eat(types2.semi);
    } else {
        this.semicolon();
    }
    return this.finishNode(node, "DoWhileStatement");
};
pp$1.parseForStatement = function(node) {
    this.next();
    var awaitAt = this.options.ecmaVersion >= 9 && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction) && this.eatContextual("await") ? this.lastTokStart : -1;
    this.labels.push(loopLabel);
    this.enterScope(0);
    this.expect(types2.parenL);
    if (this.type === types2.semi) {
        if (awaitAt > -1) {
            this.unexpected(awaitAt);
        }
        return this.parseFor(node, null);
    }
    var isLet = this.isLet();
    if (this.type === types2._var || this.type === types2._const || isLet) {
        var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
        this.next();
        this.parseVar(init$1, true, kind);
        this.finishNode(init$1, "VariableDeclaration");
        if ((this.type === types2._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
            if (this.options.ecmaVersion >= 9) {
                if (this.type === types2._in) {
                    if (awaitAt > -1) {
                        this.unexpected(awaitAt);
                    }
                } else {
                    node.await = awaitAt > -1;
                }
            }
            return this.parseForIn(node, init$1);
        }
        if (awaitAt > -1) {
            this.unexpected(awaitAt);
        }
        return this.parseFor(node, init$1);
    }
    var refDestructuringErrors = new DestructuringErrors();
    var init1 = this.parseExpression(true, refDestructuringErrors);
    if (this.type === types2._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
        if (this.options.ecmaVersion >= 9) {
            if (this.type === types2._in) {
                if (awaitAt > -1) {
                    this.unexpected(awaitAt);
                }
            } else {
                node.await = awaitAt > -1;
            }
        }
        this.toAssignable(init1, false, refDestructuringErrors);
        this.checkLVal(init1);
        return this.parseForIn(node, init1);
    } else {
        this.checkExpressionErrors(refDestructuringErrors, true);
    }
    if (awaitAt > -1) {
        this.unexpected(awaitAt);
    }
    return this.parseFor(node, init1);
};
pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
    this.next();
    return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync);
};
pp$1.parseIfStatement = function(node) {
    this.next();
    node.test = this.parseParenExpression();
    node.consequent = this.parseStatement("if");
    node.alternate = this.eat(types2._else) ? this.parseStatement("if") : null;
    return this.finishNode(node, "IfStatement");
};
pp$1.parseReturnStatement = function(node) {
    if (!this.inFunction && !this.options.allowReturnOutsideFunction) {
        this.raise(this.start, "'return' outside of function");
    }
    this.next();
    if (this.eat(types2.semi) || this.insertSemicolon()) {
        node.argument = null;
    } else {
        node.argument = this.parseExpression();
        this.semicolon();
    }
    return this.finishNode(node, "ReturnStatement");
};
pp$1.parseSwitchStatement = function(node) {
    this.next();
    node.discriminant = this.parseParenExpression();
    node.cases = [];
    this.expect(types2.braceL);
    this.labels.push(switchLabel);
    this.enterScope(0);
    var cur;
    for(var sawDefault = false; this.type !== types2.braceR;){
        if (this.type === types2._case || this.type === types2._default) {
            var isCase = this.type === types2._case;
            if (cur) {
                this.finishNode(cur, "SwitchCase");
            }
            node.cases.push(cur = this.startNode());
            cur.consequent = [];
            this.next();
            if (isCase) {
                cur.test = this.parseExpression();
            } else {
                if (sawDefault) {
                    this.raiseRecoverable(this.lastTokStart, "Multiple default clauses");
                }
                sawDefault = true;
                cur.test = null;
            }
            this.expect(types2.colon);
        } else {
            if (!cur) {
                this.unexpected();
            }
            cur.consequent.push(this.parseStatement(null));
        }
    }
    this.exitScope();
    if (cur) {
        this.finishNode(cur, "SwitchCase");
    }
    this.next();
    this.labels.pop();
    return this.finishNode(node, "SwitchStatement");
};
pp$1.parseThrowStatement = function(node) {
    this.next();
    if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) {
        this.raise(this.lastTokEnd, "Illegal newline after throw");
    }
    node.argument = this.parseExpression();
    this.semicolon();
    return this.finishNode(node, "ThrowStatement");
};
var empty = [];
pp$1.parseTryStatement = function(node) {
    this.next();
    node.block = this.parseBlock();
    node.handler = null;
    if (this.type === types2._catch) {
        var clause = this.startNode();
        this.next();
        if (this.eat(types2.parenL)) {
            clause.param = this.parseBindingAtom();
            var simple1 = clause.param.type === "Identifier";
            this.enterScope(simple1 ? SCOPE_SIMPLE_CATCH : 0);
            this.checkLVal(clause.param, simple1 ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
            this.expect(types2.parenR);
        } else {
            if (this.options.ecmaVersion < 10) {
                this.unexpected();
            }
            clause.param = null;
            this.enterScope(0);
        }
        clause.body = this.parseBlock(false);
        this.exitScope();
        node.handler = this.finishNode(clause, "CatchClause");
    }
    node.finalizer = this.eat(types2._finally) ? this.parseBlock() : null;
    if (!node.handler && !node.finalizer) {
        this.raise(node.start, "Missing catch or finally clause");
    }
    return this.finishNode(node, "TryStatement");
};
pp$1.parseVarStatement = function(node, kind) {
    this.next();
    this.parseVar(node, false, kind);
    this.semicolon();
    return this.finishNode(node, "VariableDeclaration");
};
pp$1.parseWhileStatement = function(node) {
    this.next();
    node.test = this.parseParenExpression();
    this.labels.push(loopLabel);
    node.body = this.parseStatement("while");
    this.labels.pop();
    return this.finishNode(node, "WhileStatement");
};
pp$1.parseWithStatement = function(node) {
    if (this.strict) {
        this.raise(this.start, "'with' in strict mode");
    }
    this.next();
    node.object = this.parseParenExpression();
    node.body = this.parseStatement("with");
    return this.finishNode(node, "WithStatement");
};
pp$1.parseEmptyStatement = function(node) {
    this.next();
    return this.finishNode(node, "EmptyStatement");
};
pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
    for(var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1){
        var label = list[i$1];
        if (label.name === maybeName) {
            this.raise(expr.start, "Label '" + maybeName + "' is already declared");
        }
    }
    var kind = this.type.isLoop ? "loop" : this.type === types2._switch ? "switch" : null;
    for(var i = this.labels.length - 1; i >= 0; i--){
        var label$1 = this.labels[i];
        if (label$1.statementStart === node.start) {
            label$1.statementStart = this.start;
            label$1.kind = kind;
        } else {
            break;
        }
    }
    this.labels.push({
        name: maybeName,
        kind,
        statementStart: this.start
    });
    node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
    this.labels.pop();
    node.label = expr;
    return this.finishNode(node, "LabeledStatement");
};
pp$1.parseExpressionStatement = function(node, expr) {
    node.expression = expr;
    this.semicolon();
    return this.finishNode(node, "ExpressionStatement");
};
pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
    if (createNewLexicalScope === void 0) createNewLexicalScope = true;
    if (node === void 0) node = this.startNode();
    node.body = [];
    this.expect(types2.braceL);
    if (createNewLexicalScope) {
        this.enterScope(0);
    }
    while(this.type !== types2.braceR){
        var stmt = this.parseStatement(null);
        node.body.push(stmt);
    }
    if (exitStrict) {
        this.strict = false;
    }
    this.next();
    if (createNewLexicalScope) {
        this.exitScope();
    }
    return this.finishNode(node, "BlockStatement");
};
pp$1.parseFor = function(node, init2) {
    node.init = init2;
    this.expect(types2.semi);
    node.test = this.type === types2.semi ? null : this.parseExpression();
    this.expect(types2.semi);
    node.update = this.type === types2.parenR ? null : this.parseExpression();
    this.expect(types2.parenR);
    node.body = this.parseStatement("for");
    this.exitScope();
    this.labels.pop();
    return this.finishNode(node, "ForStatement");
};
pp$1.parseForIn = function(node, init3) {
    var isForIn = this.type === types2._in;
    this.next();
    if (init3.type === "VariableDeclaration" && init3.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init3.kind !== "var" || init3.declarations[0].id.type !== "Identifier")) {
        this.raise(init3.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
    } else if (init3.type === "AssignmentPattern") {
        this.raise(init3.start, "Invalid left-hand side in for-loop");
    }
    node.left = init3;
    node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
    this.expect(types2.parenR);
    node.body = this.parseStatement("for");
    this.exitScope();
    this.labels.pop();
    return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
};
pp$1.parseVar = function(node, isFor, kind) {
    node.declarations = [];
    node.kind = kind;
    for(;;){
        var decl = this.startNode();
        this.parseVarId(decl, kind);
        if (this.eat(types2.eq)) {
            decl.init = this.parseMaybeAssign(isFor);
        } else if (kind === "const" && !(this.type === types2._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
            this.unexpected();
        } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types2._in || this.isContextual("of")))) {
            this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
        } else {
            decl.init = null;
        }
        node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
        if (!this.eat(types2.comma)) {
            break;
        }
    }
    return node;
};
pp$1.parseVarId = function(decl, kind) {
    decl.id = this.parseBindingAtom();
    this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
};
var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
    this.initFunction(node);
    if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
        if (this.type === types2.star && statement & FUNC_HANGING_STATEMENT) {
            this.unexpected();
        }
        node.generator = this.eat(types2.star);
    }
    if (this.options.ecmaVersion >= 8) {
        node.async = !!isAsync;
    }
    if (statement & FUNC_STATEMENT) {
        node.id = statement & FUNC_NULLABLE_ID && this.type !== types2.name ? null : this.parseIdent();
        if (node.id && !(statement & FUNC_HANGING_STATEMENT)) {
            this.checkLVal(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION);
        }
    }
    var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    this.enterScope(functionFlags(node.async, node.generator));
    if (!(statement & FUNC_STATEMENT)) {
        node.id = this.type === types2.name ? this.parseIdent() : null;
    }
    this.parseFunctionParams(node);
    this.parseFunctionBody(node, allowExpressionBody, false);
    this.yieldPos = oldYieldPos;
    this.awaitPos = oldAwaitPos;
    this.awaitIdentPos = oldAwaitIdentPos;
    return this.finishNode(node, statement & FUNC_STATEMENT ? "FunctionDeclaration" : "FunctionExpression");
};
pp$1.parseFunctionParams = function(node) {
    this.expect(types2.parenL);
    node.params = this.parseBindingList(types2.parenR, false, this.options.ecmaVersion >= 8);
    this.checkYieldAwaitInDefaultParams();
};
pp$1.parseClass = function(node, isStatement) {
    this.next();
    var oldStrict = this.strict;
    this.strict = true;
    this.parseClassId(node, isStatement);
    this.parseClassSuper(node);
    var classBody = this.startNode();
    var hadConstructor = false;
    classBody.body = [];
    this.expect(types2.braceL);
    while(this.type !== types2.braceR){
        var element = this.parseClassElement(node.superClass !== null);
        if (element) {
            classBody.body.push(element);
            if (element.type === "MethodDefinition" && element.kind === "constructor") {
                if (hadConstructor) {
                    this.raise(element.start, "Duplicate constructor in the same class");
                }
                hadConstructor = true;
            }
        }
    }
    this.strict = oldStrict;
    this.next();
    node.body = this.finishNode(classBody, "ClassBody");
    return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$1.parseClassElement = function(constructorAllowsSuper) {
    var this$1 = this;
    if (this.eat(types2.semi)) {
        return null;
    }
    var method = this.startNode();
    var tryContextual = function(k, noLineBreak) {
        if (noLineBreak === void 0) noLineBreak = false;
        var start = this$1.start, startLoc = this$1.startLoc;
        if (!this$1.eatContextual(k)) {
            return false;
        }
        if (this$1.type !== types2.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) {
            return true;
        }
        if (method.key) {
            this$1.unexpected();
        }
        method.computed = false;
        method.key = this$1.startNodeAt(start, startLoc);
        method.key.name = k;
        this$1.finishNode(method.key, "Identifier");
        return false;
    };
    method.kind = "method";
    method.static = tryContextual("static");
    var isGenerator = this.eat(types2.star);
    var isAsync = false;
    if (!isGenerator) {
        if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
            isAsync = true;
            isGenerator = this.options.ecmaVersion >= 9 && this.eat(types2.star);
        } else if (tryContextual("get")) {
            method.kind = "get";
        } else if (tryContextual("set")) {
            method.kind = "set";
        }
    }
    if (!method.key) {
        this.parsePropertyName(method);
    }
    var key = method.key;
    var allowsDirectSuper = false;
    if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
        if (method.kind !== "method") {
            this.raise(key.start, "Constructor can't have get/set modifier");
        }
        if (isGenerator) {
            this.raise(key.start, "Constructor can't be a generator");
        }
        if (isAsync) {
            this.raise(key.start, "Constructor can't be an async method");
        }
        method.kind = "constructor";
        allowsDirectSuper = constructorAllowsSuper;
    } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
        this.raise(key.start, "Classes may not have a static property named prototype");
    }
    this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
    if (method.kind === "get" && method.value.params.length !== 0) {
        this.raiseRecoverable(method.value.start, "getter should have no params");
    }
    if (method.kind === "set" && method.value.params.length !== 1) {
        this.raiseRecoverable(method.value.start, "setter should have exactly one param");
    }
    if (method.kind === "set" && method.value.params[0].type === "RestElement") {
        this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params");
    }
    return method;
};
pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
    method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
    return this.finishNode(method, "MethodDefinition");
};
pp$1.parseClassId = function(node, isStatement) {
    if (this.type === types2.name) {
        node.id = this.parseIdent();
        if (isStatement) {
            this.checkLVal(node.id, BIND_LEXICAL, false);
        }
    } else {
        if (isStatement === true) {
            this.unexpected();
        }
        node.id = null;
    }
};
pp$1.parseClassSuper = function(node) {
    node.superClass = this.eat(types2._extends) ? this.parseExprSubscripts() : null;
};
pp$1.parseExport = function(node, exports) {
    this.next();
    if (this.eat(types2.star)) {
        if (this.options.ecmaVersion >= 11) {
            if (this.eatContextual("as")) {
                node.exported = this.parseIdent(true);
                this.checkExport(exports, node.exported.name, this.lastTokStart);
            } else {
                node.exported = null;
            }
        }
        this.expectContextual("from");
        if (this.type !== types2.string) {
            this.unexpected();
        }
        node.source = this.parseExprAtom();
        this.semicolon();
        return this.finishNode(node, "ExportAllDeclaration");
    }
    if (this.eat(types2._default)) {
        this.checkExport(exports, "default", this.lastTokStart);
        var isAsync;
        if (this.type === types2._function || (isAsync = this.isAsyncFunction())) {
            var fNode = this.startNode();
            this.next();
            if (isAsync) {
                this.next();
            }
            node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
        } else if (this.type === types2._class) {
            var cNode = this.startNode();
            node.declaration = this.parseClass(cNode, "nullableID");
        } else {
            node.declaration = this.parseMaybeAssign();
            this.semicolon();
        }
        return this.finishNode(node, "ExportDefaultDeclaration");
    }
    if (this.shouldParseExportStatement()) {
        node.declaration = this.parseStatement(null);
        if (node.declaration.type === "VariableDeclaration") {
            this.checkVariableExport(exports, node.declaration.declarations);
        } else {
            this.checkExport(exports, node.declaration.id.name, node.declaration.id.start);
        }
        node.specifiers = [];
        node.source = null;
    } else {
        node.declaration = null;
        node.specifiers = this.parseExportSpecifiers(exports);
        if (this.eatContextual("from")) {
            if (this.type !== types2.string) {
                this.unexpected();
            }
            node.source = this.parseExprAtom();
        } else {
            for(var i = 0, list = node.specifiers; i < list.length; i += 1){
                var spec = list[i];
                this.checkUnreserved(spec.local);
                this.checkLocalExport(spec.local);
            }
            node.source = null;
        }
        this.semicolon();
    }
    return this.finishNode(node, "ExportNamedDeclaration");
};
pp$1.checkExport = function(exports, name121, pos) {
    if (!exports) {
        return;
    }
    if (has(exports, name121)) {
        this.raiseRecoverable(pos, "Duplicate export '" + name121 + "'");
    }
    exports[name121] = true;
};
pp$1.checkPatternExport = function(exports, pat) {
    var type = pat.type;
    if (type === "Identifier") {
        this.checkExport(exports, pat.name, pat.start);
    } else if (type === "ObjectPattern") {
        for(var i = 0, list = pat.properties; i < list.length; i += 1){
            var prop = list[i];
            this.checkPatternExport(exports, prop);
        }
    } else if (type === "ArrayPattern") {
        for(var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1){
            var elt = list$1[i$1];
            if (elt) {
                this.checkPatternExport(exports, elt);
            }
        }
    } else if (type === "Property") {
        this.checkPatternExport(exports, pat.value);
    } else if (type === "AssignmentPattern") {
        this.checkPatternExport(exports, pat.left);
    } else if (type === "RestElement") {
        this.checkPatternExport(exports, pat.argument);
    } else if (type === "ParenthesizedExpression") {
        this.checkPatternExport(exports, pat.expression);
    }
};
pp$1.checkVariableExport = function(exports, decls) {
    if (!exports) {
        return;
    }
    for(var i = 0, list = decls; i < list.length; i += 1){
        var decl = list[i];
        this.checkPatternExport(exports, decl.id);
    }
};
pp$1.shouldParseExportStatement = function() {
    return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$1.parseExportSpecifiers = function(exports) {
    var nodes = [], first = true;
    this.expect(types2.braceL);
    while(!this.eat(types2.braceR)){
        if (!first) {
            this.expect(types2.comma);
            if (this.afterTrailingComma(types2.braceR)) {
                break;
            }
        } else {
            first = false;
        }
        var node = this.startNode();
        node.local = this.parseIdent(true);
        node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
        this.checkExport(exports, node.exported.name, node.exported.start);
        nodes.push(this.finishNode(node, "ExportSpecifier"));
    }
    return nodes;
};
pp$1.parseImport = function(node) {
    this.next();
    if (this.type === types2.string) {
        node.specifiers = empty;
        node.source = this.parseExprAtom();
    } else {
        node.specifiers = this.parseImportSpecifiers();
        this.expectContextual("from");
        node.source = this.type === types2.string ? this.parseExprAtom() : this.unexpected();
    }
    this.semicolon();
    return this.finishNode(node, "ImportDeclaration");
};
pp$1.parseImportSpecifiers = function() {
    var nodes = [], first = true;
    if (this.type === types2.name) {
        var node = this.startNode();
        node.local = this.parseIdent();
        this.checkLVal(node.local, BIND_LEXICAL);
        nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
        if (!this.eat(types2.comma)) {
            return nodes;
        }
    }
    if (this.type === types2.star) {
        var node$1 = this.startNode();
        this.next();
        this.expectContextual("as");
        node$1.local = this.parseIdent();
        this.checkLVal(node$1.local, BIND_LEXICAL);
        nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
        return nodes;
    }
    this.expect(types2.braceL);
    while(!this.eat(types2.braceR)){
        if (!first) {
            this.expect(types2.comma);
            if (this.afterTrailingComma(types2.braceR)) {
                break;
            }
        } else {
            first = false;
        }
        var node$2 = this.startNode();
        node$2.imported = this.parseIdent(true);
        if (this.eatContextual("as")) {
            node$2.local = this.parseIdent();
        } else {
            this.checkUnreserved(node$2.imported);
            node$2.local = node$2.imported;
        }
        this.checkLVal(node$2.local, BIND_LEXICAL);
        nodes.push(this.finishNode(node$2, "ImportSpecifier"));
    }
    return nodes;
};
pp$1.adaptDirectivePrologue = function(statements) {
    for(var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i){
        statements[i].directive = statements[i].expression.raw.slice(1, -1);
    }
};
pp$1.isDirectiveCandidate = function(statement) {
    return statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && (this.input[statement.start] === '"' || this.input[statement.start] === "'");
};
var pp$2 = Parser.prototype;
pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
    if (this.options.ecmaVersion >= 6 && node) {
        switch(node.type){
            case "Identifier":
                if (this.inAsync && node.name === "await") {
                    this.raise(node.start, "Cannot use 'await' as identifier inside an async function");
                }
                break;
            case "ObjectPattern":
            case "ArrayPattern":
            case "RestElement":
                break;
            case "ObjectExpression":
                node.type = "ObjectPattern";
                if (refDestructuringErrors) {
                    this.checkPatternErrors(refDestructuringErrors, true);
                }
                for(var i = 0, list = node.properties; i < list.length; i += 1){
                    var prop = list[i];
                    this.toAssignable(prop, isBinding);
                    if (prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")) {
                        this.raise(prop.argument.start, "Unexpected token");
                    }
                }
                break;
            case "Property":
                if (node.kind !== "init") {
                    this.raise(node.key.start, "Object pattern can't contain getter or setter");
                }
                this.toAssignable(node.value, isBinding);
                break;
            case "ArrayExpression":
                node.type = "ArrayPattern";
                if (refDestructuringErrors) {
                    this.checkPatternErrors(refDestructuringErrors, true);
                }
                this.toAssignableList(node.elements, isBinding);
                break;
            case "SpreadElement":
                node.type = "RestElement";
                this.toAssignable(node.argument, isBinding);
                if (node.argument.type === "AssignmentPattern") {
                    this.raise(node.argument.start, "Rest elements cannot have a default value");
                }
                break;
            case "AssignmentExpression":
                if (node.operator !== "=") {
                    this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
                }
                node.type = "AssignmentPattern";
                delete node.operator;
                this.toAssignable(node.left, isBinding);
            case "AssignmentPattern":
                break;
            case "ParenthesizedExpression":
                this.toAssignable(node.expression, isBinding, refDestructuringErrors);
                break;
            case "ChainExpression":
                this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
                break;
            case "MemberExpression":
                if (!isBinding) {
                    break;
                }
            default:
                this.raise(node.start, "Assigning to rvalue");
        }
    } else if (refDestructuringErrors) {
        this.checkPatternErrors(refDestructuringErrors, true);
    }
    return node;
};
pp$2.toAssignableList = function(exprList, isBinding) {
    var end = exprList.length;
    for(var i = 0; i < end; i++){
        var elt = exprList[i];
        if (elt) {
            this.toAssignable(elt, isBinding);
        }
    }
    if (end) {
        var last = exprList[end - 1];
        if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") {
            this.unexpected(last.argument.start);
        }
    }
    return exprList;
};
pp$2.parseSpread = function(refDestructuringErrors) {
    var node = this.startNode();
    this.next();
    node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    return this.finishNode(node, "SpreadElement");
};
pp$2.parseRestBinding = function() {
    var node = this.startNode();
    this.next();
    if (this.options.ecmaVersion === 6 && this.type !== types2.name) {
        this.unexpected();
    }
    node.argument = this.parseBindingAtom();
    return this.finishNode(node, "RestElement");
};
pp$2.parseBindingAtom = function() {
    if (this.options.ecmaVersion >= 6) {
        switch(this.type){
            case types2.bracketL:
                var node = this.startNode();
                this.next();
                node.elements = this.parseBindingList(types2.bracketR, true, true);
                return this.finishNode(node, "ArrayPattern");
            case types2.braceL:
                return this.parseObj(true);
        }
    }
    return this.parseIdent();
};
pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
    var elts = [], first = true;
    while(!this.eat(close)){
        if (first) {
            first = false;
        } else {
            this.expect(types2.comma);
        }
        if (allowEmpty && this.type === types2.comma) {
            elts.push(null);
        } else if (allowTrailingComma && this.afterTrailingComma(close)) {
            break;
        } else if (this.type === types2.ellipsis) {
            var rest = this.parseRestBinding();
            this.parseBindingListItem(rest);
            elts.push(rest);
            if (this.type === types2.comma) {
                this.raise(this.start, "Comma is not permitted after the rest element");
            }
            this.expect(close);
            break;
        } else {
            var elem = this.parseMaybeDefault(this.start, this.startLoc);
            this.parseBindingListItem(elem);
            elts.push(elem);
        }
    }
    return elts;
};
pp$2.parseBindingListItem = function(param) {
    return param;
};
pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
    left = left || this.parseBindingAtom();
    if (this.options.ecmaVersion < 6 || !this.eat(types2.eq)) {
        return left;
    }
    var node = this.startNodeAt(startPos, startLoc);
    node.left = left;
    node.right = this.parseMaybeAssign();
    return this.finishNode(node, "AssignmentPattern");
};
pp$2.checkLVal = function(expr, bindingType, checkClashes) {
    if (bindingType === void 0) bindingType = BIND_NONE;
    switch(expr.type){
        case "Identifier":
            if (bindingType === BIND_LEXICAL && expr.name === "let") {
                this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
            }
            if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
                this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
            }
            if (checkClashes) {
                if (has(checkClashes, expr.name)) {
                    this.raiseRecoverable(expr.start, "Argument name clash");
                }
                checkClashes[expr.name] = true;
            }
            if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) {
                this.declareName(expr.name, bindingType, expr.start);
            }
            break;
        case "ChainExpression":
            this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
            break;
        case "MemberExpression":
            if (bindingType) {
                this.raiseRecoverable(expr.start, "Binding member expression");
            }
            break;
        case "ObjectPattern":
            for(var i = 0, list = expr.properties; i < list.length; i += 1){
                var prop = list[i];
                this.checkLVal(prop, bindingType, checkClashes);
            }
            break;
        case "Property":
            this.checkLVal(expr.value, bindingType, checkClashes);
            break;
        case "ArrayPattern":
            for(var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1){
                var elem = list$1[i$1];
                if (elem) {
                    this.checkLVal(elem, bindingType, checkClashes);
                }
            }
            break;
        case "AssignmentPattern":
            this.checkLVal(expr.left, bindingType, checkClashes);
            break;
        case "RestElement":
            this.checkLVal(expr.argument, bindingType, checkClashes);
            break;
        case "ParenthesizedExpression":
            this.checkLVal(expr.expression, bindingType, checkClashes);
            break;
        default:
            this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue");
    }
};
var pp$3 = Parser.prototype;
pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
    if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") {
        return;
    }
    if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) {
        return;
    }
    var key = prop.key;
    var name122;
    switch(key.type){
        case "Identifier":
            name122 = key.name;
            break;
        case "Literal":
            name122 = String(key.value);
            break;
        default:
            return;
    }
    var kind = prop.kind;
    if (this.options.ecmaVersion >= 6) {
        if (name122 === "__proto__" && kind === "init") {
            if (propHash.proto) {
                if (refDestructuringErrors) {
                    if (refDestructuringErrors.doubleProto < 0) {
                        refDestructuringErrors.doubleProto = key.start;
                    }
                } else {
                    this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
                }
            }
            propHash.proto = true;
        }
        return;
    }
    name122 = "$" + name122;
    var other = propHash[name122];
    if (other) {
        var redefinition;
        if (kind === "init") {
            redefinition = this.strict && other.init || other.get || other.set;
        } else {
            redefinition = other.init || other[kind];
        }
        if (redefinition) {
            this.raiseRecoverable(key.start, "Redefinition of property");
        }
    } else {
        other = propHash[name122] = {
            init: false,
            get: false,
            set: false
        };
    }
    other[kind] = true;
};
pp$3.parseExpression = function(noIn, refDestructuringErrors) {
    var startPos = this.start, startLoc = this.startLoc;
    var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
    if (this.type === types2.comma) {
        var node = this.startNodeAt(startPos, startLoc);
        node.expressions = [
            expr
        ];
        while(this.eat(types2.comma)){
            node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors));
        }
        return this.finishNode(node, "SequenceExpression");
    }
    return expr;
};
pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
    if (this.isContextual("yield")) {
        if (this.inGenerator) {
            return this.parseYield(noIn);
        } else {
            this.exprAllowed = false;
        }
    }
    var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
    if (refDestructuringErrors) {
        oldParenAssign = refDestructuringErrors.parenthesizedAssign;
        oldTrailingComma = refDestructuringErrors.trailingComma;
        refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
    } else {
        refDestructuringErrors = new DestructuringErrors();
        ownDestructuringErrors = true;
    }
    var startPos = this.start, startLoc = this.startLoc;
    if (this.type === types2.parenL || this.type === types2.name) {
        this.potentialArrowAt = this.start;
    }
    var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
    if (afterLeftParse) {
        left = afterLeftParse.call(this, left, startPos, startLoc);
    }
    if (this.type.isAssign) {
        var node = this.startNodeAt(startPos, startLoc);
        node.operator = this.value;
        node.left = this.type === types2.eq ? this.toAssignable(left, false, refDestructuringErrors) : left;
        if (!ownDestructuringErrors) {
            refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
        }
        if (refDestructuringErrors.shorthandAssign >= node.left.start) {
            refDestructuringErrors.shorthandAssign = -1;
        }
        this.checkLVal(left);
        this.next();
        node.right = this.parseMaybeAssign(noIn);
        return this.finishNode(node, "AssignmentExpression");
    } else {
        if (ownDestructuringErrors) {
            this.checkExpressionErrors(refDestructuringErrors, true);
        }
    }
    if (oldParenAssign > -1) {
        refDestructuringErrors.parenthesizedAssign = oldParenAssign;
    }
    if (oldTrailingComma > -1) {
        refDestructuringErrors.trailingComma = oldTrailingComma;
    }
    return left;
};
pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
    var startPos = this.start, startLoc = this.startLoc;
    var expr = this.parseExprOps(noIn, refDestructuringErrors);
    if (this.checkExpressionErrors(refDestructuringErrors)) {
        return expr;
    }
    if (this.eat(types2.question)) {
        var node = this.startNodeAt(startPos, startLoc);
        node.test = expr;
        node.consequent = this.parseMaybeAssign();
        this.expect(types2.colon);
        node.alternate = this.parseMaybeAssign(noIn);
        return this.finishNode(node, "ConditionalExpression");
    }
    return expr;
};
pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
    var startPos = this.start, startLoc = this.startLoc;
    var expr = this.parseMaybeUnary(refDestructuringErrors, false);
    if (this.checkExpressionErrors(refDestructuringErrors)) {
        return expr;
    }
    return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn);
};
pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
    var prec = this.type.binop;
    if (prec != null && (!noIn || this.type !== types2._in)) {
        if (prec > minPrec) {
            var logical = this.type === types2.logicalOR || this.type === types2.logicalAND;
            var coalesce = this.type === types2.coalesce;
            if (coalesce) {
                prec = types2.logicalAND.binop;
            }
            var op = this.value;
            this.next();
            var startPos = this.start, startLoc = this.startLoc;
            var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
            var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
            if (logical && this.type === types2.coalesce || coalesce && (this.type === types2.logicalOR || this.type === types2.logicalAND)) {
                this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
            }
            return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
        }
    }
    return left;
};
pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
    var node = this.startNodeAt(startPos, startLoc);
    node.left = left;
    node.operator = op;
    node.right = right;
    return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression");
};
pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
    var startPos = this.start, startLoc = this.startLoc, expr;
    if (this.isContextual("await") && (this.inAsync || !this.inFunction && this.options.allowAwaitOutsideFunction)) {
        expr = this.parseAwait();
        sawUnary = true;
    } else if (this.type.prefix) {
        var node = this.startNode(), update = this.type === types2.incDec;
        node.operator = this.value;
        node.prefix = true;
        this.next();
        node.argument = this.parseMaybeUnary(null, true);
        this.checkExpressionErrors(refDestructuringErrors, true);
        if (update) {
            this.checkLVal(node.argument);
        } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") {
            this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
        } else {
            sawUnary = true;
        }
        expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
    } else {
        expr = this.parseExprSubscripts(refDestructuringErrors);
        if (this.checkExpressionErrors(refDestructuringErrors)) {
            return expr;
        }
        while(this.type.postfix && !this.canInsertSemicolon()){
            var node$1 = this.startNodeAt(startPos, startLoc);
            node$1.operator = this.value;
            node$1.prefix = false;
            node$1.argument = expr;
            this.checkLVal(expr);
            this.next();
            expr = this.finishNode(node$1, "UpdateExpression");
        }
    }
    if (!sawUnary && this.eat(types2.starstar)) {
        return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false);
    } else {
        return expr;
    }
};
pp$3.parseExprSubscripts = function(refDestructuringErrors) {
    var startPos = this.start, startLoc = this.startLoc;
    var expr = this.parseExprAtom(refDestructuringErrors);
    if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") {
        return expr;
    }
    var result = this.parseSubscripts(expr, startPos, startLoc);
    if (refDestructuringErrors && result.type === "MemberExpression") {
        if (refDestructuringErrors.parenthesizedAssign >= result.start) {
            refDestructuringErrors.parenthesizedAssign = -1;
        }
        if (refDestructuringErrors.parenthesizedBind >= result.start) {
            refDestructuringErrors.parenthesizedBind = -1;
        }
    }
    return result;
};
pp$3.parseSubscripts = function(base6, startPos, startLoc, noCalls) {
    var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base6.type === "Identifier" && base6.name === "async" && this.lastTokEnd === base6.end && !this.canInsertSemicolon() && base6.end - base6.start === 5 && this.potentialArrowAt === base6.start;
    var optionalChained = false;
    while(true){
        var element = this.parseSubscript(base6, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
        if (element.optional) {
            optionalChained = true;
        }
        if (element === base6 || element.type === "ArrowFunctionExpression") {
            if (optionalChained) {
                var chainNode = this.startNodeAt(startPos, startLoc);
                chainNode.expression = element;
                element = this.finishNode(chainNode, "ChainExpression");
            }
            return element;
        }
        base6 = element;
    }
};
pp$3.parseSubscript = function(base7, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
    var optionalSupported = this.options.ecmaVersion >= 11;
    var optional = optionalSupported && this.eat(types2.questionDot);
    if (noCalls && optional) {
        this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
    }
    var computed = this.eat(types2.bracketL);
    if (computed || optional && this.type !== types2.parenL && this.type !== types2.backQuote || this.eat(types2.dot)) {
        var node = this.startNodeAt(startPos, startLoc);
        node.object = base7;
        node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
        node.computed = !!computed;
        if (computed) {
            this.expect(types2.bracketR);
        }
        if (optionalSupported) {
            node.optional = optional;
        }
        base7 = this.finishNode(node, "MemberExpression");
    } else if (!noCalls && this.eat(types2.parenL)) {
        var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
        this.yieldPos = 0;
        this.awaitPos = 0;
        this.awaitIdentPos = 0;
        var exprList = this.parseExprList(types2.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
        if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types2.arrow)) {
            this.checkPatternErrors(refDestructuringErrors, false);
            this.checkYieldAwaitInDefaultParams();
            if (this.awaitIdentPos > 0) {
                this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function");
            }
            this.yieldPos = oldYieldPos;
            this.awaitPos = oldAwaitPos;
            this.awaitIdentPos = oldAwaitIdentPos;
            return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true);
        }
        this.checkExpressionErrors(refDestructuringErrors, true);
        this.yieldPos = oldYieldPos || this.yieldPos;
        this.awaitPos = oldAwaitPos || this.awaitPos;
        this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
        var node$1 = this.startNodeAt(startPos, startLoc);
        node$1.callee = base7;
        node$1.arguments = exprList;
        if (optionalSupported) {
            node$1.optional = optional;
        }
        base7 = this.finishNode(node$1, "CallExpression");
    } else if (this.type === types2.backQuote) {
        if (optional || optionalChained) {
            this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
        }
        var node$2 = this.startNodeAt(startPos, startLoc);
        node$2.tag = base7;
        node$2.quasi = this.parseTemplate({
            isTagged: true
        });
        base7 = this.finishNode(node$2, "TaggedTemplateExpression");
    }
    return base7;
};
pp$3.parseExprAtom = function(refDestructuringErrors) {
    if (this.type === types2.slash) {
        this.readRegexp();
    }
    var node, canBeArrow = this.potentialArrowAt === this.start;
    switch(this.type){
        case types2._super:
            if (!this.allowSuper) {
                this.raise(this.start, "'super' keyword outside a method");
            }
            node = this.startNode();
            this.next();
            if (this.type === types2.parenL && !this.allowDirectSuper) {
                this.raise(node.start, "super() call outside constructor of a subclass");
            }
            if (this.type !== types2.dot && this.type !== types2.bracketL && this.type !== types2.parenL) {
                this.unexpected();
            }
            return this.finishNode(node, "Super");
        case types2._this:
            node = this.startNode();
            this.next();
            return this.finishNode(node, "ThisExpression");
        case types2.name:
            var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
            var id = this.parseIdent(false);
            if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types2._function)) {
                return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true);
            }
            if (canBeArrow && !this.canInsertSemicolon()) {
                if (this.eat(types2.arrow)) {
                    return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [
                        id
                    ], false);
                }
                if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types2.name && !containsEsc) {
                    id = this.parseIdent(false);
                    if (this.canInsertSemicolon() || !this.eat(types2.arrow)) {
                        this.unexpected();
                    }
                    return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [
                        id
                    ], true);
                }
            }
            return id;
        case types2.regexp:
            var value = this.value;
            node = this.parseLiteral(value.value);
            node.regex = {
                pattern: value.pattern,
                flags: value.flags
            };
            return node;
        case types2.num:
        case types2.string:
            return this.parseLiteral(this.value);
        case types2._null:
        case types2._true:
        case types2._false:
            node = this.startNode();
            node.value = this.type === types2._null ? null : this.type === types2._true;
            node.raw = this.type.keyword;
            this.next();
            return this.finishNode(node, "Literal");
        case types2.parenL:
            var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
            if (refDestructuringErrors) {
                if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) {
                    refDestructuringErrors.parenthesizedAssign = start;
                }
                if (refDestructuringErrors.parenthesizedBind < 0) {
                    refDestructuringErrors.parenthesizedBind = start;
                }
            }
            return expr;
        case types2.bracketL:
            node = this.startNode();
            this.next();
            node.elements = this.parseExprList(types2.bracketR, true, true, refDestructuringErrors);
            return this.finishNode(node, "ArrayExpression");
        case types2.braceL:
            return this.parseObj(false, refDestructuringErrors);
        case types2._function:
            node = this.startNode();
            this.next();
            return this.parseFunction(node, 0);
        case types2._class:
            return this.parseClass(this.startNode(), false);
        case types2._new:
            return this.parseNew();
        case types2.backQuote:
            return this.parseTemplate();
        case types2._import:
            if (this.options.ecmaVersion >= 11) {
                return this.parseExprImport();
            } else {
                return this.unexpected();
            }
        default:
            this.unexpected();
    }
};
pp$3.parseExprImport = function() {
    var node = this.startNode();
    if (this.containsEsc) {
        this.raiseRecoverable(this.start, "Escape sequence in keyword import");
    }
    var meta = this.parseIdent(true);
    switch(this.type){
        case types2.parenL:
            return this.parseDynamicImport(node);
        case types2.dot:
            node.meta = meta;
            return this.parseImportMeta(node);
        default:
            this.unexpected();
    }
};
pp$3.parseDynamicImport = function(node) {
    this.next();
    node.source = this.parseMaybeAssign();
    if (!this.eat(types2.parenR)) {
        var errorPos = this.start;
        if (this.eat(types2.comma) && this.eat(types2.parenR)) {
            this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
        } else {
            this.unexpected(errorPos);
        }
    }
    return this.finishNode(node, "ImportExpression");
};
pp$3.parseImportMeta = function(node) {
    this.next();
    var containsEsc = this.containsEsc;
    node.property = this.parseIdent(true);
    if (node.property.name !== "meta") {
        this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'");
    }
    if (containsEsc) {
        this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters");
    }
    if (this.options.sourceType !== "module") {
        this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
    }
    return this.finishNode(node, "MetaProperty");
};
pp$3.parseLiteral = function(value) {
    var node = this.startNode();
    node.value = value;
    node.raw = this.input.slice(this.start, this.end);
    if (node.raw.charCodeAt(node.raw.length - 1) === 110) {
        node.bigint = node.raw.slice(0, -1).replace(/_/g, "");
    }
    this.next();
    return this.finishNode(node, "Literal");
};
pp$3.parseParenExpression = function() {
    this.expect(types2.parenL);
    var val = this.parseExpression();
    this.expect(types2.parenR);
    return val;
};
pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
    var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
    if (this.options.ecmaVersion >= 6) {
        this.next();
        var innerStartPos = this.start, innerStartLoc = this.startLoc;
        var exprList = [], first = true, lastIsComma = false;
        var refDestructuringErrors = new DestructuringErrors(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
        this.yieldPos = 0;
        this.awaitPos = 0;
        while(this.type !== types2.parenR){
            first ? first = false : this.expect(types2.comma);
            if (allowTrailingComma && this.afterTrailingComma(types2.parenR, true)) {
                lastIsComma = true;
                break;
            } else if (this.type === types2.ellipsis) {
                spreadStart = this.start;
                exprList.push(this.parseParenItem(this.parseRestBinding()));
                if (this.type === types2.comma) {
                    this.raise(this.start, "Comma is not permitted after the rest element");
                }
                break;
            } else {
                exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
            }
        }
        var innerEndPos = this.start, innerEndLoc = this.startLoc;
        this.expect(types2.parenR);
        if (canBeArrow && !this.canInsertSemicolon() && this.eat(types2.arrow)) {
            this.checkPatternErrors(refDestructuringErrors, false);
            this.checkYieldAwaitInDefaultParams();
            this.yieldPos = oldYieldPos;
            this.awaitPos = oldAwaitPos;
            return this.parseParenArrowList(startPos, startLoc, exprList);
        }
        if (!exprList.length || lastIsComma) {
            this.unexpected(this.lastTokStart);
        }
        if (spreadStart) {
            this.unexpected(spreadStart);
        }
        this.checkExpressionErrors(refDestructuringErrors, true);
        this.yieldPos = oldYieldPos || this.yieldPos;
        this.awaitPos = oldAwaitPos || this.awaitPos;
        if (exprList.length > 1) {
            val = this.startNodeAt(innerStartPos, innerStartLoc);
            val.expressions = exprList;
            this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
        } else {
            val = exprList[0];
        }
    } else {
        val = this.parseParenExpression();
    }
    if (this.options.preserveParens) {
        var par = this.startNodeAt(startPos, startLoc);
        par.expression = val;
        return this.finishNode(par, "ParenthesizedExpression");
    } else {
        return val;
    }
};
pp$3.parseParenItem = function(item) {
    return item;
};
pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
    return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
};
var empty$1 = [];
pp$3.parseNew = function() {
    if (this.containsEsc) {
        this.raiseRecoverable(this.start, "Escape sequence in keyword new");
    }
    var node = this.startNode();
    var meta = this.parseIdent(true);
    if (this.options.ecmaVersion >= 6 && this.eat(types2.dot)) {
        node.meta = meta;
        var containsEsc = this.containsEsc;
        node.property = this.parseIdent(true);
        if (node.property.name !== "target") {
            this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'");
        }
        if (containsEsc) {
            this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters");
        }
        if (!this.inNonArrowFunction()) {
            this.raiseRecoverable(node.start, "'new.target' can only be used in functions");
        }
        return this.finishNode(node, "MetaProperty");
    }
    var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types2._import;
    node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
    if (isImport && node.callee.type === "ImportExpression") {
        this.raise(startPos, "Cannot use new with import()");
    }
    if (this.eat(types2.parenL)) {
        node.arguments = this.parseExprList(types2.parenR, this.options.ecmaVersion >= 8, false);
    } else {
        node.arguments = empty$1;
    }
    return this.finishNode(node, "NewExpression");
};
pp$3.parseTemplateElement = function(ref2) {
    var isTagged = ref2.isTagged;
    var elem = this.startNode();
    if (this.type === types2.invalidTemplate) {
        if (!isTagged) {
            this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
        }
        elem.value = {
            raw: this.value,
            cooked: null
        };
    } else {
        elem.value = {
            raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
            cooked: this.value
        };
    }
    this.next();
    elem.tail = this.type === types2.backQuote;
    return this.finishNode(elem, "TemplateElement");
};
pp$3.parseTemplate = function(ref2) {
    if (ref2 === void 0) ref2 = {};
    var isTagged = ref2.isTagged;
    if (isTagged === void 0) isTagged = false;
    var node = this.startNode();
    this.next();
    node.expressions = [];
    var curElt = this.parseTemplateElement({
        isTagged
    });
    node.quasis = [
        curElt
    ];
    while(!curElt.tail){
        if (this.type === types2.eof) {
            this.raise(this.pos, "Unterminated template literal");
        }
        this.expect(types2.dollarBraceL);
        node.expressions.push(this.parseExpression());
        this.expect(types2.braceR);
        node.quasis.push(curElt = this.parseTemplateElement({
            isTagged
        }));
    }
    this.next();
    return this.finishNode(node, "TemplateLiteral");
};
pp$3.isAsyncProp = function(prop) {
    return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types2.name || this.type === types2.num || this.type === types2.string || this.type === types2.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types2.star) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$3.parseObj = function(isPattern, refDestructuringErrors) {
    var node = this.startNode(), first = true, propHash = {};
    node.properties = [];
    this.next();
    while(!this.eat(types2.braceR)){
        if (!first) {
            this.expect(types2.comma);
            if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types2.braceR)) {
                break;
            }
        } else {
            first = false;
        }
        var prop = this.parseProperty(isPattern, refDestructuringErrors);
        if (!isPattern) {
            this.checkPropClash(prop, propHash, refDestructuringErrors);
        }
        node.properties.push(prop);
    }
    return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
};
pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
    var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
    if (this.options.ecmaVersion >= 9 && this.eat(types2.ellipsis)) {
        if (isPattern) {
            prop.argument = this.parseIdent(false);
            if (this.type === types2.comma) {
                this.raise(this.start, "Comma is not permitted after the rest element");
            }
            return this.finishNode(prop, "RestElement");
        }
        if (this.type === types2.parenL && refDestructuringErrors) {
            if (refDestructuringErrors.parenthesizedAssign < 0) {
                refDestructuringErrors.parenthesizedAssign = this.start;
            }
            if (refDestructuringErrors.parenthesizedBind < 0) {
                refDestructuringErrors.parenthesizedBind = this.start;
            }
        }
        prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
        if (this.type === types2.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
            refDestructuringErrors.trailingComma = this.start;
        }
        return this.finishNode(prop, "SpreadElement");
    }
    if (this.options.ecmaVersion >= 6) {
        prop.method = false;
        prop.shorthand = false;
        if (isPattern || refDestructuringErrors) {
            startPos = this.start;
            startLoc = this.startLoc;
        }
        if (!isPattern) {
            isGenerator = this.eat(types2.star);
        }
    }
    var containsEsc = this.containsEsc;
    this.parsePropertyName(prop);
    if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
        isAsync = true;
        isGenerator = this.options.ecmaVersion >= 9 && this.eat(types2.star);
        this.parsePropertyName(prop, refDestructuringErrors);
    } else {
        isAsync = false;
    }
    this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
    return this.finishNode(prop, "Property");
};
pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
    if ((isGenerator || isAsync) && this.type === types2.colon) {
        this.unexpected();
    }
    if (this.eat(types2.colon)) {
        prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
        prop.kind = "init";
    } else if (this.options.ecmaVersion >= 6 && this.type === types2.parenL) {
        if (isPattern) {
            this.unexpected();
        }
        prop.kind = "init";
        prop.method = true;
        prop.value = this.parseMethod(isGenerator, isAsync);
    } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && this.type !== types2.comma && this.type !== types2.braceR && this.type !== types2.eq) {
        if (isGenerator || isAsync) {
            this.unexpected();
        }
        prop.kind = prop.key.name;
        this.parsePropertyName(prop);
        prop.value = this.parseMethod(false);
        var paramCount = prop.kind === "get" ? 0 : 1;
        if (prop.value.params.length !== paramCount) {
            var start = prop.value.start;
            if (prop.kind === "get") {
                this.raiseRecoverable(start, "getter should have no params");
            } else {
                this.raiseRecoverable(start, "setter should have exactly one param");
            }
        } else {
            if (prop.kind === "set" && prop.value.params[0].type === "RestElement") {
                this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params");
            }
        }
    } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
        if (isGenerator || isAsync) {
            this.unexpected();
        }
        this.checkUnreserved(prop.key);
        if (prop.key.name === "await" && !this.awaitIdentPos) {
            this.awaitIdentPos = startPos;
        }
        prop.kind = "init";
        if (isPattern) {
            prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
        } else if (this.type === types2.eq && refDestructuringErrors) {
            if (refDestructuringErrors.shorthandAssign < 0) {
                refDestructuringErrors.shorthandAssign = this.start;
            }
            prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
        } else {
            prop.value = prop.key;
        }
        prop.shorthand = true;
    } else {
        this.unexpected();
    }
};
pp$3.parsePropertyName = function(prop) {
    if (this.options.ecmaVersion >= 6) {
        if (this.eat(types2.bracketL)) {
            prop.computed = true;
            prop.key = this.parseMaybeAssign();
            this.expect(types2.bracketR);
            return prop.key;
        } else {
            prop.computed = false;
        }
    }
    return prop.key = this.type === types2.num || this.type === types2.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never");
};
pp$3.initFunction = function(node) {
    node.id = null;
    if (this.options.ecmaVersion >= 6) {
        node.generator = node.expression = false;
    }
    if (this.options.ecmaVersion >= 8) {
        node.async = false;
    }
};
pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
    var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.initFunction(node);
    if (this.options.ecmaVersion >= 6) {
        node.generator = isGenerator;
    }
    if (this.options.ecmaVersion >= 8) {
        node.async = !!isAsync;
    }
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
    this.expect(types2.parenL);
    node.params = this.parseBindingList(types2.parenR, false, this.options.ecmaVersion >= 8);
    this.checkYieldAwaitInDefaultParams();
    this.parseFunctionBody(node, false, true);
    this.yieldPos = oldYieldPos;
    this.awaitPos = oldAwaitPos;
    this.awaitIdentPos = oldAwaitIdentPos;
    return this.finishNode(node, "FunctionExpression");
};
pp$3.parseArrowExpression = function(node, params, isAsync) {
    var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
    this.initFunction(node);
    if (this.options.ecmaVersion >= 8) {
        node.async = !!isAsync;
    }
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    node.params = this.toAssignableList(params, true);
    this.parseFunctionBody(node, true, false);
    this.yieldPos = oldYieldPos;
    this.awaitPos = oldAwaitPos;
    this.awaitIdentPos = oldAwaitIdentPos;
    return this.finishNode(node, "ArrowFunctionExpression");
};
pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
    var isExpression = isArrowFunction && this.type !== types2.braceL;
    var oldStrict = this.strict, useStrict = false;
    if (isExpression) {
        node.body = this.parseMaybeAssign();
        node.expression = true;
        this.checkParams(node, false);
    } else {
        var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
        if (!oldStrict || nonSimple) {
            useStrict = this.strictDirective(this.end);
            if (useStrict && nonSimple) {
                this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list");
            }
        }
        var oldLabels = this.labels;
        this.labels = [];
        if (useStrict) {
            this.strict = true;
        }
        this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
        if (this.strict && node.id) {
            this.checkLVal(node.id, BIND_OUTSIDE);
        }
        node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
        node.expression = false;
        this.adaptDirectivePrologue(node.body.body);
        this.labels = oldLabels;
    }
    this.exitScope();
};
pp$3.isSimpleParamList = function(params) {
    for(var i = 0, list = params; i < list.length; i += 1){
        var param = list[i];
        if (param.type !== "Identifier") {
            return false;
        }
    }
    return true;
};
pp$3.checkParams = function(node, allowDuplicates) {
    var nameHash = {};
    for(var i = 0, list = node.params; i < list.length; i += 1){
        var param = list[i];
        this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash);
    }
};
pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
    var elts = [], first = true;
    while(!this.eat(close)){
        if (!first) {
            this.expect(types2.comma);
            if (allowTrailingComma && this.afterTrailingComma(close)) {
                break;
            }
        } else {
            first = false;
        }
        var elt = void 0;
        if (allowEmpty && this.type === types2.comma) {
            elt = null;
        } else if (this.type === types2.ellipsis) {
            elt = this.parseSpread(refDestructuringErrors);
            if (refDestructuringErrors && this.type === types2.comma && refDestructuringErrors.trailingComma < 0) {
                refDestructuringErrors.trailingComma = this.start;
            }
        } else {
            elt = this.parseMaybeAssign(false, refDestructuringErrors);
        }
        elts.push(elt);
    }
    return elts;
};
pp$3.checkUnreserved = function(ref2) {
    var start = ref2.start;
    var end = ref2.end;
    var name123 = ref2.name;
    if (this.inGenerator && name123 === "yield") {
        this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
    }
    if (this.inAsync && name123 === "await") {
        this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
    }
    if (this.keywords.test(name123)) {
        this.raise(start, "Unexpected keyword '" + name123 + "'");
    }
    if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
        return;
    }
    var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
    if (re.test(name123)) {
        if (!this.inAsync && name123 === "await") {
            this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
        }
        this.raiseRecoverable(start, "The keyword '" + name123 + "' is reserved");
    }
};
pp$3.parseIdent = function(liberal, isBinding) {
    var node = this.startNode();
    if (this.type === types2.name) {
        node.name = this.value;
    } else if (this.type.keyword) {
        node.name = this.type.keyword;
        if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
            this.context.pop();
        }
    } else {
        this.unexpected();
    }
    this.next(!!liberal);
    this.finishNode(node, "Identifier");
    if (!liberal) {
        this.checkUnreserved(node);
        if (node.name === "await" && !this.awaitIdentPos) {
            this.awaitIdentPos = node.start;
        }
    }
    return node;
};
pp$3.parseYield = function(noIn) {
    if (!this.yieldPos) {
        this.yieldPos = this.start;
    }
    var node = this.startNode();
    this.next();
    if (this.type === types2.semi || this.canInsertSemicolon() || this.type !== types2.star && !this.type.startsExpr) {
        node.delegate = false;
        node.argument = null;
    } else {
        node.delegate = this.eat(types2.star);
        node.argument = this.parseMaybeAssign(noIn);
    }
    return this.finishNode(node, "YieldExpression");
};
pp$3.parseAwait = function() {
    if (!this.awaitPos) {
        this.awaitPos = this.start;
    }
    var node = this.startNode();
    this.next();
    node.argument = this.parseMaybeUnary(null, false);
    return this.finishNode(node, "AwaitExpression");
};
var pp$4 = Parser.prototype;
pp$4.raise = function(pos, message) {
    var loc = getLineInfo(this.input, pos);
    message += " (" + loc.line + ":" + loc.column + ")";
    var err = new SyntaxError(message);
    err.pos = pos;
    err.loc = loc;
    err.raisedAt = this.pos;
    throw err;
};
pp$4.raiseRecoverable = pp$4.raise;
pp$4.curPosition = function() {
    if (this.options.locations) {
        return new Position(this.curLine, this.pos - this.lineStart);
    }
};
var pp$5 = Parser.prototype;
var Scope = function Scope2(flags) {
    this.flags = flags;
    this.var = [];
    this.lexical = [];
    this.functions = [];
};
pp$5.enterScope = function(flags) {
    this.scopeStack.push(new Scope(flags));
};
pp$5.exitScope = function() {
    this.scopeStack.pop();
};
pp$5.treatFunctionsAsVarInScope = function(scope) {
    return scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_TOP;
};
pp$5.declareName = function(name124, bindingType, pos) {
    var redeclared = false;
    if (bindingType === BIND_LEXICAL) {
        var scope = this.currentScope();
        redeclared = scope.lexical.indexOf(name124) > -1 || scope.functions.indexOf(name124) > -1 || scope.var.indexOf(name124) > -1;
        scope.lexical.push(name124);
        if (this.inModule && scope.flags & SCOPE_TOP) {
            delete this.undefinedExports[name124];
        }
    } else if (bindingType === BIND_SIMPLE_CATCH) {
        var scope$1 = this.currentScope();
        scope$1.lexical.push(name124);
    } else if (bindingType === BIND_FUNCTION) {
        var scope$2 = this.currentScope();
        if (this.treatFunctionsAsVar) {
            redeclared = scope$2.lexical.indexOf(name124) > -1;
        } else {
            redeclared = scope$2.lexical.indexOf(name124) > -1 || scope$2.var.indexOf(name124) > -1;
        }
        scope$2.functions.push(name124);
    } else {
        for(var i = this.scopeStack.length - 1; i >= 0; --i){
            var scope$3 = this.scopeStack[i];
            if (scope$3.lexical.indexOf(name124) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name124) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name124) > -1) {
                redeclared = true;
                break;
            }
            scope$3.var.push(name124);
            if (this.inModule && scope$3.flags & SCOPE_TOP) {
                delete this.undefinedExports[name124];
            }
            if (scope$3.flags & SCOPE_VAR) {
                break;
            }
        }
    }
    if (redeclared) {
        this.raiseRecoverable(pos, "Identifier '" + name124 + "' has already been declared");
    }
};
pp$5.checkLocalExport = function(id) {
    if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) {
        this.undefinedExports[id.name] = id;
    }
};
pp$5.currentScope = function() {
    return this.scopeStack[this.scopeStack.length - 1];
};
pp$5.currentVarScope = function() {
    for(var i = this.scopeStack.length - 1;; i--){
        var scope = this.scopeStack[i];
        if (scope.flags & SCOPE_VAR) {
            return scope;
        }
    }
};
pp$5.currentThisScope = function() {
    for(var i = this.scopeStack.length - 1;; i--){
        var scope = this.scopeStack[i];
        if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) {
            return scope;
        }
    }
};
var Node1 = function Node2(parser, pos, loc) {
    this.type = "";
    this.start = pos;
    this.end = 0;
    if (parser.options.locations) {
        this.loc = new SourceLocation(parser, loc);
    }
    if (parser.options.directSourceFile) {
        this.sourceFile = parser.options.directSourceFile;
    }
    if (parser.options.ranges) {
        this.range = [
            pos,
            0
        ];
    }
};
var pp$6 = Parser.prototype;
pp$6.startNode = function() {
    return new Node1(this, this.start, this.startLoc);
};
pp$6.startNodeAt = function(pos, loc) {
    return new Node1(this, pos, loc);
};
function finishNodeAt(node, type, pos, loc) {
    node.type = type;
    node.end = pos;
    if (this.options.locations) {
        node.loc.end = loc;
    }
    if (this.options.ranges) {
        node.range[1] = pos;
    }
    return node;
}
pp$6.finishNode = function(node, type) {
    return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
};
pp$6.finishNodeAt = function(node, type, pos, loc) {
    return finishNodeAt.call(this, node, type, pos, loc);
};
var TokContext = function TokContext2(token, isExpr, preserveSpace, override, generator) {
    this.token = token;
    this.isExpr = !!isExpr;
    this.preserveSpace = !!preserveSpace;
    this.override = override;
    this.generator = !!generator;
};
var types$1 = {
    b_stat: new TokContext("{", false),
    b_expr: new TokContext("{", true),
    b_tmpl: new TokContext("${", false),
    p_stat: new TokContext("(", false),
    p_expr: new TokContext("(", true),
    q_tmpl: new TokContext("`", true, true, function(p) {
        return p.tryReadTemplateToken();
    }),
    f_stat: new TokContext("function", false),
    f_expr: new TokContext("function", true),
    f_expr_gen: new TokContext("function", true, false, null, true),
    f_gen: new TokContext("function", false, false, null, true)
};
var pp$7 = Parser.prototype;
pp$7.initialContext = function() {
    return [
        types$1.b_stat
    ];
};
pp$7.braceIsBlock = function(prevType) {
    var parent = this.curContext();
    if (parent === types$1.f_expr || parent === types$1.f_stat) {
        return true;
    }
    if (prevType === types2.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) {
        return !parent.isExpr;
    }
    if (prevType === types2._return || prevType === types2.name && this.exprAllowed) {
        return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
    }
    if (prevType === types2._else || prevType === types2.semi || prevType === types2.eof || prevType === types2.parenR || prevType === types2.arrow) {
        return true;
    }
    if (prevType === types2.braceL) {
        return parent === types$1.b_stat;
    }
    if (prevType === types2._var || prevType === types2._const || prevType === types2.name) {
        return false;
    }
    return !this.exprAllowed;
};
pp$7.inGeneratorContext = function() {
    for(var i = this.context.length - 1; i >= 1; i--){
        var context = this.context[i];
        if (context.token === "function") {
            return context.generator;
        }
    }
    return false;
};
pp$7.updateContext = function(prevType) {
    var update, type = this.type;
    if (type.keyword && prevType === types2.dot) {
        this.exprAllowed = false;
    } else if (update = type.updateContext) {
        update.call(this, prevType);
    } else {
        this.exprAllowed = type.beforeExpr;
    }
};
types2.parenR.updateContext = types2.braceR.updateContext = function() {
    if (this.context.length === 1) {
        this.exprAllowed = true;
        return;
    }
    var out = this.context.pop();
    if (out === types$1.b_stat && this.curContext().token === "function") {
        out = this.context.pop();
    }
    this.exprAllowed = !out.isExpr;
};
types2.braceL.updateContext = function(prevType) {
    this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
    this.exprAllowed = true;
};
types2.dollarBraceL.updateContext = function() {
    this.context.push(types$1.b_tmpl);
    this.exprAllowed = true;
};
types2.parenL.updateContext = function(prevType) {
    var statementParens = prevType === types2._if || prevType === types2._for || prevType === types2._with || prevType === types2._while;
    this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
    this.exprAllowed = true;
};
types2.incDec.updateContext = function() {};
types2._function.updateContext = types2._class.updateContext = function(prevType) {
    if (prevType.beforeExpr && prevType !== types2.semi && prevType !== types2._else && !(prevType === types2._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types2.colon || prevType === types2.braceL) && this.curContext() === types$1.b_stat)) {
        this.context.push(types$1.f_expr);
    } else {
        this.context.push(types$1.f_stat);
    }
    this.exprAllowed = false;
};
types2.backQuote.updateContext = function() {
    if (this.curContext() === types$1.q_tmpl) {
        this.context.pop();
    } else {
        this.context.push(types$1.q_tmpl);
    }
    this.exprAllowed = false;
};
types2.star.updateContext = function(prevType) {
    if (prevType === types2._function) {
        var index = this.context.length - 1;
        if (this.context[index] === types$1.f_expr) {
            this.context[index] = types$1.f_expr_gen;
        } else {
            this.context[index] = types$1.f_gen;
        }
    }
    this.exprAllowed = true;
};
types2.name.updateContext = function(prevType) {
    var allowed = false;
    if (this.options.ecmaVersion >= 6 && prevType !== types2.dot) {
        if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) {
            allowed = true;
        }
    }
    this.exprAllowed = allowed;
};
var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
var ecma11BinaryProperties = ecma10BinaryProperties;
var unicodeBinaryProperties = {
    9: ecma9BinaryProperties,
    10: ecma10BinaryProperties,
    11: ecma11BinaryProperties
};
var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var unicodeScriptValues = {
    9: ecma9ScriptValues,
    10: ecma10ScriptValues,
    11: ecma11ScriptValues
};
var data = {};
function buildUnicodeData(ecmaVersion) {
    var d = data[ecmaVersion] = {
        binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
        nonBinary: {
            General_Category: wordsRegexp(unicodeGeneralCategoryValues),
            Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
        }
    };
    d.nonBinary.Script_Extensions = d.nonBinary.Script;
    d.nonBinary.gc = d.nonBinary.General_Category;
    d.nonBinary.sc = d.nonBinary.Script;
    d.nonBinary.scx = d.nonBinary.Script_Extensions;
}
buildUnicodeData(9);
buildUnicodeData(10);
buildUnicodeData(11);
var pp$8 = Parser.prototype;
var RegExpValidationState = function RegExpValidationState2(parser) {
    this.parser = parser;
    this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
    this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion];
    this.source = "";
    this.flags = "";
    this.start = 0;
    this.switchU = false;
    this.switchN = false;
    this.pos = 0;
    this.lastIntValue = 0;
    this.lastStringValue = "";
    this.lastAssertionIsQuantifiable = false;
    this.numCapturingParens = 0;
    this.maxBackReference = 0;
    this.groupNames = [];
    this.backReferenceNames = [];
};
RegExpValidationState.prototype.reset = function reset(start, pattern, flags) {
    var unicode = flags.indexOf("u") !== -1;
    this.start = start | 0;
    this.source = pattern + "";
    this.flags = flags;
    this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
    this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
};
RegExpValidationState.prototype.raise = function raise(message) {
    this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
};
RegExpValidationState.prototype.at = function at(i, forceU) {
    if (forceU === void 0) forceU = false;
    var s = this.source;
    var l = s.length;
    if (i >= l) {
        return -1;
    }
    var c = s.charCodeAt(i);
    if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i + 1 >= l) {
        return c;
    }
    var next = s.charCodeAt(i + 1);
    return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;
};
RegExpValidationState.prototype.nextIndex = function nextIndex(i, forceU) {
    if (forceU === void 0) forceU = false;
    var s = this.source;
    var l = s.length;
    if (i >= l) {
        return l;
    }
    var c = s.charCodeAt(i), next;
    if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i + 1 >= l || (next = s.charCodeAt(i + 1)) < 56320 || next > 57343) {
        return i + 1;
    }
    return i + 2;
};
RegExpValidationState.prototype.current = function current(forceU) {
    if (forceU === void 0) forceU = false;
    return this.at(this.pos, forceU);
};
RegExpValidationState.prototype.lookahead = function lookahead(forceU) {
    if (forceU === void 0) forceU = false;
    return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState.prototype.advance = function advance(forceU) {
    if (forceU === void 0) forceU = false;
    this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState.prototype.eat = function eat(ch, forceU) {
    if (forceU === void 0) forceU = false;
    if (this.current(forceU) === ch) {
        this.advance(forceU);
        return true;
    }
    return false;
};
function codePointToString(ch) {
    if (ch <= 65535) {
        return String.fromCharCode(ch);
    }
    ch -= 65536;
    return String.fromCharCode((ch >> 10) + 55296, (ch & 1023) + 56320);
}
pp$8.validateRegExpFlags = function(state40) {
    var validFlags = state40.validFlags;
    var flags = state40.flags;
    for(var i = 0; i < flags.length; i++){
        var flag = flags.charAt(i);
        if (validFlags.indexOf(flag) === -1) {
            this.raise(state40.start, "Invalid regular expression flag");
        }
        if (flags.indexOf(flag, i + 1) > -1) {
            this.raise(state40.start, "Duplicate regular expression flag");
        }
    }
};
pp$8.validateRegExpPattern = function(state41) {
    this.regexp_pattern(state41);
    if (!state41.switchN && this.options.ecmaVersion >= 9 && state41.groupNames.length > 0) {
        state41.switchN = true;
        this.regexp_pattern(state41);
    }
};
pp$8.regexp_pattern = function(state42) {
    state42.pos = 0;
    state42.lastIntValue = 0;
    state42.lastStringValue = "";
    state42.lastAssertionIsQuantifiable = false;
    state42.numCapturingParens = 0;
    state42.maxBackReference = 0;
    state42.groupNames.length = 0;
    state42.backReferenceNames.length = 0;
    this.regexp_disjunction(state42);
    if (state42.pos !== state42.source.length) {
        if (state42.eat(41)) {
            state42.raise("Unmatched ')'");
        }
        if (state42.eat(93) || state42.eat(125)) {
            state42.raise("Lone quantifier brackets");
        }
    }
    if (state42.maxBackReference > state42.numCapturingParens) {
        state42.raise("Invalid escape");
    }
    for(var i = 0, list = state42.backReferenceNames; i < list.length; i += 1){
        var name125 = list[i];
        if (state42.groupNames.indexOf(name125) === -1) {
            state42.raise("Invalid named capture referenced");
        }
    }
};
pp$8.regexp_disjunction = function(state43) {
    this.regexp_alternative(state43);
    while(state43.eat(124)){
        this.regexp_alternative(state43);
    }
    if (this.regexp_eatQuantifier(state43, true)) {
        state43.raise("Nothing to repeat");
    }
    if (state43.eat(123)) {
        state43.raise("Lone quantifier brackets");
    }
};
pp$8.regexp_alternative = function(state44) {
    while(state44.pos < state44.source.length && this.regexp_eatTerm(state44)){}
};
pp$8.regexp_eatTerm = function(state45) {
    if (this.regexp_eatAssertion(state45)) {
        if (state45.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state45)) {
            if (state45.switchU) {
                state45.raise("Invalid quantifier");
            }
        }
        return true;
    }
    if (state45.switchU ? this.regexp_eatAtom(state45) : this.regexp_eatExtendedAtom(state45)) {
        this.regexp_eatQuantifier(state45);
        return true;
    }
    return false;
};
pp$8.regexp_eatAssertion = function(state46) {
    var start = state46.pos;
    state46.lastAssertionIsQuantifiable = false;
    if (state46.eat(94) || state46.eat(36)) {
        return true;
    }
    if (state46.eat(92)) {
        if (state46.eat(66) || state46.eat(98)) {
            return true;
        }
        state46.pos = start;
    }
    if (state46.eat(40) && state46.eat(63)) {
        var lookbehind = false;
        if (this.options.ecmaVersion >= 9) {
            lookbehind = state46.eat(60);
        }
        if (state46.eat(61) || state46.eat(33)) {
            this.regexp_disjunction(state46);
            if (!state46.eat(41)) {
                state46.raise("Unterminated group");
            }
            state46.lastAssertionIsQuantifiable = !lookbehind;
            return true;
        }
    }
    state46.pos = start;
    return false;
};
pp$8.regexp_eatQuantifier = function(state47, noError) {
    if (noError === void 0) noError = false;
    if (this.regexp_eatQuantifierPrefix(state47, noError)) {
        state47.eat(63);
        return true;
    }
    return false;
};
pp$8.regexp_eatQuantifierPrefix = function(state48, noError) {
    return state48.eat(42) || state48.eat(43) || state48.eat(63) || this.regexp_eatBracedQuantifier(state48, noError);
};
pp$8.regexp_eatBracedQuantifier = function(state49, noError) {
    var start = state49.pos;
    if (state49.eat(123)) {
        var min = 0, max = -1;
        if (this.regexp_eatDecimalDigits(state49)) {
            min = state49.lastIntValue;
            if (state49.eat(44) && this.regexp_eatDecimalDigits(state49)) {
                max = state49.lastIntValue;
            }
            if (state49.eat(125)) {
                if (max !== -1 && max < min && !noError) {
                    state49.raise("numbers out of order in {} quantifier");
                }
                return true;
            }
        }
        if (state49.switchU && !noError) {
            state49.raise("Incomplete quantifier");
        }
        state49.pos = start;
    }
    return false;
};
pp$8.regexp_eatAtom = function(state50) {
    return this.regexp_eatPatternCharacters(state50) || state50.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state50) || this.regexp_eatCharacterClass(state50) || this.regexp_eatUncapturingGroup(state50) || this.regexp_eatCapturingGroup(state50);
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state51) {
    var start = state51.pos;
    if (state51.eat(92)) {
        if (this.regexp_eatAtomEscape(state51)) {
            return true;
        }
        state51.pos = start;
    }
    return false;
};
pp$8.regexp_eatUncapturingGroup = function(state52) {
    var start = state52.pos;
    if (state52.eat(40)) {
        if (state52.eat(63) && state52.eat(58)) {
            this.regexp_disjunction(state52);
            if (state52.eat(41)) {
                return true;
            }
            state52.raise("Unterminated group");
        }
        state52.pos = start;
    }
    return false;
};
pp$8.regexp_eatCapturingGroup = function(state53) {
    if (state53.eat(40)) {
        if (this.options.ecmaVersion >= 9) {
            this.regexp_groupSpecifier(state53);
        } else if (state53.current() === 63) {
            state53.raise("Invalid group");
        }
        this.regexp_disjunction(state53);
        if (state53.eat(41)) {
            state53.numCapturingParens += 1;
            return true;
        }
        state53.raise("Unterminated group");
    }
    return false;
};
pp$8.regexp_eatExtendedAtom = function(state54) {
    return state54.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state54) || this.regexp_eatCharacterClass(state54) || this.regexp_eatUncapturingGroup(state54) || this.regexp_eatCapturingGroup(state54) || this.regexp_eatInvalidBracedQuantifier(state54) || this.regexp_eatExtendedPatternCharacter(state54);
};
pp$8.regexp_eatInvalidBracedQuantifier = function(state55) {
    if (this.regexp_eatBracedQuantifier(state55, true)) {
        state55.raise("Nothing to repeat");
    }
    return false;
};
pp$8.regexp_eatSyntaxCharacter = function(state56) {
    var ch = state56.current();
    if (isSyntaxCharacter(ch)) {
        state56.lastIntValue = ch;
        state56.advance();
        return true;
    }
    return false;
};
function isSyntaxCharacter(ch) {
    return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$8.regexp_eatPatternCharacters = function(state57) {
    var start = state57.pos;
    var ch = 0;
    while((ch = state57.current()) !== -1 && !isSyntaxCharacter(ch)){
        state57.advance();
    }
    return state57.pos !== start;
};
pp$8.regexp_eatExtendedPatternCharacter = function(state58) {
    var ch = state58.current();
    if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
        state58.advance();
        return true;
    }
    return false;
};
pp$8.regexp_groupSpecifier = function(state59) {
    if (state59.eat(63)) {
        if (this.regexp_eatGroupName(state59)) {
            if (state59.groupNames.indexOf(state59.lastStringValue) !== -1) {
                state59.raise("Duplicate capture group name");
            }
            state59.groupNames.push(state59.lastStringValue);
            return;
        }
        state59.raise("Invalid group");
    }
};
pp$8.regexp_eatGroupName = function(state60) {
    state60.lastStringValue = "";
    if (state60.eat(60)) {
        if (this.regexp_eatRegExpIdentifierName(state60) && state60.eat(62)) {
            return true;
        }
        state60.raise("Invalid capture group name");
    }
    return false;
};
pp$8.regexp_eatRegExpIdentifierName = function(state61) {
    state61.lastStringValue = "";
    if (this.regexp_eatRegExpIdentifierStart(state61)) {
        state61.lastStringValue += codePointToString(state61.lastIntValue);
        while(this.regexp_eatRegExpIdentifierPart(state61)){
            state61.lastStringValue += codePointToString(state61.lastIntValue);
        }
        return true;
    }
    return false;
};
pp$8.regexp_eatRegExpIdentifierStart = function(state62) {
    var start = state62.pos;
    var forceU = this.options.ecmaVersion >= 11;
    var ch = state62.current(forceU);
    state62.advance(forceU);
    if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state62, forceU)) {
        ch = state62.lastIntValue;
    }
    if (isRegExpIdentifierStart(ch)) {
        state62.lastIntValue = ch;
        return true;
    }
    state62.pos = start;
    return false;
};
function isRegExpIdentifierStart(ch) {
    return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
}
pp$8.regexp_eatRegExpIdentifierPart = function(state63) {
    var start = state63.pos;
    var forceU = this.options.ecmaVersion >= 11;
    var ch = state63.current(forceU);
    state63.advance(forceU);
    if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state63, forceU)) {
        ch = state63.lastIntValue;
    }
    if (isRegExpIdentifierPart(ch)) {
        state63.lastIntValue = ch;
        return true;
    }
    state63.pos = start;
    return false;
};
function isRegExpIdentifierPart(ch) {
    return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$8.regexp_eatAtomEscape = function(state64) {
    if (this.regexp_eatBackReference(state64) || this.regexp_eatCharacterClassEscape(state64) || this.regexp_eatCharacterEscape(state64) || state64.switchN && this.regexp_eatKGroupName(state64)) {
        return true;
    }
    if (state64.switchU) {
        if (state64.current() === 99) {
            state64.raise("Invalid unicode escape");
        }
        state64.raise("Invalid escape");
    }
    return false;
};
pp$8.regexp_eatBackReference = function(state65) {
    var start = state65.pos;
    if (this.regexp_eatDecimalEscape(state65)) {
        var n11 = state65.lastIntValue;
        if (state65.switchU) {
            if (n11 > state65.maxBackReference) {
                state65.maxBackReference = n11;
            }
            return true;
        }
        if (n11 <= state65.numCapturingParens) {
            return true;
        }
        state65.pos = start;
    }
    return false;
};
pp$8.regexp_eatKGroupName = function(state66) {
    if (state66.eat(107)) {
        if (this.regexp_eatGroupName(state66)) {
            state66.backReferenceNames.push(state66.lastStringValue);
            return true;
        }
        state66.raise("Invalid named reference");
    }
    return false;
};
pp$8.regexp_eatCharacterEscape = function(state67) {
    return this.regexp_eatControlEscape(state67) || this.regexp_eatCControlLetter(state67) || this.regexp_eatZero(state67) || this.regexp_eatHexEscapeSequence(state67) || this.regexp_eatRegExpUnicodeEscapeSequence(state67, false) || !state67.switchU && this.regexp_eatLegacyOctalEscapeSequence(state67) || this.regexp_eatIdentityEscape(state67);
};
pp$8.regexp_eatCControlLetter = function(state68) {
    var start = state68.pos;
    if (state68.eat(99)) {
        if (this.regexp_eatControlLetter(state68)) {
            return true;
        }
        state68.pos = start;
    }
    return false;
};
pp$8.regexp_eatZero = function(state69) {
    if (state69.current() === 48 && !isDecimalDigit(state69.lookahead())) {
        state69.lastIntValue = 0;
        state69.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatControlEscape = function(state70) {
    var ch = state70.current();
    if (ch === 116) {
        state70.lastIntValue = 9;
        state70.advance();
        return true;
    }
    if (ch === 110) {
        state70.lastIntValue = 10;
        state70.advance();
        return true;
    }
    if (ch === 118) {
        state70.lastIntValue = 11;
        state70.advance();
        return true;
    }
    if (ch === 102) {
        state70.lastIntValue = 12;
        state70.advance();
        return true;
    }
    if (ch === 114) {
        state70.lastIntValue = 13;
        state70.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatControlLetter = function(state71) {
    var ch = state71.current();
    if (isControlLetter(ch)) {
        state71.lastIntValue = ch % 32;
        state71.advance();
        return true;
    }
    return false;
};
function isControlLetter(ch) {
    return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state72, forceU) {
    if (forceU === void 0) forceU = false;
    var start = state72.pos;
    var switchU = forceU || state72.switchU;
    if (state72.eat(117)) {
        if (this.regexp_eatFixedHexDigits(state72, 4)) {
            var lead = state72.lastIntValue;
            if (switchU && lead >= 55296 && lead <= 56319) {
                var leadSurrogateEnd = state72.pos;
                if (state72.eat(92) && state72.eat(117) && this.regexp_eatFixedHexDigits(state72, 4)) {
                    var trail = state72.lastIntValue;
                    if (trail >= 56320 && trail <= 57343) {
                        state72.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
                        return true;
                    }
                }
                state72.pos = leadSurrogateEnd;
                state72.lastIntValue = lead;
            }
            return true;
        }
        if (switchU && state72.eat(123) && this.regexp_eatHexDigits(state72) && state72.eat(125) && isValidUnicode(state72.lastIntValue)) {
            return true;
        }
        if (switchU) {
            state72.raise("Invalid unicode escape");
        }
        state72.pos = start;
    }
    return false;
};
function isValidUnicode(ch) {
    return ch >= 0 && ch <= 1114111;
}
pp$8.regexp_eatIdentityEscape = function(state73) {
    if (state73.switchU) {
        if (this.regexp_eatSyntaxCharacter(state73)) {
            return true;
        }
        if (state73.eat(47)) {
            state73.lastIntValue = 47;
            return true;
        }
        return false;
    }
    var ch = state73.current();
    if (ch !== 99 && (!state73.switchN || ch !== 107)) {
        state73.lastIntValue = ch;
        state73.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatDecimalEscape = function(state74) {
    state74.lastIntValue = 0;
    var ch = state74.current();
    if (ch >= 49 && ch <= 57) {
        do {
            state74.lastIntValue = 10 * state74.lastIntValue + (ch - 48);
            state74.advance();
        }while ((ch = state74.current()) >= 48 && ch <= 57)
        return true;
    }
    return false;
};
pp$8.regexp_eatCharacterClassEscape = function(state75) {
    var ch = state75.current();
    if (isCharacterClassEscape(ch)) {
        state75.lastIntValue = -1;
        state75.advance();
        return true;
    }
    if (state75.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) {
        state75.lastIntValue = -1;
        state75.advance();
        if (state75.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state75) && state75.eat(125)) {
            return true;
        }
        state75.raise("Invalid property name");
    }
    return false;
};
function isCharacterClassEscape(ch) {
    return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$8.regexp_eatUnicodePropertyValueExpression = function(state76) {
    var start = state76.pos;
    if (this.regexp_eatUnicodePropertyName(state76) && state76.eat(61)) {
        var name126 = state76.lastStringValue;
        if (this.regexp_eatUnicodePropertyValue(state76)) {
            var value = state76.lastStringValue;
            this.regexp_validateUnicodePropertyNameAndValue(state76, name126, value);
            return true;
        }
    }
    state76.pos = start;
    if (this.regexp_eatLoneUnicodePropertyNameOrValue(state76)) {
        var nameOrValue = state76.lastStringValue;
        this.regexp_validateUnicodePropertyNameOrValue(state76, nameOrValue);
        return true;
    }
    return false;
};
pp$8.regexp_validateUnicodePropertyNameAndValue = function(state77, name127, value) {
    if (!has(state77.unicodeProperties.nonBinary, name127)) {
        state77.raise("Invalid property name");
    }
    if (!state77.unicodeProperties.nonBinary[name127].test(value)) {
        state77.raise("Invalid property value");
    }
};
pp$8.regexp_validateUnicodePropertyNameOrValue = function(state78, nameOrValue) {
    if (!state78.unicodeProperties.binary.test(nameOrValue)) {
        state78.raise("Invalid property name");
    }
};
pp$8.regexp_eatUnicodePropertyName = function(state79) {
    var ch = 0;
    state79.lastStringValue = "";
    while(isUnicodePropertyNameCharacter(ch = state79.current())){
        state79.lastStringValue += codePointToString(ch);
        state79.advance();
    }
    return state79.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter(ch) {
    return isControlLetter(ch) || ch === 95;
}
pp$8.regexp_eatUnicodePropertyValue = function(state80) {
    var ch = 0;
    state80.lastStringValue = "";
    while(isUnicodePropertyValueCharacter(ch = state80.current())){
        state80.lastStringValue += codePointToString(ch);
        state80.advance();
    }
    return state80.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter(ch) {
    return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
}
pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state81) {
    return this.regexp_eatUnicodePropertyValue(state81);
};
pp$8.regexp_eatCharacterClass = function(state82) {
    if (state82.eat(91)) {
        state82.eat(94);
        this.regexp_classRanges(state82);
        if (state82.eat(93)) {
            return true;
        }
        state82.raise("Unterminated character class");
    }
    return false;
};
pp$8.regexp_classRanges = function(state83) {
    while(this.regexp_eatClassAtom(state83)){
        var left = state83.lastIntValue;
        if (state83.eat(45) && this.regexp_eatClassAtom(state83)) {
            var right = state83.lastIntValue;
            if (state83.switchU && (left === -1 || right === -1)) {
                state83.raise("Invalid character class");
            }
            if (left !== -1 && right !== -1 && left > right) {
                state83.raise("Range out of order in character class");
            }
        }
    }
};
pp$8.regexp_eatClassAtom = function(state84) {
    var start = state84.pos;
    if (state84.eat(92)) {
        if (this.regexp_eatClassEscape(state84)) {
            return true;
        }
        if (state84.switchU) {
            var ch$1 = state84.current();
            if (ch$1 === 99 || isOctalDigit(ch$1)) {
                state84.raise("Invalid class escape");
            }
            state84.raise("Invalid escape");
        }
        state84.pos = start;
    }
    var ch = state84.current();
    if (ch !== 93) {
        state84.lastIntValue = ch;
        state84.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatClassEscape = function(state85) {
    var start = state85.pos;
    if (state85.eat(98)) {
        state85.lastIntValue = 8;
        return true;
    }
    if (state85.switchU && state85.eat(45)) {
        state85.lastIntValue = 45;
        return true;
    }
    if (!state85.switchU && state85.eat(99)) {
        if (this.regexp_eatClassControlLetter(state85)) {
            return true;
        }
        state85.pos = start;
    }
    return this.regexp_eatCharacterClassEscape(state85) || this.regexp_eatCharacterEscape(state85);
};
pp$8.regexp_eatClassControlLetter = function(state86) {
    var ch = state86.current();
    if (isDecimalDigit(ch) || ch === 95) {
        state86.lastIntValue = ch % 32;
        state86.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatHexEscapeSequence = function(state87) {
    var start = state87.pos;
    if (state87.eat(120)) {
        if (this.regexp_eatFixedHexDigits(state87, 2)) {
            return true;
        }
        if (state87.switchU) {
            state87.raise("Invalid escape");
        }
        state87.pos = start;
    }
    return false;
};
pp$8.regexp_eatDecimalDigits = function(state88) {
    var start = state88.pos;
    var ch = 0;
    state88.lastIntValue = 0;
    while(isDecimalDigit(ch = state88.current())){
        state88.lastIntValue = 10 * state88.lastIntValue + (ch - 48);
        state88.advance();
    }
    return state88.pos !== start;
};
function isDecimalDigit(ch) {
    return ch >= 48 && ch <= 57;
}
pp$8.regexp_eatHexDigits = function(state89) {
    var start = state89.pos;
    var ch = 0;
    state89.lastIntValue = 0;
    while(isHexDigit(ch = state89.current())){
        state89.lastIntValue = 16 * state89.lastIntValue + hexToInt(ch);
        state89.advance();
    }
    return state89.pos !== start;
};
function isHexDigit(ch) {
    return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt(ch) {
    if (ch >= 65 && ch <= 70) {
        return 10 + (ch - 65);
    }
    if (ch >= 97 && ch <= 102) {
        return 10 + (ch - 97);
    }
    return ch - 48;
}
pp$8.regexp_eatLegacyOctalEscapeSequence = function(state90) {
    if (this.regexp_eatOctalDigit(state90)) {
        var n1 = state90.lastIntValue;
        if (this.regexp_eatOctalDigit(state90)) {
            var n21 = state90.lastIntValue;
            if (n1 <= 3 && this.regexp_eatOctalDigit(state90)) {
                state90.lastIntValue = n1 * 64 + n21 * 8 + state90.lastIntValue;
            } else {
                state90.lastIntValue = n1 * 8 + n21;
            }
        } else {
            state90.lastIntValue = n1;
        }
        return true;
    }
    return false;
};
pp$8.regexp_eatOctalDigit = function(state91) {
    var ch = state91.current();
    if (isOctalDigit(ch)) {
        state91.lastIntValue = ch - 48;
        state91.advance();
        return true;
    }
    state91.lastIntValue = 0;
    return false;
};
function isOctalDigit(ch) {
    return ch >= 48 && ch <= 55;
}
pp$8.regexp_eatFixedHexDigits = function(state92, length) {
    var start = state92.pos;
    state92.lastIntValue = 0;
    for(var i = 0; i < length; ++i){
        var ch = state92.current();
        if (!isHexDigit(ch)) {
            state92.pos = start;
            return false;
        }
        state92.lastIntValue = 16 * state92.lastIntValue + hexToInt(ch);
        state92.advance();
    }
    return true;
};
var Token = function Token2(p) {
    this.type = p.type;
    this.value = p.value;
    this.start = p.start;
    this.end = p.end;
    if (p.options.locations) {
        this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
    }
    if (p.options.ranges) {
        this.range = [
            p.start,
            p.end
        ];
    }
};
var pp$9 = Parser.prototype;
pp$9.next = function(ignoreEscapeSequenceInKeyword) {
    if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) {
        this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword);
    }
    if (this.options.onToken) {
        this.options.onToken(new Token(this));
    }
    this.lastTokEnd = this.end;
    this.lastTokStart = this.start;
    this.lastTokEndLoc = this.endLoc;
    this.lastTokStartLoc = this.startLoc;
    this.nextToken();
};
pp$9.getToken = function() {
    this.next();
    return new Token(this);
};
if (typeof Symbol !== "undefined") {
    pp$9[Symbol.iterator] = function() {
        var this$1 = this;
        return {
            next: function() {
                var token = this$1.getToken();
                return {
                    done: token.type === types2.eof,
                    value: token
                };
            }
        };
    };
}
pp$9.curContext = function() {
    return this.context[this.context.length - 1];
};
pp$9.nextToken = function() {
    var curContext = this.curContext();
    if (!curContext || !curContext.preserveSpace) {
        this.skipSpace();
    }
    this.start = this.pos;
    if (this.options.locations) {
        this.startLoc = this.curPosition();
    }
    if (this.pos >= this.input.length) {
        return this.finishToken(types2.eof);
    }
    if (curContext.override) {
        return curContext.override(this);
    } else {
        this.readToken(this.fullCharCodeAtPos());
    }
};
pp$9.readToken = function(code28) {
    if (isIdentifierStart(code28, this.options.ecmaVersion >= 6) || code28 === 92) {
        return this.readWord();
    }
    return this.getTokenFromCode(code28);
};
pp$9.fullCharCodeAtPos = function() {
    var code29 = this.input.charCodeAt(this.pos);
    if (code29 <= 55295 || code29 >= 57344) {
        return code29;
    }
    var next = this.input.charCodeAt(this.pos + 1);
    return (code29 << 10) + next - 56613888;
};
pp$9.skipBlockComment = function() {
    var startLoc = this.options.onComment && this.curPosition();
    var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
    if (end === -1) {
        this.raise(this.pos - 2, "Unterminated comment");
    }
    this.pos = end + 2;
    if (this.options.locations) {
        lineBreakG.lastIndex = start;
        var match;
        while((match = lineBreakG.exec(this.input)) && match.index < this.pos){
            ++this.curLine;
            this.lineStart = match.index + match[0].length;
        }
    }
    if (this.options.onComment) {
        this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
    }
};
pp$9.skipLineComment = function(startSkip) {
    var start = this.pos;
    var startLoc = this.options.onComment && this.curPosition();
    var ch = this.input.charCodeAt(this.pos += startSkip);
    while(this.pos < this.input.length && !isNewLine(ch)){
        ch = this.input.charCodeAt(++this.pos);
    }
    if (this.options.onComment) {
        this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
    }
};
pp$9.skipSpace = function() {
    loop: while(this.pos < this.input.length){
        var ch = this.input.charCodeAt(this.pos);
        switch(ch){
            case 32:
            case 160:
                ++this.pos;
                break;
            case 13:
                if (this.input.charCodeAt(this.pos + 1) === 10) {
                    ++this.pos;
                }
            case 10:
            case 8232:
            case 8233:
                ++this.pos;
                if (this.options.locations) {
                    ++this.curLine;
                    this.lineStart = this.pos;
                }
                break;
            case 47:
                switch(this.input.charCodeAt(this.pos + 1)){
                    case 42:
                        this.skipBlockComment();
                        break;
                    case 47:
                        this.skipLineComment(2);
                        break;
                    default:
                        break loop;
                }
                break;
            default:
                if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
                    ++this.pos;
                } else {
                    break loop;
                }
        }
    }
};
pp$9.finishToken = function(type, val) {
    this.end = this.pos;
    if (this.options.locations) {
        this.endLoc = this.curPosition();
    }
    var prevType = this.type;
    this.type = type;
    this.value = val;
    this.updateContext(prevType);
};
pp$9.readToken_dot = function() {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next >= 48 && next <= 57) {
        return this.readNumber(true);
    }
    var next2 = this.input.charCodeAt(this.pos + 2);
    if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
        this.pos += 3;
        return this.finishToken(types2.ellipsis);
    } else {
        ++this.pos;
        return this.finishToken(types2.dot);
    }
};
pp$9.readToken_slash = function() {
    var next = this.input.charCodeAt(this.pos + 1);
    if (this.exprAllowed) {
        ++this.pos;
        return this.readRegexp();
    }
    if (next === 61) {
        return this.finishOp(types2.assign, 2);
    }
    return this.finishOp(types2.slash, 1);
};
pp$9.readToken_mult_modulo_exp = function(code30) {
    var next = this.input.charCodeAt(this.pos + 1);
    var size = 1;
    var tokentype = code30 === 42 ? types2.star : types2.modulo;
    if (this.options.ecmaVersion >= 7 && code30 === 42 && next === 42) {
        ++size;
        tokentype = types2.starstar;
        next = this.input.charCodeAt(this.pos + 2);
    }
    if (next === 61) {
        return this.finishOp(types2.assign, size + 1);
    }
    return this.finishOp(tokentype, size);
};
pp$9.readToken_pipe_amp = function(code31) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === code31) {
        if (this.options.ecmaVersion >= 12) {
            var next2 = this.input.charCodeAt(this.pos + 2);
            if (next2 === 61) {
                return this.finishOp(types2.assign, 3);
            }
        }
        return this.finishOp(code31 === 124 ? types2.logicalOR : types2.logicalAND, 2);
    }
    if (next === 61) {
        return this.finishOp(types2.assign, 2);
    }
    return this.finishOp(code31 === 124 ? types2.bitwiseOR : types2.bitwiseAND, 1);
};
pp$9.readToken_caret = function() {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 61) {
        return this.finishOp(types2.assign, 2);
    }
    return this.finishOp(types2.bitwiseXOR, 1);
};
pp$9.readToken_plus_min = function(code32) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === code32) {
        if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
            this.skipLineComment(3);
            this.skipSpace();
            return this.nextToken();
        }
        return this.finishOp(types2.incDec, 2);
    }
    if (next === 61) {
        return this.finishOp(types2.assign, 2);
    }
    return this.finishOp(types2.plusMin, 1);
};
pp$9.readToken_lt_gt = function(code33) {
    var next = this.input.charCodeAt(this.pos + 1);
    var size = 1;
    if (next === code33) {
        size = code33 === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
        if (this.input.charCodeAt(this.pos + size) === 61) {
            return this.finishOp(types2.assign, size + 1);
        }
        return this.finishOp(types2.bitShift, size);
    }
    if (next === 33 && code33 === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) {
        this.skipLineComment(4);
        this.skipSpace();
        return this.nextToken();
    }
    if (next === 61) {
        size = 2;
    }
    return this.finishOp(types2.relational, size);
};
pp$9.readToken_eq_excl = function(code34) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 61) {
        return this.finishOp(types2.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
    }
    if (code34 === 61 && next === 62 && this.options.ecmaVersion >= 6) {
        this.pos += 2;
        return this.finishToken(types2.arrow);
    }
    return this.finishOp(code34 === 61 ? types2.eq : types2.prefix, 1);
};
pp$9.readToken_question = function() {
    var ecmaVersion = this.options.ecmaVersion;
    if (ecmaVersion >= 11) {
        var next = this.input.charCodeAt(this.pos + 1);
        if (next === 46) {
            var next2 = this.input.charCodeAt(this.pos + 2);
            if (next2 < 48 || next2 > 57) {
                return this.finishOp(types2.questionDot, 2);
            }
        }
        if (next === 63) {
            if (ecmaVersion >= 12) {
                var next2$1 = this.input.charCodeAt(this.pos + 2);
                if (next2$1 === 61) {
                    return this.finishOp(types2.assign, 3);
                }
            }
            return this.finishOp(types2.coalesce, 2);
        }
    }
    return this.finishOp(types2.question, 1);
};
pp$9.getTokenFromCode = function(code35) {
    switch(code35){
        case 46:
            return this.readToken_dot();
        case 40:
            ++this.pos;
            return this.finishToken(types2.parenL);
        case 41:
            ++this.pos;
            return this.finishToken(types2.parenR);
        case 59:
            ++this.pos;
            return this.finishToken(types2.semi);
        case 44:
            ++this.pos;
            return this.finishToken(types2.comma);
        case 91:
            ++this.pos;
            return this.finishToken(types2.bracketL);
        case 93:
            ++this.pos;
            return this.finishToken(types2.bracketR);
        case 123:
            ++this.pos;
            return this.finishToken(types2.braceL);
        case 125:
            ++this.pos;
            return this.finishToken(types2.braceR);
        case 58:
            ++this.pos;
            return this.finishToken(types2.colon);
        case 96:
            if (this.options.ecmaVersion < 6) {
                break;
            }
            ++this.pos;
            return this.finishToken(types2.backQuote);
        case 48:
            var next = this.input.charCodeAt(this.pos + 1);
            if (next === 120 || next === 88) {
                return this.readRadixNumber(16);
            }
            if (this.options.ecmaVersion >= 6) {
                if (next === 111 || next === 79) {
                    return this.readRadixNumber(8);
                }
                if (next === 98 || next === 66) {
                    return this.readRadixNumber(2);
                }
            }
        case 49:
        case 50:
        case 51:
        case 52:
        case 53:
        case 54:
        case 55:
        case 56:
        case 57:
            return this.readNumber(false);
        case 34:
        case 39:
            return this.readString(code35);
        case 47:
            return this.readToken_slash();
        case 37:
        case 42:
            return this.readToken_mult_modulo_exp(code35);
        case 124:
        case 38:
            return this.readToken_pipe_amp(code35);
        case 94:
            return this.readToken_caret();
        case 43:
        case 45:
            return this.readToken_plus_min(code35);
        case 60:
        case 62:
            return this.readToken_lt_gt(code35);
        case 61:
        case 33:
            return this.readToken_eq_excl(code35);
        case 63:
            return this.readToken_question();
        case 126:
            return this.finishOp(types2.prefix, 1);
    }
    this.raise(this.pos, "Unexpected character '" + codePointToString$1(code35) + "'");
};
pp$9.finishOp = function(type, size) {
    var str73 = this.input.slice(this.pos, this.pos + size);
    this.pos += size;
    return this.finishToken(type, str73);
};
pp$9.readRegexp = function() {
    var escaped, inClass, start = this.pos;
    for(;;){
        if (this.pos >= this.input.length) {
            this.raise(start, "Unterminated regular expression");
        }
        var ch = this.input.charAt(this.pos);
        if (lineBreak.test(ch)) {
            this.raise(start, "Unterminated regular expression");
        }
        if (!escaped) {
            if (ch === "[") {
                inClass = true;
            } else if (ch === "]" && inClass) {
                inClass = false;
            } else if (ch === "/" && !inClass) {
                break;
            }
            escaped = ch === "\\";
        } else {
            escaped = false;
        }
        ++this.pos;
    }
    var pattern = this.input.slice(start, this.pos);
    ++this.pos;
    var flagsStart = this.pos;
    var flags = this.readWord1();
    if (this.containsEsc) {
        this.unexpected(flagsStart);
    }
    var state93 = this.regexpState || (this.regexpState = new RegExpValidationState(this));
    state93.reset(start, pattern, flags);
    this.validateRegExpFlags(state93);
    this.validateRegExpPattern(state93);
    var value = null;
    try {
        value = new RegExp(pattern, flags);
    } catch (e) {}
    return this.finishToken(types2.regexp, {
        pattern,
        flags,
        value
    });
};
pp$9.readInt = function(radix, len10, maybeLegacyOctalNumericLiteral) {
    var allowSeparators = this.options.ecmaVersion >= 12 && len10 === void 0;
    var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
    var start = this.pos, total = 0, lastCode = 0;
    for(var i = 0, e = len10 == null ? Infinity : len10; i < e; ++i, ++this.pos){
        var code36 = this.input.charCodeAt(this.pos), val = void 0;
        if (allowSeparators && code36 === 95) {
            if (isLegacyOctalNumericLiteral) {
                this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals");
            }
            if (lastCode === 95) {
                this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore");
            }
            if (i === 0) {
                this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
            }
            lastCode = code36;
            continue;
        }
        if (code36 >= 97) {
            val = code36 - 97 + 10;
        } else if (code36 >= 65) {
            val = code36 - 65 + 10;
        } else if (code36 >= 48 && code36 <= 57) {
            val = code36 - 48;
        } else {
            val = Infinity;
        }
        if (val >= radix) {
            break;
        }
        lastCode = code36;
        total = total * radix + val;
    }
    if (allowSeparators && lastCode === 95) {
        this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits");
    }
    if (this.pos === start || len10 != null && this.pos - start !== len10) {
        return null;
    }
    return total;
};
function stringToNumber(str74, isLegacyOctalNumericLiteral) {
    if (isLegacyOctalNumericLiteral) {
        return parseInt(str74, 8);
    }
    return parseFloat(str74.replace(/_/g, ""));
}
function stringToBigInt(str75) {
    if (typeof BigInt !== "function") {
        return null;
    }
    return BigInt(str75.replace(/_/g, ""));
}
pp$9.readRadixNumber = function(radix) {
    var start = this.pos;
    this.pos += 2;
    var val = this.readInt(radix);
    if (val == null) {
        this.raise(this.start + 2, "Expected number in radix " + radix);
    }
    if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
        val = stringToBigInt(this.input.slice(start, this.pos));
        ++this.pos;
    } else if (isIdentifierStart(this.fullCharCodeAtPos())) {
        this.raise(this.pos, "Identifier directly after number");
    }
    return this.finishToken(types2.num, val);
};
pp$9.readNumber = function(startsWithDot) {
    var start = this.pos;
    if (!startsWithDot && this.readInt(10, void 0, true) === null) {
        this.raise(start, "Invalid number");
    }
    var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
    if (octal && this.strict) {
        this.raise(start, "Invalid number");
    }
    var next = this.input.charCodeAt(this.pos);
    if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
        var val$1 = stringToBigInt(this.input.slice(start, this.pos));
        ++this.pos;
        if (isIdentifierStart(this.fullCharCodeAtPos())) {
            this.raise(this.pos, "Identifier directly after number");
        }
        return this.finishToken(types2.num, val$1);
    }
    if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
        octal = false;
    }
    if (next === 46 && !octal) {
        ++this.pos;
        this.readInt(10);
        next = this.input.charCodeAt(this.pos);
    }
    if ((next === 69 || next === 101) && !octal) {
        next = this.input.charCodeAt(++this.pos);
        if (next === 43 || next === 45) {
            ++this.pos;
        }
        if (this.readInt(10) === null) {
            this.raise(start, "Invalid number");
        }
    }
    if (isIdentifierStart(this.fullCharCodeAtPos())) {
        this.raise(this.pos, "Identifier directly after number");
    }
    var val = stringToNumber(this.input.slice(start, this.pos), octal);
    return this.finishToken(types2.num, val);
};
pp$9.readCodePoint = function() {
    var ch = this.input.charCodeAt(this.pos), code37;
    if (ch === 123) {
        if (this.options.ecmaVersion < 6) {
            this.unexpected();
        }
        var codePos = ++this.pos;
        code37 = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
        ++this.pos;
        if (code37 > 1114111) {
            this.invalidStringToken(codePos, "Code point out of bounds");
        }
    } else {
        code37 = this.readHexChar(4);
    }
    return code37;
};
function codePointToString$1(code38) {
    if (code38 <= 65535) {
        return String.fromCharCode(code38);
    }
    code38 -= 65536;
    return String.fromCharCode((code38 >> 10) + 55296, (code38 & 1023) + 56320);
}
pp$9.readString = function(quote) {
    var out = "", chunkStart = ++this.pos;
    for(;;){
        if (this.pos >= this.input.length) {
            this.raise(this.start, "Unterminated string constant");
        }
        var ch = this.input.charCodeAt(this.pos);
        if (ch === quote) {
            break;
        }
        if (ch === 92) {
            out += this.input.slice(chunkStart, this.pos);
            out += this.readEscapedChar(false);
            chunkStart = this.pos;
        } else {
            if (isNewLine(ch, this.options.ecmaVersion >= 10)) {
                this.raise(this.start, "Unterminated string constant");
            }
            ++this.pos;
        }
    }
    out += this.input.slice(chunkStart, this.pos++);
    return this.finishToken(types2.string, out);
};
var INVALID_TEMPLATE_ESCAPE_ERROR = {};
pp$9.tryReadTemplateToken = function() {
    this.inTemplateElement = true;
    try {
        this.readTmplToken();
    } catch (err) {
        if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
            this.readInvalidTemplateToken();
        } else {
            throw err;
        }
    }
    this.inTemplateElement = false;
};
pp$9.invalidStringToken = function(position, message) {
    if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
        throw INVALID_TEMPLATE_ESCAPE_ERROR;
    } else {
        this.raise(position, message);
    }
};
pp$9.readTmplToken = function() {
    var out = "", chunkStart = this.pos;
    for(;;){
        if (this.pos >= this.input.length) {
            this.raise(this.start, "Unterminated template");
        }
        var ch = this.input.charCodeAt(this.pos);
        if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
            if (this.pos === this.start && (this.type === types2.template || this.type === types2.invalidTemplate)) {
                if (ch === 36) {
                    this.pos += 2;
                    return this.finishToken(types2.dollarBraceL);
                } else {
                    ++this.pos;
                    return this.finishToken(types2.backQuote);
                }
            }
            out += this.input.slice(chunkStart, this.pos);
            return this.finishToken(types2.template, out);
        }
        if (ch === 92) {
            out += this.input.slice(chunkStart, this.pos);
            out += this.readEscapedChar(true);
            chunkStart = this.pos;
        } else if (isNewLine(ch)) {
            out += this.input.slice(chunkStart, this.pos);
            ++this.pos;
            switch(ch){
                case 13:
                    if (this.input.charCodeAt(this.pos) === 10) {
                        ++this.pos;
                    }
                case 10:
                    out += "\n";
                    break;
                default:
                    out += String.fromCharCode(ch);
                    break;
            }
            if (this.options.locations) {
                ++this.curLine;
                this.lineStart = this.pos;
            }
            chunkStart = this.pos;
        } else {
            ++this.pos;
        }
    }
};
pp$9.readInvalidTemplateToken = function() {
    for(; this.pos < this.input.length; this.pos++){
        switch(this.input[this.pos]){
            case "\\":
                ++this.pos;
                break;
            case "$":
                if (this.input[this.pos + 1] !== "{") {
                    break;
                }
            case "`":
                return this.finishToken(types2.invalidTemplate, this.input.slice(this.start, this.pos));
        }
    }
    this.raise(this.start, "Unterminated template");
};
pp$9.readEscapedChar = function(inTemplate) {
    var ch = this.input.charCodeAt(++this.pos);
    ++this.pos;
    switch(ch){
        case 110:
            return "\n";
        case 114:
            return "\r";
        case 120:
            return String.fromCharCode(this.readHexChar(2));
        case 117:
            return codePointToString$1(this.readCodePoint());
        case 116:
            return "	";
        case 98:
            return "\b";
        case 118:
            return "\v";
        case 102:
            return "\f";
        case 13:
            if (this.input.charCodeAt(this.pos) === 10) {
                ++this.pos;
            }
        case 10:
            if (this.options.locations) {
                this.lineStart = this.pos;
                ++this.curLine;
            }
            return "";
        case 56:
        case 57:
            if (inTemplate) {
                var codePos = this.pos - 1;
                this.invalidStringToken(codePos, "Invalid escape sequence in template string");
                return null;
            }
        default:
            if (ch >= 48 && ch <= 55) {
                var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
                var octal = parseInt(octalStr, 8);
                if (octal > 255) {
                    octalStr = octalStr.slice(0, -1);
                    octal = parseInt(octalStr, 8);
                }
                this.pos += octalStr.length - 1;
                ch = this.input.charCodeAt(this.pos);
                if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
                    this.invalidStringToken(this.pos - 1 - octalStr.length, inTemplate ? "Octal literal in template string" : "Octal literal in strict mode");
                }
                return String.fromCharCode(octal);
            }
            if (isNewLine(ch)) {
                return "";
            }
            return String.fromCharCode(ch);
    }
};
pp$9.readHexChar = function(len11) {
    var codePos = this.pos;
    var n12 = this.readInt(16, len11);
    if (n12 === null) {
        this.invalidStringToken(codePos, "Bad character escape sequence");
    }
    return n12;
};
pp$9.readWord1 = function() {
    this.containsEsc = false;
    var word = "", first = true, chunkStart = this.pos;
    var astral = this.options.ecmaVersion >= 6;
    while(this.pos < this.input.length){
        var ch = this.fullCharCodeAtPos();
        if (isIdentifierChar(ch, astral)) {
            this.pos += ch <= 65535 ? 1 : 2;
        } else if (ch === 92) {
            this.containsEsc = true;
            word += this.input.slice(chunkStart, this.pos);
            var escStart = this.pos;
            if (this.input.charCodeAt(++this.pos) !== 117) {
                this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX");
            }
            ++this.pos;
            var esc = this.readCodePoint();
            if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) {
                this.invalidStringToken(escStart, "Invalid Unicode escape");
            }
            word += codePointToString$1(esc);
            chunkStart = this.pos;
        } else {
            break;
        }
        first = false;
    }
    return word + this.input.slice(chunkStart, this.pos);
};
pp$9.readWord = function() {
    var word = this.readWord1();
    var type = types2.name;
    if (this.keywords.test(word)) {
        type = keywords$1[word];
    }
    return this.finishToken(type, word);
};
var version = "7.4.1";
Parser.acorn = {
    Parser,
    version,
    defaultOptions,
    Position,
    SourceLocation,
    getLineInfo,
    Node: Node1,
    TokenType,
    tokTypes: types2,
    keywordTypes: keywords$1,
    TokContext,
    tokContexts: types$1,
    isIdentifierChar,
    isIdentifierStart,
    Token,
    isNewLine,
    lineBreak,
    lineBreakG,
    nonASCIIwhitespace
};
function parse32(input, options) {
    return Parser.parse(input, options);
}
function simple(node, visitors, baseVisitor, state94, override) {
    if (!baseVisitor) {
        baseVisitor = base;
    }
    (function c(node2, st, override2) {
        var type = override2 || node2.type, found = visitors[type];
        baseVisitor[type](node2, st, c);
        if (found) {
            found(node2, st);
        }
    })(node, state94, override);
}
function ancestor(node, visitors, baseVisitor, state95, override) {
    var ancestors = [];
    if (!baseVisitor) {
        baseVisitor = base;
    }
    (function c(node2, st, override2) {
        var type = override2 || node2.type, found = visitors[type];
        var isNew = node2 !== ancestors[ancestors.length - 1];
        if (isNew) {
            ancestors.push(node2);
        }
        baseVisitor[type](node2, st, c);
        if (found) {
            found(node2, st || ancestors, ancestors);
        }
        if (isNew) {
            ancestors.pop();
        }
    })(node, state95, override);
}
var create = Object.create || function(proto5) {
    function Ctor() {}
    Ctor.prototype = proto5;
    return new Ctor();
};
function make(funcs, baseVisitor) {
    var visitor = create(baseVisitor || base);
    for(var type in funcs){
        visitor[type] = funcs[type];
    }
    return visitor;
}
function skipThrough(node, st, c) {
    c(node, st);
}
function ignore(_node, _st, _c) {}
var base = {};
base.Program = base.BlockStatement = function(node, st, c) {
    for(var i = 0, list = node.body; i < list.length; i += 1){
        var stmt = list[i];
        c(stmt, st, "Statement");
    }
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = function(node, st, c) {
    return c(node.expression, st, "Expression");
};
base.IfStatement = function(node, st, c) {
    c(node.test, st, "Expression");
    c(node.consequent, st, "Statement");
    if (node.alternate) {
        c(node.alternate, st, "Statement");
    }
};
base.LabeledStatement = function(node, st, c) {
    return c(node.body, st, "Statement");
};
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function(node, st, c) {
    c(node.object, st, "Expression");
    c(node.body, st, "Statement");
};
base.SwitchStatement = function(node, st, c) {
    c(node.discriminant, st, "Expression");
    for(var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1){
        var cs = list$1[i$1];
        if (cs.test) {
            c(cs.test, st, "Expression");
        }
        for(var i = 0, list = cs.consequent; i < list.length; i += 1){
            var cons = list[i];
            c(cons, st, "Statement");
        }
    }
};
base.SwitchCase = function(node, st, c) {
    if (node.test) {
        c(node.test, st, "Expression");
    }
    for(var i = 0, list = node.consequent; i < list.length; i += 1){
        var cons = list[i];
        c(cons, st, "Statement");
    }
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function(node, st, c) {
    if (node.argument) {
        c(node.argument, st, "Expression");
    }
};
base.ThrowStatement = base.SpreadElement = function(node, st, c) {
    return c(node.argument, st, "Expression");
};
base.TryStatement = function(node, st, c) {
    c(node.block, st, "Statement");
    if (node.handler) {
        c(node.handler, st);
    }
    if (node.finalizer) {
        c(node.finalizer, st, "Statement");
    }
};
base.CatchClause = function(node, st, c) {
    if (node.param) {
        c(node.param, st, "Pattern");
    }
    c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function(node, st, c) {
    c(node.test, st, "Expression");
    c(node.body, st, "Statement");
};
base.ForStatement = function(node, st, c) {
    if (node.init) {
        c(node.init, st, "ForInit");
    }
    if (node.test) {
        c(node.test, st, "Expression");
    }
    if (node.update) {
        c(node.update, st, "Expression");
    }
    c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function(node, st, c) {
    c(node.left, st, "ForInit");
    c(node.right, st, "Expression");
    c(node.body, st, "Statement");
};
base.ForInit = function(node, st, c) {
    if (node.type === "VariableDeclaration") {
        c(node, st);
    } else {
        c(node, st, "Expression");
    }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function(node, st, c) {
    return c(node, st, "Function");
};
base.VariableDeclaration = function(node, st, c) {
    for(var i = 0, list = node.declarations; i < list.length; i += 1){
        var decl = list[i];
        c(decl, st);
    }
};
base.VariableDeclarator = function(node, st, c) {
    c(node.id, st, "Pattern");
    if (node.init) {
        c(node.init, st, "Expression");
    }
};
base.Function = function(node, st, c) {
    if (node.id) {
        c(node.id, st, "Pattern");
    }
    for(var i = 0, list = node.params; i < list.length; i += 1){
        var param = list[i];
        c(param, st, "Pattern");
    }
    c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function(node, st, c) {
    if (node.type === "Identifier") {
        c(node, st, "VariablePattern");
    } else if (node.type === "MemberExpression") {
        c(node, st, "MemberPattern");
    } else {
        c(node, st);
    }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function(node, st, c) {
    return c(node.argument, st, "Pattern");
};
base.ArrayPattern = function(node, st, c) {
    for(var i = 0, list = node.elements; i < list.length; i += 1){
        var elt = list[i];
        if (elt) {
            c(elt, st, "Pattern");
        }
    }
};
base.ObjectPattern = function(node, st, c) {
    for(var i = 0, list = node.properties; i < list.length; i += 1){
        var prop = list[i];
        if (prop.type === "Property") {
            if (prop.computed) {
                c(prop.key, st, "Expression");
            }
            c(prop.value, st, "Pattern");
        } else if (prop.type === "RestElement") {
            c(prop.argument, st, "Pattern");
        }
    }
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function(node, st, c) {
    for(var i = 0, list = node.elements; i < list.length; i += 1){
        var elt = list[i];
        if (elt) {
            c(elt, st, "Expression");
        }
    }
};
base.ObjectExpression = function(node, st, c) {
    for(var i = 0, list = node.properties; i < list.length; i += 1){
        var prop = list[i];
        c(prop, st);
    }
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function(node, st, c) {
    for(var i = 0, list = node.expressions; i < list.length; i += 1){
        var expr = list[i];
        c(expr, st, "Expression");
    }
};
base.TemplateLiteral = function(node, st, c) {
    for(var i = 0, list = node.quasis; i < list.length; i += 1){
        var quasi = list[i];
        c(quasi, st);
    }
    for(var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1){
        var expr = list$1[i$1];
        c(expr, st, "Expression");
    }
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function(node, st, c) {
    c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function(node, st, c) {
    c(node.left, st, "Expression");
    c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function(node, st, c) {
    c(node.left, st, "Pattern");
    c(node.right, st, "Expression");
};
base.ConditionalExpression = function(node, st, c) {
    c(node.test, st, "Expression");
    c(node.consequent, st, "Expression");
    c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function(node, st, c) {
    c(node.callee, st, "Expression");
    if (node.arguments) {
        for(var i = 0, list = node.arguments; i < list.length; i += 1){
            var arg = list[i];
            c(arg, st, "Expression");
        }
    }
};
base.MemberExpression = function(node, st, c) {
    c(node.object, st, "Expression");
    if (node.computed) {
        c(node.property, st, "Expression");
    }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function(node, st, c) {
    if (node.declaration) {
        c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression");
    }
    if (node.source) {
        c(node.source, st, "Expression");
    }
};
base.ExportAllDeclaration = function(node, st, c) {
    if (node.exported) {
        c(node.exported, st);
    }
    c(node.source, st, "Expression");
};
base.ImportDeclaration = function(node, st, c) {
    for(var i = 0, list = node.specifiers; i < list.length; i += 1){
        var spec = list[i];
        c(spec, st);
    }
    c(node.source, st, "Expression");
};
base.ImportExpression = function(node, st, c) {
    c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
base.TaggedTemplateExpression = function(node, st, c) {
    c(node.tag, st, "Expression");
    c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function(node, st, c) {
    return c(node, st, "Class");
};
base.Class = function(node, st, c) {
    if (node.id) {
        c(node.id, st, "Pattern");
    }
    if (node.superClass) {
        c(node.superClass, st, "Expression");
    }
    c(node.body, st);
};
base.ClassBody = function(node, st, c) {
    for(var i = 0, list = node.body; i < list.length; i += 1){
        var elt = list[i];
        c(elt, st);
    }
};
base.MethodDefinition = base.Property = function(node, st, c) {
    if (node.computed) {
        c(node.key, st, "Expression");
    }
    c(node.value, st, "Expression");
};
var defaultGlobals = new Set([
    "Array",
    "ArrayBuffer",
    "atob",
    "AudioContext",
    "Blob",
    "Boolean",
    "BigInt",
    "btoa",
    "clearInterval",
    "clearTimeout",
    "console",
    "crypto",
    "CustomEvent",
    "DataView",
    "Date",
    "decodeURI",
    "decodeURIComponent",
    "devicePixelRatio",
    "document",
    "encodeURI",
    "encodeURIComponent",
    "Error",
    "escape",
    "eval",
    "fetch",
    "File",
    "FileList",
    "FileReader",
    "Float32Array",
    "Float64Array",
    "Function",
    "Headers",
    "Image",
    "ImageData",
    "Infinity",
    "Int16Array",
    "Int32Array",
    "Int8Array",
    "Intl",
    "isFinite",
    "isNaN",
    "JSON",
    "Map",
    "Math",
    "NaN",
    "Number",
    "navigator",
    "Object",
    "parseFloat",
    "parseInt",
    "performance",
    "Path2D",
    "Promise",
    "Proxy",
    "RangeError",
    "ReferenceError",
    "Reflect",
    "RegExp",
    "cancelAnimationFrame",
    "requestAnimationFrame",
    "Set",
    "setInterval",
    "setTimeout",
    "String",
    "Symbol",
    "SyntaxError",
    "TextDecoder",
    "TextEncoder",
    "this",
    "TypeError",
    "Uint16Array",
    "Uint32Array",
    "Uint8Array",
    "Uint8ClampedArray",
    "undefined",
    "unescape",
    "URIError",
    "URL",
    "WeakMap",
    "WeakSet",
    "WebSocket",
    "Worker",
    "window"
]);
var walk = make({
    Import () {},
    ViewExpression (node, st, c) {
        c(node.id, st, "Identifier");
    },
    MutableExpression (node, st, c) {
        c(node.id, st, "Identifier");
    }
});
function isScope(node) {
    return node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression" || node.type === "Program";
}
function isBlockScope(node) {
    return node.type === "BlockStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || isScope(node);
}
function declaresArguments(node) {
    return node.type === "FunctionExpression" || node.type === "FunctionDeclaration";
}
function findReferences(cell, globals) {
    const ast = {
        type: "Program",
        body: [
            cell.body
        ]
    };
    const locals = new Map();
    const globalSet = new Set(globals);
    const references = [];
    function hasLocal(node, name128) {
        const l = locals.get(node);
        return l ? l.has(name128) : false;
    }
    function declareLocal(node, id) {
        const l = locals.get(node);
        if (l) l.add(id.name);
        else locals.set(node, new Set([
            id.name
        ]));
    }
    function declareClass(node) {
        if (node.id) declareLocal(node, node.id);
    }
    function declareFunction(node) {
        node.params.forEach((param)=>declarePattern(param, node)
        );
        if (node.id) declareLocal(node, node.id);
    }
    function declareCatchClause(node) {
        if (node.param) declarePattern(node.param, node);
    }
    function declarePattern(node, parent) {
        switch(node.type){
            case "Identifier":
                declareLocal(parent, node);
                break;
            case "ObjectPattern":
                node.properties.forEach((node2)=>declarePattern(node2, parent)
                );
                break;
            case "ArrayPattern":
                node.elements.forEach((node2)=>node2 && declarePattern(node2, parent)
                );
                break;
            case "Property":
                declarePattern(node.value, parent);
                break;
            case "RestElement":
                declarePattern(node.argument, parent);
                break;
            case "AssignmentPattern":
                declarePattern(node.left, parent);
                break;
            default:
                throw new Error("Unrecognized pattern type: " + node.type);
        }
    }
    function declareModuleSpecifier(node) {
        declareLocal(ast, node.local);
    }
    ancestor(ast, {
        VariableDeclaration: (node, parents)=>{
            let parent = null;
            for(let i = parents.length - 1; i >= 0 && parent === null; --i){
                if (node.kind === "var" ? isScope(parents[i]) : isBlockScope(parents[i])) {
                    parent = parents[i];
                }
            }
            node.declarations.forEach((declaration)=>declarePattern(declaration.id, parent)
            );
        },
        FunctionDeclaration: (node, parents)=>{
            let parent = null;
            for(let i = parents.length - 2; i >= 0 && parent === null; --i){
                if (isScope(parents[i])) {
                    parent = parents[i];
                }
            }
            declareLocal(parent, node.id);
            declareFunction(node);
        },
        Function: declareFunction,
        ClassDeclaration: (node, parents)=>{
            let parent = null;
            for(let i = parents.length - 2; i >= 0 && parent === null; i--){
                if (isScope(parents[i])) {
                    parent = parents[i];
                }
            }
            declareLocal(parent, node.id);
        },
        Class: declareClass,
        CatchClause: declareCatchClause,
        ImportDefaultSpecifier: declareModuleSpecifier,
        ImportSpecifier: declareModuleSpecifier,
        ImportNamespaceSpecifier: declareModuleSpecifier
    }, walk);
    function identifier(node, parents) {
        let name129 = node.name;
        if (name129 === "undefined") return;
        for(let i = parents.length - 2; i >= 0; --i){
            if (name129 === "arguments") {
                if (declaresArguments(parents[i])) {
                    return;
                }
            }
            if (hasLocal(parents[i], name129)) {
                return;
            }
            if (parents[i].type === "ViewExpression") {
                node = parents[i];
                name129 = `viewof ${node.id.name}`;
            }
            if (parents[i].type === "MutableExpression") {
                node = parents[i];
                name129 = `mutable ${node.id.name}`;
            }
        }
        if (!globalSet.has(name129)) {
            if (name129 === "arguments") {
                throw Object.assign(new SyntaxError(`arguments is not allowed`), {
                    node
                });
            }
            references.push(node);
        }
    }
    ancestor(ast, {
        VariablePattern: identifier,
        Identifier: identifier
    }, walk);
    function checkConst(node, parents) {
        if (!node) return;
        switch(node.type){
            case "Identifier":
            case "VariablePattern":
                {
                    for (const parent of parents){
                        if (hasLocal(parent, node.name)) {
                            return;
                        }
                    }
                    if (parents[parents.length - 2].type === "MutableExpression") {
                        return;
                    }
                    throw Object.assign(new SyntaxError(`Assignment to constant variable ${node.name}`), {
                        node
                    });
                }
            case "ArrayPattern":
                {
                    for (const element of node.elements){
                        checkConst(element, parents);
                    }
                    return;
                }
            case "ObjectPattern":
                {
                    for (const property2 of node.properties){
                        checkConst(property2, parents);
                    }
                    return;
                }
            case "Property":
                {
                    checkConst(node.value, parents);
                    return;
                }
            case "RestElement":
                {
                    checkConst(node.argument, parents);
                    return;
                }
        }
    }
    function checkConstArgument(node, parents) {
        checkConst(node.argument, parents);
    }
    function checkConstLeft(node, parents) {
        checkConst(node.left, parents);
    }
    ancestor(ast, {
        AssignmentExpression: checkConstLeft,
        AssignmentPattern: checkConstLeft,
        UpdateExpression: checkConstArgument,
        ForOfStatement: checkConstLeft,
        ForInStatement: checkConstLeft
    }, walk);
    return references;
}
function findFeatures(cell, featureName) {
    const ast = {
        type: "Program",
        body: [
            cell.body
        ]
    };
    const features = new Map();
    const { references  } = cell;
    simple(ast, {
        CallExpression: (node)=>{
            const { callee , arguments: args  } = node;
            if (callee.type !== "Identifier" || callee.name !== featureName || references.indexOf(callee) < 0) return;
            if (args.length !== 1 || !(args[0].type === "Literal" && /^['"]/.test(args[0].raw) || args[0].type === "TemplateLiteral" && args[0].expressions.length === 0)) {
                throw Object.assign(new SyntaxError(`${featureName} requires a single literal string argument`), {
                    node
                });
            }
            const [arg] = args;
            const name130 = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked;
            const location = {
                start: arg.start,
                end: arg.end
            };
            if (features.has(name130)) features.get(name130).push(location);
            else features.set(name130, [
                location
            ]);
        }
    }, walk);
    return features;
}
Symbol("start");
Symbol("modifier");
Symbol("function");
Symbol("name");
class CellParser extends Parser {
    constructor(options, ...args){
        super(Object.assign({
            ecmaVersion: 12
        }, options), ...args);
    }
    enterScope(flags) {
        if (flags & 2) ++this.O_function;
        return super.enterScope(flags);
    }
    exitScope() {
        if (this.currentScope().flags & 2) --this.O_function;
        return super.exitScope();
    }
    parseForIn(node, init4) {
        if (this.O_function === 1 && node.await) this.O_async = true;
        return super.parseForIn(node, init4);
    }
    parseAwait() {
        if (this.O_function === 1) this.O_async = true;
        return super.parseAwait();
    }
    parseYield(noIn) {
        if (this.O_function === 1) this.O_generator = true;
        return super.parseYield(noIn);
    }
    parseImport(node) {
        this.next();
        node.specifiers = this.parseImportSpecifiers();
        if (this.type === types2._with) {
            this.next();
            node.injections = this.parseImportSpecifiers();
        }
        this.expectContextual("from");
        node.source = this.type === types2.string ? this.parseExprAtom() : this.unexpected();
        return this.finishNode(node, "ImportDeclaration");
    }
    parseImportSpecifiers() {
        const nodes = [];
        const identifiers = new Set();
        let first = true;
        this.expect(types2.braceL);
        while(!this.eat(types2.braceR)){
            if (first) {
                first = false;
            } else {
                this.expect(types2.comma);
                if (this.afterTrailingComma(types2.braceR)) break;
            }
            const node = this.startNode();
            node.view = this.eatContextual("viewof");
            node.mutable = node.view ? false : this.eatContextual("mutable");
            node.imported = this.parseIdent();
            this.checkUnreserved(node.imported);
            this.checkLocal(node.imported);
            if (this.eatContextual("as")) {
                node.local = this.parseIdent();
                this.checkUnreserved(node.local);
                this.checkLocal(node.local);
            } else {
                node.local = node.imported;
            }
            this.checkLVal(node.local, "let");
            if (identifiers.has(node.local.name)) {
                this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`);
            }
            identifiers.add(node.local.name);
            nodes.push(this.finishNode(node, "ImportSpecifier"));
        }
        return nodes;
    }
    parseExprAtom(refDestructuringErrors) {
        return this.parseMaybeKeywordExpression("viewof", "ViewExpression") || this.parseMaybeKeywordExpression("mutable", "MutableExpression") || super.parseExprAtom(refDestructuringErrors);
    }
    startCell() {
        this.O_function = 0;
        this.O_async = false;
        this.O_generator = false;
        this.strict = true;
        this.enterScope(2 | 4 | 8);
    }
    finishCell(node, body, id) {
        if (id) this.checkLocal(id);
        node.id = id;
        node.body = body;
        node.async = this.O_async;
        node.generator = this.O_generator;
        this.exitScope();
        return this.finishNode(node, "Cell");
    }
    parseCell(node, eof) {
        const lookahead = new CellParser({}, this.input, this.start);
        let token = lookahead.getToken();
        let body = null;
        let id = null;
        this.startCell();
        if (token.type === types2._import && lookahead.getToken().type !== types2.parenL) {
            body = this.parseImport(this.startNode());
        } else if (token.type !== types2.eof && token.type !== types2.semi) {
            if (token.type === types2.name) {
                if (token.value === "viewof" || token.value === "mutable") {
                    token = lookahead.getToken();
                    if (token.type !== types2.name) {
                        lookahead.unexpected();
                    }
                }
                token = lookahead.getToken();
                if (token.type === types2.eq) {
                    id = this.parseMaybeKeywordExpression("viewof", "ViewExpression") || this.parseMaybeKeywordExpression("mutable", "MutableExpression") || this.parseIdent();
                    token = lookahead.getToken();
                    this.expect(types2.eq);
                }
            }
            if (token.type === types2.braceL) {
                body = this.parseBlock();
            } else {
                body = this.parseExpression();
                if (id === null && (body.type === "FunctionExpression" || body.type === "ClassExpression")) {
                    id = body.id;
                }
            }
        }
        this.semicolon();
        if (eof) this.expect(types2.eof);
        return this.finishCell(node, body, id);
    }
    parseTopLevel(node) {
        return this.parseCell(node, true);
    }
    toAssignable(node, isBinding, refDestructuringErrors) {
        return node.type === "MutableExpression" ? node : super.toAssignable(node, isBinding, refDestructuringErrors);
    }
    checkLocal(id) {
        const node = id.id || id;
        if (defaultGlobals.has(node.name) || node.name === "arguments") {
            this.raise(node.start, `Identifier '${node.name}' is reserved`);
        }
    }
    checkUnreserved(node) {
        if (node.name === "viewof" || node.name === "mutable") {
            this.raise(node.start, `Unexpected keyword '${node.name}'`);
        }
        return super.checkUnreserved(node);
    }
    checkLVal(expr, bindingType, checkClashes) {
        return super.checkLVal(expr.type === "MutableExpression" ? expr.id : expr, bindingType, checkClashes);
    }
    unexpected(pos) {
        this.raise(pos != null ? pos : this.start, this.type === types2.eof ? "Unexpected end of input" : "Unexpected token");
    }
    parseMaybeKeywordExpression(keyword, type) {
        if (this.isContextual(keyword)) {
            const node = this.startNode();
            this.next();
            node.id = this.parseIdent();
            return this.finishNode(node, type);
        }
    }
}
new TokContext("`", true, true, (parser)=>readTemplateToken.call(parser)
);
function readTemplateToken() {
    out: for(; this.pos < this.input.length; this.pos++){
        switch(this.input.charCodeAt(this.pos)){
            case 92:
                {
                    if (this.pos < this.input.length - 1) ++this.pos;
                    break;
                }
            case 36:
                {
                    if (this.input.charCodeAt(this.pos + 1) === 123) {
                        if (this.pos === this.start && this.type === types2.invalidTemplate) {
                            this.pos += 2;
                            return this.finishToken(types2.dollarBraceL);
                        }
                        break out;
                    }
                    break;
                }
        }
    }
    return this.finishToken(types2.invalidTemplate, this.input.slice(this.start, this.pos));
}
function parseModule(input, { globals  } = {}) {
    const program = ModuleParser.parse(input);
    for (const cell of program.cells){
        parseReferences(cell, input, globals);
        parseFeatures(cell, input);
    }
    return program;
}
class ModuleParser extends CellParser {
    parseTopLevel(node) {
        if (!node.cells) node.cells = [];
        while(this.type !== types2.eof){
            const cell = this.parseCell(this.startNode());
            cell.input = this.input;
            node.cells.push(cell);
        }
        this.next();
        return this.finishNode(node, "Program");
    }
}
function parseReferences(cell, input, globals = defaultGlobals) {
    if (!cell.body) {
        cell.references = [];
    } else if (cell.body.type === "ImportDeclaration") {
        cell.references = cell.body.injections ? cell.body.injections.map((i)=>i.imported
        ) : [];
    } else {
        try {
            cell.references = findReferences(cell, globals);
        } catch (error29) {
            if (error29.node) {
                const loc = getLineInfo(input, error29.node.start);
                error29.message += ` (${loc.line}:${loc.column})`;
                error29.pos = error29.node.start;
                error29.loc = loc;
                delete error29.node;
            }
            throw error29;
        }
    }
    return cell;
}
function parseFeatures(cell, input) {
    if (cell.body && cell.body.type !== "ImportDeclaration") {
        try {
            cell.fileAttachments = findFeatures(cell, "FileAttachment");
            cell.databaseClients = findFeatures(cell, "DatabaseClient");
            cell.secrets = findFeatures(cell, "Secret");
        } catch (error30) {
            if (error30.node) {
                const loc = getLineInfo(input, error30.node.start);
                error30.message += ` (${loc.line}:${loc.column})`;
                error30.pos = error30.node.start;
                error30.loc = loc;
                delete error30.node;
            }
            throw error30;
        }
    } else {
        cell.fileAttachments = new Map();
        cell.databaseClients = new Map();
        cell.secrets = new Map();
    }
    return cell;
}
async function esbuildCompile(input, workingDir, args, format88) {
    format88 = format88 ?? "esm";
    const fullArgs = [
        "--bundle",
        `--format=${format88}`,
        ...args || [], 
    ];
    return await esbuildCommand(fullArgs, input, workingDir);
}
async function esbuildCommand(args, input, workingDir) {
    const cmd = [
        binaryPath("esbuild"),
        ...args, 
    ];
    const result = await execProcess({
        cmd,
        cwd: workingDir,
        stdout: "piped"
    }, input);
    if (result.success) {
        return result.stdout;
    } else {
        throw new Error("esbuild command failed");
    }
}
async function breakQuartoMd(src, validate3 = false) {
    const nb = {
        cells: []
    };
    const yamlRegEx = /^---\s*$/;
    const startCodeCellRegEx = new RegExp("^\\s*```+\\s*\\{([=A-Za-z]+)( *[ ,].*)?\\}\\s*$");
    const startCodeRegEx = /^```/;
    const endCodeRegEx = /^```\s*$/;
    const delimitMathBlockRegEx = /^\$\$/;
    let language = "";
    const lineBuffer = [];
    const flushLineBuffer = async (cell_type, index)=>{
        if (lineBuffer.length) {
            if (lineBuffer[lineBuffer.length - 1].substring === "") {
                lineBuffer.splice(lineBuffer.length - 1, 1);
            }
            const mappedChunks = [];
            for (const line of lineBuffer){
                mappedChunks.push(line.range);
                mappedChunks.push("\n");
            }
            mappedChunks.pop();
            const source = mappedString(src, mappedChunks);
            const cell = {
                cell_type: cell_type === "code" ? {
                    language
                } : cell_type,
                source: source,
                sourceOffset: 0,
                sourceStartLine: 0,
                sourceVerbatim: source,
                cellStartLine: index
            };
            if (cell_type === "code" && (language === "ojs" || language === "dot")) {
                const { yaml , source , sourceStartLine  } = await partitionCellOptionsMapped1(language, cell.source, validate3);
                const breaks = Array.from(cell.source.value.matchAll(/\r?\n/g));
                let strUpToLastBreak = "";
                if (sourceStartLine > 0) {
                    if (breaks.length) {
                        const lastBreak = breaks[Math.min(sourceStartLine - 1, breaks.length - 1)];
                        const pos = lastBreak.index + lastBreak[0].length;
                        strUpToLastBreak = cell.source.value.substring(0, pos);
                    } else {
                        strUpToLastBreak = cell.source.value;
                    }
                }
                cell.sourceOffset = strUpToLastBreak.length + "```{ojs}\n".length;
                cell.sourceVerbatim = mappedString(cell.sourceVerbatim, [
                    "```{ojs}\n",
                    {
                        start: 0,
                        end: cell.sourceVerbatim.value.length
                    },
                    "\n```", 
                ]);
                cell.source = source;
                cell.options = yaml;
                cell.sourceStartLine = sourceStartLine;
            }
            if (mdTrimEmptyLines1(lines(cell.source.value)).length > 0) {
                nb.cells.push(cell);
            }
            lineBuffer.splice(0, lineBuffer.length);
        }
    };
    let inYaml = false, inMathBlock = false, inCodeCell = false, inCode = false;
    const srcLines = rangedLines(src.value);
    for(let i = 0; i < srcLines.length; ++i){
        const line = srcLines[i];
        if (yamlRegEx.test(line.substring) && !inCodeCell && !inCode && !inMathBlock) {
            if (inYaml) {
                lineBuffer.push(line);
                await flushLineBuffer("raw", i);
                inYaml = false;
            } else {
                await flushLineBuffer("markdown", i);
                lineBuffer.push(line);
                inYaml = true;
            }
        } else if (startCodeCellRegEx.test(line.substring)) {
            const m = line.substring.match(startCodeCellRegEx);
            language = m[1];
            await flushLineBuffer("markdown", i);
            inCodeCell = true;
        } else if (endCodeRegEx.test(line.substring)) {
            if (inCodeCell) {
                inCodeCell = false;
                await flushLineBuffer("code", i);
            } else {
                inCode = !inCode;
                lineBuffer.push(line);
            }
        } else if (startCodeRegEx.test(line.substring)) {
            inCode = true;
            lineBuffer.push(line);
        } else if (delimitMathBlockRegEx.test(line.substring)) {
            if (inMathBlock) {
                await flushLineBuffer("math", i);
            } else {
                if (inYaml || inCode || inCodeCell) {} else {
                    await flushLineBuffer("markdown", i);
                }
            }
            inMathBlock = !inMathBlock;
            lineBuffer.push(line);
        } else {
            lineBuffer.push(line);
        }
    }
    await flushLineBuffer("markdown", srcLines.length);
    return nb;
}
function mdTrimEmptyLines1(lines1) {
    const firstNonEmpty = lines1.findIndex((line)=>line.trim().length > 0
    );
    if (firstNonEmpty === -1) {
        return [];
    }
    lines1 = lines1.slice(firstNonEmpty);
    let lastNonEmpty = -1;
    for(let i = lines1.length - 1; i >= 0; i--){
        if (lines1[i].trim().length > 0) {
            lastNonEmpty = i;
            break;
        }
    }
    if (lastNonEmpty > -1) {
        lines1 = lines1.slice(0, lastNonEmpty + 1);
    }
    return lines1;
}
const walkerBase = make({
    Import () {},
    ViewExpression (node, st, c) {
        c(node.id, st, "Identifier");
    },
    MutableExpression (node, st, c) {
        c(node.id, st, "Identifier");
    },
    Cell (node, st, c) {
        c(node.body, st);
    },
    Program (node, st, c) {
        if (node.body) {
            for(let i = 0, list = node.body; i < list.length; i += 1){
                const stmt = list[i];
                c(stmt, st, "Statement");
            }
        } else if (node.cells) {
            for(let i = 0, list = node.cells; i < list.length; i += 1){
                const stmt = list[i];
                c(stmt, st);
            }
        } else {
            error("I don't know how to walk this node", node);
            throw new Error("Internal error while walking OJS source");
        }
    }
});
function ojsSimpleWalker(parse18, visitor) {
    simple(parse18, visitor, walkerBase);
}
function resolveResourceFilename(resource, rootDir) {
    if (resource.pathType == "relative") {
        const result = resolve2(rootDir, dirname2(resource.referent), resource.filename);
        return result;
    } else if (resource.pathType === "root-relative") {
        const result = resolve2(rootDir, dirname2(resource.referent), `.${resource.filename}`);
        return result;
    } else {
        throw new Error(`Unrecognized pathType ${resource.pathType}`);
    }
}
function uniqueResources(resourceList) {
    const result = [];
    const uniqResources = new Map();
    for (const resource of resourceList){
        if (!uniqResources.has(resource.filename)) {
            result.push(resource);
            uniqResources.set(resource.filename, resource);
        }
    }
    return result;
}
async function directDependencies(source1, fileDir, language, projectRoot1) {
    const resolveES6Path = (path81, originDir, projectRoot)=>{
        if (path81.startsWith("/")) {
            if (projectRoot === undefined) {
                return {
                    pathType: "root-relative",
                    resolvedImportPath: resolve2(originDir, `.${path81}`)
                };
            } else {
                return {
                    pathType: "root-relative",
                    resolvedImportPath: resolve2(projectRoot, `.${path81}`)
                };
            }
        } else {
            return {
                pathType: "relative",
                resolvedImportPath: resolve2(originDir, path81)
            };
        }
    };
    const localImports = (parse19)=>{
        const result = [];
        ojsSimpleWalker(parse19, {
            ExportNamedDeclaration (node) {
                if (node.source?.value) {
                    const source = node.source?.value;
                    if (source.startsWith("/") || source.startsWith(".")) {
                        result.push(source);
                    }
                }
            },
            ImportDeclaration (node) {
                const source = node.source?.value;
                if (source.startsWith("/") || source.startsWith(".")) {
                    result.push(source);
                }
            }
        });
        return result;
    };
    let ast;
    if (language === "js") {
        try {
            ast = parse32(source1.value, {
                ecmaVersion: "2020",
                sourceType: "module"
            });
        } catch (e) {
            if (!(e instanceof SyntaxError)) {
                throw e;
            }
            return [];
        }
    } else if (language === "ojs") {
        try {
            ast = parseModule(source1.value);
        } catch (e) {
            if (!(e instanceof SyntaxError)) {
                throw e;
            }
            return [];
        }
    } else {
        const ojsCellsSrc = (await breakQuartoMd(source1)).cells.filter((cell)=>cell.cell_type !== "markdown" && cell.cell_type !== "raw" && cell.cell_type !== "math" && cell.cell_type?.language === "ojs"
        ).flatMap((v)=>v.source
        );
        return await directDependencies(mappedConcat(ojsCellsSrc), fileDir, "ojs", projectRoot1);
    }
    return localImports(ast).map((importPath)=>{
        const { resolvedImportPath , pathType  } = resolveES6Path(importPath, fileDir, projectRoot1);
        return {
            resolvedImportPath,
            pathType,
            importPath
        };
    });
}
async function extractResolvedResourceFilenamesFromQmd(markdown, mdDir, projectRoot) {
    const pageResources = [];
    for (const cell of (await breakQuartoMd(markdown)).cells){
        if (cell.cell_type !== "markdown" && cell.cell_type !== "raw" && cell.cell_type !== "math" && cell.cell_type?.language === "ojs") {
            pageResources.push(...await extractResourceDescriptionsFromOJSChunk(cell.source, mdDir, projectRoot));
        }
    }
    const result = new Set();
    for (const resource of uniqueResources(pageResources)){
        result.add(resolveResourceFilename(resource, Deno.cwd()));
    }
    return Array.from(result);
}
async function extractResourceDescriptionsFromOJSChunk(ojsSource, mdDir, projectRoot) {
    const literalFileAttachments = (parse20)=>{
        const result = [];
        ojsSimpleWalker(parse20, {
            CallExpression (node) {
                if (node.callee?.type !== "Identifier") {
                    return;
                }
                if (node.callee?.name !== "FileAttachment") {
                    return;
                }
                const args = node.arguments || [];
                if (args.length < 1) {
                    return;
                }
                if (args[0]?.type !== "Literal") {
                    return;
                }
                result.push(args[0]?.value);
            }
        });
        return result;
    };
    let result1 = [];
    const handled = new Set();
    const imports = new Map();
    const rootReferent = `${mdDir}/<<root>>.qmd`;
    for (const { resolvedImportPath , pathType: pathType1 , importPath: importPath1  } of (await directDependencies(ojsSource, mdDir, "ojs", projectRoot))){
        if (!imports.has(resolvedImportPath)) {
            const v = {
                filename: resolvedImportPath,
                referent: rootReferent,
                pathType: pathType1,
                importPath: importPath1,
                resourceType: "import"
            };
            result1.push(v);
            imports.set(resolvedImportPath, v);
        }
    }
    while(imports.size > 0){
        const [thisResolvedImportPath, importResource] = imports.entries().next().value;
        imports.delete(thisResolvedImportPath);
        if (handled.has(thisResolvedImportPath)) {
            continue;
        }
        handled.add(thisResolvedImportPath);
        let source;
        try {
            source = Deno.readTextFileSync(thisResolvedImportPath);
        } catch (_e) {
            console.error(`WARNING: While following dependencies, could not resolve reference:`);
            console.error(`  Reference: ${importResource.importPath}`);
            console.error(`  In file: ${importResource.referent}`);
            continue;
        }
        let language;
        if (thisResolvedImportPath.endsWith(".js")) {
            language = "js";
        } else if (thisResolvedImportPath.endsWith(".ojs")) {
            language = "ojs";
        } else if (thisResolvedImportPath.endsWith(".qmd")) {
            language = "qmd";
        } else {
            throw new Error(`Unknown language "${language}" in file "${thisResolvedImportPath}"`);
        }
        for (const { resolvedImportPath , pathType , importPath  } of (await directDependencies(asMappedString(source), dirname2(thisResolvedImportPath), language, projectRoot))){
            if (!imports.has(resolvedImportPath)) {
                const v = {
                    filename: resolvedImportPath,
                    referent: thisResolvedImportPath,
                    pathType,
                    importPath,
                    resourceType: "import"
                };
                result1.push(v);
                imports.set(resolvedImportPath, v);
            }
        }
    }
    const fileAttachments = [];
    for (const importFile of result1){
        if (importFile.filename.endsWith(".ojs")) {
            try {
                const ast = parseModule(Deno.readTextFileSync(importFile.filename));
                for (const attachment of literalFileAttachments(ast)){
                    fileAttachments.push({
                        filename: attachment,
                        referent: importFile.filename
                    });
                }
            } catch (e) {
                if (!(e instanceof SyntaxError)) {
                    throw e;
                }
            }
        }
    }
    try {
        const ast = parseModule(ojsSource.value);
        for (const attachment of literalFileAttachments(ast)){
            fileAttachments.push({
                filename: attachment,
                referent: rootReferent
            });
        }
    } catch (e) {
        if (!(e instanceof SyntaxError)) {
            throw e;
        }
    }
    result1 = result1.filter((description)=>!description.filename.endsWith(".qmd")
    );
    result1 = result1.map((description)=>{
        const { referent , resourceType , importPath , pathType  } = description;
        if (pathType === "relative") {
            let relName = relative2(mdDir, description.filename);
            if (!relName.startsWith(".")) {
                relName = `./${relName}`;
            }
            return {
                filename: relName,
                referent,
                importPath,
                pathType,
                resourceType
            };
        } else {
            return description;
        }
    });
    result1.push(...fileAttachments.map(({ filename , referent  })=>{
        let pathType;
        if (filename.startsWith("/")) {
            pathType = "root-relative";
        } else {
            pathType = "relative";
        }
        return {
            referent,
            filename,
            pathType,
            resourceType: "FileAttachment"
        };
    }));
    return result1;
}
async function makeSelfContainedResources(resourceList, wd) {
    const asDataURL = (content, mimeType)=>{
        const b64Src = encode(content);
        return `data:${mimeType};base64,${b64Src}`;
    };
    const uniqResources = uniqueResources(resourceList);
    const jsFiles = uniqResources.filter((r)=>r.resourceType === "import" && r.filename.endsWith(".js")
    );
    const ojsFiles = uniqResources.filter((r)=>r.resourceType === "import" && r.filename.endsWith("ojs")
    );
    const attachments = uniqResources.filter((r)=>r.resourceType !== "import"
    );
    const jsModuleResolves = [];
    if (jsFiles.length > 0) {
        const bundleInput = jsFiles.map((r)=>`export * from "${r.filename}";`
        ).join("\n");
        const es6BundledModule = await esbuildCompile(bundleInput, wd, [
            "--target=es2018"
        ]);
        const jsModule = asDataURL(es6BundledModule, "application/javascript");
        jsModuleResolves.push(...jsFiles.map((f)=>[
                f.importPath,
                jsModule
            ]
        ));
    }
    const result = [
        ...jsModuleResolves,
        ...ojsFiles.map((f)=>[
                f.importPath,
                asDataURL(Deno.readTextFileSync(f.filename), "application/ojs-javascript"), 
            ]
        ),
        ...attachments.map((f)=>{
            const resolvedFileName = resolveResourceFilename(f, Deno.cwd());
            return [
                f.filename,
                asDataURL(Deno.readTextFileSync(resolvedFileName), lookup1(resolvedFileName)), 
            ];
        }), 
    ];
    return result;
}
function resourcesFromMetadata(resourcesMetadata) {
    const resources = [];
    if (resourcesMetadata) {
        if (Array.isArray(resourcesMetadata)) {
            for (const file of resourcesMetadata){
                resources.push(String(file));
            }
        } else {
            resources.push(String(resourcesMetadata));
        }
    }
    return resources;
}
async function resolveFileResources(rootDir, fileDir, markdown, globs) {
    const ignore2 = engineIgnoreGlobs().concat(kQuartoScratch + "/").concat([
        "**/.*",
        "**/.*/**"
    ]);
    const resources = resolvePathGlobs(fileDir, globs, ignore2);
    if (markdown.length > 0) {
        resources.include.push(...await extractResolvedResourceFilenamesFromQmd(asMappedString(markdown), fileDir, rootDir));
    }
    return resources;
}
class Semaphore {
    value;
    tasks;
    constructor(value){
        this.value = value;
        this.tasks = [];
    }
    release() {
        this.value += 1;
        if (this.tasks.length) {
            const { resolve: resolve6  } = this.tasks.pop();
            resolve6();
        }
    }
    async acquire() {
        if (this.value > 0) {
            this.value -= 1;
            return;
        }
        const result = new Promise((resolve7, reject)=>{
            this.tasks.push({
                resolve: resolve7,
                reject
            });
        });
        await result;
        await this.acquire();
    }
    async runExclusive(fun) {
        await this.acquire();
        try {
            fun();
        } finally{
            this.release();
        }
    }
}
function makeInitializer(thunk) {
    let initStarted = false;
    const hasInitSemaphore = new Semaphore(0);
    return async ()=>{
        if (initStarted) {
            await hasInitSemaphore.runExclusive(async ()=>{});
            return;
        }
        initStarted = true;
        await thunk();
        hasInitSemaphore.release();
    };
}
let initializer = ()=>{
    throw new Error("initializer not set!!");
};
async function initState() {
    await initializer();
}
let hasSet = false;
function setInitializer(init5) {
    if (hasSet) {
        return;
    }
    initializer = makeInitializer(init5);
    hasSet = true;
}
const getProjectConfigFieldsSchema = defineCached(async ()=>{
    return {
        schema: objectSchemaFromFieldsObject(getYamlIntelligenceResource("schema/project.yml")),
        errorHandlers: []
    };
}, "project-config-fields");
const getProjectConfigSchema = defineCached(async ()=>{
    const projectConfigFields = await getProjectConfigFieldsSchema();
    const execute = await getFormatExecuteOptionsSchema();
    const format89 = await getFrontMatterFormatSchema();
    const result = allOfSchema(objectSchema({
        properties: {
            execute,
            format: format89
        },
        description: "be a Quarto YAML front matter object"
    }), execute, await getFrontMatterSchema(), projectConfigFields);
    return {
        schema: describeSchema(result, "a project configuration object"),
        errorHandlers: []
    };
}, "project-config");
function patchMarkdownDescriptions() {
    const descriptionList = getYamlIntelligenceResource("schema/html-descriptions.yml");
    const schemaList = Object.values(getSchemaDefinitionsObject());
    let cursor = 0;
    for (const schema of schemaList){
        walkSchema(schema, (s)=>{
            if (s === false || s === true) {
                return;
            }
            const description = s && s.tags && s.tags.description;
            if (!description) {
                return;
            }
            const fixedDescription = descriptionList[cursor++];
            if (typeof fixedDescription === "string") {
                s.documentation = fixedDescription;
            } else if (typeof (fixedDescription && fixedDescription.short) === "string") {
                s.documentation = fixedDescription.short;
            }
        });
    }
}
async function initYamlIntelligence(obj) {
    const { resourceModule , patchMarkdown ,  } = obj;
    setYamlIntelligenceResources(resourceModule);
    await loadDefaultSchemaDefinitions();
    getFormatAliases();
    await getFrontMatterSchema();
    await getProjectConfigSchema();
    await getEngineOptionsSchema();
    for (const schema of getYamlIntelligenceResource("schema/external-schemas.yml")){
        setSchemaDefinition(schema);
    }
    if (patchMarkdown === undefined || patchMarkdown) {
        patchMarkdownDescriptions();
    }
}
async function initYamlIntelligenceResourcesFromFilesystem() {
    const resourceModule = (await import(toFileUrl2(resourcePath("editor/tools/yaml/yaml-intelligence-resources.json")).href, {
        assert: {
            type: "json"
        }
    })).default;
    await initYamlIntelligence({
        resourceModule
    });
}
function ojsParseError(acornError, ojsSource) {
    const acornMsg = String(acornError).split("\n")[0].trim().replace(/ *\(\d+:\d+\)$/, "");
    const { line , column  } = indexToRowCol(ojsSource.originalString)(ojsSource.mapClosest(acornError.pos));
    const errMsg = `OJS parsing failed on line ${line + 1}, column ${column + 1}`;
    error(errMsg);
    error(acornMsg);
    error("----- OJS Source:");
    const ojsSourceSplit = ojsSource.value.split("\n");
    for(let i = 0; i < ojsSourceSplit.length; ++i){
        error(ojsSourceSplit[i]);
        if (i + 1 === acornError.loc.line) {
            error(" ".repeat(acornError.loc.column) + "^");
        }
    }
    error("-----");
}
function computePageTitle(format90, extras) {
    const meta = extras?.metadata || {};
    const pageTitle = meta[kPageTitle] || format90.metadata[kPageTitle];
    const titlePrefix = extras?.pandoc?.[kTitlePrefix] || format90.metadata[kWebsite]?.[kTitle];
    const title13 = format90.metadata[kTitle];
    if (pageTitle !== undefined) {
        return pageTitle;
    } else if (titlePrefix !== undefined) {
        if (titlePrefix === title13) {
            return title13;
        } else if (title13 !== undefined) {
            return titlePrefix + " - " + title13;
        } else {
            return undefined;
        }
    } else {
        return title13;
    }
}
function inputFileHref(href) {
    const [hrefDir, hrefStem] = dirAndStem(href);
    const htmlHref = "/" + join3(hrefDir, `${hrefStem}.html`);
    return pathWithForwardSlashes(htmlHref);
}
function websiteNavigationConfig(project) {
    let navbar = websiteConfigMetadata(kSiteNavbar, project.config);
    if (typeof navbar !== "object") {
        navbar = undefined;
    }
    const sidebar = websiteConfig(kSiteSidebar, project.config);
    const sidebars = Array.isArray(sidebar) ? sidebar : typeof sidebar == "object" ? [
        sidebar
    ] : undefined;
    if (sidebars && sidebars[0]) {
        if (sidebars[0].style === undefined) {
            sidebars[0].style = "floating";
        }
        if (sidebars[0].contents === undefined) {
            sidebars[0].contents = [];
        }
        if (sidebars[0].tools === undefined) {
            sidebars[0].tools = [];
        }
    }
    if (sidebars && sidebars.length > 1) {
        const sidebarOptions = __VIRTUAL_FILE107(sidebars[0]);
        delete sidebarOptions.id;
        delete sidebarOptions.title;
        sidebarOptions.contents.splice(0, sidebarOptions.contents.length);
        for(let i = 1; i < sidebars.length; i++){
            sidebars[i] = {
                ...sidebarOptions,
                ...sidebars[i]
            };
        }
    }
    const pageNavigation = websiteConfigBoolean(kSitePageNavigation, false, project.config);
    const footerValue = (value)=>{
        if (typeof value === "string") {
            return value;
        } else if (Array.isArray(value)) {
            return value;
        } else {
            return undefined;
        }
    };
    const footer = {};
    const footerConfig = websiteConfig(kPageFooter, project.config);
    if (typeof footerConfig === "string") {
        footer.center = footerConfig;
    } else if (!Array.isArray(footerConfig)) {
        footer.left = footerValue(footerConfig?.left);
        footer.center = footerValue(footerConfig?.center);
        footer.right = footerValue(footerConfig?.right);
    }
    if (footer.center === undefined && cookieConsentEnabled(project)) {
        footer.center = " ";
    }
    const pageMargin = {};
    const headerVal = websiteConfigArray(kMarginHeader, project.config);
    if (headerVal) {
        pageMargin.header = headerVal;
    }
    const footerVal = websiteConfigArray(kMarginFooter, project.config);
    if (footerVal) {
        pageMargin.footer = footerVal;
    }
    const bodyDecorators = {};
    const bodyHeaderVal = websiteConfigArray(kBodyHeader, project.config);
    if (bodyHeaderVal) {
        bodyDecorators.header = bodyHeaderVal;
    }
    const bodyFooterVal = websiteConfigArray(kBodyFooter, project.config);
    if (bodyFooterVal) {
        bodyDecorators.footer = bodyFooterVal;
    }
    return {
        navbar,
        sidebars,
        pageNavigation,
        footer,
        pageMargin,
        bodyDecorators
    };
}
function flattenItems(sidebarItems, includeItem) {
    const items = [];
    const flatten = (sidebarItem)=>{
        if (includeItem(sidebarItem)) {
            items.push(sidebarItem);
        }
        if (sidebarItem.contents) {
            items.push(...flattenItems(sidebarItem.contents, includeItem));
        }
    };
    sidebarItems.forEach(flatten);
    return items;
}
function imageSize(path82) {
    if (path82 !== undefined) {
        if (path82.endsWith(".png")) {
            if (existsSync(path82)) {
                const imageData = Deno.readFileSync(path82);
                const png = new PngImage(imageData);
                return {
                    height: png.height,
                    width: png.width
                };
            }
        }
    }
}
function imageContentType(path83) {
    const ext = extname2(path83);
    return kimageTypes[ext];
}
const kimageTypes = {
    ".apng": "image/apng",
    ".avif": "image/avif",
    ".gif": "image/gif",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".jfif": "image/jpeg",
    ".pjpeg": "image/jpeg",
    ".pjp": "image/jpeg",
    ".png": "image/png",
    ".svg": "image/svg+xml",
    ".webp": "image/webp"
};
const kPreviewImgClass = "preview-image";
const kNamedFilePattern = "(.*?(?:preview|feature|cover|thumbnail).*?(?:\\.png|\\.gif|\\.jpg|\\.jpeg|\\.webp))";
const kPreviewClassPattern = `!\\[[^\\]]*\\]\\((.*?)(?:\\".*\\")?\\)\\{[^\\|]*\\.${kPreviewImgClass}[\\s\\}]+`;
const kMdNamedImagePattern = `!\\[[^\\]]*\\]\\(${kNamedFilePattern}(?:\\".*\\")?\\)(?:\\{[^\\|]*\.*[\\s\\}]+)?`;
const kNamedFileRegex = RegExp(kNamedFilePattern);
const kMdPreviewClassRegex = RegExp(kPreviewClassPattern);
const kMdNamedImageRegex = RegExp(kMdNamedImagePattern);
const kMarkdownImg = /!\[[^\]]*\]\((.*?)(?:\".*\")?\)(?:\{(?:[^\|]*)\})?/;
function findPreviewImg(doc) {
    let image2 = undefined;
    const match = doc.querySelector(`img.${kPreviewImgClass}`);
    if (match) {
        const src = getDecodedAttribute(match, "src");
        if (src !== null) {
            image2 = src;
        }
    }
    if (image2 == undefined) {
        const imgs = doc.querySelectorAll("img");
        for(let i = 0; i < imgs.length; i++){
            const img = imgs[i];
            const src = getDecodedAttribute(img, "src");
            if (src !== null && kNamedFileRegex.test(src)) {
                image2 = src;
                break;
            }
        }
    }
    return image2;
}
function estimateReadingTimeMinutes(markdown) {
    if (markdown) {
        const wordCount = markdown.split(" ").length;
        return wordCount / 200;
    }
    return 0;
}
function findPreviewImgMd(markdown) {
    if (markdown) {
        const explicitMatch = markdown.match(kMdPreviewClassRegex);
        if (explicitMatch) {
            return explicitMatch[1];
        }
        const fileNameMatch = markdown.match(kMdNamedImageRegex);
        if (fileNameMatch) {
            return fileNameMatch[1];
        }
        const match = markdown.match(kMarkdownImg);
        if (match) {
            return match[1];
        }
    }
    return undefined;
}
function findDescriptionMd(markdown) {
    if (markdown) {
        const previewText = [];
        let accum = false;
        const skipLines = [
            /^\#+/,
            /^\:\:\:[\:]*/
        ];
        const emptyLine = (line)=>{
            return line.trim() === "";
        };
        for (const line1 of lines(markdown)){
            if (!accum) {
                if (!emptyLine(line1) && !skipLines.find((skip)=>line1.match(skip)
                )) {
                    accum = true;
                    previewText.push(line1);
                }
            } else {
                if (emptyLine(line1) || skipLines.find((skip)=>line1.match(skip)
                )) {
                    break;
                } else {
                    previewText.push(line1);
                }
            }
        }
        return previewText.join("\n");
    }
    return undefined;
}
const createMarkdownPipeline = (envelopeId, handlers)=>{
    return {
        markdownAfterBody () {
            const pipelineMarkdown = {};
            handlers.forEach((handler)=>{
                const handlerPipelineMarkdown = handler.getUnrendered();
                if (handlerPipelineMarkdown) {
                    const inlines = handlerPipelineMarkdown.inlines;
                    if (inlines) {
                        pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
                        for (const key of Object.keys(inlines)){
                            pipelineMarkdown.inlines[key] = inlines[key];
                        }
                    }
                    const blocks = handlerPipelineMarkdown.blocks;
                    if (blocks) {
                        pipelineMarkdown.blocks = pipelineMarkdown.blocks || {};
                        for (const key of Object.keys(blocks)){
                            pipelineMarkdown.blocks[key] = blocks[key];
                        }
                    }
                }
            });
            return createMarkdownRenderEnvelope(envelopeId, pipelineMarkdown);
        },
        processRenderedMarkdown (doc) {
            processMarkdownRenderEnvelope(doc, envelopeId, handlers.map((handler)=>{
                return handler.processRendered;
            }));
        }
    };
};
function createMarkdownRenderEnvelope(envelopeId, pipelineMarkdown) {
    const envelope = markdownEnvelopeWriter(envelopeId);
    if (pipelineMarkdown.inlines) {
        for (const key of Object.keys(pipelineMarkdown.inlines)){
            envelope.addInline(key, pipelineMarkdown.inlines[key]);
        }
    }
    if (pipelineMarkdown.blocks) {
        for (const key of Object.keys(pipelineMarkdown.blocks)){
            envelope.addBlock(key, pipelineMarkdown.blocks[key]);
        }
    }
    return envelope.toMarkdown();
}
function processMarkdownRenderEnvelope(doc, envelopeId, processors) {
    const renderedMarkdown = readEnvelope(doc, envelopeId);
    processors.forEach((processor)=>{
        processor(renderedMarkdown, doc);
    });
}
const markdownEnvelopeWriter = (envelopeId)=>{
    const renderList = [];
    const hiddenSpan = (id, contents)=>{
        return `[${contents}]{.hidden render-id="${id}"}`;
    };
    const hiddenDiv = (id, contents)=>{
        return `\n:::{.hidden render-id="${id}"}\n${contents}\n:::\n`;
    };
    return {
        addBlock: (id, value)=>{
            renderList.push(hiddenDiv(id, value));
        },
        addInline: (id, value)=>{
            renderList.push(hiddenSpan(id, value));
        },
        toMarkdown: ()=>{
            const contents = renderList.join("\n");
            return `\n:::{#${envelopeId} .hidden}\n${contents}\n:::\n`;
        }
    };
};
const readEnvelope = (doc, envelopeId)=>{
    const envelope = doc.getElementById(envelopeId);
    const contents = {};
    const addContent = (node)=>{
        const el = node;
        const id = el.getAttribute("data-render-id");
        if (id) {
            contents[id] = el;
        }
    };
    if (envelope) {
        const blockNodes = envelope.querySelectorAll("div[data-render-id]");
        blockNodes.forEach((blockNode)=>{
            addContent(blockNode);
        });
        const inlineNodes = envelope.querySelectorAll("span[data-render-id]");
        inlineNodes.forEach((inlineNode)=>{
            addContent(inlineNode);
        });
        envelope.remove();
    }
    return contents;
};
const kDateFormat1 = "date-format";
const kQuartoListingClass = "quarto-listing";
function templateMarkdownHandler(template6, listing, items, format91, cache, attributes) {
    const reshapedItems = items.map((item)=>{
        resolveItemForTemplate(item, listing);
        const record = {
            ...item
        };
        if (item.author) {
            record.author = item.author.join(", ");
        }
        const dateFormat = listing[kDateFormat1] || format91.metadata[kDateFormat1];
        const fieldTypes = listing[kFieldTypes];
        for (const field of Object.keys(fieldTypes)){
            if (fieldTypes[field] === kFieldDate) {
                const dateRaw = item[field];
                if (dateRaw) {
                    const includeTime = field === kFieldFileModified;
                    const date = typeof dateRaw === "string" ? new Date(dateRaw) : dateRaw;
                    const locale = format91.metadata.lang || "en";
                    record[field] = dateFormat ? formatDate(date, locale, dateFormat) : includeTime ? formatDate(date, locale, "short", "medium") : formatDate(date, locale, "medium");
                }
            } else if (fieldTypes[field] === "minutes") {
                const val = item[field];
                record[field] = localizedString(format91, kListingPageMinutesCompact, [
                    Math.floor(val).toString(), 
                ]);
            }
        }
        if (item.description !== undefined) {
            const maxDescLength = listing[kMaxDescLength] || -1;
            if (maxDescLength > 0) {
                record.description = truncateText(item.description, maxDescLength);
            }
        }
        return record;
    });
    const reshapedListing = reshapeListing(listing, format91);
    const paramsForType = (type)=>{
        const ejsParams = {
            items: reshapedItems
        };
        if (type !== ListingType.Custom) {
            ejsParams.listing = reshapedListing;
        } else {
            ejsParams["metadataAttrs"] = reshapedListing.utilities.metadataAttrs;
        }
        return ejsParams;
    };
    const filterRendered = renderEjs(resourcePath("projects/website/listing/_filter.ejs.md"), {
        items: reshapedItems,
        listing: reshapedListing
    });
    const templateRendered = renderEjs(template6, paramsForType(listing.type), true, cache);
    const paginationRendered = renderEjs(resourcePath("projects/website/listing/_pagination.ejs.md"), {
        items: reshapedItems,
        listing: reshapedListing
    });
    const markdown = [
        filterRendered,
        templateRendered,
        paginationRendered
    ].join("\n");
    const pipelineId = (id)=>{
        return `pipeline-listing-${id}`;
    };
    return {
        getUnrendered () {
            return {
                blocks: {
                    [pipelineId(listing.id)]: markdown
                }
            };
        },
        processRendered (rendered, doc) {
            let listingEl = doc.querySelector(`div[id='${listing.id}']`);
            if (listingEl === null) {
                const content = doc.querySelector("#quarto-content main.content");
                if (content) {
                    listingEl = doc.createElement("div");
                    content.appendChild(listingEl);
                }
            }
            if (!listingEl?.classList.contains(kQuartoListingClass)) {
                listingEl?.classList.add(kQuartoListingClass);
            }
            const outListingId = `listing-${listing.id}`;
            listingEl?.setAttribute("id", outListingId);
            if (attributes) {
                Object.keys(attributes).forEach((attrName)=>{
                    listingEl?.setAttribute(attrName, attributes[attrName]);
                });
            }
            const renderedEl = rendered[pipelineId(listing.id)];
            listingEl.innerHTML = renderedEl.innerHTML;
        }
    };
}
function resolveItemForTemplate(item1, listing) {
    const addSortable = (item, field, value)=>{
        item.sortableValues = item.sortableValues || {};
        item.sortableValues[field] = value;
    };
    for (const field2 of Object.keys(listing[kFieldTypes])){
        const type = listing[kFieldTypes][field2];
        if (item1[field2] !== undefined) {
            if (type === "date") {
                addSortable(item1, field2, item1[field2].valueOf().toString());
            } else if (type === "number") {
                addSortable(item1, field2, item1[field2].toString());
            } else if (type === "minutes") {
                addSortable(item1, field2, item1[field2].toString());
            }
        }
    }
    for (const field1 of listing[kFieldLinks]){
        const val = item1[field1];
        if (val !== undefined) {
            addSortable(item1, field1, val);
        }
    }
}
function reshapeListing(listing, format92) {
    const reshaped = __VIRTUAL_FILE107(listing);
    const utilities = {};
    utilities.sortableFieldData = ()=>{
        const fieldSortData = [];
        reshaped[kFieldSort].filter((field)=>{
            return reshaped.fields.includes(field);
        }).forEach((field)=>{
            if (reshaped[kFieldTypes][field] === "date") {
                fieldSortData.push({
                    listingSort: {
                        field: sortAttrValue(field),
                        direction: kSortAsc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field} - ${format92.language[kListingPageOrderByDateAsc]}`
                });
                fieldSortData.push({
                    listingSort: {
                        field: sortAttrValue(field),
                        direction: kSortDesc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field} - ${format92.language[kListingPageOrderByDateDesc]}`
                });
            } else if (reshaped[kFieldTypes][field] === "number" || reshaped[kFieldTypes][field] === "minutes") {
                fieldSortData.push({
                    listingSort: {
                        field: sortAttrValue(field),
                        direction: kSortAsc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field} (${format92.language[kListingPageOrderByNumberAsc]})`
                });
                fieldSortData.push({
                    listingSort: {
                        field: sortAttrValue(field),
                        direction: kSortDesc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field} (${format92.language[kListingPageOrderByNumberDesc]})`
                });
            } else {
                const sortField = useSortTarget(listing, field) ? sortAttrValue(field) : `listing-${field}`;
                fieldSortData.push({
                    listingSort: {
                        field: sortField,
                        direction: kSortAsc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field}`
                });
            }
        });
        return fieldSortData;
    };
    utilities.fieldName = (field)=>{
        return reshaped[kFieldDisplayNames][field] || field;
    };
    utilities.outputLink = (item, field, val)=>{
        const fieldLinks = reshaped[kFieldLinks];
        const value = val || item[field];
        const path84 = item.path;
        if (path84 && value !== undefined && fieldLinks.includes(field)) {
            return `<a href="${path84}" class="${field}">${value}</a>`;
        } else {
            return value;
        }
    };
    utilities.sortTarget = (field)=>{
        if (useSortTarget(listing, field)) {
            return sortAttrValue(field);
        } else {
            return `listing-${field}`;
        }
    };
    let itemNumber1 = 0;
    utilities.itemNumber = ()=>{
        return ++itemNumber1;
    };
    utilities.img = (itemNumber, src, classes)=>{
        const pageSize = listing[kPageSize];
        const classAttr = classes ? `class="${classes}"` : "";
        const styleAttr = listing[kImageHeight1] ? `style="height: ${listing[kImageHeight1]};"` : "";
        const srcAttr = itemNumber > pageSize ? "data-src" : "src";
        return `<img ${srcAttr}="${src}" ${classAttr} ${styleAttr}>`;
    };
    let index = 0;
    utilities.metadataAttrs = (item)=>{
        const attr = {};
        attr["index"] = (index++).toString();
        if (item.categories) {
            attr["categories"] = item.categories.join(",");
        }
        item.sortableValues = item.sortableValues || {};
        for (const field of Object.keys(item.sortableValues)){
            if (useSortTarget(listing, field)) {
                attr[sortAttrValue(field)] = escape1(item.sortableValues[field]);
            }
        }
        const attrs = Object.keys(attr).map((key)=>{
            const value = attr[key];
            return `data-${key}='${value}'`;
        });
        return attrs.join(" ");
    };
    utilities.localizedString = (str76)=>{
        const localizedStrings = format92.language;
        return localizedStrings[str76];
    };
    reshaped.utilities = utilities;
    return reshaped;
}
function sortAttrValue(field) {
    return `listing-${field}-sort`;
}
const useSortTarget = (listing, field)=>{
    const links = listing[kFieldLinks];
    if (links.includes(field)) {
        return true;
    }
    const type = listing[kFieldTypes][field];
    if (type === "date" || type === "number" || type === "minutes") {
        return true;
    } else if (listing[kFieldLinks].includes(field)) {
        return true;
    }
    return false;
};
function templateJsScript(id, listing, itemCount1) {
    const pageSize = listing[kPageSize] || 50;
    const columns = listing[kFields] || [];
    const pageOptions = itemCount1 > pageSize ? `${pageSize ? `page: ${pageSize}` : ""},
    pagination: { item: "<li class='page-item'><a class='page page-link' href='#'></a></li>" },` : "";
    const filterOptions = `searchColumns: [${listing[kFieldFilter].map((field)=>{
        return `"listing-${field}"`;
    }).join(",")}],`;
    const resolvedColumns = columns.map((field)=>{
        return `'listing-${field}'`;
    });
    resolvedColumns.push(`{ data: ['index'] }`, `{ data: ['categories'] }`);
    for (const field3 of listing[kFieldSort]){
        if (useSortTarget(listing, field3)) {
            resolvedColumns.push(`{ data: ['${sortAttrValue(field3)}'] }`);
        }
    }
    const rowJs = `[${resolvedColumns.join(",")}]`;
    const jsScript = `
  window.document.addEventListener("DOMContentLoaded", function (_event) {
    const listingTargetEl = window.document.querySelector('#listing-${id} .list');
    if (!listingTargetEl) {
      // No listing discovered, do not attach.
      return; 
    }

    const options = {
      valueNames: ${rowJs},
      ${pageOptions}
      ${filterOptions}
    };

    window['quarto-listings'] = window['quarto-listings'] || {};
    window['quarto-listings']['listing-${id}'] = new List('listing-${id}', options);

    if (window['quarto-listing-loaded']) {
      window['quarto-listing-loaded']();
    }
  });
  `;
    return jsScript;
}
function truncateText(text, length) {
    if (text.length < length) {
        return text;
    } else {
        const clipLength = length - 1;
        const clipped = text.substring(0, clipLength);
        const lastSpace = clipped.lastIndexOf(" ");
        if (lastSpace > 0) {
            return clipped.substring(0, lastSpace) + "…";
        } else {
            return clipped + "…";
        }
    }
}
function categorySidebar(doc, listingDescriptors, format93, options) {
    const categoryStyle = options[kCategoryStyle];
    const headingEl = doc.createElement("h5");
    headingEl.innerText = localizedString(format93, kListingPageFieldCategories);
    headingEl.classList.add("quarto-listing-category-title");
    const cats = accumCategories(listingDescriptors);
    const categoriesEl = categoryContainer(doc);
    const totalCategories = itemCount(listingDescriptors);
    categoriesEl.classList.add(categoryStyle);
    const defaultFormat1 = (category, count)=>{
        return category + ` <span class="quarto-category-count">(${count})</span>`;
    };
    const cloudFormat = (category, count)=>{
        const size = Math.ceil(count / totalCategories * 10);
        return `<span class="quarto-category-count category-cloud-${size}">${category}</span>`;
    };
    const unnumberedFormat = (category, _count)=>{
        return `${category}`;
    };
    const formatFn = categoryStyle === "category-default" ? defaultFormat1 : categoryStyle === "category-cloud" ? cloudFormat : unnumberedFormat;
    if (categoryStyle === "category-default") {
        const allCategory = localizedString(format93, kListingPageCategoryAll);
        const allEl = categoryElement(doc, allCategory, formatFn(allCategory, totalCategories), "");
        categoriesEl.appendChild(allEl);
    }
    for (const cat of Object.keys(cats).sort()){
        const count = cats[cat];
        const catEl = categoryElement(doc, cat, formatFn(cat, count), cat);
        categoriesEl.appendChild(catEl);
    }
    return {
        headingEl,
        categoriesEl
    };
}
function itemCount(listingDescriptors) {
    return listingDescriptors.reduce((previous, listingDescriptor)=>{
        return previous + listingDescriptor.items.length;
    }, 0);
}
function accumCategories(listingDescriptors) {
    const items = listingDescriptors.flatMap((listingDescriptor)=>{
        return listingDescriptor.items;
    });
    const categories = {};
    items.forEach((item)=>{
        if (item.categories) {
            item.categories.forEach((category)=>{
                const currentCount = categories[category] || 0;
                categories[category] = currentCount + 1;
            });
        }
    });
    return categories;
}
function categoryContainer(doc) {
    const container = doc.createElement("div");
    container.classList.add("quarto-listing-category");
    return container;
}
function categoryElement(doc, category, contents, value) {
    const categoryEl = doc.createElement("div");
    categoryEl.classList.add("category");
    categoryEl.setAttribute("data-category", value !== undefined ? value : category);
    categoryEl.innerHTML = contents;
    return categoryEl;
}
const kListingDir = "listing";
const kListingMapFile = "listing-cache.json";
function cacheListingProjectData(project, listingPath, descriptors) {
    const listingContents = descriptors.flatMap((descriptor)=>{
        const contentItems = descriptor.listing.contents;
        return contentItems.filter((item)=>{
            return typeof item === "string";
        });
    });
    const cache = readListingMap(project) || {};
    const listingMap = cache.listingMap || {};
    listingContents.forEach((content)=>{
        const globSet = new Set(listingMap[listingPath] || []);
        globSet.add(content);
        listingMap[listingPath] = [
            ...globSet
        ];
    });
    writeListingCache(project, {
        listingMap
    });
}
function listingProjectData(project) {
    return readListingMap(project);
}
function clearListingProjectData(project) {
    clearListingMap(project);
}
function clearListingMap(project) {
    const file = projectListingMapFile(project.dir);
    try {
        Deno.removeSync(file);
    } catch  {}
}
function readListingMap(project) {
    const file = projectListingMapFile(project.dir);
    try {
        const mapRaw = Deno.readTextFileSync(file);
        const data54 = JSON.parse(mapRaw);
        return data54;
    } catch  {
        return {};
    }
}
function writeListingCache(project, cache) {
    const file = projectListingMapFile(project.dir);
    ensureDirSync(dirname2(file));
    const mapJson = JSON.stringify(cache, undefined, 2);
    Deno.writeTextFileSync(file, mapJson);
}
function projectListingMapFile(dir) {
    return join3(projectScratchPath(dir, kListingDir), kListingMapFile);
}
" ".charCodeAt(0);
"\t".charCodeAt(0);
":".charCodeAt(0);
new TextDecoder();
async function touch(path85) {
    if (Deno.build.os === "windows") {
        const contents = await Deno.readTextFile(path85);
        await Deno.writeTextFile(path85, contents);
    } else {
        await execProcess({
            cmd: [
                "touch",
                path85
            ]
        });
    }
}
const kSearch = "search";
const kType1 = "type";
const kLocation = "location";
const kCopyButton = "copy-button";
const kCollapseAfter = "collapse-after";
const kPanelPlacement = "panel-placement";
const kLimit = "limit";
const kAlgolia = "algolia";
const kSearchOnlyApiKey = "search-only-api-key";
const kSearchApplicationId = "application-id";
const kSearchParams = "params";
const kSearchIndexName = "index-name";
const kIndexFields = "index-fields";
const kAnalyticsEvents = "analytics-events";
const kShowLogo = "show-logo";
function updateSearchIndex(context, outputFiles, incremental) {
    const outputDir = projectOutputDir(context);
    const searchJsonPath = join3(outputDir, "search.json");
    const searchJson = existsSync(searchJsonPath) ? Deno.readTextFileSync(searchJsonPath) : undefined;
    const searchDocs1 = new Array();
    if (incremental && searchJson) {
        const existingSearchJson = JSON.parse(searchJson);
        searchDocs1.push(...existingSearchJson);
    }
    const updatedSearchDocs = outputFiles.reduce((searchDocs, outputFile)=>{
        const file = outputFile.file;
        const href = pathWithForwardSlashes(relative2(outputDir, file));
        if (outputFile.format.metadata[kSearch] === false || outputFile.format.metadata[kDraft]) {
            searchDocs = searchDocs.filter((doc)=>{
                return doc.href !== href && !doc.href.startsWith(href + "#");
            });
            return searchDocs;
        }
        if (!isHtmlContent(file)) {
            return searchDocs;
        }
        const updateDoc = (doc)=>{
            const idx = searchDocs.findIndex((d)=>d.href === doc.href
            );
            if (idx !== -1) {
                searchDocs[idx] = doc;
            } else {
                searchDocs.push(doc);
            }
        };
        const contents = Deno.readTextFileSync(file);
        const doc1 = new DOMParser().parseFromString(contents, "text/html");
        const titleEl = doc1.querySelector("h1.title");
        const title14 = titleEl ? titleEl.textContent : websiteTitle(context.config) || "";
        const header = doc1.getElementById("title-block-header");
        if (header) {
            header.remove();
        }
        const toc = doc1.querySelector(`nav[role="doc-toc"]`);
        if (toc) {
            toc.remove();
        }
        [
            "script",
            "style"
        ].forEach((tag)=>{
            const els = doc1.querySelectorAll(tag);
            if (els) {
                els.forEach((el)=>el.remove()
                );
            }
        });
        const sections = doc1.querySelectorAll("section.level2");
        if (sections.length > 0) {
            for(let i = 0; i < sections.length; i++){
                const section = sections[i];
                const h2 = section.querySelector("h2");
                if (h2 && section.id) {
                    const sectionTitle = h2.textContent;
                    const hrefWithAnchor = `${href}#${section.id}`;
                    const sectionText = section.textContent.trim();
                    h2.remove();
                    if (sectionText) {
                        updateDoc({
                            objectID: hrefWithAnchor,
                            href: hrefWithAnchor,
                            title: title14,
                            section: sectionTitle,
                            text: sectionText
                        });
                    }
                }
            }
        } else {
            const main2 = doc1.querySelector("main");
            if (main2) {
                const mainText = main2.textContent.trim();
                if (mainText) {
                    updateDoc({
                        objectID: href,
                        href,
                        title: title14,
                        section: "",
                        text: mainText
                    });
                }
            }
        }
        return searchDocs;
    }, searchDocs1);
    if (updatedSearchDocs.length > 0) {
        const updatedSearchJson = JSON.stringify(updatedSearchDocs, undefined, 2);
        if (searchJson !== updatedSearchJson) {
            Deno.writeTextFileSync(searchJsonPath, updatedSearchJson);
        }
    }
}
function searchOptions(project) {
    const searchMetadata = websiteConfigMetadata(kSearch, project.config);
    const location = searchInputLocation(project);
    if (searchMetadata) {
        const collapseMatches = typeof searchMetadata[kCollapseAfter] === "number" ? searchMetadata[kCollapseAfter] : searchMetadata[kCollapseAfter] !== false ? 2 : false;
        return {
            [kLocation]: location,
            [kCopyButton]: searchMetadata[kCopyButton] === true,
            [kCollapseAfter]: collapseMatches,
            [kPanelPlacement]: location === "navbar" ? "end" : "start",
            [kType1]: searchType(searchMetadata[kType1], location),
            [kLimit]: searchInputLimit(searchMetadata),
            [kAlgolia]: algoliaOptions(searchMetadata, project)
        };
    } else {
        const searchRaw = websiteConfig(kSearch, project.config);
        if (searchRaw === undefined || !!searchRaw) {
            return {
                [kLocation]: location,
                [kCopyButton]: false,
                [kCollapseAfter]: 2,
                [kPanelPlacement]: location === "navbar" ? "end" : "start",
                [kType1]: searchType(undefined, location),
                [kLimit]: searchInputLimit(undefined)
            };
        }
    }
}
function searchInputLimit(searchConfig) {
    if (searchConfig && typeof searchConfig === "object") {
        const limit = searchConfig[kLimit];
        if (typeof limit === "number") {
            return limit;
        }
    }
    return 20;
}
function searchType(userType, location) {
    if (userType && typeof userType === "string") {
        switch(userType){
            case "overlay":
                return "overlay";
            default:
            case "textbox":
                return "textbox";
        }
    } else {
        if (location === "sidebar") {
            return "textbox";
        } else {
            return "overlay";
        }
    }
}
function algoliaOptions(searchConfig, project) {
    const algoliaRaw = searchConfig[kAlgolia];
    if (algoliaRaw && typeof algoliaRaw === "object") {
        const algoliaObj = algoliaRaw;
        const applicationId = algoliaObj[kSearchApplicationId];
        const apiKey = algoliaObj[kSearchOnlyApiKey];
        const indexName = algoliaObj[kSearchIndexName];
        const params = algoliaObj[kSearchParams];
        const indexKeys = algoliaObj[kIndexFields];
        const analytics = !!algoliaObj[kAnalyticsEvents];
        const showLogo = !!algoliaObj[kShowLogo];
        return {
            [kSearchApplicationId]: applicationId,
            [kSearchOnlyApiKey]: apiKey,
            [kSearchIndexName]: indexName,
            [kSearchParams]: params,
            [kIndexFields]: indexKeys,
            [kAnalyticsEvents]: analytics,
            [kShowLogo]: showLogo,
            libDir: project?.config?.project[kProjectLibDir]
        };
    } else {
        return undefined;
    }
}
function searchInputLocation(project) {
    const searchConfig = websiteConfigMetadata(kSearch, project.config);
    if (searchConfig && searchConfig[kLocation]) {
        switch(searchConfig[kLocation]){
            case "sidebar":
                return "sidebar";
            case "navbar":
            default:
                return "navbar";
        }
    } else {
        const { navbar  } = websiteNavigationConfig(project);
        if (navbar) {
            return "navbar";
        } else {
            return "sidebar";
        }
    }
}
const kDependencyName = "quarto-search";
function websiteSearchSassBundle() {
    const scssPath = searchDependency("quarto-search.scss").path;
    const layer = sassLayer(scssPath);
    return {
        dependency: kBootstrapDependencyName,
        key: scssPath,
        quarto: {
            name: "quarto-search.css",
            ...layer
        }
    };
}
function websiteSearchIncludeInHeader(project, format94, temp) {
    const websiteSearchScript = temp.createFile({
        suffix: "html"
    });
    const options = searchOptions(project) || {};
    options[kLanguageDefaults] = {};
    Object.keys(format94.language).forEach((key)=>{
        if (key.startsWith("search-")) {
            options[kLanguageDefaults][key] = format94.language[key];
        }
    });
    const searchOptionsJson = JSON.stringify(options, null, 2);
    const searchOptionsScript = `<script id="quarto-search-options" type="application/json">${searchOptionsJson}</script>`;
    const includes = [
        searchOptionsScript
    ];
    if (options[kAlgolia]) {
        includes.push(kAlogioSearchApiScript);
        if (options[kAlgolia]?.[kAnalyticsEvents]) {
            const cookieConsent = cookieConsentEnabled(project);
            includes.push(algoliaSearchInsightsScript(cookieConsent));
            includes.push(autocompleteInsightsPluginScript(cookieConsent));
        }
    }
    Deno.writeTextFileSync(websiteSearchScript, includes.join("\n"));
    return websiteSearchScript;
}
function websiteSearchDependency(project, source) {
    const searchDependencies = [];
    const resources = [];
    const options = searchOptions(project);
    if (options) {
        const sourceRelative = relative2(project.dir, source);
        const offset = projectOffset(project, source);
        const href = inputFileHref(sourceRelative);
        const scripts = [
            searchDependency("autocomplete.umd.js"),
            searchDependency("fuse.min.js"),
            searchDependency("quarto-search.js"), 
        ];
        const algoliaOpts = options[kAlgolia];
        if (algoliaOpts) {
            if (algoliaOpts[kShowLogo]) {
                resources.push(searchDependency("search-by-algolia.svg"));
            }
            if (algoliaOpts[kSearchApplicationId] && algoliaOpts[kSearchOnlyApiKey] && algoliaOpts[kSearchIndexName]) {
                scripts.push(searchDependency("autocomplete-preset-algolia.umd.js"));
            } else {
                warning("Algolia search is misconfigured. Please ensure that you provide an application-id, search-only-api-key, and index-name.");
            }
            const limit = options[kLimit];
            if (limit) {
                if (typeof limit === "number" && limit > 20) {
                    warning("Algolia Insights is limited to 20 objectIds when recording the `Items Viewed` event. Please reduce the limit for your search to avoid a truncated event.");
                }
            }
        }
        searchDependencies.push(clipboardDependency());
        searchDependencies.push({
            name: kDependencyName,
            meta: {
                "quarto:offset": href === "/404.html" ? websitePath(project.config) : offset + "/"
            },
            stylesheets: [],
            scripts,
            resources
        });
    }
    return searchDependencies;
}
function searchDependency(resource) {
    return {
        name: basename2(resource),
        path: resourcePath(`projects/website/search/${resource}`)
    };
}
function autocompleteInsightsPluginScript(cookieConsent) {
    return scriptTagWithConsent(cookieConsent, "tracking", "", "https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-algolia-insights");
}
function algoliaSearchInsightsScript(cookieConsent) {
    return scriptTagWithConsent(cookieConsent, "tracking", `var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights/dist/search-insights.iife.min.js";
!function(e,a,t,n,s,i,c){e.AlgoliaAnalyticsObject=s,e[s]=e[s]||function(){
(e[s].queue=e[s].queue||[]).push(arguments)},i=a.createElement(t),c=a.getElementsByTagName(t)[0],
i.async=1,i.src=n,c.parentNode.insertBefore(i,c)
}(window,document,"script",ALGOLIA_INSIGHTS_SRC,"aa");`);
}
const kAlogioSearchApiScript = `<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4.5.1/dist/algoliasearch-lite.umd.js"></script>
`;
class QName {
    _qName;
    _prefix;
    _localPart;
    constructor(qName){
        this._qName = qName;
        const i = qName.indexOf(':');
        const q = i < 0 ? [
            '',
            qName
        ] : qName.split(':');
        this._prefix = q[0];
        this._localPart = q[1];
    }
    get qName() {
        return this._qName;
    }
    get prefix() {
        return this._prefix;
    }
    get localPart() {
        return this._localPart;
    }
}
class Attribute extends QName {
    uri;
    value = '';
    constructor(qName){
        super(qName);
        if (qName === 'xmlns') {
            this._prefix = 'xmlns';
            this._localPart = '';
        }
    }
}
class Element1 extends QName {
    _attributes = [];
    _parent;
    uri;
    emptyElement = false;
    constructor(name131, parent){
        super(name131);
        this._parent = parent;
    }
    get parent() {
        return this._parent;
    }
    newAttribute(qName) {
        const attribute = new Attribute(qName);
        this._attributes.push(attribute);
    }
    peekAttribute() {
        const i = this._attributes.length - 1;
        if (i < 0) {
            return undefined;
        }
        return this._attributes[i];
    }
    get attributes() {
        return this._attributes;
    }
    get prefixMappings() {
        const filterd = this._attributes.filter((attr)=>attr.prefix === 'xmlns'
        );
        return filterd.map((attr)=>({
                ns: attr.localPart,
                uri: attr.value
            })
        );
    }
}
class AttributeInfo extends QName {
    _attribute;
    constructor(attribute){
        super(attribute.qName);
        if (attribute.qName === 'xmlns') {
            this._prefix = 'xmlns';
            this._localPart = '';
        }
        this._attribute = attribute;
    }
    get uri() {
        return this._attribute.uri;
    }
    get value() {
        return this._attribute.value;
    }
}
class ElementInfo extends QName {
    _element;
    constructor(element){
        super(element.qName);
        this._element = element;
    }
    get uri() {
        return this._element.uri;
    }
    get parent() {
        const parent = this._element.parent;
        if (parent) {
            return new ElementInfo(parent);
        }
        return undefined;
    }
    get attributes() {
        return this._element.attributes.map((attribute)=>{
            return new AttributeInfo(attribute);
        });
    }
    get emptyElement() {
        return this._element.emptyElement;
    }
}
class XMLParseContext {
    _locator;
    _memento = '';
    _elementStack = [];
    _namespaces = {};
    quote = '';
    state = 'BEFORE_DOCUMENT';
    constructor(locator){
        this._locator = locator;
    }
    get position() {
        return this._locator?.position || {
            line: -1,
            column: -1
        };
    }
    appendMemento(value) {
        this._memento += value;
    }
    clearMemento() {
        this._memento = '';
    }
    get memento() {
        return this._memento;
    }
    newElement(qName) {
        const parent = this.peekElement();
        this._elementStack.push(new Element1(qName, parent));
    }
    peekElement() {
        return this._elementStack[this._elementStack.length - 1];
    }
    popElement() {
        const element = this._elementStack.pop();
        element?.prefixMappings.forEach(({ ns  })=>{
            this._namespaces[ns] = undefined;
        });
        return element;
    }
    get elementLength() {
        return this._elementStack.length;
    }
    registerNamespace(ns, uri) {
        this._namespaces[ns] = uri;
    }
    getNamespaceURI(ns) {
        return this._namespaces[ns];
    }
}
class XMLParseError extends Error {
    _position;
    constructor(message, cx){
        super(message);
        this._position = cx.position;
    }
    get line() {
        return this._position.line;
    }
    get column() {
        return this._position.column;
    }
}
const NAME_HEAD = /[:_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]/;
const NAME_BODY = /[:_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 isWhitespace1(c) {
    return c === ' ' || c === '\n' || c === '\r' || c === '\t';
}
function isQuote(c) {
    return c === '"' || c === '\'';
}
function resolveEntity(text) {
    let result = text;
    [
        {
            reg: /&amp;/g,
            ch: '&'
        },
        {
            reg: /&gt;/g,
            ch: '>'
        },
        {
            reg: /&lt;/g,
            ch: '<'
        },
        {
            reg: /&quot;/g,
            ch: '"'
        },
        {
            reg: /&apos;/g,
            ch: '\''
        }, 
    ].forEach(({ reg , ch  })=>{
        result = result.replace(reg, ch);
    });
    return result;
}
function handleBeforeDocument(cx, c) {
    if (c === '<') {
        cx.state = 'FOUND_LT';
    } else {
        if (!isWhitespace1(c)) {
            throw new XMLParseError('Non-whitespace before document.', cx);
        }
    }
    return [];
}
function handleGeneralStuff(cx, c) {
    if (c === '<') {
        cx.state = 'FOUND_LT';
    } else {
        cx.appendMemento(c);
    }
    return [];
}
function handleFoundLT(cx, c) {
    let events = [];
    const text = resolveEntity(cx.memento).trim();
    cx.clearMemento();
    if (text) {
        events = [
            [
                'text',
                text,
                new ElementInfo(cx.peekElement()),
                false
            ]
        ];
    }
    if (!isWhitespace1(c)) {
        if (c === '?') {
            cx.state = 'PROC_INST';
        } else if (c === '!') {
            cx.state = 'SGML_DECL';
        } else if (NAME_HEAD.test(c)) {
            cx.appendMemento(c);
            cx.state = 'START_TAG';
        } else if (c === '/') {
            cx.state = 'END_TAG';
        } else {
            throw new XMLParseError('Unencoded <', cx);
        }
    }
    return events;
}
function handleProcInst(cx, c) {
    if (c === '?') {
        cx.state = 'PROC_INST_ENDING';
    } else {
        cx.appendMemento(c);
    }
    return [];
}
function handleProcInstEnding(cx, c) {
    let events = [];
    if (c === '>') {
        events = [
            [
                'processing_instruction',
                cx.memento
            ]
        ];
        cx.clearMemento();
        cx.state = cx.elementLength > 0 ? 'GENERAL_STUFF' : 'BEFORE_DOCUMENT';
    } else {
        cx.appendMemento(`?${c}`);
        cx.state = 'PROC_INST';
    }
    return events;
}
function handleSgmlDecl(cx, c) {
    let events = [];
    const sgmlCmd = `${cx.memento}${c}`.toUpperCase();
    if (sgmlCmd === '[CDATA[') {
        cx.clearMemento();
        cx.state = 'CDATA';
    } else if (sgmlCmd === '--') {
        cx.clearMemento();
        cx.state = 'COMMENT';
    } else if (sgmlCmd === 'DOCTYPE') {
        if (cx.elementLength > 0) {
            throw new XMLParseError('Inappropriately located doctype declaration', cx);
        }
        cx.clearMemento();
        cx.state = 'DOCTYPE';
    } else if (c === '>') {
        events = [
            [
                'sgml_declaration',
                cx.memento
            ]
        ];
        cx.clearMemento();
        cx.state = cx.elementLength > 0 ? 'GENERAL_STUFF' : 'BEFORE_DOCUMENT';
    } else {
        cx.appendMemento(c);
    }
    return events;
}
function handleCdata(cx, c) {
    if (c === ']') {
        cx.state = 'CDATA_ENDING';
    } else {
        cx.appendMemento(c);
    }
    return [];
}
function handleCdataEnding(cx, c) {
    if (c === ']') {
        cx.state = 'CDATA_ENDING_2';
    } else {
        cx.appendMemento(`]${c}`);
        cx.state = 'CDATA';
    }
    return [];
}
function handleCdataEnding2(cx, c) {
    let events = [];
    if (c === '>') {
        if (cx.memento) {
            events = [
                [
                    'text',
                    cx.memento,
                    new ElementInfo(cx.peekElement()),
                    true
                ]
            ];
            cx.clearMemento();
        }
        cx.state = 'GENERAL_STUFF';
    } else if (c === ']') {
        cx.appendMemento(']');
    } else {
        cx.appendMemento(`]]${c}`);
        cx.state = 'CDATA';
    }
    return events;
}
function handleComment(cx, c) {
    if (c === '-') {
        cx.state = 'COMMENT_ENDING';
    } else {
        cx.appendMemento(c);
    }
    return [];
}
function handleCommentEnding(cx, c) {
    if (c === '-') {
        cx.state = 'COMMENT_ENDING_2';
    } else {
        cx.appendMemento(`-${c}`);
        cx.state = 'COMMENT';
    }
    return [];
}
function handleCommentEnding2(cx, c) {
    let events = [];
    if (c === '>') {
        const comment = cx.memento;
        if (comment) {
            events = [
                [
                    'comment',
                    comment
                ]
            ];
        }
        cx.clearMemento();
        cx.state = 'GENERAL_STUFF';
    } else {
        cx.appendMemento(`--${c}`);
        cx.state = 'COMMENT';
    }
    return events;
}
function handleDoctype(cx, c) {
    let events = [];
    if (c === '>') {
        events = [
            [
                'doctype',
                cx.memento
            ]
        ];
        cx.clearMemento();
        cx.state = 'BEFORE_DOCUMENT';
    } else {
        cx.appendMemento(c);
    }
    return events;
}
function emitStartElement(cx) {
    const events = [];
    if (cx.elementLength === 1) {
        events.push([
            'start_document'
        ]);
    }
    const element = cx.peekElement();
    for (const { ns , uri  } of element.prefixMappings){
        cx.registerNamespace(ns, uri);
        events.push([
            'start_prefix_mapping',
            ns,
            uri
        ]);
    }
    element.uri = cx.getNamespaceURI(element.prefix);
    for (const attribute of element.attributes){
        attribute.uri = cx.getNamespaceURI(attribute.prefix);
    }
    events.push([
        'start_element',
        new ElementInfo(element)
    ]);
    return events;
}
function handleStartTag(cx, c) {
    let events = [];
    if (NAME_BODY.test(c)) {
        cx.appendMemento(c);
    } else {
        cx.newElement(cx.memento);
        cx.clearMemento();
        if (c === '>') {
            events = emitStartElement(cx);
            cx.state = 'GENERAL_STUFF';
        } else if (c === '/') {
            cx.state = 'EMPTY_ELEMENT_TAG';
        } else {
            if (!isWhitespace1(c)) {
                throw new XMLParseError('Invalid character in element name', cx);
            }
            cx.state = 'START_TAG_STUFF';
        }
    }
    return events;
}
function handleStartTagStuff(cx, c) {
    let events = [];
    if (!isWhitespace1(c)) {
        if (c === '>') {
            events = emitStartElement(cx);
            cx.state = 'GENERAL_STUFF';
        } else if (c === '/') {
            cx.state = 'EMPTY_ELEMENT_TAG';
        } else if (NAME_HEAD.test(c)) {
            cx.appendMemento(c);
            cx.state = 'ATTRIBUTE_NAME';
        } else {
            throw new XMLParseError('Invalid attribute name', cx);
        }
    }
    return events;
}
function emitEndElement(cx, qName) {
    let events = [];
    const element = cx.popElement();
    if (element.qName !== qName) {
        throw new XMLParseError(`Illegal element structure, ${element.qName} & ${qName}`, cx);
    }
    events = [
        [
            'end_element',
            new ElementInfo(element)
        ]
    ];
    for (const { ns , uri  } of element.prefixMappings){
        events.push([
            'end_prefix_mapping',
            ns,
            uri
        ]);
    }
    return events;
}
function handleEmptyElementTag(cx, c) {
    let events = [];
    if (c !== '>') {
        throw new XMLParseError('Forward-slash in start-tag not followed by &gt', cx);
    }
    const element = cx.peekElement();
    element.emptyElement = true;
    events = emitStartElement(cx).concat(emitEndElement(cx, element.qName));
    cx.state = 'GENERAL_STUFF';
    return events;
}
function newAttribute(cx) {
    const qName = cx.memento;
    cx.clearMemento();
    cx.peekElement().newAttribute(qName);
    cx.state = 'ATTRIBUTE_EQUAL';
}
function handleAttributeName(cx, c) {
    if (NAME_BODY.test(c)) {
        cx.appendMemento(c);
    } else if (isWhitespace1(c)) {
        cx.state = 'ATTRIBUTE_NAME_SAW_WHITE';
    } else if (c === '=') {
        newAttribute(cx);
    } else {
        throw new XMLParseError(c === '>' ? 'Attribute without value' : 'Invalid attribute name', cx);
    }
    return [];
}
function handleAttributeNameSawWhite(cx, c) {
    if (c === '=') {
        newAttribute(cx);
    } else if (!isWhitespace1(c)) {
        throw new XMLParseError('Attribute without value', cx);
    }
    return [];
}
function handleAttributeEqual(cx, c) {
    if (!isWhitespace1(c)) {
        if (isQuote(c)) {
            cx.quote = c;
            cx.state = 'ATTRIBUTE_VALUE_START';
        } else {
            throw new XMLParseError('Unquoted attribute value', cx);
        }
    }
    return [];
}
function handleAttributeValueStart(cx, c) {
    if (c === cx.quote) {
        const value = cx.memento;
        cx.clearMemento();
        cx.peekElement().peekAttribute().value = resolveEntity(value);
        cx.quote = '';
        cx.state = 'ATTRIBUTE_VALUE_END';
    } else {
        cx.appendMemento(c);
    }
    return [];
}
function handleAttributeValueEnd(cx, c) {
    let events = [];
    if (isWhitespace1(c)) {
        cx.state = 'START_TAG_STUFF';
    } else if (c === '/') {
        cx.state = 'EMPTY_ELEMENT_TAG';
    } else if (c === '>') {
        events = emitStartElement(cx);
        cx.state = 'GENERAL_STUFF';
    } else {
        throw new XMLParseError('Invalid attribute name', cx);
    }
    return events;
}
function closeElement(cx) {
    const events = emitEndElement(cx, cx.memento);
    cx.clearMemento();
    if (cx.elementLength === 0) {
        events.push([
            'end_document'
        ]);
        cx.state = 'AFTER_DOCUMENT';
    } else {
        cx.state = 'GENERAL_STUFF';
    }
    return events;
}
function handleEndTag(cx, c) {
    let events = [];
    if (NAME_BODY.test(c)) {
        cx.appendMemento(c);
    } else if (c === '>') {
        events = closeElement(cx);
    } else if (isWhitespace1(c)) {
        cx.state = 'END_TAG_SAW_WHITE';
    } else {
        throw new XMLParseError('Invalid element name', cx);
    }
    return events;
}
function handleEndTagSawWhite(cx, c) {
    let events = [];
    if (c === '>') {
        events = closeElement(cx);
    } else if (!isWhitespace1(c)) {
        throw new XMLParseError('Invalid characters in end-tag', cx);
    }
    return events;
}
function handleAfterDocument(cx, c) {
    if (!isWhitespace1(c)) {
        throw new XMLParseError('Non-whitespace after document.', cx);
    }
    return [];
}
class ParserBase {
    _cx = new XMLParseContext(this);
    _handlers = {};
    _chunk = '';
    _index = -1;
    _position = {
        line: 1,
        column: 0
    };
    constructor(){
        this.appendHandler('BEFORE_DOCUMENT', handleBeforeDocument);
        this.appendHandler('GENERAL_STUFF', handleGeneralStuff);
        this.appendHandler('FOUND_LT', handleFoundLT);
        this.appendHandler('PROC_INST', handleProcInst);
        this.appendHandler('PROC_INST_ENDING', handleProcInstEnding);
        this.appendHandler('SGML_DECL', handleSgmlDecl);
        this.appendHandler('CDATA', handleCdata);
        this.appendHandler('CDATA_ENDING', handleCdataEnding);
        this.appendHandler('CDATA_ENDING_2', handleCdataEnding2);
        this.appendHandler('COMMENT', handleComment);
        this.appendHandler('COMMENT_ENDING', handleCommentEnding);
        this.appendHandler('COMMENT_ENDING_2', handleCommentEnding2);
        this.appendHandler('DOCTYPE', handleDoctype);
        this.appendHandler('START_TAG', handleStartTag);
        this.appendHandler('START_TAG_STUFF', handleStartTagStuff);
        this.appendHandler('EMPTY_ELEMENT_TAG', handleEmptyElementTag);
        this.appendHandler('ATTRIBUTE_NAME', handleAttributeName);
        this.appendHandler('ATTRIBUTE_NAME_SAW_WHITE', handleAttributeNameSawWhite);
        this.appendHandler('ATTRIBUTE_EQUAL', handleAttributeEqual);
        this.appendHandler('ATTRIBUTE_VALUE_START', handleAttributeValueStart);
        this.appendHandler('ATTRIBUTE_VALUE_END', handleAttributeValueEnd);
        this.appendHandler('END_TAG', handleEndTag);
        this.appendHandler('END_TAG_SAW_WHITE', handleEndTagSawWhite);
        this.appendHandler('AFTER_DOCUMENT', handleAfterDocument);
    }
    get cx() {
        return this._cx;
    }
    appendHandler(state96, handler) {
        this._handlers[state96] = handler;
        return this;
    }
    get handlers() {
        return this._handlers;
    }
    set chunk(chunk) {
        this._chunk = chunk;
        this._index = -1;
    }
    hasNext() {
        return this._index < this._chunk.length - 1;
    }
    readNext() {
        this._index += 1;
        const c = this._chunk[this._index];
        if (c === '\n') {
            this._position.line += 1;
            this._position.column = 0;
        } else {
            this._position.column += 1;
        }
        return c;
    }
    get position() {
        return this._position;
    }
}
class SAXParser extends ParserBase {
    _listeners = {};
    _controller;
    fireListeners(event) {
        const [name132, ...args] = event;
        const list = this._listeners[name132] || [];
        for (const listener of list){
            listener.call(this, ...args);
        }
    }
    run() {
        try {
            while(this.hasNext()){
                const state97 = this.cx.state;
                const handler = this.handlers[state97];
                if (!handler) {
                    throw new Error(`Handler for ${state97} not found`);
                }
                const events = handler(this.cx, this.readNext());
                for (const event of events){
                    this.fireListeners(event);
                }
            }
        } catch (e) {
            if (e instanceof XMLParseError) {
                this.fireListeners([
                    'error',
                    e
                ]);
                this._controller?.error(e);
            } else {
                throw e;
            }
        }
    }
    write(chunk, controller) {
        try {
            this._controller = controller;
            this.chunk = new TextDecoder().decode(chunk);
            this.run();
        } finally{
            this._controller = undefined;
        }
    }
    getStream() {
        return new WritableStream(this);
    }
    getWriter() {
        const streamWriter = this.getStream().getWriter();
        return {
            async write (p) {
                await streamWriter.ready;
                await streamWriter.write(p);
                return p.length;
            }
        };
    }
    async parse(source) {
        if (typeof source === 'string') {
            this.chunk = source;
            this.run();
        } else if (source instanceof Uint8Array) {
            this.write(source);
        } else {
            await Deno.copy(source, this.getWriter());
        }
    }
    on(event, listener) {
        const list = this._listeners[event] || [];
        list.push(listener);
        this._listeners[event] = list;
        return this;
    }
}
async function updateSitemap(context, outputFiles, incremental) {
    const outputDir = projectOutputDir(context);
    const robotsTxtPath = join3(context.dir, "robots.txt");
    const srcRobotsTxt = existsSync(robotsTxtPath) ? robotsTxtPath : undefined;
    const destRobotsTxt = join3(outputDir, "robots.txt");
    if (srcRobotsTxt) {
        copySync(srcRobotsTxt, destRobotsTxt, {
            overwrite: true,
            preserveTimestamps: true
        });
    }
    const baseUrlConfig = websiteBaseurl(context.config);
    const sitemapPath = join3(outputDir, "sitemap.xml");
    if (typeof baseUrlConfig === "string") {
        let baseUrl = baseUrlConfig;
        if (!baseUrl.endsWith("/")) {
            baseUrl += "/";
        }
        const fileLoc = (file)=>baseUrl + pathWithForwardSlashes(relative2(outputDir, file))
        ;
        const fileLastMod = (file)=>(Deno.statSync(file).mtime || new Date(0)).toISOString()
        ;
        const urlsetEntry = (outputFile)=>{
            const file = outputFile.file;
            const isDraft = !!outputFile.format.metadata[kDraft];
            return {
                loc: fileLoc(file),
                lastmod: fileLastMod(file),
                draft: isDraft
            };
        };
        if (!incremental || !existsSync(sitemapPath)) {
            writeSitemap(sitemapPath, outputFiles.map(urlsetEntry));
        } else {
            const urlset1 = outputFiles.reduce((urlset, outputFile)=>{
                const file = outputFile.file;
                const loc = fileLoc(file);
                const url1 = urlset.find((url)=>url.loc === loc
                );
                if (url1) {
                    url1.lastmod = fileLastMod(file);
                    url1.draft = !!outputFile.format.metadata[kDraft];
                } else {
                    urlset.push(urlsetEntry(outputFile));
                }
                return urlset;
            }, await readSitemap(sitemapPath));
            writeSitemap(sitemapPath, urlset1);
        }
        if (!srcRobotsTxt) {
            const robotsTxt = `Sitemap: ${baseUrl}sitemap.xml\n`;
            if (!existsSync(destRobotsTxt) || Deno.readTextFileSync(destRobotsTxt) !== robotsTxt) {
                Deno.writeTextFileSync(destRobotsTxt, robotsTxt);
            }
        }
    } else {
        removeIfExists(sitemapPath);
    }
}
async function readSitemap(sitemapPath) {
    const urlset = new Array();
    const parser = new SAXParser();
    let loc;
    let lastmod;
    parser.on("text", (text, element)=>{
        if (element.qName === "loc") {
            loc = text;
        } else if (element.qName == "lastmod") {
            lastmod = text;
        }
    });
    parser.on("end_element", (element)=>{
        if (element.qName === "url" && loc && lastmod) {
            urlset.push({
                loc,
                lastmod
            });
        }
    });
    const reader = await Deno.open(sitemapPath);
    await parser.parse(reader);
    reader.close();
    return urlset;
}
function writeSitemap(sitemapPath, urlset) {
    const nonDraftUrls = urlset.filter((url)=>!url.draft
    );
    const sitemap = renderEjs(resourcePath(join3("projects", "website", "templates", "sitemap.ejs.xml")), {
        urlset: nonDraftUrls
    });
    Deno.writeTextFileSync(sitemapPath, sitemap);
}
const kCard = "card";
function metadataHtmlDependencies(source, project, format95, extras) {
    const pipeline = metaMarkdownPipeline(format95);
    return {
        [kHtmlPostprocessors]: metadataHtmlPostProcessor(source, project, format95, extras, pipeline),
        [kMarkdownAfterBody]: pipeline.markdownAfterBody()
    };
}
function metadataHtmlPostProcessor(source, project, format96, extras, pipeline) {
    return (doc)=>{
        const pageMeta = pageMetadata(format96, extras);
        const openGraphMetadataProvider = {
            key: kOpenGraph,
            prefix: "og",
            metadata: {
                ...pageMeta,
                ...opengraphMetadata(format96)
            },
            filter: (key)=>{
                if ([
                    kImageHeight,
                    kImageWidth
                ].includes(key)) {
                    return key.replace("-", ":");
                }
                return key;
            }
        };
        const twitterMetadataProvider = {
            key: kTwitterCard,
            prefix: "twitter",
            metadata: {
                ...pageMeta,
                ...twitterMetadata(format96)
            },
            filter: (key)=>{
                if (key === kCardStyle) {
                    return kCard;
                }
                return key;
            },
            resolveDefaults: (finalMetadata)=>{
                if (finalMetadata[kCardStyle] === undefined) {
                    finalMetadata[kCardStyle] = finalMetadata[kImage] ? "summary_large_image" : "summary";
                }
            }
        };
        [
            openGraphMetadataProvider,
            twitterMetadataProvider, 
        ].forEach((provider)=>{
            const metadata = provider.metadata;
            const siteMeta = format96.metadata[kWebsite];
            if (!format96.metadata[provider.key] && (!siteMeta || !siteMeta[provider.key])) {
                return;
            }
            if (metadata[kTitle] === undefined) {
                return;
            }
            if (metadata[kImage] === undefined) {
                metadata[kImage] = findPreviewImg(doc);
            }
            resolveImageMetadata(source, project, format96, metadata);
            if (provider.resolveDefaults) {
                provider.resolveDefaults(metadata);
            }
            Object.keys(metadata).forEach((key)=>{
                if (metadata[key] !== undefined) {
                    const data55 = metadata[key];
                    if (provider.filter) {
                        key = provider.filter(key);
                    }
                    writeMetaTag(`${provider.prefix}:${key}`, data55, doc);
                }
            });
        });
        pipeline.processRenderedMarkdown(doc);
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function opengraphMetadata(format97) {
    const metadata = {};
    const openGraph = mergedSiteAndDocumentData(kOpenGraph, format97);
    const siteMeta = format97.metadata[kWebsite];
    if (siteMeta && siteMeta[kTitle]) {
        metadata[kSiteName] = siteMeta[kTitle];
    }
    if (openGraph && typeof openGraph === "object") {
        [
            kTitle,
            kDescription,
            kImage,
            kLocale,
            kSiteName
        ].forEach((key)=>{
            if (openGraph[key] !== undefined) {
                metadata[key] = openGraph[key];
            }
        });
    }
    return metadata;
}
function twitterMetadata(format98) {
    const metadata = {};
    const twitterData = mergedSiteAndDocumentData(kTwitterCard, format98);
    if (twitterData && typeof twitterData === "object") {
        [
            kTitle,
            kDescription,
            kImage,
            kCreator,
            kWebsite,
            kCardStyle
        ].forEach((key)=>{
            if (twitterData[key] !== undefined) {
                metadata[key] = twitterData[key];
            }
        });
    }
    return metadata;
}
function pageMetadata(format99, extras) {
    const pageTitle = computePageTitle(format99, extras);
    const pageDescription = format99.metadata[kDescription];
    const pageImage = format99.metadata[kImage];
    return {
        [kTitle]: pageTitle,
        [kDescription]: pageDescription || format99.metadata[kAbstract],
        [kImage]: pageImage
    };
}
function resolveImageMetadata(source, project, format100, metadata) {
    const siteMeta = format100.metadata[kWebsite];
    if (metadata[kImage] && siteMeta && siteMeta[kSiteUrl] !== undefined) {
        const imgMeta = imageMetadata(metadata[kImage], siteMeta[kSiteUrl], source, project);
        metadata[kImage] = imgMeta.href;
        metadata[kImageHeight] = imgMeta.height;
        metadata[kImageWidth] = imgMeta.width;
    }
}
function mergedSiteAndDocumentData(key, format101) {
    const siteData = format101.metadata[kWebsite];
    const siteMetadata = siteData && siteData[key] !== undefined ? siteData[key] : false;
    const docMetadata = format101.metadata[key] !== undefined ? format101.metadata[key] : false;
    if (typeof siteMetadata === "object" && typeof docMetadata === "object") {
        return mergeConfigs(siteMetadata, docMetadata);
    } else if (docMetadata !== false) {
        return docMetadata;
    } else if (siteMetadata !== false) {
        return siteMetadata;
    } else {
        return false;
    }
}
function imageMetadata(image3, baseUrl, source, context) {
    if (isAbsoluteRef(image3)) {
        return {
            href: image3
        };
    } else if (image3.startsWith("/")) {
        const imagePath = join3(context.dir, image3.slice(1));
        const size = imageSize(imagePath);
        return {
            href: `${baseUrl}${image3}`,
            height: size?.height,
            width: size?.width
        };
    } else {
        const sourceRelative = relative2(context.dir, source);
        const imageProjectRelative = join3(dirname2(sourceRelative), image3);
        const imagePath = join3(context.dir, imageProjectRelative);
        const size = imageSize(imagePath);
        return {
            href: `${baseUrl}/${imageProjectRelative}`,
            height: size?.height,
            width: size?.width
        };
    }
}
const kMetaTitleId = "quarto-metatitle";
const kMetaSideNameId = "quarto-metasitename";
function metaMarkdownPipeline(format102) {
    const titleMetaHandler = {
        getUnrendered () {
            const resolvedTitle = computePageTitle(format102);
            if (resolvedTitle !== undefined) {
                return {
                    inlines: {
                        [kMetaTitleId]: resolvedTitle
                    }
                };
            }
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kMetaTitleId];
            if (renderedEl) {
                const el = doc.querySelector(`head title`);
                if (el) {
                    el.innerHTML = renderedEl.innerText;
                }
                [
                    'meta[name="og:title"]',
                    'meta[name="twitter:title"]'
                ].forEach((sel)=>{
                    const metaEl = doc.querySelector(sel);
                    if (metaEl) {
                        metaEl.setAttribute("content", renderedEl.innerText);
                    }
                });
            }
        }
    };
    const siteTitleMetaHandler = {
        getUnrendered () {
            const siteMeta = format102.metadata[kWebsite];
            if (siteMeta && siteMeta[kTitle]) {
                return {
                    inlines: {
                        [kMetaSideNameId]: siteMeta[kTitle]
                    }
                };
            }
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kMetaSideNameId];
            if (renderedEl) {
                const el = doc.querySelector(`meta[name="og:site-name"]`);
                if (el) {
                    el.setAttribute("content", renderedEl.innerText);
                }
            }
        }
    };
    return createMarkdownPipeline("quarto-meta-markdown", [
        titleMetaHandler,
        siteTitleMetaHandler, 
    ]);
}
function htmlResourceResolverPostprocessor(source, project) {
    const sourceRelative = relative2(project.dir, source);
    const offset = projectOffset(project, source);
    const href = inputFileHref(sourceRelative);
    return (doc)=>{
        const forceRoot = href === "/404.html" ? websitePath(project.config) : null;
        const refs = resolveResourceRefs(doc, offset, forceRoot);
        return Promise.resolve({
            resources: refs,
            supporting: []
        });
    };
}
function resolveResourceRefs(doc, offset, forceRoot) {
    const refs = [];
    Object.keys(kHtmlResourceTags).forEach((tag)=>{
        for (const attrib of kHtmlResourceTags[tag]){
            refs.push(...resolveTag(doc, offset, tag, attrib, forceRoot).map((ref6)=>ref6.replace(/\/$/, "/index.html")
            ));
        }
    });
    const styles = doc.querySelectorAll("style");
    for(let i = 0; i < styles.length; i++){
        const style = styles[i];
        if (style.innerHTML) {
            style.innerHTML = fixupCssReferences(style.innerHTML, offset + "/", (ref7)=>refs.push(ref7)
            );
        }
    }
    return refs;
}
function resolveTag(doc, offset, tag1, attrib, forceRoot) {
    const refs = [];
    processFileResourceRefs(doc, tag1, attrib, (tag, href)=>{
        if (forceRoot) {
            if (!href.startsWith("/")) {
                tag.setAttribute(attrib, forceRoot + href);
            } else if (!href.startsWith(forceRoot)) {
                tag.setAttribute(attrib, forceRoot + href.slice(1));
            }
        } else if (href.startsWith("/")) {
            href = offset + href;
            tag.setAttribute(attrib, href);
        }
        refs.push(href);
    });
    return refs;
}
const defaultProjectType = {
    type: "default",
    formatLibDirs: ()=>[
            "bootstrap",
            "quarto-html",
            "quarto-ojs"
        ]
    ,
    create: (title15)=>{
        const resourceDir = resourcePath(join3("projects", "default"));
        return {
            configTemplate: join3(resourceDir, "templates", "_quarto.ejs.yml"),
            resourceDir,
            scaffold: (engine, kernel, packages)=>{
                const file = [
                    {
                        name: title15,
                        content: `## Quarto

Quarto enables you to weave together content and executable code into a finished document. To learn more about Quarto see <https://quarto.org>.`,
                        title: title15
                    }
                ];
                if (engine === kJupyterEngine && (!kernel || kernel.startsWith("python")) && packages) {
                    file[0].content += `
  
## Running Code

You can embed executable code like this:

\`\`\`{python}
1 + 1
\`\`\`

You can add options to executable code like this

\`\`\`{python}
#| echo: false
2 * 2
\`\`\`

The \`echo: false\` option disables the printing of code (only output is displayed).`;
                    if (packages.includes("matplotlib")) {
                        file[0].noEngineContent = true;
                        file[0].content += `

## Plots

See @fig-polar for an example of rendering plots as figures:

\`\`\`{python}
#| label: fig-polar
#| fig-cap: "A line plot on a polar axis"
#| code-fold: true

import numpy as np
import matplotlib.pyplot as plt

r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
ax.plot(theta, r)
ax.set_rticks([0.5, 1, 1.5, 2])
ax.grid(True)
plt.show()
\`\`\`

Note that we included the cell option \`fold: true\` to hide the code by default (click the *Code* button to show it).`;
                    }
                }
                return file;
            }
        };
    }
};
const kGiscusDir = "giscus";
async function resolveFormatForGiscus(project, format103) {
    const comments = format103.metadata[kComments];
    if (comments) {
        const giscusOptions = comments[kGiscus];
        if (giscusOptions) {
            if (giscusOptions[kGiscusRepoId] === undefined || giscusOptions[kGiscusCategoryId] === undefined) {
                const repo = giscusOptions.repo;
                const fileName = `${repo}.json`;
                let giscusMeta;
                const giscusPath = projectScratchPath(project.dir, kGiscusDir);
                ensureDirSync(giscusPath);
                const path86 = join3(giscusPath, fileName.replace("/", "."));
                try {
                    const giscusJson = Deno.readTextFileSync(path86);
                    giscusMeta = JSON.parse(giscusJson);
                } catch  {
                    removeIfExists(path86);
                    giscusMeta = await getGithubDiscussionsMetadata(repo);
                    const jsonStr = JSON.stringify(giscusMeta, undefined, 2);
                    Deno.writeTextFileSync(path86, jsonStr);
                }
                if (giscusOptions[kGiscusRepoId] === undefined) {
                    giscusOptions[kGiscusRepoId] = giscusMeta.repositoryId;
                }
                if (giscusOptions[kGiscusCategoryId] === undefined) {
                    giscusOptions[kGiscusCategoryId] = getDiscussionCategoryId(giscusOptions[kGiscusCategoryId], giscusMeta);
                }
            }
        }
    }
}
async function pandocListFormats() {
    const result = await execProcess({
        cmd: [
            pandocBinaryPath(),
            "--list-output-formats"
        ],
        stdout: "piped"
    });
    if (result.success) {
        return lines(result.stdout).filter((line)=>line.length > 0
        );
    } else {
        return Promise.reject();
    }
}
function pandocFormatWith(format104, prepend, append) {
    const split1 = splitPandocFormatString(format104);
    return `${split1.format}${prepend}${split1.options}${append}`;
}
function splitPandocFormatString(format105) {
    let optionsPos = format105.indexOf("-");
    if (optionsPos === -1) {
        optionsPos = format105.indexOf("+");
    }
    const base8 = optionsPos === -1 ? format105 : format105.substr(0, optionsPos);
    const options = optionsPos === -1 ? "" : format105.substr(optionsPos);
    return {
        format: base8,
        options
    };
}
const kRevealJsMultiplex = "multiplex";
function revealMultiplexPlugin(format106) {
    if (format106.metadata[kRevealJsMultiplex]) {
        return formatResourcePath("revealjs", join3("plugins", "multiplex"));
    } else {
        return undefined;
    }
}
function revealMuliplexPreviewFile(file) {
    const speakerFile = revealSpeakerOutput(file);
    if (existsSync(speakerFile) && existsSync(file)) {
        const modTime = Deno.statSync(file).mtime;
        const speakerModTime = Deno.statSync(speakerFile).mtime;
        if (modTime && speakerModTime && speakerModTime > modTime) {
            return speakerFile;
        }
    }
    return file;
}
function revealMultiplexExtras(format107) {
    if (format107.metadata[kRevealJsMultiplex]) {
        return {
            postprocessors: [
                async (output)=>{
                    const token = await revealMultiplexToken(format107, output);
                    const content = await Deno.readTextFile(output);
                    const speakerContent = withMultiplexToken(content, token);
                    token.secret = null;
                    const clientContent = withMultiplexToken(content, token).replace(/(\/\/ reveal\.js plugins\n\s*plugins: \[[^\[]+?)(RevealNotes,)([^\[]+?\])/, "$1$3");
                    await Deno.writeTextFile(output, clientContent);
                    const speakerOutput = revealSpeakerOutput(output);
                    await Deno.writeTextFile(speakerOutput, speakerContent);
                }
            ]
        };
    } else {
        return undefined;
    }
}
function revealSpeakerOutput(output) {
    const [dir, stem] = dirAndStem(output);
    return join3(dir, `${stem}-speaker.html`);
}
const kDefaultMultiplexUrl = "https://reveal-multiplex.glitch.me/";
async function revealMultiplexToken(format108, output) {
    const multiplex = format108.metadata[kRevealJsMultiplex];
    if (typeof multiplex === "object" && typeof multiplex.secret === "string" && typeof multiplex.id === "string") {
        multiplex.url = multiplex.url || kDefaultMultiplexUrl;
        return multiplex;
    }
    const speakerOutput = revealSpeakerOutput(output);
    if (existsSync(speakerOutput)) {
        const speakerContent = await Deno.readTextFile(speakerOutput);
        const initPos = speakerContent.lastIndexOf("Reveal.initialize({");
        if (initPos !== -1) {
            const initLines = lines(speakerContent.substring(initPos));
            const kMultiplexStart = "'multiplex': {";
            const kMultiplexEnd = "},";
            for (const line of initLines){
                if (line.startsWith(kMultiplexStart) && line.endsWith(kMultiplexEnd)) {
                    const multiplexJson = "{ " + line.substring(kMultiplexStart.length, line.length - kMultiplexEnd.length) + " }";
                    const multiplex = JSON.parse(multiplexJson);
                    if (!!multiplex.id && !!multiplex.secret) {
                        return multiplex;
                    }
                }
            }
        }
    }
    const url = typeof multiplex === "object" ? multiplex.url || kDefaultMultiplexUrl : kDefaultMultiplexUrl;
    try {
        const response = await fetch(pathWithForwardSlashes(join3(url, "token")));
        const jsonData = await response.json();
        const multiplex = {
            secret: jsonData.secret,
            id: jsonData.socketId,
            url
        };
        return multiplex;
    } catch (e) {
        throw Error("Error attempting to provision multiplex token from '" + url + "': " + e.message);
    }
}
function withMultiplexToken(content, token) {
    return content.replace(/(Reveal.initialize\({[\s\S]*?'multiplex': )({.*?},)/g, `$1${JSON.stringify(token)},`);
}
const scriptSchema = anyOfSchema(stringSchema, objectSchema({
    properties: {
        path: stringSchema,
        "async": booleanSchema
    },
    required: [
        "path"
    ]
}));
const revealPluginSchema = idSchema(objectSchema({
    properties: {
        path: stringSchema,
        name: stringSchema,
        register: booleanSchema,
        script: anyOfSchema(scriptSchema, arraySchema(scriptSchema)),
        stylesheet: anyOfSchema(stringSchema, arraySchema(stringSchema)),
        [kSelfContained]: booleanSchema
    },
    required: [
        "name"
    ]
}), "plugin-reveal");
function pdfFormat() {
    return mergeConfigs(createPdfFormat(), {
        extensions: {
            book: pdfBookExtension
        }
    });
}
function beamerFormat() {
    return createFormat("pdf", createPdfFormat(false, false), {
        execute: {
            [kFigWidth]: 10,
            [kFigHeight]: 7,
            [kEcho]: false,
            [kWarning]: false
        }
    });
}
function latexFormat() {
    return createFormat("tex", createPdfFormat());
}
function createPdfFormat(autoShiftHeadings = true, koma = true) {
    return createFormat("pdf", {
        execute: {
            [kFigWidth]: 6.5,
            [kFigHeight]: 4.5,
            [kFigFormat]: "pdf",
            [kFigDpi]: 300
        },
        pandoc: {
            [kPdfEngine]: "xelatex",
            standalone: true,
            variables: {
                graphics: true,
                tables: true
            },
            [kDefaultImageExtension]: "pdf"
        },
        formatExtras: (_input, flags, format109, _libDir, temp)=>{
            const extras = {};
            extras.postprocessors = [
                pdfLatexPostProcessor(flags, format109, temp)
            ];
            const documentclass = format109.metadata[kDocumentClass];
            if (documentclass && ![
                "srcbook",
                "scrreprt",
                "scrreport",
                "scrartcl",
                "scrarticle", 
            ].includes(documentclass)) {
                koma = false;
            }
            if (koma) {
                const captionOptions = [];
                const tblCaploc = tblCapLocation(format109);
                captionOptions.push(tblCaploc === kCapTop ? "tableheading" : "tablesignature");
                if (figCapLocation(format109) === kCapTop) {
                    captionOptions.push("figureheading");
                }
                const defaultClassOptions = [
                    "DIV=11"
                ];
                if (format109.metadata[kLang] !== "de") {
                    defaultClassOptions.push("numbers=noendperiod");
                }
                const userClassOptions = format109.metadata[kClassOption];
                const classOptions = defaultClassOptions.filter((option)=>{
                    if (Array.isArray(userClassOptions)) {
                        const name133 = option.split("=")[0];
                        return !userClassOptions.some((userOption)=>String(userOption).startsWith(name133 + "=")
                        );
                    } else {
                        return true;
                    }
                });
                extras.metadata = {
                    [kDocumentClass]: "scrartcl",
                    [kClassOption]: classOptions,
                    [kPaperSize]: "letter",
                    [kHeaderIncludes]: [
                        "\\KOMAoption{captions}{" + captionOptions.join(",") + "}", 
                    ]
                };
            }
            if (autoShiftHeadings && (flags?.[kNumberSections] === true || format109.pandoc[kNumberSections] === true) && flags?.[kTopLevelDivision] === undefined && format109.pandoc?.[kTopLevelDivision] === undefined && flags?.[kShiftHeadingLevelBy] === undefined && format109.pandoc?.[kShiftHeadingLevelBy] === undefined) {
                extras.pandoc = {
                    [kShiftHeadingLevelBy]: -1
                };
            }
            return extras;
        }
    });
}
const pdfBookExtension = {
    onSingleFilePostRender: (project, renderedFile)=>{
        if (renderedFile.format.render[kKeepTex]) {
            const finalOutputFile = renderedFile.file;
            const texOutputFile = texSafeFilename(basename2(finalOutputFile, extname2(finalOutputFile))) + ".tex";
            Deno.renameSync(join3(project.dir, "index.tex"), join3(project.dir, texOutputFile));
        }
    }
};
function pdfLatexPostProcessor(flags, format112, temp) {
    return async (output)=>{
        const lineProcessors = [
            sidecaptionLineProcessor(), 
        ];
        const marginCites = format112.metadata[kCitationLocation];
        const renderedCites = {};
        if (marginCites) {
            if (format112.pandoc[kCiteMethod] === "biblatex") {
                lineProcessors.push(suppressBibLatexBibliographyLineProcessor());
                lineProcessors.push(bibLatexCiteLineProcessor());
            } else if (format112.pandoc[kCiteMethod] === "natbib") {
                lineProcessors.push(suppressNatbibBibliographyLineProcessor());
                lineProcessors.push(natbibCiteLineProcessor());
            } else {
                lineProcessors.push(indexAndSuppressPandocBibliography(renderedCites));
            }
        }
        if (tblCapLocation(format112) === kCapBottom) {
            lineProcessors.push(longtableBottomCaptionProcessor());
        }
        if (marginRefs(flags, format112)) {
            lineProcessors.push(sideNoteLineProcessor());
        }
        await processLines(output, lineProcessors, temp);
        if (Object.keys(renderedCites).length > 0) {
            await processLines(output, [
                placePandocBibliographyEntries(renderedCites), 
            ], temp);
        }
    };
}
function tblCapLocation(format113) {
    return format113.metadata[kTblCapLoc] || format113.metadata[kCapLoc] || kCapTop;
}
function figCapLocation(format114) {
    return format114.metadata[kFigCapLoc] || format114.metadata[kCapLoc] || kCapBottom;
}
function marginRefs(flags, format115) {
    return format115.pandoc[kReferenceLocation] === "margin" || flags[kReferenceLocation] === "margin";
}
async function processLines(inputFile, lineProcessors, temp) {
    const outputFile = temp.createFile({
        suffix: ".tex"
    });
    const file = await Deno.open(inputFile);
    try {
        for await (const line of readLines(file)){
            let processedLine = line;
            for (const processor of lineProcessors){
                if (processedLine !== undefined) {
                    processedLine = processor(processedLine);
                }
            }
            if (processedLine !== undefined) {
                Deno.writeTextFileSync(outputFile, processedLine + "\n", {
                    append: true
                });
            }
        }
    } finally{
        file.close();
        Deno.copyFileSync(outputFile, inputFile);
    }
}
const kBeginScanRegex = /^%quartopost-sidecaption-206BE349/;
const kEndScanRegex = /^%\/quartopost-sidecaption-206BE349/;
const sidecaptionLineProcessor = ()=>{
    let state98 = "scanning";
    return (line)=>{
        switch(state98){
            case "scanning":
                if (line.match(kBeginScanRegex)) {
                    state98 = "replacing";
                    return kbeginLongTablesideCap;
                } else {
                    return line;
                }
            case "replacing":
                if (line.match(kEndScanRegex)) {
                    state98 = "scanning";
                    return kEndLongTableSideCap;
                } else {
                    return line;
                }
        }
    };
};
const suppressBibLatexBibliographyLineProcessor = ()=>{
    return (line)=>{
        if (line.match(/^\\printbibliography$/)) {
            return "";
        }
        return line;
    };
};
const suppressNatbibBibliographyLineProcessor = ()=>{
    return (line)=>{
        return line.replace(/^\s*\\bibliography{(.*)}$/, (_match, bib)=>{
            return `\\newsavebox\\mytempbib
\\savebox\\mytempbib{\\parbox{\\textwidth}{\\bibliography{${bib}}}}`;
        });
    };
};
const kQuartoCiteRegex = /{\?quarto-cite:(.*?)}/g;
const bibLatexCiteLineProcessor = ()=>{
    return (line)=>{
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey)=>{
            return `\\fullcite{${citeKey}}`;
        });
    };
};
const natbibCiteLineProcessor = ()=>{
    return (line)=>{
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey)=>{
            return `\\bibentry{${citeKey}}`;
        });
    };
};
const sideNoteLineProcessor = ()=>{
    return (line)=>{
        return line.replaceAll(/\\footnote{/g, "\\sidenote{\\footnotesize ");
    };
};
const longtableBottomCaptionProcessor = ()=>{
    let scanning = false;
    let caption;
    return (line)=>{
        if (scanning) {
            if (line.match(/^\\caption.*?\\tabularnewline$/)) {
                caption = line;
                return undefined;
            } else if (line.match(/^\\end{longtable}$/)) {
                scanning = false;
                if (caption) {
                    line = caption + "\n" + line;
                    caption = undefined;
                    return line;
                }
            }
        } else {
            scanning = !!line.match(/^\\begin{longtable}/);
        }
        return line;
    };
};
const indexAndSuppressPandocBibliography = (renderedCites)=>{
    let consuming = false;
    let currentCiteKey = undefined;
    return (line)=>{
        if (!consuming && line.match(/^\\hypertarget{refs}{}$/)) {
            consuming = true;
            return undefined;
        } else if (consuming && line.match(/^\\end{CSLReferences}$/)) {
            consuming = false;
            return undefined;
        } else if (consuming) {
            const matches = line.match(/pre{\\hypertarget{ref\-(.*?)}{}}\%/);
            if (matches && matches[1]) {
                currentCiteKey = matches[1];
                renderedCites[currentCiteKey] = [
                    line.replace("pre{\\hypertarget{ref", "pre{\\protect\\hypertarget{ref"), 
                ];
            } else if (line.length === 0) {
                currentCiteKey = undefined;
            } else if (currentCiteKey) {
                renderedCites[currentCiteKey].push(line);
            }
        }
        if (consuming) {
            return undefined;
        } else {
            return line;
        }
    };
};
const placePandocBibliographyEntries = (renderedCites)=>{
    return (line)=>{
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey)=>{
            const citeLines = renderedCites[citeKey];
            if (citeLines) {
                return citeLines.join("\n");
            } else {
                return citeKey;
            }
        });
    };
};
const kbeginLongTablesideCap = `{
\\makeatletter
\\def\\LT@makecaption#1#2#3{%
  \\noalign{\\smash{\\hbox{\\kern\\textwidth\\rlap{\\kern\\marginparsep
  \\parbox[t]{\\marginparwidth}{%
    \\footnotesize{%
      \\vspace{(1.1\\baselineskip)}
    #1{#2: }\\ignorespaces #3}}}}}}%
    }
\\makeatother`;
const kEndLongTableSideCap = "}";
function epubFormat() {
    return mergeConfigs(createEbookFormat("epub"), {
        extensions: {
            book: epubBookExtension
        }
    });
}
const epubBookExtension = {
    onSingleFilePreRender: (format116, config)=>{
        if (!format116.pandoc[kEPubCoverImage] && !format116.metadata[kBookCoverImage]) {
            const coverImage = bookConfig(kBookCoverImage, config);
            if (coverImage) {
                format116.metadata[kBookCoverImage] = coverImage;
            }
        }
        return format116;
    }
};
const kIconCaution = "icon-caution";
const kIconImportant = "icon-important";
const kIconNote = "icon-note";
const kIconTip = "icon-tip";
const kIconWarning = "icon-warning";
function docxFormat() {
    return mergeConfigs(createWordprocessorFormat("docx"), {
        formatExtras: ()=>{
            return {
                [kFilterParams]: {
                    [kIconCaution]: iconPath("caution.png"),
                    [kIconImportant]: iconPath("important.png"),
                    [kIconNote]: iconPath("note.png"),
                    [kIconTip]: iconPath("tip.png"),
                    [kIconWarning]: iconPath("warning.png")
                }
            };
        },
        extensions: {
            book: {}
        }
    });
}
function iconPath(icon) {
    return formatResourcePath("docx", icon);
}
function ipynbFormat() {
    return createFormat("ipynb", {
        pandoc: {
            standalone: true,
            [kDefaultImageExtension]: "png"
        },
        formatExtras: ()=>{
            return {
                postprocessors: [
                    (output)=>{
                        const nb = jupyterFromFile(output);
                        nb.cells = nb.cells.map((cell)=>{
                            if (cell.cell_type == "raw") {
                                if (cell.metadata[kCellFormat]) {
                                    const format117 = cell.metadata[kCellFormat];
                                    delete cell.metadata[kCellFormat];
                                    if (format117 === kTextHtml) {
                                        cell.metadata[kCellRawMimeType] = format117;
                                    } else if (format117 === "tex") {
                                        cell.metadata[kCellRawMimeType] = kTextLatex;
                                    } else if (format117 === "rst") {
                                        cell.metadata[kCellRawMimeType] = kRestructuredText;
                                    } else if (format117 === "rtf") {
                                        cell.metadata[kCellRawMimeType] = kApplicationRtf;
                                    } else {
                                        cell.metadata[kCellFormat] = format117;
                                    }
                                }
                            }
                            return cell;
                        });
                        Deno.writeTextFileSync(output, JSON.stringify(nb, null, 2));
                        return Promise.resolve();
                    }
                ]
            };
        }
    });
}
function annotateOjsLineNumbers(context) {
    const canPatch = !isJupyterNotebook(context.target.source);
    if (canPatch) {
        const source = lines(Deno.readTextFileSync(context.target.source));
        const ojsBlockLineNumbers = [];
        let lineNumber = 1;
        const chunkBegin = /^[\t ]*```+\s*\{(ojs( *[ ,].*)?)\}\s*$/;
        source.forEach((line)=>{
            lineNumber++;
            if (line.match(chunkBegin)) {
                ojsBlockLineNumbers.push(lineNumber);
            }
        });
        return {
            ojsBlockLineNumbers
        };
    } else {
        return {
            ojsBlockLineNumbers: []
        };
    }
}
async function validateDocumentFromSource(src, engine, errorFn, filename) {
    const result = [];
    const reportSet = new Set();
    if (filename?.startsWith("/")) {
        filename = relative2(Deno.cwd(), filename);
    }
    const nb = await breakQuartoMd(asMappedString(src, filename));
    if (nb.cells.length < 1) {
        return [];
    }
    const firstCell = nb.cells[0];
    let firstContentCellIndex;
    if (firstCell.source.value.startsWith("---")) {
        firstContentCellIndex = 1;
        if (!firstCell.source.value.endsWith("---")) {
            throw new Error("Expected front matter to end with '---'");
        }
        const lineRanges = rangedLines(firstCell.source.value);
        const frontMatterText = mappedString(firstCell.source, [
            {
                start: lineRanges[1].range.start,
                end: lineRanges[lineRanges.length - 2].range.end
            }
        ]);
        const annotation = readAnnotatedYamlFromMappedString(frontMatterText);
        if (annotation.result === null || !__VIRTUAL_FILE18(annotation.result) || annotation.result["validate-yaml"] !== false) {
            const frontMatterSchema = await getFrontMatterSchema();
            await withValidator(frontMatterSchema, async (frontMatterValidator)=>{
                const fmValidation = await frontMatterValidator.validateParseWithErrors(frontMatterText, annotation, "Validation of YAML front matter failed.", errorFn, reportOnce((err)=>error(tidyverseFormatError(err), {
                        colorize: false
                    })
                , reportSet));
                if (fmValidation && fmValidation.errors.length) {
                    result.push(...fmValidation.errors);
                }
            });
        }
    } else {
        firstContentCellIndex = 0;
    }
    for (const cell of nb.cells.slice(firstContentCellIndex)){
        if (cell.cell_type === "markdown" || cell.cell_type === "raw" || cell.cell_type === "math") {
            continue;
        }
        const lang = cell.cell_type.language;
        try {
            await partitionCellOptionsMapped1(lang, cell.source, true, engine);
        } catch (e) {
            if (e instanceof ValidationError2) {
                result.push(...e.validationErrors);
            } else {
                throw e;
            }
        }
    }
    return result;
}
async function validateDocument(context) {
    if (context.target.markdown === "") {
        return [];
    }
    return validateDocumentFromSource(context.target.markdown, context.engine.name, error, context.target.source);
}
let tempDir;
function initSessionTempDir() {
    tempDir = Deno.makeTempDirSync({
        prefix: "quarto-session"
    });
}
function cleanupSessionTempDir() {
    if (tempDir) {
        removeIfExists(tempDir);
        tempDir = undefined;
    }
}
function createTempContext(options1) {
    let dir = Deno.makeTempDirSync({
        ...options1,
        dir: tempDir
    });
    return {
        createFile: (options)=>{
            return Deno.makeTempFileSync({
                ...options,
                dir
            });
        },
        createDir: (options)=>{
            return Deno.makeTempDirSync({
                ...options,
                dir
            });
        },
        cleanup: ()=>{
            if (dir) {
                try {
                    removeIfExists(dir);
                } catch (error31) {
                    warning(`Error removing temp dir at ${dir}: ${error31.message}`);
                }
                dir = undefined;
            }
        }
    };
}
const navigation = {
    sidebars: []
};
const kSidebarLogo = "logo";
async function initWebsiteNavigation(project) {
    resetMenuIds();
    const { navbar , sidebars , pageNavigation , footer , pageMargin , bodyDecorators ,  } = websiteNavigationConfig(project);
    if (!navbar && !sidebars && !pageNavigation) {
        return;
    }
    if (sidebars) {
        navigation.sidebars = await sidebarsEjsData(project, sidebars);
        navigation.sidebars = resolveNavReferences(navigation.sidebars);
    } else {
        navigation.sidebars = [];
    }
    if (navbar) {
        navigation.navbar = await navbarEjsData(project, navbar);
        navigation.navbar = resolveNavReferences(navigation.navbar);
    } else {
        navigation.navbar = undefined;
    }
    navigation.pageNavigation = pageNavigation;
    navigation.footer = await resolveFooter(project, footer);
    navigation.bodyDecorators = bodyDecorators;
    navigation.pageMargin = pageMargin;
}
function listingSupplementalFiles(project1, inputs, incremental1) {
    if (incremental1) {
        const listingProjData = listingProjectData(project1);
        const listingMap = listingProjData.listingMap || {};
        const listingFiles = Object.keys(listingMap);
        const inputPaths = inputs.map((inp)=>inp.path
        );
        const matching = listingFiles.filter((listingFile)=>{
            const listingDir = join3(project1.dir, dirname2(listingFile));
            const globs = listingMap[listingFile];
            if (filterPaths(listingDir, inputPaths, globs).include.length > 0) {
                return true;
            }
        });
        if (matching.length > 0) {
            const supplementalFiles = matching.map((listingRelativePath)=>{
                return join3(project1.dir, listingRelativePath);
            });
            const files1 = __VIRTUAL_FILE210(supplementalFiles.filter((file)=>{
                return !inputs.find((inp)=>{
                    return inp.path === file;
                }) && existsSync(file);
            }));
            const onRenderComplete = async (project, files, incremental)=>{
                if (incremental) {
                    const outputDir = projectOutputDir(project);
                    for (const file of files){
                        const filePath = join3(outputDir, file);
                        await touch(filePath);
                    }
                }
            };
            return {
                files: files1.map((file)=>{
                    return {
                        path: file,
                        formats: [
                            "html",
                            "html4",
                            "html5"
                        ]
                    };
                }),
                onRenderComplete
            };
        } else {
            return {
                files: []
            };
        }
    } else {
        clearListingProjectData(project1);
        return {
            files: []
        };
    }
}
const kSidebarTitleId = "quarto-int-sidebar-title";
const kNavbarTitleId = "quarto-int-navbar-title";
const kNavNextId = "quarto-int-next";
const kNavPrevId = "quarto-int-prev";
const kSidebarIdPrefix = "quarto-int-sidebar:";
const kNavbarIdPrefix = "quarto-int-navbar:";
function navigationMarkdownHandlers(context) {
    return [
        sidebarTitleHandler(context),
        navbarTitleHandler(context),
        nextPageTitleHandler(context),
        prevPageTitleHandler(context),
        sidebarContentsHandler(context),
        sidebarHeaderFooterHandler(context),
        navbarContentsHandler(context),
        footerHandler(context),
        marginHeaderFooterHandler(context),
        bodyHeaderFooterHandler(context), 
    ];
}
async function websiteNavigationExtras(project, source, flags, format118, temp) {
    const usesCustomLayout = !formatHasArticleLayout(format118);
    const hasToc = ()=>{
        if (disabledTableOfContents(format118)) {
            return false;
        } else if (hasTableOfContents(flags, format118)) {
            return true;
        } else if (usesCustomLayout) {
            return false;
        } else {
            return true;
        }
    };
    const inputRelative = relative2(project.dir, source);
    const dependencies = [
        websiteNavigationDependency(project), 
    ];
    const includeInHeader = [];
    const sassBundles = [
        websiteNavigationSassBundle()
    ];
    const searchDep = websiteSearchDependency(project, source);
    if (searchDep) {
        dependencies.push(...searchDep);
        sassBundles.push(websiteSearchSassBundle());
        includeInHeader.push(websiteSearchIncludeInHeader(project, format118, temp));
    }
    const disableNavbar = format118.metadata[kSiteNavbar] !== undefined && format118.metadata[kSiteNavbar] === false;
    const disableSidebar = format118.metadata[kSiteSidebar] !== undefined && format118.metadata[kSiteSidebar] === false || usesCustomLayout;
    const target = await resolveInputTarget(project, inputRelative);
    const href = target?.outputHref || inputFileHref(inputRelative);
    const sidebar = sidebarForHref(href, format118);
    const nav = {
        hasToc: hasToc(),
        [kTocLocation]: format118.metadata[kTocLocation] || "right",
        layout: formatPageLayout(format118),
        navbar: disableNavbar ? undefined : navigation.navbar,
        sidebar: disableSidebar ? undefined : expandedSidebar(href, sidebar),
        sidebarStyle: sidebarStyle(),
        footer: navigation.footer
    };
    const pageNavigation = nextAndPrevious(href, sidebar);
    if (navigation.pageNavigation && !usesCustomLayout) {
        nav.prevPage = pageNavigation.prevPage;
        nav.nextPage = pageNavigation.nextPage;
        const metaLinks = [];
        if (pageNavigation.nextPage?.href) {
            metaLinks.push({
                rel: "next",
                href: pageNavigation.nextPage?.href
            });
        }
        if (pageNavigation.prevPage?.href) {
            metaLinks.push({
                rel: "prev",
                href: pageNavigation.prevPage?.href
            });
        }
        if (metaLinks.length > 0) {
            dependencies.push({
                name: "website-pagination",
                links: metaLinks
            });
        }
    }
    if (navigation.footer) {
        nav.footer = navigation.footer;
    }
    const darkMode = formatDarkMode(format118);
    if (darkMode !== undefined && nav.navbar) {
        nav.navbar.darkToggle = true;
    } else if (darkMode !== undefined && nav.sidebar) {
        nav.sidebar.darkToggle = true;
    }
    const readerMode = websiteConfigBoolean(kSiteReaderMode, false, project.config);
    if (readerMode && nav.navbar) {
        nav.navbar.readerToggle = true;
    } else if (readerMode && nav.sidebar) {
        nav.sidebar.readerToggle = true;
    }
    const projTemplate = (template7)=>resourcePath(`projects/website/templates/${template7}`)
    ;
    const bodyEnvelope = {
        before: renderEjs(projTemplate("nav-before-body.ejs"), {
            nav
        }),
        afterPreamble: renderEjs(projTemplate("nav-after-body-preamble.ejs"), {
            nav
        }),
        afterPostamble: renderEjs(projTemplate("nav-after-body-postamble.ejs"), {
            nav
        })
    };
    const pipelineHandlers = navigationMarkdownHandlers({
        source,
        format: format118,
        sidebar,
        navigation,
        pageNavigation,
        bodyDecorators: navigation.bodyDecorators
    });
    const markdownPipeline = createMarkdownPipeline("quarto-navigation-envelope", pipelineHandlers);
    return {
        [kIncludeInHeader]: includeInHeader,
        html: {
            [kSassBundles]: sassBundles,
            [kDependencies]: dependencies,
            [kBodyEnvelope]: bodyEnvelope,
            [kHtmlPostprocessors]: [
                navigationHtmlPostprocessor(project, source, markdownPipeline, format118.language), 
            ],
            [kMarkdownAfterBody]: [
                markdownPipeline.markdownAfterBody(), 
            ]
        }
    };
}
const kListing = "listing";
const kDefaultListingType = ListingType.Default;
const kDefaultContentsGlob = [
    "*"
];
const kDefaultId = "listing";
const kDefaultTableFields = [
    kFieldDate,
    kFieldTitle,
    kFieldAuthor, 
];
const kDefaultGridFields = [
    kFieldTitle,
    kFieldAuthor,
    kFieldDate,
    kFieldImage,
    kFieldDescription, 
];
const kDefaultFields = [
    kFieldDate,
    kFieldTitle,
    kFieldAuthor,
    kFieldSubtitle,
    kFieldImage,
    kFieldDescription, 
];
const defaultFieldDisplayNames = (format119)=>{
    return {
        [kFieldImage]: " ",
        [kFieldDate]: format119.language[kListingPageFieldDate] || "",
        [kFieldTitle]: format119.language[kListingPageFieldTitle] || "",
        [kFieldDescription]: format119.language[kListingPageFieldDescription] || "",
        [kFieldAuthor]: format119.language[kListingPageFieldAuthor] || "",
        [kFieldFileName]: format119.language[kListingPageFieldFileName] || "",
        [kFieldFileModified]: format119.language[kListingPageFieldFileModified] || "",
        [kFieldSubtitle]: format119.language[kListingPageFieldSubtitle] || "",
        [kFieldReadingTime]: format119.language[kListingPageFieldReadingTime] || "",
        [kFieldCategories]: format119.language[kListingPageFieldCategories] || ""
    };
};
const kDefaultFieldTypes = {
    [kFieldDate]: "date",
    [kFieldFileModified]: "date",
    [kFieldReadingTime]: "minutes"
};
const kDefaultFieldLinks = [
    kFieldTitle,
    kFieldFileName
];
const kDefaultFieldSort = [
    kFieldTitle,
    kFieldDate,
    kFieldAuthor,
    kFieldFileName,
    kFieldFileModified, 
];
const kDefaultFieldRequired = [];
async function readListings(source, project, format120) {
    const listingItems = [];
    const listings = readDehydratedListings(source, format120);
    const firstListingValue = (key, defaultValue)=>{
        for (const listing of listings){
            const value = listing[key];
            if (value !== undefined) {
                return value;
            }
        }
        return defaultValue;
    };
    const categories1 = firstListingValue(kFieldCategories, false);
    const parseCategoryStyle = (categories)=>{
        if (typeof categories === "string") {
            switch(categories){
                case "unnumbered":
                    return "category-unnumbered";
                case "cloud":
                    return "category-cloud";
                default:
                case "default":
                    return "category-default";
            }
        } else {
            return "category-default";
        }
    };
    const categoryStyle = parseCategoryStyle(categories1);
    const sharedOptions = {
        [kFieldCategories]: !!categories1,
        [kCategoryStyle]: categoryStyle
    };
    const feed = firstListingValue(kFeed, undefined);
    if (feed !== undefined) {
        if (typeof feed === "object") {
            sharedOptions[kFeed] = feed;
        } else if (feed) {
            sharedOptions[kFeed] = {
                type: "full"
            };
        }
    }
    for (const listing1 of listings){
        const { items: items1 , sources  } = await readContents(source, project, listing1);
        const listingHydrated = hydrateListing(format120, listing1, items1, sources, sharedOptions);
        const sortedAndFiltered = (listing, items)=>{
            if (listing.sort && listing.sort.length > 0) {
                return __VIRTUAL_FILE217(items, listing.sort.map((l)=>{
                    return (item)=>{
                        return item[l.field];
                    };
                }), listing.sort.map((l)=>l.direction
                ));
            } else {
                return items;
            }
        };
        const orderedItems = sortedAndFiltered(listingHydrated, items1);
        listingItems.push({
            listing: listingHydrated,
            items: orderedItems
        });
    }
    return {
        listingDescriptors: listingItems,
        options: sharedOptions
    };
}
async function listingHtmlDependencies(source, project, format121, temp, _extras) {
    const { listingDescriptors , options  } = await readListings(source, project, format121);
    const pageHasListings = listingDescriptors.length > 0;
    if (pageHasListings) {
        cacheListingProjectData(project, relative2(project.dir, source), listingDescriptors);
    }
    const markdownHandlers = [];
    listingDescriptors.forEach((listingDescriptor)=>{
        markdownHandlers.push(markdownHandler(format121, listingDescriptor.listing, listingDescriptor.items));
    });
    const pipeline = createMarkdownPipeline(`quarto-listing-pipeline`, markdownHandlers);
    const kListingDependency = "quarto-listing";
    const jsPaths = [
        resourcePath("projects/website/listing/list.min.js"),
        resourcePath("projects/website/listing/quarto-listing.js"), 
    ];
    const listingDependencies = [
        {
            name: kListingDependency,
            scripts: jsPaths.map((path87)=>{
                return {
                    name: basename2(path87),
                    path: path87
                };
            })
        }
    ];
    const generateScriptListJsScript = ()=>{
        return listingDescriptors.map((listingItem)=>{
            return templateJsScript(listingItem.listing.id, listingItem.listing, listingItem.items.length);
        });
    };
    const listingPostProcessor = async (doc)=>{
        pipeline.processRenderedMarkdown(doc);
        listingPostProcess(doc, listingDescriptors, options, format121);
        const supporting = [];
        if (options[kFeed]) {
            const listingOptions = {
                type: "full",
                ...options[kFeed]
            };
            const feedAbsPaths = await createFeed(doc, source, project, listingDescriptors, listingOptions, format121);
            if (feedAbsPaths) {
                feedAbsPaths.forEach((feedAbsPath)=>{
                    supporting.push(feedAbsPath);
                });
            }
        }
        return Promise.resolve({
            resources: [],
            supporting
        });
    };
    return {
        [kSassBundles]: [
            listingSassBundle()
        ],
        [kDependencies]: pageHasListings ? listingDependencies : [],
        [kMarkdownAfterBody]: pageHasListings ? pipeline.markdownAfterBody() : undefined,
        [kIncludeInHeader]: pageHasListings ? [
            scriptFileForScripts(generateScriptListJsScript(), temp), 
        ] : [],
        [kHtmlPostprocessors]: pageHasListings ? listingPostProcessor : undefined
    };
}
const kAbout = "about";
const kTemplate1 = "template";
const kType2 = "type";
const kLinks = "links";
const kImageWidth1 = "image-width";
const kImageShape = "image-shape";
const kImageShapeRound = "round";
const kImageShapeRounded = "rounded";
const kTemplateJolla = "jolla";
const kTemplateTrestles = "trestles";
const kTemplateSolana = "solana";
const kTemplateMarquee = "marquee";
const kTemplateBroadside = "broadside";
const kTemplates = [
    kTemplateJolla,
    kTemplateTrestles,
    kTemplateSolana,
    kTemplateMarquee,
    kTemplateBroadside, 
];
async function aboutHtmlDependencies(source, project, format122, _temp, _extras) {
    const aboutPage = await readAbout(source, project, format122);
    if (aboutPage) {
        format122.pandoc[kToc] = false;
    }
    const scssPath = join3(projectTypeResourcePath("website"), `about/about.scss`);
    const aboutLayer = sassLayerFile(scssPath);
    const sassBundles = [
        {
            dependency: kBootstrapDependencyName,
            key: scssPath,
            quarto: {
                name: `quarto-about.css`,
                ...aboutLayer
            }
        }, 
    ];
    return {
        [kHtmlPostprocessors]: aboutPage ? aboutPagePostProcessor(aboutPage) : undefined,
        [kSassBundles]: sassBundles
    };
}
const kSiteTemplateDefault = "default";
const kSiteTemplateBlog = "blog";
const websiteProjectType = {
    type: kWebsite,
    typeAliases: [
        "site"
    ],
    templates: [
        kSiteTemplateDefault,
        kSiteTemplateBlog
    ],
    create: (title16, template8)=>{
        const resourceDir = resourcePath(join3("projects", "website"));
        return websiteTemplate(resourceDir, title16, template8);
    },
    libDir: "site_libs",
    outputDir: "_site",
    formatLibDirs: ()=>defaultProjectType.formatLibDirs().concat([
            "quarto-nav",
            "quarto-search"
        ])
    ,
    config: websiteProjectConfig,
    metadataFields: websiteMetadataFields,
    resourceIgnoreFields: ()=>[
            kWebsite,
            "site"
        ]
    ,
    preRender: async (context)=>{
        await initWebsiteNavigation(context);
    },
    supplementRender: (project, files, incremental)=>{
        const listingSupplements = listingSupplementalFiles(project, files, incremental);
        return listingSupplements;
    },
    formatExtras: async (project, source, flags, format123, temp)=>{
        if (isHtmlOutput(format123.pandoc)) {
            const extras = formatHasBootstrap(format123) ? await websiteNavigationExtras(project, source, flags, format123, temp) : {};
            extras.pandoc = extras.pandoc || {};
            extras.metadata = extras.metadata || {};
            resolveFormatForGiscus(project, format123);
            const title17 = websiteTitle(project.config);
            if (title17) {
                extras.pandoc = {
                    [kTitlePrefix]: title17
                };
            }
            const favicon = websiteConfigString(kSiteFavicon, project.config);
            if (favicon) {
                const offset = projectOffset(project, source);
                extras.html = extras.html || {};
                extras.html.dependencies = extras.html.dependencies || [];
                extras.html.dependencies.push({
                    name: kSiteFavicon,
                    links: [
                        {
                            rel: "icon",
                            href: offset + "/" + favicon,
                            type: contentType(favicon)
                        }
                    ]
                });
            }
            const offset = projectOffset(project, source);
            const [_dir, stem] = dirAndStem(source);
            const home = stem === "index" && offset === ".";
            if (home && !format123.metadata[kTitle] && !format123.metadata[kPageTitle] && title17) {
                extras.metadata[kPageTitle] = title17;
            }
            extras.html = extras.html || {};
            extras.html[kHtmlPostprocessors] = extras.html[kHtmlPostprocessors] || [];
            extras.html[kHtmlFinalizers] = extras.html[kHtmlFinalizers] || [];
            extras.html[kMarkdownAfterBody] = extras.html[kMarkdownAfterBody] || [];
            extras.html[kHtmlPostprocessors]?.push(...[
                htmlResourceResolverPostprocessor(source, project), 
            ]);
            const hasBootstrap = formatHasBootstrap(format123);
            if (hasBootstrap) {
                const htmlListingDependencies = await listingHtmlDependencies(source, project, format123, temp, extras);
                if (htmlListingDependencies) {
                    const listingPostProcessor = htmlListingDependencies[kHtmlPostprocessors];
                    if (listingPostProcessor) {
                        extras.html[kHtmlPostprocessors]?.push(listingPostProcessor);
                    }
                    const listingAfterBody = htmlListingDependencies[kMarkdownAfterBody];
                    if (listingAfterBody) {
                        extras.html[kMarkdownAfterBody]?.push(listingAfterBody);
                    }
                    extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
                    extras[kIncludeInHeader].push(...htmlListingDependencies[kIncludeInHeader]);
                    extras.html[kSassBundles] = extras.html[kSassBundles] || [];
                    extras.html[kSassBundles].push(...htmlListingDependencies[kSassBundles]);
                    extras.html[kDependencies] = extras.html[kDependencies] || [];
                    extras.html[kDependencies]?.push(...htmlListingDependencies[kDependencies]);
                }
                const aboutDependencies = await aboutHtmlDependencies(source, project, format123, temp, extras);
                if (aboutDependencies) {
                    const aboutPostProcessor = aboutDependencies[kHtmlPostprocessors];
                    if (aboutPostProcessor) {
                        extras.html[kHtmlPostprocessors]?.push(aboutPostProcessor);
                    }
                    extras.html[kSassBundles] = extras.html[kSassBundles] || [];
                    extras.html[kSassBundles].push(...aboutDependencies[kSassBundles]);
                }
            }
            const htmlMetadataDependencies = metadataHtmlDependencies(source, project, format123, extras);
            extras.html[kHtmlPostprocessors]?.push(htmlMetadataDependencies[kHtmlPostprocessors]);
            extras.html[kMarkdownAfterBody]?.push(htmlMetadataDependencies[kMarkdownAfterBody]);
            const analyticsDependency = websiteAnalyticsScriptFile(project, temp);
            if (analyticsDependency) {
                extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
                extras[kIncludeInHeader]?.push(analyticsDependency);
            }
            const cookieDep = cookieConsentDependencies(project, temp);
            if (cookieDep) {
                extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
                extras[kIncludeInHeader]?.push(cookieDep.scriptFile);
                extras.html = extras.html || {};
                extras.html[kDependencies] = extras.html[kDependencies] || [];
                extras.html[kDependencies]?.push(cookieDep.dependency);
                extras.html[kHtmlPostprocessors] = extras.html[kHtmlPostprocessors] || [];
                extras.html[kHtmlPostprocessors]?.push(cookieDep.htmlPostProcessor);
            }
            return Promise.resolve(extras);
        } else {
            return Promise.resolve({});
        }
    },
    postRender: async (context, incremental, outputFiles)=>{
        await websitePostRender(context, incremental, websiteOutputFiles(outputFiles));
    }
};
const kBookChapters = "chapters";
const kBookAppendix = "appendices";
const kBookReferences = "references";
const kBookRender = "render";
const kBookOutputFile = "output-file";
const kBookTools = "tools";
const kBookSearch = "search";
const kBookItemChapter = "chapter";
const kBookItemAppendix = "appendix";
const kBookItemPart = "part";
async function bookProjectConfig(projectDir, config, forceHtml, flags) {
    const site = config[kWebsite] || {};
    config[kWebsite] = site;
    const book = config[kBook];
    if (book) {
        site[kSiteTitle] = book[kSiteTitle];
        site[kSiteFavicon] = book[kSiteFavicon];
        site[kSiteUrl] = book[kSiteUrl];
        site[kSitePath] = book[kSitePath];
        site[kSiteRepoUrl] = book[kSiteRepoUrl];
        site[kSiteRepoBranch] = book[kSiteRepoBranch];
        site[kSiteRepoActions] = book[kSiteRepoActions];
        site[kSiteNavbar] = book[kSiteNavbar];
        site[kSiteSidebar] = book[kSiteSidebar];
        site[kSitePageNavigation] = book[kSitePageNavigation] !== false;
        site[kOpenGraph] = book[kOpenGraph];
        site[kTwitterCard] = book[kTwitterCard];
        site[kImage] = book[kImage];
        site[kMarginHeader] = book[kMarginHeader];
        site[kMarginFooter] = book[kMarginFooter];
        site[kBodyHeader] = book[kBodyHeader];
        site[kBodyFooter] = book[kBodyFooter];
        site[kBookSearch] = book[kBookSearch];
        site[kSiteReaderMode] = book[kSiteReaderMode];
        site[kGoogleAnalytics] = book[kGoogleAnalytics];
        site[kCookieConsent] = book[kCookieConsent];
        site[kComments] = book[kComments];
        if (book[kPageFooter]) {
            site[kPageFooter] = book[kPageFooter];
        }
    }
    const language = await formatLanguage(config, config[kLanguageDefaults], flags);
    site[kSiteSidebar] = site[kSiteSidebar] || {};
    const siteSidebar = site[kSiteSidebar];
    siteSidebar[kSiteTitle] = book[kSiteTitle];
    siteSidebar[kSidebarLogo] = book[kSidebarLogo];
    siteSidebar[kContents] = [];
    const bookContents = bookConfig(kBookChapters, config);
    if (Array.isArray(bookContents)) {
        siteSidebar[kContents] = bookChaptersToSidebarItems(bookContents);
    }
    const bookReferences = bookConfig(kBookReferences, config);
    if (bookReferences) {
        siteSidebar[kContents].push(bookReferences);
    }
    const bookAppendix = bookConfig(kBookAppendix, config);
    if (Array.isArray(bookAppendix)) {
        siteSidebar[kContents] = siteSidebar[kContents].concat([
            chapterToSidebarItem({
                part: language[kSectionTitleAppendices],
                chapters: bookAppendix
            }), 
        ]);
    }
    if (book[kBookSearch] !== false) {
        siteSidebar[kBookSearch] = true;
    }
    siteSidebar[kSiteSidebarStyle] = siteSidebar[kSiteSidebarStyle] || "floating";
    const tools = [];
    if (site[kSiteRepoUrl]) {
        const repoUrl = site[kSiteRepoUrl];
        const icon = isGithubRepoUrl(repoUrl) ? "github" : "journal-code";
        tools.push({
            text: "Source Code",
            icon,
            href: repoUrl
        });
    }
    tools.push(...downloadTools(projectDir, config) || []);
    tools.push(...sharingTools(config) || []);
    if (site[kSiteNavbar]) {
        site[kSiteNavbar][kBookTools] = tools;
    } else {
        siteSidebar[kBookTools] = siteSidebar[kBookTools] || [];
        siteSidebar[kBookTools].push(...tools);
    }
    const renderItems = await bookRenderItems(projectDir, language, config);
    book[kBookRender] = renderItems;
    config.project[kProjectRender] = renderItems.filter((target)=>!!target.file
    ).map((target)=>target.file
    );
    const ext404 = engineValidExtensions().find((ext)=>existsSync(join3(projectDir, `404${ext}`))
    );
    if (ext404) {
        config.project[kProjectRender].push(`404${ext404}`);
    }
    return websiteProjectConfig(projectDir, config, forceHtml);
}
function withChapterMetadata(format124, headingText, headingAttr, chapterInfo, config) {
    format124 = cloneDeep1(format124);
    if (headingText) {
        format124.metadata[kTitle] = formatChapterTitle(format124, headingText, headingAttr, chapterInfo);
    }
    format124.metadata[kCrossref] = format124.metadata[kCrossref] || {};
    const crossref = format124.metadata[kCrossref];
    if (headingAttr?.id) {
        crossref[kCrossrefChapterId] = headingAttr?.id;
    }
    if (chapterInfo) {
        format124.pandoc[kNumberOffset] = [
            chapterInfo.number
        ];
        if (chapterInfo.appendix) {
            crossref[kCrossrefChaptersAlpha] = true;
        }
    } else {
        format124.pandoc[kNumberSections] = false;
    }
    format124.pandoc[kToc] = isListedChapter(headingAttr);
    delete format124.metadata[kDoi];
    const description = bookConfig("description", config);
    if (description) {
        format124.metadata[kDescription] = description;
    }
    return format124;
}
function isListedChapter(headingAttr) {
    return !headingAttr || !headingAttr.classes.includes("unlisted");
}
const variableRegex = /{{<\s*var\s+(.*?)\s*>}}/gm;
function resolveVariables(value, config) {
    variableRegex.lastIndex = 0;
    return value.replaceAll(variableRegex, (_, varName)=>{
        const vars = config[kQuartoVarsKey];
        if (vars && vars[varName] !== undefined) {
            return String(vars[varName]);
        } else {
            return `?var:${varName}`;
        }
    });
}
function bookConfigRenderItems(project) {
    return bookConfig(kBookRender, project);
}
function chapterInfoForInput(project, chapterHref) {
    const renderItems = bookConfigRenderItems(project.config);
    const appendixPos = renderItems.findIndex((item)=>item.type === kBookItemAppendix
    );
    const itemPos = renderItems.findIndex((item)=>item.file === chapterHref
    );
    if (itemPos !== -1) {
        const appendix = appendixPos !== -1 && itemPos > appendixPos;
        const item = renderItems[itemPos];
        if (item.number) {
            return {
                number: item.number,
                appendix,
                labelPrefix: appendix ? String.fromCharCode(64 + item.number) : item.number.toString()
            };
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function bookPandocRenderer(options, project) {
    const renderedFiles = [];
    const executedFiles = {};
    const cleanupExecutedFiles = ()=>{
        for (const format125 of Object.keys(executedFiles)){
            executedFiles[format125].forEach((executedFile)=>{
                cleanupExecutedFile(executedFile, executedFile.recipe.output);
            });
        }
    };
    return {
        onBeforeExecute: (format126)=>{
            return {
                resolveDependencies: isMultiFileBookFormat(format126)
            };
        },
        onRender: async (format127, file, quiet)=>{
            if (isMultiFileBookFormat(file.context.format)) {
                const partitioned = partitionMarkdown(file.executeResult.markdown);
                const fileRelative = pathWithForwardSlashes(relative2(project.dir, file.context.target.source));
                if (isBookIndexPage(fileRelative)) {
                    file.recipe.format = withBookTitleMetadata(file.recipe.format, project.config);
                    if (!isNumberedChapter(partitioned)) {
                        file.recipe.format.pandoc[kNumberSections] = false;
                    }
                    if (!isListedChapter(partitioned.headingAttr)) {
                        file.recipe.format.pandoc[kToc] = false;
                    }
                    const coverImage = file.recipe.format.metadata[kBookCoverImage] || bookConfig(kBookCoverImage, project.config);
                    if (coverImage) {
                        const title18 = file.recipe.format.metadata[kTitle] || "";
                        file.executeResult.markdown = `![](${coverImage} "${title18}"){.quarto-cover-image}\n\n` + file.executeResult.markdown;
                    }
                } else {
                    const chapterInfo = isHtmlOutput(file.recipe.format.pandoc) ? chapterInfoForInput(project, fileRelative) : undefined;
                    const titleInMetadata = frontMatterTitle(partitioned.yaml);
                    if (titleInMetadata) {
                        const parsedHeading = parsePandocTitle(titleInMetadata);
                        file.recipe.format = withChapterMetadata(file.recipe.format, parsedHeading.heading, parsedHeading.attr, chapterInfo, project.config);
                    } else {
                        if (partitioned.headingText) {
                            file.recipe.format = withChapterMetadata(file.recipe.format, partitioned.headingText, partitioned.headingAttr, chapterInfo, project.config);
                        }
                        file.executeResult.markdown = partitioned.markdown;
                    }
                }
                renderedFiles.push(await renderPandoc(file, quiet));
            } else {
                executedFiles[format127] = executedFiles[format127] || [];
                executedFiles[format127].push(file);
            }
        },
        onComplete: async (error32, quiet)=>{
            if (error32) {
                cleanupExecutedFiles();
                return {
                    files: renderedFiles
                };
            }
            try {
                const renderFormats1 = Object.keys(executedFiles);
                for (const renderFormat of renderFormats1){
                    const files = executedFiles[renderFormat];
                    if (files.length > 0) {
                        const format128 = files[0].context.format;
                        if (!isMultiFileBookFormat(format128)) {
                            renderedFiles.push(await renderSingleFileBook(project, options, files, !!quiet));
                        }
                    }
                    delete executedFiles[renderFormat];
                }
                return {
                    files: renderedFiles
                };
            } catch (error1) {
                cleanupExecutedFiles();
                return {
                    files: renderedFiles,
                    error: error1 ? typeof error1 === "string" ? new Error(error1) : error1 : new Error()
                };
            }
        }
    };
}
function formatChapterTitle(format129, label, attr, info5) {
    const withIdSpan = (text)=>{
        if (!attr?.id) {
            return text;
        } else {
            return `[${text}]{#${attr.id} .quarto-section-identifier}`;
        }
    };
    if (info5) {
        if (info5.appendix) {
            const crossref = format129.metadata?.crossref;
            const title19 = crossref?.[kCrossrefAppendixTitle] || "Appendix";
            const delim = crossref?.[kCrossrefAppendixDelim] !== undefined ? crossref?.[kCrossrefAppendixDelim] : " —";
            return withIdSpan(`${title19} ${info5.labelPrefix}${delim} ${label}`);
        } else {
            return withIdSpan(`[${info5.labelPrefix}]{.chapter-number}\u00A0 [${label}]{.chapter-title}`);
        }
    } else {
        return withIdSpan(label);
    }
}
function formatChapterHtmlNav(label, info6) {
    if (info6) {
        return `<span class='chapter-number'>${info6.labelPrefix}</span>\u00A0 <span class='chapter-title'>${label}</span>`;
    } else {
        return label;
    }
}
function onSingleFileBookPreRender(format130, config) {
    const extension = format130.extensions?.book;
    if (extension && extension.onSingleFilePreRender) {
        extension.onSingleFilePreRender(format130, config);
    }
    return format130;
}
function onSingleFileBookPostRender(project, file) {
    const extension = file.format.extensions?.book;
    if (extension && extension.onSingleFilePostRender) {
        extension.onSingleFilePostRender(project, file);
    }
}
async function renderSingleFileBook(project, options, files, quiet) {
    const executedFile = await mergeExecutedFiles(project, options, files);
    executedFile.recipe.format = withBookTitleMetadata(executedFile.recipe.format, project.config);
    executedFile.recipe.format = onSingleFileBookPreRender(executedFile.recipe.format, project.config);
    const renderedFile = await renderPandoc(executedFile, quiet);
    files.forEach((file)=>{
        cleanupExecutedFile(file, join3(project.dir, renderedFile.file));
    });
    onSingleFileBookPostRender(project, renderedFile);
    return renderedFile;
}
function renderProgress(message) {
    info(bold(blue(message)));
}
const kSingleFileBook = "single-file-book";
const bookProjectType = {
    type: "book",
    inheritsType: websiteProjectType.type,
    create: (_title)=>{
        const resourceDir = resourcePath(join3("projects", "book"));
        return {
            configTemplate: join3(resourceDir, "templates", "_quarto.ejs.yml"),
            resourceDir,
            scaffold: ()=>[
                    {
                        name: "index",
                        content: "# Preface {.unnumbered}\n\n" + "This is a Quarto book.\n\n" + "To learn more about Quarto books visit <https://quarto.org/docs/books>."
                    },
                    {
                        name: "intro",
                        content: "# Introduction\n\n" + "This is a book created from markdown and executable code.\n\n" + "See @knuth84 for additional discussion of literate programming."
                    },
                    {
                        name: "summary",
                        content: "# Summary\n\nIn summary, this book has no content whatsoever."
                    },
                    {
                        name: "references",
                        content: "# References {.unnumbered}\n\n::: {#refs}\n:::",
                        noEngineContent: true
                    }, 
                ]
            ,
            supporting: [
                "cover.png",
                "references.bib", 
            ]
        };
    },
    libDir: "site_libs",
    outputDir: "_book",
    config: bookProjectConfig,
    projectFormatsOnly: true,
    isSupportedFormat: (format131)=>{
        return !!format131.extensions?.book;
    },
    filterParams: (options)=>{
        if (isMultiFileBookFormat(options.format)) {
            return {
                [kCrossrefResolveRefs]: false
            };
        } else {
            return {
                [kSingleFileBook]: true
            };
        }
    },
    pandocRenderer: bookPandocRenderer,
    navItemText: (context, input, text)=>{
        const chapterInfo = chapterInfoForInput(context, input);
        if (chapterInfo) {
            return Promise.resolve(formatChapterHtmlNav(text, chapterInfo));
        } else {
            return Promise.resolve(text);
        }
    },
    incrementalRenderAll: bookIncrementalRenderAll,
    preRender: websiteProjectType.preRender,
    postRender: bookPostRender,
    formatLibDirs: websiteProjectType.formatLibDirs,
    metadataFields: ()=>[
            ...websiteProjectType.metadataFields(),
            "book"
        ]
    ,
    resourceIgnoreFields: ()=>[
            ...websiteProjectType.resourceIgnoreFields(),
            kBook, 
        ]
    ,
    formatExtras: async (context, source, flags, format132, temp)=>{
        let extras = {
            pandoc: {
                [kToc]: !isEpubOutput(format132.pandoc),
                [kNumberSections]: true
            },
            metadata: {
                [kCrossref]: {
                    [kCrossrefChapters]: true
                }
            }
        };
        if (isHtmlOutput(format132.pandoc, true)) {
            if (formatHasBootstrap(format132)) {
                extras.html = {
                    [kSassBundles]: [
                        bookScssBundle()
                    ],
                    [kHtmlPostprocessors]: [
                        bookHtmlPostprocessor()
                    ]
                };
            }
            const websiteExtras = await websiteProjectType.formatExtras(context, source, flags, format132, temp);
            extras = mergeConfigs(extras, websiteExtras);
        } else if (isLatexOutput(format132.pandoc)) {
            extras = mergeConfigs(extras, {
                metadata: {
                    [kDocumentClass]: "scrreprt",
                    [kPaperSize]: "letter"
                },
                pandoc: {
                    [kTopLevelDivision]: "chapter"
                }
            });
        }
        return extras;
    }
};
function kTypes() {
    return [
        defaultProjectType,
        websiteProjectType,
        bookProjectType, 
    ];
}
function parseProjectType(projType) {
    if (projType) {
        const parts = projType.split(":");
        return {
            type: parts[0],
            template: parts.length > 1 ? parts[1] : undefined
        };
    } else {
        return {
            type: "default"
        };
    }
}
function projectTypes() {
    return kTypes().map((type)=>type.type
    );
}
function projectTypeAliases() {
    return kTypes().flatMap((type)=>type.typeAliases || []
    );
}
function projectType(type = "default") {
    const projectType1 = kTypes().find((pt)=>pt.type === type
    );
    if (projectType1) {
        return projectType1;
    } else {
        throw new Error(`Unsuppported project type ${type}`);
    }
}
function deleteProjectMetadata(metadata) {
    const projType = projectType(metadata.project?.[kProjectType]);
    if (projType.metadataFields) {
        for (const field of projType.metadataFields().concat("project")){
            if (typeof field === "string") {
                delete metadata[field];
            } else {
                for (const key of Object.keys(metadata)){
                    if (field.test(key)) {
                        delete metadata[key];
                    }
                }
            }
        }
    }
    delete metadata.project;
}
function crossrefFilter() {
    return resourcePath("filters/crossref/crossref.lua");
}
function crossrefFilterActive(options) {
    return options.format.metadata.crossref !== false;
}
const kQuartoParams = "quarto-params";
const kProjectOffset = "project-offset";
const kResultsFile = "results-file";
async function projectContext(path88, flags, force = false, forceHtml = false) {
    let dir = Deno.realPathSync(Deno.statSync(path88).isDirectory ? path88 : dirname2(path88));
    const originalDir = dir;
    while(true){
        const configFile = projectConfigFile(dir);
        if (configFile) {
            const configSchema = await getProjectConfigSchema();
            const configFiles = [
                configFile
            ];
            const errMsg = "Project _quarto.yml validation failed.";
            let projectConfig = await readAndValidateYamlFromFile(configFile, configSchema, errMsg);
            projectConfig.project = projectConfig.project || {};
            const includedMeta = await includedMetadata(dir, projectConfig, configSchema);
            const metadata = includedMeta.metadata;
            configFiles.push(...includedMeta.files);
            projectConfig = mergeConfigs(projectConfig, metadata);
            delete projectConfig[kMetadataFile];
            delete projectConfig[kMetadataFiles];
            projectConfig = migrateProjectConfig(projectConfig);
            const varsFile = projectVarsFile(dir);
            if (varsFile) {
                configFiles.push(varsFile);
                const vars = readYaml(varsFile);
                projectConfig[kQuartoVarsKey] = mergeConfigs(projectConfig[kQuartoVarsKey] || {}, vars);
            }
            const translationFiles = await resolveLanguageTranslations(projectConfig, dir);
            configFiles.push(...translationFiles);
            if (flags?.to && flags?.to !== "all" && flags?.to !== "default") {
                const projectFormats = normalizeFormatYaml(projectConfig[kMetadataFormat]);
                const toFormat = projectFormats[flags?.to] || {};
                delete projectFormats[flags?.to];
                const formats5 = {
                    [flags?.to]: toFormat
                };
                Object.keys(projectFormats).forEach((format133)=>{
                    formats5[format133] = projectFormats[format133];
                });
                projectConfig[kMetadataFormat] = formats5;
            }
            if (projectConfig?.project) {
                if (flags?.outputDir) {
                    projectConfig.project[kProjectOutputDir] = flags.outputDir;
                }
                if (typeof projectConfig.project[kProjectPreRender] === "string") {
                    projectConfig.project[kProjectPreRender] = [
                        projectConfig.project[kProjectPreRender], 
                    ];
                }
                if (typeof projectConfig.project[kProjectPostRender] === "string") {
                    projectConfig.project[kProjectPostRender] = [
                        projectConfig.project[kProjectPostRender], 
                    ];
                }
                const type = projectType(projectConfig.project?.[kProjectType]);
                if (projectConfig.project[kProjectLibDir] === undefined && type.libDir) {
                    projectConfig.project[kProjectLibDir] = type.libDir;
                }
                if (!projectConfig.project[kProjectOutputDir] && type.outputDir) {
                    projectConfig.project[kProjectOutputDir] = type.outputDir;
                }
                if (projectConfig.project[kProjectOutputDir] === ".") {
                    delete projectConfig.project[kProjectOutputDir];
                }
                if (type.config) {
                    projectConfig = await type.config(dir, projectConfig, forceHtml, flags);
                }
                const { files , engines  } = projectInputFiles(dir, projectConfig);
                const fullPath = Deno.realPathSync(path88);
                if (Deno.statSync(fullPath).isFile && !files.includes(fullPath)) {
                    return undefined;
                }
                return {
                    dir,
                    engines,
                    files: {
                        input: files,
                        resources: projectResourceFiles(dir, projectConfig),
                        config: configFiles,
                        configResources: projectConfigResources(dir, projectConfig, type)
                    },
                    config: projectConfig,
                    formatExtras: type.formatExtras
                };
            } else {
                const { files , engines  } = projectInputFiles(dir);
                return {
                    dir,
                    engines,
                    config: projectConfig,
                    files: {
                        input: files,
                        resources: projectResourceFiles(dir, projectConfig),
                        config: configFiles,
                        configResources: projectConfigResources(dir, projectConfig)
                    }
                };
            }
        } else {
            const nextDir = dirname2(dir);
            if (nextDir === dir) {
                if (force) {
                    const context = {
                        dir: originalDir,
                        engines: [],
                        config: {
                            project: {}
                        },
                        files: {
                            input: []
                        }
                    };
                    if (Deno.statSync(path88).isDirectory) {
                        const { files , engines  } = projectInputFiles(originalDir);
                        context.engines = engines;
                        context.files.input = files;
                    } else {
                        const input = Deno.realPathSync(path88);
                        context.engines = [
                            fileExecutionEngine(input)?.name || kMarkdownEngine, 
                        ];
                        context.files.input = [
                            input
                        ];
                    }
                    return context;
                } else {
                    return undefined;
                }
            } else {
                dir = nextDir;
            }
        }
    }
}
async function inputTargetIndex(project, input) {
    const inputFile = join3(project.dir, input);
    if (!existsSync(inputFile) || Deno.statSync(inputFile).isDirectory) {
        return Promise.resolve(undefined);
    }
    if (!project.files.input.includes(Deno.realPathSync(inputFile))) {
        return Promise.resolve(undefined);
    }
    const engine = fileExecutionEngine(inputFile);
    if (engine === undefined) {
        return Promise.resolve(undefined);
    }
    const targetIndex = readInputTargetIndex(project.dir, input);
    if (targetIndex) {
        return targetIndex;
    }
    const formats6 = await renderFormats(inputFile, "all", project);
    const firstFormat = Object.values(formats6)[0];
    const index = {
        title: firstFormat ? firstFormat.metadata?.[kTitle] : undefined,
        markdown: await engine.partitionedMarkdown(inputFile),
        formats: formats6
    };
    if (index.title) {
        const parsedTitle = parsePandocTitle(index.title);
        index.title = parsedTitle.heading;
    } else {
        index.title = index.markdown.headingText;
    }
    const indexFile = inputTargetIndexFile(project.dir, input);
    Deno.writeTextFileSync(indexFile, JSON.stringify(index));
    return index;
}
function readInputTargetIndex(projectDir, input) {
    const index = readInputTargetIndexIfStillCurrent(projectDir, input);
    if (index) {
        const formats7 = Object.keys(index.formats);
        const projConfigFile = projectConfigFile(projectDir);
        if (projConfigFile) {
            const config = readYaml(projConfigFile);
            const projFormats = formatKeys(config);
            if (__VIRTUAL_FILE211(formats7, projFormats)) {
                return index;
            } else {
                return undefined;
            }
        } else {
            return index;
        }
    } else {
        return undefined;
    }
}
const kAriaLabel = "aria-label";
const kCollapseLevel = "collapse-level";
const kCollapseBelow = "collapse-below";
const kSidebarMenus = "sidebar-menus";
function normalizeSidebarItem(projectDir, item) {
    item = cloneDeep1(item);
    if (typeof item === "string") {
        if (safeExistsSync(join3(projectDir, item))) {
            item = {
                href: item
            };
        } else {
            item = {
                text: item
            };
        }
    } else {
        resolveHrefAttribute(item);
        const section = item.section;
        if (section) {
            const sectionPath = join3(projectDir, section);
            if (safeExistsSync(sectionPath) && Deno.statSync(sectionPath).isFile) {
                item.href = section;
            } else {
                item.text = section;
            }
            item.sectionId = kQuartoSidebarPrefix + asHtmlId(section);
            delete item.section;
        }
        if (item.contents && !item.sectionId) {
            item.sectionId = kQuartoSidebarPrefix + shortUuid();
        }
        if (item.contents) {
            for(let i = 0; i < item.contents.length; i++){
                item.contents[i] = normalizeSidebarItem(projectDir, item.contents[i]);
            }
        }
    }
    return item;
}
const kQuartoSidebarPrefix = "quarto-sidebar-section-";
function resolveHrefAttribute(item) {
    item.href = item.href || item.file || item.url;
    delete item.file;
    delete item.url;
}
async function partitionedMarkdownForInput(projectDir, input) {
    const index = readInputTargetIndex(projectDir, input);
    if (index) {
        return index.markdown;
    } else {
        const inputPath = join3(projectDir, input);
        const engine = fileExecutionEngine(inputPath);
        if (engine) {
            return await engine.partitionedMarkdown(inputPath);
        } else {
            return undefined;
        }
    }
}
function pandocMetadataPath(path89) {
    return pathWithForwardSlashes(path89);
}
function resourceFilesFromRenderedFile(baseDir, renderedFile, partitioned) {
    return resourceFilesFromFile(baseDir, renderedFile.file, renderedFile.resourceFiles, renderedFile.selfContained, renderedFile.supporting, partitioned);
}
async function ojsExecuteResult(context, executeResult, ojsBlockLineNumbers) {
    executeResult = cloneDeep1(executeResult);
    const source = Deno.readTextFileSync(context.target.source);
    const mappedMarkdown = mappedDiff(asMappedString(source), executeResult.markdown);
    const { markdown , includes , filters , resourceFiles  } = await ojsCompile({
        source: context.target.source,
        format: context.format,
        markdown: mappedMarkdown,
        libDir: context.libDir,
        project: context.project,
        temp: context.options.temp,
        ojsBlockLineNumbers
    });
    executeResult.markdown = markdown;
    if (includes) {
        executeResult.includes = mergeConfigs(includes, executeResult.includes || {});
    }
    if (filters) {
        executeResult.filters = (executeResult.filters || []).concat(filters);
    }
    return {
        executeResult,
        resourceFiles: resourceFiles || []
    };
}
async function renderFiles(files, options, alwaysExecuteFiles, pandocRenderer, project) {
    pandocRenderer = pandocRenderer || defaultPandocRenderer(options, project);
    const tempContext = createTempContext();
    try {
        options = cloneDeep1(options);
        const progress = options.progress || project && files.length > 1 && !options.flags?.quiet;
        const pandocQuiet = !!progress;
        const numWidth = String(files.length).length;
        for(let i = 0; i < files.length; i++){
            const file = files[i];
            if (progress) {
                renderProgress(`[${String(i + 1).padStart(numWidth)}/${files.length}] ${relative2(project.dir, file.path)}`);
            }
            let contexts;
            try {
                contexts = await renderContexts(file, options, true, project);
            } catch (e) {
                const { engine , target  } = await fileExecutionEngineAndTarget(file.path, options.flags?.quiet);
                const validationResult = await validateDocumentFromSource(target.markdown, engine.name, error, file.path);
                if (validationResult.length) {
                    throw new RenderInvalidYAMLError();
                } else {
                    throw e;
                }
            }
            for (const format134 of Object.keys(contexts)){
                const context = contexts[format134];
                if (isHtmlCompatible(context.format)) {
                    await initDenoDom();
                }
                const recipe = await outputRecipe(context);
                const executeOptions = mergeConfigs({
                    alwaysExecute: alwaysExecuteFiles?.includes(file.path)
                }, pandocRenderer.onBeforeExecute(recipe.format));
                const validate4 = context.format.metadata?.["validate-yaml"];
                if (validate4 !== false) {
                    const validationResult = await validateDocument(context);
                    if (validationResult.length) {
                        throw new RenderInvalidYAMLError();
                    }
                }
                const { ojsBlockLineNumbers  } = annotateOjsLineNumbers(context);
                const baseExecuteResult = await renderExecute(context, recipe.output, executeOptions);
                const { executeResult , resourceFiles  } = await ojsExecuteResult(context, baseExecuteResult, ojsBlockLineNumbers);
                await pandocRenderer.onRender(format134, {
                    context,
                    recipe,
                    executeResult,
                    resourceFiles
                }, pandocQuiet);
            }
        }
        if (progress) {
            info("");
        }
        return await pandocRenderer.onComplete(false, options.flags?.quiet);
    } catch (error1) {
        return {
            files: (await pandocRenderer.onComplete(true)).files,
            error: error1 || new Error()
        };
    } finally{
        tempContext.cleanup();
    }
}
async function renderProject(context, options, files) {
    const projType = projectType(context.config?.project?.[kProjectType]);
    const projDir = Deno.realPathSync(context.dir);
    const incremental = !!files;
    let alwaysExecuteFiles = incremental && !options.useFreezer ? __VIRTUAL_FILE107(files) : undefined;
    const normalizeFiles = (targetFiles)=>{
        return targetFiles.map((file)=>{
            const target = isAbsolute2(file) ? file : join3(Deno.cwd(), file);
            if (!existsSync(target)) {
                throw new Error("Render target does not exist: " + file);
            }
            return Deno.realPathSync(target);
        });
    };
    if (files) {
        if (alwaysExecuteFiles) {
            alwaysExecuteFiles = normalizeFiles(alwaysExecuteFiles);
            files = normalizeFiles(files);
        } else if (options.useFreezer) {
            files = normalizeFiles(files);
        }
    }
    if (files && alwaysExecuteFiles && projType.incrementalRenderAll && await projType.incrementalRenderAll(context, options, files)) {
        files = context.files.input;
        options = {
            ...options,
            useFreezer: true
        };
    }
    const renderAll = !files || files.length === context.files.input.length;
    const prePostEnv = {
        "QUARTO_PROJECT_OUTPUT_DIR": context.config?.project?.[kProjectOutputDir] || ".",
        ...renderAll ? {
            QUARTO_PROJECT_RENDER_ALL: "1"
        } : {}
    };
    files = files || context.files.input;
    const filesToRender1 = files.map((file)=>{
        return {
            path: file
        };
    });
    const projectSupplement = (filesToRender)=>{
        if (projType.supplementRender && !options.devServerReload) {
            return projType.supplementRender(context, filesToRender, incremental);
        } else {
            return {
                files: []
            };
        }
    };
    const supplements = projectSupplement(filesToRender1);
    filesToRender1.push(...supplements.files);
    const projResults = {
        baseDir: projDir,
        outputDir: context.config?.project?.[kProjectOutputDir],
        files: []
    };
    await ensureGitignore(context.dir);
    const progress = !!options.progress || filesToRender1.length > 1;
    const projOutputDir = context.config?.project?.[kProjectOutputDir];
    if (renderAll && typeof projOutputDir === "string" && options.flags?.clean == true) {
        const realProjectDir = Deno.realPathSync(context.dir);
        let realOutputDir = join3(realProjectDir, projOutputDir);
        if (existsSync(realOutputDir)) {
            realOutputDir = Deno.realPathSync(realOutputDir);
            if (realOutputDir !== realProjectDir && realOutputDir.startsWith(realProjectDir)) {
                removeIfExists(realOutputDir);
            }
        }
    }
    if (filesToRender1.length > 0 && context.config?.project?.[kProjectPreRender]) {
        await runPreRender(projDir, context.config?.project?.[kProjectPreRender], progress, !!options.flags?.quiet, {
            ...prePostEnv,
            QUARTO_PROJECT_INPUT_FILES: filesToRender1.map((fileToRender)=>fileToRender.path
            ).map((file)=>relative2(projDir, file)
            ).join("\n")
        });
    }
    if (projType.preRender) {
        await projType.preRender(context);
    }
    const executeDir = context.config?.project?.[kProjectExecuteDir];
    if (options.flags?.executeDir === undefined && executeDir === "project") {
        options = {
            ...options,
            flags: {
                ...options.flags,
                executeDir: projDir
            }
        };
    }
    if (filesToRender1.length > 1 && options.flags && options.flags.executeDaemon === undefined) {
        options.flags.executeDaemon = 0;
    }
    const outputDir = projResults.outputDir;
    const outputDirAbsolute = outputDir ? join3(projDir, outputDir) : undefined;
    if (outputDirAbsolute) {
        ensureDirSync(outputDirAbsolute);
    }
    const libDir = context.config?.project[kProjectLibDir];
    const resourcesFrom = async (file)=>{
        const partitioned = await partitionedMarkdownForInput(projDir, file.input);
        const resourceFiles = resourceFilesFromRenderedFile(projDir, file, partitioned);
        return resourceFiles;
    };
    Deno.env.set("QUARTO_PROJECT_DIR", projDir);
    try {
        const fileResults = await renderFiles(filesToRender1, options, alwaysExecuteFiles, projType?.pandocRenderer ? projType.pandocRenderer(options, context) : undefined, context);
        if (outputDirAbsolute) {
            const relocateDir = (dir, copy4 = false)=>{
                const targetDir = join3(outputDirAbsolute, dir);
                if (existsSync(targetDir)) {
                    Deno.removeSync(targetDir, {
                        recursive: true
                    });
                }
                const srcDir = join3(projDir, dir);
                if (existsSync(srcDir)) {
                    ensureDirSync(dirname2(targetDir));
                    if (copy4) {
                        copySync(srcDir, targetDir);
                    } else {
                        Deno.renameSync(srcDir, targetDir);
                    }
                }
            };
            const moveDir = relocateDir;
            const copyDir1 = (dir)=>relocateDir(dir, true)
            ;
            let keepLibsDir = false;
            for(let i = 0; i < fileResults.files.length; i++){
                const renderedFile = fileResults.files[i];
                const outputFile = join3(outputDirAbsolute, renderedFile.file);
                ensureDirSync(dirname2(outputFile));
                Deno.renameSync(join3(projDir, renderedFile.file), outputFile);
                const keepFiles = !!renderedFile.format.execute[kKeepMd];
                keepLibsDir = keepLibsDir || keepFiles;
                if (renderedFile.supporting) {
                    renderedFile.supporting = renderedFile.supporting.filter((file)=>file !== libDir
                    );
                    if (keepFiles) {
                        renderedFile.supporting.map((file)=>copyDir1(file)
                        );
                    } else {
                        renderedFile.supporting.map((file)=>moveDir(file)
                        );
                    }
                }
                if (!keepFiles) {
                    const filesDir = join3(projDir, dirname2(renderedFile.file), inputFilesDir(renderedFile.file));
                    removeIfEmptyDir(filesDir);
                }
                projResults.files.push({
                    input: renderedFile.input,
                    markdown: renderedFile.markdown,
                    format: renderedFile.format,
                    file: renderedFile.file,
                    supporting: renderedFile.supporting,
                    resourceFiles: await resourcesFrom(renderedFile)
                });
            }
            if (libDir) {
                const libDirFull = join3(context.dir, libDir);
                if (existsSync(libDirFull)) {
                    const libsIncremental = !!(incremental || options.useFreezer);
                    const formatLibDirs = projType.formatLibDirs ? projType.formatLibDirs() : [];
                    const freezeLibDir = (hidden35)=>{
                        copyToProjectFreezer(context, libDir, hidden35, false);
                        pruneProjectFreezerDir(context, libDir, formatLibDirs, hidden35);
                        pruneProjectFreezer(context, hidden35);
                    };
                    freezeLibDir(true);
                    if (existsSync(join3(context.dir, kProjectFreezeDir))) {
                        freezeLibDir(false);
                    }
                    if (libsIncremental) {
                        for (const lib of Deno.readDirSync(libDirFull)){
                            if (lib.isDirectory) {
                                const copyDir2 = join3(libDir, lib.name);
                                const srcDir = join3(projDir, copyDir2);
                                const targetDir = join3(outputDirAbsolute, copyDir2);
                                copyMinimal(srcDir, targetDir);
                                if (!keepLibsDir) {
                                    removeIfExists(srcDir);
                                }
                            }
                        }
                        if (!keepLibsDir) {
                            Deno.removeSync(libDirFull, {
                                recursive: true
                            });
                        }
                    } else {
                        if (keepLibsDir) {
                            copyDir1(libDir);
                        } else {
                            moveDir(libDir);
                        }
                    }
                }
            }
            const outputFiles = projResults.files.map((result)=>join3(projDir, result.file)
            );
            projResults.files.forEach((file)=>{
                file.resourceFiles = file.resourceFiles.filter((resource)=>!outputFiles.includes(resource)
                );
            });
            const allResourceFiles = __VIRTUAL_FILE181((context.files.resources || []).concat(projResults.files.flatMap((file)=>file.resourceFiles
            )));
            allResourceFiles.forEach((file)=>{
                const sourcePath = relative2(projDir, file);
                const destPath = join3(outputDirAbsolute, sourcePath);
                if (existsSync(file)) {
                    if (Deno.statSync(file).isFile) {
                        copyResourceFile(context.dir, file, destPath);
                    }
                } else if (!existsSync(destPath)) {
                    warning(`File '${sourcePath}' was not found.`);
                }
            });
        } else {
            for (const result of fileResults.files){
                const resourceFiles = await resourcesFrom(result);
                projResults.files.push({
                    input: result.input,
                    markdown: result.markdown,
                    format: result.format,
                    file: result.file,
                    supporting: result.supporting,
                    resourceFiles
                });
            }
        }
        projResults.error = fileResults.error;
        if (!projResults.error) {
            const outputFiles = projResults.files.map((result)=>{
                const file = outputDir ? join3(outputDir, result.file) : result.file;
                return {
                    file: join3(projDir, file),
                    format: result.format
                };
            });
            if (projType.postRender) {
                await projType.postRender(context, incremental, outputFiles);
            }
            if (filesToRender1.length > 0 && context.config?.project?.[kProjectPostRender]) {
                await runPostRender(projDir, context.config?.project?.[kProjectPostRender], progress, !!options.flags?.quiet, {
                    ...prePostEnv,
                    QUARTO_PROJECT_OUTPUT_FILES: outputFiles.map((outputFile)=>relative2(projDir, outputFile.file)
                    ).join("\n")
                });
            }
        }
        projResults.files.forEach((file)=>{
            if (supplements.files.find((supFile)=>{
                return supFile.path === join3(projDir, file.input);
            })) {
                file.supplemental = true;
            }
        });
        const nonSupplementalFiles = projResults.files.filter((file)=>!file.supplemental
        ).map((file)=>file.file
        );
        if (supplements.onRenderComplete) {
            await supplements.onRenderComplete(context, nonSupplementalFiles, incremental);
        }
        return projResults;
    } finally{
        Deno.env.delete("QUARTO_PROJECT_DIR");
    }
}
function migrateProjectConfig(projectConfig) {
    projectConfig = cloneDeep1(projectConfig);
    const kSite = "site";
    if (projectConfig.project[kProjectType] === kSite) {
        projectConfig.project[kProjectType] = kWebsite;
    }
    if (projectConfig[kSite]) {
        projectConfig[kWebsite] = cloneDeep1(projectConfig[kSite]);
        delete projectConfig[kSite];
    }
    return projectConfig;
}
async function resolveLanguageTranslations(projectConfig, dir) {
    const files = [];
    files.push(...await resolveLanguageMetadata(projectConfig, dir));
    const translations = await readLanguageTranslations(join3(dir, "_language.yml"));
    projectConfig[kLanguageDefaults] = mergeConfigs(translations.language, projectConfig[kLanguageDefaults]);
    files.push(...translations.files);
    return files;
}
function projectContextForDirectory(path90, flags) {
    return projectContext(path90, flags, true);
}
async function render(path91, options) {
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
    const context = await projectContext(path91, options.flags);
    if (Deno.statSync(path91).isDirectory) {
        let files;
        if (context) {
            const renderDir = Deno.realPathSync(path91);
            const projectDir = Deno.realPathSync(context.dir);
            if (renderDir !== projectDir) {
                files = context.files.input.filter((file)=>file.startsWith(renderDir)
                );
            }
            return renderProject(context || await projectContextForDirectory(path91, options.flags), options, files);
        } else {
            throw new Error("The specified directory ('" + path91 + "') is not a Quarto project");
        }
    } else if (context?.config) {
        if (isProjectInputFile(path91, context)) {
            return renderProject(context, options, [
                path91
            ]);
        }
    }
    const result = await renderFiles([
        {
            path: path91
        }
    ], options);
    const engine = fileExecutionEngine(path91);
    const partitioned = engine && result.files.length > 0 ? await engine.partitionedMarkdown(path91) : undefined;
    return {
        files: await Promise.all(result.files.map(async (file)=>{
            const resourceFiles = await resourceFilesFromRenderedFile(dirname2(path91), file, partitioned);
            return {
                input: file.input,
                markdown: file.markdown,
                format: file.format,
                file: file.file,
                supporting: file.supporting,
                resourceFiles
            };
        })),
        error: result.error
    };
}
function crossrefFilterParams(options, defaults) {
    const flags = options.flags;
    const metadata = options.format.metadata;
    const kCrossrefFilterParams = [
        kListings,
        kNumberSections,
        kNumberOffset
    ];
    const params = {};
    kCrossrefFilterParams.forEach((option)=>{
        const value = crossrefOption(option, flags, defaults);
        if (value) {
            if (option === kNumberOffset) {
                if (!Array.isArray(value) || value.some((num)=>!Number.isInteger(num)
                )) {
                    throw new Error("Invalid value for number-offset (should be an array of numbers)");
                }
            }
            params[option] = value;
        }
    });
    params[kNumberDepth] = metadata?.[kNumberDepth];
    if (options.project) {
        params[kCrossrefIndexFile] = pandocMetadataPath(crossrefIndexForOutputFile(options.project.dir, options.source, options.output));
    } else {
        const crossrefIndex = Deno.env.get("QUARTO_CROSSREF_INDEX_PATH");
        if (crossrefIndex) {
            params[kCrossrefIndexFile] = pandocMetadataPath(crossrefIndex);
        }
    }
    return params;
}
function filterParamsJson(args, options, defaults, filterParams, resultsFile) {
    const includes = options.format.render[kMergeIncludes] !== false ? extractIncludeParams(args, options.format.metadata, defaults || {}) : {};
    const quartoColumnParams = extractColumnParams(args, options.format.metadata, defaults);
    const params = {
        ...includes,
        ...projectFilterParams(options),
        ...quartoColumnParams,
        ...quartoFilterParams(options.format),
        ...crossrefFilterParams(options, defaults),
        ...layoutFilterParams(options.format),
        ...languageFilterParams(options.format.language),
        ...filterParams,
        [kResultsFile]: pandocMetadataPath(resultsFile)
    };
    return JSON.stringify(params);
}
function removeFilterParmas(metadata) {
    delete metadata[kQuartoParams];
}
function quartoInitFilter() {
    return resourcePath("filters/init/init.lua");
}
function quartoPreFilter() {
    return resourcePath("filters/quarto-pre/quarto-pre.lua");
}
function quartoPostFilter() {
    return resourcePath("filters/quarto-post/quarto-post.lua");
}
function extractIncludeParams(args, metadata, defaults) {
    const includes = mergeConfigs(extractIncludeVariables(metadata), extractIncludeVariables(defaults.variables || {}));
    if (defaults.variables && Object.keys(defaults.variables).length === 0) {
        delete defaults.variables;
    }
    const inHeaderFiles = defaults[kIncludeInHeader] || [];
    const beforeBodyFiles = defaults[kIncludeBeforeBody] || [];
    const afterBodyFiles = defaults[kIncludeAfterBody] || [];
    delete defaults[kIncludeInHeader];
    delete defaults[kIncludeAfterBody];
    delete defaults[kIncludeBeforeBody];
    for(const arg in args){
        switch(arg){
            case kIncludeInHeader:
                inHeaderFiles.push(arg);
                break;
            case kIncludeBeforeBody:
                beforeBodyFiles.push(arg);
                break;
            case kIncludeAfterBody:
                afterBodyFiles.push(arg);
                break;
        }
    }
    const removeArgs = new Map();
    removeArgs.set(kIncludeInHeader, true);
    removeArgs.set(kIncludeBeforeBody, true);
    removeArgs.set(kIncludeAfterBody, true);
    removePandocArgsInPlace(args, removeArgs);
    return {
        ...includes,
        [kIncludeInHeader]: inHeaderFiles.map(pandocMetadataPath),
        [kIncludeBeforeBody]: beforeBodyFiles.map(pandocMetadataPath),
        [kIncludeAfterBody]: afterBodyFiles.map(pandocMetadataPath)
    };
}
function extractIncludeVariables(obj) {
    const extractVariable = (name134)=>{
        const value = obj[name134];
        delete obj[name134];
        if (!value) {
            return [];
        } else if (__VIRTUAL_FILE53(value)) {
            return value;
        } else {
            return [
                value
            ];
        }
    };
    return {
        [kHeaderIncludes]: extractVariable(kHeaderIncludes),
        [kIncludeBefore]: extractVariable(kIncludeBefore),
        [kIncludeAfter]: extractVariable(kIncludeAfter)
    };
}
function extractColumnParams(args, metadata, defaults) {
    const quartoColumnParams = {};
    if (defaults?.[kReferenceLocation] === "margin" || referenceLocationArg(args) === "margin") {
        quartoColumnParams[kReferenceLocation] = "margin";
        const removeArgs = new Map();
        removeArgs.set(`--${kReferenceLocation}`, true);
        removePandocArgsInPlace(args, removeArgs);
        if (defaults) {
            delete defaults[kReferenceLocation];
        }
    }
    if (defaults?.[kCiteMethod]) {
        quartoColumnParams[kCiteMethod] = defaults[kCiteMethod];
    }
    if (metadata[kCitationLocation]) {
        quartoColumnParams[kCitationLocation] = metadata[kCitationLocation];
    }
    return quartoColumnParams;
}
function removePandocArgsInPlace(args, removeArgs) {
    const cleanedArgs = removePandocArgs(args, removeArgs);
    if (cleanedArgs.length !== args.length) {
        args.splice(0, args.length);
        args.push(...cleanedArgs);
    }
}
function referenceLocationArg(args) {
    const argIndex = args.findIndex((arg)=>{
        return arg === `--${kReferenceLocation}`;
    });
    if (argIndex > -1 && args.length > argIndex + 1) {
        const referenceLocation = args[argIndex + 1];
        return referenceLocation;
    } else {
        return undefined;
    }
}
function languageFilterParams(language) {
    const params = {
        [kCodeSummary]: language[kCodeSummary],
        [kTocTitleDocument]: language[kTocTitleDocument]
    };
    Object.keys(language).forEach((key)=>{
        if (key.startsWith("callout-") || key.startsWith("crossref-")) {
            params[key] = language[key];
        }
    });
    [
        "fig",
        "tbl",
        "lst",
        "thm",
        "lem",
        "cor",
        "prp",
        "cnj",
        "def",
        "exm",
        "exr", 
    ].forEach((type)=>{
        params[`crossref-${type}-prefix`] = language[`crossref-${type}-title`];
    });
    return params;
}
function projectFilterParams(options) {
    const projType = projectType(options.project?.config?.project?.[kProjectType]);
    const params = (projType.filterParams ? projType.filterParams(options) : undefined) || {};
    if (options.offset) {
        return {
            ...params,
            [kProjectOffset]: options.offset
        };
    } else {
        return params;
    }
}
function quartoFilterParams(format135) {
    const params = {
        [kOutputDivs]: format135.render[kOutputDivs]
    };
    const figAlign = format135.render[kFigAlign];
    if (figAlign) {
        params[kFigAlign] = figAlign;
    }
    const figPos = format135.render[kFigPos];
    if (figPos) {
        params[kFigPos] = figPos;
    }
    const figEnv = format135.render[kFigEnv];
    if (figEnv) {
        params[kFigEnv] = figEnv;
    }
    const foldCode = format135.render[kCodeFold];
    if (foldCode) {
        params[kCodeFold] = foldCode;
    }
    const tblColwidths = format135.render[kTblColwidths];
    if (tblColwidths !== undefined) {
        params[kTblColwidths] = tblColwidths;
    }
    const figResponsive = format135.metadata[kFigResponsive] === true;
    if (figResponsive) {
        params[kFigResponsive] = figResponsive;
    }
    const lineNumbers = format135.render[kCodeLineNumbers];
    if (lineNumbers) {
        params[kCodeLineNumbers] = lineNumbers;
    }
    const keepHidden = format135.render[kKeepHidden];
    if (keepHidden) {
        params[kKeepHidden] = kKeepHidden;
    }
    return params;
}
function resolveFilters(filters, options) {
    const quartoFilters = [];
    if (isWindows1()) {
        quartoFilters.push(quartoInitFilter());
    }
    quartoFilters.push(quartoPreFilter());
    if (crossrefFilterActive(options)) {
        quartoFilters.push(crossrefFilter());
    }
    quartoFilters.push(layoutFilter());
    quartoFilters.push(quartoPostFilter());
    const quartoLoc = filters.findIndex((filter5)=>filter5 === "quarto"
    );
    if (quartoLoc !== -1) {
        filters = [
            ...filters.slice(0, quartoLoc),
            ...quartoFilters,
            ...filters.slice(quartoLoc + 1), 
        ];
    } else {
        filters.unshift(...quartoFilters);
    }
    filters = filters.filter((filter6)=>filter6 !== "citeproc"
    );
    const citeproc = citeMethod(options) === "citeproc";
    if (citeproc) {
        filters.push("citeproc");
    }
    if (filters.length > 0) {
        return filters;
    } else {
        return undefined;
    }
}
function generateDefaults(options) {
    let allDefaults;
    if (options.format.pandoc) {
        allDefaults = options.format.pandoc || {};
        const resolvedFilters = resolveFilters([
            ...allDefaults[kFilters] || [], 
        ], options);
        if (resolvedFilters) {
            allDefaults[kFilters] = resolvedFilters;
        }
        if (isLatexOutput(options.format.pandoc)) {
            if (options.format.metadata[kNumberDepth] !== undefined) {
                allDefaults.variables = allDefaults.variables || {};
                allDefaults.variables["secnumdepth"] = options.format.metadata[kNumberDepth];
            }
        }
        return Promise.resolve(allDefaults);
    } else {
        return Promise.resolve(undefined);
    }
}
function projectIsWebsite(context) {
    if (context) {
        const projType = projectType(context.config?.project?.[kProjectType]);
        return projType.type === kWebsite || projType.inheritsType === kWebsite;
    } else {
        return false;
    }
}
function projectIsBook(context) {
    if (context) {
        const projType = projectType(context.config?.project?.[kProjectType]);
        return projType.type === "book";
    } else {
        return false;
    }
}
async function writeDefaultsFile(defaults, temp) {
    const defaultsStr = "---\n" + stringify(defaults, {
        indent: 2,
        sortKeys: false,
        skipInvalid: true
    });
    const defaultsFile = temp.createFile({
        prefix: "quarto-defaults",
        suffix: ".yml"
    });
    await Deno.writeTextFile(defaultsFile, defaultsStr);
    return defaultsFile;
}
async function runPandoc(options, sysFilters) {
    const cwd = dirname2(options.source);
    const cmd = [
        pandocBinaryPath()
    ];
    const args = [
        ...options.args
    ];
    if (options.flags?.quiet) {
        args.push("--quiet");
    }
    if (options.metadata) {
        options.format.metadata = mergeConfigs(options.format.metadata, options.metadata);
    }
    const printArgs = [
        ...args
    ];
    let printMetadata = {
        ...__VIRTUAL_FILE107(options.format.metadata),
        ...options.flags?.metadata
    };
    const cleanMetadataForPrinting = (metadata)=>{
        delete metadata.params;
        delete metadata[kQuartoVarsKey];
        delete metadata[kFigResponsive];
        deleteProjectMetadata(metadata);
        deleteCrossrefMetadata(metadata);
    };
    cleanMetadataForPrinting(printMetadata);
    let allDefaults = await generateDefaults(options) || {};
    let printAllDefaults = __VIRTUAL_FILE107(allDefaults);
    const formatFilterParams = {};
    const kOJSFilter = "ojs";
    if (sysFilters.includes(kOJSFilter)) {
        formatFilterParams[kOJSFilter] = true;
        sysFilters = sysFilters.filter((filter7)=>filter7 !== kOJSFilter
        );
    }
    options.format.language = await formatLanguage(options.format.metadata, options.format.language, options.flags);
    if (!options.format.metadata[kTocTitle]) {
        options.format.metadata[kTocTitle] = options.format.language[projectIsWebsite(options.project) && !projectIsBook(options.project) && isHtmlOutput(options.format.pandoc, true) ? kTocTitleWebsite : kTocTitleDocument];
    }
    if (options.format.metadata[kAbstract] && (isHtmlDocOutput(options.format.pandoc) || isEpubOutput(options.format.pandoc))) {
        options.format.metadata[kAbstractTitle] = options.format.language[kSectionTitleAbstract];
    }
    const postprocessors = [];
    const htmlPostprocessors = [];
    const htmlFinalizers = [];
    const htmlRenderAfterBody = [];
    if (sysFilters.length > 0 || options.format.formatExtras || options.project?.formatExtras) {
        const projectExtras = options.project?.formatExtras ? await options.project.formatExtras(options.project, options.source, options.flags || {}, options.format, options.temp) : {};
        const formatExtras = options.format.formatExtras ? await options.format.formatExtras(options.source, options.flags || {}, options.format, options.libDir, options.temp, options.offset) : {};
        const extras = await resolveExtras(projectExtras, formatExtras, options.format, cwd, options.libDir, options.temp, options.project);
        postprocessors.push(...extras.postprocessors || []);
        if (options.format?.render[kKeepSource] || formatHasCodeTools(options.format)) {
            htmlPostprocessors.push(codeToolsPostprocessor(options.format));
        }
        htmlPostprocessors.push(...extras.html?.[kHtmlPostprocessors] || []);
        htmlFinalizers.push(...extras.html?.[kHtmlFinalizers] || []);
        if (isHtmlFileOutput(options.format.pandoc)) {
            htmlPostprocessors.push(selectInputPostprocessor);
            if (!projectIsWebsite(options.project)) {
                htmlPostprocessors.push(discoverResourceRefs);
            }
        }
        htmlRenderAfterBody.push(...extras.html?.[kMarkdownAfterBody] || []);
        if (sysFilters.length > 0) {
            extras.filters = extras.filters || {};
            extras.filters.post = extras.filters.post || [];
            extras.filters.post.unshift(...sysFilters.map((filter8)=>resourcePath(join3("filters", filter8))
            ));
        }
        if (extras.args) {
            args.push(...extras.args);
            printArgs.push(...extras.args);
        }
        if (extras.pandoc) {
            if (typeof allDefaults[kFrom] === "string" && typeof extras.pandoc[kFrom] === "string") {
                const userFrom = splitPandocFormatString(allDefaults[kFrom]);
                const extrasFrom = splitPandocFormatString(extras.pandoc[kFrom]);
                allDefaults[kFrom] = pandocFormatWith(userFrom.format, "", extrasFrom.options + userFrom.options);
                printAllDefaults[kFrom] = allDefaults[kFrom];
            }
            allDefaults = mergeConfigs(extras.pandoc, allDefaults);
            printAllDefaults = mergeConfigs(extras.pandoc, printAllDefaults);
            if (extras.pandoc[kHighlightStyle]) {
                delete printAllDefaults[kHighlightStyle];
                allDefaults[kHighlightStyle] = extras.pandoc[kHighlightStyle];
            }
        }
        if (extras.metadata) {
            options.format.metadata = {
                ...mergeConfigs(extras.metadata, options.format.metadata),
                ...extras.metadataOverride
            };
            printMetadata = mergeConfigs(extras.metadata, printMetadata);
            cleanMetadataForPrinting(printMetadata);
        }
        if (!allDefaults[kTemplate] && !havePandocArg(args, "--template")) {
            if (allDefaults.to && isHtmlOutput(allDefaults.to)) {
                allDefaults[kTemplate] = await patchHtmlTemplate(allDefaults.to, options.format, options.temp, extras.html?.[kTemplatePatches], options.flags);
            }
        }
        options.format.metadata = cleanupPandocMetadata(options.format.metadata);
        printMetadata = cleanupPandocMetadata(printMetadata);
        if (extras[kIncludeInHeader]) {
            allDefaults = {
                ...allDefaults,
                [kIncludeInHeader]: [
                    ...extras[kIncludeInHeader] || [],
                    ...allDefaults[kIncludeInHeader] || [], 
                ]
            };
        }
        if (extras[kIncludeBeforeBody]) {
            allDefaults = {
                ...allDefaults,
                [kIncludeBeforeBody]: [
                    ...extras[kIncludeBeforeBody] || [],
                    ...allDefaults[kIncludeBeforeBody] || [], 
                ]
            };
        }
        if (extras[kIncludeAfterBody]) {
            allDefaults = {
                ...allDefaults,
                [kIncludeAfterBody]: [
                    ...allDefaults[kIncludeAfterBody] || [],
                    ...extras[kIncludeAfterBody] || [], 
                ]
            };
        }
        if (extras.html?.[kBodyEnvelope] && projectExtras.html?.[kBodyEnvelope]) {
            extras.html[kBodyEnvelope] = projectExtras.html[kBodyEnvelope];
        }
        resolveBodyEnvelope(allDefaults, extras, options.temp);
        allDefaults.filters = [
            ...extras.filters?.pre || [],
            ...allDefaults.filters || [],
            ...extras.filters?.post || [], 
        ];
        allDefaults.filters = allDefaults.filters.map(pandocMetadataPath);
        const filterParams = extras[kFilterParams];
        if (filterParams) {
            Object.keys(filterParams).forEach((key)=>{
                formatFilterParams[key] = filterParams[key];
            });
        }
    }
    const title20 = allDefaults?.[kVariables]?.[kTitle] || options.format.metadata[kTitle];
    const pageTitle = allDefaults?.[kVariables]?.[kPageTitle] || options.format.metadata[kPageTitle];
    const titlePrefix = allDefaults?.[kTitlePrefix];
    if (!title20 && !pageTitle) {
        const [_dir, stem] = dirAndStem(options.source);
        args.push("--metadata", `pagetitle:${pandocAutoIdentifier(stem, false)}`);
    }
    if (pageTitle !== undefined && pageTitle === titlePrefix || pageTitle === undefined && title20 === titlePrefix) {
        delete allDefaults[kTitlePrefix];
    }
    const filterResultsFile = options.temp.createFile();
    let pandocArgs = args;
    const paramsJson = filterParamsJson(pandocArgs, options, allDefaults, formatFilterParams, filterResultsFile);
    if (!isLatexOutput(options.format.pandoc) && crossrefFilterActive(options)) {
        delete allDefaults[kNumberSections];
        delete allDefaults[kNumberOffset];
        const removeArgs = new Map();
        removeArgs.set("--number-sections", false);
        removeArgs.set("--number-offset", true);
        pandocArgs = removePandocArgs(pandocArgs, removeArgs);
    }
    allDefaults[kSyntaxDefinitions] = allDefaults[kSyntaxDefinitions] || [];
    const syntaxDefinitions = expandGlobSync(join3(resourcePath(join3("pandoc", "syntax-definitions")), "*.xml"));
    for (const syntax of syntaxDefinitions){
        allDefaults[kSyntaxDefinitions]?.push(syntax.path);
    }
    if (allDefaults[kHtmlMathMethod] === "webtex") {
        allDefaults[kHtmlMathMethod] = {
            method: "webtex",
            url: "https://latex.codecogs.com/svg.latex?"
        };
    }
    if (allDefaults) {
        const defaultsFile = await writeDefaultsFile(allDefaults, options.temp);
        cmd.push("--defaults", defaultsFile);
    }
    const paritioned = partitionYamlFrontMatter(options.markdown);
    const engineMetadata = paritioned?.yaml ? readYamlFromMarkdown(paritioned.yaml) : {};
    const markdown = paritioned?.markdown || options.markdown;
    const pandocMetadata = __VIRTUAL_FILE107(options.format.metadata || {});
    for (const key1 of Object.keys(engineMetadata)){
        const isChapterTitle = key1 === kTitle && projectIsBook(options.project);
        if (!isQuartoMetadata(key1) && !isChapterTitle && !isIncludeMetadata(key1)) {
            const formats8 = engineMetadata[kMetadataFormat];
            if (__VIRTUAL_FILE18(formats8) && metadataGetDeep(formats8, key1).length > 0) {
                continue;
            }
            pandocMetadata[key1] = engineMetadata[key1];
        }
    }
    const authorsRaw = pandocMetadata[kAuthor];
    if (authorsRaw) {
        const authors = parseAuthor(pandocMetadata[kAuthor]);
        if (authors) {
            pandocMetadata[kAuthor] = authors.map((author)=>author.name
            );
        }
    }
    if (isLatexOutput(options.format.pandoc) && !isBeamerOutput(options.format.pandoc)) {
        const docClass = pandocMetadata[kDocumentClass];
        const isPrintDocumentClass = docClass && [
            "book",
            "scrbook"
        ].includes(docClass);
        if (!isPrintDocumentClass) {
            if (pandocMetadata[kColorLinks] === undefined) {
                pandocMetadata[kColorLinks] = true;
            }
            if (pandocMetadata[kLinkColor] === undefined) {
                pandocMetadata[kLinkColor] = "blue";
            }
        }
    }
    const markdownWithRenderAfter = isHtmlOutput(options.format.pandoc) && htmlRenderAfterBody.length > 0 ? markdown + "\n\n\n" + htmlRenderAfterBody.join("\n") + "\n\n" : markdown;
    const input = markdownWithRenderAfter + keepSourceBlock(options.format, options.source);
    const inputTemp = options.temp.createFile({
        prefix: "quarto-input",
        suffix: ".md"
    });
    Deno.writeTextFileSync(inputTemp, input);
    cmd.push(inputTemp);
    const metadataTemp = options.temp.createFile({
        prefix: "quarto-metadata",
        suffix: ".yml"
    });
    Deno.writeTextFileSync(metadataTemp, stringify(pandocMetadata, {
        indent: 2,
        sortKeys: false,
        skipInvalid: true
    }));
    cmd.push("--metadata-file", metadataTemp);
    cmd.push(...pandocArgs);
    if (!options.quiet && !options.flags?.quiet) {
        runPandocMessage(printArgs, printAllDefaults, sysFilters, printMetadata);
    }
    const result = await execProcess({
        cmd,
        cwd,
        env: {
            "QUARTO_FILTER_PARAMS": encode(paramsJson)
        }
    });
    const resources = resourcesFromMetadata(options.format.metadata[kResources]);
    if (existsSync(filterResultsFile)) {
        const filterResultsJSON = Deno.readTextFileSync(filterResultsFile);
        if (filterResultsJSON.trim().length > 0) {
            const filterResults = JSON.parse(filterResultsJSON);
            resources.push(...filterResults.resourceFiles || []);
        }
    }
    if (result.success) {
        return {
            resources,
            postprocessors,
            htmlPostprocessors: isHtmlOutput(options.format.pandoc) ? htmlPostprocessors : [],
            htmlFinalizers: isHtmlDocOutput(options.format.pandoc) ? htmlFinalizers : []
        };
    } else {
        return null;
    }
}
function cleanupPandocMetadata(metadata) {
    const cleaned = __VIRTUAL_FILE107(metadata);
    const classoption = cleaned[kClassOption];
    if (Array.isArray(classoption)) {
        cleaned[kClassOption] = uniqBy1(classoption.reverse(), (option)=>{
            return option.replace(/=.+$/, "");
        }).reverse();
    }
    return cleaned;
}
async function resolveExtras(projectExtras, formatExtras, format136, inputDir, libDir, temp, project) {
    let extras = mergeConfigs(projectExtras, formatExtras);
    if (projectExtras.metadata?.[kDocumentClass]) {
        extras.metadata = extras.metadata || {};
        extras.metadata[kDocumentClass] = projectExtras.metadata?.[kDocumentClass];
    }
    if (isHtmlOutput(format136.pandoc)) {
        extras = await resolveSassBundles(extras, format136.pandoc, temp, formatExtras.html?.[kSassBundles], projectExtras.html?.[kSassBundles], project);
        extras = resolveDependencies(extras, inputDir, libDir, temp);
    } else {
        delete extras.html;
    }
    extras = resolveTextHighlightStyle(extras, format136.pandoc);
    return extras;
}
function resolveDependencies(extras, inputDir, libDir, temp) {
    extras = cloneDeep1(extras);
    const metaTemplate = __VIRTUAL_FILE176(`<meta name="<%- name %>" content="<%- value %>"/>`);
    const scriptTemplate = __VIRTUAL_FILE176(`<script <%= attribs %> src="<%- href %>"></script>`);
    const stylesheetTempate = __VIRTUAL_FILE176(`<link <%= attribs %> href="<%- href %>" rel="stylesheet" />`);
    const rawLinkTemplate = __VIRTUAL_FILE176(`<link href="<%- href %>" rel="<%- rel %>"<% if (type) { %> type="<%- type %>"<% } %> />`);
    const lines13 = [];
    if (extras.html?.[kDependencies]) {
        const copiedDependencies = [];
        for (const dependency of extras.html?.[kDependencies]){
            if (copiedDependencies.includes(dependency.name)) {
                continue;
            }
            const dir = dependency.version ? `${dependency.name}-${dependency.version}` : dependency.name;
            const targetDir = join3(inputDir, libDir, dir);
            const copyDep = (file, template9)=>{
                const targetPath = join3(targetDir, file.name);
                ensureDirSync(dirname2(targetPath));
                Deno.copyFileSync(file.path, targetPath);
                if (template9) {
                    const attribs = file.attribs ? Object.entries(file.attribs).map((entry)=>{
                        const attrib = `${entry[0]}="${entry[1]}"`;
                        return attrib;
                    }).join(" ") : "";
                    const href = join3(libDir, dir, file.name);
                    lines13.push(template9({
                        href: pathWithForwardSlashes(href),
                        attribs
                    }));
                }
            };
            if (dependency.meta) {
                Object.keys(dependency.meta).forEach((name135)=>{
                    lines13.push(metaTemplate({
                        name: name135,
                        value: dependency.meta[name135]
                    }));
                });
            }
            if (dependency.scripts) {
                dependency.scripts.forEach((script)=>copyDep(script, scriptTemplate)
                );
            }
            if (dependency.stylesheets) {
                dependency.stylesheets.forEach((stylesheet)=>{
                    copyDep(stylesheet, stylesheetTempate);
                });
            }
            if (dependency.links) {
                dependency.links.forEach((link1)=>{
                    if (!link1.type) {
                        link1.type = "";
                    }
                    lines13.push(rawLinkTemplate(link1));
                });
            }
            if (dependency.resources) {
                dependency.resources.forEach((resource)=>copyDep(resource)
                );
            }
            copiedDependencies.push(dependency.name);
        }
        delete extras.html?.[kDependencies];
        const dependenciesHead = temp.createFile({
            prefix: "dependencies",
            suffix: ".html"
        });
        Deno.writeTextFileSync(dependenciesHead, lines13.join("\n"));
        extras[kIncludeInHeader] = [
            dependenciesHead
        ].concat(extras[kIncludeInHeader] || []);
    }
    return extras;
}
async function ojsCompile(options) {
    const { markdown , project , ojsBlockLineNumbers  } = options;
    if (!isJavascriptCompatible(options.format)) {
        return {
            markdown: markdown.value
        };
    }
    const languages = languagesInMarkdown(markdown.value);
    if (!languages.has("ojs") && !languages.has("dot")) {
        return {
            markdown: markdown.value
        };
    }
    const projDir = project?.dir;
    const selfContained = options.format.pandoc?.[kSelfContained] ?? false;
    const isHtmlMarkdown = isMarkdownOutput(options.format.pandoc, [
        "gfm",
        "commonmark", 
    ]);
    const output = await breakQuartoMd(markdown, true);
    let ojsCellID = 0;
    let ojsBlockIndex = 0;
    const userIds = new Set();
    const scriptContents = [];
    const ojsRuntimeDir = resolve2(dirname2(options.source), options.libDir + "/ojs");
    const docDir = dirname2(options.source);
    const rootDir = projDir ?? "./";
    const runtimeToDoc = relative2(ojsRuntimeDir, docDir);
    const runtimeToRoot = relative2(ojsRuntimeDir, rootDir);
    const docToRoot = relative2(docDir, rootDir);
    scriptContents.push(`window._ojs.paths.runtimeToDoc = "${runtimeToDoc}";`);
    scriptContents.push(`window._ojs.paths.runtimeToRoot = "${runtimeToRoot}";`);
    scriptContents.push(`window._ojs.paths.docToRoot = "${docToRoot}";`);
    scriptContents.push(`window._ojs.selfContained = ${selfContained};`);
    const moduleContents = [];
    function interpret(jsSrc, inline, lenient) {
        const inlineStr = inline ? "inline-" : "";
        const methodName = lenient ? "interpretLenient" : "interpret";
        moduleContents.push({
            methodName,
            cellName: `ojs-${inlineStr}cell-${ojsCellID}`,
            inline,
            source: jsSrc.value
        });
    }
    const ls = [];
    const resourceFiles = [];
    const pageResources = [];
    const ojsViews = new Set();
    const ojsIdentifiers = new Set();
    for (const cell1 of output.cells){
        const errorVal = (cell1.options?.[kError] ?? options.format.execute?.[kError]) ?? false;
        const handleOJSCell = async (cell, mdClassList)=>{
            const cellSrcStr = cell.source;
            const userCellId = ()=>{
                const chooseId = (label)=>{
                    const htmlLabel = asHtmlId(label);
                    if (userIds.has(htmlLabel)) {
                        throw new Error(`FATAL: duplicate label ${htmlLabel}`);
                    } else {
                        userIds.add(htmlLabel);
                        return htmlLabel;
                    }
                };
                if (cell.options?.label) {
                    return chooseId(cell.options.label);
                } else if (cell.options?.[kCellLstLabel]) {
                    return chooseId(cell.options[kCellLstLabel]);
                } else {
                    return undefined;
                }
            };
            const bumpOjsCellIdString = ()=>{
                ojsCellID += 1;
                return `ojs-cell-${ojsCellID}`;
            };
            const ojsId = bumpOjsCellIdString();
            const userId = userCellId();
            const attrs = [];
            const hasFigureLabel = ()=>{
                if (!cell.options?.label) {
                    return false;
                }
                return cell.options.label.startsWith("fig-");
            };
            const hasFigureCaption = ()=>{
                return cell.options?.[kCellFigCap];
            };
            const hasFigureSubCaptions = ()=>{
                return cell.options?.[kCellFigSubCap];
            };
            const cellStartingLoc = ojsBlockLineNumbers[ojsBlockIndex++] || 0;
            if (cellStartingLoc === 0) {
                warning("OJS block count mismatch. Line number reporting is likely to be wrong");
            }
            const handleError = (err, cellSrc)=>{
                const div = pandocDiv({
                    classes: [
                        "quarto-ojs-syntax-error"
                    ]
                });
                const msg = String(err).split("\n")[0].trim().replace(/ *\(\d+:\d+\)$/, "");
                ojsParseError(err, cellSrc);
                const preDiv = pandocBlock("````")({
                    classes: [
                        "numberLines",
                        "java"
                    ],
                    attrs: [
                        `startFrom="${cellStartingLoc - 1}"`,
                        `syntax-error-position="${err.pos}"`,
                        `source-offset="${cell.sourceOffset}"`, 
                    ]
                });
                preDiv.push(pandocRawStr(cell.sourceVerbatim.value));
                div.push(preDiv);
                const errMsgDiv = pandocDiv({
                    classes: [
                        "cell-output-error"
                    ]
                });
                const calloutDiv = pandocDiv({
                    classes: [
                        "callout-important"
                    ]
                });
                const [_heading, fullMsg] = msg.split(": ");
                calloutDiv.push(pandocRawStr(`#### OJS Syntax Error (line ${err.loc.line + cellStartingLoc + cell.sourceStartLine - 1}, column ${err.loc.column + 1})`));
                calloutDiv.push(pandocRawStr(`${fullMsg}`));
                errMsgDiv.push(calloutDiv);
                div.push(errMsgDiv);
                div.emit(ls);
            };
            let nCells = 0;
            const parsedCells = [];
            try {
                const parse21 = parseModule(cellSrcStr.value);
                let info7 = [];
                const flushSeqSrc = ()=>{
                    parsedCells.push({
                        info: info7
                    });
                    for(let i = 1; i < info7.length; ++i){
                        parsedCells.push({
                            info: []
                        });
                    }
                    info7 = [];
                };
                ojsSimpleWalker(parse21, {
                    Cell (node) {
                        if (node.id && node.id.type === "ViewExpression") {
                            ojsViews.add(node.id.id.name);
                        } else if (node.id && node.id.type === "Identifier") {
                            ojsIdentifiers.add(node.id.name);
                        }
                        if (node.id === null && node.body.type !== "ImportDeclaration") {
                            info7.push({
                                start: node.start,
                                end: node.end,
                                cellType: "expression"
                            });
                            flushSeqSrc();
                        } else {
                            info7.push({
                                start: node.start,
                                end: node.end,
                                cellType: "declaration"
                            });
                        }
                    }
                });
                nCells = parse21.cells.length;
                if (info7.length > 0) {
                    flushSeqSrc();
                }
            } catch (e) {
                if (e instanceof SyntaxError) {
                    handleError(e, cellSrcStr);
                    return;
                } else {
                    logError(e);
                    throw new Error();
                }
            }
            pageResources.push(...await extractResourceDescriptionsFromOJSChunk(cellSrcStr, dirname2(options.source), projDir));
            const hasManyRowsCols = ()=>{
                const cols = cell.options?.[kLayoutNcol];
                const rows = cell.options?.[kLayoutNrow];
                return Number(cols) && Number(cols) > 1 || Number(rows) && Number(rows) > 1 || nCells > 1;
            };
            const nCol = ()=>{
                const col = cell.options?.[kLayoutNcol];
                if (!col) {
                    return 1;
                }
                return Number(col);
            };
            const nRow = ()=>{
                const row = cell.options?.[kLayoutNrow];
                if (!row) {
                    return Math.ceil(nCells / nCol());
                }
                return Number(row);
            };
            const hasSubFigures = ()=>{
                return hasFigureSubCaptions() || hasManyRowsCols() && nRow() * nCol() > 1;
            };
            const idPlacement = ()=>{
                if (hasSubFigures() || cell.options?.[kCellLstLabel]) {
                    return "outer";
                } else {
                    return "inner";
                }
            };
            const keysToNotSerialize = new Set([
                kEcho,
                kCellLabel,
                kCellFigCap,
                kCellFigSubCap,
                kCellFigScap,
                kCapLoc,
                kFigCapLoc,
                kTblCapLoc,
                kCellFigColumn,
                kCellTblColumn,
                kCellFigLink,
                kCellFigAlign,
                kCellFigEnv,
                kCellFigPos,
                kCellFigAlt,
                kOutput,
                kCellLstCap,
                kCellLstLabel,
                kCodeFold,
                kCodeLineNumbers,
                kCodeSummary,
                kCodeOverflow,
                kCellClasses,
                kCellPanel,
                kCellColumn,
                "include.hidden",
                "source.hidden",
                "plot.hidden",
                "output.hidden",
                "echo.hidden", 
            ]);
            for (const [key, value] of Object.entries(cell.options || {})){
                if (!keysToNotSerialize.has(key)) {
                    const t = typeof value;
                    if (t === "object") {
                        attrs.push(`${key}="${JSON.stringify(value)}"`);
                    } else if (t === "string") {
                        attrs.push(`${key}=${JSON.stringify(value)}`);
                    } else if (t === "number") {
                        attrs.push(`${key}="${value}"`);
                    } else if (t === "boolean") {
                        attrs.push(`${key}=${value}`);
                    } else {
                        throw new Error(`Can't serialize yaml metadata value of type ${t}`);
                    }
                }
            }
            const outputVal = (cell.options?.[kOutput] ?? options.format.execute[kOutput]) ?? true;
            if (outputVal === "all") {
                attrs.push(`output="all"`);
            }
            if (cell.options?.[kCellLstCap]) {
                attrs.push(`caption="${cell.options?.[kCellLstCap]}"`);
            }
            const classes = cell.options?.classes || [];
            if (typeof cell.options?.panel === "string") {
                classes.push(`panel-${cell.options?.panel}`);
            }
            if (typeof cell.options?.column === "string") {
                classes.push(`column-${cell.options?.column}`);
            }
            if (typeof cell.options?.[kCapLoc] === "string") {
                classes.push(`caption-${cell.options?.[kCapLoc]}`);
            }
            if (typeof cell.options?.[kFigCapLoc] === "string") {
                classes.push(`fig-cap-location-${cell.options?.[kFigCapLoc]}`);
            }
            if (typeof cell.options?.[kTblCapLoc] === "string") {
                classes.push(`tbl-cap-location-${cell.options?.[kTblCapLoc]}`);
            }
            if (typeof cell.options?.[kCellFigColumn] === "string") {
                classes.push(`fig-caption-${cell.options?.[kCellFigColumn]}`);
            }
            if (typeof cell.options?.[kCellTblColumn] === "string") {
                classes.push(`fig-caption-${cell.options?.[kCellTblColumn]}`);
            }
            const evalVal = (cell.options?.[kEval] ?? options.format.execute[kEval]) ?? true;
            const echoVal = (cell.options?.[kEcho] ?? options.format.execute[kEcho]) ?? true;
            const div1 = pandocDiv({
                id: idPlacement() === "outer" ? userId : undefined,
                classes: [
                    "cell",
                    ...classes, 
                ],
                attrs
            });
            const includeVal = (cell.options?.[kInclude] ?? options.format.execute[kInclude]) ?? true;
            if (hasFigureCaption() && !hasFigureLabel()) {
                throw new Error("Cannot have figure caption without figure label");
            }
            if (hasFigureSubCaptions() && !hasFigureLabel()) {
                throw new Error("Cannot have figure subcaptions without figure caption");
            }
            const srcClasses = mdClassList ?? [
                "js",
                "cell-code"
            ];
            const srcAttrs = [];
            if (!echoVal) {
                srcClasses.push("hidden");
            }
            if (cell.options?.[kCodeOverflow] === "wrap") {
                srcClasses.push("code-overflow-wrap");
            } else if (cell.options?.[kCodeOverflow] === "scroll") {
                srcClasses.push("code-overflow-scroll");
            }
            if (asUndefined(options.format.render?.[kCodeFold], "none") ?? cell.options?.[kCodeFold]) {
                srcAttrs.push(`${kCodeFold}="${cell.options?.[kCodeFold]}"`);
            }
            if (cell.options?.[kCodeLineNumbers]) {
                srcAttrs.push(`${kCodeLineNumbers}="${cell.options?.[kCodeLineNumbers]}"`);
            }
            const srcConfig = {
                classes: srcClasses.slice(),
                attrs: srcAttrs.slice()
            };
            if (evalVal) {
                interpret(cell.source, false, errorVal);
            }
            const outputCellClasses = [
                "cell-output-display"
            ];
            if (!outputVal || !includeVal) {
                outputCellClasses.push("hidden");
            }
            if (echoVal === "fenced") {
                const ourAttrs = srcConfig.attrs.slice();
                const ourClasses = srcConfig.classes.filter((d)=>d !== "js"
                );
                ourClasses.push("java");
                ourAttrs.push(`startFrom="${cellStartingLoc - 1}"`, `source-offset="${cell.sourceOffset}"`);
                const srcDiv = pandocBlock("````")({
                    classes: ourClasses,
                    attrs: ourAttrs
                });
                srcDiv.push(pandocRawStr(cell.sourceVerbatim.value));
                div1.push(srcDiv);
            }
            const shouldEmitSource = echoVal !== "fenced" && !(echoVal === false && isHtmlMarkdown);
            const makeSubFigures = (specs)=>{
                let subfigIx = 1;
                const cellInfo = [].concat(...parsedCells.map((n13)=>n13.info
                ));
                for (const spec of specs){
                    const outputDiv = pandocDiv({
                        classes: outputCellClasses
                    });
                    const outputInnerDiv = pandocDiv({
                        id: userId && `${userId}-${subfigIx}`
                    });
                    const innerInfo = parsedCells[subfigIx - 1].info;
                    const ojsDiv = pandocDiv({
                        id: `${ojsId}-${subfigIx}`,
                        attrs: [
                            `nodetype="${cellInfo[subfigIx - 1].cellType}"`
                        ]
                    });
                    if (shouldEmitSource && innerInfo.length > 0 && srcConfig !== undefined) {
                        const ourAttrs = srcConfig.attrs.slice();
                        const linesSkipped = cellSrcStr.value.substring(0, innerInfo[0].start).split("\n").length;
                        ourAttrs.push(`startFrom="${cellStartingLoc + cell.sourceStartLine - 1 + linesSkipped}"`);
                        ourAttrs.push(`source-offset="-${innerInfo[0].start}"`);
                        const srcDiv = pandocCode({
                            attrs: ourAttrs,
                            classes: srcConfig.classes
                        });
                        srcDiv.push(pandocRawStr(cellSrcStr.value.substring(innerInfo[0].start, innerInfo[innerInfo.length - 1].end)));
                        div1.push(srcDiv);
                    }
                    subfigIx++;
                    outputDiv.push(outputInnerDiv);
                    outputInnerDiv.push(ojsDiv);
                    if (spec.caption) {
                        outputInnerDiv.push(pandocRawStr(spec.caption));
                    }
                    div1.push(outputDiv);
                }
            };
            if (!hasFigureSubCaptions() && hasManyRowsCols()) {
                const cellCount = Math.max(nRow() * nCol(), nCells, 1);
                const specs = [];
                for(let i = 0; i < cellCount; ++i){
                    specs.push({
                        caption: ""
                    });
                }
                makeSubFigures(specs);
                if (cell.options?.[kCellFigCap]) {
                    div1.push(pandocRawStr(cell.options[kCellFigCap]));
                }
            } else if (hasFigureSubCaptions()) {
                let subCap = cell.options?.[kCellFigSubCap];
                if (subCap === true) {
                    subCap = [
                        ""
                    ];
                }
                if (!Array.isArray(subCap)) {
                    subCap = [
                        subCap
                    ];
                }
                if (hasManyRowsCols() && subCap.length !== nRow() * nCol()) {
                    throw new Error("Cannot have subcaptions and multi-row/col layout with mismatched number of cells");
                }
                const specs = subCap.map((caption)=>({
                        caption
                    })
                );
                makeSubFigures(specs);
                if (cell.options?.[kCellFigCap]) {
                    div1.push(pandocRawStr(cell.options[kCellFigCap]));
                }
            } else {
                const innerInfo = parsedCells[0].info;
                if (innerInfo.length > 0 && srcConfig !== undefined) {
                    const ourAttrs = srcConfig.attrs.slice();
                    const linesSkipped = cellSrcStr.value.substring(0, innerInfo[0].start).split("\n").length;
                    ourAttrs.push(`startFrom="${cellStartingLoc + cell.sourceStartLine - 1 + linesSkipped}"`);
                    ourAttrs.push(`source-offset="-${innerInfo[0].start}"`);
                    if (shouldEmitSource) {
                        const srcDiv = pandocCode({
                            attrs: ourAttrs,
                            classes: srcConfig.classes
                        });
                        srcDiv.push(pandocRawStr(cellSrcStr.value.substring(innerInfo[0].start, innerInfo[0].end)));
                        div1.push(srcDiv);
                    }
                }
                const outputDiv = pandocDiv({
                    id: idPlacement() === "inner" ? userId : undefined,
                    classes: outputCellClasses
                });
                div1.push(outputDiv);
                outputDiv.push(pandocDiv({
                    id: ojsId,
                    attrs: [
                        `nodetype="${innerInfo[0].cellType}"`
                    ]
                }));
                if (cell.options?.[kCellFigCap]) {
                    outputDiv.push(pandocRawStr(cell.options[kCellFigCap]));
                }
            }
            div1.emit(ls);
        };
        if (cell1.cell_type === "raw" || cell1.cell_type === "markdown" || cell1.cell_type === "math") {
            ls.push(cell1.source.value);
        } else if (cell1.cell_type?.language === "dot") {
            const newCell = {
                ...cell1,
                "cell_type": {
                    language: "ojs"
                },
                source: mappedString(cell1.source, [
                    "dot`\n",
                    {
                        start: 0,
                        end: cell1.source.value.length
                    },
                    "\n`"
                ])
            };
            await handleOJSCell(newCell, [
                "dot",
                "cell-code"
            ]);
        } else if (cell1.cell_type?.language === "ojs") {
            await handleOJSCell(cell1);
        } else {
            ls.push(`\n\`\`\`{${cell1.cell_type.language}}`);
            ls.push(cell1.source.value);
            ls.push("```");
        }
    }
    if (selfContained) {
        const selfContainedPageResources = await makeSelfContainedResources(pageResources, docDir);
        const resolver = JSON.stringify(Object.fromEntries(Array.from(selfContainedPageResources)));
        scriptContents.unshift(`window._ojs.runtime.setLocalResolver(${resolver});`);
    } else {
        for (const resource of uniqueResources(pageResources)){
            resourceFiles.push(resource.filename);
        }
    }
    const serverMetadata = options.format.metadata?.server;
    const normalizeMetadata = (key, def1)=>{
        if (!serverMetadata || serverMetadata["type"] !== "shiny" || !serverMetadata[key]) {
            return def1;
        }
        if (typeof serverMetadata[key] === "string") {
            return [
                serverMetadata[key]
            ];
        } else {
            return serverMetadata[key];
        }
    };
    const shinyInputMetadata = normalizeMetadata("ojs-export", [
        "viewof"
    ]);
    const shinyOutputMetadata = normalizeMetadata("ojs-import", []);
    const shinyInputs = new Set();
    const shinyInputExcludes = new Set();
    if (serverMetadata?.["ojs-exports"]) {
        throw new Error("Document metadata contains server.ojs-exports; did you mean 'ojs-export' instead?");
    }
    if (serverMetadata?.["ojs-imports"]) {
        throw new Error("Document metadata contains server.ojs-imports; did you mean 'ojs-import' instead?");
    }
    let importAllViews = false;
    let importEverything = false;
    for (const shinyInput of shinyInputMetadata){
        if (shinyInput === "viewof") {
            importAllViews = true;
        } else if (shinyInput === "all") {
            importEverything = true;
        } else if (shinyInput.startsWith("~")) {
            shinyInputExcludes.add(shinyInput.slice(1));
        } else {
            shinyInputs.add(shinyInput);
        }
    }
    const resultSet = new Set();
    if (importEverything) {
        for (const el of ojsViews){
            resultSet.add(el);
        }
        for (const el4 of ojsIdentifiers){
            resultSet.add(el4);
        }
    }
    if (importAllViews) {
        for (const el of ojsViews){
            resultSet.add(el);
        }
    }
    for (const el of shinyInputs){
        resultSet.add(el);
    }
    for (const el1 of shinyInputExcludes){
        resultSet.delete(el1);
    }
    for (const el2 of resultSet){
        moduleContents.push({
            methodName: "interpretQuiet",
            source: `shinyInput('${el2}')`
        });
    }
    for (const el3 of shinyOutputMetadata){
        moduleContents.push({
            methodName: "interpretQuiet",
            source: `${el3} = shinyOutput('${el3}')`
        });
    }
    scriptContents.push("window._ojs.runtime.interpretFromScriptTags();");
    const afterBody = [
        `<script type="ojs-module-contents">`,
        JSON.stringify({
            contents: moduleContents
        }),
        `</script>`,
        `<script type="module">`,
        ...scriptContents,
        `</script>`, 
    ].join("\n");
    const includeAfterBodyFile = options.temp.createFile();
    Deno.writeTextFileSync(includeAfterBodyFile, afterBody);
    const extras = resolveDependencies({
        html: {
            [kDependencies]: [
                ojsFormatDependency(selfContained)
            ]
        }
    }, dirname2(options.source), options.libDir, options.temp);
    const ojsBundleTempFiles = [];
    if (selfContained) {
        const ojsBundleFilename = join3(quartoConfig.sharePath(), "formats/html/ojs/esbuild-bundle.js");
        const ojsBundle = [
            `<script type="module">`,
            Deno.readTextFileSync(ojsBundleFilename),
            `</script>`, 
        ];
        const filename = options.temp.createFile();
        Deno.writeTextFileSync(filename, ojsBundle.join("\n"));
        ojsBundleTempFiles.push(filename);
    }
    const includeInHeader = [
        ...extras?.[kIncludeInHeader] || [],
        ...ojsBundleTempFiles, 
    ];
    return {
        markdown: ls.join("\n"),
        filters: [
            "ojs", 
        ],
        includes: {
            [kIncludeInHeader]: includeInHeader,
            [kIncludeAfterBody]: [
                includeAfterBodyFile
            ]
        },
        resourceFiles
    };
}
async function renderContexts(file, options, forExecute, project) {
    options = cloneDeep1(options);
    const { engine , target  } = await fileExecutionEngineAndTarget(file.path, options.flags?.quiet);
    const formats9 = await resolveFormats(file, target, engine, options, project);
    options = removePandocTo(options);
    let libDir = project?.config?.project[kProjectLibDir];
    if (project && libDir) {
        libDir = relative2(dirname2(file.path), join3(project.dir, libDir));
    } else {
        libDir = filesDirLibDir(file.path);
    }
    const contexts = {};
    Object.keys(formats9).forEach((format137)=>{
        contexts[format137] = {
            target,
            options,
            engine,
            format: formats9[format137],
            project,
            libDir: libDir
        };
        if (!forExecute && engine.executeTargetSkipped) {
            engine.executeTargetSkipped(target, formats9[format137]);
        }
    });
    return contexts;
}
async function renderFormats(file, to = "all", project) {
    const tempContext = createTempContext();
    try {
        const contexts = await renderContexts({
            path: file
        }, {
            temp: tempContext,
            flags: {
                to
            }
        }, false, project);
        const formats10 = {};
        Object.keys(contexts).forEach((formatName)=>{
            const context = contexts[formatName];
            const format138 = context.format;
            delete format138.metadata.format;
            deleteProjectMetadata(format138.metadata);
            if (!format138.pandoc[kOutputFile]) {
                const [_dir, stem] = dirAndStem(file);
                format138.pandoc[kOutputFile] = `${stem}.${format138.render[kOutputExt]}`;
            }
            format138.execute[kEngine] = context.engine.name;
            formats10[formatName] = format138;
        });
        return formats10;
    } finally{
        tempContext.cleanup();
    }
}
async function renderExecute(context, output, options) {
    const { resolveDependencies: resolveDependencies1 = true , alwaysExecute =false  } = options;
    const flags = context.options.flags || {};
    const filesDir = inputFilesDir(context.target.source);
    let projRelativeFilesDir;
    if (context.project) {
        const inputDir = relative2(context.project.dir, dirname2(context.target.source));
        projRelativeFilesDir = join3(inputDir, filesDir);
    }
    const canFreeze = context.engine.canFreeze && context.format.execute[kExecuteEnabled] !== false;
    if (context.project && !alwaysExecute) {
        const thaw = canFreeze && (context.format.execute[kFreeze] || (context.options.useFreezer ? "auto" : false));
        if (thaw) {
            const hidden36 = context.format.execute[kFreeze] === false;
            copyFromProjectFreezer(context.project, projRelativeFilesDir, hidden36);
            const thawedResult = defrostExecuteResult(context.target.source, output, context.options.temp, thaw === true);
            if (thawedResult) {
                const libDir = context.project?.config?.project[kProjectLibDir];
                if (libDir) {
                    copyFromProjectFreezer(context.project, libDir, hidden36);
                }
                removeFreezeResults(join3(context.project.dir, projRelativeFilesDir));
                if (context.engine.executeTargetSkipped) {
                    context.engine.executeTargetSkipped(context.target, context.format);
                }
                return thawedResult;
            }
        }
    }
    const figsDir = join3(filesDir, figuresDir(context.format.pandoc.to));
    if (context.engine.generatesFigures) {
        removeIfExists(figsDir);
    }
    const executeResult = await context.engine.execute({
        target: context.target,
        resourceDir: resourcePath(),
        tempDir: context.options.temp.createDir(),
        dependencies: resolveDependencies1,
        libDir: context.libDir,
        format: context.format,
        cwd: flags.executeDir,
        params: resolveParams(flags.params, flags.paramsFile),
        quiet: flags.quiet
    });
    const keepMd = executionEngineKeepMd(context.target.input);
    if (keepMd && context.format.execute[kKeepMd]) {
        Deno.writeTextFileSync(keepMd, executeResult.markdown);
    }
    if (context.project && canFreeze) {
        const freezeFile = freezeExecuteResult(context.target.source, output, executeResult);
        copyToProjectFreezer(context.project, projRelativeFilesDir, true, true);
        if (context.format.execute[kFreeze] !== false) {
            copyToProjectFreezer(context.project, projRelativeFilesDir, false, true);
        } else {
            const freezeFigsDir = freezerFigsDir(context.project, projRelativeFilesDir, basename2(figsDir));
            removeIfExists(freezeFigsDir);
            const projRelativeFreezeFile = relative2(context.project.dir, freezeFile);
            const freezerFile = freezerFreezeFile(context.project, projRelativeFreezeFile);
            removeIfExists(freezerFile);
            removeIfEmptyDir(dirname2(freezerFile));
            removeIfEmptyDir(dirname2(freezeFigsDir));
            removeIfEmptyDir(join3(context.project.dir, kProjectFreezeDir));
        }
        removeFreezeResults(join3(context.project.dir, projRelativeFilesDir));
    }
    return executeResult;
}
function removePandocTo(renderOptions) {
    renderOptions = cloneDeep1(renderOptions);
    delete renderOptions.flags?.to;
    if (renderOptions.pandocArgs) {
        renderOptions.pandocArgs = removePandocToArg(renderOptions.pandocArgs);
    }
    return renderOptions;
}
const kRevealOptions = [
    "controls",
    "controlsTutorial",
    "controlsLayout",
    "controlsBackArrows",
    "progress",
    "slideNumber",
    "showSlideNumber",
    "hash",
    "hashOneBasedIndex",
    "respondToHashChanges",
    "history",
    "keyboard",
    "overview",
    "disableLayout",
    "center",
    "touch",
    "loop",
    "rtl",
    "navigationMode",
    "shuffle",
    "fragments",
    "fragmentInURL",
    "embedded",
    "help",
    "pause",
    "showNotes",
    "autoPlayMedia",
    "preloadIframes",
    "autoAnimate",
    "autoAnimateMatcher",
    "autoAnimateEasing",
    "autoAnimateDuration",
    "autoAnimateUnmatched",
    "autoAnimateStyles",
    "autoSlide",
    "autoSlideStoppable",
    "autoSlideMethod",
    "defaultTiming",
    "mouseWheel",
    "display",
    "hideInactiveCursor",
    "hideCursorTime",
    "previewLinks",
    "transition",
    "transitionSpeed",
    "backgroundTransition",
    "viewDistance",
    "mobileViewDistance",
    "parallaxBackgroundImage",
    "parallaxBackgroundSize",
    "parallaxBackgroundHorizontal",
    "parallaxBackgroundVertical",
    "width",
    "height",
    "margin",
    "minScale",
    "maxScale",
    "mathjax",
    "pdfSeparateFragments",
    "pdfPageHeightOffset", 
];
const kRevealKebabOptions = optionsToKebab(kRevealOptions);
const kRevealJsUrl = "revealjs-url";
async function revealTheme(format139, input, libDir, temp) {
    const metadata = {};
    const revealDir = join3(libDir, "revealjs");
    const revealJsUrl = format139.metadata[kRevealJsUrl];
    if (revealJsUrl && !isFileRef(revealJsUrl)) {
        throw new Error("Invalid revealjs-url: " + revealJsUrl + " (remote urls are not supported)");
    }
    const revealUrl = pathWithForwardSlashes(revealDir);
    metadata[kRevealJsUrl] = revealUrl;
    const revealSrcDir = revealJsUrl || formatResourcePath("revealjs", "reveal");
    const revealDestDir = join3(dirname2(input), libDir, "revealjs");
    [
        "dist",
        "plugin"
    ].forEach((dir)=>{
        copyMinimal(join3(revealSrcDir, dir), join3(revealDestDir, dir));
    });
    const themeConfig = format139.metadata?.[kTheme] || "default";
    const themeLayers = (Array.isArray(themeConfig) ? themeConfig : [
        themeConfig
    ]).map((theme)=>{
        const themePath = join3(relative2(Deno.cwd(), dirname2(input)), theme);
        if (existsSync(themePath)) {
            return themeLayer(themePath);
        } else {
            if (theme === "white") {
                theme = "default";
            } else if (theme === "black") {
                theme = "dark";
            }
            theme = formatResourcePath("revealjs", join3("themes", `${theme}.scss`));
            return themeLayer(theme);
        }
    });
    const yamlLayer = {
        uses: "",
        defaults: pandocVariablesToThemeScss(format139.metadata, true),
        functions: "",
        mixins: "",
        rules: ""
    };
    const cssThemeDir = join3(revealSrcDir, "css", "theme");
    const loadPaths = [
        join3(cssThemeDir, "source"),
        join3(cssThemeDir, "template"), 
    ];
    const bundleLayers = {
        key: "reveal-theme",
        user: mergeLayers(yamlLayer, ...themeLayers),
        quarto: mergeLayers(quartoBaseLayer(format139, true, true, false), quartoLayer()),
        framework: revealFrameworkLayer(revealSrcDir),
        loadPaths
    };
    const css = await compileSass([
        bundleLayers
    ], temp);
    Deno.copyFileSync(css, join3(revealDestDir, "dist", "theme", "quarto.css"));
    metadata[kTheme] = "quarto";
    const highlightingMode = cssHasDarkModeSentinel(Deno.readTextFileSync(css)) ? "dark" : "light";
    return {
        revealUrl,
        revealDestDir,
        metadata,
        [kTextHighlightingMode]: highlightingMode
    };
}
function renderResultFinalOutput(renderResults, relativeToInputDir) {
    let result = renderResults.files.find((file)=>{
        return !file.supplemental;
    });
    if (!result) {
        return undefined;
    }
    for (const fileResult of renderResults.files){
        if (fileResult.file === "index.html" && !fileResult.supplemental) {
            result = fileResult;
            break;
        }
    }
    let finalInput = result.input;
    let finalOutput = result.file;
    if (renderResults.baseDir) {
        finalInput = join3(renderResults.baseDir, finalInput);
        if (renderResults.outputDir) {
            finalOutput = join3(renderResults.baseDir, renderResults.outputDir, finalOutput);
        } else {
            finalOutput = join3(renderResults.baseDir, finalOutput);
        }
    } else {
        finalOutput = join3(dirname2(finalInput), finalOutput);
    }
    if (!existsSync(finalOutput)) {
        return undefined;
    }
    if (relativeToInputDir) {
        const inputRealPath = Deno.realPathSync(relativeToInputDir);
        const outputRealPath = Deno.realPathSync(finalOutput);
        return relative2(inputRealPath, outputRealPath);
    } else {
        return finalOutput;
    }
}
function renderResultUrlPath(renderResult) {
    if (renderResult.baseDir && renderResult.outputDir) {
        const finalOutput = renderResultFinalOutput(renderResult);
        if (finalOutput) {
            const targetPath = pathWithForwardSlashes(relative2(join3(renderResult.baseDir, renderResult.outputDir), finalOutput));
            return targetPath;
        }
    }
    return undefined;
}
function defaultPandocRenderer(_options, _project) {
    const renderedFiles = [];
    return {
        onBeforeExecute: (_format)=>({})
        ,
        onRender: async (_format, executedFile, quiet)=>{
            renderedFiles.push(await renderPandoc(executedFile, quiet));
        },
        onComplete: async ()=>{
            return {
                files: await Promise.resolve(renderedFiles)
            };
        }
    };
}
function mergePandocIncludes(format140, pandocIncludes) {
    return mergeConfigs(format140, pandocIncludes);
}
const kStandaloneExtensionNames = [
    "pdf",
    "epub",
    "fb2",
    "docx",
    "rtf",
    "pptx",
    "odt",
    "ipynb", 
];
const kStandaloneExtensions = kStandaloneExtensionNames.map((name136)=>`.${name136}`
);
function isSelfContained(flags, format141) {
    return !!(flags[kSelfContained] || format141.pandoc[kSelfContained]);
}
const kRevealJsConfig = "revealjs-config";
const kSlideLogo = "logo";
const kSlideFooter = "footer";
const kHashType = "hash-type";
const kScrollable = "scrollable";
const kSmaller = "smaller";
const kCenterTitleSlide = "center-title-slide";
const kControlsAuto = "controlsAuto";
const kPreviewLinksAuto = "previewLinksAuto";
const kPdfSeparateFragments = "pdfSeparateFragments";
const kAutoAnimateEasing = "autoAnimateEasing";
const kAutoAnimateDuration = "autoAnimateDuration";
const kAutoAnimateUnmatched = "autoAnimateUnmatched";
const kAutoStretch = "auto-stretch";
function optionsToKebab(options1) {
    return options1.reduce((options, option)=>{
        const kebab = camelToKebab(option);
        if (kebab !== option) {
            options.push(kebab);
        }
        return options;
    }, []);
}
function revealResolveFormat(format142) {
    format142.metadata = revealMetadataFilter(format142.metadata);
    if (format142.metadata["navigationMode"] === "vertical") {
        format142.metadata["navigationMode"] = "default";
    }
}
function injectRevealConfig(config, template10) {
    const configJs = [];
    Object.keys(config).forEach((key)=>{
        configJs.push(`'${key}': ${JSON.stringify(config[key])}`);
    });
    if (configJs.length > 0) {
        const kRevealInitialize = "Reveal.initialize({";
        template10 = template10.replace(kRevealInitialize, kRevealInitialize + "\n" + configJs.join(",\n") + ",\n");
    }
    return template10;
}
function revealMetadataFilter(metadata, kebabOptions = kRevealKebabOptions) {
    const filtered = {};
    Object.keys(metadata).forEach((key)=>{
        const value = metadata[key];
        if (kebabOptions.includes(key)) {
            filtered[kebabToCamel(key)] = value;
        } else {
            filtered[key] = value;
        }
    });
    return filtered;
}
const kRevealjsPlugins = "revealjs-plugins";
const kRevealSlideTone = "slide-tone";
const kRevealMenu = "menu";
const kRevealChalkboard = "chalkboard";
const kRevealPluginOptions = [
    "side",
    "width",
    "numbers",
    "titleSelector",
    "useTextContentForMissingTitles",
    "hideMissingTitles",
    "markers",
    "custom",
    "themes",
    "themesPath",
    "transitions",
    "openButton",
    "openSlideNumber",
    "keyboard",
    "sticky",
    "autoOpen",
    "delayInit",
    "openOnInit",
    "loadIcons",
    "boardmarkerWidth",
    "chalkWidth",
    "chalkEffect",
    "storage",
    "src",
    "readOnly",
    "transition",
    "theme",
    "background",
    "grid",
    "eraser",
    "boardmarkers",
    "chalks",
    "rememberColor",
    "pdfExportShortcut", 
];
const kRevealPluginKebabOptions = optionsToKebab(kRevealPluginOptions);
async function revealPluginExtras(format143, flags, temp, revealUrl, revealDestDir) {
    const pluginsDestDir = join3(revealDestDir, "plugin");
    const register1 = [];
    const scripts = [];
    const stylesheets = [];
    const config = {};
    const metadata = [];
    const dependencies = [];
    const pluginBundles = [
        {
            plugin: formatResourcePath("revealjs", join3("plugins", "line-highlight"))
        },
        {
            plugin: formatResourcePath("revealjs", join3("plugins", "pdfexport"))
        }, 
    ];
    const menuPlugin = revealMenuPlugin(format143);
    if (menuPlugin) {
        pluginBundles.push(menuPlugin);
    }
    const chalkboardPlugiln = revealChalkboardPlugin(format143);
    if (chalkboardPlugiln) {
        pluginBundles.push(chalkboardPlugiln);
    }
    const tonePlugin = revealTonePlugin(format143);
    if (tonePlugin) {
        dependencies.push(toneDependency());
        pluginBundles.push(tonePlugin);
    }
    const multiplexPlugin = revealMultiplexPlugin(format143);
    if (multiplexPlugin) {
        pluginBundles.push(multiplexPlugin);
    }
    if (Array.isArray(format143.metadata[kRevealjsPlugins])) {
        pluginBundles.push(...format143.metadata[kRevealjsPlugins]);
    }
    pluginBundles.push({
        plugin: formatResourcePath("revealjs", join3("plugins", "support"))
    });
    for (let bundle of pluginBundles){
        if (typeof bundle === "string") {
            bundle = {
                plugin: bundle
            };
        }
        const plugin = await pluginFromBundle(bundle);
        if (isSelfContained(flags, format143)) {
            if (plugin[kSelfContained] === false) {
                throw new Error("Reveal plugin '" + plugin.name + " is not compatible with self-contained output");
            }
        }
        if (plugin.register !== false) {
            register1.push(plugin.name);
        }
        const pluginUrl = pathWithForwardSlashes(join3(revealUrl, "plugin", camelToKebab(plugin.name)));
        const pluginDir = join3(pluginsDestDir, camelToKebab(plugin.name));
        copyMinimal(bundle.plugin, pluginDir);
        if (plugin.script) {
            for (const script of plugin.script){
                script.path = pathWithForwardSlashes(join3(pluginUrl, script.path));
                scripts.push(script);
            }
        }
        if (plugin.stylesheet) {
            for (const stylesheet of plugin.stylesheet){
                const pluginStylesheet = pathWithForwardSlashes(join3(pluginUrl, stylesheet));
                stylesheets.push(pathWithForwardSlashes(pluginStylesheet));
            }
        }
        if (plugin.config) {
            for (const key of Object.keys(plugin.config)){
                const kebabKey = camelToKebab(key);
                if (typeof plugin.config[key] === "object") {
                    config[key] = plugin.config[key];
                    if (typeof format143.metadata[kebabKey] === "object") {
                        config[key] = mergeConfigs(revealMetadataFilter(config[key], kRevealPluginKebabOptions), revealMetadataFilter(format143.metadata[kebabKey], kRevealPluginKebabOptions));
                    }
                } else {
                    config[key] = plugin.config[key];
                    if (format143.metadata[key] !== undefined) {
                        config[key] = format143.metadata[key];
                    }
                }
            }
        }
        if (plugin.metadata) {
            metadata.push(...plugin.metadata);
        }
    }
    const extras = {
        [kIncludeInHeader]: [],
        html: {
            [kDependencies]: dependencies,
            [kTemplatePatches]: []
        }
    };
    const linkTags = stylesheets.map((file)=>{
        return `<link href="${file}" rel="stylesheet">`;
    }).join("\n");
    const linkTagsInclude = temp.createFile({
        suffix: ".html"
    });
    Deno.writeTextFileSync(linkTagsInclude, linkTags);
    extras[kIncludeInHeader]?.push(linkTagsInclude);
    extras.html?.[kTemplatePatches]?.push((template11)=>{
        const kRevealJsPlugins = "<!-- reveal.js plugins -->";
        const scriptTags = scripts.map((file)=>{
            const async = file.async ? " async" : "";
            return `  <script src="${file.path}"${async}></script>`;
        }).join("\n");
        template11 = template11.replace(kRevealJsPlugins, kRevealJsPlugins + "\n" + scriptTags);
        if (register1.length > 0) {
            const kRevealPluginArray = "plugins: [";
            template11 = template11.replace(kRevealPluginArray, kRevealPluginArray + register1.join(", ") + ",\n");
        }
        metadata.forEach((option)=>{
            if (format143.metadata[option] !== undefined) {
                config[option] = format143.metadata[option];
            }
        });
        template11 = injectRevealConfig(config, template11);
        return template11;
    });
    return extras;
}
function revealjsFormat() {
    return mergeConfigs(createHtmlPresentationFormat(10, 5), {
        pandoc: {
            [kHtmlMathMethod]: {
                method: "mathjax",
                url: "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML-full"
            },
            [kSlideLevel]: 2
        },
        render: {
            [kCodeLineNumbers]: true
        },
        metadata: {
            [kAutoStretch]: true
        },
        resolveFormat: revealResolveFormat,
        formatPreviewFile: revealMuliplexPreviewFile,
        formatExtras: async (input, flags, format144, libDir, temp, offset)=>{
            const stylesFile = temp.createFile({
                suffix: ".html"
            });
            const styles = renderEjs(formatResourcePath("revealjs", "styles.html"), {
                [kScrollable]: format144.metadata[kScrollable]
            });
            Deno.writeTextFileSync(stylesFile, styles);
            const metadataOverride = {};
            const controlsAuto = typeof format144.metadata["controls"] !== "boolean";
            if (controlsAuto) {
                metadataOverride.controls = false;
            }
            const previewLinksAuto = format144.metadata["previewLinks"] === "auto";
            if (previewLinksAuto) {
                metadataOverride.previewLinks = false;
            }
            const extraConfigPatch = (template12)=>{
                const extraConfig = {
                    [kControlsAuto]: controlsAuto,
                    [kPreviewLinksAuto]: previewLinksAuto,
                    [kSmaller]: !!format144.metadata[kSmaller],
                    [kPdfSeparateFragments]: !!format144.metadata[kPdfSeparateFragments],
                    [kAutoAnimateEasing]: format144.metadata[kAutoAnimateEasing] || "ease",
                    [kAutoAnimateDuration]: format144.metadata[kAutoAnimateDuration] || 1,
                    [kAutoAnimateUnmatched]: format144.metadata[kAutoAnimateUnmatched] !== undefined ? format144.metadata[kAutoAnimateUnmatched] : true
                };
                return injectRevealConfig(extraConfig, template12);
            };
            let extras = mergeConfigs(await htmlFormatExtras(input, offset, format144, temp, {
                tabby: true,
                anchors: false,
                copyCode: true,
                hoverCitations: true,
                hoverFootnotes: true,
                figResponsive: false
            }, {
                theme: "quarto-reveal",
                parent: "section.slide",
                config: {
                    offset: [
                        0,
                        0
                    ],
                    maxWidth: 700
                }
            }, {
                quartoBase: false
            }), {
                args: [],
                pandoc: {},
                metadata: {
                    [kLinkCitations]: true
                },
                metadataOverride,
                [kIncludeInHeader]: [
                    formatResourcePath("html", "styles-callout.html"),
                    stylesFile, 
                ],
                html: {
                    [kTemplatePatches]: [
                        extraConfigPatch,
                        revealRequireJsPatch,
                        (template13)=>{
                            template13 = template13.replace(/(disableLayout: )false/, "$1$disableLayout$");
                            return template13;
                        }, 
                    ],
                    [kHtmlPostprocessors]: [
                        revealHtmlPostprocessor(format144), 
                    ],
                    [kMarkdownAfterBody]: [
                        revealMarkdownAfterBody(format144)
                    ]
                }
            });
            const theme = await revealTheme(format144, input, libDir, temp);
            extras.metadataOverride = {
                ...extras.metadataOverride,
                ...theme.metadata
            };
            extras.html[kTextHighlightingMode] = theme[kTextHighlightingMode];
            const revealPluginExtrasConfig = await revealPluginExtras(format144, flags, temp, theme.revealUrl, theme.revealDestDir);
            extras = mergeConfigs(revealPluginExtrasConfig, extras);
            const multiplexExtras = revealMultiplexExtras(format144);
            if (multiplexExtras) {
                extras = mergeConfigs(extras, multiplexExtras);
            }
            if (format144.metadata[kRevealJsConfig] !== "default") {
                const navigationMode = format144.metadata["navigationMode"];
                const verticalSlides = navigationMode === "default" || navigationMode === "grid";
                if (format144.metadata["slideNumber"] === true) {
                    extras.metadataOverride["slideNumber"] = verticalSlides ? "h.v" : "c/t";
                }
                extras.metadata = {
                    ...extras.metadata,
                    ...revealMetadataFilter({
                        width: 1050,
                        height: 700,
                        margin: 0.1,
                        center: false,
                        navigationMode: "linear",
                        controlsLayout: "edges",
                        controlsTutorial: false,
                        hash: true,
                        history: true,
                        hashOneBasedIndex: false,
                        fragmentInURL: false,
                        transition: "none",
                        backgroundTransition: "none",
                        pdfSeparateFragments: false
                    })
                };
            }
            if (format144.metadata[kHashType] === "number") {
                extras.pandoc = {
                    ...extras.pandoc,
                    from: pandocFormatWith(format144.pandoc[kFrom] || "markdown", "", "-auto_identifiers")
                };
            }
            return extras;
        }
    });
}
function defaultWriterFormat(to) {
    const lookupTo = to.split("+")[0];
    let pandocTo = lookupTo;
    let writerFormat;
    switch(lookupTo){
        case "html":
        case "html4":
        case "html5":
            writerFormat = htmlFormat(7, 5);
            break;
        case "pdf":
            writerFormat = pdfFormat();
            break;
        case "beamer":
            writerFormat = beamerFormat();
            break;
        case "latex":
        case "context":
            writerFormat = latexFormat();
            break;
        case "s5":
        case "dzslides":
        case "slidy":
        case "slideous":
            writerFormat = createHtmlPresentationFormat(9.5, 6.5);
            break;
        case "revealjs":
            writerFormat = revealjsFormat();
            break;
        case "markdown":
        case "markdown_phpextra":
        case "markdown_github":
        case "markdown_mmd":
        case "markdown_strict":
        case "markua":
            writerFormat = markdownFormat();
            pandocTo = to;
            break;
        case "commonmark":
        case "commonmark_x":
            writerFormat = commonmarkFormat(to);
            pandocTo = to;
            break;
        case "gfm":
            writerFormat = gfmFormat();
            pandocTo = to;
            break;
        case "asciidoc":
            writerFormat = plaintextFormat("txt");
            break;
        case "asciidoctor":
            writerFormat = plaintextFormat("adoc");
            break;
        case "docbook":
        case "docbook4":
        case "docbook5":
            writerFormat = plaintextFormat("xml");
            break;
        case "docx":
            writerFormat = docxFormat();
            break;
        case "pptx":
            writerFormat = powerpointFormat();
            break;
        case "odt":
            writerFormat = createWordprocessorFormat("odt");
            break;
        case "opendocument":
            writerFormat = createWordprocessorFormat("xml");
            break;
        case "rtf":
            writerFormat = rtfFormat();
            break;
        case "plain":
            writerFormat = plaintextFormat("txt");
            break;
        case "epub":
        case "epub2":
        case "epub3":
            writerFormat = epubFormat();
            break;
        case "fb2":
            writerFormat = createEbookFormat("fb2");
            break;
        case "zimwiki":
            writerFormat = plaintextFormat("zim");
            break;
        case "jats":
        case "jats_archiving":
        case "jats_articleauthoring":
        case "jats_publishing":
            writerFormat = plaintextFormat("xml");
            break;
        case "ipynb":
            writerFormat = ipynbFormat();
            break;
        case "hugo":
            writerFormat = hugoFormat();
            break;
        default:
            writerFormat = plaintextFormat(to);
    }
    writerFormat.pandoc = writerFormat.pandoc || {};
    if (!writerFormat.pandoc.to) {
        writerFormat.pandoc.to = pandocTo;
    }
    return writerFormat;
}
function filesDirLibDir(input) {
    return join3(inputFilesDir(input), "libs");
}
function renderCleanup(input, output, format145, supporting, keepMd) {
    if (!isAbsolute2(output)) {
        output = join3(dirname2(input), output);
    }
    if (keepMd && !format145.execute[kKeepMd] && keepMd !== output) {
        removeIfExists(keepMd);
    }
    if (!format145.execute[kKeepMd] && !format145.render[kKeepTex] && supporting) {
        if (isHtmlOutput(format145.pandoc)) {
            const libDir = join3(dirname2(input), filesDirLibDir(input));
            if (existsSync(libDir)) {
                supporting.push(Deno.realPathSync(libDir));
            }
        }
        __VIRTUAL_FILE181(supporting).forEach((path92)=>{
            if (existsSync(path92)) {
                Deno.removeSync(path92, {
                    recursive: true
                });
            }
        });
    }
    const filesDir = inputFilesDir(input);
    const figsDir = join3(filesDir, figuresDir(format145.pandoc.to));
    const libDir = filesDirLibDir(input);
    removeIfEmptyDir(figsDir);
    removeIfEmptyDir(libDir);
    removeIfEmptyDir(filesDir);
}
async function renderPandoc(file1, quiet) {
    const { context , recipe , executeResult , resourceFiles  } = file1;
    const format146 = recipe.format;
    if (executeResult.includes) {
        format146.pandoc = mergePandocIncludes(format146.pandoc || {}, executeResult.includes);
    }
    if (executeResult.pandoc) {
        format146.pandoc = mergeConfigs(format146.pandoc || {}, executeResult.pandoc);
    }
    if (executeResult.engineDependencies) {
        for (const engineName of Object.keys(executeResult.engineDependencies)){
            const engine = executionEngine(engineName);
            const dependenciesResult = await engine.dependencies({
                target: context.target,
                format: format146,
                output: recipe.output,
                resourceDir: resourcePath(),
                tempDir: context.options.temp.createDir(),
                libDir: context.libDir,
                dependencies: executeResult.engineDependencies[engineName],
                quiet: context.options.flags?.quiet
            });
            format146.pandoc = mergePandocIncludes(format146.pandoc, dependenciesResult.includes);
        }
    }
    const pandocOptions = {
        markdown: executeResult.markdown,
        source: context.target.source,
        output: recipe.output,
        libDir: context.libDir,
        format: format146,
        project: context.project,
        args: recipe.args,
        temp: context.options.temp,
        metadata: executeResult.metadata,
        quiet,
        flags: context.options.flags
    };
    if (context.project) {
        pandocOptions.offset = projectOffset(context.project, context.target.input);
    }
    const pandocResult = await runPandoc(pandocOptions, executeResult.filters);
    if (!pandocResult) {
        return Promise.reject();
    }
    if (executeResult.postProcess) {
        await context.engine.postprocess({
            engine: context.engine,
            target: context.target,
            format: format146,
            output: recipe.output,
            tempDir: context.options.temp.createDir(),
            preserve: executeResult.preserve,
            quiet: context.options.flags?.quiet
        });
    }
    const canHtmlPostProcess = isHtmlFileOutput(format146.pandoc);
    if (!canHtmlPostProcess && pandocResult.htmlPostprocessors.length > 0) {
        const postProcessorNames = pandocResult.htmlPostprocessors.map((p)=>p.name
        ).join(", ");
        const msg = `Attempt to HTML post process non HTML output using: ${postProcessorNames}`;
        throw new Error(msg);
    }
    const htmlPostProcessors = canHtmlPostProcess ? pandocResult.htmlPostprocessors : [];
    const htmlFinalizers = canHtmlPostProcess ? pandocResult.htmlFinalizers || [] : [];
    const htmlPostProcessResult = await runHtmlPostprocessors(pandocOptions, htmlPostProcessors, htmlFinalizers);
    if (pandocResult.postprocessors) {
        const outputFile = isAbsolute2(pandocOptions.output) ? pandocOptions.output : join3(dirname2(pandocOptions.source), pandocOptions.output);
        for (const postprocessor of pandocResult.postprocessors){
            await postprocessor(outputFile);
        }
    }
    const flags = context.options.flags || {};
    const finalOutput = await recipe.complete(pandocOptions) || recipe.output;
    const selfContained = isSelfContainedOutput(flags, format146, finalOutput);
    let filesDir = inputFilesDir(context.target.source);
    filesDir = existsSync(join3(dirname2(context.target.source), filesDir)) ? filesDir : undefined;
    let supporting = filesDir ? executeResult.supporting : undefined;
    if (filesDir) {
        const filesDirAbsolute = join3(dirname2(context.target.source), filesDir);
        if (existsSync(filesDirAbsolute) && (!supporting || !supporting.includes(filesDirAbsolute))) {
            const filesLibs = join3(dirname2(context.target.source), context.libDir);
            if (existsSync(filesLibs) && (!supporting || !supporting.includes(filesLibs))) {
                supporting = supporting || [];
                supporting.push(filesLibs);
            }
        }
    }
    if (htmlPostProcessResult.supporting && htmlPostProcessResult.supporting.length > 0) {
        supporting = supporting || [];
        supporting.push(...htmlPostProcessResult.supporting);
    }
    renderCleanup(context.target.input, finalOutput, format146, selfContained ? supporting : undefined, executionEngineKeepMd(context.target.input));
    const projectPath = (path93)=>{
        if (context.project) {
            if (isAbsolute2(path93)) {
                return relative2(Deno.realPathSync(context.project.dir), Deno.realPathSync(path93));
            } else {
                return relative2(Deno.realPathSync(context.project.dir), Deno.realPathSync(join3(dirname2(context.target.source), path93)));
            }
        } else {
            return path93;
        }
    };
    return {
        input: projectPath(context.target.source),
        markdown: executeResult.markdown,
        format: format146,
        supporting: supporting ? supporting.filter(existsSync).map((file)=>context.project ? relative2(context.project.dir, file) : file
        ) : undefined,
        file: projectPath(finalOutput),
        resourceFiles: {
            globs: pandocResult.resources,
            files: resourceFiles.concat(htmlPostProcessResult.resources)
        },
        selfContained: selfContained
    };
}
function isSelfContainedOutput(flags, format147, finalOutput) {
    return isSelfContained(flags, format147) || kStandaloneExtensions.includes(extname2(finalOutput));
}
async function resolveFormatsFromMetadata(metadata, includeDir, formats11, flags) {
    const frontMatterSchema = await getFrontMatterSchema();
    const included = await includedMetadata(includeDir, metadata, frontMatterSchema);
    const allMetadata = mergeQuartoConfigs(metadata, included.metadata, flags?.metadata || {});
    await resolveLanguageMetadata(allMetadata, includeDir);
    const baseFormat = metadataAsFormat(allMetadata);
    if (formats11 === undefined) {
        formats11 = formatKeys(allMetadata);
    }
    if (formats11.length === 0) {
        formats11.push(baseFormat.pandoc.to || baseFormat.pandoc.writer || "html");
    }
    const renderFormats1 = [];
    if (flags?.to === undefined || flags?.to === "all") {
        renderFormats1.push(...formats11);
    } else if (flags?.to === "default") {
        renderFormats1.push(formats11[0]);
    } else {
        renderFormats1.push(...flags.to.split(","));
    }
    const resolved = {};
    renderFormats1.forEach((to)=>{
        const format148 = formatFromMetadata(baseFormat, to, flags?.debug);
        const config = mergeFormatMetadata(baseFormat, format148);
        const resolveFormat = defaultWriterFormat(to).resolveFormat;
        if (resolveFormat) {
            resolveFormat(config);
        }
        if (flags?.execute !== undefined) {
            config.execute[kExecuteEnabled] = flags?.execute;
        }
        if (flags?.executeCache !== undefined) {
            config.execute[kCache] = flags?.executeCache;
        }
        if (flags?.executeDaemon !== undefined) {
            config.execute[kExecuteDaemon] = flags.executeDaemon;
        }
        if (flags?.executeDaemonRestart !== undefined) {
            config.execute[kExecuteDaemonRestart] = flags.executeDaemonRestart;
        }
        if (flags?.executeDebug !== undefined) {
            config.execute[kExecuteDebug] = flags.executeDebug;
        }
        resolved[to] = config;
    });
    return resolved;
}
async function bookRenderItems(projectDir, language, config) {
    if (!config) {
        return [];
    }
    let nextNumber = 1;
    const inputs = [];
    const findInputs = async (type, items)=>{
        const throwInputNotFound = (input)=>{
            throw new Error(`Book ${type} '${input}' not found`);
        };
        for (const item of items){
            if (item.contents) {
                inputs.push({
                    type: kBookItemPart,
                    file: item.href,
                    text: item.text
                });
                await findInputs(type, item.contents);
            } else if (item.href) {
                const itemPath = join3(projectDir, item.href);
                if (safeExistsSync(itemPath)) {
                    const engine = fileExecutionEngine(itemPath);
                    if (engine) {
                        let number5;
                        if (type === kBookItemChapter && await inputIsNumbered(projectDir, item.href)) {
                            number5 = nextNumber++;
                        }
                        inputs.push({
                            type,
                            file: item.href,
                            number: number5
                        });
                    }
                } else {
                    throwInputNotFound(item.href);
                }
            } else if (item.text && !item.text.trim().match(/^-+$/)) {
                throwInputNotFound(item.text);
            }
        }
    };
    const findChapters = async (key, delimiter3)=>{
        nextNumber = 1;
        const bookInputs = bookConfig(key, config);
        if (bookInputs) {
            if (delimiter3) {
                inputs.push(delimiter3);
            }
            await findInputs(kBookItemChapter, bookChaptersToSidebarItems(bookInputs).map((item)=>normalizeSidebarItem(projectDir, item)
            ));
        }
    };
    await findChapters(kBookChapters);
    const references = bookConfig("references", config);
    if (references) {
        await findInputs(kBookItemChapter, [
            normalizeSidebarItem(projectDir, references), 
        ]);
    }
    await findChapters(kBookAppendix, {
        type: kBookItemAppendix,
        text: language[kSectionTitleAppendices] + " {.unnumbered}"
    });
    const missing = inputs.filter((input)=>input.file && !existsSync(join3(projectDir, input.file))
    );
    if (missing.length) {
        throw new Error("Book contents file(s) do not exist: " + missing.join(", "));
    }
    const indexPos = inputs.findIndex((input)=>isBookIndexPage(input.file)
    );
    if (indexPos === -1) {
        throw new Error("Book contents must include a home page (e.g. index.md)");
    }
    const index = inputs.splice(indexPos, 1);
    return index.concat(inputs);
}
const kDownloadableItems = {
    "epub": {
        name: "ePub",
        icon: "journal"
    },
    "pdf": {
        name: "PDF",
        icon: "file-pdf"
    },
    "docx": {
        name: "Docx",
        icon: "file-word"
    }
};
function bookChaptersToSidebarItems(chapters) {
    return chapters.map(chapterToSidebarItem);
}
function chapterToSidebarItem(chapter) {
    const item = __VIRTUAL_FILE107(chapter);
    if (item.part) {
        item.section = item.part;
        delete item.part;
    }
    if (item.chapters) {
        item.contents = bookChaptersToSidebarItems(item.chapters);
        delete item.chapters;
    }
    return item;
}
function downloadTools(projectDir, config) {
    const downloadActions = websiteConfigActions("downloads", kBook, config);
    const filteredActions = downloadActions.filter((action)=>{
        const format149 = defaultWriterFormat(action);
        if (format149) {
            return format149.extensions?.book && !isMultiFileBookFormat(format149);
        } else {
            return false;
        }
    });
    const outputStem = bookOutputStem(projectDir, config);
    const downloads = filteredActions.map((action)=>{
        const format150 = defaultWriterFormat(action);
        const downloadItem = kDownloadableItems[action];
        if (downloadItem) {
            return {
                icon: downloadItem.icon,
                text: `Download ${downloadItem.name}`,
                href: `/${outputStem}.${format150.render[kOutputExt]}`
            };
        } else {
            return {
                text: `Download action}`,
                href: `/${outputStem}.${format150.render[kOutputExt]}`
            };
        }
    });
    if (downloads.length === 0) {
        return undefined;
    } else if (downloads.length === 1) {
        return [
            {
                icon: "download",
                ...downloads[0]
            }
        ];
    } else {
        return [
            {
                icon: "download",
                text: "Download",
                menu: downloads
            }
        ];
    }
}
function bookOutputStem(projectDir, config) {
    const outputFile = bookConfig(kBookOutputFile, config) || bookConfig(kTitle, config) || basename2(projectDir);
    return texSafeFilename(config !== undefined ? resolveVariables(outputFile, config) : outputFile);
}
async function mergeExecutedFiles(project, options, files) {
    const context = __VIRTUAL_FILE107(files[0].context);
    context.options = removePandocTo(options);
    const outputStem = bookOutputStem(project.dir, project.config);
    context.format.pandoc[kOutputFile] = `${outputStem}.${context.format.render[kOutputExt]}`;
    const recipe = await outputRecipe(context);
    if (isAbsolute2(recipe.output)) {
        recipe.output = relative2(project.dir, recipe.output);
        recipe.format.pandoc[kOutputFile] = recipe.output;
    }
    const renderItems = bookConfigRenderItems(project.config);
    const markdown1 = renderItems.reduce((markdown, item)=>{
        let itemMarkdown = "";
        if (item.file) {
            const itemInputPath = join3(project.dir, item.file);
            const file1 = files.find((file)=>file.context.target.source === itemInputPath
            );
            if (file1) {
                const partitioned = partitionYamlFrontMatter(file1.executeResult.markdown);
                const yaml = partitioned?.yaml ? readYamlFromMarkdown(partitioned?.yaml) : undefined;
                const frontTitle = frontMatterTitle(yaml);
                const titleMarkdown = frontTitle ? `# ${frontTitle}\n\n` : "";
                itemMarkdown = bookItemMetadata(project, item, file1) + titleMarkdown + file1.executeResult.markdown;
            } else {
                throw new Error("Executed file not found for book item: " + item.file);
            }
        } else if (item.type === kBookItemPart || item.type === kBookItemAppendix) {
            itemMarkdown = bookPartMarkdown(project, item);
        }
        if ((item.type === kBookItemPart || item.type === kBookItemAppendix) && itemMarkdown.length > 0) {
            itemMarkdown = `\n\n::: {.quarto-book-part}\n${itemMarkdown}\n:::\n\n`;
        }
        return markdown + itemMarkdown;
    }, "");
    const supporting1 = files.reduce((supporting, file)=>{
        return __VIRTUAL_FILE181(supporting.concat(file.executeResult.supporting.map((f)=>relative2(project.dir, f)
        )));
    }, []);
    const filters = __VIRTUAL_FILE181(files.flatMap((file)=>file.executeResult.filters
    ));
    const engineDependencies1 = files.reduce((engineDependencies, file)=>{
        const fileEngineDependencies = file.executeResult.engineDependencies;
        if (fileEngineDependencies) {
            for (const engineName of Object.keys(fileEngineDependencies)){
                engineDependencies[engineName] = (engineDependencies[engineName] || []).concat(fileEngineDependencies[engineName]);
            }
        }
        return engineDependencies;
    }, {});
    const preserve1 = files.reduce((preserve, file)=>{
        return {
            ...preserve,
            ...file.executeResult.preserve
        };
    }, {});
    const postProcess1 = files.reduce((postProcess, file)=>{
        return postProcess || !!file.executeResult.postProcess;
    }, false);
    const resourceFiles = __VIRTUAL_FILE181(files.flatMap((file)=>file.resourceFiles
    ));
    return Promise.resolve({
        context,
        recipe,
        executeResult: {
            markdown: markdown1,
            supporting: supporting1,
            filters,
            engineDependencies: engineDependencies1,
            preserve: preserve1,
            postProcess: postProcess1
        },
        resourceFiles
    });
}
async function createFeed(doc, source, project, descriptors, options, format151) {
    const siteUrl = websiteBaseurl(project.config);
    if (!siteUrl) {
        warning("Unable to create a feed as the required `site-url` property is missing from this project.");
        return;
    }
    const feedTitle = options.title || websiteTitle(project.config);
    if (!feedTitle) {
        warning("Unable to create a feed as the required `site > title` property is missing from this project.");
        return;
    }
    const feedDescription = options.description || format151.metadata[kDescription1] || websiteDescription(project.config) || "";
    const projectRelInput = relative2(project.dir, source);
    const inputTarget = await resolveInputTarget(project, projectRelInput, false);
    const [dir, stem] = dirAndStem(source);
    const finalRelPath1 = relative2(project.dir, join3(dir, `${stem}.xml`));
    const link2 = absoluteUrl(siteUrl, inputTarget?.outputHref);
    const feedLink = absoluteUrl(siteUrl, finalRelPath1);
    const items = [];
    for (const descriptor of descriptors){
        items.push(...descriptor.items);
    }
    const filteredItems = prepareItems(items, options);
    const mostRecent = mostRecentItem(filteredItems);
    const feed = {
        title: feedTitle,
        description: feedDescription,
        link: link2,
        feedLink,
        generator: `quarto-${quartoConfig.version()}`,
        lastBuildDate: mostRecent && mostRecent.date ? new Date(mostRecent.date).toUTCString() : new Date().toUTCString(),
        language: options.language
    };
    const image4 = options.image || format151.metadata[kImage] || websiteImage(project.config);
    if (image4) {
        feed.image = {
            title: feedTitle,
            link: link2,
            url: absoluteUrl(siteUrl, image4)
        };
        const size = imageSize(image4);
        if (size) {
            const [height, width] = feedImageSize(size.height, size.width);
            feed.image.height = height;
            feed.image.width = width;
        }
    }
    const stagedPath = feedPath(dir, stem, options.type === "full");
    const feedFiles = [];
    const rendered = await renderFeed(siteUrl, feed, filteredItems, project, stagedPath);
    if (rendered) {
        feedFiles.push(stagedPath);
        addLinkTagToDocument(doc, feed, `${stem}.xml`);
    }
    const categoriesToRender = options[kFieldCategories]?.map((category)=>{
        const finalRelPath = relative2(project.dir, join3(dir, `${stem}-${category.toLocaleLowerCase()}.xml`));
        return {
            category,
            file: feedPath(dir, `${stem}-${category.toLocaleLowerCase()}`, options.type === "full"),
            finalFile: finalRelPath,
            feedLink: `${siteUrl}/${finalRelPath}`
        };
    });
    if (categoriesToRender) {
        for (const categoryToRender of categoriesToRender){
            const rendered = await renderCategoryFeed(siteUrl, categoryToRender, feed, items, options, project);
            if (rendered) {
                feedFiles.push(categoryToRender.file);
            }
        }
    }
    return feedFiles;
}
function completeStagedFeeds(context, outputFiles, _incremental) {
    const siteUrl = websiteBaseurl(context.config);
    if (siteUrl !== undefined) {
        outputFiles.forEach((outputFile)=>{
            if (outputFile.format.metadata[kListing]) {
                const [dir, stem] = dirAndStem(outputFile.file);
                const files = resolvePathGlobs(dir, [
                    `${stem}${kStagedFileGlob}`
                ], []);
                const contentReader = renderedContentReader(context, siteUrl);
                for (const feedFile of files.include){
                    const [feedDir, feedStem] = dirAndStem(feedFile);
                    try {
                        const fullContents = feedFile.endsWith(kFullStagedExt);
                        let feedContents = Deno.readTextFileSync(feedFile);
                        const tagWithReplacements = [
                            {
                                tag: "title",
                                regex: kTitleRegex,
                                replaceValue: (rendered)=>{
                                    return rendered.title;
                                }
                            },
                            {
                                tag: "description",
                                regex: kDescRegex,
                                replaceValue: (rendered)=>{
                                    if (fullContents) {
                                        return `<![CDATA[ ${rendered.fullContents} ]]>`;
                                    } else {
                                        return `<![CDATA[ ${rendered.firstPara} ]]>`;
                                    }
                                }
                            }, 
                        ];
                        tagWithReplacements.forEach((tagWithReplacement)=>{
                            const regex = tagWithReplacement.regex;
                            const tag = tagWithReplacement.tag;
                            regex.lastIndex = 0;
                            let match = regex.exec(feedContents);
                            while(match){
                                const relativePath = match[1];
                                const absolutePath = relativePath.startsWith("/") ? join3(projectOutputDir(context), relativePath) : join3(feedDir, relativePath);
                                const contents = contentReader(absolutePath);
                                if (contents) {
                                    const replaceStr = placholderForReplace(tag, relativePath);
                                    if (contents.title) {
                                        feedContents = feedContents.replace(replaceStr, `<${tag}>${tagWithReplacement.replaceValue(contents)}</${tag}>`);
                                    }
                                }
                                match = regex.exec(feedContents);
                            }
                            regex.lastIndex = 0;
                        });
                        Deno.writeTextFileSync(join3(feedDir, `${feedStem}.${kFinalExt}`), feedContents);
                    } catch  {
                        warnOnce(`Unable to generate feed '${feedStem}.xml'`);
                    } finally{
                        Deno.removeSync(feedFile);
                    }
                }
            }
        });
    }
}
async function websitePostRender(context, incremental, outputFiles) {
    const doc404 = join3(projectOutputDir(context), kProject404File);
    outputFiles = outputFiles.filter((file)=>{
        return file.file !== doc404;
    });
    await updateSitemap(context, outputFiles, incremental);
    updateSearchIndex(context, outputFiles, incremental);
    completeStagedFeeds(context, outputFiles, incremental);
    ensureIndexPage(context);
    await updateAliases(context, outputFiles, incremental);
}
function websiteOutputFiles(outputFiles) {
    return outputFiles.filter((outputFile)=>{
        return isHtmlContent(outputFile.file);
    }).map((outputFile)=>{
        const contents = Deno.readTextFileSync(outputFile.file);
        const doctypeMatch = contents.match(/^<!DOCTYPE.*?>/);
        const doc = new DOMParser().parseFromString(contents, "text/html");
        return {
            ...outputFile,
            doc,
            doctype: doctypeMatch ? doctypeMatch[0] : undefined
        };
    });
}
async function bookCrossrefsPostRender(context, outputFiles) {
    const projOutput = projectOutputDir(context);
    const crossrefOutputFiles = outputFiles.filter((file)=>isMultiFileBookFormat(file.format)
    );
    if (crossrefOutputFiles.length > 0) {
        const indexes = await bookCrossrefIndexes(context);
        for (const outputFile of crossrefOutputFiles){
            const fileRelative = relative2(projOutput, outputFile.file);
            const index = bookCrossrefIndexForOutputFile(fileRelative, indexes);
            if (index) {
                resolveCrossrefs(context, fileRelative, outputFile.doc, index);
            }
        }
    }
}
async function bookPostRender(context, incremental, outputFiles) {
    const websiteFiles = websiteOutputFiles(outputFiles);
    if (websiteFiles.length > 0) {
        await bookBibliographyPostRender(context, incremental, websiteFiles);
        await bookCrossrefsPostRender(context, websiteFiles);
        websiteFiles.forEach((websiteFile)=>{
            const doctype = websiteFile.doctype;
            const htmlOutput = (doctype ? doctype + "\n" : "") + websiteFile.doc.documentElement?.outerHTML;
            Deno.writeTextFileSync(websiteFile.file, htmlOutput);
        });
        await websitePostRender(context, incremental, outputFiles);
    }
}
async function bookIncrementalRenderAll(context, options, files) {
    for(let i = 0; i < files.length; i++){
        const contexts = await renderContexts({
            path: files[i]
        }, options, false, context);
        for (const context1 of Object.values(contexts)){
            if (!isMultiFileBookFormat(context1.format)) {
                return true;
            }
        }
    }
    return false;
}
const kAliases = "aliases";
const luaRunHandler = {
    canHandle: (script)=>{
        return [
            ".lua"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, options)=>{
        const cmd = [
            pandocBinaryPath(),
            "--from",
            "markdown",
            "--to",
            "plain", 
        ];
        if (isWindows1()) {
            cmd.push("--lua-filter");
            cmd.push(quartoInitFilter());
        }
        cmd.push("--lua-filter", script);
        cmd.push(...args);
        return await execProcess({
            cmd,
            ...options
        }, "");
    }
};
const kRunHandlers = [
    denoRunHandler,
    luaRunHandler,
    pythonRunHandler,
    rRunHandler, 
];
async function bookBibliographyPostRender(context, incremental, outputFiles) {
    const renderFiles1 = context.config?.project[kProjectRender] || [];
    let refsHtml;
    for (const file2 of renderFiles1){
        const index = await inputTargetIndex(context, file2);
        if (index?.markdown.containsRefs) {
            const target = await resolveInputTarget(context, file2, false);
            if (target) {
                refsHtml = join3(projectOutputDir(context), target.outputHref);
            }
            break;
        }
    }
    if (refsHtml && outputFiles.length > 0) {
        const file1 = outputFiles[0];
        const bibliography = file1.format.metadata[kBibliography];
        const csl = file1.format.metadata[kCsl];
        if (!bibliography) {
            return;
        }
        const citeIds = [];
        outputFiles.forEach((file)=>{
            const refsRelative = pathWithForwardSlashes(relative2(dirname2(file.file), refsHtml));
            forEachCite(file.doc, (cite)=>{
                citeIds.push(...citeIdsFromCite(cite));
                const citeLinks = cite.querySelectorAll("a[role='doc-biblioref']");
                for(let l = 0; l < citeLinks.length; l++){
                    const link3 = citeLinks[l];
                    link3.setAttribute("href", refsRelative + link3.getAttribute("href"));
                }
            });
            const refsDiv = file.doc.getElementById("refs");
            if (refsDiv) {
                refsDiv.setAttribute("style", "display: none");
            }
        });
        const refsOutputFile = outputFiles.find((file)=>file.file === refsHtml
        );
        if (refsOutputFile) {
            if (incremental) {
                const bookHtmlOutputs = await bookMultiFileHtmlOutputs(context);
                bookHtmlOutputs.forEach((htmlOutput)=>{
                    if (outputFiles.findIndex((file)=>file.file === htmlOutput
                    ) === -1) {
                        if (existsSync(htmlOutput)) {
                            const doc = new DOMParser().parseFromString(Deno.readTextFileSync(htmlOutput), "text/html");
                            if (doc) {
                                forEachCite(doc, (cite)=>{
                                    citeIds.push(...citeIdsFromCite(cite));
                                });
                            }
                        }
                    }
                });
            }
            if (citeIds.length > 0) {
                const biblioHtml = await generateBibliographyHTML(context, bibliography, csl, citeIds);
                const newRefsDiv = refsOutputFile.doc.createElement("div");
                newRefsDiv.innerHTML = biblioHtml;
                const refsDiv = refsOutputFile.doc.getElementById("refs");
                if (refsDiv) {
                    refsDiv.replaceWith(newRefsDiv.firstChild);
                } else {
                    const mainEl = refsOutputFile.doc.querySelector("main");
                    if (mainEl) {
                        mainEl.appendChild(newRefsDiv.firstChild);
                    }
                }
            }
        }
    }
}
async function runHtmlPostprocessors(options, htmlPostprocessors, htmlFinalizers) {
    const postProcessResult = {
        resources: [],
        supporting: []
    };
    if (htmlPostprocessors.length > 0 || htmlFinalizers.length > 0) {
        const outputFile = isAbsolute2(options.output) ? options.output : join3(dirname2(options.source), options.output);
        const htmlInput = Deno.readTextFileSync(outputFile);
        const doctypeMatch = htmlInput.match(/^<!DOCTYPE.*?>/);
        const doc = new DOMParser().parseFromString(htmlInput, "text/html");
        for(let i = 0; i < htmlPostprocessors.length; i++){
            const postprocessor = htmlPostprocessors[i];
            const result = await postprocessor(doc);
            postProcessResult.resources.push(...result.resources);
            postProcessResult.supporting.push(...result.supporting);
        }
        for(let i1 = 0; i1 < htmlFinalizers.length; i1++){
            const finalizer = htmlFinalizers[i1];
            await finalizer(doc);
        }
        const htmlOutput = (doctypeMatch ? doctypeMatch[0] + "\n" : "") + doc.documentElement?.outerHTML;
        Deno.writeTextFileSync(outputFile, htmlOutput);
    }
    return postProcessResult;
}
function projectIgnoreGlobs(dir) {
    return engineIgnoreGlobs().concat(gitignoreEntries(dir).map((ignore3)=>`**/${ignore3}**`
    ));
}
async function projectMetadataForInputFile(input, flags, project) {
    if (project) {
        project = cloneDeep1(project);
    } else {
        project = await projectContext(input, flags);
    }
    if (project?.dir && project?.config) {
        return toInputRelativePaths(project.dir, dirname2(input), project.config);
    } else {
        return project?.config || {};
    }
}
async function directoryMetadataForInputFile(projectDir, inputDir) {
    const metadataFile = (dir)=>{
        return [
            "_metadata.yml",
            "_metadata.yaml"
        ].map((file)=>join3(dir, file)
        ).find(existsSync);
    };
    const relativePath = relative2(projectDir, inputDir);
    const dirs = relativePath.split(SEP_PATTERN);
    let config = {};
    let currentDir = projectDir;
    const frontMatterSchema = await getFrontMatterSchema();
    for(let i = 0; i < dirs.length; i++){
        const dir = dirs[i];
        currentDir = join3(currentDir, dir);
        const file = metadataFile(currentDir);
        if (file) {
            const errMsg = "Directory metadata validation failed.";
            const yaml = await readAndValidateYamlFromFile(file, frontMatterSchema, errMsg) || {};
            if (yaml.format) {
                yaml.format = normalizeFormatYaml(yaml.format);
            }
            config = mergeConfigs(config, toInputRelativePaths(currentDir, inputDir, yaml));
        }
    }
    return config;
}
async function resolveFormats(file, target, engine, options, project) {
    const inputMetadata = target.metadata;
    const directoryMetadata = project?.dir ? await directoryMetadataForInputFile(project.dir, dirname2(target.input)) : {};
    const projMetadata = await projectMetadataForInputFile(target.input, options.flags, project);
    let formats12 = [];
    const projFormatKeys = formatKeys(projMetadata);
    const dirFormatKeys = formatKeys(directoryMetadata);
    const inputFormatKeys = __VIRTUAL_FILE181(formatKeys(inputMetadata).concat(dirFormatKeys));
    const projType = projectType(project?.config?.project?.[kProjectType]);
    if (projType.projectFormatsOnly) {
        formats12 = projFormatKeys;
    } else if (inputFormatKeys.length > 0) {
        formats12 = inputFormatKeys;
    } else {
        formats12 = projFormatKeys;
    }
    if (file.formats) {
        formats12 = formats12.filter((format152)=>{
            return file.formats?.includes(format152);
        });
        options = cloneDeep1(options);
        delete options.flags?.to;
    }
    const projFormats = await resolveFormatsFromMetadata(projMetadata, dirname2(target.input), formats12, options.flags);
    const directoryFormats = await resolveFormatsFromMetadata(directoryMetadata, dirname2(target.input), formats12, options.flags);
    const inputFormats = await resolveFormatsFromMetadata(inputMetadata, dirname2(target.input), formats12, options.flags);
    const targetFormats = __VIRTUAL_FILE181(Object.keys(projFormats).concat(Object.keys(directoryFormats)).concat(Object.keys(inputFormats)));
    const mergedFormats = {};
    targetFormats.forEach((format153)=>{
        const projFormat = projFormats[format153];
        const directoryFormat = directoryFormats[format153];
        const inputFormat = inputFormats[format153];
        if (project && isHtmlOutput(format153, true) && formatHasBootstrap(projFormat)) {
            if (formatHasBootstrap(inputFormat)) {
                delete inputFormat.metadata[kTheme];
            }
            if (formatHasBootstrap(directoryFormat)) {
                delete directoryFormat.metadata[kTheme];
            }
        }
        const userFormat = mergeFormatMetadata(projFormat || {}, directoryFormat || {}, inputFormat || {});
        if (userFormat.execute[kEcho] === undefined) {
            if (userFormat.metadata[kServer] !== undefined) {
                userFormat.execute[kEcho] = false;
            }
        }
        mergedFormats[format153] = mergeFormatMetadata(defaultWriterFormat(format153), userFormat);
    });
    for (const formatName of Object.keys(mergedFormats)){
        const format154 = mergedFormats[formatName];
        if (projType.isSupportedFormat) {
            if (!projType.isSupportedFormat(format154)) {
                delete mergedFormats[formatName];
                warnOnce(`The ${formatName} format is not supported by ${projType.type} projects`);
            }
        }
    }
    if (engine.filterFormat) {
        for (const format155 of Object.keys(mergedFormats)){
            mergedFormats[format155] = engine.filterFormat(target.source, options, mergedFormats[format155]);
        }
    }
    return mergedFormats;
}
function mergeQuartoConfigs(config1, ...configs) {
    config1 = cloneDeep1(config1);
    configs = cloneDeep1(configs);
    const fixupMergeableScalars = (metadata)=>{
        [
            kBibliography,
            kCss,
            kHeaderIncludes,
            kIncludeBefore,
            kIncludeAfter,
            kIncludeInHeader,
            kIncludeBeforeBody,
            kIncludeAfterBody, 
        ].forEach((key)=>{
            if (typeof metadata[key] === "string") {
                metadata[key] = [
                    metadata[key]
                ];
            }
        });
    };
    const fixupFormat = (config)=>{
        const format156 = config[kMetadataFormat];
        if (typeof format156 === "string") {
            config.format = {
                [format156]: {}
            };
        } else if (format156 instanceof Object) {
            Object.keys(format156).forEach((key)=>{
                if (typeof Reflect.get(format156, key) !== "object") {
                    Reflect.set(format156, key, {});
                }
                fixupMergeableScalars(Reflect.get(format156, key));
            });
        }
        fixupMergeableScalars(config);
        return config;
    };
    return mergeConfigs(fixupFormat(config1), ...configs.map((c)=>fixupFormat(c)
    ));
}
class RenderInvalidYAMLError extends YAMLValidationError {
    constructor(){
        super("Render failed due to invalid YAML.");
    }
}
function hugoFormat() {
    return createFormat("md", markdownFormat(), {
        render: {
            [kKeepYaml]: true,
            [kPreferHtml]: true,
            [kVariant]: "+definition_lists+footnotes+smart+tex_math_dollars"
        },
        execute: {
            [kFigFormat]: "retina",
            [kFigWidth]: 8,
            [kFigHeight]: 5
        },
        pandoc: {
            to: "gfm",
            [kHtmlMathMethod]: "webtex"
        }
    });
}
function gfmFormat() {
    return createFormat("md", markdownFormat(), {
        pandoc: {
            to: "gfm",
            [kHtmlMathMethod]: "webtex"
        },
        render: {
            [kVariant]: "+footnotes+tex_math_dollars-yaml_metadata_block"
        }
    });
}
function commonmarkFormat(to) {
    return createFormat("md", markdownFormat(), {
        pandoc: {
            to
        },
        render: {
            [kVariant]: "-yaml_metadata_block"
        }
    });
}
function markdownFormat() {
    return createFormat("md", plaintextFormat("md"), {});
}
function powerpointFormat() {
    return createFormat("pptx", {
        render: {
            [kPageWidth]: 10,
            [kOutputDivs]: false
        },
        execute: {
            [kFigWidth]: 11,
            [kFigHeight]: 5.5,
            [kEcho]: false,
            [kWarning]: false
        },
        pandoc: {
            [kDefaultImageExtension]: "png"
        }
    });
}
function rtfFormat() {
    return createFormat("rtf", createWordprocessorFormat("rtf"), {
        pandoc: {
            standalone: true
        }
    });
}
function plaintextFormat(ext) {
    return createFormat(ext, {
        pandoc: {
            standalone: true,
            [kDefaultImageExtension]: "png"
        }
    });
}
const kRevelJsRegEx = /(<script src="\$revealjs-url\$\/dist\/reveal.js"><\/script>)/m;
function revealRequireJsPatch(template14) {
    template14 = template14.replace(kRevelJsRegEx, "<script>window.backupDefine = window.define; window.define = undefined;</script>\n  $1");
    template14 = template14.replace(/(<script src="\$revealjs-url\$\/plugin\/math\/math.js"><\/script>(?:\r?\n|\r)\$endif\$)/, "$1\n  <script>window.define = window.backupDefine; window.backupDefine = undefined;</script>\n");
    return template14;
}
function revealMarkdownAfterBody(format157) {
    const lines14 = [];
    if (format157.metadata[kSlideLogo]) {
        lines14.push(`<img src="${format157.metadata[kSlideLogo]}" class="slide-logo" />`);
        lines14.push("\n");
    }
    lines14.push("::: {.footer .footer-default}");
    if (format157.metadata[kSlideFooter]) {
        lines14.push(String(format157.metadata[kSlideFooter]));
    } else {
        lines14.push("");
    }
    lines14.push(":::");
    lines14.push("\n");
    return lines14.join("\n");
}
function revealHtmlPostprocessor(format158) {
    return (doc)=>{
        if (format158.metadata[kHashType] === "number") {
            const titleSlide = doc.getElementById("title-slide");
            if (titleSlide) {
                titleSlide.removeAttribute("id");
            }
        }
        const scripts = doc.querySelectorAll("script");
        for (const script of scripts){
            const scriptEl = script;
            if (scriptEl.innerText && scriptEl.innerText.indexOf("Reveal.initialize({") !== -1) {
                scriptEl.innerText = scriptEl.innerText.replace(/slideNumber: (h[\.\/]v|c(?:\/t)?)/, "slideNumber: '$1'");
            }
        }
        const invisibleSlides = doc.querySelectorAll('section.slide[data-visibility="hidden"]');
        for(let i1 = invisibleSlides.length - 1; i1 >= 0; i1--){
            const slide = invisibleSlides.item(i1);
            const id = slide.id;
            if (id) {
                const tocEntry = doc.querySelector('nav[role="doc-toc"] a[href="#/' + id + '"]');
                if (tocEntry) {
                    tocEntry.parentNode?.remove();
                }
            }
            slide.parentNode?.removeChild(slide);
        }
        const slideLevel = format158.pandoc[kSlideLevel] || 2;
        const slideHeadingTags = Array.from(Array(slideLevel)).map((_e, i)=>"H" + (i + 1)
        );
        const slideHeadings = doc.querySelectorAll("section.slide > :first-child");
        slideHeadings.forEach((slideHeading)=>{
            const slideHeadingEl = slideHeading;
            if (slideHeadingTags.includes(slideHeadingEl.tagName)) {
                for (const attrib of slideHeadingEl.getAttributeNames()){
                    slideHeadingEl.removeAttribute(attrib);
                    if (attrib === "data-auto-animate") {
                        slideHeadingEl.setAttribute("data-id", "quarto-animate-title");
                        const codeBlocks = slideHeadingEl.parentElement?.querySelectorAll("div.sourceCode > pre > code");
                        if (codeBlocks?.length === 1) {
                            const codeEl = codeBlocks.item(0);
                            const preEl = codeEl.parentElement;
                            preEl.setAttribute("data-id", "quarto-animate-code");
                            codeEl.classList.add("hljs");
                            codeEl.childNodes.forEach((spanNode)=>{
                                if (spanNode.nodeType === NodeType.ELEMENT_NODE) {
                                    const spanEl = spanNode;
                                    spanEl.classList.add("hljs-ln-code");
                                }
                            });
                        }
                    }
                }
            }
        });
        if (format158.metadata[kCenterTitleSlide] !== false) {
            const titleSlide = doc.getElementById("title-slide");
            if (titleSlide) {
                titleSlide.classList.add("center");
            }
            const titleSlides = doc.querySelectorAll(".title-slide");
            for (const slide of titleSlides){
                slide.classList.add("center");
            }
        }
        const notes = doc.querySelectorAll('a[role="doc-noteref"]');
        for (const note of notes){
            const noteEl = note;
            noteEl.setAttribute("onclick", "return false;");
        }
        const cites = doc.querySelectorAll('a[role="doc-biblioref"');
        for (const cite of cites){
            const citeEl = cite;
            citeEl.setAttribute("onclick", "return false;");
        }
        const refs = doc.querySelector("#refs");
        if (refs) {
            applyClassesToParentSlide(refs, [
                "smaller",
                "scrollable"
            ]);
            removeClassesFromParentSlide(refs, [
                "center"
            ]);
        }
        const footnotes = doc.querySelectorAll('section[role="doc-endnotes"]');
        if (footnotes.length === 1) {
            const footnotesEl = footnotes[0];
            insertFootnotesTitle(doc, footnotesEl, format158.language, slideLevel);
            footnotesEl.classList.add("smaller");
            footnotesEl.classList.add("scrollable");
            footnotesEl.classList.remove("center");
            removeFootnoteBacklinks(footnotesEl);
        }
        applyStretch(doc, format158.metadata[kAutoStretch]);
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function applyStretch(doc, autoStretch) {
    const allSlides = doc.querySelectorAll("section.slide");
    for (const slide of allSlides){
        const slideEl = slide;
        if (slideEl.classList.contains("nostretch")) continue;
        const images = slideEl.querySelectorAll("img");
        if (images.length === 1) {
            const image5 = images[0];
            const imageEl1 = image5;
            if (findParent(imageEl1, (el)=>{
                return el.classList.contains("column") || el.classList.contains("quarto-layout-panel") || !!el.className.match(/panel-/);
            })) {
                continue;
            }
            let selNode;
            for (const node of slide.childNodes){
                if (node.contains(image5)) {
                    selNode = node;
                    break;
                }
            }
            const nodeEl = selNode;
            if (!nodeEl || nodeEl.nodeName === "P" && nodeEl.childNodes.length > 1) {
                continue;
            }
            const hasStretchClass = function(imageEl) {
                return imageEl.classList.contains("stretch") || imageEl.classList.contains("r-stretch");
            };
            if (autoStretch === true && !hasStretchClass(imageEl1) && !imageEl1.getAttribute("style")?.match("height:") && !imageEl1.hasAttribute("height")) {
                imageEl1.classList.add("r-stretch");
            }
            if (hasStretchClass(imageEl1) && imageEl1.parentNode?.nodeName !== "SECTION") {
                const removeEmpty = function(el) {
                    const parentEl = el.parentElement;
                    parentEl?.removeChild(el);
                    if (parentEl?.innerText.trim() === "") removeEmpty(parentEl);
                };
                const quartoFig = slideEl.querySelector("div.quarto-figure");
                const caption = doc.createElement("p");
                if (quartoFig) {
                    const align = quartoFig.className.match("quarto-figure-(center|left|right)");
                    if (align) imageEl1.classList.add(align[0]);
                    const figCaption = nodeEl.querySelector("figcaption");
                    if (figCaption) {
                        caption.classList.add("caption");
                        caption.innerHTML = figCaption.innerHTML;
                    }
                }
                const nextEl = nodeEl.nextElementSibling;
                removeEmpty(imageEl1);
                slideEl.insertBefore(image5, nextEl);
                if (caption.classList.contains("caption")) {
                    slideEl.insertBefore(caption, imageEl1.nextElementSibling);
                }
                if (quartoFig) removeEmpty(quartoFig);
            }
        }
    }
}
function applyClassesToParentSlide(el, classes, slideClass = "slide") {
    const slideEl = findParentSlide(el, slideClass);
    if (slideEl) {
        classes.forEach((clz)=>slideEl.classList.add(clz)
        );
    }
}
function removeClassesFromParentSlide(el, classes, slideClass = "slide") {
    const slideEl = findParentSlide(el, slideClass);
    if (slideEl) {
        classes.forEach((clz)=>slideEl.classList.remove(clz)
        );
    }
}
function findParentSlide(el1, slideClass = "slide") {
    return findParent(el1, (el)=>{
        return el.classList.contains(slideClass);
    });
}
function revealMenuPlugin(format159) {
    return {
        plugin: formatResourcePath("revealjs", join3("plugins", "menu")),
        config: {
            menu: {
                custom: [
                    {
                        title: "Tools",
                        icon: '<i class="fas fa-gear"></i>',
                        content: revealMenuTools(format159)
                    }
                ],
                openButton: format159.metadata[kRevealMenu] !== false
            }
        }
    };
}
function revealChalkboardPlugin(format160) {
    if (format160.metadata[kRevealChalkboard]) {
        return {
            plugin: formatResourcePath("revealjs", join3("plugins", "chalkboard"))
        };
    } else {
        return undefined;
    }
}
function revealMenuTools(format161) {
    const tools = [
        {
            title: "Fullscreen",
            key: "f",
            handler: "fullscreen"
        },
        {
            title: "Speaker View",
            key: "s",
            handler: "speakerMode"
        },
        {
            title: "Slide Overview",
            key: "o",
            handler: "overview"
        },
        {
            title: "PDF Export Mode",
            key: "e",
            handler: "overview"
        }, 
    ];
    if (format161.metadata[kRevealChalkboard]) {
        tools.push({
            title: "Toggle Chalkboard",
            key: "b",
            handler: "toggleChalkboard"
        }, {
            title: "Toggle Notes Canvas",
            key: "c",
            handler: "toggleNotesCanvas"
        }, {
            title: "Download Drawings",
            key: "d",
            handler: "downloadDrawings"
        });
    }
    tools.push({
        title: "Keyboard Help",
        key: "?",
        handler: "keyboardHelp"
    });
    const lines15 = [
        '<ul class="slide-menu-items">'
    ];
    lines15.push(...tools.map((tool, index)=>{
        return `<li class="slide-tool-item${index === 0 ? " active" : ""}" data-item="${index}"><a href="#" onclick="RevealMenuToolHandlers.${tool.handler}(event)"><kbd>${tool.key || " "}</kbd> ${tool.title}</a></li>`;
    }));
    lines15.push("</ul>");
    return lines15.join("\n");
}
function revealTonePlugin(format162) {
    if (format162.metadata[kRevealSlideTone]) {
        return {
            plugin: formatResourcePath("revealjs", join3("plugins", "tone"))
        };
    } else {
        return undefined;
    }
}
function toneDependency() {
    const dependency = {
        name: "tone",
        scripts: [
            {
                name: "tone.js",
                path: formatResourcePath("revealjs", join3("tone", "tone.js"))
            }
        ]
    };
    return dependency;
}
async function pluginFromBundle(bundle) {
    if (!existsSync(bundle.plugin) || !Deno.statSync(bundle.plugin).isDirectory) {
        throw new Error("Specified Reveal plugin directory '" + bundle.plugin + "' does not exist.");
    }
    let plugin;
    try {
        plugin = await readAndValidateYamlFromFile(join3(bundle.plugin, "plugin.yml"), revealPluginSchema, "Validation of reveal plugin object failed.");
        plugin.path = bundle.plugin;
    } catch (e) {
        error(`Validation of plugin configuration ${join3(bundle.plugin, "plugin.yml")} failed.`);
        throw e;
    }
    if (plugin.script && !Array.isArray(plugin.script)) {
        plugin.script = [
            plugin.script
        ];
    }
    plugin.script = plugin.script?.map((script)=>{
        if (typeof script === "string") {
            return {
                path: script
            };
        } else {
            return script;
        }
    });
    if (plugin.stylesheet && !Array.isArray(plugin.stylesheet)) {
        plugin.stylesheet = [
            plugin.stylesheet
        ];
    }
    plugin.stylesheet = plugin.stylesheet?.map((stylesheet)=>String(stylesheet)
    );
    validatePlugin(plugin);
    if (typeof bundle.config === "object") {
        plugin.config = mergeConfigs(plugin.config || {}, bundle.config || {});
    }
    if (typeof plugin.metadata === "string") {
        plugin.metadata = [
            plugin.metadata
        ];
    }
    return plugin;
}
function validatePlugin(plugin) {
    if (typeof plugin.name !== "string") {
        throw new Error("Reveal plugin definition must include a name.");
    }
    if (!Array.isArray(plugin.script)) {
        throw new Error("Reveal plugin definition must include a script.");
    }
    for (const script of plugin.script){
        if (!existsSync(join3(plugin.path, script.path))) {
            throw new Error("Reveal plugin script '" + script + "' not found.");
        }
    }
    if (plugin.stylesheet) {
        for (const stylesheet of plugin.stylesheet){
            if (!existsSync(join3(plugin.path, stylesheet))) {
                throw new Error("Reveal plugin stylesheet '" + stylesheet + "' not found.");
            }
        }
    }
    if (plugin.config) {
        if (typeof plugin.config !== "object") {
            throw new Error("Reveal plugin config must be an object.");
        }
    }
}
function resolveBodyEnvelope(pandoc, extras, temp) {
    const envelope = extras.html?.[kBodyEnvelope];
    if (envelope) {
        const writeBodyFile = (type, prepend, content)=>{
            if (content) {
                const file = temp.createFile({
                    suffix: ".html"
                });
                Deno.writeTextFileSync(file, content);
                if (!prepend) {
                    pandoc[type] = (pandoc[type] || []).concat(file);
                } else {
                    pandoc[type] = [
                        file
                    ].concat(pandoc[type] || []);
                }
            }
        };
        writeBodyFile(kIncludeInHeader, true, envelope.header);
        writeBodyFile(kIncludeBeforeBody, true, envelope.before);
        writeBodyFile(kIncludeAfterBody, true, envelope.afterPreamble);
        writeBodyFile(kIncludeAfterBody, false, envelope.afterPostamble);
    }
}
function pandocDefaultsMessage(pandoc, sysFilters, debug4) {
    const kDebugOnly = [
        kIncludeInHeader,
        kIncludeBeforeBody,
        kIncludeAfterBody, 
    ];
    const kOrder = [
        kTo,
        kFrom,
        kOutputFile,
        kTemplate,
        kStandalone,
        kSelfContained, 
    ];
    const defaults = {};
    kOrder.forEach((key)=>{
        if (Object.keys(pandoc).includes(key)) {
            defaults[key] = pandoc[key];
        }
    });
    Object.keys(pandoc).forEach((key)=>{
        if (!kOrder.includes(key) && (debug4 || !kDebugOnly.includes(key))) {
            defaults[key] = pandoc[key];
        }
    });
    if (defaults.filters?.length) {
        defaults.filters = defaults.filters.map((filter9)=>{
            if (filter9 === crossrefFilter()) {
                return "crossref";
            } else {
                return filter9;
            }
        }).filter((filter10)=>{
            return filter10 !== quartoInitFilter() && filter10 !== quartoPreFilter() && filter10 !== quartoPostFilter() && filter10 !== layoutFilter() && !sysFilters.includes(filter10);
        });
        if (defaults.filters?.length === 0) {
            delete defaults.filters;
        }
    }
    if (defaults.template && extname2(defaults.template) === kPatchedTemplateExt) {
        delete defaults.template;
    }
    return stringify(defaults);
}
function runPandocMessage(args, pandoc, sysFilters, metadata, debug5) {
    info(`pandoc ${args.join(" ")}`, {
        bold: true
    });
    if (pandoc) {
        info(pandocDefaultsMessage(pandoc, sysFilters, debug5), {
            indent: 2
        });
    }
    const keys10 = Object.keys(metadata);
    if (keys10.length > 0) {
        const printMetadata = __VIRTUAL_FILE107(metadata);
        delete printMetadata.format;
        removeFilterParmas(printMetadata);
        if (Object.keys(printMetadata).length > 0) {
            info("metadata", {
                bold: true
            });
            info(stringify(printMetadata, {
                indent: 2,
                sortKeys: false,
                skipInvalid: true
            }), {
                indent: 2
            });
        }
    }
}
function resolveTextHighlightStyle(extras, pandoc) {
    extras = cloneDeep1(extras);
    const highlightTheme = pandoc[kHighlightStyle] || kDefaultHighlightStyle;
    const textHighlightingMode = extras.html?.[kTextHighlightingMode];
    switch(textHighlightingMode){
        case "light":
        case "dark":
            extras.pandoc = extras.pandoc || {};
            extras.pandoc[kHighlightStyle] = textHighlightThemePath(highlightTheme, textHighlightingMode) || highlightTheme;
            break;
        case "none":
            delete pandoc[kHighlightStyle];
            if (extras.pandoc) {
                delete extras.pandoc[kHighlightStyle];
            }
            break;
        case undefined:
        default:
            extras.pandoc = extras.pandoc || {};
            extras.pandoc[kHighlightStyle] = textHighlightThemePath(highlightTheme, "light") || highlightTheme;
            break;
    }
    return extras;
}
function normalizeFormatYaml(yamlFormat) {
    if (yamlFormat) {
        if (typeof yamlFormat === "string") {
            yamlFormat = {
                [yamlFormat]: {}
            };
        } else if (typeof yamlFormat === "object") {
            const formats13 = Object.keys(yamlFormat);
            for (const format163 of formats13){
                if (yamlFormat[format163] === "default") {
                    yamlFormat[format163] = {};
                }
            }
        }
    }
    return yamlFormat || {};
}
function toInputRelativePaths(baseDir, inputDir, collection1, parentKey) {
    __VIRTUAL_FILE144(collection1, (value1, index, collection)=>{
        const assign = (value)=>{
            if (typeof index === "number") {
                collection[index] = value;
            } else if (typeof index === "string") {
                collection[index] = value;
            }
        };
        if (parentKey === kHtmlMathMethod && index === "method") {} else if (Array.isArray(value1)) {
            assign(toInputRelativePaths(baseDir, inputDir, value1));
        } else if (typeof value1 === "object") {
            assign(toInputRelativePaths(baseDir, inputDir, value1, index));
        } else if (typeof value1 === "string") {
            if (!isAbsolute2(value1)) {
                const projectPath = join3(baseDir, value1);
                try {
                    if (existsSync(projectPath)) {
                        const offset = relative2(inputDir, baseDir);
                        assign(pathWithForwardSlashes(join3(offset, value1)));
                    }
                } catch  {}
            }
        }
    });
    return collection1;
}
function projectYamlFiles(dir) {
    const files = [];
    const projIgnoreGlobs = projectHiddenIgnoreGlob(dir);
    for (const walk5 of walkSync(dir, {
        includeDirs: true,
        followSymlinks: false,
        skip: [
            kSkipHidden
        ].concat(projIgnoreGlobs.map((ignore4)=>globToRegExp(join3(dir, ignore4) + SEP)
        ))
    })){
        if (walk5.isFile && isYamlPath(walk5.path)) {
            files.push(walk5.path);
        }
    }
    return files;
}
function projectHiddenIgnoreGlob(dir) {
    return projectIgnoreGlobs(dir).concat([
        "**/_*",
        "**/_*/**"
    ]).concat([
        "**/.*",
        "**/.*/**"
    ]).concat([
        "**/README.?([Rrq])md"
    ]);
}
function projectInputFiles(dir1, metadata) {
    const files = [];
    const engines = [];
    const keepFiles = [];
    const outputDir = metadata?.project[kProjectOutputDir];
    const projIgnoreGlobs = projectHiddenIgnoreGlob(dir1);
    const projectIgnores = projIgnoreGlobs.map((glob)=>globToRegExp(glob, {
            extended: true,
            globstar: true
        })
    );
    const addFile = (file)=>{
        if (!outputDir || !file.startsWith(join3(dir1, outputDir))) {
            const engine = fileExecutionEngine(file);
            if (engine) {
                if (!engines.includes(engine.name)) {
                    engines.push(engine.name);
                }
                files.push(file);
                const keep = executionEngineKeepFiles(engine, file);
                if (keep) {
                    keepFiles.push(...keep);
                }
            }
        }
    };
    const addDir = (dir)=>{
        for (const walk6 of walkSync(dir, {
            includeDirs: false,
            followSymlinks: false,
            skip: [
                kSkipHidden
            ].concat(engineIgnoreDirs().map((ignore5)=>globToRegExp(join3(dir, ignore5) + SEP)
            ))
        })){
            const pathRelative = pathWithForwardSlashes(relative2(dir, walk6.path));
            if (!projectIgnores.some((regex)=>regex.test(pathRelative)
            )) {
                addFile(walk6.path);
            }
        }
    };
    const renderFiles2 = metadata?.project[kProjectRender];
    if (renderFiles2) {
        const exclude = projIgnoreGlobs.concat(outputDir ? [
            outputDir
        ] : []);
        const resolved = resolvePathGlobs(dir1, renderFiles2, exclude);
        __VIRTUAL_FILE137(resolved.include, resolved.exclude).forEach((file)=>{
            if (Deno.statSync(file).isDirectory) {
                addDir(file);
            } else {
                addFile(file);
            }
        });
    } else {
        addDir(dir1);
    }
    const inputFiles = __VIRTUAL_FILE137(__VIRTUAL_FILE181(files), __VIRTUAL_FILE181(keepFiles));
    return {
        files: inputFiles,
        engines
    };
}
function projectConfigResources(dir, metadata, type) {
    const resourceIgnoreFields = type ? [
        "project"
    ].concat(type.resourceIgnoreFields ? type.resourceIgnoreFields() : []) : [];
    const resources = [];
    const findResources = (collection, parentKey)=>{
        __VIRTUAL_FILE144(collection, (value, index)=>{
            if (parentKey === kHtmlMathMethod && index === "method") {} else if (resourceIgnoreFields.includes(index)) {} else if (Array.isArray(value)) {
                findResources(value);
            } else if (typeof value === "object") {
                findResources(value, index);
            } else if (typeof value === "string") {
                const path94 = isAbsolute2(value) ? value : join3(dir, value);
                try {
                    if (existsSync(path94) && !Deno.statSync(path94).isDirectory) {
                        resources.push(Deno.realPathSync(path94));
                    }
                } catch  {}
            }
        });
    };
    findResources(metadata);
    return resources;
}
function bookHtmlPostprocessor() {
    return (doc)=>{
        const coverImage = doc.querySelector(".quarto-cover-image");
        const nextEl = coverImage?.parentNode?.nextElementSibling;
        if (nextEl && nextEl.tagName === "SECTION" && coverImage?.parentNode) {
            coverImage?.parentNode.remove();
            nextEl.firstChild.after(coverImage?.parentNode);
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function bookScssBundle() {
    const scssPath = resourcePath("projects/book/book.scss");
    return {
        dependency: kBootstrapDependencyName,
        key: scssPath,
        quarto: {
            name: "quarto-book.css",
            uses: "",
            defaults: "",
            functions: "",
            mixins: "",
            rules: Deno.readTextFileSync(scssPath)
        }
    };
}
function websiteTemplate(resourceDir, title21, template15) {
    if (template15 === kSiteTemplateBlog) {
        const today = new Date();
        const secondPostDateStr = today.toLocaleDateString();
        today.setDate(today.getDate() - 3);
        const firstPostDateStr = today.toLocaleDateString();
        return {
            configTemplate: join3(resourceDir, "templates", "blog", "_quarto-blog.ejs.yml"),
            resourceDir,
            scaffold: ()=>[
                    {
                        name: "index",
                        content: "",
                        noEngineContent: true,
                        title: title21,
                        yaml: 'listing:\n  contents: posts\n  sort: "date desc"\n  type: default\n  categories: true'
                    },
                    {
                        name: "index",
                        subdirectory: "posts/welcome",
                        title: "Welcome To My Blog",
                        content: "This is the first post in a Quarto blog. Welcome!\n\n![](thumbnail.jpg)\n\nSince this post doesn't specify an explicit `image`, the first image in the post will be used in the listing page of posts.",
                        noEngineContent: true,
                        yaml: `author: "Tristan O'Malley"\ndate: "${firstPostDateStr}"\ncategories: [news]`,
                        supporting: [
                            join3(resourceDir, "templates", "blog", "thumbnail.jpg"), 
                        ]
                    },
                    {
                        name: "index",
                        subdirectory: "posts/post-with-code",
                        title: "Post With Code",
                        content: "This is a post with executable code.",
                        yaml: `author: "Harlow Malloc"\ndate: "${secondPostDateStr}"\ncategories: [news, code, analysis]\nimage: "image.jpg"`,
                        supporting: [
                            join3(resourceDir, "templates", "blog", "image.jpg"), 
                        ]
                    },
                    {
                        name: "about",
                        title: "About",
                        content: "About this blog",
                        yaml: `image: profile.jpg\nabout:\n  template: jolla\n  links:\n    - icon: twitter\n      text: Twitter\n      href: https://twitter.com\n    - icon: linkedin\n      text: LinkedIn\n      href: https://linkedin.com\n    - icon: github\n      text: Github\n      href: https://github.com\n`,
                        supporting: [
                            join3(resourceDir, "templates", "blog", "profile.jpg"), 
                        ],
                        noEngineContent: true
                    }, 
                ]
            ,
            supporting: [
                "styles.css",
                {
                    from: join3("templates", "blog", "_metadata.yml"),
                    to: join3("posts", "_metadata.yml")
                }, 
            ]
        };
    } else {
        return {
            configTemplate: join3(resourceDir, "templates", "_quarto.ejs.yml"),
            resourceDir,
            scaffold: ()=>[
                    {
                        name: "index",
                        content: "This is a Quarto website.\n\nTo learn more about Quarto websites visit <https://quarto.org/docs/websites>.",
                        title: title21
                    },
                    {
                        name: "about",
                        content: "About this site",
                        title: "About"
                    }, 
                ]
            ,
            supporting: [
                "styles.css", 
            ]
        };
    }
}
async function ensureIndexPage(project) {
    const outputDir = projectOutputDir(project);
    const indexPage = join3(outputDir, "index.html");
    if (!safeExistsSync(indexPage)) {
        const firstInput = project.files.input[0];
        if (firstInput) {
            const firstInputHref = relative2(project.dir, firstInput);
            const resolved = await resolveInputTarget(project, firstInputHref, false);
            if (resolved) {
                writeRedirectPage(indexPage, resolved.outputHref);
            }
        }
    }
}
function writeRedirectPage(path95, href) {
    const redirectTemplate = resourcePath("projects/website/templates/redirect-simple.ejs");
    const redirectHtml = renderEjs(redirectTemplate, {
        url: href
    });
    Deno.writeTextFileSync(path95, redirectHtml);
}
function navigationHtmlPostprocessor(project, source, markdownPipeline, language) {
    const sourceRelative = relative2(project.dir, source);
    const offset = projectOffset(project, source);
    const href1 = inputFileHref(sourceRelative);
    return async (doc)=>{
        markdownPipeline.processRenderedMarkdown(doc);
        const sidebarEl = doc.body.getElementById("quarto-sidebar");
        if (sidebarEl?.classList.contains("floating")) {
            doc.body.classList.add("floating");
        } else if (sidebarEl?.classList.contains("docked")) {
            doc.body.classList.add("docked");
        }
        const navLinks = doc.querySelectorAll("a.nav-link");
        for(let i = 0; i < navLinks.length; i++){
            const navLink = navLinks[i];
            const navLinkHref = navLink.getAttribute("href");
            const sidebarLink = doc.querySelector('.sidebar-navigation a[href="' + navLinkHref + '"]');
            if (sidebarLink || navLinkHref === href1) {
                navLink.classList.add("active");
                navLink.setAttribute("aria-current", "page");
                break;
            }
        }
        const title22 = doc.querySelector("header .title .quarto-section-identifier") || doc.querySelector("header .title");
        const secondaryNavTitleEl = doc.querySelector(".quarto-secondary-nav .quarto-secondary-nav-title");
        if (secondaryNavTitleEl) {
            if (title22) {
                title22.classList.add("d-none");
                title22.classList.add("d-lg-block");
            }
            if (title22) {
                secondaryNavTitleEl.innerHTML = title22.innerHTML;
            } else {
                secondaryNavTitleEl.innerHTML = "(Untitled)";
            }
            const titleBlock = doc.querySelector("header > .quarto-title-block");
            if (titleBlock) {
                titleBlock.classList.add("d-none");
                titleBlock.classList.add("d-lg-block");
            }
        }
        const links = doc.querySelectorAll("a[href]");
        for(let i1 = 0; i1 < links.length; i1++){
            const link4 = links[i1];
            const href = getDecodedAttribute(link4, "href");
            if (href && !isExternalPath(href)) {
                let projRelativeHref = href.startsWith("/") ? href.slice(1) : join3(dirname2(sourceRelative), href);
                const hashLoc = projRelativeHref.indexOf("#");
                const hash = hashLoc !== -1 ? projRelativeHref.slice(hashLoc) : "";
                if (hash) {
                    projRelativeHref = projRelativeHref.slice(0, hashLoc);
                }
                const resolved = await resolveInputTarget(project, projRelativeHref);
                if (resolved) {
                    link4.setAttribute("href", offset + resolved.outputHref + hash);
                } else {
                    if (!safeExistsSync(join3(project.dir, projRelativeHref))) {
                        const targetFile = join3(projectOutputDir(project), projRelativeHref);
                        if (engineValidExtensions().includes(extname2(targetFile)) && !safeExistsSync(join3(projectOutputDir(project), projRelativeHref))) {
                            warning("Unable to resolve link target: " + projRelativeHref);
                        }
                    }
                }
            }
        }
        handleRepoLinks(doc, sourceRelative, language, project.config);
        const numberSections = websiteHtmlFormat(project).pandoc[kNumberSections] !== false;
        if (numberSections === false) {
            const sidebarItems = doc.querySelectorAll(".sidebar-item .sidebar-item-text");
            for(let i = 0; i < sidebarItems.length; i++){
                const sidebarItem = sidebarItems[i];
                removeChapterNumber(sidebarItem);
            }
            const titleEl = doc.querySelector("h1.title");
            if (titleEl) {
                removeChapterNumber(titleEl);
            }
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function removeChapterNumber(item) {
    const numberSpan = item.querySelector(".chapter-number");
    const titleSpan = item.querySelector(".chapter-title");
    if (numberSpan && titleSpan) {
        if (numberSpan && titleSpan) {
            item.innerHTML = "";
            item.appendChild(titleSpan);
        }
    }
}
function handleRepoLinks(doc, source, language, config) {
    const repoActions = websiteConfigActions(kSiteRepoActions, kWebsite, config);
    const elRepoSource = doc.querySelector("[" + kDataQuartoSourceUrl + '="repo"]');
    if (repoActions.length > 0 || elRepoSource) {
        const repoUrl = websiteRepoUrl(config);
        if (repoUrl) {
            if (isGithubRepoUrl(repoUrl)) {
                if (repoActions.length > 0) {
                    const toc = doc.querySelector(`nav[role="doc-toc"]`);
                    if (toc) {
                        const links = repoActionLinks(repoActions, repoUrl, websiteRepoBranch(config), source, language);
                        const actionsDiv = doc.createElement("div");
                        actionsDiv.classList.add("toc-actions");
                        const iconDiv = doc.createElement("div");
                        const iconEl = doc.createElement("i");
                        iconEl.classList.add("bi").add("bi-github");
                        iconDiv.appendChild(iconEl);
                        actionsDiv.appendChild(iconDiv);
                        const linksDiv = doc.createElement("div");
                        linksDiv.classList.add("action-links");
                        links.forEach((link5)=>{
                            const a = doc.createElement("a");
                            a.setAttribute("href", link5.url);
                            a.classList.add("toc-action");
                            a.innerHTML = link5.text;
                            const p = doc.createElement("p");
                            p.appendChild(a);
                            linksDiv.appendChild(p);
                        });
                        actionsDiv.appendChild(linksDiv);
                        toc.appendChild(actionsDiv);
                    }
                }
                if (elRepoSource) {
                    elRepoSource.setAttribute(kDataQuartoSourceUrl, `${repoUrl}blob/${websiteRepoBranch(config)}/${source}`);
                }
            } else {
                warnOnce(`Repository links require a github.com ${kSiteRepoUrl}`);
            }
        } else {
            warnOnce(`Repository links require that you specify a ${kSiteRepoUrl}`);
        }
    }
}
function repoActionLinks(actions, repoUrl, branch, source, language) {
    return actions.map((action)=>{
        switch(action){
            case "edit":
                return {
                    text: language[kRepoActionLinksEdit],
                    url: `${repoUrl}edit/${branch}/${source}`
                };
            case "source":
                return {
                    text: language[kRepoActionLinksSource],
                    url: `${repoUrl}blob/${branch}/${source}`
                };
            case "issue":
                return {
                    text: language[kRepoActionLinksIssue],
                    url: `${repoUrl}issues/new`
                };
            default:
                {
                    warnOnce(`Unknown repo action '${action}'`);
                    return null;
                }
        }
    }).filter((action)=>action !== null
    );
}
async function resolveFooter(project, footer) {
    const resolveItems = async (contents)=>{
        if (Array.isArray(contents)) {
            const resolvedItems = [];
            for(let i = 0; i < contents.length; i++){
                const item = contents[i];
                const navItem = await navigationItem(project, item);
                resolvedItems.push(navItem);
            }
            return resolvedItems;
        } else {
            return contents;
        }
    };
    if (footer) {
        footer.left = await resolveItems(footer.left);
        footer.center = await resolveItems(footer.center);
        footer.right = await resolveItems(footer.right);
    }
    return footer;
}
async function sidebarsEjsData(project, sidebars) {
    const ejsSidebars = [];
    for(let i = 0; i < sidebars.length; i++){
        ejsSidebars.push(await sidebarEjsData(project, sidebars[i]));
    }
    return Promise.resolve(ejsSidebars);
}
async function sidebarEjsData(project, sidebar) {
    sidebar = cloneDeep1(sidebar);
    if (sidebar.title && !sidebar.id) {
        sidebar.id = asHtmlId(sidebar.title);
    }
    sidebar.title = sidebarTitle(sidebar, project);
    sidebar.logo = resolveLogo(sidebar.logo);
    const searchOpts = searchOptions(project);
    sidebar.search = sidebar.search !== undefined ? sidebar.search : searchOpts && searchOpts.location === "sidebar" ? searchOpts.type : false;
    sidebar[kCollapseLevel] = sidebar[kCollapseLevel] || 2;
    sidebar.aligment = sidebar.aligment || "center";
    sidebar.pinned = sidebar.pinned !== undefined ? !!sidebar.pinned : false;
    await resolveSidebarItems(project, sidebar.contents);
    await resolveSidebarTools(project, sidebar.tools);
    return sidebar;
}
async function resolveSidebarItems(project, items) {
    for(let i = 0; i < items.length; i++){
        let item = normalizeSidebarItem(project.dir, items[i]);
        if (Object.keys(item).includes("contents")) {
            const subItems = item.contents || [];
            if (item.href) {
                item = await resolveItem(project, item.href, item);
            }
            for(let i2 = 0; i2 < subItems.length; i2++){
                subItems[i2] = await resolveSidebarItem(project, normalizeSidebarItem(project.dir, subItems[i2]));
            }
            items[i] = item;
        } else {
            items[i] = await resolveSidebarItem(project, item);
        }
    }
}
async function resolveSidebarItem(project, item) {
    if (item.href) {
        item = await resolveItem(project, item.href, item);
    }
    if (item.contents) {
        await resolveSidebarItems(project, item.contents);
        return item;
    } else {
        return item;
    }
}
async function resolveSidebarTools(project, tools) {
    if (tools) {
        for(let i = 0; i < tools.length; i++){
            if (Object.keys(tools[i]).includes("menu")) {
                const items = tools[i].menu || [];
                for(let i4 = 0; i4 < items.length; i4++){
                    const toolItem = await navigationItem(project, items[i4], 1);
                    if (toolItem.href) {
                        const tool = await resolveItem(project, toolItem.href, toolItem);
                        validateTool(tool);
                        items[i4] = tool;
                    }
                }
            } else {
                const toolItem = tools[i];
                resolveHrefAttribute(toolItem);
                if (toolItem.href) {
                    tools[i] = await resolveItem(project, toolItem.href, toolItem);
                    validateTool(tools[i]);
                }
            }
        }
    }
}
function validateTool(tool) {
    if (tool.icon === undefined && tool.text === undefined) {
        warning("A sidebar tool is defined without text or an icon.");
    }
}
function sidebarForHref(href, format164) {
    if (navigation.sidebars.length === 1) {
        return navigation.sidebars[0];
    } else {
        for (const sidebar of navigation.sidebars){
            if (sidebar.id === format164.metadata[kSiteSidebar]) {
                return sidebar;
            } else if (containsHref(href, sidebar.contents)) {
                return sidebar;
            }
        }
    }
}
function sidebarStyle() {
    if (navigation.sidebars.length > 0) {
        return navigation.sidebars[0].style;
    } else {
        return undefined;
    }
}
function containsHref(href, items) {
    for(let i = 0; i < items.length; i++){
        if (items[i].href && items[i].href === href) {
            return true;
        } else if (Object.keys(items[i]).includes("contents")) {
            const subItems = items[i].contents || [];
            const subItemsHasHref = containsHref(href, subItems);
            if (subItemsHasHref) {
                return true;
            }
        } else {
            if (itemHasNavTarget(items[i], href)) {
                return true;
            }
        }
    }
    return false;
}
function expandedSidebar(href2, sidebar) {
    if (sidebar) {
        const resolveExpandedItems = (href, items)=>{
            for(let i = 0; i < items.length; i++){
                const item = items[i];
                item.active = itemHasNavTarget(item, href);
                if (Object.keys(item).includes("contents")) {
                    if (resolveExpandedItems(href, item.contents || [])) {
                        item.expanded = true;
                        return true;
                    }
                } else if (item.active) {
                    return true;
                }
            }
            return false;
        };
        const expandedSidebar1 = __VIRTUAL_FILE107(sidebar);
        resolveExpandedItems(href2, expandedSidebar1.contents);
        return expandedSidebar1;
    }
}
function itemHasNavTarget(item, href) {
    return item.href === href || item.href === href.replace(/index\.html$/, "");
}
function isSeparator(item) {
    return !!item && !!item.text?.match(/^\-\-\-[\-\s]*$/);
}
function nextAndPrevious(href, sidebar) {
    if (sidebar?.contents) {
        const sidebarItems = flattenItems(sidebar?.contents, (item)=>{
            return item.href !== undefined && !isExternalPath(item.href) || isSeparator(item);
        });
        const sidebarItemsUniq = __VIRTUAL_FILE210(sidebarItems, (sidebarItem)=>{
            return sidebarItem.href;
        });
        const index = sidebarItemsUniq.findIndex((item)=>item.href === href
        );
        const nextPage = index > -1 && index < sidebarItemsUniq.length - 1 && !isSeparator(sidebarItemsUniq[index + 1]) ? sidebarItemsUniq[index + 1] : undefined;
        const prevPage = index > -1 && index <= sidebarItemsUniq.length - 1 && !isSeparator(sidebarItemsUniq[index - 1]) ? sidebarItemsUniq[index - 1] : undefined;
        return {
            nextPage,
            prevPage
        };
    } else {
        return {};
    }
}
async function navbarEjsData(project, navbar) {
    const collapse = navbar.collapse !== undefined ? !!navbar.collapse : true;
    const searchOpts = searchOptions(project);
    const data56 = {
        ...navbar,
        search: searchOpts && searchOpts.location === "navbar" ? searchOpts.type : false,
        background: navbar.background || "primary",
        logo: resolveLogo(navbar.logo),
        collapse,
        [kCollapseBelow]: !collapse ? "" : "-" + (navbar[kCollapseBelow] || "lg"),
        pinned: navbar.pinned !== undefined ? !!navbar.pinned : false
    };
    if (!data56.title && data56.title !== false) {
        data56.title = websiteTitle(project.config);
    }
    data56.title = data56.title || "";
    const sidebarMenus = navbar[kSidebarMenus] !== false;
    if (navbar.left) {
        if (!Array.isArray(navbar.left)) {
            throw new Error("navbar 'left' must be an array of nav items");
        }
        data56.left = new Array();
        for(let i = 0; i < navbar.left.length; i++){
            data56.left.push(await navigationItem(project, navbar.left[i], 0, sidebarMenus));
        }
    }
    if (navbar.right) {
        if (!Array.isArray(navbar.right)) {
            throw new Error("navbar 'right' must be an array of nav items");
        }
        data56.right = new Array();
        for(let i = 0; i < navbar.right.length; i++){
            data56.right.push(await navigationItem(project, navbar.right[i], 0, sidebarMenus));
        }
    }
    if (navbar.tools) {
        await resolveSidebarTools(project, navbar.tools);
        data56.right?.push(...navbar.tools.map((tool)=>{
            const navItem = tool;
            navItem[kAriaLabel] = navItem.text;
            delete navItem.text;
            resolveIcon(navItem);
            return navItem;
        }));
    }
    return data56;
}
function resolveIcon(navItem) {
    navItem.icon = navItem.icon ? !navItem.icon.startsWith("bi-") ? `bi-${navItem.icon}` : navItem.icon : navItem.icon;
}
function resolveSidebarRef(navItem) {
    const ref8 = navItem.href || navItem.text;
    if (ref8) {
        const id = sidebarTargetId(ref8);
        if (id) {
            const sidebar = navigation.sidebars.find(sidebarHasId(id));
            if (sidebar) {
                navItem.href = undefined;
                navItem.text = sidebar.title || id;
                navItem.menu = new Array();
                for (const item of sidebar.contents){
                    if (item.text && item.contents) {
                        if (navItem.menu.length > 0) {
                            navItem.menu.push({
                                text: "---"
                            });
                        }
                        navItem.menu.push({
                            text: item.text
                        });
                        for (const subItem of item.contents){
                            const targetItem = subItem.contents?.length ? !subItem.contents[0].contents ? subItem.contents[0] : undefined : subItem;
                            if (targetItem?.href) {
                                navItem.menu.push({
                                    text: subItem.text,
                                    href: targetItem.href
                                });
                            }
                        }
                    } else if (item.href) {
                        navItem.menu.push({
                            text: item.text,
                            href: item.href
                        });
                    }
                }
            }
        }
    }
}
async function navigationItem(project, navItem, level = 0, sidebarMenus = false) {
    navItem = cloneDeep1(navItem);
    if (typeof navItem === "string") {
        const navItemPath = join3(project.dir, navItem);
        if (safeExistsSync(navItemPath) && Deno.statSync(navItemPath).isFile) {
            navItem = {
                href: navItem
            };
        } else {
            navItem = {
                text: navItem
            };
        }
    }
    resolveIcon(navItem);
    resolveHrefAttribute(navItem);
    if (level === 0 && sidebarMenus) {
        resolveSidebarRef(navItem);
    }
    if (navItem.href) {
        return await resolveItem(project, navItem.href, navItem);
    } else if (navItem.menu) {
        if (level > 0) {
            throw Error(`"${navItem.text || ""}" menu: this menu does not support sub-menus`);
        }
        for(let i = 0; i < navItem.menu.length; i++){
            navItem.menu[i] = await navigationItem(project, navItem.menu[i], level + 1, false);
        }
        return {
            ...navItem,
            id: uniqueMenuId(navItem),
            text: navItem.text || ""
        };
    } else {
        return navItem;
    }
}
const menuIds = new Map();
function resetMenuIds() {
    menuIds.clear();
}
function uniqueMenuId(navItem) {
    const id = asHtmlId(navItem.text || navItem.icon || "");
    const number6 = menuIds.get(id) || 0;
    menuIds.set(id, number6 + 1);
    return `nav-menu-${id}${number6 ? "-" + number6 : ""}`;
}
async function resolveItem(project, href, item) {
    if (!isExternalPath(href)) {
        const resolved = await resolveInputTarget(project, href);
        if (resolved) {
            const inputItem = {
                ...item,
                href: resolved.outputHref,
                text: item.text || resolved.title || basename2(resolved.outputHref)
            };
            const projType = projectType(project.config?.project?.[kProjectType]);
            if (projType.navItemText) {
                inputItem.text = await projType.navItemText(project, href, inputItem.text);
            }
            return inputItem;
        } else {
            return {
                ...item,
                href: !href.startsWith("/") ? "/" + href : href
            };
        }
    } else {
        return item;
    }
}
function sidebarTitle(sidebar, project) {
    const { navbar  } = websiteNavigationConfig(project);
    if (sidebar.title) {
        return sidebar.title;
    } else if (!sidebar.logo) {
        if (!navbar) {
            return websiteTitle(project.config);
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function resolveLogo(logo) {
    if (logo && !isExternalPath(logo) && !logo.startsWith("/")) {
        return "/" + logo;
    } else {
        return logo;
    }
}
function websiteHeadroom(project) {
    const { navbar , sidebars  } = websiteNavigationConfig(project);
    if (navbar || sidebars?.length) {
        const navbarPinned = navbar?.pinned === true;
        const anySidebarPinned = sidebars && sidebars.some((sidebar)=>sidebar.pinned === true
        );
        return !navbarPinned && !anySidebarPinned;
    } else {
        return false;
    }
}
const kDependencyName1 = "quarto-nav";
function websiteNavigationSassBundle() {
    const scssPath = navigationDependency("quarto-nav.scss").path;
    const navSassLayer = sassLayer(scssPath);
    return {
        dependency: kBootstrapDependencyName,
        key: scssPath,
        quarto: {
            ...navSassLayer,
            name: "quarto-nav.css"
        }
    };
}
function websiteNavigationDependency(project) {
    const scripts = [
        navigationDependency("quarto-nav.js")
    ];
    if (websiteHeadroom(project)) {
        scripts.push(navigationDependency("headroom.min.js"));
    }
    return {
        name: kDependencyName1,
        scripts
    };
}
function navigationDependency(resource) {
    return {
        name: basename2(resource),
        path: resourcePath(`projects/website/navigation/${resource}`)
    };
}
function isExternalPath(path96) {
    return /^\w+:/.test(path96);
}
function resolveNavReferences(collection1) {
    if (!collection1) {
        return collection1;
    }
    __VIRTUAL_FILE144(collection1, (value1, index, collection)=>{
        const assign = (value)=>{
            if (typeof index === "number") {
                collection[index] = value;
            } else if (typeof index === "string") {
                collection[index] = value;
            }
        };
        if (Array.isArray(value1)) {
            assign(resolveNavReferences(value1));
        } else if (typeof value1 === "object") {
            assign(resolveNavReferences(value1));
        } else if (typeof value1 === "string") {
            const navRef = resolveNavReference(value1);
            if (navRef) {
                const navItem = collection;
                navItem["href"] = navRef.href;
                navItem["text"] = navRef.text;
            }
        }
    });
    return collection1;
}
function resolveNavReference(href) {
    const id = sidebarTargetId(href);
    if (id) {
        const sidebar = navigation.sidebars.find(sidebarHasId(id));
        if (sidebar && sidebar.contents?.length) {
            const item = findFirstItem(sidebar.contents[0]);
            if (item) {
                return {
                    href: item.href,
                    text: sidebar.title || id
                };
            }
        }
    }
    return undefined;
}
function sidebarTargetId(href) {
    if (href) {
        const match = href.match(/^sidebar:([^\s]+).*$/);
        if (match) {
            return match[1];
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function sidebarHasId(id) {
    return (sidebar)=>{
        return sidebar.id === id;
    };
}
function findFirstItem(item) {
    if (item.contents?.length) {
        return findFirstItem(item.contents[0]);
    } else if (item.href) {
        return item;
    } else {
        return undefined;
    }
}
function readInputTargetIndexIfStillCurrent(projectDir, input) {
    const inputFile = join3(projectDir, input);
    const indexFile = inputTargetIndexFile(projectDir, input);
    if (existsSync(indexFile)) {
        const inputMod = Deno.statSync(inputFile).mtime;
        const indexMod = Deno.statSync(indexFile).mtime;
        if (inputMod && indexMod && indexMod >= inputMod) {
            try {
                return JSON.parse(Deno.readTextFileSync(indexFile));
            } catch  {
                return undefined;
            }
        }
    }
}
async function resolveInputTarget(project, href, absolute = true) {
    const index = await inputTargetIndex(project, href);
    if (index) {
        const format165 = Object.values(index.formats)[0];
        const [hrefDir, hrefStem] = dirAndStem(href);
        const outputFile = format165?.pandoc[kOutputFile] || `${hrefStem}.html`;
        const outputHref = pathWithForwardSlashes((absolute ? "/" : "") + join3(hrefDir, outputFile));
        return {
            title: index.title,
            outputHref
        };
    } else {
        return undefined;
    }
}
async function inputFileForOutputFile(project, output) {
    const outputDir = projectOutputDir(project);
    output = join3(outputDir, output);
    for (const file of project.files.input){
        const inputRelative = relative2(project.dir, file);
        const index = await inputTargetIndex(project, relative2(project.dir, file));
        if (index) {
            const hasOutput = Object.keys(index.formats).some((key)=>{
                const format166 = index.formats[key];
                if (format166.pandoc[kOutputFile]) {
                    const formatOutputPath = join3(outputDir, dirname2(inputRelative), format166.pandoc[kOutputFile]);
                    return output === formatOutputPath;
                }
            });
            if (hasOutput) {
                return file;
            }
        }
    }
}
async function inputTargetIndexForOutputFile(project, outputRelative) {
    const input = await inputFileForOutputFile(project, outputRelative);
    if (input) {
        return await inputTargetIndex(project, relative2(project.dir, input));
    } else {
        return undefined;
    }
}
function inputTargetIndexFile(projectDir, input) {
    return indexPath(projectDir, `${input}.json`);
}
function indexPath(projectDir, path97 = "") {
    return projectScratchPath(projectDir, join3("idx", path97));
}
async function updateAliases(context, outputFiles, incremental) {
    const redirectMap = {};
    const allOutputFiles = [];
    const outputDir = projectOutputDir(context);
    for (const outputFile1 of outputFiles){
        const aliases = outputFile1.format.metadata[kAliases];
        if (aliases && Array.isArray(aliases)) {
            addRedirectsToMap(aliases, outputFile1.file, outputDir, true, redirectMap);
        }
    }
    if (Object.keys(redirectMap).length > 0) {
        for (const file of context.files.input){
            const relativePath = relative2(context.dir, file);
            const inputIndexEntry = await inputTargetIndex(context, relativePath);
            if (inputIndexEntry) {
                const format167 = Object.values(inputIndexEntry.formats)[0];
                const outputTarget = await resolveInputTarget(context, relativePath, false);
                if (outputTarget) {
                    const fileFullPath = context.config?.project[kProjectOutputDir] !== undefined ? join3(context.config?.project[kProjectOutputDir], outputTarget.outputHref) : outputTarget.outputHref;
                    allOutputFiles.push(join3(context.dir, fileFullPath));
                    if (incremental) {
                        const aliases = format167.metadata[kAliases];
                        if (aliases && Array.isArray(aliases)) {
                            addRedirectsToMap(aliases, join3(outputDir, outputTarget.outputHref), outputDir, false, redirectMap);
                        }
                    }
                }
            }
        }
    }
    for (const targetFile of Object.keys(redirectMap)){
        const targetHrefs = redirectMap[targetFile];
        const redirects = {};
        for (const targetHref of targetHrefs){
            const aliasHref = relative2(dirname2(targetFile), targetHref.outputFile);
            redirects[targetHref.hash || ""] = aliasHref;
        }
        if (!existsSync(targetFile)) {
            ensureDirSync(dirname2(targetFile));
        }
        if (allOutputFiles.find((outputFile)=>outputFile === targetFile
        )) {
            warning(`Aliases that you have created would overwrite the output file ${targetFile}. The aliases file was not created.`);
        } else {
            writeMultipleRedirectPage(targetFile, redirects);
        }
    }
}
function addRedirectsToMap(aliases, outputFile, outputDir, allowNewAnchors, anchorMap) {
    for (const alias of aliases){
        const anchor = toAnchor(alias, outputFile);
        const aliasTarget = anchor.href.startsWith("/") ? join3(outputDir, anchor.href.slice(1)) : join3(dirname2(outputFile), anchor.href);
        if (allowNewAnchors && !anchorMap[aliasTarget]) {
            anchorMap[aliasTarget] = [];
        }
        if (anchorMap[aliasTarget]) {
            anchorMap[aliasTarget].push(anchor);
        }
    }
}
function toAnchor(url, outputFile) {
    const fixupHref = (href)=>{
        if (href.endsWith("/")) {
            return `${href}index.html`;
        } else if (extname2(href) === "") {
            return `${href}/index.html`;
        } else {
            return href;
        }
    };
    if (url.includes("#")) {
        const anchorParts = url.split("#");
        return {
            href: fixupHref(anchorParts[0]),
            outputFile,
            hash: anchorParts[1]
        };
    } else {
        return {
            href: fixupHref(url),
            outputFile
        };
    }
}
function writeMultipleRedirectPage(path98, redirects) {
    const redirectTemplate = resourcePath("projects/website/templates/redirect-map.ejs");
    const redirectHtml = renderEjs(redirectTemplate, {
        redirects
    });
    Deno.writeTextFileSync(path98, redirectHtml);
}
function markdownHandler(format168, listing, items) {
    switch(listing.type){
        case ListingType.Table:
            {
                return templateMarkdownHandler(resourcePath("projects/website/listing/listing-table.ejs.md"), listing, items, format168, true);
            }
        case ListingType.Grid:
            {
                return templateMarkdownHandler(resourcePath("projects/website/listing/listing-grid.ejs.md"), listing, items, format168, true);
            }
        case ListingType.Custom:
            {
                if (listing.template === undefined) {
                    throw new Error("In order to use a listing of type custom, please provide the path to a template.");
                } else {
                    if (!existsSync(listing.template)) {
                        throw new Error(`The template ${listing.template} can't be found.`);
                    }
                }
                return templateMarkdownHandler(listing.template, listing, items, format168, false);
            }
        case ListingType.Default:
        default:
            {
                return templateMarkdownHandler(resourcePath("projects/website/listing/listing-default.ejs.md"), listing, items, format168, true);
            }
    }
}
function listingPostProcess(doc, listingDescriptors, options, format169) {
    const categories = options[kFieldCategories];
    if (categories) {
        const { headingEl , categoriesEl  } = categorySidebar(doc, listingDescriptors, format169, options);
        const rightSidebar = doc.getElementById(kMarginSidebarId1);
        const marginHeader = rightSidebar?.querySelector(".quarto-margin-header");
        if (marginHeader) {
            marginHeader.after(...[
                headingEl,
                categoriesEl
            ]);
        } else {
            const marginFooter = rightSidebar?.querySelector(".quarto-margin-footer");
            if (marginFooter) {
                rightSidebar?.insertBefore(headingEl, marginFooter);
                rightSidebar?.insertBefore(categoriesEl, marginFooter);
            } else {
                rightSidebar?.appendChild(headingEl);
                rightSidebar?.appendChild(categoriesEl);
            }
        }
    }
    const descImgs = doc.querySelectorAll(".listing-description img");
    descImgs.forEach((descImg)=>{
        descImg.remove();
    });
}
const kMarginSidebarId1 = "quarto-margin-sidebar";
function scriptFileForScripts(scripts, temp) {
    const scriptFile1 = temp.createFile({
        suffix: "html"
    });
    const contents = `<script>\n${scripts.join("\n")}</script>`;
    Deno.writeTextFileSync(scriptFile1, contents);
    return scriptFile1;
}
function listingSassBundle() {
    const scssPath = resourcePath("projects/website/listing/quarto-listing.scss");
    const layer = sassLayer(scssPath);
    return {
        dependency: kBootstrapDependencyName,
        key: scssPath,
        quarto: {
            name: "quarto-listing.css",
            ...layer
        }
    };
}
function hydrateListing(format170, listing, items3, sources, options) {
    const fieldsForItems = (items)=>{
        const unionedItem = items.reduce((prev, current)=>{
            const item = {
                ...prev
            };
            for (const key of Object.keys(current)){
                if (current[key] !== undefined) {
                    item[key] = current[key];
                }
            }
            return item;
        }, {});
        return Object.keys(unionedItem).filter((key)=>{
            return unionedItem[key] !== undefined;
        });
    };
    const itemFields1 = fieldsForItems(items3);
    const suggestFields = (type, itemFields)=>{
        if (sources.size === 1 && sources.has(ListingItemSource.rawfile)) {
            return [
                kFieldFileName,
                kFieldFileModified
            ];
        } else if (sources.has(ListingItemSource.metadata)) {
            return itemFields;
        } else {
            return defaultFields(type, itemFields);
        }
    };
    const suggestedFields = suggestFields(listing.type, itemFields1);
    const fields = suggestedFields.filter((field)=>{
        return itemFields1.includes(field);
    });
    const finalFields = fields.length > 0 ? fields : itemFields1;
    const defaultSort = listing.type !== ListingType.Custom && listing.type !== ListingType.Table ? kDefaultFieldSort : suggestedFields;
    const defaultLinks = listing.type === ListingType.Table ? kDefaultFieldLinks : [];
    const defaultPageSize = ()=>{
        switch(listing.type){
            case ListingType.Table:
                return 30;
            case ListingType.Grid:
                return 18;
            default:
            case ListingType.Default:
                return 25;
        }
    };
    const hydratedFields = [
        ...finalFields
    ];
    if (options[kFieldCategories] && (listing.type === ListingType.Grid || listing.type === ListingType.Default)) {
        if (!hydratedFields.includes(kFieldCategories)) {
            hydratedFields.push(kFieldCategories);
        }
    }
    const listingHydrated = __VIRTUAL_FILE107({
        fields: hydratedFields,
        [kFieldDisplayNames]: {},
        [kFieldTypes]: kDefaultFieldTypes,
        [kFieldLinks]: defaultLinks,
        [kFieldSort]: defaultSort,
        [kFieldFilter]: hydratedFields,
        [kFieldRequired]: kDefaultFieldRequired,
        [kPageSize]: defaultPageSize(),
        [kFilterUi]: listing.type !== ListingType.Custom || listing[kFilterUi],
        [kSortUi]: listing.type !== ListingType.Custom || listing[kSortUi],
        ...listing
    });
    const sort = hydratedFields.includes(kFieldTitle) ? [
        {
            field: "title",
            direction: "asc"
        }
    ] : undefined;
    if (sort && !listingHydrated.sort && sources.has(ListingItemSource.document)) {
        listingHydrated.sort = sort;
    }
    const sortUi = listingHydrated[kSortUi];
    if (sortUi && Array.isArray(sortUi)) {
        listingHydrated[kFieldSort] = sortUi;
    }
    const filterUi = listingHydrated[kFilterUi];
    if (filterUi && Array.isArray(filterUi)) {
        listingHydrated[kFieldFilter] = filterUi;
    }
    if (listing.type === ListingType.Grid) {
        listingHydrated[kGridColumns] = listingHydrated[kGridColumns] || 3;
        listingHydrated[kImageHeight1] = listingHydrated[kImageHeight1] || "150px";
        listingHydrated[kMaxDescLength] = listingHydrated[kMaxDescLength] || 175;
    } else if (listing.type === ListingType.Default) {
        listingHydrated[kImageAlign] = listingHydrated[kImageAlign] || "right";
    } else if (listing.type === ListingType.Table) {
        listingHydrated[kImageHeight1] = listingHydrated[kImageHeight1] || "40px";
        listingHydrated[kTableStriped] = listingHydrated[kTableStriped] !== undefined ? listingHydrated[kTableStriped] : false;
        listingHydrated[kTableHover] = listingHydrated[kTableHover] !== undefined ? listingHydrated[kTableHover] : false;
    }
    listingHydrated[kFieldTypes] = {
        ...listingHydrated[kFieldTypes],
        ...listing[kFieldTypes]
    };
    listingHydrated[kFieldDisplayNames] = {
        ...defaultFieldDisplayNames(format170),
        ...listing[kFieldDisplayNames]
    };
    return listingHydrated;
}
async function readContents(source, project, listing) {
    const listingItems = [];
    const listingItemSources = new Set();
    const inputsWithoutSource = project.files.input.filter((file)=>file !== source
    );
    const yamlFiles = projectYamlFiles(dirname2(source));
    const possibleListingFiles = [
        ...inputsWithoutSource,
        ...yamlFiles, 
    ];
    const filterListingFiles = (globOrPath)=>{
        const expanded = expandGlob(source, project, globOrPath);
        if (isGlob(expanded.glob)) {
            if (expanded.inputs) {
                return filterPaths(dirname2(source), possibleListingFiles, [
                    expanded.glob
                ]);
            } else {
                return resolvePathGlobs(dirname2(source), [
                    expanded.glob
                ], [
                    "_*",
                    ".*",
                    "**/_*",
                    "**/.*"
                ]);
            }
        } else {
            const fullPath = join3(dirname2(source), expanded.glob);
            const matchingFiles = possibleListingFiles.filter((file)=>{
                return file === fullPath;
            });
            return {
                include: matchingFiles,
                exclude: []
            };
        }
    };
    for (const content of listing.contents){
        if (typeof content === "string") {
            const files = filterListingFiles(content);
            for (const file of files.include){
                if (!files.exclude.includes(file)) {
                    if (isYamlPath(file)) {
                        const yaml = readYaml(file);
                        if (Array.isArray(yaml)) {
                            const items = yaml;
                            items.forEach((item)=>{
                                if (typeof item === "object") {
                                    const listingItem = listItemFromMeta(item);
                                    validateItem(listing, listingItem, (field)=>{
                                        return `An item from the file '${file}' is missing the required field '${field}'.`;
                                    });
                                    listingItemSources.add(ListingItemSource.metadata);
                                    listingItems.push(listingItem);
                                } else {
                                    throw new Error(`Unexpected listing contents in file ${file}. The array may only contain listing items, not paths or other types of data.`);
                                }
                            });
                        } else if (typeof yaml === "object") {
                            const listingItem = listItemFromMeta(yaml);
                            validateItem(listing, listingItem, (field)=>{
                                return `The item defined in file '${file}' is missing the required field '${field}'.`;
                            });
                            listingItemSources.add(ListingItemSource.metadata);
                            listingItems.push(listingItem);
                        } else {
                            throw new Error(`Unexpected listing contents in file ${file}. The file should contain only one more listing items.`);
                        }
                    } else {
                        const item = await listItemFromFile(file, project);
                        if (item) {
                            validateItem(listing, item, (field)=>{
                                return `The file ${file} is missing the required field '${field}'.`;
                            });
                            listingItemSources.add(item.source);
                            listingItems.push(item.item);
                        }
                    }
                }
            }
        } else {
            const listingItem = listItemFromMeta(content);
            validateItem(listing, listingItem, (field)=>{
                return `An item in the listing '${listing.id}' is missing the required field '${field}'.`;
            });
            listingItemSources.add(ListingItemSource.metadata);
            listingItems.push(listingItem);
        }
    }
    return {
        items: listingItems,
        sources: listingItemSources
    };
}
function validateItem(listing2, item, message) {
    const requiredFields = (listing)=>{
        const fields = listing[kFieldRequired];
        if (fields) {
            if (Array.isArray(fields)) {
                return fields;
            } else {
                return [
                    fields
                ];
            }
        } else {
            return undefined;
        }
    };
    const validationFields = requiredFields(listing2);
    if (validationFields) {
        validationFields.forEach((requiredField)=>{
            if (item[requiredField] === undefined) {
                throw new Error(message(requiredField));
            }
        });
    }
}
function listItemFromMeta(meta) {
    const listingItem = __VIRTUAL_FILE107(meta);
    if (meta.path !== undefined) {
        meta[kFieldFileName] = basename2(meta.path);
        meta[kFieldFileModified] = fileModifiedDate(meta.path);
    }
    if (meta.author) {
        if (!Array.isArray(meta.author)) {
            meta.author = [
                meta.author
            ];
        }
    }
    return listingItem;
}
async function listItemFromFile(input, project) {
    const projectRelativePath = relative2(project.dir, input);
    const target = await inputTargetIndex(project, projectRelativePath);
    const documentMeta = target?.markdown.yaml;
    if (documentMeta?.draft) {
        return undefined;
    } else {
        const filename = basename2(projectRelativePath);
        const filemodified = fileModifiedDate(input);
        const description = documentMeta?.description || documentMeta?.abstract || findDescriptionMd(target?.markdown.markdown);
        const imageRaw = documentMeta?.image || findPreviewImgMd(target?.markdown.markdown);
        const image6 = imageRaw !== undefined ? listingItemHref(imageRaw, dirname2(projectRelativePath)) : undefined;
        const date = documentMeta?.date ? new Date(documentMeta.date) : undefined;
        const authors = parseAuthor(documentMeta?.author);
        const author = authors ? authors.map((auth)=>auth.name
        ) : [];
        const readingtime = target?.markdown ? estimateReadingTimeMinutes(target.markdown.markdown) : undefined;
        const categories = documentMeta?.categories ? Array.isArray(documentMeta?.categories) ? documentMeta?.categories : [
            documentMeta?.categories
        ] : undefined;
        const item = {
            ...documentMeta,
            path: `/${projectRelativePath}`,
            [kFieldTitle]: target?.title,
            [kFieldDate]: date,
            [kFieldAuthor]: author,
            [kFieldCategories]: categories,
            [kFieldImage]: image6,
            [kFieldDescription]: description,
            [kFieldFileName]: filename,
            [kFieldFileModified]: filemodified,
            [kFieldReadingTime]: readingtime
        };
        return {
            item,
            source: target !== undefined ? ListingItemSource.document : ListingItemSource.rawfile
        };
    }
}
function readDehydratedListings(source, format171) {
    const listingConfig = format171.metadata[kListing];
    const listings = [];
    if (typeof listingConfig == "string") {
        const listing = listingForType(listingType(listingConfig));
        if (listing) {
            listings.push(listing);
        }
    } else if (Array.isArray(listingConfig)) {
        const listingConfigs = listingConfig.filter((listing)=>typeof listing === "object"
        );
        let count = 0;
        listings.push(...listingConfigs.map((listing)=>{
            return listingForMetadata(listing, ()=>{
                count = count + 1;
                return `${kDefaultId}-${count}`;
            }, source);
        }));
    } else if (listingConfig && typeof listingConfig === "object") {
        listings.push(listingForMetadata(listingConfig, ()=>{
            return kDefaultId;
        }, source));
    } else if (listingConfig) {
        listings.push(listingForType(ListingType.Default));
    }
    return listings;
}
function listingForMetadata(meta, synthId, source) {
    const listingType1 = meta.type || kDefaultListingType;
    const baseListing = listingForType(listingType1);
    const ensureArray = (val)=>{
        if (Array.isArray(val)) {
            return val;
        } else {
            return [
                val
            ];
        }
    };
    const listing = {
        ...baseListing,
        ...meta
    };
    listing.id = meta.id || synthId();
    listing.sort = computeListingSort(meta.sort);
    if (meta.contents) {
        listing.contents = ensureArray(meta.contents);
    }
    if (meta.template && typeof meta.template === "string") {
        listing.type = ListingType.Custom;
        listing.template = join3(dirname2(source), meta.template);
    }
    return listing;
}
function computeListingSort(rawValue) {
    const parseValue = (sortValue)=>{
        if (sortValue == undefined) {
            return undefined;
        }
        if (typeof sortValue === "string") {
            const sortStr = sortValue;
            const parts = sortStr.split(" ");
            if (parts.length === 2) {
                return {
                    field: parts[0],
                    direction: parts[1] === kSortAsc ? kSortAsc : kSortDesc
                };
            } else {
                return {
                    field: parts[0],
                    direction: kSortAsc
                };
            }
        }
    };
    if (Array.isArray(rawValue)) {
        return rawValue.map(parseValue).filter((val)=>val !== undefined
        );
    } else {
        const sort = parseValue(rawValue);
        if (sort) {
            return [
                sort
            ];
        }
    }
    return undefined;
}
function defaultFields(type, itemFields) {
    switch(type){
        case ListingType.Grid:
            return kDefaultGridFields;
        case ListingType.Table:
            return kDefaultTableFields;
        case ListingType.Custom:
            return itemFields;
        case ListingType.Default:
        default:
            return kDefaultFields;
    }
}
function listingType(val) {
    switch(val){
        case ListingType.Grid:
        case ListingType.Default:
        case ListingType.Table:
            return val;
        default:
            return ListingType.Default;
    }
}
function listingForType(type) {
    const listing = {
        id: kDefaultId,
        type: type,
        contents: kDefaultContentsGlob
    };
    return listing;
}
function fileModifiedDate(input) {
    if (existsSync(input)) {
        const fileInfo = Deno.statSync(input);
        return fileInfo.mtime !== null ? fileInfo.mtime : undefined;
    } else {
        return undefined;
    }
}
function listingItemHref(path99, projectRelativePath) {
    if (isAbsoluteRef(path99) || path99.startsWith("/")) {
        return path99;
    } else {
        return join3("/", projectRelativePath, path99);
    }
}
function expandGlob(source, project, globOrPath) {
    const getPath = ()=>{
        if (globOrPath.startsWith("/")) {
            return join3(project.dir, globOrPath);
        } else {
            const sourcePath = dirname2(source);
            return join3(sourcePath, globOrPath);
        }
    };
    const globOrPathAsPath = getPath();
    try {
        if (Deno.statSync(globOrPathAsPath).isDirectory) {
            return {
                glob: join3(globOrPath, "**"),
                inputs: true
            };
        } else {
            return {
                glob: globOrPath,
                inputs: false
            };
        }
    } catch  {
        return {
            glob: globOrPath,
            inputs: false
        };
    }
}
async function renderCategoryFeed(siteUrl, categoryToRender, feed, items, options, project) {
    const categoryItems = items.filter((item)=>{
        const categories = item[kFieldCategories];
        if (categories) {
            return categories.includes(categoryToRender.category);
        } else {
            return false;
        }
    });
    const filteredItems = prepareItems(categoryItems, options);
    const feedMeta = {
        ...feed
    };
    feedMeta.link = feedMeta.link + "#category=" + encodeURI(categoryToRender.category);
    feedMeta.feedLink = categoryToRender.feedLink;
    if (feedMeta.image) {
        feedMeta.image.link = feedMeta.link;
        feedMeta.image.title = feedMeta.title;
    }
    const mostRecent = mostRecentItem(filteredItems);
    feedMeta.lastBuildDate = mostRecent && mostRecent.date ? new Date(mostRecent.date).toUTCString() : new Date().toUTCString();
    return await renderFeed(siteUrl, feedMeta, filteredItems, project, categoryToRender.file);
}
async function renderFeed(siteUrl, feed, items, project, feedPath1) {
    const feedItems = [];
    for (const item of items){
        const inputTarget = await resolveInputTarget(project, item.path, false);
        const title23 = inputTarget?.outputHref ? placeholder(inputTarget?.outputHref) : "";
        const link6 = `${siteUrl}${inputTarget?.outputHref}`;
        const description = inputTarget?.outputHref ? placeholder(inputTarget?.outputHref) : "";
        const pubDate = item.date ? new Date(item.date) : new Date();
        const feedItem = {
            title: title23,
            link: link6,
            description,
            guid: link6,
            pubDate
        };
        if (Array.isArray(item[kFieldCategories])) {
            feedItem.categories = item[kFieldCategories];
        }
        if (Array.isArray(item[kFieldAuthor])) {
            feedItem.authors = item[kFieldAuthor];
        }
        if (item[kFieldImage] && typeof (item[kFieldImage] === "string")) {
            const image7 = item[kFieldImage];
            feedItem.image = absoluteUrl(siteUrl, image7);
            const imagePath = join3(project.dir, image7);
            feedItem.imageContentType = imageContentType(imagePath);
            const size = imageSize(imagePath);
            if (size) {
                const [height, width] = feedImageSize(size.height, size.width);
                feedItem.imageHeight = height;
                feedItem.imageWidth = width;
            }
        }
        feedItems.push(feedItem);
    }
    await generateFeed(feed, feedItems, feedPath1);
    return true;
}
async function generateFeed(feed, feedItems, path100) {
    const feedFile = await Deno.open(path100, {
        write: true,
        create: true
    });
    const textEncoder = new TextEncoder();
    const preamble = renderEjs(resourcePath("projects/website/listing/feed/preamble.ejs.md"), {
        feed
    });
    await Deno.write(feedFile.rid, textEncoder.encode(preamble));
    for (const feedItem of feedItems){
        const item = renderEjs(resourcePath("projects/website/listing/feed/item.ejs.md"), {
            item: feedItem
        });
        await Deno.write(feedFile.rid, textEncoder.encode(item));
    }
    const postamble = renderEjs(resourcePath("projects/website/listing/feed/postamble.ejs.md"), {
        feed
    });
    await Deno.write(feedFile.rid, textEncoder.encode(postamble));
}
function prepareItems(items, options) {
    const validItems = items.filter((item)=>{
        return item.title !== undefined && item.path !== undefined;
    });
    const uniqueItems = __VIRTUAL_FILE210(validItems, (item)=>{
        return item.path;
    });
    const sortedItems = uniqueItems.sort((a, b)=>{
        const aTimestamp = a.date ? new Date(a.date).valueOf() : -1;
        const bTimestamp = b.date ? new Date(b.date).valueOf() : -1;
        return bTimestamp - aTimestamp;
    });
    const itemCount2 = options[kItems] || 20;
    if (sortedItems.length > itemCount2) {
        return sortedItems.slice(0, itemCount2);
    } else {
        return sortedItems;
    }
}
function mostRecentItem(items) {
    const sortedItems = items.sort((a, b)=>{
        const aTime = a.date ? a.date.getTime() : 0;
        const bTime = b.date ? b.date.getTime() : 0;
        return bTime - aTime;
    });
    const mostRecentItem1 = sortedItems.length > 0 ? sortedItems[0] : undefined;
    return mostRecentItem1;
}
function addLinkTagToDocument(doc, feed, path101) {
    const linkEl = doc.createElement("link");
    linkEl.setAttribute("rel", "alternate");
    linkEl.setAttribute("type", "application/rss+xml");
    linkEl.setAttribute("title", feed.title);
    linkEl.setAttribute("href", path101);
    doc.head.appendChild(linkEl);
}
const kFullStagedExt = "feed-full-staged";
const kPartialStageExt = "feed-partial-staged";
const kFinalExt = "xml";
const kStagedFileGlob = "*.feed-*-staged";
function placeholder(outputHref) {
    return `{B4F502887207:${outputHref}}`;
}
function placholderForReplace(tag, outputHref) {
    return `<${tag}>{B4F502887207\:${outputHref}}<\/${tag}>`;
}
const kTitleRegex = tagplaceholderRegex("title");
const kDescRegex = tagplaceholderRegex("description");
function tagplaceholderRegex(tag) {
    return new RegExp(`<${tag}>{B4F502887207\:(.*?)}<\/${tag}>`, "gm");
}
function feedPath(dir, stem, full) {
    const ext = full ? kFullStagedExt : kPartialStageExt;
    const file = `${stem}.${ext}`;
    return join3(dir, file);
}
const renderedContentReader = (project, siteUrl)=>{
    const renderedContent = {};
    return (filePath)=>{
        if (!renderedContent[filePath]) {
            renderedContent[filePath] = readRenderedContents(filePath, siteUrl, project);
        }
        return renderedContent[filePath];
    };
};
function readRenderedContents(filePath, siteUrl, project) {
    const htmlInput = Deno.readTextFileSync(filePath);
    const doc = new DOMParser().parseFromString(htmlInput, "text/html");
    const fileRelPath = relative2(projectOutputDir(project), filePath);
    const fileRelFolder = dirname2(fileRelPath);
    const mainEl = doc.querySelector("main.content");
    const titleEl = doc.getElementById("title-block-header");
    const titleText = titleEl?.querySelector("h1.title")?.innerText;
    if (titleEl) {
        titleEl.remove();
    }
    const navEls = doc.querySelectorAll("nav");
    if (navEls) {
        for (const navEl of navEls){
            navEl.remove();
        }
    }
    const imgNodes = doc.querySelectorAll("img");
    if (imgNodes) {
        for (const imgNode of imgNodes){
            const imgEl = imgNode;
            let src = imgEl.getAttribute("src");
            if (src) {
                if (!src.startsWith("/")) {
                    src = join3(fileRelFolder, src);
                }
                imgEl.setAttribute("src", absoluteUrl(siteUrl, src));
            }
        }
    }
    const stripSelectors = [
        '*[aria-hidden="true"]',
        "button.code-copy-button"
    ];
    stripSelectors.forEach((sel)=>{
        const nodes = doc.querySelectorAll(sel);
        nodes?.forEach((node)=>{
            node.remove();
        });
    });
    const stripAttrs = [
        "role", 
    ];
    stripAttrs.forEach((attr)=>{
        const nodes = doc.querySelectorAll(`[${attr}]`);
        nodes?.forEach((node)=>{
            const el = node;
            el.removeAttribute(attr);
        });
    });
    const relativeLinkSel = 'a[href^="#"]';
    const linkNodes = doc.querySelectorAll(relativeLinkSel);
    linkNodes.forEach((linkNode)=>{
        const nodesToMove = linkNode.childNodes;
        linkNode.after(...nodesToMove);
        linkNode.remove();
    });
    const highlightingMap = defaultSyntaxHighlightingClassMap();
    const spanNodes = doc.querySelectorAll("code span");
    for (const spanNode of spanNodes){
        const spanEl = spanNode;
        for (const clz of spanEl.classList){
            const styles = highlightingMap[clz];
            if (styles) {
                spanEl.setAttribute("style", styles.join("\n"));
                break;
            }
        }
    }
    const codeStyle = "background: #f1f3f5;";
    const codeBlockNodes = doc.querySelectorAll("div.sourceCode");
    for (const codeBlockNode of codeBlockNodes){
        const codeBlockEl = codeBlockNode;
        codeBlockEl.setAttribute("style", codeStyle);
    }
    const trimMath = (str77)=>{
        if (str77.length > 4 && (str77.startsWith("\\[") || str77.startsWith("\\("))) {
            const trimStart = str77.slice(2);
            return trimStart.slice(0, trimStart.length - 2);
        } else {
            return str77;
        }
    };
    const mathNodes = doc.querySelectorAll("span.math");
    for (const mathNode of mathNodes){
        const mathEl = mathNode;
        const math = trimMath(mathEl.innerText);
        const imgEl = doc.createElement("IMG");
        imgEl.setAttribute("src", kWebTexUrl(math));
        mathNode.parentElement?.replaceChild(imgEl, mathNode);
    }
    return {
        title: titleText,
        fullContents: mainEl?.innerHTML,
        firstPara: mainEl?.querySelector("p")?.innerHTML
    };
}
const kWebTexUrl = (math, type = "png")=>{
    const encodedMath = encodeURI(math);
    return `https://latex.codecogs.com/${type}.latex?${encodedMath}`;
};
const absoluteUrl = (siteUrl, url)=>{
    if (url.startsWith("http:") || url.startsWith("https:")) {
        return url;
    } else {
        return `${siteUrl}/${url}`;
    }
};
const feedImageSize = (height, width)=>{
    const heightScale = 400 / height;
    const widthScale = 144 / width;
    if (heightScale >= 1 && widthScale >= 1) {
        return [
            height,
            width
        ];
    } else {
        const scaleFactor = heightScale < widthScale ? heightScale : widthScale;
        return [
            Math.round(height * scaleFactor),
            Math.round(width * scaleFactor), 
        ];
    }
};
async function readAbout(source, project, format172) {
    const about = format172.metadata[kAbout];
    if (about) {
        const resolveOptions = (aboutTemplate, aboutObj, aboutPage)=>{
            const knownFieldList = [
                "image",
                "template",
                "links"
            ];
            for (const key of Object.keys(aboutObj)){
                if (!knownFieldList.includes(key)) {
                    aboutPage.options[key] = aboutObj[key];
                }
            }
            if (aboutPage.options[kImageShape] === undefined) {
                if (aboutTemplate === kTemplateJolla) {
                    aboutPage.options[kImageShape] = kImageShapeRound;
                } else if (aboutTemplate === kTemplateSolana) {
                    aboutPage.options[kImageShape] = kImageShapeRounded;
                } else if (aboutTemplate === kTemplateTrestles) {
                    aboutPage.options[kImageShape] = kImageShapeRounded;
                }
            }
            if (aboutPage.options[kImageWidth1] === undefined) {
                if (aboutTemplate === kTemplateJolla) {
                    aboutPage.options[kImageWidth1] = "15em";
                } else if (aboutTemplate === kTemplateSolana) {
                    aboutPage.options[kImageWidth1] = "15em";
                } else if (aboutTemplate === kTemplateTrestles) {
                    aboutPage.options[kImageWidth1] = "20em";
                } else if (aboutTemplate === kTemplateMarquee) {
                    aboutPage.options[kImageWidth1] = "100%";
                } else if (aboutTemplate === kTemplateBroadside) {
                    aboutPage.options[kImageWidth1] = "15em";
                }
            }
            return aboutPage;
        };
        if (typeof about === "string") {
            const [template16, custom] = templatePath(about, source);
            const aboutPage = {
                template: template16,
                custom,
                options: {}
            };
            if (format172.metadata[kImage]) {
                aboutPage.image = format172.metadata[kImage];
            }
            resolveOptions(about, {}, aboutPage);
            return aboutPage;
        } else if (typeof about === "object") {
            const aboutObj = about;
            const aboutTemplate = aboutObj[kType2] || aboutObj[kTemplate1];
            const [template17, custom] = templatePath(aboutTemplate, source);
            const aboutPage = {
                template: template17,
                custom,
                options: {}
            };
            const aboutImage = aboutObj[kImage];
            if (aboutImage) {
                aboutPage.image = aboutImage;
            } else {
                if (format172.metadata[kImage]) {
                    aboutPage.image = format172.metadata[kImage];
                }
            }
            const aboutLinks = aboutObj[kLinks];
            if (aboutLinks) {
                const links = [];
                for (const aboutLink of aboutLinks){
                    links.push(await navigationItem(project, aboutLink, 0, false));
                }
                aboutPage.links = links;
            }
            resolveOptions(aboutTemplate, aboutObj, aboutPage);
            return aboutPage;
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function templatePath(template18, source) {
    if (kTemplates.includes(template18)) {
        return [
            join3(projectTypeResourcePath("website"), `about/${template18}.ejs.html`),
            false, 
        ];
    } else {
        return [
            join3(dirname2(source), template18),
            true
        ];
    }
}
const aboutPagePostProcessor = (aboutPage)=>{
    return (doc)=>{
        const titleEl = doc.getElementById("title-block-header");
        titleEl?.remove();
        const title24 = titleEl?.outerHTML || "";
        const mainEl = doc.querySelector("main.content");
        const body = mainEl?.outerHTML || "";
        const ejsData = {
            title: title24,
            body,
            image: aboutPage.image,
            links: aboutPage.links,
            options: aboutPage.options
        };
        const aboutPageHtml = renderEjs(aboutPage.template, {
            about: ejsData
        }, true, !aboutPage.custom && !quartoConfig.isDebug());
        const aboutPageContainer = doc.createElement("div");
        aboutPageContainer.innerHTML = aboutPageHtml;
        mainEl?.after(...aboutPageContainer.childNodes);
        mainEl?.remove();
        const result = {
            resources: [],
            supporting: []
        };
        if (aboutPage.image) {
            result.resources.push(aboutPage.image);
        }
        return Promise.resolve(result);
    };
};
function title(format173) {
    const site = format173.metadata[kWebsite];
    if (site && site[kTitle] && typeof site[kTitle] !== "object") {
        return String(site[kTitle]);
    } else if (format173.metadata[kTitle] && typeof format173.metadata[kTitle] !== "object") {
        return String(format173.metadata[kTitle]);
    }
}
const sidebarTitleHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.sidebar?.title) {
                return {
                    inlines: {
                        [kSidebarTitleId]: context.sidebar.title
                    }
                };
            } else {
                const mainTitle = title(context.format);
                if (mainTitle) {
                    return {
                        inlines: {
                            [kSidebarTitleId]: mainTitle
                        }
                    };
                }
            }
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kSidebarTitleId];
            if (renderedEl) {
                const sidebarTitleEl = doc.querySelector("#quarto-sidebar .sidebar-title a") || doc.querySelector("#quarto-sidebar .sidebar-title");
                if (sidebarTitleEl && sidebarTitleEl.innerText) {
                    sidebarTitleEl.innerHTML = renderedEl.innerHTML;
                }
            }
        }
    };
};
const navbarTitleHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.navigation?.navbar?.title) {
                return {
                    inlines: {
                        [kNavbarTitleId]: context.navigation.navbar.title
                    }
                };
            } else {
                const mainTitle = title(context.format);
                if (mainTitle) {
                    return {
                        inlines: {
                            [kNavbarTitleId]: mainTitle
                        }
                    };
                }
            }
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kNavbarTitleId];
            if (renderedEl) {
                const navbarTitleEl = doc.querySelector("#quarto-header .navbar-brand .navbar-title");
                if (navbarTitleEl && navbarTitleEl.innerText) {
                    navbarTitleEl.innerHTML = renderedEl.innerHTML;
                }
            }
        }
    };
};
const nextPageTitleHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.pageNavigation.nextPage?.text) {
                return {
                    inlines: {
                        [kNavNextId]: context.pageNavigation.nextPage.text
                    }
                };
            }
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kNavNextId];
            if (renderedEl) {
                const el = doc.querySelector(`.page-navigation .nav-page-next a .nav-page-text`);
                if (el) {
                    el.innerHTML = renderedEl.innerHTML;
                }
            }
        }
    };
};
const prevPageTitleHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.pageNavigation.prevPage?.text) {
                return {
                    inlines: {
                        [kNavPrevId]: context.pageNavigation.prevPage.text
                    }
                };
            }
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kNavPrevId];
            if (renderedEl) {
                const el = doc.querySelector(`.page-navigation .nav-page-previous a .nav-page-text`);
                if (el) {
                    el.innerHTML = renderedEl.innerHTML;
                }
            }
        }
    };
};
const sidebarContentsHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.sidebar?.contents) {
                const sidebarItems = flattenItems(context.sidebar?.contents, (_)=>{
                    return true;
                });
                const markdown = {};
                sidebarItems.forEach((item)=>{
                    if (item.text) {
                        if (item.sectionId) {
                            markdown[`${kSidebarIdPrefix}${item.sectionId}`] = item.text;
                        } else {
                            markdown[`${kSidebarIdPrefix}${item.href}`] = item.text;
                        }
                    }
                });
                return {
                    inlines: markdown
                };
            }
        },
        processRendered (rendered, doc) {
            const sidebarItemEls = doc.querySelectorAll(".sidebar-item:not(.sidebar-item-section) .sidebar-item-text");
            for(let i = 0; i < sidebarItemEls.length; i++){
                const link7 = sidebarItemEls[i];
                const href = link7.getAttribute("href");
                const sidebarText = rendered[`${kSidebarIdPrefix}${href}`];
                if (sidebarText) {
                    link7.innerHTML = sidebarText.innerHTML;
                }
            }
            const sidebarSectionEls = doc.querySelectorAll(".sidebar-item.sidebar-item-section .sidebar-item-text");
            for(let i1 = 0; i1 < sidebarSectionEls.length; i1++){
                const link8 = sidebarSectionEls[i1];
                const target = link8.getAttribute("data-bs-target");
                if (target) {
                    const id = target.slice(1);
                    const sectionText = rendered[`${kSidebarIdPrefix}${id}`];
                    if (sectionText) {
                        link8.innerHTML = sectionText.innerHTML;
                    }
                }
            }
        }
    };
};
const navbarContentsHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.navigation?.navbar) {
                const markdown = {};
                const entries = [
                    ...context.navigation.navbar.left || [],
                    ...context.navigation.navbar.right || [], 
                ];
                const addEntry = (entry)=>{
                    if (entry.text) {
                        markdown[`${kNavbarIdPrefix}${entry.text.trim()}`] = entry.text;
                    }
                    if (entry.menu?.entries) {
                        for (const childEntry of entry.menu){
                            addEntry(childEntry);
                        }
                    }
                };
                entries.forEach((entry)=>{
                    addEntry(entry);
                });
                return {
                    inlines: markdown
                };
            }
        },
        processRendered (rendered, doc) {
            const selectors = [
                ".navbar-nav .nav-item a.nav-link",
                ".navbar-nav .dropdown-menu .dropdown-item .dropdown-text",
                ".navbar-nav .dropdown-menu .dropdown-header", 
            ];
            selectors.forEach((selector)=>{
                const navItemEls = doc.querySelectorAll(selector);
                for(let i = 0; i < navItemEls.length; i++){
                    const link9 = navItemEls[i];
                    const id = link9.innerText.trim();
                    if (id) {
                        const renderedEl = rendered[`${kNavbarIdPrefix}${id}`];
                        if (renderedEl) {
                            link9.innerHTML = renderedEl?.innerHTML;
                        }
                    }
                }
            });
        }
    };
};
const toHeaderFooterMarkdown = (source, prefix, content)=>{
    const markdown = content.map((con)=>{
        return expandMarkdown(source, prefix, con);
    });
    return markdown.reduce((previousValue, currentValue)=>{
        return `${previousValue}\n:::{.${prefix}-item}\n${currentValue}\n:::\n`;
    }, "");
};
const toHeaderFooterContainer = (doc, prefix, contentEl)=>{
    const containerEl = doc.createElement("div");
    containerEl.classList.add(`quarto-${prefix}`);
    for (const child of contentEl.children){
        containerEl.appendChild(child);
    }
    return containerEl;
};
const sidebarHeaderFooterHandler = (context)=>{
    const kSidebarHeader = "sidebar-header";
    const kSidebarFooter = "sidebar-footer";
    return {
        getUnrendered () {
            const result = {};
            if (context.sidebar?.header) {
                if (context.sidebar?.header && context.sidebar?.header.length > 0) {
                    result[kSidebarHeader] = toHeaderFooterMarkdown(context.source, kSidebarHeader, context.sidebar.header);
                }
            }
            if (context.sidebar?.footer) {
                if (context.sidebar?.footer && context.sidebar?.footer.length > 0) {
                    result[kSidebarFooter] = toHeaderFooterMarkdown(context.source, kSidebarFooter, context.sidebar.footer);
                }
            }
            return {
                blocks: result
            };
        },
        processRendered (rendered, doc) {
            const sidebarEl = doc.getElementById("quarto-sidebar");
            if (sidebarEl) {
                const renderedHeaderEl = rendered[kSidebarHeader];
                if (renderedHeaderEl) {
                    const headerEl = toHeaderFooterContainer(doc, kSidebarHeader, renderedHeaderEl);
                    sidebarEl.insertBefore(headerEl, sidebarEl.firstChild);
                }
                const renderedFooterEl = rendered[kSidebarFooter];
                if (renderedFooterEl) {
                    const footerEl = toHeaderFooterContainer(doc, kSidebarFooter, renderedFooterEl);
                    sidebarEl.appendChild(footerEl);
                }
            }
        }
    };
};
const bodyHeaderFooterHandler = (context)=>{
    return {
        getUnrendered () {
            const result = {};
            if (context.bodyDecorators?.header) {
                result[kBodyHeader] = toHeaderFooterMarkdown(context.source, kBodyHeader, context.bodyDecorators?.header);
            }
            if (context.bodyDecorators?.footer) {
                result[kBodyFooter] = toHeaderFooterMarkdown(context.source, kBodyFooter, context.bodyDecorators?.footer);
            }
            return {
                blocks: result
            };
        },
        processRendered (rendered, doc) {
            const mainEl = doc.querySelector("main");
            if (mainEl) {
                const renderedHeaderEl = rendered[kBodyHeader];
                if (renderedHeaderEl) {
                    const headerEl = renderedHeaderEl.querySelector(`.${kBodyHeader}-item`);
                    if (headerEl) {
                        const titleBlock = mainEl.querySelector("#title-block-header");
                        const insertBefore = titleBlock?.nextElementSibling || mainEl.childNodes[0] || null;
                        for (const child of headerEl.children){
                            if (insertBefore) {
                                mainEl.insertBefore(child, insertBefore);
                            } else {
                                mainEl.appendChild(child);
                            }
                        }
                    }
                }
                const renderedFooterEl = rendered[kBodyFooter];
                if (renderedFooterEl) {
                    const footerEl = renderedFooterEl.querySelector(`.${kBodyFooter}-item`);
                    if (footerEl) {
                        for (const child of footerEl.children){
                            mainEl.appendChild(child);
                        }
                    }
                }
            }
        }
    };
};
const marginHeaderFooterHandler = (context)=>{
    return {
        getUnrendered () {
            const result = {};
            if (context.navigation?.pageMargin) {
                const projectHeaders = context.navigation.pageMargin.header;
                const pageHeaderRaw = context.format.metadata[kMarginHeader];
                const pageHeaders = pageHeaderRaw !== undefined ? Array.isArray(pageHeaderRaw) ? pageHeaderRaw : [
                    pageHeaderRaw
                ] : [];
                const marginHeaders = [
                    ...projectHeaders || [],
                    ...pageHeaders || [], 
                ];
                if (marginHeaders && marginHeaders.length > 0) {
                    result[kMarginHeader] = toHeaderFooterMarkdown(context.source, kMarginHeader, marginHeaders);
                }
                const projectFooters = context.navigation.pageMargin.footer;
                const pageFooterRaw = context.format.metadata[kMarginFooter];
                const pageFooters = pageFooterRaw !== undefined ? Array.isArray(pageFooterRaw) ? pageFooterRaw : [
                    pageFooterRaw
                ] : [];
                const marginFooters = [
                    ...projectFooters || [],
                    ...pageFooters || [], 
                ].filter((item)=>item !== undefined
                );
                if (marginFooters && marginFooters.length > 0) {
                    result[kMarginFooter] = toHeaderFooterMarkdown(context.source, kMarginFooter, marginFooters);
                }
            }
            return {
                blocks: result
            };
        },
        processRendered (rendered, doc) {
            const sidebarEl = doc.getElementById("quarto-margin-sidebar");
            if (sidebarEl) {
                const renderedHeaderEl = rendered[kMarginHeader];
                if (renderedHeaderEl) {
                    const headerEl = toHeaderFooterContainer(doc, kMarginHeader, renderedHeaderEl);
                    sidebarEl.insertBefore(headerEl, sidebarEl.firstChild);
                }
                const renderedFooterEl = rendered[kMarginFooter];
                if (renderedFooterEl) {
                    const footerEl = toHeaderFooterContainer(doc, kMarginFooter, renderedFooterEl);
                    sidebarEl.appendChild(footerEl);
                }
            }
        }
    };
};
const kNavFooterPrefix = "footer-";
const footerHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.navigation?.footer) {
                const markdown = {};
                const addEntry = (key, value)=>{
                    if (typeof value === "string") {
                        markdown[`${kNavFooterPrefix}${key}`] = value;
                    } else {
                        value.forEach((navItem)=>{
                            if (typeof navItem === "object") {
                                if (navItem.text) {
                                    markdown[`${kNavFooterPrefix}${key}-${navItem.href || navItem.text}`] = navItem.text;
                                }
                            }
                        });
                    }
                };
                if (context.navigation.footer.left) {
                    addEntry("left", context.navigation.footer.left);
                }
                if (context.navigation.footer.center) {
                    addEntry("center", context.navigation.footer.center);
                }
                if (context.navigation.footer.right) {
                    addEntry("right", context.navigation.footer.right);
                }
                return {
                    inlines: markdown
                };
            }
        },
        processRendered (rendered, doc) {
            const process = (key)=>{
                const footerEl = doc.querySelector(`.nav-footer .nav-footer-${key}`);
                if (footerEl) {
                    const footer = rendered[`${kNavFooterPrefix}${key}`];
                    if (footer) {
                        footerEl.innerHTML = footer.innerHTML;
                    }
                }
                const navItemEls = doc.querySelectorAll(".nav-footer .nav-item a.nav-link");
                for(let i = 0; i < navItemEls.length; i++){
                    const link10 = navItemEls[i];
                    const href = link10.getAttribute("href");
                    const id = href || link10.innerText;
                    if (id) {
                        const renderedEl = rendered[`${kNavFooterPrefix}${key}-${id}`];
                        if (renderedEl) {
                            removeChapterNumber(renderedEl);
                            link10.innerHTML = renderedEl?.innerHTML;
                        }
                    }
                }
            };
            process("left");
            process("center");
            process("right");
        }
    };
};
function expandMarkdown(source, name137, val) {
    if (Array.isArray(val)) {
        return val.map((pathOrMarkdown)=>{
            return expandMarkdownFilePath(source, pathOrMarkdown);
        });
    } else if (typeof val == "string") {
        return [
            expandMarkdownFilePath(source, val)
        ];
    } else {
        throw Error(`Invalid value for ${name137}:\n${val}`);
    }
}
function expandMarkdownFilePath(source, path102) {
    const absPath = isAbsolute2(path102) ? path102 : join3(dirname2(source), path102);
    if (safeExistsSync(absPath)) {
        const fileContents = Deno.readTextFileSync(absPath);
        const ext = extname2(absPath);
        if (ext === ".html") {
            return "```{=html}\n" + fileContents + "\n```";
        } else {
            return fileContents;
        }
    } else {
        return path102;
    }
}
function asUndefined(value, test) {
    if (value === test) {
        return undefined;
    }
    return value;
}
function ojsFormatDependency(selfContained) {
    const ojsResource = (resource)=>formatResourcePath("html", join3("ojs", resource))
    ;
    const ojsDependency = (resource, attribs)=>({
            name: resource,
            path: ojsResource(resource),
            attribs
        })
    ;
    const scripts = selfContained ? [] : [
        ojsDependency("esbuild-bundle.js", {
            type: "module"
        })
    ];
    return {
        name: "quarto-ojs",
        stylesheets: [
            ojsDependency("quarto-ojs.css"), 
        ],
        scripts
    };
}
function pandocRawStr(content) {
    return {
        emit: (ls)=>ls.push(content)
    };
}
function pandocHtmlBlock(elementName) {
    return function(opts) {
        let { id , classes , attrs  } = opts || {};
        if (classes === undefined) {
            classes = [];
        }
        if (attrs === undefined) {
            attrs = [];
        }
        const contents = [];
        function attrString() {
            const strs = [];
            if (id) {
                strs.push(`id="${id}"`);
            }
            if (classes) {
                strs.push(`class="${classes.join(" ")}"`);
            }
            if (attrs) {
                strs.push(...attrs.map((attr)=>`data-${attr}`
                ));
            }
            return strs.join(" ");
        }
        return {
            push: function(s) {
                contents.push(s);
            },
            emit: function(ls) {
                ls.push(`\n<${elementName} ${attrString()}>`);
                for (const entry of contents){
                    entry.emit(ls);
                }
                ls.push(`\n</${elementName}>\n`);
            }
        };
    };
}
function pandocBlock(delimiter4) {
    return function(opts) {
        let { id , classes , attrs  } = opts || {};
        if (classes === undefined) {
            classes = [];
        }
        if (attrs === undefined) {
            attrs = [];
        }
        const contents = [];
        function attrString() {
            const strs = [];
            if (id) {
                strs.push(`#${id}`);
            }
            if (classes) {
                strs.push(...classes.map((c)=>`.${c}`
                ));
            }
            if (attrs) {
                strs.push(...attrs);
            }
            if (strs.length) {
                return `{${strs.join(" ")}}`;
            } else {
                return "{}";
            }
        }
        return {
            push: function(s) {
                contents.push(s);
            },
            emit: function(ls) {
                ls.push(`\n${delimiter4}${attrString()}`);
                for (const entry of contents){
                    entry.emit(ls);
                }
                ls.push(`\n${delimiter4}\n`);
            }
        };
    };
}
const pandocDiv = pandocHtmlBlock("div");
const pandocCode = pandocBlock("```");
function crossrefOption(name138, flags, defaults) {
    if (flags && Object.keys(flags).includes(name138)) {
        return flags[name138];
    } else if (Object.keys(defaults || {}).includes(name138)) {
        return defaults[name138];
    } else {
        return undefined;
    }
}
async function resourceFilesFromFile(baseDir, file1, resources, selfContained, supporting, partitioned) {
    const resourceDir = join3(baseDir, dirname2(file1));
    const markdown = partitioned ? partitioned.markdown : "";
    const globs = resources.globs;
    const fileResourceFiles = await resolveFileResources(baseDir, resourceDir, markdown, globs);
    if (!selfContained) {
        const resultFiles = resources.files.map((file)=>join3(resourceDir, file)
        ).filter(existsSync).map(Deno.realPathSync);
        fileResourceFiles.include.push(...resultFiles);
    }
    const resourceFiles = fileResourceFiles.include.filter((file)=>{
        if (fileResourceFiles.exclude.includes(file)) {
            return false;
        } else if (supporting && supporting.some((support)=>file.startsWith(join3(baseDir, support))
        )) {
            return false;
        } else {
            return true;
        }
    });
    return resourceFiles;
}
function printWatchingForChangesMessage() {
    info("Watching files for changes", {
        format: green
    });
}
function printBrowsePreviewMessage(port, path103) {
    if (isJupyterHubServer()) {
        const httpReferrer = `${jupyterHubHttpReferrer() || "<jupyterhub-server-url>/"}user/${jupyterHubUser()}/`;
        info(`\nBrowse at ${httpReferrer}proxy/${port}/${path103}`, {
            format: green
        });
    } else {
        const url = `http://localhost:${port}/${path103}`;
        if (!isRStudioServer()) {
            info(`Browse at `, {
                newline: false,
                format: green
            });
        }
        info(url, {
            format: (str78)=>underline(green(str78))
        });
    }
}
async function runPreRender(projDir, preRender, progress, quiet, env) {
    await runScripts(projDir, preRender, progress, quiet, env);
}
async function runPostRender(projDir, postRender, progress, quiet, env) {
    await runScripts(projDir, postRender, progress, quiet, env);
}
function handlerForScript(script) {
    return kRunHandlers.find((handler)=>handler.canHandle(script)
    );
}
async function runScripts(projDir, scripts, progress, quiet, env) {
    for(let i = 0; i < scripts.length; i++){
        const args = parse7(scripts[i]);
        const script = args[0];
        if (progress && !quiet) {
            info(bold(blue(`${script}`)));
        }
        const handler = handlerForScript(script);
        if (handler) {
            await handler.run(script, args.splice(1), {
                cwd: projDir,
                stdout: quiet ? "piped" : "inherit",
                env
            });
        } else {
            await execProcess({
                cmd: args,
                cwd: projDir,
                stdout: quiet ? "piped" : "inherit",
                env
            });
        }
    }
    if (scripts.length > 0) {
        info("");
    }
}
function parse7(cmdLine) {
    let space = "{{space}}";
    while(cmdLine.indexOf(space) > -1){
        space += "&";
    }
    const noSpaces = cmdLine.replace(/"([^"]*)"?/g, (_, capture)=>{
        return capture.replace(/ /g, space);
    });
    const paramArray = noSpaces.split(/ +/);
    return paramArray.map((mangled)=>{
        return mangled.replace(RegExp(space, "g"), " ");
    });
}
function citeMethod(options) {
    const pandoc = options.format.pandoc;
    const metadata = options.format.metadata;
    if (!metadata[kBibliography] && !metadata.references) {
        return null;
    }
    const engine = bibEngine(options.format.pandoc, options.flags);
    if (engine) {
        return engine;
    }
    if (pandoc.citeproc !== false) {
        return "citeproc";
    } else {
        return null;
    }
}
function cleanupExecutedFile(file, finalOutput) {
    renderCleanup(file.context.target.input, finalOutput, file.recipe.format, file.executeResult.supporting, executionEngineKeepMd(file.context.target.input));
}
function bookItemMetadata(project, item, file) {
    const resourceDir = file ? relative2(project.dir, dirname2(file.context.target.input)) : undefined;
    const inlineMetadata = {
        resourceDir: resourceDir || "."
    };
    const blockMetadata = {
        ...inlineMetadata,
        bookItemType: item.type,
        bookItemNumber: item.number ? item.number : null,
        bookItemFile: item.file
    };
    const inlineMetadataEncoded = encode(JSON.stringify(inlineMetadata));
    const blockMetadataEncoded = encode(JSON.stringify(blockMetadata));
    return `\n\n\`<!-- quarto-file-metadata: ${inlineMetadataEncoded} -->\`{=html}\n\n\`\`\`{=html}\n<!-- quarto-file-metadata: ${blockMetadataEncoded} -->\n\`\`\`\n\n`;
}
function bookPartMarkdown(project, item) {
    const metadata = bookItemMetadata(project, item);
    return `${metadata}# ${item.text ? item.text : ""}\n\n`;
}
function withBookTitleMetadata(format174, config) {
    format174 = cloneDeep1(format174);
    if (config) {
        const setMetadata = (key)=>{
            const value = bookConfig(key, config);
            if (value) {
                format174.metadata[key] = value;
            }
        };
        setMetadata(kTitle);
        setMetadata(kSubtitle);
        setMetadata(kAuthor);
        setMetadata(kDate);
        setMetadata(kAbstract);
        setMetadata(kDescription);
    }
    return format174;
}
function frontMatterTitle(yaml) {
    if (yaml) {
        return yaml[kTitle];
    } else {
        return undefined;
    }
}
async function bookMultiFileHtmlOutputs(context) {
    const renderFiles3 = bookConfigRenderItems(context.config).filter((item)=>!!item.file
    );
    if (renderFiles3.length === 0) {
        return [];
    }
    const index = await inputTargetIndex(context, renderFiles3[0].file);
    if (!index) {
        return [];
    }
    const formatName = Object.keys(index.formats).find((name139)=>{
        if (isMultiFileBookFormat(defaultWriterFormat(name139))) {
            const format175 = index.formats[name139];
            return isHtmlOutput(format175.pandoc, true) && !!format175.pandoc[kOutputFile];
        } else {
            return false;
        }
    });
    if (!formatName) {
        return [];
    }
    const outputFiles = [];
    for(let i = 0; i < renderFiles3.length; i++){
        const file = renderFiles3[i].file;
        const index = await inputTargetIndex(context, file);
        const outputFile = index?.formats[formatName].pandoc[kOutputFile];
        if (outputFile) {
            outputFiles.push(join3(projectOutputDir(context), dirname2(file), outputFile));
        }
    }
    return outputFiles;
}
function sharingTools(projectConfig) {
    const sharingActions = websiteConfigActions("sharing", kBook, projectConfig);
    const sidebarTools = [];
    sidebarTools.push(...sharingActions.filter((action)=>{
        const sidebarTool = kSharingUrls[action];
        if (sidebarTool) {
            return true;
        } else {
            return false;
        }
    }).map((action)=>{
        return kSharingUrls[action];
    }));
    if (sidebarTools.length === 0) {
        return undefined;
    } else if (sidebarTools.length === 1) {
        return sidebarTools;
    } else {
        return [
            {
                text: "Share",
                icon: kShareIcon,
                menu: sidebarTools
            }
        ];
    }
}
const kShareIcon = "share";
const kSharingUrls = {
    linkedin: {
        icon: "linkedin",
        text: "LinkedIn",
        href: "https://www.linkedin.com/sharing/share-offsite/?url=|url|"
    },
    facebook: {
        icon: "facebook",
        text: "Facebook",
        url: "https://www.facebook.com/sharer/sharer.php?u=|url|"
    },
    twitter: {
        icon: "twitter",
        text: "Twitter",
        url: "https://twitter.com/intent/tweet?url=|url|"
    }
};
async function inputIsNumbered(projectDir, input) {
    const partitioned = await partitionedMarkdownForInput(projectDir, input);
    if (partitioned) {
        return isNumberedChapter(partitioned);
    } else {
        return false;
    }
}
function resolveCrossrefs(context, file, doc, index) {
    const projOutput = projectOutputDir(context);
    const relativePathTo = (target)=>{
        const currentFile = join3(projOutput, file);
        const targetFile = join3(projOutput, target);
        return pathWithForwardSlashes(relative2(dirname2(currentFile), targetFile));
    };
    const refs = doc.querySelectorAll(".quarto-unresolved-ref");
    for(let i = 0; i < refs.length; i++){
        const ref9 = refs[i];
        const id = ref9.textContent;
        const type = refType(id);
        if (!type) {
            continue;
        }
        const entry = index.entries[id];
        let parentLink;
        if (ref9.parentElement?.tagName === "A" && ref9.parentElement?.getAttribute("href") === `#${id}`) {
            parentLink = ref9.parentElement;
        }
        if (entry) {
            if (parentLink && file !== entry.file) {
                const relativeFilePath = relativePathTo(entry.file);
                const hash = isChapterRef(entry) ? "" : `#${id}`;
                parentLink.setAttribute("href", `${relativeFilePath}${hash}`);
            }
            ref9.innerHTML = formatCrossref(type, index.files[entry.file], entry, entry.parent ? index.entries[entry.parent] : undefined);
            ref9.removeAttribute("class");
        } else {
            warning(`${file}: Unable to resolve crossref @${id}`);
            if (parentLink) {
                const parentLinkParent = parentLink.parentElement;
                if (parentLinkParent) {
                    const span = doc.createElement("span");
                    span.classList.add("quarto-unresolved-ref");
                    span.innerHTML = `?${id}`;
                    parentLinkParent.insertBefore(span, parentLink);
                    parentLink.remove();
                }
            }
        }
    }
    const links = doc.querySelectorAll("a");
    for(let i1 = 0; i1 < links.length; i1++){
        const link11 = links[i1];
        const href = link11.getAttribute("href");
        if (href && href.startsWith("#")) {
            const id = href.slice(1);
            if (index.headings[id]) {
                if (!index.headings[id].files.includes(file)) {
                    const linkToFile = index.headings[id].files[0];
                    const hash = index.files[linkToFile]?.[kCrossrefChapterId] === id ? "" : `#${id}`;
                    const relativeFilePath = relativePathTo(index.headings[id].files[0]);
                    link11.setAttribute("href", `${relativeFilePath}${hash}`);
                }
            }
        }
    }
}
function isChapterRef(entry) {
    if (refType(entry.key) === "sec" && entry.order.section) {
        return !entry.order.section.slice(1).some((index)=>index > 0
        );
    } else {
        return false;
    }
}
function bookCrossrefIndexForOutputFile(outputFile, indexes) {
    return indexes.find((index)=>Object.keys(index.files).find((file)=>file === outputFile
        )
    );
}
async function bookCrossrefIndexes(context) {
    const indexes = {};
    const renderFiles4 = bookConfigRenderItems(context.config).filter((item)=>!!item.file
    );
    for (const renderFile of renderFiles4){
        const file = renderFile.file;
        const index = await inputTargetIndex(context, file);
        if (index) {
            for (const formatName of Object.keys(index.formats)){
                if (isMultiFileBookFormat(defaultWriterFormat(formatName))) {
                    const format176 = index.formats[formatName];
                    if (format176.pandoc[kOutputFile]) {
                        const outputFile = join3(dirname2(file), format176.pandoc[kOutputFile]);
                        const indexFile = crossrefIndexForOutputFile(context.dir, file, outputFile);
                        if (existsSync(indexFile)) {
                            const indexJson = JSON.parse(Deno.readTextFileSync(indexFile));
                            indexes[formatName] = indexes[formatName] || {
                                files: {},
                                entries: {},
                                headings: {}
                            };
                            const index = indexes[formatName];
                            index.files[outputFile] = indexJson.options || {};
                            indexJson.entries.forEach((entry)=>{
                                index.entries[entry.key] = {
                                    ...entry,
                                    file: outputFile
                                };
                            });
                            indexJson.headings.forEach((heading)=>{
                                if (!index.headings[heading]) {
                                    index.headings[heading] = {
                                        id: heading,
                                        files: []
                                    };
                                }
                                index.headings[heading].files.push(outputFile);
                            });
                        }
                    }
                }
            }
        }
    }
    return Object.values(indexes);
}
function formatCrossref(type, options, entry, parent) {
    if (parent) {
        const crossref = [];
        const parentType = refType(parent.key);
        crossref.push(numberOption(parent.order, options, parentType));
        crossref.push(" (");
        crossref.push(numberOption(entry.order, options, "subref", "alpha a"));
        crossref.push(")");
        return crossref.join("");
    } else {
        return numberOption(entry.order, options, type);
    }
}
function refWithChapter(options, ref10, section) {
    if (options[kCrossrefChapters] !== false) {
        const chapter = section ? section[0] : undefined;
        const chapterPrefix = chapter ? formatChapterIndex(options, chapter) + "." : "";
        return chapterPrefix + ref10;
    } else {
        return ref10;
    }
}
function refType(id) {
    const match = id.match(/^(\w+)-/);
    return match ? match[1] : "fig";
}
function numberOption(order, options, type, defaultFormat2) {
    if (type === "sec" && order.section) {
        return sectionNumber(options, order.section);
    }
    const style = numberStyle(options, type, defaultFormat2);
    if (Array.isArray(style)) {
        const entryCount = style.length;
        const entryIndex = (order.number - 1) % entryCount;
        const option = style[entryIndex];
        return refWithChapter(options, option, order.section);
    } else if (style.match(/^alpha /)) {
        let startIndexChar = style[style.length - 1];
        if (startIndexChar === " ") {
            startIndexChar = "a";
        }
        const startIndex = startIndexChar.charCodeAt(0);
        return refWithChapter(options, String.fromCharCode(startIndex + order.number - 1), order.section);
    } else if (style.match(/^roman/)) {
        const lower = style.endsWith("i");
        return refWithChapter(options, convertToRoman(order.number, lower), order.section);
    } else {
        return refWithChapter(options, order.number.toString(), order.section);
    }
}
function numberStyle(options, type, defaultFormat3) {
    const opt = `${type}-labels`;
    if (defaultFormat3 === undefined) {
        defaultFormat3 = "arabic";
    }
    const labelOpt = options[kCrossrefLabels] || defaultFormat3;
    return options[opt] || labelOpt;
}
function sectionNumber(options, section) {
    let lastIndex = 0;
    for(let i = section.length - 1; i >= 0; i--){
        if (section[i] > 0) {
            lastIndex = i;
            break;
        }
    }
    const num = [];
    for(let i2 = 0; i2 <= lastIndex; i2++){
        if (i2 === 0) {
            const chapIndex = formatChapterIndex(options, section[i2]);
            if (chapIndex) {
                num.push(chapIndex);
            }
        } else {
            num.push(section[i2].toString());
        }
    }
    return num.join(".");
}
function formatChapterIndex(options, index) {
    return index ? options[kCrossrefChaptersAlpha] ? String.fromCharCode(64 + index) : index.toString() : "";
}
function convertToRoman(num, lower) {
    const roman = {
        M: 1000,
        CM: 900,
        D: 500,
        CD: 400,
        C: 100,
        XC: 90,
        L: 50,
        XL: 40,
        X: 10,
        IX: 9,
        V: 5,
        IV: 4,
        I: 1
    };
    let str79 = "";
    for (const i of Object.keys(roman)){
        const q = Math.floor(num / roman[i]);
        num -= q * roman[i];
        str79 += lower ? i.toLowerCase().repeat(q) : i.repeat(q);
    }
    return str79;
}
async function generateBibliographyHTML(context, bibliography, csl, citeIds) {
    const yaml = {
        bibliography,
        nocite: __VIRTUAL_FILE181(citeIds).map((id)=>"@" + id
        ).join(", ")
    };
    if (csl) {
        yaml[kCsl] = csl;
    }
    const frontMatter = `---\n${stringify(yaml, {
        indent: 2
    })}\n---\n`;
    const result = await execProcess({
        cmd: [
            pandocBinaryPath(),
            "--from",
            "markdown",
            "--to",
            "html",
            "--citeproc", 
        ],
        cwd: context.dir,
        stdout: "piped"
    }, frontMatter);
    if (result.success) {
        return result.stdout;
    } else {
        error(result.stderr);
        throw new Error();
    }
}
function forEachCite(doc, f) {
    const cites = doc.querySelectorAll(".citation");
    for(let i = 0; i < cites.length; i++){
        const cite = cites[i];
        f(cite);
    }
}
function citeIdsFromCite(cite) {
    const citeTarget = cite.getAttribute("data-cites");
    if (citeTarget) {
        return citeTarget.split(" ");
    } else {
        return [];
    }
}
function revealFrameworkLayer(revealDir) {
    const readTemplate = (template19)=>{
        return Deno.readTextFileSync(join3(revealDir, "css", "theme", "template", template19));
    };
    return {
        uses: "",
        defaults: "",
        functions: "",
        mixins: readTemplate("mixins.scss"),
        rules: readTemplate("theme.scss")
    };
}
function quartoLayer() {
    return sassLayerFile(formatResourcePath("revealjs", "quarto.scss"));
}
function themeLayer(theme) {
    return sassLayerFile(theme);
}
const renderCommand = new Command().name("render").stopEarly().arguments("[input:string] [...args]").description("Render input file(s) to various document types.").option("-t, --to", "Specify output format(s).").option("-o, --output", "Write output to FILE (use '--output -' for stdout).").option("--output-dir", "Write project output to DIR (path is project relative)").option("--execute", "Execute code (--no-execute to skip execution).").option("-P, --execute-param", "Execution parameter (KEY:VALUE).").option("--execute-params", "YAML file with execution parameters.").option("--execute-dir", "Working directory for code execution.").option("--execute-daemon", "Keep Jupyter kernel alive (defaults to 300 seconds).").option("--execute-daemon-restart", "Restart keepalive Jupyter kernel before render.").option("--execute-debug", "Show debug output for Jupyter kernel.").option("--use-freezer", "Force use of frozen computations for an incremental file render.").option("--cache", "Cache execution output (--no-cache to prevent cache).").option("--cache-refresh", "Force refresh of execution cache.").option("--no-clean", "Do not clean project output-dir prior to render").option("--debug", "Leave intermediate files in place after render.").option("pandoc-args...", "Additional pandoc command line arguments.").example("Render Markdown (w/ Knitr engine)", "quarto render notebook.Rmd\n" + "quarto render notebook.Rmd --to html\n" + "quarto render notebook.Rmd --to pdf --toc").example("Render Markdown (w/ Jupyter engine)", "quarto render notebook.qmd\n" + "quarto render notebook.qmd --to docx --highlight-style=espresso").example("Render Jupyter Notebook", "quarto render notebook.ipynb --to docx\n" + "quarto render notebook.ipynb --to pdf --toc").example("Render to Standard Output", "quarto render notebook.Rmd --output -").action(async (options, input, args)=>{
    args = args || [];
    delete options.clean;
    if (Object.keys(options).length === 1) {
        const option = Object.keys(options)[0];
        const optionArg = option.replaceAll(/([A-Z])/g, (_match, p1)=>`-${p1.toLowerCase()}`
        );
        if (input) {
            args.unshift(input);
            input = undefined;
        }
        args.unshift("--" + optionArg);
        delete options[option];
    }
    if (args.length > 0 && args[0] === "--help") {
        renderCommand.showHelp();
        return;
    }
    input = input || ".";
    const inputs = [
        input
    ];
    const firstPandocArg = args.findIndex((arg)=>arg.startsWith("-")
    );
    if (firstPandocArg !== -1) {
        inputs.push(...args.slice(0, firstPandocArg));
        args = args.slice(firstPandocArg);
    }
    const normalizedArgs = [];
    for (const arg1 of args){
        const equalSignIndex = arg1.indexOf("=");
        if (equalSignIndex > 0 && arg1.startsWith("-")) {
            normalizedArgs.push(arg1.slice(0, equalSignIndex));
            normalizedArgs.push(arg1.slice(equalSignIndex + 1));
        } else {
            normalizedArgs.push(arg1);
        }
    }
    args = normalizedArgs;
    const flags = parseRenderFlags(args);
    args = fixupPandocArgs(args, flags);
    let renderResult;
    let renderResultInput;
    for (const input1 of inputs){
        for (const walk7 of expandGlobSync(input1)){
            const temp = createTempContext();
            try {
                renderResultInput = relative2(Deno.cwd(), walk7.path) || ".";
                renderResult = await render(renderResultInput, {
                    temp,
                    flags,
                    pandocArgs: args,
                    useFreezer: flags.useFreezer === true
                });
                if (renderResult.error) {
                    throw renderResult.error;
                }
            } finally{
                temp.cleanup();
            }
        }
    }
    if (renderResult && renderResultInput) {
        if (!options.flags?.quiet && options.flags?.output !== kStdOut) {
            const finalOutput = renderResultFinalOutput(renderResult, Deno.statSync(renderResultInput).isDirectory ? renderResultInput : dirname2(renderResultInput));
            if (finalOutput) {
                info("Output created: " + finalOutput + "\n");
            }
        }
    } else {
        throw new Error(`No valid input files passed to render`);
    }
});
async function serve(options) {
    const engine = await fileExecutionEngine(options.input);
    if (engine?.run) {
        const target = await engine.target(options.input, options.quiet);
        if (target) {
            const temp = createTempContext();
            try {
                if (options.render) {
                    const result = await render(target.input, {
                        temp
                    });
                    if (result.error) {
                        throw result.error;
                    }
                }
                await engine.run({
                    ...options,
                    input: target.input
                });
                return processSuccessResult();
            } finally{
                temp.cleanup();
            }
        }
    }
    return Promise.reject(new Error("Unable to run computations for input file"));
}
const serveCommand = new Command().name("serve").arguments("<input:string>").option("--no-render", "Do not render the document before serving.").option("-p, --port [port:number]", "The TCP port that the application should listen on.").option("--host [host:string]", "Hostname to bind to (defaults to 127.0.0.1)").description("Serve an interactive document.\n\nBy default, the document will be rendered first and then served. " + "If you have previously rendered the document, pass --no-render to skip the rendering step.").example("Serve an interactive Shiny document", "quarto run dashboard.Rmd").example("Serve a document without rendering", "quarto run dashboard.Rmd --no-render").action(async (options, input)=>{
    const result = await serve({
        input,
        render: options.render,
        port: options.port,
        host: options.host,
        tempDir: Deno.makeTempDirSync()
    });
    if (!result.success) {
        Deno.exit(result.code);
    }
});
async function jupyterCreateVenv(dir, packages) {
    const kEnvDir = "env";
    info(`Creating virtual environment at ${bold(kEnvDir + "/")}:`);
    const caps = await jupyterCapabilitiesNoConda();
    if (caps) {
        const executable = caps.pyLauncher ? "py" : caps.executable;
        const result = await execProcess({
            cmd: [
                executable,
                "-m",
                "venv",
                kEnvDir
            ],
            cwd: dir
        });
        if (!result.success) {
            throw new Error();
        }
        const pip3 = join3(dir, kEnvDir, isWindows1() ? "Scripts\\pip.exe" : "bin/pip3");
        packages = uniq1([
            "jupyter"
        ].concat(packages || []));
        const installResult = await execProcess({
            cmd: [
                pip3,
                "install",
                ...packages
            ],
            cwd: dir
        });
        if (!installResult.success) {
            throw new Error();
        }
    } else {
        throw new Error("Unable to create venv (Non-conda Python 3 not found)");
    }
}
async function jupyterCreateCondaenv(dir, packages) {
    const kEnvDir = "env";
    info(`Creating conda environment at ${bold(kEnvDir + "/")}:`);
    const conda = await which("conda");
    if (conda) {
        info(`Using conda at ${conda}`);
        packages = uniq1([
            "jupyter"
        ].concat(packages || []));
        const installResult = await execProcess({
            cmd: [
                "conda",
                "create",
                "--yes",
                "--prefix",
                "env",
                ...packages
            ],
            cwd: dir
        });
        if (!installResult.success) {
            throw new Error();
        }
    } else {
        throw new Error("Unable to create condaenv (conda not found)");
    }
}
async function projectCreate(options) {
    options = await readOptions(options);
    const engine = executionEngine(options.engine);
    if (!engine) {
        throw Error(`Invalid execution engine: ${options.engine}`);
    }
    ensureDirSync(options.dir);
    options.dir = Deno.realPathSync(options.dir);
    info(`Creating project at `, {
        newline: false
    });
    info(`${options.dir}`, {
        bold: true,
        newline: false
    });
    info(":");
    if (options.type === "site") {
        options.type = kWebsite;
    }
    const projType = projectType(options.type);
    const projCreate = projType.create(options.title, options.template);
    const quartoConfig1 = renderEjs(projCreate.configTemplate, {
        title: options.title,
        editor: options.editor,
        ext: engine.defaultExt
    }, false);
    await Deno.writeTextFileSync(join3(options.dir, "_quarto.yml"), quartoConfig1);
    info("- Created _quarto.yml", {
        indent: 2
    });
    if (await ensureGitignore(options.dir, !!options.venv || !!options.condaenv)) {
        info("- Created .gitignore\n" + "- Created .gitattributes", {
            indent: 2
        });
    }
    if (options.scaffold && projCreate.scaffold) {
        for (const scaffold of projCreate.scaffold(options.engine, options.kernel, options.envPackages)){
            const md = projectMarkdownFile(options.dir, scaffold.name, scaffold.content, engine, options.kernel, scaffold.title, scaffold.noEngineContent, scaffold.yaml, scaffold.subdirectory, scaffold.supporting);
            if (md) {
                info("- Created " + md, {
                    indent: 2
                });
            }
        }
    }
    if (projCreate.supporting) {
        for (const supporting of projCreate.supporting){
            let src;
            let dest;
            let displayName;
            if (typeof supporting === "string") {
                src = join3(projCreate.resourceDir, supporting);
                dest = join3(options.dir, supporting);
                displayName = supporting;
            } else {
                src = join3(projCreate.resourceDir, supporting.from);
                dest = join3(options.dir, supporting.to);
                displayName = supporting.to;
            }
            ensureDirSync(dirname2(dest));
            Deno.copyFileSync(src, dest);
            info("- Created " + displayName, {
                indent: 2
            });
        }
    }
    if (options.venv) {
        await jupyterCreateVenv(options.dir, options.envPackages);
    } else if (options.condaenv) {
        await jupyterCreateCondaenv(options.dir, options.envPackages);
    }
}
async function readOptions(options) {
    options = cloneDeep1(options);
    if (options.engine === "jupyter") {
        const kernel = options.kernel || "python3";
        const kernelspec = await jupyterKernelspec(kernel);
        if (!kernelspec) {
            throw new Error(`Specified jupyter kernel ('${kernel}') not found.`);
        }
    } else {
        if (options.venv) {
            throw new Error("You can only use --with-venv with the jupyter engine");
        }
    }
    options.title = options.title || basename2(options.dir);
    if (projectConfigFile(options.dir)) {
        throw new Error(`The directory '${options.dir}' already contains a quarto project`);
    }
    return options;
}
function projectMarkdownFile(dir1, name1, content, engine, kernel, title25, noEngineContent, yaml, subdirectory1, supporting) {
    const lines16 = [
        "---"
    ];
    if (title25) {
        lines16.push(`title: "${title25}"`);
    }
    if (yaml) {
        lines16.push(yaml);
    }
    if (!noEngineContent) {
        lines16.push(...engine.defaultYaml(kernel));
    }
    lines16.push("---", "");
    if (lines16.length === 3) {
        lines16.splice(0, lines16.length);
    }
    lines16.push(content);
    if (!noEngineContent) {
        const engineContent = engine.defaultContent(kernel);
        if (engineContent.length > 0) {
            lines16.push("");
            lines16.push(...engineContent);
        }
    }
    name1 = name1 + engine.defaultExt;
    const ensureSubDir = (dir, name140, subdirectory)=>{
        if (subdirectory) {
            const newDir = join3(dir, subdirectory);
            ensureDirSync(newDir);
            return join3(newDir, name140);
        } else {
            return join3(dir, name140);
        }
    };
    const path104 = ensureSubDir(dir1, name1, subdirectory1);
    if (!existsSync(path104)) {
        Deno.writeTextFileSync(path104, lines16.join("\n") + "\n");
        supporting?.forEach((from)=>{
            const name141 = basename2(from);
            const target = join3(dirname2(path104), name141);
            Deno.copyFileSync(from, target);
        });
        return subdirectory1 ? join3(subdirectory1, name1) : name1;
    } else {
        return undefined;
    }
}
const kProjectTypes = projectTypes();
const kProjectTypeAliases = projectTypeAliases();
const kProjectTypesAndAliases = [
    ...kProjectTypes,
    ...kProjectTypeAliases
];
const kExecutionEngines = executionEngines().reverse();
const editorType = new EnumType([
    "visual",
    "source"
]);
const createProjectCommand = new Command().type("editor", editorType).name("create-project").description("Create a project for rendering multiple documents").arguments("[dir:string]").option("--title <title:string>", "Project title").option("--type <type:string>", `Project type (${kProjectTypes.join(", ")})`).option("--template <type:string>", `Use a specific project template`).option("--engine <engine:string>", `Use execution engine (${kExecutionEngines.join(", ")})`, {
    value: (value)=>{
        value = value || kMarkdownEngine;
        const engine = executionEngine(value.split(":")[0]);
        if (!engine) {
            throw new Error(`Unknown --engine: ${value}`);
        }
        const match = value.match(/(\w+)(:(.+))?$/);
        if (match) {
            return [
                match[1],
                match[3]
            ];
        } else {
            return [
                value
            ];
        }
    }
}).option("--editor <editor:editor>", "Default editor for project").option("--with-venv [packages:string]", "Create a virtualenv for this project").option("--with-condaenv [packages:string]", "Create a condaenv for this project").option("--no-scaffold", "Don't create initial project file(s)").example("Create a project in the current directory", "quarto create-project").example("Create a project in the 'myproject' directory", "quarto create-project myproject").example("Create a website project", "quarto create-project mysite --type website").example("Create a blog project", "quarto create-project mysite --type website --template blog").example("Create a book project", "quarto create-project mybook --type book").example("Create a website project with jupyter", "quarto create-project mysite --type website --engine jupyter").example("Create a website project with jupyter + kernel", "quarto create-project mysite --type website --engine jupyter:python3").example("Create a book project with knitr", "quarto create-project mybook --type book --engine knitr").example("Create jupyter project with virtualenv", "quarto create-project myproject --engine jupyter --with-venv").example("Create jupyter project with virtualenv + packages", "quarto create-project myproject --engine jupyter --with-venv pandas,matplotlib").example("Create jupyter project with condaenv ", "quarto create-project myproject --engine jupyter --with-condaenv").example("Create jupyter project with condaenv + packages", "quarto create-project myproject --engine jupyter --with-condaenv pandas,matplotlib").action(async (options, dir)=>{
    dir = dir || Deno.cwd();
    const engine = options.engine || [];
    const envPackages = typeof options.withVenv === "string" ? options.withVenv.split(",").map((pkg)=>pkg.trim()
    ) : typeof options.withCondaenv === "string" ? options.withCondaenv.split(",").map((pkg)=>pkg.trim()
    ) : undefined;
    const { type , template: template20  } = parseProjectType(options.type);
    const projectTemplate = options.template || template20;
    if (kProjectTypesAndAliases.indexOf(type) === -1) {
        throw new Error(`Project type must be one of ${kProjectTypes.join(", ")}, but got "${type}".`);
    }
    const projType = projectType(type);
    if (projectTemplate && !projType.templates?.includes(projectTemplate)) {
        if (projType.templates) {
            throw new Error(`Project template must be one of ${projType.templates.join(", ")}, but got "${projectTemplate}".`);
        } else {
            throw new Error(`The project type ${type} does not support any templates.`);
        }
    }
    await projectCreate({
        dir,
        type: type,
        title: options.title || basename2(dir),
        scaffold: !!options.scaffold,
        engine: engine[0] || kMarkdownEngine,
        kernel: engine[1],
        editor: options.editor,
        venv: !!options.withVenv,
        condaenv: !!options.withCondaenv,
        envPackages,
        template: projectTemplate
    });
});
const main = {
    ARROW_UP: "↑",
    ARROW_DOWN: "↓",
    ARROW_LEFT: "←",
    ARROW_RIGHT: "→",
    ARROW_UP_LEFT: "↖",
    ARROW_UP_RIGHT: "↗",
    ARROW_DOWN_RIGHT: "↘",
    ARROW_DOWN_LEFT: "↙",
    RADIO_ON: "◉",
    RADIO_OFF: "◯",
    TICK: "✔",
    CROSS: "✘",
    ELLIPSIS: "…",
    POINTER_SMALL: "›",
    LINE: "─",
    POINTER: "❯",
    INFO: "ℹ",
    TAB_LEFT: "⇤",
    TAB_RIGHT: "⇥",
    ESCAPE: "⎋",
    BACKSPACE: "⌫",
    PAGE_UP: "⇞",
    PAGE_DOWN: "⇟",
    ENTER: "↵",
    SEARCH: "⌕"
};
const win = {
    ...main,
    RADIO_ON: "(*)",
    RADIO_OFF: "( )",
    TICK: "√",
    CROSS: "×",
    POINTER_SMALL: "»"
};
const Figures = Deno.build.os === "windows" ? win : main;
const KeyMap = {
    "[P": "f1",
    "[Q": "f2",
    "[R": "f3",
    "[S": "f4",
    "OP": "f1",
    "OQ": "f2",
    "OR": "f3",
    "OS": "f4",
    "[11~": "f1",
    "[12~": "f2",
    "[13~": "f3",
    "[14~": "f4",
    "[[A": "f1",
    "[[B": "f2",
    "[[C": "f3",
    "[[D": "f4",
    "[[E": "f5",
    "[15~": "f5",
    "[17~": "f6",
    "[18~": "f7",
    "[19~": "f8",
    "[20~": "f9",
    "[21~": "f10",
    "[23~": "f11",
    "[24~": "f12",
    "[A": "up",
    "[B": "down",
    "[C": "right",
    "[D": "left",
    "[E": "clear",
    "[F": "end",
    "[H": "home",
    "OA": "up",
    "OB": "down",
    "OC": "right",
    "OD": "left",
    "OE": "clear",
    "OF": "end",
    "OH": "home",
    "[1~": "home",
    "[2~": "insert",
    "[3~": "delete",
    "[4~": "end",
    "[5~": "pageup",
    "[6~": "pagedown",
    "[[5~": "pageup",
    "[[6~": "pagedown",
    "[7~": "home",
    "[8~": "end"
};
const KeyMapShift = {
    "[a": "up",
    "[b": "down",
    "[c": "right",
    "[d": "left",
    "[e": "clear",
    "[2$": "insert",
    "[3$": "delete",
    "[5$": "pageup",
    "[6$": "pagedown",
    "[7$": "home",
    "[8$": "end",
    "[Z": "tab"
};
const KeyMapCtrl = {
    "Oa": "up",
    "Ob": "down",
    "Oc": "right",
    "Od": "left",
    "Oe": "clear",
    "[2^": "insert",
    "[3^": "delete",
    "[5^": "pageup",
    "[6^": "pagedown",
    "[7^": "home",
    "[8^": "end"
};
const SpecialKeyMap = {
    "\r": "return",
    "\n": "enter",
    "\t": "tab",
    "\b": "backspace",
    "\x7f": "backspace",
    "\x1b": "escape",
    " ": "space"
};
const kEscape = "\x1b";
function parse8(data57) {
    let index = -1;
    const keys11 = [];
    const input = data57 instanceof Uint8Array ? new TextDecoder().decode(data57) : data57;
    const hasNext = ()=>input.length - 1 >= index + 1
    ;
    const next = ()=>input[++index]
    ;
    parseNext();
    return keys11;
    function parseNext() {
        let ch = next();
        let s = ch;
        let escaped = false;
        const key = {
            name: undefined,
            sequence: undefined,
            code: undefined,
            ctrl: false,
            meta: false,
            shift: false
        };
        if (ch === kEscape && hasNext()) {
            escaped = true;
            s += ch = next();
            if (ch === kEscape) {
                s += ch = next();
            }
        }
        if (escaped && (ch === "O" || ch === "[")) {
            let code39 = ch;
            let modifier = 0;
            if (ch === "O") {
                s += ch = next();
                if (ch >= "0" && ch <= "9") {
                    modifier = (Number(ch) >> 0) - 1;
                    s += ch = next();
                }
                code39 += ch;
            } else if (ch === "[") {
                s += ch = next();
                if (ch === "[") {
                    code39 += ch;
                    s += ch = next();
                }
                const cmdStart = s.length - 1;
                if (ch >= "0" && ch <= "9") {
                    s += ch = next();
                    if (ch >= "0" && ch <= "9") {
                        s += ch = next();
                    }
                }
                if (ch === ";") {
                    s += ch = next();
                    if (ch >= "0" && ch <= "9") {
                        s += next();
                    }
                }
                const cmd = s.slice(cmdStart);
                let match;
                if (match = cmd.match(/^(\d\d?)(;(\d))?([~^$])$/)) {
                    code39 += match[1] + match[4];
                    modifier = (Number(match[3]) || 1) - 1;
                } else if (match = cmd.match(/^((\d;)?(\d))?([A-Za-z])$/)) {
                    code39 += match[4];
                    modifier = (Number(match[3]) || 1) - 1;
                } else {
                    code39 += cmd;
                }
            }
            key.ctrl = !!(modifier & 4);
            key.meta = !!(modifier & 10);
            key.shift = !!(modifier & 1);
            key.code = code39;
            if (code39 in KeyMap) {
                key.name = KeyMap[code39];
            } else if (code39 in KeyMapShift) {
                key.name = KeyMapShift[code39];
                key.shift = true;
            } else if (code39 in KeyMapCtrl) {
                key.name = KeyMapCtrl[code39];
                key.ctrl = true;
            } else {
                key.name = "undefined";
            }
        } else if (ch in SpecialKeyMap) {
            key.name = SpecialKeyMap[ch];
            key.meta = escaped;
        } else if (!escaped && ch <= "\x1a") {
            key.name = String.fromCharCode(ch.charCodeAt(0) + "a".charCodeAt(0) - 1);
            key.ctrl = true;
        } else if (/^[0-9A-Za-z]$/.test(ch)) {
            key.name = ch.toLowerCase();
            key.shift = /^[A-Z]$/.test(ch);
            key.meta = escaped;
        } else if (escaped) {
            key.name = ch.length ? undefined : "escape";
            key.meta = true;
        }
        key.sequence = s;
        if (s.length !== 0 && (key.name !== undefined || escaped)) {
            keys11.push(key);
        } else if (charLengthAt(s, 0) === s.length) {
            keys11.push(key);
        } else {
            throw new Error("Unrecognized or broken escape sequence");
        }
        if (hasNext()) {
            parseNext();
        }
    }
}
function charLengthAt(str80, i) {
    const pos = str80.codePointAt(i);
    if (typeof pos === "undefined") {
        return 1;
    }
    return pos >= 65536 ? 2 : 1;
}
class GenericPrompt {
    static injectedValue;
    settings;
    tty = tty;
    indent;
    cursor = {
        x: 0,
        y: 0
    };
    #value;
    #lastError;
    #isFirstRun = true;
    static inject(value) {
        GenericPrompt.injectedValue = value;
    }
    constructor(settings){
        this.settings = {
            ...settings,
            keys: {
                submit: [
                    "enter",
                    "return"
                ],
                ...settings.keys ?? {}
            }
        };
        this.indent = this.settings.indent ?? " ";
    }
    async prompt() {
        try {
            return await this.#execute();
        } finally{
            this.tty.cursorShow();
        }
    }
    clear() {
        this.tty.cursorLeft.eraseDown();
    }
    #execute = async ()=>{
        if (typeof GenericPrompt.injectedValue !== "undefined" && this.#lastError) {
            throw new Error(await this.error());
        }
        await this.render();
        this.#lastError = undefined;
        if (!await this.read()) {
            return this.#execute();
        }
        if (typeof this.#value === "undefined") {
            throw new Error("internal error: failed to read value");
        }
        this.clear();
        const successMessage = this.success(this.#value);
        if (successMessage) {
            console.log(successMessage);
        }
        GenericPrompt.injectedValue = undefined;
        this.tty.cursorShow();
        return this.#value;
    };
    async render() {
        const result = await Promise.all([
            this.message(),
            this.body?.(),
            this.footer(), 
        ]);
        const content = result.filter(Boolean).join("\n");
        const y = content.split("\n").length - this.cursor.y - 1;
        if (!this.#isFirstRun || this.#lastError) {
            this.clear();
        }
        this.#isFirstRun = false;
        if (Deno.build.os === "windows") {
            console.log(content);
            this.tty.cursorUp();
        } else {
            Deno.stdout.writeSync(new TextEncoder().encode(content));
        }
        if (y) {
            this.tty.cursorUp(y);
        }
        this.tty.cursorTo(this.cursor.x);
    }
    async read() {
        if (typeof GenericPrompt.injectedValue !== "undefined") {
            const value = GenericPrompt.injectedValue;
            await this.#validateValue(value);
        } else {
            const events = await this.#readKey();
            if (!events.length) {
                return false;
            }
            for (const event of events){
                await this.handleEvent(event);
            }
        }
        return typeof this.#value !== "undefined";
    }
    submit() {
        return this.#validateValue(this.getValue());
    }
    message() {
        return `${this.settings.indent}${this.settings.prefix}` + bold(this.settings.message) + this.defaults();
    }
    defaults() {
        let defaultMessage = "";
        if (typeof this.settings.default !== "undefined") {
            defaultMessage += dim(` (${this.format(this.settings.default)})`);
        }
        return defaultMessage;
    }
    success(value) {
        return `${this.settings.indent}${this.settings.prefix}` + bold(this.settings.message) + this.defaults() + " " + this.settings.pointer + " " + green(this.format(value));
    }
    footer() {
        return this.error() ?? this.hint();
    }
    error() {
        return this.#lastError ? this.settings.indent + red(bold(`${Figures.CROSS} `) + this.#lastError) : undefined;
    }
    hint() {
        return this.settings.hint ? this.settings.indent + italic(blue(dim(`${Figures.POINTER} `) + this.settings.hint)) : undefined;
    }
    async handleEvent(event) {
        switch(true){
            case event.name === "c" && event.ctrl:
                this.clear();
                this.tty.cursorShow();
                Deno.exit(130);
                return;
            case this.isKey(this.settings.keys, "submit", event):
                await this.submit();
                break;
        }
    }
    #readKey = async ()=>{
        const data58 = await this.#readChar();
        return data58.length ? parse8(data58) : [];
    };
    #readChar = async ()=>{
        const buffer = new Uint8Array(8);
        const isTty = Deno.isatty(Deno.stdin.rid);
        if (isTty) {
            Deno.setRaw(Deno.stdin.rid, true, {
                cbreak: this.settings.cbreak === true
            });
        }
        const nread = await Deno.stdin.read(buffer);
        if (isTty) {
            Deno.setRaw(Deno.stdin.rid, false);
        }
        if (nread === null) {
            return buffer;
        }
        return buffer.subarray(0, nread);
    };
    #transformValue = (value)=>{
        return this.settings.transform ? this.settings.transform(value) : this.transform(value);
    };
    #validateValue = async (value)=>{
        if (!value && typeof this.settings.default !== "undefined") {
            this.#value = this.settings.default;
            return;
        }
        this.#value = undefined;
        this.#lastError = undefined;
        const validation = await (this.settings.validate ? this.settings.validate(value) : this.validate(value));
        if (validation === false) {
            this.#lastError = `Invalid answer.`;
        } else if (typeof validation === "string") {
            this.#lastError = validation;
        } else {
            this.#value = this.#transformValue(value);
        }
    };
    isKey(keys12, name142, event) {
        const keyNames = keys12?.[name142];
        return typeof keyNames !== "undefined" && (typeof event.name !== "undefined" && keyNames.indexOf(event.name) !== -1 || typeof event.sequence !== "undefined" && keyNames.indexOf(event.sequence) !== -1);
    }
}
class GenericInput extends GenericPrompt {
    inputValue = "";
    inputIndex = 0;
    constructor(settings){
        super({
            ...settings,
            keys: {
                moveCursorLeft: [
                    "left"
                ],
                moveCursorRight: [
                    "right"
                ],
                deleteCharLeft: [
                    "backspace"
                ],
                deleteCharRight: [
                    "delete"
                ],
                ...settings.keys ?? {}
            }
        });
    }
    getCurrentInputValue() {
        return this.inputValue;
    }
    message() {
        const message = super.message() + " " + this.settings.pointer + " ";
        this.cursor.x = stripColor(message).length + this.inputIndex + 1;
        return message + this.input();
    }
    input() {
        return underline(this.inputValue);
    }
    highlight(value, color1 = dim, color2 = blue) {
        value = value.toString();
        const inputLowerCase = this.getCurrentInputValue().toLowerCase();
        const valueLowerCase = value.toLowerCase();
        const index = valueLowerCase.indexOf(inputLowerCase);
        const matched = value.slice(index, index + inputLowerCase.length);
        return index >= 0 ? color1(value.slice(0, index)) + color2(matched) + color1(value.slice(index + inputLowerCase.length)) : value;
    }
    async handleEvent(event) {
        switch(true){
            case event.name === "c" && event.ctrl:
                this.clear();
                this.tty.cursorShow();
                Deno.exit(130);
                return;
            case this.isKey(this.settings.keys, "moveCursorLeft", event):
                this.moveCursorLeft();
                break;
            case this.isKey(this.settings.keys, "moveCursorRight", event):
                this.moveCursorRight();
                break;
            case this.isKey(this.settings.keys, "deleteCharRight", event):
                this.deleteCharRight();
                break;
            case this.isKey(this.settings.keys, "deleteCharLeft", event):
                this.deleteChar();
                break;
            case this.isKey(this.settings.keys, "submit", event):
                await this.submit();
                break;
            default:
                if (event.sequence && !event.meta && !event.ctrl) {
                    this.addChar(event.sequence);
                }
        }
    }
    addChar(__char) {
        this.inputValue = this.inputValue.slice(0, this.inputIndex) + __char + this.inputValue.slice(this.inputIndex);
        this.inputIndex++;
    }
    moveCursorLeft() {
        if (this.inputIndex > 0) {
            this.inputIndex--;
        }
    }
    moveCursorRight() {
        if (this.inputIndex < this.inputValue.length) {
            this.inputIndex++;
        }
    }
    deleteChar() {
        if (this.inputIndex > 0) {
            this.inputIndex--;
            this.deleteCharRight();
        }
    }
    deleteCharRight() {
        if (this.inputIndex < this.inputValue.length) {
            this.inputValue = this.inputValue.slice(0, this.inputIndex) + this.inputValue.slice(this.inputIndex + 1);
        }
    }
}
class GenericList extends GenericInput {
    options = this.settings.options;
    listIndex = this.getListIndex();
    listOffset = this.getPageOffset(this.listIndex);
    static separator(label = "------------") {
        return {
            value: label,
            disabled: true
        };
    }
    static mapOption(option) {
        return {
            value: option.value,
            name: typeof option.name === "undefined" ? option.value : option.name,
            disabled: !!option.disabled
        };
    }
    constructor(settings){
        super({
            ...settings,
            keys: {
                previous: settings.search ? [
                    "up"
                ] : [
                    "up",
                    "u",
                    "8"
                ],
                next: settings.search ? [
                    "down"
                ] : [
                    "down",
                    "d",
                    "2"
                ],
                previousPage: [
                    "pageup"
                ],
                nextPage: [
                    "pagedown"
                ],
                ...settings.keys ?? {}
            }
        });
    }
    match() {
        const input = this.getCurrentInputValue().toLowerCase();
        if (!input.length) {
            this.options = this.settings.options.slice();
        } else {
            this.options = this.settings.options.filter((option)=>match(option.name) || option.name !== option.value && match(option.value)
            ).sort((a, b)=>distance(a.name, input) - distance(b.name, input)
            );
        }
        this.listIndex = Math.max(0, Math.min(this.options.length - 1, this.listIndex));
        this.listOffset = Math.max(0, Math.min(this.options.length - this.getListHeight(), this.listOffset));
        function match(value) {
            return stripColor(value).toLowerCase().includes(input);
        }
    }
    message() {
        let message = `${this.settings.indent}${this.settings.prefix}` + bold(this.settings.message) + this.defaults();
        if (this.settings.search) {
            message += " " + this.settings.searchLabel + " ";
        }
        this.cursor.x = stripColor(message).length + this.inputIndex + 1;
        return message + this.input();
    }
    body() {
        return this.getList() + this.getInfo();
    }
    getInfo() {
        if (!this.settings.info) {
            return "";
        }
        const selected = this.listIndex + 1;
        const actions = [
            [
                "Next",
                [
                    Figures.ARROW_DOWN
                ]
            ],
            [
                "Previous",
                [
                    Figures.ARROW_UP
                ]
            ],
            [
                "Next Page",
                [
                    Figures.PAGE_DOWN
                ]
            ],
            [
                "Previous Page",
                [
                    Figures.PAGE_UP
                ]
            ],
            [
                "Submit",
                [
                    Figures.ENTER
                ]
            ], 
        ];
        return "\n" + this.settings.indent + blue(Figures.INFO) + bold(` ${selected}/${this.options.length} `) + actions.map((cur)=>`${cur[0]}: ${bold(cur[1].join(" "))}`
        ).join(", ");
    }
    getList() {
        const list = [];
        const height = this.getListHeight();
        for(let i = this.listOffset; i < this.listOffset + height; i++){
            list.push(this.getListItem(this.options[i], this.listIndex === i));
        }
        if (!list.length) {
            list.push(this.settings.indent + dim("  No matches..."));
        }
        return list.join("\n");
    }
    getListHeight() {
        return Math.min(this.options.length, this.settings.maxRows || this.options.length);
    }
    getListIndex(value) {
        return typeof value === "undefined" ? this.options.findIndex((item)=>!item.disabled
        ) || 0 : this.options.findIndex((item)=>item.value === value
        ) || 0;
    }
    getPageOffset(index) {
        if (index === 0) {
            return 0;
        }
        const height = this.getListHeight();
        return Math.floor(index / height) * height;
    }
    getOptionByValue(value) {
        return this.options.find((option)=>option.value === value
        );
    }
    read() {
        if (!this.settings.search) {
            this.tty.cursorHide();
        }
        return super.read();
    }
    async handleEvent(event) {
        switch(true){
            case this.isKey(this.settings.keys, "previous", event):
                this.selectPrevious();
                break;
            case this.isKey(this.settings.keys, "next", event):
                this.selectNext();
                break;
            case this.isKey(this.settings.keys, "nextPage", event):
                this.selectNextPage();
                break;
            case this.isKey(this.settings.keys, "previousPage", event):
                this.selectPreviousPage();
                break;
            default:
                await super.handleEvent(event);
        }
    }
    moveCursorLeft() {
        if (this.settings.search) {
            super.moveCursorLeft();
        }
    }
    moveCursorRight() {
        if (this.settings.search) {
            super.moveCursorRight();
        }
    }
    deleteChar() {
        if (this.settings.search) {
            super.deleteChar();
        }
    }
    deleteCharRight() {
        if (this.settings.search) {
            super.deleteCharRight();
            this.match();
        }
    }
    addChar(__char) {
        if (this.settings.search) {
            super.addChar(__char);
            this.match();
        }
    }
    selectPrevious() {
        if (this.options.length < 2) {
            return;
        }
        if (this.listIndex > 0) {
            this.listIndex--;
            if (this.listIndex < this.listOffset) {
                this.listOffset--;
            }
            if (this.options[this.listIndex].disabled) {
                this.selectPrevious();
            }
        } else {
            this.listIndex = this.options.length - 1;
            this.listOffset = this.options.length - this.getListHeight();
            if (this.options[this.listIndex].disabled) {
                this.selectPrevious();
            }
        }
    }
    selectNext() {
        if (this.options.length < 2) {
            return;
        }
        if (this.listIndex < this.options.length - 1) {
            this.listIndex++;
            if (this.listIndex >= this.listOffset + this.getListHeight()) {
                this.listOffset++;
            }
            if (this.options[this.listIndex].disabled) {
                this.selectNext();
            }
        } else {
            this.listIndex = this.listOffset = 0;
            if (this.options[this.listIndex].disabled) {
                this.selectNext();
            }
        }
    }
    selectPreviousPage() {
        if (this.options?.length) {
            const height = this.getListHeight();
            if (this.listOffset >= height) {
                this.listIndex -= height;
                this.listOffset -= height;
            } else if (this.listOffset > 0) {
                this.listIndex -= this.listOffset;
                this.listOffset = 0;
            }
        }
    }
    selectNextPage() {
        if (this.options?.length) {
            const height = this.getListHeight();
            if (this.listOffset + height + height < this.options.length) {
                this.listIndex += height;
                this.listOffset += height;
            } else if (this.listOffset + height < this.options.length) {
                const offset = this.options.length - height;
                this.listIndex += offset - this.listOffset;
                this.listOffset = offset;
            }
        }
    }
}
class Checkbox extends GenericList {
    static inject(value) {
        GenericPrompt.inject(value);
    }
    static prompt(options) {
        return new this({
            pointer: blue(Figures.POINTER_SMALL),
            prefix: yellow("? "),
            indent: " ",
            listPointer: blue(Figures.POINTER),
            maxRows: 10,
            searchLabel: blue(Figures.SEARCH),
            minOptions: 0,
            maxOptions: Infinity,
            check: green(Figures.TICK),
            uncheck: red(Figures.CROSS),
            ...options,
            keys: {
                check: [
                    "space"
                ],
                ...options.keys ?? {}
            },
            options: Checkbox.mapOptions(options)
        }).prompt();
    }
    static separator(label) {
        return {
            ...super.separator(label),
            icon: false
        };
    }
    static mapOptions(options) {
        return options.options.map((item)=>typeof item === "string" ? {
                value: item
            } : item
        ).map((item)=>({
                ...this.mapOption(item),
                checked: typeof item.checked === "undefined" && options.default && options.default.indexOf(item.value) !== -1 ? true : !!item.checked,
                icon: typeof item.icon === "undefined" ? true : item.icon
            })
        );
    }
    getListItem(item, isSelected) {
        let line = this.settings.indent;
        line += isSelected ? this.settings.listPointer + " " : "  ";
        if (item.icon) {
            let check1 = item.checked ? this.settings.check + " " : this.settings.uncheck + " ";
            if (item.disabled) {
                check1 = dim(check1);
            }
            line += check1;
        } else {
            line += "  ";
        }
        line += `${isSelected ? this.highlight(item.name, (val)=>val
        ) : this.highlight(item.name)}`;
        return line;
    }
    getValue() {
        return this.settings.options.filter((item)=>item.checked
        ).map((item)=>item.value
        );
    }
    async handleEvent(event) {
        switch(true){
            case this.isKey(this.settings.keys, "check", event):
                this.checkValue();
                break;
            default:
                await super.handleEvent(event);
        }
    }
    checkValue() {
        const item = this.options[this.listIndex];
        item.checked = !item.checked;
    }
    validate(value) {
        const isValidValue = Array.isArray(value) && value.every((val)=>typeof val === "string" && val.length > 0 && this.settings.options.findIndex((option)=>option.value === val
            ) !== -1
        );
        if (!isValidValue) {
            return false;
        }
        if (value.length < this.settings.minOptions) {
            return `The minimum number of options is ${this.settings.minOptions} but got ${value.length}.`;
        }
        if (value.length > this.settings.maxOptions) {
            return `The maximum number of options is ${this.settings.maxOptions} but got ${value.length}.`;
        }
        return true;
    }
    transform(value) {
        return value.map((val)=>val.trim()
        );
    }
    format(value) {
        return value.map((val)=>this.getOptionByValue(val)?.name ?? val
        ).join(", ");
    }
}
class GenericSuggestions extends GenericInput {
    suggestionsIndex = -1;
    suggestionsOffset = 0;
    suggestions = [];
    constructor(settings){
        super({
            ...settings,
            keys: {
                complete: [
                    "tab"
                ],
                next: [
                    "up"
                ],
                previous: [
                    "down"
                ],
                nextPage: [
                    "pageup"
                ],
                previousPage: [
                    "pagedown"
                ],
                ...settings.keys ?? {}
            }
        });
        const suggestions = this.loadSuggestions();
        if (suggestions.length || this.settings.suggestions) {
            this.settings.suggestions = [
                ...suggestions,
                ...this.settings.suggestions ?? [], 
            ].filter(uniqueSuggestions);
        }
    }
    get localStorage() {
        if (this.settings.id && "localStorage" in window) {
            try {
                return window.localStorage;
            } catch (_) {}
        }
        return null;
    }
    loadSuggestions() {
        if (this.settings.id) {
            const json4 = this.localStorage?.getItem(this.settings.id);
            const suggestions = json4 ? JSON.parse(json4) : [];
            if (!Array.isArray(suggestions)) {
                return [];
            }
            return suggestions;
        }
        return [];
    }
    saveSuggestions(...suggestions) {
        if (this.settings.id) {
            this.localStorage?.setItem(this.settings.id, JSON.stringify([
                ...suggestions,
                ...this.loadSuggestions(), 
            ].filter(uniqueSuggestions)));
        }
    }
    render() {
        this.match();
        return super.render();
    }
    match() {
        if (!this.settings.suggestions?.length) {
            return;
        }
        const input = this.getCurrentInputValue().toLowerCase();
        if (!input.length) {
            this.suggestions = this.settings.suggestions.slice();
        } else {
            this.suggestions = this.settings.suggestions.filter((value)=>stripColor(value.toString()).toLowerCase().startsWith(input)
            ).sort((a, b)=>distance((a || a).toString(), input) - distance((b || b).toString(), input)
            );
        }
        this.suggestionsIndex = Math.max(this.getCurrentInputValue().trim().length === 0 ? -1 : 0, Math.min(this.suggestions.length - 1, this.suggestionsIndex));
        this.suggestionsOffset = Math.max(0, Math.min(this.suggestions.length - this.getListHeight(), this.suggestionsOffset));
    }
    input() {
        return super.input() + dim(this.getSuggestion());
    }
    getSuggestion() {
        return this.suggestions[this.suggestionsIndex]?.toString().substr(this.getCurrentInputValue().length) ?? "";
    }
    body() {
        return this.getList() + this.getInfo();
    }
    getInfo() {
        if (!this.settings.info) {
            return "";
        }
        const selected = this.suggestionsIndex + 1;
        const matched = this.suggestions.length;
        const actions = [];
        if (this.settings.suggestions?.length) {
            if (this.settings.list) {
                actions.push([
                    "Next",
                    [
                        Figures.ARROW_DOWN
                    ]
                ], [
                    "Previous",
                    [
                        Figures.ARROW_UP
                    ]
                ], [
                    "Next Page",
                    [
                        Figures.PAGE_DOWN
                    ]
                ], [
                    "Previous Page",
                    [
                        Figures.PAGE_UP
                    ]
                ]);
            } else {
                actions.push([
                    "Next",
                    [
                        Figures.ARROW_UP
                    ]
                ], [
                    "Previous",
                    [
                        Figures.ARROW_DOWN
                    ]
                ]);
            }
            actions.push([
                "Complete",
                [
                    Figures.TAB_RIGHT,
                    dim(" or"),
                    Figures.ARROW_RIGHT
                ]
            ]);
        }
        actions.push([
            "Submit",
            [
                Figures.ENTER
            ]
        ]);
        let info8 = this.settings.indent;
        if (this.settings.suggestions?.length) {
            info8 += blue(Figures.INFO) + bold(` ${selected}/${matched} `);
        }
        info8 += actions.map((cur)=>`${cur[0]}: ${bold(cur[1].join(" "))}`
        ).join(", ");
        return info8;
    }
    getList() {
        if (!this.settings.suggestions?.length || !this.settings.list) {
            return "";
        }
        const list = [];
        const height = this.getListHeight();
        for(let i = this.suggestionsOffset; i < this.suggestionsOffset + height; i++){
            list.push(this.getListItem(this.suggestions[i], this.suggestionsIndex === i));
        }
        if (list.length && this.settings.info) {
            list.push("");
        }
        return list.join("\n");
    }
    getListItem(value, isSelected) {
        let line = this.settings.indent ?? "";
        line += isSelected ? `${this.settings.listPointer} ` : "  ";
        if (isSelected) {
            line += underline(this.highlight(value));
        } else {
            line += this.highlight(value);
        }
        return line;
    }
    getListHeight(suggestions = this.suggestions) {
        return Math.min(suggestions.length, this.settings.maxRows || suggestions.length);
    }
    async handleEvent(event) {
        switch(true){
            case this.isKey(this.settings.keys, "next", event):
                if (this.settings.list) {
                    this.selectPreviousSuggestion();
                } else {
                    this.selectNextSuggestion();
                }
                break;
            case this.isKey(this.settings.keys, "previous", event):
                if (this.settings.list) {
                    this.selectNextSuggestion();
                } else {
                    this.selectPreviousSuggestion();
                }
                break;
            case this.isKey(this.settings.keys, "nextPage", event):
                if (this.settings.list) {
                    this.selectPreviousSuggestionsPage();
                } else {
                    this.selectNextSuggestionsPage();
                }
                break;
            case this.isKey(this.settings.keys, "previousPage", event):
                if (this.settings.list) {
                    this.selectNextSuggestionsPage();
                } else {
                    this.selectPreviousSuggestionsPage();
                }
                break;
            case this.isKey(this.settings.keys, "complete", event):
                this.complete();
                break;
            case this.isKey(this.settings.keys, "moveCursorRight", event):
                if (this.inputIndex < this.inputValue.length) {
                    this.moveCursorRight();
                } else {
                    this.complete();
                }
                break;
            default:
                await super.handleEvent(event);
        }
    }
    deleteCharRight() {
        if (this.inputIndex < this.inputValue.length) {
            super.deleteCharRight();
            if (!this.getCurrentInputValue().length) {
                this.suggestionsIndex = -1;
                this.suggestionsOffset = 0;
            }
        }
    }
    complete() {
        if (this.suggestions.length && this.suggestions[this.suggestionsIndex]) {
            this.inputValue = this.suggestions[this.suggestionsIndex].toString();
            this.inputIndex = this.inputValue.length;
            this.suggestionsIndex = 0;
            this.suggestionsOffset = 0;
        }
    }
    selectPreviousSuggestion() {
        if (this.suggestions?.length) {
            if (this.suggestionsIndex > -1) {
                this.suggestionsIndex--;
                if (this.suggestionsIndex < this.suggestionsOffset) {
                    this.suggestionsOffset--;
                }
            }
        }
    }
    selectNextSuggestion() {
        if (this.suggestions?.length) {
            if (this.suggestionsIndex < this.suggestions.length - 1) {
                this.suggestionsIndex++;
                if (this.suggestionsIndex >= this.suggestionsOffset + this.getListHeight()) {
                    this.suggestionsOffset++;
                }
            }
        }
    }
    selectPreviousSuggestionsPage() {
        if (this.suggestions?.length) {
            const height = this.getListHeight();
            if (this.suggestionsOffset >= height) {
                this.suggestionsIndex -= height;
                this.suggestionsOffset -= height;
            } else if (this.suggestionsOffset > 0) {
                this.suggestionsIndex -= this.suggestionsOffset;
                this.suggestionsOffset = 0;
            }
        }
    }
    selectNextSuggestionsPage() {
        if (this.suggestions?.length) {
            const height = this.getListHeight();
            if (this.suggestionsOffset + height + height < this.suggestions.length) {
                this.suggestionsIndex += height;
                this.suggestionsOffset += height;
            } else if (this.suggestionsOffset + height < this.suggestions.length) {
                const offset = this.suggestions.length - height;
                this.suggestionsIndex += offset - this.suggestionsOffset;
                this.suggestionsOffset = offset;
            }
        }
    }
}
function uniqueSuggestions(value, index, self) {
    return typeof value !== "undefined" && value !== "" && self.indexOf(value) === index;
}
class Confirm extends GenericSuggestions {
    static prompt(options) {
        if (typeof options === "string") {
            options = {
                message: options
            };
        }
        return new this({
            pointer: blue(Figures.POINTER_SMALL),
            prefix: yellow("? "),
            indent: " ",
            listPointer: blue(Figures.POINTER),
            maxRows: 8,
            active: "Yes",
            inactive: "No",
            ...options,
            suggestions: [
                options.active ?? "Yes",
                options.inactive ?? "No", 
            ],
            list: false,
            info: false
        }).prompt();
    }
    static inject(value) {
        GenericPrompt.inject(value);
    }
    defaults() {
        let defaultMessage = "";
        if (this.settings.default === true) {
            defaultMessage += this.settings.active[0].toUpperCase() + "/" + this.settings.inactive[0].toLowerCase();
        } else if (this.settings.default === false) {
            defaultMessage += this.settings.active[0].toLowerCase() + "/" + this.settings.inactive[0].toUpperCase();
        } else {
            defaultMessage += this.settings.active[0].toLowerCase() + "/" + this.settings.inactive[0].toLowerCase();
        }
        return defaultMessage ? dim(` (${defaultMessage})`) : "";
    }
    success(value) {
        this.saveSuggestions(this.format(value));
        return super.success(value);
    }
    getValue() {
        return this.inputValue;
    }
    validate(value) {
        return typeof value === "string" && [
            this.settings.active[0].toLowerCase(),
            this.settings.active.toLowerCase(),
            this.settings.inactive[0].toLowerCase(),
            this.settings.inactive.toLowerCase(), 
        ].indexOf(value.toLowerCase()) !== -1;
    }
    transform(value) {
        switch(value.toLowerCase()){
            case this.settings.active[0].toLowerCase():
            case this.settings.active.toLowerCase():
                return true;
            case this.settings.inactive[0].toLowerCase():
            case this.settings.inactive.toLowerCase():
                return false;
        }
        return;
    }
    format(value) {
        return value ? this.settings.active : this.settings.inactive;
    }
}
class Select extends GenericList {
    listIndex = this.getListIndex(this.settings.default);
    static inject(value) {
        GenericPrompt.inject(value);
    }
    static prompt(options) {
        return new this({
            pointer: blue(Figures.POINTER_SMALL),
            prefix: yellow("? "),
            indent: " ",
            listPointer: blue(Figures.POINTER),
            maxRows: 10,
            searchLabel: blue(Figures.SEARCH),
            ...options,
            options: Select.mapOptions(options)
        }).prompt();
    }
    static mapOptions(options) {
        return options.options.map((item)=>typeof item === "string" ? {
                value: item
            } : item
        ).map((item)=>this.mapOption(item)
        );
    }
    input() {
        return underline(blue(this.inputValue));
    }
    getListItem(item, isSelected) {
        let line = this.settings.indent;
        line += isSelected ? `${this.settings.listPointer} ` : "  ";
        line += `${isSelected ? this.highlight(item.name, (val)=>val
        ) : this.highlight(item.name)}`;
        return line;
    }
    getValue() {
        return this.options[this.listIndex]?.value ?? this.settings.default;
    }
    validate(value) {
        return typeof value === "string" && value.length > 0 && this.options.findIndex((option)=>option.value === value
        ) !== -1;
    }
    transform(value) {
        return value.trim();
    }
    format(value) {
        return this.getOptionByValue(value)?.name ?? value;
    }
}
function unzip(file) {
    const dir = dirname2(file);
    if (file.endsWith("zip")) {
        if (Deno.build.os === "windows") {
            return execProcess({
                cmd: [
                    "powershell",
                    "Expand-Archive",
                    file,
                    "-DestinationPath",
                    dir
                ],
                cwd: dir,
                stdout: "piped"
            });
        } else {
            return execProcess({
                cmd: [
                    "unzip",
                    "-o",
                    file
                ],
                cwd: dir,
                stdout: "piped"
            });
        }
    } else {
        return execProcess({
            cmd: [
                "tar",
                "xfz",
                file
            ],
            cwd: dir,
            stdout: "piped"
        });
    }
}
async function getLatestRelease(repo) {
    const url = `https://api.github.com/repos/${repo}/releases/latest`;
    const response = await fetch(url);
    return response.json();
}
const kDefaultRepos = [
    "https://mirrors.rit.edu/CTAN/systems/texlive/tlnet/",
    "https://ctan.math.illinois.edu/systems/texlive/tlnet/",
    "https://mirror.las.iastate.edu/tex-archive/systems/texlive/tlnet/", 
];
const kTinyTexRepo = "yihui/tinytex-releases";
const kPackageMaximal = "TinyTeX";
const kVersionFileName = "version";
const tinyTexInstallable = {
    name: "TinyTeX",
    prereqs: [
        {
            check: ()=>{
                return isWritable("/usr/local/bin");
            },
            os: [
                "darwin"
            ],
            message: "The directory /usr/local/bin is not writable."
        },
        {
            check: async ()=>{
                const hasTl = await hasTexLive();
                return !hasTl;
            },
            os: [
                "darwin",
                "linux",
                "windows"
            ],
            message: "An existing TexLive installation has been detected."
        },
        {
            check: async ()=>{
                const hasTl = await hasLatexDistribution();
                return !hasTl;
            },
            os: [
                "darwin",
                "linux",
                "windows"
            ],
            message: "An existing LaTeX installation has been detected."
        },
        {
            check: ()=>{
                const needsSource = needsSourceInstall();
                return Promise.resolve(!needsSource);
            },
            os: [
                "linux"
            ],
            message: "This platform doesn't support installation at this time. Please install manually instead."
        }
    ],
    installed,
    installDir,
    installedVersion,
    latestRelease: remotePackageInfo,
    preparePackage,
    install,
    afterInstall,
    uninstall
};
async function installed() {
    const hasTl = await hasTexLive();
    if (hasTl) {
        return await isTinyTex();
    } else {
        return Promise.resolve(false);
    }
}
async function installDir() {
    if (await installed()) {
        return Promise.resolve(tinyTexInstallDir());
    } else {
        return Promise.resolve(undefined);
    }
}
async function installedVersion() {
    const installDir1 = tinyTexInstallDir();
    if (installDir1) {
        const versionFile = join3(installDir1, kVersionFileName);
        if (existsSync(versionFile)) {
            return await Deno.readTextFile(versionFile);
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function noteInstalledVersion(version10) {
    const installDir2 = tinyTexInstallDir();
    if (installDir2) {
        const versionFile = join3(installDir2, kVersionFileName);
        Deno.writeTextFileSync(versionFile, version10);
    }
}
async function preparePackage(context) {
    const pkgInfo = await remotePackageInfo();
    const version11 = pkgInfo.version;
    const pkgName = tinyTexPkgName(kPackageMaximal, version11);
    const filePath = join3(context.workingDir, pkgName);
    const url = tinyTexUrl(pkgName, pkgInfo);
    if (url) {
        await context.download(`TinyTex ${version11}`, url, filePath);
        return {
            filePath,
            version: version11
        };
    } else {
        context.error("Couldn't determine what URL to use to download");
        return Promise.reject();
    }
}
async function install(pkgInfo, context) {
    const installDir3 = tinyTexInstallDir();
    if (installDir3) {
        const parentDir = join3(installDir3, "..");
        const realParentDir = expandPath(parentDir);
        const tinyTexDirName = Deno.build.os === "linux" ? ".TinyTeX" : "TinyTeX";
        if (existsSync(realParentDir)) {
            await context.withSpinner({
                message: `Unzipping ${basename2(pkgInfo.filePath)}`
            }, async ()=>{
                await unzip(pkgInfo.filePath);
            });
            await context.withSpinner({
                message: `Moving files`
            }, ()=>{
                const from = join3(context.workingDir, tinyTexDirName);
                moveSync(from, installDir3, {
                    overwrite: true
                });
                noteInstalledVersion(pkgInfo.version);
                return Promise.resolve();
            });
            const macBinFolder = ()=>{
                const oldBinFolder = join3(installDir3, "bin", `${Deno.build.arch}-${Deno.build.os}`);
                if (existsSync(oldBinFolder)) {
                    return oldBinFolder;
                } else {
                    return join3(installDir3, "bin", `universal-${Deno.build.os}`);
                }
            };
            const binFolder = Deno.build.os === "windows" ? join3(installDir3, "bin", "win32") : macBinFolder();
            context.props[kTlMgrKey] = Deno.build.os === "windows" ? join3(binFolder, "tlmgr.bat") : join3(binFolder, "tlmgr");
            return Promise.resolve();
        } else {
            context.error("Installation target directory doesn't exist");
            return Promise.reject();
        }
    } else {
        context.error("Unable to determine installation directory");
        return Promise.reject();
    }
}
async function afterInstall(context) {
    const tlmgrPath = context.props[kTlMgrKey];
    if (tlmgrPath) {
        await context.withSpinner({
            message: "Verifying tlgpg support"
        }, async ()=>{
            if ([
                "darwin",
                "windows"
            ].includes(Deno.build.os)) {
                await exec(tlmgrPath, [
                    "-q",
                    "--repository",
                    "http://www.preining.info/tlgpg/",
                    "install",
                    "tlgpg", 
                ]);
            }
        });
        let restartRequired = false;
        const defaultRepo = textLiveRepo();
        await context.withSpinner({
            message: `Setting default repository`,
            doneMessage: `Default Repository: ${defaultRepo}`
        }, async ()=>{
            await exec(tlmgrPath, [
                "-q",
                "option",
                "repository",
                defaultRepo
            ]);
            if (Deno.build.os === "linux") {
                const binPath = expandPath("~/bin");
                if (!existsSync(binPath)) {
                    Deno.mkdirSync(binPath);
                    restartRequired = true;
                }
                await exec(tlmgrPath, [
                    "option",
                    "sys_bin",
                    binPath
                ]);
            }
        });
        await context.withSpinner({
            message: "Updating paths"
        }, async ()=>{
            await exec(tlmgrPath, [
                "path",
                "add"
            ]);
        });
        if (Deno.build.os === "windows") {
            const tlmgrIsInPath = await hasTexLive();
            restartRequired = restartRequired || !tlmgrIsInPath;
        }
        return Promise.resolve(restartRequired);
    } else {
        context.error("Couldn't locate tlmgr after installation");
        return Promise.reject();
    }
}
async function uninstall(context) {
    if (!isTinyTex()) {
        context.error("Current LateX installation does not appear to be TinyTex");
        return Promise.reject();
    }
    await context.withSpinner({
        message: "Removing commands"
    }, async ()=>{
        const result = await removePath();
        if (!result.success) {
            context.error("Failed to uninstall");
            return Promise.reject();
        }
    });
    await context.withSpinner({
        message: "Removing directory"
    }, async ()=>{
        const installDir4 = tinyTexInstallDir();
        if (installDir4) {
            await Deno.remove(installDir4, {
                recursive: true
            });
        } else {
            context.error("Couldn't find install directory");
            return Promise.reject();
        }
    });
}
function exec(path105, cmd) {
    return execProcess({
        cmd: [
            path105,
            ...cmd
        ],
        stdout: "piped"
    });
}
const kTlMgrKey = "tlmgr";
function textLiveRepo() {
    const randomInt1 = Math.floor(Math.random() * kDefaultRepos.length);
    return kDefaultRepos[randomInt1];
}
function tinyTexInstallDir() {
    switch(Deno.build.os){
        case "windows":
            return expandPath(join3(getenv("APPDATA", undefined), "TinyTeX"));
        case "linux":
            return expandPath("~/.TinyTeX");
        case "darwin":
            return expandPath("~/Library/TinyTeX");
        default:
            return undefined;
    }
}
function tinyTexPkgName(base9, ver) {
    const ext = Deno.build.os === "windows" ? "zip" : Deno.build.os === "linux" ? "tar.gz" : "tgz";
    base9 = base9 || "TinyTeX";
    if (ver) {
        return `${base9}-${ver}.${ext}`;
    } else {
        return `${base9}.${ext}`;
    }
}
function tinyTexUrl(pkg, remotePkgInfo) {
    const asset1 = remotePkgInfo.assets.find((asset)=>{
        return asset.name === pkg;
    });
    return asset1?.url;
}
async function remotePackageInfo() {
    const githubRelease = await getLatestRelease(kTinyTexRepo);
    return {
        url: githubRelease.html_url,
        version: githubRelease.tag_name,
        assets: githubRelease.assets.map((asset)=>{
            return {
                name: asset.name,
                url: asset.browser_download_url
            };
        })
    };
}
async function isWritable(path106) {
    const desc = {
        name: "write",
        path: path106
    };
    const status = await Deno.permissions.query(desc);
    return status.state === "granted";
}
function needsSourceInstall() {
    if (Deno.build.os === "linux" && Deno.build.arch !== "x86_64") {
        return true;
    } else {
        return false;
    }
}
async function isTinyTex() {
    const root9 = await texLiveRoot();
    if (root9) {
        if (root9.match(/[/\\][Tt]iny[Tt]e[Xx][/\\]?/)) {
            return true;
        }
        const cnfFile = join3(root9, "texmf-dist/web2c/fmtutil.cnf");
        if (existsSync(cnfFile)) {
            const cnfText = Deno.readTextFileSync(cnfFile);
            const match = cnfText.match(/\W[.]?TinyTeX\W/);
            if (match) {
                return true;
            }
        }
        return false;
    }
    return false;
}
async function texLiveRoot() {
    const texLivePath = await which("tlmgr");
    if (texLivePath) {
        const realPath = await Deno.realPath(texLivePath);
        if (Deno.build.os === "windows") {
            return join3(realPath, "..", "..", "..");
        } else {
            const root10 = join3(realPath, "..", "..", "..", "..");
            const tlBin = join3(root10, "bin");
            if (existsSync(tlBin)) {
                return root10;
            } else {
                return undefined;
            }
        }
    } else {
        return undefined;
    }
}
const kInstallableTools = {
    tinytex: tinyTexInstallable
};
function installableTools() {
    const tools = [];
    Object.keys(kInstallableTools).forEach((key)=>{
        const tool = kInstallableTools[key];
        tools.push(tool.name.toLowerCase());
    });
    return tools;
}
async function printToolInfo(name143) {
    name143 = name143 || "";
    const installableTool1 = kInstallableTools[name143.toLowerCase()];
    if (installableTool1) {
        const response = {
            name: installableTool1.name,
            installed: await installableTool1.installed(),
            version: await installableTool1.installedVersion(),
            directory: await installableTool1.installDir()
        };
        info(JSON.stringify(response, null, 2));
    }
}
async function installTool(name1) {
    name1 = name1 || "";
    const installableTool2 = kInstallableTools[name1.toLowerCase()];
    if (installableTool2) {
        const workingDir = Deno.makeTempDirSync();
        try {
            const context = installContext(workingDir);
            context.info(`Installing ${name1}`);
            const alreadyInstalled = await installableTool2.installed();
            if (alreadyInstalled) {
                context.error(`Install canceled - ${name1} is already installed.`);
                return Promise.reject();
            } else {
                const platformPrereqs = installableTool2.prereqs.filter((prereq)=>prereq.os.includes(Deno.build.os)
                );
                for (const prereq1 of platformPrereqs){
                    const met = await prereq1.check();
                    if (!met) {
                        context.error(prereq1.message);
                        return Promise.reject();
                    }
                }
                const pkgInfo = await installableTool2.preparePackage(context);
                await installableTool2.install(pkgInfo, context);
                const restartRequired = await installableTool2.afterInstall(context);
                context.info("Installation successful\n");
                if (restartRequired) {
                    context.info("To complete this installation, please restart your system.");
                }
            }
        } finally{
            Deno.removeSync(workingDir, {
                recursive: true
            });
        }
    } else {
        info(`Could not install '${name1}'- try again with one of the following:`);
        installableTools().forEach((name144)=>info("quarto install " + name144, {
                indent: 2
            })
        );
    }
}
async function uninstallTool(name145) {
    const installableTool3 = kInstallableTools[name145.toLowerCase()];
    if (installableTool3) {
        const installed1 = await installableTool3.installed();
        if (installed1) {
            const workingDir = Deno.makeTempDirSync();
            const context = installContext(workingDir);
            context.info(`Uninstalling ${name145}`);
            try {
                await installableTool3.uninstall(context);
                info(`Uninstallation successful\n`);
            } catch (e) {
                logError(e);
            } finally{
                Deno.removeSync(workingDir, {
                    recursive: true
                });
            }
        } else {
            info(`${name145} is not installed Use 'quarto install ${name145} to install it.`);
        }
    }
}
async function updateTool(name146) {
    const summary = await toolSummary(name146);
    const installableTool4 = kInstallableTools[name146];
    if (installableTool4 && summary && summary.installed) {
        const workingDir = Deno.makeTempDirSync();
        const context = installContext(workingDir);
        try {
            context.info(`Updating ${installableTool4.name} from ${summary.installedVersion} to ${summary.latestRelease.version}`);
            const pkgInfo = await installableTool4.preparePackage(context);
            context.info(`Removing ${summary.installedVersion}`);
            await installableTool4.uninstall(context);
            context.info(`Installing ${summary.latestRelease.version}`);
            await installableTool4.install(pkgInfo, context);
            context.info("Finishing update");
            const restartRequired = await installableTool4.afterInstall(context);
            context.info("Update successful\n");
            if (restartRequired) {
                context.info("To complete this update, please restart your system.");
            }
        } catch (e) {
            logError(e);
        } finally{
            Deno.removeSync(workingDir, {
                recursive: true
            });
        }
    } else {
        info(`${name146} is not installed Use 'quarto install ${name146} to install it.`);
    }
}
async function toolSummary(name147) {
    const tool = installableTool(name147);
    if (tool) {
        const installed2 = await tool.installed();
        const installedVersion1 = await tool.installedVersion();
        const latestRelease = await tool.latestRelease();
        return {
            installed: installed2,
            installedVersion: installedVersion1,
            latestRelease
        };
    } else {
        return undefined;
    }
}
function installableTool(name148) {
    return kInstallableTools[name148.toLowerCase()];
}
const installContext = (workingDir)=>{
    const installMessaging = {
        info: (msg)=>{
            info(msg);
        },
        error: (msg)=>{
            info(msg);
        },
        withSpinner
    };
    return {
        download: async (name149, url, target)=>{
            const response = await fetch(url, {
                redirect: "follow"
            });
            if (response.status === 200 && response.body) {
                const pkgFile = await Deno.open(target, {
                    create: true,
                    write: true
                });
                const contentLength = response.headers.get("content-length") || 0;
                const contentLengthMb = contentLength / 1024 / 1024;
                const prog = progressBar(contentLengthMb, `Downloading ${name149}`);
                let totalLength = 0;
                for await (const chunk of response.body){
                    await writeAll(pkgFile, chunk);
                    totalLength = totalLength + chunk.length;
                    if (contentLength > 0) {
                        prog.update(totalLength / 1024 / 1024, `${(totalLength / 1024 / 1024).toFixed(1)}MB`);
                    }
                }
                prog.complete();
                pkgFile.close();
            } else {
                installMessaging.error(`download failed (HTTP status ${response.status} - ${response.statusText})`);
                return Promise.reject();
            }
        },
        workingDir,
        ...installMessaging,
        props: {}
    };
};
const toolsCommand = new Command().name("tools").arguments("[command:string] [tool:string]").description(`Manage the installation, update, and uninstallation of useful tools.
    
  tools:\n  ${installableTools().map((name150)=>"  " + name150
).join("\n")}

  commands:
    install
    uninstall
    update
    
Use 'quarto tools' with no arguments to show the status of all tools.`).example("Install TinyTex", "quarto tools install tinytex").example("Uninstall TinyTex", "quarto tools uninstall tinytex").example("Update TinyTex", "quarto tools update tinytex").example("Show tool status", "quarto tools").action(async (_options, command, tool)=>{
    switch(command){
        case "info":
            if (tool) {
                await printToolInfo(tool);
            }
            break;
        case "install":
            if (tool) {
                await installTool(tool);
            }
            break;
        case "uninstall":
            if (tool) {
                await confirmDestructiveAction(tool, `This will remove ${tool} and all of its files. Are you sure?`, async ()=>{
                    await uninstallTool(tool);
                }, false, await toolSummary(tool));
            }
            break;
        case "update":
            if (tool) {
                const summary = await toolSummary(tool);
                await confirmDestructiveAction(tool, `This will update ${tool} from ${summary?.installedVersion} to ${summary?.latestRelease.version}. Are you sure?`, async ()=>{
                    await updateTool(tool);
                }, true, summary);
            }
            break;
        default:
        case "list":
            await outputTools();
            break;
    }
});
async function confirmDestructiveAction(name151, prompt, action, update, summary) {
    if (summary) {
        if (summary.installed) {
            if (summary.installedVersion === summary.latestRelease.version && update) {
                info(`${name151} is already up to date.`);
            } else if (summary.installedVersion !== undefined) {
                const confirmed = await Confirm.prompt(prompt);
                if (confirmed) {
                    await action();
                }
            } else {
                info(`${name151} was not installed using Quarto. Please use the tool that you used to install ${name151} instead.`);
            }
        } else {
            info(`${name151} isn't installed. Please use 'quarto install ${name151} to install it.`);
        }
    } else {
        info(`${name151} isn't a supported tool. Use 'quarto install help' for more information.`);
    }
}
async function outputTools() {
    const toolRows = [];
    const cols = [
        20,
        32,
        14,
        14
    ];
    await withSpinner({
        message: "Reading Tool Data"
    }, async ()=>{
        const installStatus = (summary)=>{
            if (summary.installed) {
                if (summary.installedVersion) {
                    if (summary.installedVersion === summary.latestRelease.version) {
                        return "Up to date";
                    } else {
                        return "Update available";
                    }
                } else {
                    return "Present - ext. managed";
                }
            } else {
                return "Not installed";
            }
        };
        for (const tool of installableTools()){
            const summary = await toolSummary(tool);
            if (summary) {
                toolRows.push(formatLine([
                    tool,
                    installStatus(summary),
                    summary.installedVersion || "----",
                    summary.latestRelease.version, 
                ], cols));
            }
        }
    });
    info(formatLine([
        "Tool",
        "Status",
        "Installed",
        "Latest"
    ], cols), {
        bold: true
    });
    if (toolRows.length === 0) {
        info("nothing installed", {
            indent: 2
        });
    } else {
        toolRows.forEach((row)=>info(row)
        );
    }
}
function randomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min) + min);
}
const kLocalhost = "127.0.0.1";
const kMinPort = 3000;
const kMaxPort = 8000;
function findOpenPort(defaultPort) {
    defaultPort = defaultPort || randomInt(kMinPort, kMaxPort);
    if (isPortAvailableSync({
        port: defaultPort,
        hostname: kLocalhost
    })) {
        return defaultPort;
    } else {
        let ports = new Array(8000 - 3000);
        for(let i = 0; i < ports.length; i++){
            ports[i] = kMinPort + i;
        }
        ports = shuffle1(ports);
        while(true){
            const port = getAvailablePortSync({
                port: ports,
                hostname: kLocalhost
            });
            if (port === undefined) {
                throw new Error("Unabled to find open port for serve");
            }
            if (![
                3659,
                4045,
                6000,
                6665,
                6666,
                6667,
                6668,
                6669,
                6697
            ].includes(port)) {
                return port;
            }
        }
    }
}
function isPortAvailableSync(options) {
    try {
        const listener = Deno.listen({
            port: options.port,
            ...options.hostname ? {
                hostname: options.hostname
            } : {},
            ...options.transport ? {
                transport: options.transport
            } : {}
        });
        listener.close();
        return true;
    } catch (error33) {
        if (error33 instanceof Deno.errors.AddrInUse) {
            return false;
        }
        throw error33;
    }
}
function getAvailablePortSync(options = {
    transport: "tcp"
}) {
    if (options.port === undefined) {
        return getRandomPortSync(options);
    } else if (Array.isArray(options.port)) {
        const portList = options.port;
        for(let i = 0; i < portList.length; i++){
            if (withinRange(portList[i])) {
                const portAvailable = isPortAvailableSync({
                    port: portList[i],
                    ...options.hostname ? {
                        hostname: options.hostname
                    } : {},
                    ...options.transport ? {
                        transport: options.transport
                    } : {}
                });
                if (portAvailable) {
                    return portList[i];
                } else {
                    continue;
                }
            } else {
                continue;
            }
        }
    } else if (options.port.start !== undefined && options.port.end !== undefined) {
        const start = options.port.start;
        const end = options.port.end;
        if (start >= 0 && end <= 65535 && start <= end) {
            for(let p = start; p <= end; p++){
                const portAvailable = isPortAvailableSync({
                    port: p,
                    ...options.hostname ? {
                        hostname: options.hostname
                    } : {},
                    ...options.transport ? {
                        transport: options.transport
                    } : {}
                });
                if (portAvailable) {
                    return p;
                } else {
                    continue;
                }
            }
        } else {
            throw new Error("Range should be between 0 - 65535 and start should be less than end");
        }
    }
}
function getRandomPortSync(options) {
    const randomPort = random(0, 65535);
    if (isPortAvailableSync({
        port: randomPort,
        ...options.hostname ? {
            hostname: options.hostname
        } : {},
        ...options.transport ? {
            transport: options.transport
        } : {}
    })) {
        return randomPort;
    } else {
        return getRandomPortSync(options);
    }
}
function random(min, max) {
    return Math.round(Math.random() * (max - min)) + min;
}
function withinRange(port) {
    return port >= 0 && port <= 65535;
}
async function openUrl(url) {
    const shellOpen = {
        windows: "explorer",
        darwin: "open",
        linux: "xdg-open"
    };
    const cmd = shellOpen[Deno.build.os];
    if (await which(cmd)) {
        Deno.run({
            cmd: [
                cmd,
                url
            ]
        });
    }
}
function httpDevServer(port, timeout, isRendering, stopServer, isPresentation) {
    const clients = [];
    let onSocketClose;
    if (timeout > 0 && !isRStudioPreview()) {
        onSocketClose = debounce1(()=>{
            if (!isRendering() && !clients.find((client)=>client.socket.readyState !== WebSocket.CLOSED
            )) {
                stopServer();
            }
        }, timeout * 1000);
    }
    LogEventsHandler.onLog(async (logRecord, msg)=>{
        for(let i = clients.length - 1; i >= 0; i--){
            const socket = clients[i].socket;
            try {
                await socket.send("log:" + JSON.stringify({
                    ...logRecord,
                    msgFormatted: msg
                }));
            } catch (_e) {}
        }
    });
    return {
        handle: (req)=>{
            return req.headers.get("upgrade") === "websocket";
        },
        connect: (req)=>{
            try {
                const { socket , response  } = Deno.upgradeWebSocket(req);
                const client = {
                    socket
                };
                if (onSocketClose) {
                    socket.onclose = onSocketClose;
                }
                clients.push(client);
                return Promise.resolve(response);
            } catch (e) {
                maybeDisplaySocketError(e);
                return Promise.resolve(undefined);
            }
        },
        injectClient: (file, inputFile)=>{
            const scriptContents = new TextEncoder().encode("\n" + devServerClientScript(port, inputFile, isPresentation));
            const fileWithScript = new Uint8Array(file.length + scriptContents.length);
            fileWithScript.set(file);
            fileWithScript.set(scriptContents, file.length);
            return fileWithScript;
        },
        reloadClients: async (reloadTarget = "")=>{
            for(let i = clients.length - 1; i >= 0; i--){
                const socket = clients[i].socket;
                try {
                    const message = "reload";
                    await socket.send(`${message}${reloadTarget}`);
                } catch (e) {
                    maybeDisplaySocketError(e);
                } finally{
                    if (!socket.CLOSED && !socket.CLOSING) {
                        try {
                            socket.close();
                        } catch (e) {
                            maybeDisplaySocketError(e);
                        }
                    }
                    clients.splice(i, 1);
                }
            }
        }
    };
}
function devServerClientScript(port, inputFile, isPresentation) {
    const devserver = [
        renderEjs(resourcePath("editor/devserver/devserver-core.html"), {
            localhost: kLocalhost,
            port
        }), 
    ];
    if (isPresentation) {
        devserver.push(renderEjs(resourcePath("editor/devserver/devserver-revealjs.html"), {}));
    } else {
        devserver.push(renderEjs(resourcePath("editor/devserver/devserver-viewer.html"), {
            inputFile: inputFile || ""
        }));
    }
    return devserver.join("\n");
}
class PromiseQueue {
    queue = new Array();
    running = false;
    enqueue(promise, clearPending = false) {
        return new Promise((resolve8, reject)=>{
            if (clearPending) {
                this.queue.splice(0, this.queue.length);
            }
            this.queue.push({
                promise,
                resolve: resolve8,
                reject
            });
            this.dequeue();
        });
    }
    isRunning() {
        return this.running;
    }
    dequeue() {
        if (this.running) {
            return false;
        }
        const item = this.queue.shift();
        if (!item) {
            return false;
        }
        try {
            this.running = true;
            item.promise().then((value)=>{
                this.running = false;
                item.resolve(value);
                this.dequeue();
            }).catch((err)=>{
                this.running = false;
                item.reject(err);
                this.dequeue();
            });
        } catch (err) {
            this.running = false;
            item.reject(err);
            this.dequeue();
        }
        return true;
    }
}
const kPdfJsDefaultFile = "compressed.tracemonkey-pldi-09.pdf";
const kPdfJsViewerToolbarButtonSelector = `.toolbarButton,
.dropdownToolbarButton,
.secondaryToolbarButton,
.overlayButton {`;
const kPdfJsViewerSidebarTransitionDurationPattern = /(--sidebar-transition-duration: )(\d+ms)/;
const kPdfJsInitialPath = "web/viewer.html";
function pdfJsBaseDir() {
    return formatResourcePath("pdf", "pdfjs");
}
function pdfJsFileHandler(pdfFile, htmlHandler) {
    return async (file1, req)=>{
        if (htmlHandler) {
            const contents = await htmlHandler(file1, req);
            if (contents) {
                return contents;
            }
        }
        const previewPath = (dir, file)=>{
            return pathWithForwardSlashes(join3(pdfJsBaseDir(), dir, file));
        };
        if (file1 === previewPath("web", "viewer.js")) {
            let viewerJs = Deno.readTextFileSync(file1).replace(kPdfJsDefaultFile, basename2(pdfFile()));
            const referrer = req.headers.get("Referer");
            const isViewer = referrer && referrer.includes("capabilities=");
            if (isViewer) {
                viewerJs = viewerJs.replace("sidebarView: sidebarView", "sidebarView: _ui_utils.SidebarView.NONE");
            }
            return new TextEncoder().encode(viewerJs);
        } else if (file1 == previewPath("web", "viewer.css")) {
            const viewerCss = normalizeNewlines(Deno.readTextFileSync(file1)).replace(kPdfJsViewerToolbarButtonSelector, kPdfJsViewerToolbarButtonSelector + "\n  z-index: 199;").replace(kPdfJsViewerSidebarTransitionDurationPattern, "$1 0");
            return new TextEncoder().encode(viewerCss);
        } else if (file1 === previewPath("build", "pdf.worker.js")) {
            const filePathHash = "quarto-preview-pdf-" + md5Hash(pdfFile());
            const workerJs = Deno.readTextFileSync(file1).replace(/(key: "fingerprint",\s+get: function get\(\) {\s+)(var hash;)/, `$1return "${filePathHash}"; $2`);
            return new TextEncoder().encode(workerJs);
        } else if (file1 === previewPath("web", basename2(pdfFile()))) {
            return Deno.readFileSync(pdfFile());
        }
    };
}
function watchForFileChanges(files, pollingInterval) {
    const fileList = ()=>{
        if (Array.isArray(files)) {
            return files;
        } else {
            return files();
        }
    };
    const lastModified = new Map();
    fileList().forEach((file)=>lastModified.set(file, existsSync(file) ? Deno.statSync(file).mtime : null)
    );
    if (!pollingInterval) {
        pollingInterval = Math.max(200, lastModified.size);
    }
    let stop = false;
    return {
        close: ()=>{
            stop = true;
        },
        async *[Symbol.asyncIterator] () {
            try {
                while(!stop){
                    await sleep(pollingInterval);
                    const created = [];
                    const modified = [];
                    const currentFiles = fileList();
                    for(let i = 0; i < currentFiles.length; i++){
                        const file = currentFiles[i];
                        if (existsSync(file)) {
                            const prevMod = lastModified.get(file);
                            const lastMod = Deno.statSync(file).mtime;
                            lastModified.set(file, lastMod);
                            if (!prevMod) {
                                created.push(file);
                            } else if (lastMod?.getTime() !== prevMod?.getTime()) {
                                modified.push(file);
                            }
                        }
                    }
                    if (created.length > 0) {
                        yield {
                            kind: "create",
                            paths: created
                        };
                    }
                    if (modified.length > 0) {
                        yield {
                            kind: "modify",
                            paths: modified
                        };
                    }
                }
            } catch (err) {
                error("Unexpected error while scanning for file changes: " + err.message);
            }
        }
    };
}
async function preview(file, flags, pandocArgs, options) {
    await resolvePreviewFormat(file, flags, pandocArgs);
    let isRendering = false;
    const render1 = async ()=>{
        const temp = createTempContext();
        try {
            isRendering = true;
            return await renderForPreview(file, temp, flags, pandocArgs);
        } finally{
            isRendering = false;
            temp.cleanup();
        }
    };
    const result = await render1();
    const project = await projectContext(file);
    const listener = Deno.listen({
        port: options.port,
        hostname: options.host
    });
    const stopServer = ()=>listener.close()
    ;
    const reloader = httpDevServer(options.port, options.timeout, ()=>isRendering
    , stopServer, options.presentation);
    const changeHandler = createChangeHandler(result, reloader, render1, options.watchInputs);
    const handler = isPdfContent(result.outputFile) ? pdfFileRequestHandler(result.outputFile, Deno.realPathSync(file), result.format, reloader, changeHandler.render) : project ? projectHtmlFileRequestHandler(project, Deno.realPathSync(file), result.format, reloader, changeHandler.render) : htmlFileRequestHandler(result.outputFile, Deno.realPathSync(file), result.format, reloader, changeHandler.render);
    const initialPath = isPdfContent(result.outputFile) ? kPdfJsInitialPath : project ? pathWithForwardSlashes(relative2(projectOutputDir(project), result.outputFile)) : "";
    const url = `http://localhost:${options.port}/${initialPath}`;
    if (options.browse && !isRStudioServer() && !isJupyterHubServer()) {
        await openUrl(url);
    }
    printBrowsePreviewMessage(options.port, initialPath);
    for await (const conn of listener){
        (async ()=>{
            for await (const { request , respondWith  } of Deno.serveHttp(conn)){
                try {
                    await respondWith(handler(request));
                } catch (err) {
                    warning(err.message);
                }
            }
        })();
    }
}
async function resolvePreviewFormat(file, flags, pandocArgs) {
    const formats14 = await renderFormats(file);
    const format178 = flags.to || Object.keys(formats14).find((name152)=>{
        const format177 = formats14[name152];
        const outputFile = format177.pandoc[kOutputFile];
        return isHtmlContent(outputFile) || isPdfContent(outputFile);
    }) || "html";
    flags.to = format178;
    replacePandocArg(pandocArgs, "--to", format178);
}
async function renderForPreview(file1, temp, flags, pandocArgs) {
    const renderResult = await render(file1, {
        temp,
        flags,
        pandocArgs: pandocArgs
    });
    if (renderResult.error) {
        throw renderResult.error;
    }
    const finalOutput = renderResultFinalOutput(renderResult, dirname2(file1));
    if (!finalOutput) {
        throw new Error("No output created by quarto render " + basename2(file1));
    }
    info("Output created: " + finalOutput + "\n");
    printWatchingForChangesMessage();
    file1 = Deno.realPathSync(file1);
    const filesDir = join3(dirname2(file1), inputFilesDir(file1));
    const resourceFiles1 = renderResult.files.reduce((resourceFiles, file)=>{
        const resources = file.resourceFiles.concat(cssFileResourceReferences(file.resourceFiles));
        return resourceFiles.concat(resources.filter((resFile)=>!resFile.startsWith(filesDir)
        ));
    }, []);
    return {
        file: file1,
        format: renderResult.files[0].format,
        outputFile: join3(dirname2(file1), finalOutput),
        resourceFiles: resourceFiles1
    };
}
function createChangeHandler(result1, reloader, render2, renderOnChange) {
    const renderQueue = new PromiseQueue();
    let watcher;
    let lastResult = result1;
    const renderHandler = __VIRTUAL_FILE113(async ()=>{
        try {
            await renderQueue.enqueue(async ()=>{
                const result = await render2();
                sync(result);
            }, true);
        } catch (e) {
            if (e.message) {
                if (isJupyterNotebook(result1.file) && e.message.indexOf("Unexpected end of JSON input") !== -1) {
                    return;
                }
                logError(e);
            }
        }
    }, 50);
    const sync = (result)=>{
        const requiresSync = !watcher || resultRequiresSync(result, lastResult);
        lastResult = result;
        if (requiresSync) {
            if (watcher) {
                watcher.stop();
            }
            const watches = [];
            if (renderOnChange) {
                watches.push({
                    files: [
                        result.file
                    ],
                    handler: renderHandler
                });
            }
            const reloadFiles = isHtmlContent(result.outputFile) ? htmlReloadFiles(result) : pdfReloadFiles(result);
            const reloadTarget = isHtmlContent(result.outputFile) ? "" : "/" + kPdfJsInitialPath;
            watches.push({
                files: reloadFiles,
                handler: __VIRTUAL_FILE113(async ()=>{
                    await renderQueue.enqueue(async ()=>{
                        await reloader.reloadClients(reloadTarget);
                    });
                }, 50)
            });
            watcher = previewWatcher(watches);
            watcher.start();
        }
    };
    sync(result1);
    return {
        render: renderHandler
    };
}
function previewWatcher(watches) {
    watches = watches.map((watch)=>{
        return {
            ...watch,
            files: watch.files.filter(existsSync).map((file)=>{
                return Deno.realPathSync(file);
            })
        };
    });
    const handlerForFile = (file)=>{
        const watch1 = watches.find((watch)=>watch.files.includes(file)
        );
        return watch1?.handler;
    };
    const files = watches.flatMap((watch)=>watch.files
    );
    const fsWatcher = watchForFileChanges(files);
    const watchForChanges = async ()=>{
        for await (const event of fsWatcher){
            try {
                if (event.kind === "modify") {
                    const handlers = new Set();
                    event.paths.forEach((path107)=>{
                        const handler = handlerForFile(path107);
                        if (handler && !handlers.has(handler)) {
                            handlers.add(handler);
                        }
                    });
                    for (const handler1 of handlers){
                        await handler1();
                    }
                }
            } catch (e) {
                logError(e);
            }
        }
    };
    return {
        start: watchForChanges,
        stop: ()=>fsWatcher.close()
    };
}
function projectHtmlFileRequestHandler(context, inputFile, format179, reloader, renderHandler) {
    return httpFileRequestHandler(htmlFileRequestHandlerOptions(projectOutputDir(context), "index.html", inputFile, format179, reloader, renderHandler));
}
function htmlFileRequestHandler(htmlFile, inputFile, format180, reloader, renderHandler) {
    return httpFileRequestHandler(htmlFileRequestHandlerOptions(dirname2(htmlFile), basename2(htmlFile), inputFile, format180, reloader, renderHandler));
}
function htmlFileRequestHandlerOptions(baseDir, defaultFile, inputFile, format181, reloader, renderHandler) {
    return {
        baseDir,
        defaultFile,
        printUrls: "404",
        onRequest: (req)=>{
            if (reloader.handle(req)) {
                return Promise.resolve(reloader.connect(req));
            } else if (req.url.endsWith("/quarto-render/")) {
                renderHandler();
                return Promise.resolve(httpContentResponse("rendered"));
            } else {
                return Promise.resolve(undefined);
            }
        },
        onFile: async (file)=>{
            if (isHtmlContent(file)) {
                if (format181.formatPreviewFile) {
                    file = format181.formatPreviewFile(file, format181);
                }
                const fileContents = await Deno.readFile(file);
                return reloader.injectClient(fileContents, inputFile);
            }
        }
    };
}
function htmlReloadFiles(result) {
    return [
        result.outputFile
    ].concat(result.resourceFiles);
}
function pdfFileRequestHandler(pdfFile, inputFile, format182, reloader, renderHandler) {
    const pdfOptions = htmlFileRequestHandlerOptions(dirname2(pdfFile), basename2(pdfFile), inputFile, format182, reloader, renderHandler);
    pdfOptions.baseDir = pdfJsBaseDir();
    pdfOptions.onFile = pdfJsFileHandler(()=>pdfFile
    , pdfOptions.onFile);
    return httpFileRequestHandler(pdfOptions);
}
function pdfReloadFiles(result) {
    return [
        result.outputFile
    ];
}
function resultRequiresSync(result, lastResult) {
    if (!lastResult) {
        return true;
    }
    return result.file !== lastResult.file || result.outputFile !== lastResult.outputFile || !__VIRTUAL_FILE211(result.resourceFiles, lastResult.resourceFiles);
}
function copyProjectForServe(project, copyOutput, serveDir) {
    const outputDir = projectOutputDir(project);
    const libDirConfig = project.config?.project[kProjectLibDir];
    const libDir = libDirConfig ? join3(project.dir, libDirConfig) : undefined;
    const ignoreDirs = engineIgnoreDirs();
    const filter11 = (path108)=>{
        if (!copyOutput && (path108.startsWith(outputDir) || libDir && path108.startsWith(libDir))) {
            return false;
        }
        const name153 = basename2(path108);
        return !ignoreDirs.includes(name153) && !name153.startsWith(".");
    };
    for (const entry of Deno.readDirSync(project.dir)){
        const srcPath = join3(project.dir, entry.name);
        if (filter11(srcPath)) {
            const destPath = join3(serveDir, entry.name);
            if (entry.isDirectory) {
                copyMinimal(srcPath, destPath, [
                    kSkipHidden
                ], filter11);
            } else {
                copyFileIfNewer(srcPath, destPath);
            }
        }
    }
    copyMinimal(projectFreezerDir(project.dir, true), projectFreezerDir(serveDir, true));
    copyMinimal(projectCrossrefDir(project.dir), projectCrossrefDir(serveDir));
    return Deno.realPathSync(serveDir);
}
function watchProject(project, serveProject1, resourceFiles, flags, pandocArgs, options, renderingOnReload, renderQueue, stopServer, outputFile) {
    const refreshProjectConfig = async ()=>{
        project = await projectContext(project.dir, flags, false, true);
        serveProject1 = await projectContext(serveProject1.dir, flags, false, true);
    };
    const projDir = Deno.realPathSync(project.dir);
    const projDirHidden = projDir + "/.";
    const outputDir = projectOutputDir(project);
    const libDirConfig = project.config?.project[kProjectLibDir];
    const libDirSource = libDirConfig ? join3(project.dir, libDirConfig) : undefined;
    const libDir = libDirConfig ? join3(outputDir, libDirConfig) : undefined;
    const inOutputDir = (path109)=>{
        if (path109.startsWith(outputDir)) {
            if (libDir && path109.startsWith(libDir)) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    };
    const isResourceFile = (path110)=>{
        if (libDirSource && path110.startsWith(libDirSource)) {
            return false;
        } else {
            return project.files.resources?.includes(path110) || resourceFiles.includes(path110);
        }
    };
    const isInputFile = (path111)=>{
        return project.files.input.includes(path111);
    };
    const modified = [];
    const rendered = new Map();
    const handleWatchEvent = async (event)=>{
        try {
            const paths = __VIRTUAL_FILE181(event.paths.filter((path112)=>!path112.startsWith(projDirHidden)
            ));
            if (paths.length === 0) {
                return;
            }
            if ([
                "modify",
                "create"
            ].includes(event.kind)) {
                modified.push(...paths);
                if (options.watchInputs) {
                    const inputs = paths.filter(isInputFile).filter((input)=>{
                        return !rendered.has(input) || rendered.get(input) !== md5Hash(Deno.readTextFileSync(input));
                    });
                    if (inputs.length) {
                        for (const input of inputs){
                            rendered.set(input, md5Hash(Deno.readTextFileSync(input)));
                        }
                        const tempContext = createTempContext();
                        try {
                            const result = await renderQueue.enqueue(()=>{
                                if (inputs.length > 1) {
                                    return renderProject(project, {
                                        temp: tempContext,
                                        progress: true,
                                        flags,
                                        pandocArgs
                                    }, inputs);
                                } else {
                                    return render(inputs[0], {
                                        temp: tempContext,
                                        flags,
                                        pandocArgs: pandocArgs
                                    });
                                }
                            });
                            if (result.error) {
                                if (result.error.message) {
                                    logError(result.error);
                                }
                                return undefined;
                            } else {
                                return {
                                    config: false,
                                    output: true
                                };
                            }
                        } finally{
                            tempContext.cleanup();
                        }
                    }
                }
                const configFile = paths.some((path113)=>(project.files.config || []).includes(path113)
                );
                const inputFileRemoved = project.files.input.some((file)=>!existsSync(file)
                );
                const configResourceFile = paths.some((path114)=>(project.files.configResources || []).includes(path114)
                );
                const resourceFile = paths.some(isResourceFile);
                const outputDirFile = !outputFile && paths.some(inOutputDir);
                const reload = configFile || configResourceFile || resourceFile || outputDirFile || inputFileRemoved;
                if (reload) {
                    return {
                        config: configFile || inputFileRemoved,
                        output: outputDirFile
                    };
                } else {
                    return;
                }
            } else {
                return;
            }
        } catch (e) {
            logError(e);
            return;
        }
    };
    const devServer = httpDevServer(options.port, options.timeout, ()=>renderQueue.isRunning()
    , stopServer);
    const reloadClients = __VIRTUAL_FILE113(async (changes)=>{
        const tempContext = createTempContext();
        try {
            if (!changes.output && !renderingOnReload) {
                await refreshProjectConfig();
                const result = await renderQueue.enqueue(()=>renderProject(project, {
                        temp: tempContext,
                        useFreezer: true,
                        devServerReload: true,
                        flags,
                        pandocArgs
                    })
                );
                if (result.error) {
                    logError(result.error);
                }
            }
            if (changes.config) {
                serveProject1.files.input.forEach(removeIfExists);
            }
            copyProjectForServe(project, !renderingOnReload, serveProject1.dir);
            if (changes.config) {
                await refreshProjectConfig();
            }
            const lastHtmlFile = modified.reverse().find((file)=>{
                return extname2(file) === ".html";
            });
            modified.splice(0, modified.length);
            if (lastHtmlFile && await preventReload(project, lastHtmlFile, options)) {
                return;
            }
            let reloadTarget = "";
            if (lastHtmlFile && options.navigate) {
                if (lastHtmlFile.startsWith(outputDir)) {
                    reloadTarget = relative2(outputDir, lastHtmlFile);
                } else {
                    reloadTarget = relative2(projDir, lastHtmlFile);
                }
                if (existsSync(join3(outputDir, reloadTarget))) {
                    reloadTarget = "/" + pathWithForwardSlashes(reloadTarget);
                } else {
                    reloadTarget = "";
                }
            }
            devServer.reloadClients(reloadTarget);
        } catch (e) {
            logError(e);
        } finally{
            tempContext.cleanup();
        }
    }, 100);
    if (outputFile) {
        const lastOutput = new Map();
        const pollForOutputChange = async ()=>{
            const file = outputFile();
            if (existsSync(file)) {
                const lastMod = Deno.statSync(file).mtime;
                const prevMod = lastOutput.get(file);
                lastOutput.set(file, lastMod);
                if (prevMod !== undefined && lastMod?.getTime() !== prevMod?.getTime()) {
                    await reloadClients({
                        output: true
                    });
                }
            }
            setTimeout(pollForOutputChange, 100);
        };
        setTimeout(pollForOutputChange, 100);
    }
    const runWatcher = (watcherOptions)=>{
        const watchPaths = asArray(watcherOptions.paths);
        const watcher = Deno.watchFs(watchPaths, watcherOptions.options);
        const watchForChanges = async ()=>{
            for await (const event of watcher){
                try {
                    if (event.kind === "create" && !watcherOptions.options?.recursive) {
                        event.paths.forEach((path115)=>{
                            if (existsSync(path115)) {
                                try {
                                    const stat = Deno.statSync(path115);
                                    if (stat.isDirectory) {
                                        if (watchPaths.some((p)=>p === dirname2(path115)
                                        )) {
                                            runWatcher({
                                                paths: path115,
                                                options: {
                                                    recursive: true
                                                }
                                            });
                                        }
                                    }
                                } catch (e) {
                                    if (e instanceof Deno.errors.NotFound) {
                                        return;
                                    }
                                    throw e;
                                }
                            }
                        });
                    }
                    const result = await handleWatchEvent(event);
                    if (result) {
                        await reloadClients(result);
                    }
                } catch (e) {
                    logError(e);
                }
            }
        };
        watchForChanges();
    };
    computeWatchers(project).forEach(runWatcher);
    return Promise.resolve({
        handle: (req)=>{
            return devServer.handle(req);
        },
        connect: devServer.connect,
        injectClient: (file, inputFile)=>{
            return devServer.injectClient(file, inputFile);
        },
        project: ()=>project
        ,
        serveProject: ()=>serveProject1
        ,
        refreshProject: async ()=>{
            await refreshProjectConfig();
            return serveProject1;
        }
    });
}
function computeWatchers(project) {
    const projectDirs = [];
    for (const walk8 of walkSync(project.dir, {
        includeDirs: true,
        includeFiles: false,
        maxDepth: 1,
        followSymlinks: false,
        skip: [
            kSkipHidden
        ].concat(engineIgnoreDirs().map((ignore6)=>globToRegExp(join3(project.dir, ignore6) + SEP)
        ))
    })){
        if (walk8.path !== project.dir) {
            projectDirs.push(walk8.path);
        }
    }
    if (projectDirs.length <= 30) {
        return [
            {
                paths: project.dir,
                options: {
                    recursive: false
                }
            },
            {
                paths: projectDirs,
                options: {
                    recursive: true
                }
            }
        ];
    } else {
        return [
            {
                paths: project.dir,
                options: {
                    recursive: true
                }
            }
        ];
    }
}
async function preventReload(project, lastHtmlFile, options) {
    if (isRStudio() && !options.watchInputs) {
        const index = await inputTargetIndexForOutputFile(project, relative2(projectOutputDir(project), lastHtmlFile));
        if (index) {
            return isRevealjsOutput(Object.keys(index.formats)[0]);
        }
    }
    return false;
}
const kQuartoRenderCommand = "90B3C9E8-0DBC-4BC0-B164-AA2D5C031B28";
const kRenderNone = "none";
const kRenderDefault = "default";
async function serveProject(target, temp, flags, pandocArgs, options) {
    let project1;
    if (typeof target === "string") {
        if (target === ".") {
            target = Deno.cwd();
        }
        project1 = await projectContext(target, flags, false, true);
        if (!project1 || !project1?.config) {
            throw new Error(`${target} is not a website or book project`);
        }
    } else {
        project1 = target;
    }
    if (!projectIsWebsite(project1)) {
        throw new Error(`Cannot serve project of type '${project1?.config?.project[kProjectType] || "default"}' (try using project type 'website').`);
    }
    const projType = projectType(project1?.config?.project?.[kProjectType]);
    options = {
        browse: true,
        watchInputs: true,
        navigate: true,
        ...options
    };
    const renderBefore = options.render !== kRenderNone;
    if (renderBefore) {
        renderProgress("Rendering:");
    } else {
        renderProgress("Preparing to preview");
    }
    flags = {
        ...flags,
        ...renderBefore && options.render !== kRenderDefault ? {
            to: options.render
        } : {}
    };
    if (flags.to === undefined) {
        flags.to = kRenderDefault;
    }
    const pdfOutput = isPdfOutput(flags.to || "");
    let files;
    let resourceFiles = [];
    if (!renderBefore) {
        if (pdfOutput) {
            files = project1.files.input;
        } else {
            const srvFiles = await serveFiles(project1);
            files = srvFiles.files;
            resourceFiles = srvFiles.resourceFiles;
        }
    }
    const renderResult = await renderProject(project1, {
        temp,
        progress: true,
        useFreezer: !renderBefore,
        flags,
        pandocArgs
    }, files);
    if (renderResult.error) {
        throw renderResult.error;
    }
    const finalOutput1 = renderResultFinalOutput(renderResult);
    const serveDir1 = copyProjectForServe(project1, true, temp.createDir());
    const serveProject1 = await projectContext(serveDir1, flags, false, true);
    resourceFiles.push(...__VIRTUAL_FILE181(renderResult.files.flatMap((file)=>file.resourceFiles
    )));
    const renderQueue = new PromiseQueue();
    const pdfOutputFile = finalOutput1 && pdfOutput ? ()=>{
        const project = watcher.project();
        return join3(dirname2(finalOutput1), bookOutputStem(project.dir, project.config) + ".pdf");
    } : undefined;
    const listener = Deno.listen({
        port: options.port,
        hostname: options.host
    });
    const stopServer = ()=>listener.close()
    ;
    const watcher = await watchProject(project1, serveProject1, resourceFiles, flags, pandocArgs, options, !pdfOutput, renderQueue, stopServer, pdfOutputFile);
    const serveOutputDir = projectOutputDir(serveProject1);
    const handlerOptions = {
        baseDir: serveOutputDir,
        printUrls: "all",
        onRequest: async (req)=>{
            if (watcher.handle(req)) {
                return await watcher.connect(req);
            } else if (req.url.includes(kQuartoRenderCommand)) {
                const match = req.url.match(new RegExp(`/${kQuartoRenderCommand}/(.*)$`));
                if (match) {
                    const requestTemp = createTempContext();
                    const path116 = join3(project1.dir, match[1]);
                    render(path116, {
                        temp,
                        flags,
                        pandocArgs
                    }).then((result)=>{
                        if (result.error) {
                            if (result.error?.message) {
                                logError(result.error);
                            }
                        } else {
                            const finalOutput = renderResultFinalOutput(result, project1.dir);
                            if (!finalOutput) {
                                throw new Error("No output created by quarto render " + basename2(path116));
                            }
                            info("Output created: " + finalOutput + "\n");
                        }
                    }).finally(()=>{
                        requestTemp.cleanup();
                    });
                }
                return httpContentResponse("rendered");
            } else {
                return undefined;
            }
        },
        onFile: async (file)=>{
            if (isHtmlContent(file) || isPdfContent(file)) {
                const serveDir = projectOutputDir(watcher.serveProject());
                const filePathRelative = relative2(serveDir, file);
                let inputFile = await inputFileForOutputFile(watcher.serveProject(), filePathRelative);
                if (!inputFile || !existsSync(inputFile)) {
                    inputFile = await inputFileForOutputFile(await watcher.refreshProject(), filePathRelative);
                }
                let result;
                let renderError;
                if (inputFile) {
                    const renderFlags = {
                        ...flags,
                        quiet: true
                    };
                    const renderPandocArgs = projType.projectFormatsOnly ? pandocArgs : removePandocToArg(pandocArgs);
                    if (!projType.projectFormatsOnly) {
                        delete renderFlags?.to;
                    }
                    if (renderFlags?.to == "all") {
                        renderFlags.to = isHtmlContent(file) ? "html" : "pdf";
                    }
                    const tempContext = createTempContext();
                    try {
                        result = await renderQueue.enqueue(()=>renderProject(watcher.serveProject(), {
                                temp: tempContext,
                                useFreezer: true,
                                devServerReload: true,
                                flags: renderFlags,
                                pandocArgs: renderPandocArgs
                            }, [
                                inputFile
                            ])
                        );
                        if (result.error) {
                            logError(result.error);
                            renderError = result.error;
                        }
                    } catch (e) {
                        logError(e);
                        renderError = e;
                    } finally{
                        tempContext.cleanup();
                    }
                }
                const fileContents = renderError ? renderErrorPage(renderError) : Deno.readFileSync(file);
                if (isHtmlContent(file) && inputFile) {
                    const projInputFile = join3(project1.dir, relative2(watcher.serveProject().dir, inputFile));
                    return watcher.injectClient(fileContents, projInputFile);
                } else {
                    return fileContents;
                }
            } else {
                return undefined;
            }
        },
        on404: (url, req)=>{
            const print = !basename2(url).startsWith("jupyter-");
            let body = new TextEncoder().encode("Not Found");
            const custom404 = join3(serveOutputDir, kProject404File);
            if (existsSync(custom404)) {
                let content404 = Deno.readTextFileSync(custom404);
                const sitePath = websitePath(project1?.config);
                if (sitePath !== "/" || isRStudioServer()) {
                    let replacePath = "/";
                    const referer = req.headers.get("referer");
                    if (isRStudioServer() && referer) {
                        const match = referer.match(/\/p\/.*?\//);
                        if (match) {
                            replacePath = match[0];
                        }
                    }
                    content404 = content404.replaceAll(new RegExp('((?:content|ref|src)=")(' + sitePath + ")", "g"), "$1" + replacePath);
                }
                body = new TextEncoder().encode(content404);
            }
            return {
                print,
                body: watcher.injectClient(body)
            };
        }
    };
    const siteUrl = `http://localhost:${options.port}/`;
    printWatchingForChangesMessage();
    let browserPath = typeof options.browse === "string" ? options.browse.replace(/^\//, "") : undefined;
    if (browserPath) {
        const browserPathTarget = await resolveInputTarget(project1, browserPath, false);
        if (browserPathTarget) {
            browserPath = browserPathTarget.outputHref;
        }
    }
    const targetPath = browserPath ? browserPath : pdfOutput ? kPdfJsInitialPath : renderResultUrlPath(renderResult);
    printBrowsePreviewMessage(options.port, targetPath && targetPath !== "index.html" ? targetPath : "");
    if (options.browse && !isRStudioServer() && !isJupyterHubServer()) {
        const browseUrl = targetPath ? targetPath === "index.html" ? siteUrl : siteUrl + targetPath : siteUrl;
        await openUrl(browseUrl);
    }
    if (finalOutput1 && pdfOutput) {
        handlerOptions.baseDir = pdfJsBaseDir();
        handlerOptions.onFile = pdfJsFileHandler(pdfOutputFile, async (file)=>{
            if (isHtmlContent(file)) {
                const fileContents = await Deno.readFile(file);
                return watcher.injectClient(fileContents);
            } else {
                return undefined;
            }
        });
    }
    const handler = httpFileRequestHandler(handlerOptions);
    for await (const conn of listener){
        (async ()=>{
            for await (const { request , respondWith  } of Deno.serveHttp(conn)){
                try {
                    await respondWith(handler(request));
                } catch (err) {
                    warning(err.message);
                }
            }
        })();
    }
}
function renderErrorPage(e) {
    const content = `
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Quarto Render Error</title>
<script id="quarto-render-error" type="text/plain">${e.message}</script>
</head>
<body>
</body>
</html>
`;
    return new TextEncoder().encode(content);
}
async function serveFiles(project) {
    await initDenoDom();
    const files = [];
    const resourceFiles = [];
    for(let i = 0; i < project.files.input.length; i++){
        const inputFile = project.files.input[i];
        const projRelative = relative2(project.dir, inputFile);
        const target = await resolveInputTarget(project, projRelative, false);
        if (target) {
            const outputFile = join3(projectOutputDir(project), target?.outputHref);
            if (isModifiedAfter(inputFile, outputFile)) {
                files.push(inputFile);
            } else {
                const files = [];
                if (isHtmlContent(outputFile)) {
                    const htmlInput = Deno.readTextFileSync(outputFile);
                    const doc = new DOMParser().parseFromString(htmlInput, "text/html");
                    const resolver = htmlResourceResolverPostprocessor(inputFile, project);
                    files.push(...(await resolver(doc)).resources);
                }
                const partitioned = await partitionedMarkdownForInput(project.dir, projRelative);
                const globs = [];
                if (partitioned?.yaml) {
                    const metadata = partitioned.yaml;
                    globs.push(...resourcesFromMetadata(metadata[kResources]));
                }
                resourceFiles.push(...await resourceFilesFromFile(project.dir, projRelative, {
                    files,
                    globs
                }, false, [
                    join3(dirname2(projRelative), inputFilesDir(projRelative))
                ], partitioned));
            }
        } else {
            warning("Unabled to resolve output target for " + inputFile);
        }
    }
    return {
        files,
        resourceFiles: __VIRTUAL_FILE181(resourceFiles)
    };
}
const previewCommand = new Command().name("preview").stopEarly().option("--port [port:number]", "Suggested port to listen on (defaults to random value between 3000 and 8000).\n" + "If the port is not available then a random port between 3000 and 8000 will be selected.").option("--host [host:string]", "Hostname to bind to (defaults to 127.0.0.1)").option("--render [format:string]", "Render to the specified format(s) before previewing", {
    default: kRenderNone
}).option("--no-render", "Do not re-render input files when they change.", {
    hidden: true
}).option("--presentation", "Preview in presentation mode", {
    hidden: true
}).option("--no-navigate", "Don't navigate the browser automatically when outputs are updated.").option("--browser-path", "Initial path to navigate browser to").option("--no-browser", "Don't open a browser to preview the site.").option("--no-browse", "Don't open a browser to preview the site.", {
    hidden: true
}).option("--watch-inputs", "Re-render input files when they change.").option("--no-watch-inputs", "Do not re-render input files when they change.").option("--timeout", "Time (in seconds) after which to exit if there are no active clients.").arguments("[file:string] [...args:string]").description("Render and preview a Quarto document or website project. Automatically reloads the browser when\n" + "input files are re-rendered or document resources (e.g. CSS) change.\n\n" + "For website preview, the most recent execution results of computational documents are used to render\n" + "the site (this is to optimize startup time). If you want to perform a full render prior to\n" + 'previewing pass the --render option with "all" or a comma-separated list of formats to render.\n\n' + "For document preview, input file changes will result in a re-render (pass --no-watch to prevent).\n\n" + "You can also include arbitrary command line arguments to be forwarded to " + bold("quarto render") + ".").example("Preview document", "quarto preview doc.qmd").example("Preview document with render command line args", "quarto preview doc.qmd --toc").example("Preview document (don't watch for input changes)", "quarto preview doc.qmd --no-watch-inputs").example("Preview website with most recent execution results", "quarto preview").example("Previewing website using a specific port", "quarto preview --port 4444").example("Preview website (don't open a browser)", "quarto preview --no-browser").example("Fully render all website/book formats then preview", "quarto preview --render all").example("Fully render the html format then preview", "quarto preview --render html").action(async (options, file, args)=>{
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
    file = file || Deno.cwd();
    if (!existsSync(file)) {
        throw new Error(`${file} not found`);
    }
    args = args || [];
    const portPos = args.indexOf("--port");
    if (portPos !== -1) {
        options.port = parseInt(args[portPos + 1]);
        args.splice(portPos, 2);
    }
    const hostPos = args.indexOf("--host");
    if (hostPos !== -1) {
        options.host = String(args[hostPos + 1]);
        args.splice(hostPos, 2);
    }
    const renderPos = args.indexOf("--render");
    if (renderPos !== -1) {
        options.render = String(args[renderPos + 1]);
        args.splice(renderPos, 2);
    }
    const presentationPos = args.indexOf("--presentation");
    if (presentationPos !== -1) {
        options.presentation = true;
        args.splice(presentationPos, 1);
    } else {
        options.presentation = false;
    }
    const browserPathPos = args.indexOf("--browser-path");
    if (browserPathPos !== -1) {
        options.browserPath = String(args[browserPathPos + 1]);
        args.splice(browserPathPos, 2);
    }
    const noBrowsePos = args.indexOf("--no-browse");
    if (noBrowsePos !== -1) {
        options.browse = false;
        args.splice(noBrowsePos, 1);
    }
    const noBrowserPos = args.indexOf("--no-browser");
    if (noBrowserPos !== -1) {
        options.browser = false;
        args.splice(noBrowserPos, 1);
    }
    const noNavigatePos = args.indexOf("--no-navigate");
    if (noNavigatePos !== -1) {
        options.navigate = false;
        args.splice(noNavigatePos, 1);
    }
    const watchInputsPos = args.indexOf("--watch-inputs");
    if (watchInputsPos !== -1) {
        options.watchInputs = true;
        args.splice(watchInputsPos, 1);
    }
    const noWatchInputsPos = args.indexOf("--no-watch-inputs");
    if (noWatchInputsPos !== -1) {
        options.watchInputs = false;
        args.splice(noWatchInputsPos, 1);
    }
    const timeoutPos = args.indexOf("--timeout");
    if (timeoutPos !== -1) {
        options.timeout = parseInt(args[timeoutPos + 1]);
        args.splice(timeoutPos, 2);
    } else {
        options.timeout = 0;
    }
    const noWatchPos = args.indexOf("--no-watch");
    if (noWatchPos !== -1) {
        options.watchInputs = false;
        args.splice(noWatchPos, 1);
    }
    const noRenderPos = args.indexOf("--no-render");
    if (noRenderPos !== -1) {
        options.watchInputs = false;
        args.splice(noRenderPos, 1);
    }
    if (options.watchInputs === undefined) {
        options.watchInputs = !isRStudio();
    }
    options.host = options.host || kLocalhost;
    if (!options.port) {
        options.port = findOpenPort();
    } else {
        options.port = findOpenPort(parseInt(options.port));
    }
    const flags = parseRenderFlags(args);
    args = fixupPandocArgs(args, flags);
    if (Deno.statSync(file).isDirectory) {
        const tempContext = createTempContext();
        try {
            await serveProject(file, tempContext, flags, args, {
                port: options.port,
                host: options.host,
                render: options.render,
                browse: options.browser && options.browse ? typeof options.browserPath === "string" ? options.browserPath : true : false,
                watchInputs: options.watchInputs,
                navigate: options.navigate,
                timeout: options.timeout
            });
        } finally{
            tempContext.cleanup();
        }
    } else {
        if (options.render !== kRenderNone && options.render !== kRenderDefault && args.indexOf("--to") === -1) {
            args.push("--to", options.render);
        }
        await preview(file, flags, args, {
            port: options.port,
            host: options.host,
            browse: !!(options.browser && options.browse),
            presentation: options.presentation,
            watchInputs: !!options.watchInputs,
            timeout: options.timeout
        });
    }
});
async function markdownToJupyterNotebook(file, includeIds) {
    const notebook = await quartoMdToJupyter(file, includeIds);
    return JSON.stringify(notebook, null, 2);
}
async function jupyterNotebookToMarkdown(file, includeIds) {
    const notebook = jupyterFromFile(file);
    const kernelspec = notebook.metadata.kernelspec;
    const md = [];
    let frontMatter;
    for(let i = 0; i < notebook.cells.length; i++){
        {
            const cell = notebook.cells[i];
            switch(cell.cell_type){
                case "markdown":
                    md.push(...mdFromContentCell(cell));
                    break;
                case "raw":
                    if (i === 0) {
                        frontMatter = partitionYamlFrontMatter(cell.source.join(""))?.yaml;
                        if (!frontMatter) {
                            md.push(...mdFromRawCell(cell));
                        }
                    } else {
                        md.push(...mdFromRawCell(cell));
                    }
                    break;
                case "code":
                    md.push(...mdFromCodeCell1(kernelspec.language.toLowerCase(), cell, includeIds));
                    break;
                default:
                    throw new Error("Unexpected cell type " + cell.cell_type);
            }
            if (i > 0 || !frontMatter) {
                md.push("\n");
            }
        }
    }
    const mdSource = md.join("");
    const yaml = frontMatter ? readYamlFromMarkdown(frontMatter) : {};
    yaml.jupyter = notebook.metadata.jupytext ? {
        jupytext: notebook.metadata.jupytext,
        kernelspec: notebook.metadata.kernelspec
    } : notebook.metadata.kernelspec.name;
    if (typeof yaml.jupyter === "string") {
        if (!await jupyterKernelspec(yaml.jupyter)) {
            yaml.jupyter = {
                kernelspec: notebook.metadata.kernelspec
            };
        }
    }
    const yamlText = stringify(yaml, {
        indent: 2,
        sortKeys: false,
        skipInvalid: true
    });
    return `---\n${yamlText}---\n\n${mdSource}`;
}
function mdFromCodeCell1(language, cell, includeIds) {
    if (!cell.source.length) {
        return [];
    }
    const md = [
        "```{" + language + "}\n"
    ];
    const { yaml , source  } = partitionCellOptions(language, cell.source);
    const options = yaml ? yaml : {};
    if (cell.id) {
        if (!includeIds) {
            cell.id = undefined;
        } else if (options[kCellLabel]) {
            const label = String(options[kCellLabel]);
            if (jupyterAutoIdentifier(label) === cell.id) {
                cell.id = undefined;
            }
        }
    }
    let yamlOptions = {};
    if (cell.id) {
        yamlOptions[kCellId] = cell.id;
    }
    yamlOptions = {
        ...cell.metadata,
        ...yaml,
        ...yamlOptions
    };
    if (yamlOptions[kCellId]) {
        md.push(...jupyterCellOptionsAsComment(language, {
            id: yamlOptions[kCellId]
        }));
        delete yamlOptions[kCellId];
    }
    if (yaml) {
        const yamlOutput = {};
        for(const key in yaml){
            const value = yamlOptions[key];
            if (value !== undefined) {
                yamlOutput[key] = value;
                delete yamlOptions[key];
            }
        }
        md.push(...jupyterCellOptionsAsComment(language, yamlOutput));
    }
    const metadataOutput = {};
    for(const key in cell.metadata){
        const value = cell.metadata[key];
        if (value !== undefined) {
            metadataOutput[key] = value;
            delete yamlOptions[key];
        }
    }
    md.push(...jupyterCellOptionsAsComment(language, metadataOutput, {
        flowLevel: 1
    }));
    md.push(...mdEnsureTrailingNewline(source));
    md.push("```\n");
    return md;
}
const kObservableSiteUrl = "https://observablehq.com/";
const kObservableApiUrl = "https://api.observablehq.com/";
const kFormatHtml = "format: html";
function isObservableUrl(url) {
    return url.startsWith(kObservableSiteUrl) || url.startsWith(kObservableApiUrl);
}
async function observableNotebookToMarkdown(url, output) {
    const originalUrl = url;
    if (url.startsWith(kObservableSiteUrl)) {
        const nbPath = url.slice(kObservableSiteUrl.length).replace(/^d\//, "");
        url = `${kObservableApiUrl}document/${nbPath}`;
    }
    const res = await fetch(url);
    if (res.status === 404) {
        throw new Error(`Convert ${url} failed with error: ${res.statusText}`);
    }
    const body = new Uint8Array(await res.arrayBuffer());
    const json5 = new TextDecoder().decode(body);
    const nb = JSON.parse(json5);
    if ([
        "isc",
        "mit",
        "bsd-3-clause",
        "apache-2.0"
    ].indexOf(nb.license) === -1) {
        throw new Error(`Convert ${url} failed: notebook doesn't have a permissive open-source license`);
    }
    let file = output ? basename2(output) : undefined;
    if (!file) {
        const slug = nb.slug || nb.fork_of?.slug;
        if (typeof slug === "string") {
            file = slug;
        } else if (typeof nb.title === "string") {
            file = pandocAutoIdentifier(nb.title, false);
        } else {
            file = nb.id;
        }
    }
    let outputFile = output;
    let outputDir = output ? dirname2(output) : undefined;
    if (!outputDir) {
        if (nb.files.length > 0) {
            outputDir = file;
        } else {
            outputDir = Deno.cwd();
        }
    }
    if (!outputFile) {
        outputFile = join3(outputDir, file + ".qmd");
    }
    ensureDirSync(outputDir);
    info(`Writing to ${nb.files.length > 0 ? bold(basename2(outputDir) + "/") : basename2(outputFile)}`);
    const attachments = [];
    for (const file1 of nb.files){
        info("  " + file1.name + " (attachment)");
        const res = await fetch(file1.download_url);
        const contents = new Uint8Array(await res.arrayBuffer());
        const downloadTo = await Deno.create(join3(outputDir, file1.name));
        await writeAll(downloadTo, contents);
        Deno.close(downloadTo.rid);
        attachments.push(file1.name);
    }
    const pinned1 = nb.nodes.reduce((pinned, node)=>{
        return pinned + (node.pinned ? 1 : 0);
    }, 0);
    const echo = pinned1 > nb.nodes.length / 2;
    const kModePrefixes = [
        "md",
        "html",
        "tex"
    ].map((prefix)=>({
            prefix,
            re: new RegExp("^" + prefix + "\\s*`((.|\\n)+)`\\s*;?")
        })
    );
    const lines17 = [];
    for(let i = 0; i < nb.nodes.length; i++){
        const node = nb.nodes[i];
        let mode = node.mode;
        let value = node.value;
        const trimmedValue = value.trim();
        if (mode === "js") {
            for (const { prefix , re  } of kModePrefixes){
                const m = trimmedValue.match(re);
                if (m) {
                    mode = prefix;
                    value = m[1];
                }
            }
        }
        if (i === 0) {
            const skip = consumeFrontMatter(originalUrl, nb.creator, nb.publish_time, nb.license || "unknown", echo, mode, value, nb.nodes[1], lines17);
            if (skip > 0) {
                i = skip - 1;
                continue;
            }
        }
        switch(mode){
            case "js":
                lines17.push("```{ojs}");
                if (node.pinned && !echo) {
                    lines17.push("//| echo: true");
                } else if (!node.pinned && echo) {
                    lines17.push("//| echo: false");
                }
                lines17.push(value);
                lines17.push("```");
                break;
            case "md":
                lines17.push(value);
                break;
            case "html":
                lines17.push("```{=html}");
                lines17.push(value);
                lines17.push("```");
                break;
            case "tex":
                lines17.push("$$");
                lines17.push(value);
                lines17.push("$$");
                break;
            default:
                warning("Unknown mode: " + mode);
        }
        lines17.push("");
    }
    lines17.push("");
    if (nb.files.length > 0) {
        info("  " + basename2(outputFile));
    }
    Deno.writeTextFileSync(outputFile, lines17.join("\n"));
}
function consumeFrontMatter(url, creator, date, license, echo, mode, value, nextNode, lines18) {
    let skip = 0;
    let needFormat = true;
    let title26 = "";
    let leadingMd = "";
    lines18.push("---");
    if (mode === "md") {
        leadingMd = value.replace(/^\s*#\s+(.*)\n?/, (_m, p1)=>{
            title26 = p1;
            return "";
        }).trim();
        if (title26) {
            skip++;
            lines18.push('title: "' + title26 + '"');
            if (nextNode?.mode === "js") {
                const nodeValue = nextNode.value;
                const metaMatch = nodeValue.match(/^\s*\/\*-{3,}\s*([\S\s)]*)\n\-{3,}\*\/\s*$/);
                if (metaMatch) {
                    const yaml = metaMatch[1];
                    if (yaml.includes("format:")) {
                        needFormat = false;
                    }
                    lines18.push(yaml);
                    skip++;
                }
            }
        }
    }
    if (creator?.name) {
        lines18.push('author: "' + String(creator?.name) + '"');
    }
    if (date) {
        lines18.push("date: " + new Date(date).toISOString().slice(0, 10));
    }
    lines18.push("license: " + String(license));
    lines18.push(`observablehq-url: ${url}`);
    if (needFormat) {
        lines18.push(kFormatHtml);
    }
    if (echo == false) {
        lines18.push("execute:");
        lines18.push("  echo: false");
    }
    lines18.push("---");
    lines18.push("");
    if (leadingMd) {
        lines18.push(leadingMd);
        lines18.push("");
    }
    return skip;
}
const kNotebookFormat = "notebook";
const kMarkdownFormat = "markdown";
const convertCommand = new Command().name("convert").arguments("[input:string]").description("Convert documents to alternate representations.").option("-o, --output [path:string]", "Write output to PATH.").option("--with-ids", "Include ids in conversion").example("Convert notebook to markdown", "quarto convert mydocument.ipynb ").example("Convert markdown to notebook", "quarto convert mydocument.qmd").example("Convert notebook to markdown, writing to file", "quarto convert mydocument.ipynb --output mydoc.qmd").action(async (options, input)=>{
    if (isObservableUrl(input)) {
        await observableNotebookToMarkdown(input, options.output);
    } else {
        if (!await exists(input)) {
            throw new Error(`File not found: '${input}'`);
        }
        const srcFormat = isJupyterNotebook(input) ? kNotebookFormat : kMarkdownFormat;
        const withIds = options.withIds === undefined ? false : !!options.withIds;
        const converted = srcFormat === kNotebookFormat ? await jupyterNotebookToMarkdown(input, withIds) : await markdownToJupyterNotebook(input, withIds);
        const [dir, stem] = dirAndStem(input);
        let output = options.output;
        if (!output) {
            output = join3(dir, stem + (srcFormat === kMarkdownFormat ? ".ipynb" : ".qmd"));
        }
        Deno.writeTextFileSync(output, converted);
        info(`Converted to ${output}`);
    }
});
async function capabilities() {
    const caps = {
        formats: await formats(),
        themes: await themes(),
        python: await jupyterCapabilities()
    };
    if (caps.python) {
        const pythonEx = caps.python;
        if (pythonEx.jupyter_core) {
            pythonEx.kernels = Array.from((await jupyterKernelspecs()).values());
        }
        pythonEx.venv = !pythonEx.conda;
    }
    return caps;
}
async function formats() {
    const formats1 = await pandocListFormats();
    const commonFormats = [
        "html",
        "pdf",
        "docx",
        "odt",
        "pptx",
        "beamer",
        "revealjs",
        "gfm",
        "hugo",
        "epub", 
    ];
    const excludedFormats = [
        "bibtex",
        "biblatex",
        "csljson", 
    ];
    return __VIRTUAL_FILE137(commonFormats.concat(__VIRTUAL_FILE137(formats1, commonFormats)), excludedFormats);
}
async function themes() {
    const themesPath = formatResourcePath("html", join3("bootstrap", "themes"));
    const themes1 = [
        "default"
    ];
    const kScss = ".scss";
    for await (const dirEntry of Deno.readDir(themesPath)){
        if (dirEntry.isFile && dirEntry.name.endsWith(kScss)) {
            themes1.push(basename2(dirEntry.name, kScss));
        }
    }
    return themes1;
}
const capabilitiesCommand = new Command().name("capabilities").description("Query for current capabilities (output formats, engines, kernels etc.)").action(async ()=>{
    const capsJSON = JSON.stringify(await capabilities(), undefined, 2);
    writeAllSync(Deno.stdout, new TextEncoder().encode(capsJSON));
});
const kIndent = "      ";
async function check(target) {
    const temp = createTempContext();
    try {
        info("");
        if (target === "install" || target === "all") {
            await checkInstall(temp);
        }
        if (target === "jupyter" || target === "all") {
            await checkJupyterInstallation(temp);
        }
        if (target === "knitr" || target === "all") {
            await checkKnitrInstallation(temp);
        }
    } finally{
        temp.cleanup();
    }
}
async function checkInstall(temp) {
    completeMessage("Checking Quarto installation......OK");
    info(`      Version: ${quartoConfig.version()}`);
    info(`      Path: ${quartoConfig.binPath()}`);
    info("");
    const kMessage = "Checking basic markdown render....";
    await withSpinner({
        message: kMessage,
        doneMessage: kMessage + "OK\n"
    }, async ()=>{
        const mdPath = temp.createFile({
            suffix: "check.md"
        });
        Deno.writeTextFileSync(mdPath, `
---
title: "Title"
---

## Header
`);
        const result = await render(mdPath, {
            temp,
            flags: {
                quiet: true
            }
        });
        if (result.error) {
            throw result.error;
        }
    });
}
async function checkJupyterInstallation(temp) {
    const kMessage = "Checking Python 3 installation....";
    let caps;
    await withSpinner({
        message: kMessage,
        doneMessage: false
    }, async ()=>{
        caps = await jupyterCapabilities();
    });
    if (caps) {
        completeMessage(kMessage + "OK");
        info(await jupyterCapabilitiesMessage(caps, kIndent));
        info("");
        if (caps.jupyter_core) {
            const kJupyterMessage = "Checking Jupyter engine render....";
            await withSpinner({
                message: kJupyterMessage,
                doneMessage: kJupyterMessage + "OK\n"
            }, async ()=>{
                await checkJupyterRender(temp);
            });
        } else {
            info(await jupyterInstallationMessage(caps, kIndent));
            info("");
            const envMessage = jupyterUnactivatedEnvMessage(caps, kIndent);
            if (envMessage) {
                info(envMessage);
                info("");
            }
        }
    } else {
        completeMessage(kMessage + "(None)\n");
        info(pythonInstallationMessage(kIndent));
        info("");
    }
}
async function checkJupyterRender(temp) {
    const qmdPath = temp.createFile({
        suffix: "check.qmd"
    });
    Deno.writeTextFileSync(qmdPath, `
---
title: "Title"
---

## Header

\`\`\`{python}
1 + 1
\`\`\`
`);
    const result = await render(qmdPath, {
        temp,
        flags: {
            quiet: true,
            executeDaemon: 0
        }
    });
    if (result.error) {
        throw result.error;
    }
}
async function checkKnitrInstallation(temp) {
    const kMessage = "Checking R installation...........";
    let caps;
    await withSpinner({
        message: kMessage,
        doneMessage: false
    }, async ()=>{
        caps = await knitrCapabilities();
    });
    if (caps) {
        completeMessage(kMessage + "OK");
        info(knitrCapabilitiesMessage(caps, kIndent));
        info("");
        if (caps.rmarkdown) {
            const kKnitrMessage = "Checking Knitr engine render......";
            await withSpinner({
                message: kKnitrMessage,
                doneMessage: kKnitrMessage + "OK\n"
            }, async ()=>{
                await checkKnitrRender(temp);
            });
        } else {
            info(knitrInstallationMessage(kIndent));
            info("");
        }
    } else {
        completeMessage(kMessage + "(None)\n");
        info(rInstallationMessage(kIndent));
        info("");
    }
}
async function checkKnitrRender(temp) {
    const rmdPath = temp.createFile({
        suffix: "check.rmd"
    });
    Deno.writeTextFileSync(rmdPath, `
---
title: "Title"
---

## Header

\`\`\`{r}
1 + 1
\`\`\`
`);
    const result = await render(rmdPath, {
        temp,
        flags: {
            quiet: true
        }
    });
    if (result.error) {
        throw result.error;
    }
}
const kTargets = [
    "install",
    "jupyter",
    "knitr",
    "all"
];
const checkCommand = new Command().name("check").arguments("[target:string]").description("Check and verify correct functioning of Quarto installation and computation engines.\n" + "Check specific functionality with argument install, jupyter, knitr, or all.").example("Check Quarto installation", "quarto check install").example("Check Jupyter engine", "quarto check jupyter").example("Check Knitr engine", "quarto check knitr").example("Check installation and all engines", "quarto check all").action(async (_options, target)=>{
    target = target || "all";
    if (!kTargets.includes(target)) {
        error("Invalid target '" + target + "' (valid targets are " + kTargets.join(", ") + ").");
    }
    await check(target);
});
const inspectCommand = new Command().name("inspect").arguments("[path:string]").description("Inspect a Quarto project or input path. Inspecting a project returns its config and engines.\n" + "Inspecting an input path return its formats, engine, and dependent resources.\n\n" + "Emits results of inspection as JSON to stdout.").example("Inspect project in current directory", "quarto inspect").example("Inspect project in directory", "quarto inspect myproject").example("Inspect input path", "quarto inspect document.md").action(async (_options, path117)=>{
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
    path117 = path117 || Deno.cwd();
    if (!existsSync(path117)) {
        throw new Error(`${path117} not found`);
    }
    let version12 = quartoConfig.version();
    if (version12 === kLocalDevelopment) {
        version12 = "99.9.9";
    }
    const context = await projectContext(path117);
    let config;
    const stat = Deno.statSync(path117);
    if (stat.isDirectory) {
        if (context?.config) {
            config = {
                quarto: {
                    version: version12
                },
                engines: context.engines,
                config: context.config
            };
        } else {
            throw new Error(`${path117} is not a quarto project.`);
        }
    } else {
        const engine = fileExecutionEngine(path117);
        if (engine) {
            const partitioned = await engine.partitionedMarkdown(path117);
            const formats15 = await renderFormats(path117);
            const resourceConfig = Object.values(formats15).reduce((resources, format183)=>{
                resources = uniq1(resources.concat(resourcesFromMetadata(format183.metadata[kResources])));
                if (format183.pandoc[kCss]) {
                    return __VIRTUAL_FILE181(resources.concat(resourcesFromMetadata(format183.pandoc[kCss])));
                } else {
                    return resources;
                }
            }, []);
            const context = await projectContext(path117);
            const fileDir = Deno.realPathSync(dirname2(path117));
            const resources1 = await resolveResources(context ? context.dir : fileDir, fileDir, partitioned.markdown, resourceConfig);
            config = {
                quarto: {
                    version: version12
                },
                engines: [
                    engine.name
                ],
                formats: formats15,
                resources: resources1
            };
            if (context) {
                config.project = relative2(dirname2(path117), context.dir);
            }
        } else {
            throw new Error(`${path117} is not a valid Quarto input document`);
        }
    }
    const output = JSON.stringify(config, undefined, 2);
    Deno.stdout.writeSync(new TextEncoder().encode(output + "\n"));
});
async function resolveResources(rootDir, fileDir, markdown, globs) {
    const resolved = await resolveFileResources(rootDir, fileDir, markdown, globs);
    const resources = __VIRTUAL_FILE137(resolved.include, resolved.exclude);
    const allResources = resources.concat(cssFileResourceReferences(resources));
    return allResources.map((file)=>relative2(rootDir, file)
    );
}
let schemaResourcesLoaded = false;
async function ensureSchemaResources() {
    if (!schemaResourcesLoaded) {
        schemaResourcesLoaded = true;
        const resources = {};
        for (const walk9 of expandGlobSync(resourcePath("schema/*.yml"))){
            resources[`schema/${walk9.name}`] = readYaml(walk9.path);
        }
        resources[`pandoc/formats.yml`] = await pandocListFormats();
        setYamlIntelligenceResources(resources);
        await loadDefaultSchemaDefinitions();
    }
}
async function buildSchemaFile() {
    await ensureSchemaResources();
    getFormatAliases();
    await getFrontMatterSchema();
    await getProjectConfigSchema();
    await getEngineOptionsSchema();
    const externalSchemas = [
        revealPluginSchema
    ];
    for (const schema of externalSchemas){
        setSchemaDefinition(schema);
    }
    const htmlDescriptions = await createHtmlDescriptions();
    setYamlIntelligenceResources({
        "schema/html-descriptions.yml": htmlDescriptions,
        "schema/external-schemas.yml": externalSchemas
    });
    const yamlResources = exportYamlIntelligenceResources(true);
    const yamlResourcesPath = resourcePath("/editor/tools/yaml/yaml-intelligence-resources.json");
    Deno.writeTextFileSync(yamlResourcesPath, yamlResources);
}
function getMarkdownDescriptions() {
    const result = [];
    const schemaList = Object.values(getSchemaDefinitionsObject());
    for (const schema of schemaList){
        walkSchema(schema, (s)=>{
            if (s === false || s === true) {
                return;
            }
            const description = s?.tags?.description;
            if (description === undefined) {
                return;
            }
            result.push(`## annotation\n`);
            if (typeof description === "string") {
                result.push(`### string\n`);
                result.push(description);
                result.push("");
            } else {
                result.push(`### short\n`);
                result.push(description?.short || "");
                result.push("");
                result.push(`### long\n`);
                result.push(description?.long || "");
                result.push("");
            }
            return;
        });
    }
    return result.join("\n");
}
async function createHtmlDescriptions() {
    const markdownDescriptions = getMarkdownDescriptions();
    const descriptionList = [];
    const cmd = [
        pandocBinaryPath(),
        "--to",
        "html"
    ];
    const pandocResult = await execProcess({
        stdout: "piped",
        cmd
    }, markdownDescriptions);
    if (!pandocResult.success) {
        throw new Error("Internal error - couldn't run pandoc");
    }
    await initDenoDom();
    const doc = new DOMParser().parseFromString(pandocResult.stdout, "text/html");
    for (const entryNode of doc.querySelectorAll("h2")){
        const entry = entryNode;
        const values11 = {};
        for (const value of filter1(stopWhen(siblings(entry), (e)=>e.tagName === "H2"
        ), (e)=>e.tagName === "H3"
        )){
            const name154 = value.textContent;
            const html = [];
            for (const p of stopWhen(siblings(value), (e)=>e.tagName !== "P"
            )){
                html.push(p.innerHTML);
            }
            values11[name154] = html.join("\n");
        }
        if (values11["string"]) {
            descriptionList.push(values11["string"]);
        } else if (values11["short"] || values11["long"]) {
            descriptionList.push({
                short: values11["short"],
                long: values11["long"]
            });
        }
    }
    return descriptionList;
}
function* siblings(entry) {
    do {
        if (entry.nextElementSibling === null) {
            return;
        }
        entry = entry.nextElementSibling;
        yield entry;
    }while (true)
}
function* stopWhen(gen, when) {
    for (const v of gen){
        if (when(v)) {
            break;
        }
        yield v;
    }
}
function* filter1(gen, f) {
    for (const v of gen){
        if (f(v)) {
            yield v;
        }
    }
}
function ensureAllowableIDESyntax(src, filename) {
    const ast = parse32(src, {
        ecmaVersion: "2020",
        sourceType: "module"
    });
    let failed = false;
    simple(ast, {
        ChainExpression (_node) {
            console.error(`Failure: Chain expression \`?.\` not allowed in ${filename}`);
            failed = true;
        },
        LogicalExpression (node) {
            if (node.operator === "??") {
                console.error(`Failure: Nullish coalescing operator \`??\` not allows in ${filename}`);
                failed = true;
            }
        }
    });
    if (failed) {
        throw new Error("Found syntax that is not allowed");
    }
}
async function buildQuartoOJS() {
    const src = await esbuildCompile("", resourcePath("formats/html/ojs"), [
        "quarto-ojs.js"
    ], "esm");
    await Deno.writeTextFile(resourcePath("build/quarto-ojs.js"), src);
    ensureAllowableIDESyntax(src, "quarto-ojs.js");
    return copy1(resourcePath("build/quarto-ojs.js"), resourcePath("formats/html/ojs/esbuild-bundle.js"), {
        overwrite: true
    });
}
async function buildYAMLJS() {
    const treeSitterYamlJson = {
        "data": Array.from(Deno.readFileSync(resourcePath("editor/tools/yaml/tree-sitter-yaml.wasm")))
    };
    Deno.writeTextFileSync(resourcePath("editor/tools/yaml/tree-sitter-yaml.json"), JSON.stringify(treeSitterYamlJson));
    const esbuild = async (cwd, filename, outputType = "iife", checkIde = true)=>{
        const result = await esbuildCompile("", cwd, [
            filename
        ], outputType);
        if (checkIde) {
            ensureAllowableIDESyntax(result, filename);
        }
        return result;
    };
    Deno.writeTextFileSync(resourcePath("editor/tools/yaml/yaml-intelligence.js"), await esbuild(resourcePath("../core/lib/yaml-intelligence"), "ide-main.ts", "esm"));
    Deno.writeTextFileSync(resourcePath("editor/tools/yaml/yaml.js"), await esbuild(resourcePath("editor/tools/yaml"), "automation.js"));
    const webWorkerSrc = await esbuild(resourcePath("../core/lib/yaml-intelligence"), "web-worker.ts");
    const vsCodeSrc = await esbuild(resourcePath("../core/lib/yaml-intelligence"), "vs-code.ts", "esm", false);
    const treeSitter = Deno.readTextFileSync(resourcePath("editor/tools/yaml/tree-sitter.js"));
    ensureAllowableIDESyntax(treeSitter, "tree-sitter.js");
    Deno.writeTextFileSync(resourcePath("editor/tools/vs-code.mjs"), [
        treeSitter,
        vsCodeSrc
    ].join(""));
    Deno.writeTextFileSync(resourcePath("editor/tools/yaml/web-worker.js"), [
        treeSitter,
        webWorkerSrc
    ].join(""));
}
async function buildAssets() {
    await buildSchemaFile();
    await Promise.all([
        buildQuartoOJS(),
        buildYAMLJS(), 
    ]);
}
const buildJsCommand = new Command().name("build-js").hidden().description("Builds all the javascript assets necessary for IDE support.\n\n").action(async (_options, _path)=>{
    await buildAssets();
});
function commands() {
    return [
        renderCommand,
        serveCommand,
        createProjectCommand,
        previewCommand,
        convertCommand,
        capabilitiesCommand,
        checkCommand,
        inspectCommand,
        toolsCommand,
        buildJsCommand, 
    ];
}
const kDevConfig = "dev-config";
function createDevConfig(deno, deno_dom, pandoc, dartsass, esbuild, scriptDir) {
    const scriptPath = join3(scriptDir, "quarto" + (isWindows1() ? ".cmd" : ""));
    return {
        deno,
        deno_dom,
        pandoc,
        dartsass,
        esbuild,
        script: md5Hash(Deno.readTextFileSync(scriptPath))
    };
}
function readInstalledDevConfig() {
    const binPath = quartoConfig.binPath();
    const configPath = join3(binPath, "..", "config", kDevConfig);
    if (existsSync(configPath)) {
        return JSON.parse(Deno.readTextFileSync(configPath));
    } else {
        return null;
    }
}
function readSourceDevConfig() {
    const configurationScript = join3(quartoConfig.sharePath(), "..", "..", "configuration");
    const configurationScriptSrc = Deno.readTextFileSync(configurationScript);
    const readConfig = (key)=>{
        const regex = new RegExp(`${key}=(\\S+)`);
        const match = configurationScriptSrc.match(regex);
        if (match) {
            return match[1];
        } else {
            return "";
        }
    };
    const srcScriptPath = join3(quartoConfig.binPath(), "..", "..", "scripts", isWindows1() ? "windows" : "common");
    return createDevConfig(readConfig("DENO"), readConfig("DENO_DOM"), readConfig("PANDOC"), readConfig("DARTSASS"), readConfig("ESBUILD"), srcScriptPath);
}
function devConfigsEqual(a, b) {
    return a.deno === b.deno && a.deno_dom === b.deno_dom && a.pandoc === b.pandoc && a.dartsass == b.dartsass && a.esbuild == b.esbuild && a.script == b.script;
}
async function reconfigureQuarto(installed3, source) {
    const configureScript = isWindows1() ? ".\\configure-windows.cmd" : isMac() ? "./configure-macos.sh" : "./configure-linux.sh";
    const quartoDir1 = Deno.realPathSync(join3(quartoConfig.binPath(), "..", "..", ".."));
    const process = Deno.run({
        cmd: [
            configureScript
        ],
        cwd: quartoDir1
    });
    await process.status();
    info("");
    error(`Quarto required reconfiguration to ${reconfigureReason(installed3, source)}. Please try command again.\n`);
}
function reconfigureReason(installed4, source) {
    const versionMessage = (dep, version13)=>{
        return `install ${dep} version ${version13}`;
    };
    if (installed4 === null || installed4.deno !== source.deno) {
        return versionMessage("Deno", source.deno);
    } else if (installed4.deno_dom !== source.deno_dom) {
        return versionMessage("Deno Dom", source.deno_dom);
    } else if (installed4.pandoc !== source.pandoc) {
        return versionMessage("Pandoc", source.pandoc);
    } else if (installed4.dartsass !== source.dartsass) {
        return versionMessage("Dart Sass", source.dartsass);
    } else if (installed4.esbuild !== source.esbuild) {
        return versionMessage("Esbuild", source.esbuild);
    } else if (installed4.script !== source.script) {
        return "update Quarto wrapper script";
    }
}
const { hasOwn: hasOwn5  } = Object;
function get1(obj, key) {
    if (hasOwn5(obj, key)) {
        return obj[key];
    }
}
function getForce(obj, key) {
    const v = get1(obj, key);
    assert(v != null);
    return v;
}
function isNumber(x) {
    if (typeof x === "number") return true;
    if (/^0x[0-9a-f]+$/i.test(String(x))) return true;
    return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(String(x));
}
function hasKey(obj, keys13) {
    let o = obj;
    keys13.slice(0, -1).forEach((key)=>{
        o = get1(o, key) ?? {};
    });
    const key1 = keys13[keys13.length - 1];
    return key1 in o;
}
function parse9(args, { "--": doubleDash = false , alias: alias3 = {} , boolean: __boolean1 = false , default: defaults = {} , stopEarly =false , string: string26 = [] , unknown =(i)=>i
  } = {}) {
    const flags = {
        bools: {},
        strings: {},
        unknownFn: unknown,
        allBools: false
    };
    if (__boolean1 !== undefined) {
        if (typeof __boolean1 === "boolean") {
            flags.allBools = !!__boolean1;
        } else {
            const booleanArgs = typeof __boolean1 === "string" ? [
                __boolean1
            ] : __boolean1;
            for (const key of booleanArgs.filter(Boolean)){
                flags.bools[key] = true;
            }
        }
    }
    const aliases = {};
    if (alias3 !== undefined) {
        for(const key in alias3){
            const val = getForce(alias3, key);
            if (typeof val === "string") {
                aliases[key] = [
                    val
                ];
            } else {
                aliases[key] = val;
            }
            for (const alias1 of getForce(aliases, key)){
                aliases[alias1] = [
                    key
                ].concat(aliases[key].filter((y)=>alias1 !== y
                ));
            }
        }
    }
    if (string26 !== undefined) {
        const stringArgs = typeof string26 === "string" ? [
            string26
        ] : string26;
        for (const key of stringArgs.filter(Boolean)){
            flags.strings[key] = true;
            const alias = get1(aliases, key);
            if (alias) {
                for (const al of alias){
                    flags.strings[al] = true;
                }
            }
        }
    }
    const argv = {
        _: []
    };
    function argDefined(key, arg) {
        return flags.allBools && /^--[^=]+$/.test(arg) || get1(flags.bools, key) || !!get1(flags.strings, key) || !!get1(aliases, key);
    }
    function setKey(obj, keys14, value) {
        let o = obj;
        keys14.slice(0, -1).forEach(function(key) {
            if (get1(o, key) === undefined) {
                o[key] = {};
            }
            o = get1(o, key);
        });
        const key4 = keys14[keys14.length - 1];
        if (get1(o, key4) === undefined || get1(flags.bools, key4) || typeof get1(o, key4) === "boolean") {
            o[key4] = value;
        } else if (Array.isArray(get1(o, key4))) {
            o[key4].push(value);
        } else {
            o[key4] = [
                get1(o, key4),
                value
            ];
        }
    }
    function setArg(key, val, arg = undefined) {
        if (arg && flags.unknownFn && !argDefined(key, arg)) {
            if (flags.unknownFn(arg, key, val) === false) return;
        }
        const value = !get1(flags.strings, key) && isNumber(val) ? Number(val) : val;
        setKey(argv, key.split("."), value);
        const alias = get1(aliases, key);
        if (alias) {
            for (const x of alias){
                setKey(argv, x.split("."), value);
            }
        }
    }
    function aliasIsBoolean(key) {
        return getForce(aliases, key).some((x)=>typeof get1(flags.bools, x) === "boolean"
        );
    }
    for (const key3 of Object.keys(flags.bools)){
        setArg(key3, defaults[key3] === undefined ? false : defaults[key3]);
    }
    let notFlags = [];
    if (args.includes("--")) {
        notFlags = args.slice(args.indexOf("--") + 1);
        args = args.slice(0, args.indexOf("--"));
    }
    for(let i = 0; i < args.length; i++){
        const arg = args[i];
        if (/^--.+=/.test(arg)) {
            const m = arg.match(/^--([^=]+)=(.*)$/s);
            assert(m != null);
            const [, key, value] = m;
            if (flags.bools[key]) {
                const booleanValue = value !== "false";
                setArg(key, booleanValue, arg);
            } else {
                setArg(key, value, arg);
            }
        } else if (/^--no-.+/.test(arg)) {
            const m = arg.match(/^--no-(.+)/);
            assert(m != null);
            setArg(m[1], false, arg);
        } else if (/^--.+/.test(arg)) {
            const m = arg.match(/^--(.+)/);
            assert(m != null);
            const [, key] = m;
            const next = args[i + 1];
            if (next !== undefined && !/^-/.test(next) && !get1(flags.bools, key) && !flags.allBools && (get1(aliases, key) ? !aliasIsBoolean(key) : true)) {
                setArg(key, next, arg);
                i++;
            } else if (/^(true|false)$/.test(next)) {
                setArg(key, next === "true", arg);
                i++;
            } else {
                setArg(key, get1(flags.strings, key) ? "" : true, arg);
            }
        } else if (/^-[^-]+/.test(arg)) {
            const letters = arg.slice(1, -1).split("");
            let broken = false;
            for(let j = 0; j < letters.length; j++){
                const next = arg.slice(j + 2);
                if (next === "-") {
                    setArg(letters[j], next, arg);
                    continue;
                }
                if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
                    setArg(letters[j], next.split(/=(.+)/)[1], arg);
                    broken = true;
                    break;
                }
                if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                    setArg(letters[j], next, arg);
                    broken = true;
                    break;
                }
                if (letters[j + 1] && letters[j + 1].match(/\W/)) {
                    setArg(letters[j], arg.slice(j + 2), arg);
                    broken = true;
                    break;
                } else {
                    setArg(letters[j], get1(flags.strings, letters[j]) ? "" : true, arg);
                }
            }
            const [key] = arg.slice(-1);
            if (!broken && key !== "-") {
                if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !get1(flags.bools, key) && (get1(aliases, key) ? !aliasIsBoolean(key) : true)) {
                    setArg(key, args[i + 1], arg);
                    i++;
                } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
                    setArg(key, args[i + 1] === "true", arg);
                    i++;
                } else {
                    setArg(key, get1(flags.strings, key) ? "" : true, arg);
                }
            }
        } else {
            if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
                argv._.push(flags.strings["_"] ?? !isNumber(arg) ? arg : Number(arg));
            }
            if (stopEarly) {
                argv._.push(...args.slice(i + 1));
                break;
            }
        }
    }
    for (const key2 of Object.keys(defaults)){
        if (!hasKey(argv, key2.split("."))) {
            setKey(argv, key2.split("."), defaults[key2]);
            if (aliases[key2]) {
                for (const x of aliases[key2]){
                    setKey(argv, x.split("."), defaults[key2]);
                }
            }
        }
    }
    if (doubleDash) {
        argv["--"] = [];
        for (const key of notFlags){
            argv["--"].push(key);
        }
    } else {
        for (const key of notFlags){
            argv._.push(key);
        }
    }
    return argv;
}
async function runScript(args) {
    const script = args[0];
    if (!script) {
        error("quarto run: no script specified");
        Deno.exit(1);
    }
    if (!existsSync(script)) {
        error("quarto run: script '" + script + "' not found");
        Deno.exit(1);
    }
    const handler = await handlerForScript(script);
    if (!handler) {
        error("quarto run: no handler found for script '" + script + "'");
        Deno.exit(1);
    }
    return await handler.run(script, args.slice(1));
}
const importMeta1 = {
    url: "file:///home/runner/work/quarto-cli/quarto-cli/src/quarto.ts",
    main: import.meta.main
};
async function quarto(args, cmdHandler) {
    if (quartoConfig.isDebug()) {
        const installed5 = readInstalledDevConfig();
        const source = readSourceDevConfig();
        if (installed5 == null || !devConfigsEqual(installed5, source)) {
            await reconfigureQuarto(installed5, source);
            Deno.exit(1);
        }
    }
    if (args[0] === "pandoc") {
        const result = await execProcess({
            cmd: [
                pandocBinaryPath(),
                ...args.slice(1)
            ]
        });
        Deno.exit(result.code);
    }
    if (args[0] === "run") {
        const result = await runScript(args.slice(1));
        Deno.exit(result.code);
    }
    if (args.length > 1 && (args[0] === "render" || args[0] === "preview") && args[1].startsWith("-")) {
        args = [
            args[0],
            Deno.cwd(),
            ...args.slice(1)
        ];
    }
    const quartoCommand = new Command().name("quarto").version(quartoConfig.version() + "\n").description("Quarto CLI").throwErrors();
    commands().forEach((command)=>{
        quartoCommand.command(command.getName(), cmdHandler !== undefined ? cmdHandler(command) : command);
    });
    initSessionTempDir();
    await quartoCommand.command("help", new HelpCommand().global()).command("completions", new CompletionsCommand()).hidden().parse(args);
}
if (importMeta1.main) {
    try {
        if (Deno.build.os !== "windows") {
            Deno.addSignalListener("SIGINT", abend);
            Deno.addSignalListener("SIGTERM", abend);
        }
        await initializeLogger(logOptions(parse9(Deno.args)));
        await quarto(Deno.args, appendLogOptions);
        await cleanupLogger();
        Deno.exit(0);
    } catch (e) {
        if (e) {
            logError(e);
        }
        abend();
    }
}
function abend() {
    cleanup1();
    Deno.exit(1);
}
function cleanup1() {
    cleanupSessionTempDir();
}
export { quarto as quarto };
