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

const LogLevels = {
    NOTSET: 0,
    DEBUG: 10,
    INFO: 20,
    WARN: 30,
    ERROR: 40,
    CRITICAL: 50
};
Object.keys(LogLevels).filter((key)=>isNaN(Number(key)));
const byLevel = {
    [LogLevels.NOTSET]: "NOTSET",
    [LogLevels.DEBUG]: "DEBUG",
    [LogLevels.INFO]: "INFO",
    [LogLevels.WARN]: "WARN",
    [LogLevels.ERROR]: "ERROR",
    [LogLevels.CRITICAL]: "CRITICAL"
};
function getLevelByName(name) {
    const level = LogLevels[name];
    if (level !== undefined) {
        return level;
    }
    throw new Error(`no log level found for name: ${name}`);
}
function getLevelName(level) {
    const levelName = byLevel[level];
    if (levelName) {
        return levelName;
    }
    throw new Error(`no level name found for level: ${level}`);
}
const DEFAULT_FORMATTER = ({ levelName, msg })=>`${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);
        this.log(msg);
    }
    format(logRecord) {
        return this.formatter(logRecord);
    }
    log(_msg) {}
    setup() {}
    destroy() {}
    [Symbol.dispose]() {
        this.destroy();
    }
}
const { Deno: Deno1 } = globalThis;
const noColor = typeof Deno1?.noColor === "boolean" ? Deno1.noColor : false;
let enabled = !noColor;
function code(open, close) {
    return {
        open: `\x1b[${open.join(";")}m`,
        close: `\x1b[${close}m`,
        regexp: new RegExp(`\\x1b\\[${close}m`, "g")
    };
}
function run(str, code) {
    return enabled ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str;
}
function bold(str) {
    return run(str, code([
        1
    ], 22));
}
function dim(str) {
    return run(str, code([
        2
    ], 22));
}
function underline(str) {
    return run(str, code([
        4
    ], 24));
}
function red(str) {
    return run(str, code([
        31
    ], 39));
}
function green(str) {
    return run(str, code([
        32
    ], 39));
}
function yellow(str) {
    return run(str, code([
        33
    ], 39));
}
function blue(str) {
    return run(str, code([
        34
    ], 39));
}
function brightRed(str) {
    return run(str, code([
        91
    ], 39));
}
const ANSI_PATTERN = new RegExp([
    "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TXZcf-nq-uy=><~]))"
].join("|"), "g");
function stripColor(string) {
    return stripAnsiCode(string);
}
function stripAnsiCode(string) {
    return string.replace(ANSI_PATTERN, "");
}
class ConsoleHandler extends BaseHandler {
    #useColors;
    constructor(levelName, options = {}){
        super(levelName, options);
        this.#useColors = options.useColors ?? true;
    }
    format(logRecord) {
        let msg = super.format(logRecord);
        if (this.#useColors) {
            msg = this.applyColors(msg, logRecord.level);
        }
        return msg;
    }
    applyColors(msg, level) {
        switch(level){
            case LogLevels.INFO:
                msg = blue(msg);
                break;
            case LogLevels.WARN:
                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 FileHandler extends BaseHandler {
    _file;
    _buf = new Uint8Array(4096);
    _pointer = 0;
    _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
        };
    }
    setup() {
        this._file = Deno.openSync(this._filename, this._openOptions);
        this.#resetBuffer();
        addEventListener("unload", this.#unloadCallback);
    }
    handle(logRecord) {
        super.handle(logRecord);
        if (logRecord.level > LogLevels.ERROR) {
            this.flush();
        }
    }
    log(msg) {
        const bytes = this._encoder.encode(msg + "\n");
        if (bytes.byteLength > this._buf.byteLength - this._pointer) {
            this.flush();
        }
        this._buf.set(bytes, this._pointer);
        this._pointer += bytes.byteLength;
    }
    flush() {
        if (this._pointer > 0 && this._file) {
            let written = 0;
            while(written < this._pointer){
                written += this._file.writeSync(this._buf.subarray(written, this._pointer));
            }
            this.#resetBuffer();
        }
    }
    #resetBuffer() {
        this._pointer = 0;
    }
    destroy() {
        this.flush();
        this._file?.close();
        this._file = undefined;
        removeEventListener("unload", this.#unloadCallback);
    }
}
function existsSync(path, options) {
    try {
        const stat = Deno.statSync(path);
        if (options && (options.isReadable || options.isDirectory || options.isFile)) {
            if (options.isDirectory && options.isFile) {
                throw new TypeError("ExistsOptions.options.isDirectory and ExistsOptions.options.isFile must not be true together.");
            }
            if (options.isDirectory && !stat.isDirectory || options.isFile && !stat.isFile) {
                return false;
            }
            if (options.isReadable) {
                if (stat.mode === null) {
                    return true;
                }
                if (Deno.uid() === stat.uid) {
                    return (stat.mode & 0o400) === 0o400;
                } else if (Deno.gid() === stat.gid) {
                    return (stat.mode & 0o040) === 0o040;
                }
                return (stat.mode & 0o004) === 0o004;
            }
        }
        return true;
    } catch (error) {
        if (error instanceof Deno.errors.NotFound) {
            return false;
        }
        if (error instanceof Deno.errors.PermissionDenied) {
            if (Deno.permissions.querySync({
                name: "read",
                path
            }).state === "granted") {
                return !options?.isReadable;
            }
        }
        throw error;
    }
}
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) {
        try {
            this.#level = getLevelByName(getLevelName(level));
        } catch (_) {
            throw new TypeError(`Invalid log level: ${level}`);
        }
    }
    get levelName() {
        return getLevelName(this.#level);
    }
    set levelName(levelName) {
        this.#level = getLevelByName(levelName);
    }
    get loggerName() {
        return this.#loggerName;
    }
    #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(data, isProperty = false) {
        if (typeof data === "string") {
            if (isProperty) return `"${data}"`;
            return data;
        } else if (data === null || typeof data === "number" || typeof data === "bigint" || typeof data === "boolean" || typeof data === "undefined" || typeof data === "symbol") {
            return String(data);
        } else if (data instanceof Error) {
            return data.stack;
        } else if (typeof data === "object") {
            return `{${Object.entries(data).map(([k, v])=>`"${k}":${this.asString(v, true)}`).join(",")}}`;
        }
        return "undefined";
    }
    debug(msg, ...args) {
        return this.#log(LogLevels.DEBUG, msg, ...args);
    }
    info(msg, ...args) {
        return this.#log(LogLevels.INFO, msg, ...args);
    }
    warn(msg, ...args) {
        return this.#log(LogLevels.WARN, msg, ...args);
    }
    error(msg, ...args) {
        return this.#log(LogLevels.ERROR, msg, ...args);
    }
    critical(msg, ...args) {
        return this.#log(LogLevels.CRITICAL, msg, ...args);
    }
}
class AssertionError extends Error {
    constructor(message){
        super(message);
        this.name = "AssertionError";
    }
}
function assert(expr, msg = "") {
    if (!expr) {
        throw new AssertionError(msg);
    }
}
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(name) {
    if (!name) {
        const d = state.loggers.get("default");
        assert(d !== undefined, `"default" logger must be set for getting logger without name`);
        return d;
    }
    const result1 = state.loggers.get(name);
    if (!result1) {
        const logger = new Logger(name, "NOTSET", {
            handlers: []
        });
        state.loggers.set(name, logger);
        return logger;
    }
    return result1;
}
function debug(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").debug(msg, ...args);
    }
    return getLogger("default").debug(msg, ...args);
}
function error(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").error(msg, ...args);
    }
    return getLogger("default").error(msg, ...args);
}
function info(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").info(msg, ...args);
    }
    return getLogger("default").info(msg, ...args);
}
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 handlers = state.config.handlers || {};
    for (const [handlerName, handler] of Object.entries(handlers)){
        handler.setup();
        state.handlers.set(handlerName, handler);
    }
    state.loggers.clear();
    const loggers = state.config.loggers || {};
    for (const [loggerName, loggerConfig] of Object.entries(loggers)){
        const handlerNames = loggerConfig.handlers || [];
        const handlers = [];
        handlerNames.forEach((handlerName)=>{
            const handler = state.handlers.get(handlerName);
            if (handler) {
                handlers.push(handler);
            }
        });
        const levelName = loggerConfig.level || DEFAULT_LEVEL;
        const logger = new Logger(loggerName, levelName, {
            handlers: handlers
        });
        state.loggers.set(loggerName, logger);
    }
}
setup(DEFAULT_CONFIG);
function warn(msg, ...args) {
    if (msg instanceof Function) {
        return getLogger("default").warn(msg, ...args);
    }
    return getLogger("default").warn(msg, ...args);
}
function assertPath(path) {
    if (typeof path !== "string") {
        throw new TypeError(`Path must be a string. Received ${JSON.stringify(path)}`);
    }
}
function stripSuffix(name, suffix) {
    if (suffix.length >= name.length) {
        return name;
    }
    const lenDiff = name.length - suffix.length;
    for(let i1 = suffix.length - 1; i1 >= 0; --i1){
        if (name.charCodeAt(lenDiff + i1) !== suffix.charCodeAt(i1)) {
            return name;
        }
    }
    return name.slice(0, -suffix.length);
}
function lastPathSegment(path, isSep, start = 0) {
    let matchedNonSeparator = false;
    let end = path.length;
    for(let i1 = path.length - 1; i1 >= start; --i1){
        if (isSep(path.charCodeAt(i1))) {
            if (matchedNonSeparator) {
                start = i1 + 1;
                break;
            }
        } else if (!matchedNonSeparator) {
            matchedNonSeparator = true;
            end = i1 + 1;
        }
    }
    return path.slice(start, end);
}
function assertArgs(path, suffix) {
    assertPath(path);
    if (path.length === 0) return path;
    if (typeof suffix !== "string") {
        throw new TypeError(`Suffix must be a string. Received ${JSON.stringify(suffix)}`);
    }
}
const CHAR_FORWARD_SLASH = 47;
function stripTrailingSeparators(segment, isSep) {
    if (segment.length <= 1) {
        return segment;
    }
    let end = segment.length;
    for(let i1 = segment.length - 1; i1 > 0; i1--){
        if (isSep(segment.charCodeAt(i1))) {
            end = i1;
        } else {
            break;
        }
    }
    return segment.slice(0, end);
}
function isPosixPathSeparator(code) {
    return code === 47;
}
function isPathSeparator(code) {
    return code === 47 || code === 92;
}
function isWindowsDeviceRoot(code) {
    return code >= 97 && code <= 122 || code >= 65 && code <= 90;
}
function basename(path, suffix = "") {
    assertArgs(path, suffix);
    let start = 0;
    if (path.length >= 2) {
        const drive = path.charCodeAt(0);
        if (isWindowsDeviceRoot(drive)) {
            if (path.charCodeAt(1) === 58) start = 2;
        }
    }
    const lastSegment = lastPathSegment(path, isPathSeparator, start);
    const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator);
    return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;
}
const SEPARATOR = "\\";
const SEPARATOR_PATTERN = /[\\/]+/;
function assertArg(path) {
    assertPath(path);
    if (path.length === 0) return ".";
}
function dirname(path) {
    assertArg(path);
    const len = path.length;
    let rootEnd = -1;
    let end = -1;
    let matchedSlash = true;
    let offset = 0;
    const code = path.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator(code)) {
            rootEnd = offset = 1;
            if (isPathSeparator(path.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator(path.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator(path.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            return path;
                        }
                        if (j !== last) {
                            rootEnd = offset = j + 1;
                        }
                    }
                }
            }
        } else if (isWindowsDeviceRoot(code)) {
            if (path.charCodeAt(1) === 58) {
                rootEnd = offset = 2;
                if (len > 2) {
                    if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3;
                }
            }
        }
    } else if (isPathSeparator(code)) {
        return path;
    }
    for(let i1 = len - 1; i1 >= offset; --i1){
        if (isPathSeparator(path.charCodeAt(i1))) {
            if (!matchedSlash) {
                end = i1;
                break;
            }
        } else {
            matchedSlash = false;
        }
    }
    if (end === -1) {
        if (rootEnd === -1) return ".";
        else end = rootEnd;
    }
    return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator);
}
function extname(path) {
    assertPath(path);
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path.length >= 2 && path.charCodeAt(1) === 58 && isWindowsDeviceRoot(path.charCodeAt(0))) {
        start = startPart = 2;
    }
    for(let i1 = path.length - 1; i1 >= start; --i1){
        const code = path.charCodeAt(i1);
        if (isPathSeparator(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 path.slice(startDot, end);
}
function _format(sep, pathObject) {
    const dir = pathObject.dir || pathObject.root;
    const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
    if (!dir) return base;
    if (base === sep) return dir;
    if (dir === pathObject.root) return dir + base;
    return dir + sep + base;
}
function assertArg1(pathObject) {
    if (pathObject === null || typeof pathObject !== "object") {
        throw new TypeError(`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`);
    }
}
function assertArg2(url) {
    url = url instanceof URL ? url : new URL(url);
    if (url.protocol !== "file:") {
        throw new TypeError("Must be a file URL.");
    }
    return url;
}
function fromFileUrl(url) {
    url = assertArg2(url);
    let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
    if (url.hostname !== "") {
        path = `\\\\${url.hostname}${path}`;
    }
    return path;
}
function isAbsolute(path) {
    assertPath(path);
    const len = path.length;
    if (len === 0) return false;
    const code = path.charCodeAt(0);
    if (isPathSeparator(code)) {
        return true;
    } else if (isWindowsDeviceRoot(code)) {
        if (len > 2 && path.charCodeAt(1) === 58) {
            if (isPathSeparator(path.charCodeAt(2))) return true;
        }
    }
    return false;
}
function assertArg3(path) {
    assertPath(path);
    if (path.length === 0) return ".";
}
function normalizeString(path, allowAboveRoot, separator, isPathSeparator) {
    let res = "";
    let lastSegmentLength = 0;
    let lastSlash = -1;
    let dots = 0;
    let code;
    for(let i1 = 0, len = path.length; i1 <= len; ++i1){
        if (i1 < len) code = path.charCodeAt(i1);
        else if (isPathSeparator(code)) break;
        else code = CHAR_FORWARD_SLASH;
        if (isPathSeparator(code)) {
            if (lastSlash === i1 - 1 || dots === 1) {} else if (lastSlash !== i1 - 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 = i1;
                        dots = 0;
                        continue;
                    } else if (res.length === 2 || res.length === 1) {
                        res = "";
                        lastSegmentLength = 0;
                        lastSlash = i1;
                        dots = 0;
                        continue;
                    }
                }
                if (allowAboveRoot) {
                    if (res.length > 0) res += `${separator}..`;
                    else res = "..";
                    lastSegmentLength = 2;
                }
            } else {
                if (res.length > 0) res += separator + path.slice(lastSlash + 1, i1);
                else res = path.slice(lastSlash + 1, i1);
                lastSegmentLength = i1 - lastSlash - 1;
            }
            lastSlash = i1;
            dots = 0;
        } else if (code === 46 && dots !== -1) {
            ++dots;
        } else {
            dots = -1;
        }
    }
    return res;
}
function normalize(path) {
    assertArg3(path);
    const len = path.length;
    let rootEnd = 0;
    let device;
    let isAbsolute = false;
    const code = path.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator(code)) {
            isAbsolute = true;
            if (isPathSeparator(path.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator(path.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    const firstPart = path.slice(last, j);
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator(path.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            return `\\\\${firstPart}\\${path.slice(last)}\\`;
                        } else if (j !== last) {
                            device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                            rootEnd = j;
                        }
                    }
                }
            } else {
                rootEnd = 1;
            }
        } else if (isWindowsDeviceRoot(code)) {
            if (path.charCodeAt(1) === 58) {
                device = path.slice(0, 2);
                rootEnd = 2;
                if (len > 2) {
                    if (isPathSeparator(path.charCodeAt(2))) {
                        isAbsolute = true;
                        rootEnd = 3;
                    }
                }
            }
        }
    } else if (isPathSeparator(code)) {
        return "\\";
    }
    let tail;
    if (rootEnd < len) {
        tail = normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator);
    } else {
        tail = "";
    }
    if (tail.length === 0 && !isAbsolute) tail = ".";
    if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) {
        tail += "\\";
    }
    if (device === undefined) {
        if (isAbsolute) {
            if (tail.length > 0) return `\\${tail}`;
            else return "\\";
        } else if (tail.length > 0) {
            return tail;
        } else {
            return "";
        }
    } else if (isAbsolute) {
        if (tail.length > 0) return `${device}\\${tail}`;
        else return `${device}\\`;
    } else if (tail.length > 0) {
        return device + tail;
    } else {
        return device;
    }
}
function join(...paths) {
    if (paths.length === 0) return ".";
    let joined;
    let firstPart = null;
    for(let i1 = 0; i1 < paths.length; ++i1){
        const path = paths[i1];
        assertPath(path);
        if (path.length > 0) {
            if (joined === undefined) joined = firstPart = path;
            else joined += `\\${path}`;
        }
    }
    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 normalize(joined);
}
function resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for(let i1 = pathSegments.length - 1; i1 >= -1; i1--){
        let path;
        const { Deno: Deno1 } = globalThis;
        if (i1 >= 0) {
            path = pathSegments[i1];
        } else if (!resolvedDevice) {
            if (typeof Deno1?.cwd !== "function") {
                throw new TypeError("Resolved a drive-letter-less path without a CWD.");
            }
            path = Deno1.cwd();
        } else {
            if (typeof Deno1?.env?.get !== "function" || typeof Deno1?.cwd !== "function") {
                throw new TypeError("Resolved a relative path without a CWD.");
            }
            path = Deno1.cwd();
            if (path === undefined || path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
                path = `${resolvedDevice}\\`;
            }
        }
        assertPath(path);
        const len = path.length;
        if (len === 0) continue;
        let rootEnd = 0;
        let device = "";
        let isAbsolute = false;
        const code = path.charCodeAt(0);
        if (len > 1) {
            if (isPathSeparator(code)) {
                isAbsolute = true;
                if (isPathSeparator(path.charCodeAt(1))) {
                    let j = 2;
                    let last = j;
                    for(; j < len; ++j){
                        if (isPathSeparator(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        const firstPart = path.slice(last, j);
                        last = j;
                        for(; j < len; ++j){
                            if (!isPathSeparator(path.charCodeAt(j))) break;
                        }
                        if (j < len && j !== last) {
                            last = j;
                            for(; j < len; ++j){
                                if (isPathSeparator(path.charCodeAt(j))) break;
                            }
                            if (j === len) {
                                device = `\\\\${firstPart}\\${path.slice(last)}`;
                                rootEnd = j;
                            } else if (j !== last) {
                                device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                                rootEnd = j;
                            }
                        }
                    }
                } else {
                    rootEnd = 1;
                }
            } else if (isWindowsDeviceRoot(code)) {
                if (path.charCodeAt(1) === 58) {
                    device = path.slice(0, 2);
                    rootEnd = 2;
                    if (len > 2) {
                        if (isPathSeparator(path.charCodeAt(2))) {
                            isAbsolute = true;
                            rootEnd = 3;
                        }
                    }
                }
            }
        } else if (isPathSeparator(code)) {
            rootEnd = 1;
            isAbsolute = 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 = `${path.slice(rootEnd)}\\${resolvedTail}`;
            resolvedAbsolute = isAbsolute;
        }
        if (resolvedAbsolute && resolvedDevice.length > 0) break;
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
function assertArgs1(from, to) {
    assertPath(from);
    assertPath(to);
    if (from === to) return "";
}
function relative(from, to) {
    assertArgs1(from, to);
    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 i1 = 0;
    for(; i1 <= length; ++i1){
        if (i1 === length) {
            if (toLen > length) {
                if (to.charCodeAt(toStart + i1) === 92) {
                    return toOrig.slice(toStart + i1 + 1);
                } else if (i1 === 2) {
                    return toOrig.slice(toStart + i1);
                }
            }
            if (fromLen > length) {
                if (from.charCodeAt(fromStart + i1) === 92) {
                    lastCommonSep = i1;
                } else if (i1 === 2) {
                    lastCommonSep = 3;
                }
            }
            break;
        }
        const fromCode = from.charCodeAt(fromStart + i1);
        const toCode = to.charCodeAt(toStart + i1);
        if (fromCode !== toCode) break;
        else if (fromCode === 92) lastCommonSep = i1;
    }
    if (i1 !== length && lastCommonSep === -1) {
        return toOrig;
    }
    let out = "";
    if (lastCommonSep === -1) lastCommonSep = 0;
    for(i1 = fromStart + lastCommonSep + 1; i1 <= fromEnd; ++i1){
        if (i1 === fromEnd || from.charCodeAt(i1) === 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);
    }
}
const WHITESPACE_ENCODINGS = {
    "\u0009": "%09",
    "\u000A": "%0A",
    "\u000B": "%0B",
    "\u000C": "%0C",
    "\u000D": "%0D",
    "\u0020": "%20"
};
function encodeWhitespace(string) {
    return string.replaceAll(/[\s]/g, (c)=>{
        return WHITESPACE_ENCODINGS[c] ?? c;
    });
}
function toFileUrl(path) {
    if (!isAbsolute(path)) {
        throw new TypeError("Must be an absolute path.");
    }
    const [, hostname, pathname] = path.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/);
    const url = new URL("file:///");
    url.pathname = encodeWhitespace(pathname.replace(/%/g, "%25"));
    if (hostname !== undefined && hostname !== "localhost") {
        url.hostname = hostname;
        if (!url.hostname) {
            throw new TypeError("Invalid hostname.");
        }
    }
    return url;
}
function _common(paths, sep) {
    const [first = "", ...remaining] = paths;
    if (first === "" || remaining.length === 0) {
        return first.substring(0, first.lastIndexOf(sep) + 1);
    }
    const parts = first.split(sep);
    let endOfPrefix = parts.length;
    for (const path of remaining){
        const compare = path.split(sep);
        for(let i1 = 0; i1 < endOfPrefix; i1++){
            if (compare[i1] !== parts[i1]) {
                endOfPrefix = i1;
            }
        }
        if (endOfPrefix === 0) {
            return "";
        }
    }
    const prefix = parts.slice(0, endOfPrefix).join(sep);
    return prefix.endsWith(sep) ? prefix : `${prefix}${sep}`;
}
const regExpEscapeChars = [
    "!",
    "$",
    "(",
    ")",
    "*",
    "+",
    ".",
    "=",
    "?",
    "[",
    "\\",
    "^",
    "{",
    "|"
];
const rangeEscapeChars = [
    "-",
    "\\",
    "]"
];
function _globToRegExp(c, glob, { extended = true, globstar: globstarOption = true, caseInsensitive = false } = {}) {
    if (glob === "") {
        return /(?!)/;
    }
    let newLength = glob.length;
    for(; newLength > 1 && c.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 i1 = j;
        for(; i1 < glob.length && !c.seps.includes(glob[i1]); i1++){
            if (inEscape) {
                inEscape = false;
                const escapeChars = inRange ? rangeEscapeChars : regExpEscapeChars;
                segment += escapeChars.includes(glob[i1]) ? `\\${glob[i1]}` : glob[i1];
                continue;
            }
            if (glob[i1] === c.escapePrefix) {
                inEscape = true;
                continue;
            }
            if (glob[i1] === "[") {
                if (!inRange) {
                    inRange = true;
                    segment += "[";
                    if (glob[i1 + 1] === "!") {
                        i1++;
                        segment += "^";
                    } else if (glob[i1 + 1] === "^") {
                        i1++;
                        segment += "\\^";
                    }
                    continue;
                } else if (glob[i1 + 1] === ":") {
                    let k = i1 + 1;
                    let value = "";
                    while(glob[k + 1] !== undefined && glob[k + 1] !== ":"){
                        value += glob[k + 1];
                        k++;
                    }
                    if (glob[k + 1] === ":" && glob[k + 2] === "]") {
                        i1 = 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[i1] === "]" && inRange) {
                inRange = false;
                segment += "]";
                continue;
            }
            if (inRange) {
                if (glob[i1] === "\\") {
                    segment += `\\\\`;
                } else {
                    segment += glob[i1];
                }
                continue;
            }
            if (glob[i1] === ")" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") {
                segment += ")";
                const type = groupStack.pop();
                if (type === "!") {
                    segment += c.wildcard;
                } else if (type !== "@") {
                    segment += type;
                }
                continue;
            }
            if (glob[i1] === "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] !== "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i1] === "+" && extended && glob[i1 + 1] === "(") {
                i1++;
                groupStack.push("+");
                segment += "(?:";
                continue;
            }
            if (glob[i1] === "@" && extended && glob[i1 + 1] === "(") {
                i1++;
                groupStack.push("@");
                segment += "(?:";
                continue;
            }
            if (glob[i1] === "?") {
                if (extended && glob[i1 + 1] === "(") {
                    i1++;
                    groupStack.push("?");
                    segment += "(?:";
                } else {
                    segment += ".";
                }
                continue;
            }
            if (glob[i1] === "!" && extended && glob[i1 + 1] === "(") {
                i1++;
                groupStack.push("!");
                segment += "(?!";
                continue;
            }
            if (glob[i1] === "{") {
                groupStack.push("BRACE");
                segment += "(?:";
                continue;
            }
            if (glob[i1] === "}" && groupStack[groupStack.length - 1] === "BRACE") {
                groupStack.pop();
                segment += ")";
                continue;
            }
            if (glob[i1] === "," && groupStack[groupStack.length - 1] === "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i1] === "*") {
                if (extended && glob[i1 + 1] === "(") {
                    i1++;
                    groupStack.push("*");
                    segment += "(?:";
                } else {
                    const prevChar = glob[i1 - 1];
                    let numStars = 1;
                    while(glob[i1 + 1] === "*"){
                        i1++;
                        numStars++;
                    }
                    const nextChar = glob[i1 + 1];
                    if (globstarOption && numStars === 2 && [
                        ...c.seps,
                        undefined
                    ].includes(prevChar) && [
                        ...c.seps,
                        undefined
                    ].includes(nextChar)) {
                        segment += c.globstar;
                        endsWithSep = true;
                    } else {
                        segment += c.wildcard;
                    }
                }
                continue;
            }
            segment += regExpEscapeChars.includes(glob[i1]) ? `\\${glob[i1]}` : glob[i1];
        }
        if (groupStack.length > 0 || inRange || inEscape) {
            segment = "";
            for (const c of glob.slice(j, i1)){
                segment += regExpEscapeChars.includes(c) ? `\\${c}` : c;
                endsWithSep = false;
            }
        }
        regExpString += segment;
        if (!endsWithSep) {
            regExpString += i1 < glob.length ? c.sep : c.sepMaybe;
            endsWithSep = true;
        }
        while(c.seps.includes(glob[i1]))i1++;
        if (!(i1 > j)) {
            throw new Error("Assertion failure: i > j (potential infinite loop)");
        }
        j = i1;
    }
    regExpString = `^${regExpString}$`;
    return new RegExp(regExpString, caseInsensitive ? "i" : "");
}
const constants = {
    sep: "(?:\\\\|/)+",
    sepMaybe: "(?:\\\\|/)*",
    seps: [
        "\\",
        "/"
    ],
    globstar: "(?:[^\\\\/]*(?:\\\\|/|$)+)*",
    wildcard: "[^\\\\/]*",
    escapePrefix: "`"
};
function globToRegExp(glob, options = {}) {
    return _globToRegExp(constants, glob, options);
}
function isGlob(str) {
    const chars = {
        "{": "}",
        "(": ")",
        "[": "]"
    };
    const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
    if (str === "") {
        return false;
    }
    let match;
    while(match = regex.exec(str)){
        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 = str.indexOf(close, idx);
            if (n !== -1) {
                idx = n + 1;
            }
        }
        str = str.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 normalize(glob);
    }
    const s = SEPARATOR_PATTERN.source;
    const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g");
    return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, "..");
}
function joinGlobs(globs, { extended = true, globstar = false } = {}) {
    if (!globstar || globs.length === 0) {
        return join(...globs);
    }
    if (globs.length === 0) return ".";
    let joined;
    for (const glob of globs){
        const path = glob;
        if (path.length > 0) {
            if (!joined) joined = path;
            else joined += `${SEPARATOR}${path}`;
        }
    }
    if (!joined) return ".";
    return normalizeGlob(joined, {
        extended,
        globstar
    });
}
function isPosixPathSeparator1(code) {
    return code === 47;
}
function basename1(path, suffix = "") {
    assertArgs(path, suffix);
    const lastSegment = lastPathSegment(path, isPosixPathSeparator1);
    const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator1);
    return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;
}
const DELIMITER = ":";
const SEPARATOR1 = "/";
const SEPARATOR_PATTERN1 = /\/+/;
function dirname1(path) {
    assertArg(path);
    let end = -1;
    let matchedNonSeparator = false;
    for(let i1 = path.length - 1; i1 >= 1; --i1){
        if (isPosixPathSeparator1(path.charCodeAt(i1))) {
            if (matchedNonSeparator) {
                end = i1;
                break;
            }
        } else {
            matchedNonSeparator = true;
        }
    }
    if (end === -1) {
        return isPosixPathSeparator1(path.charCodeAt(0)) ? "/" : ".";
    }
    return stripTrailingSeparators(path.slice(0, end), isPosixPathSeparator1);
}
function extname1(path) {
    assertPath(path);
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for(let i1 = path.length - 1; i1 >= 0; --i1){
        const code = path.charCodeAt(i1);
        if (isPosixPathSeparator1(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 path.slice(startDot, end);
}
function format(pathObject) {
    assertArg1(pathObject);
    return _format("/", pathObject);
}
function fromFileUrl1(url) {
    url = assertArg2(url);
    return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"));
}
function isAbsolute1(path) {
    assertPath(path);
    return path.length > 0 && isPosixPathSeparator1(path.charCodeAt(0));
}
function normalize1(path) {
    assertArg3(path);
    const isAbsolute = isPosixPathSeparator1(path.charCodeAt(0));
    const trailingSeparator = isPosixPathSeparator1(path.charCodeAt(path.length - 1));
    path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator1);
    if (path.length === 0 && !isAbsolute) path = ".";
    if (path.length > 0 && trailingSeparator) path += "/";
    if (isAbsolute) return `/${path}`;
    return path;
}
function join1(...paths) {
    if (paths.length === 0) return ".";
    let joined;
    for(let i1 = 0, len = paths.length; i1 < len; ++i1){
        const path = paths[i1];
        assertPath(path);
        if (path.length > 0) {
            if (!joined) joined = path;
            else joined += `/${path}`;
        }
    }
    if (!joined) return ".";
    return normalize1(joined);
}
function parse(path) {
    assertPath(path);
    const ret = {
        root: "",
        dir: "",
        base: "",
        ext: "",
        name: ""
    };
    if (path.length === 0) return ret;
    const isAbsolute = isPosixPathSeparator1(path.charCodeAt(0));
    let start;
    if (isAbsolute) {
        ret.root = "/";
        start = 1;
    } else {
        start = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let i1 = path.length - 1;
    let preDotState = 0;
    for(; i1 >= start; --i1){
        const code = path.charCodeAt(i1);
        if (isPosixPathSeparator1(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 && isAbsolute) {
                ret.base = ret.name = path.slice(1, end);
            } else {
                ret.base = ret.name = path.slice(startPart, end);
            }
        }
        ret.base = ret.base || "/";
    } else {
        if (startPart === 0 && isAbsolute) {
            ret.name = path.slice(1, startDot);
            ret.base = path.slice(1, end);
        } else {
            ret.name = path.slice(startPart, startDot);
            ret.base = path.slice(startPart, end);
        }
        ret.ext = path.slice(startDot, end);
    }
    if (startPart > 0) {
        ret.dir = stripTrailingSeparators(path.slice(0, startPart - 1), isPosixPathSeparator1);
    } else if (isAbsolute) ret.dir = "/";
    return ret;
}
function resolve1(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for(let i1 = pathSegments.length - 1; i1 >= -1 && !resolvedAbsolute; i1--){
        let path;
        if (i1 >= 0) path = pathSegments[i1];
        else {
            const { Deno: Deno1 } = globalThis;
            if (typeof Deno1?.cwd !== "function") {
                throw new TypeError("Resolved a relative path without a CWD.");
            }
            path = Deno1.cwd();
        }
        assertPath(path);
        if (path.length === 0) {
            continue;
        }
        resolvedPath = `${path}/${resolvedPath}`;
        resolvedAbsolute = isPosixPathSeparator1(path.charCodeAt(0));
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator1);
    if (resolvedAbsolute) {
        if (resolvedPath.length > 0) return `/${resolvedPath}`;
        else return "/";
    } else if (resolvedPath.length > 0) return resolvedPath;
    else return ".";
}
function relative1(from, to) {
    assertArgs1(from, to);
    from = resolve1(from);
    to = resolve1(to);
    if (from === to) return "";
    let fromStart = 1;
    const fromEnd = from.length;
    for(; fromStart < fromEnd; ++fromStart){
        if (!isPosixPathSeparator1(from.charCodeAt(fromStart))) break;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 1;
    const toEnd = to.length;
    for(; toStart < toEnd; ++toStart){
        if (!isPosixPathSeparator1(to.charCodeAt(toStart))) break;
    }
    const toLen = toEnd - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i1 = 0;
    for(; i1 <= length; ++i1){
        if (i1 === length) {
            if (toLen > length) {
                if (isPosixPathSeparator1(to.charCodeAt(toStart + i1))) {
                    return to.slice(toStart + i1 + 1);
                } else if (i1 === 0) {
                    return to.slice(toStart + i1);
                }
            } else if (fromLen > length) {
                if (isPosixPathSeparator1(from.charCodeAt(fromStart + i1))) {
                    lastCommonSep = i1;
                } else if (i1 === 0) {
                    lastCommonSep = 0;
                }
            }
            break;
        }
        const fromCode = from.charCodeAt(fromStart + i1);
        const toCode = to.charCodeAt(toStart + i1);
        if (fromCode !== toCode) break;
        else if (isPosixPathSeparator1(fromCode)) lastCommonSep = i1;
    }
    let out = "";
    for(i1 = fromStart + lastCommonSep + 1; i1 <= fromEnd; ++i1){
        if (i1 === fromEnd || isPosixPathSeparator1(from.charCodeAt(i1))) {
            if (out.length === 0) out += "..";
            else out += "/..";
        }
    }
    if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
    else {
        toStart += lastCommonSep;
        if (isPosixPathSeparator1(to.charCodeAt(toStart))) ++toStart;
        return to.slice(toStart);
    }
}
function toFileUrl1(path) {
    if (!isAbsolute1(path)) {
        throw new TypeError("Must be an absolute path.");
    }
    const url = new URL("file:///");
    url.pathname = encodeWhitespace(path.replace(/%/g, "%25").replace(/\\/g, "%5C"));
    return url;
}
function toNamespacedPath(path) {
    return path;
}
function common(paths, sep = SEPARATOR1) {
    return _common(paths, sep);
}
const constants1 = {
    sep: "/+",
    sepMaybe: "/*",
    seps: [
        "/"
    ],
    globstar: "(?:[^/]*(?:/|$)+)*",
    wildcard: "[^/]*",
    escapePrefix: "\\"
};
function globToRegExp1(glob, options = {}) {
    return _globToRegExp(constants1, glob, options);
}
function normalizeGlob1(glob, { globstar = false } = {}) {
    if (glob.match(/\0/g)) {
        throw new Error(`Glob contains invalid characters: "${glob}"`);
    }
    if (!globstar) {
        return normalize1(glob);
    }
    const s = SEPARATOR_PATTERN1.source;
    const badParentPattern = new RegExp(`(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, "g");
    return normalize1(glob.replace(badParentPattern, "\0")).replace(/\0/g, "..");
}
function joinGlobs1(globs, { extended = true, globstar = false } = {}) {
    if (!globstar || globs.length === 0) {
        return join1(...globs);
    }
    if (globs.length === 0) return ".";
    let joined;
    for (const glob of globs){
        const path = glob;
        if (path.length > 0) {
            if (!joined) joined = path;
            else joined += `${SEPARATOR1}${path}`;
        }
    }
    if (!joined) return ".";
    return normalizeGlob1(joined, {
        extended,
        globstar
    });
}
const mod = {
    basename: basename1,
    DELIMITER,
    SEPARATOR: SEPARATOR1,
    SEPARATOR_PATTERN: SEPARATOR_PATTERN1,
    dirname: dirname1,
    extname: extname1,
    format,
    fromFileUrl: fromFileUrl1,
    isAbsolute: isAbsolute1,
    join: join1,
    normalize: normalize1,
    parse,
    relative: relative1,
    resolve: resolve1,
    toFileUrl: toFileUrl1,
    toNamespacedPath,
    common,
    globToRegExp: globToRegExp1,
    isGlob,
    joinGlobs: joinGlobs1,
    normalizeGlob: normalizeGlob1
};
const osType = (()=>{
    const { Deno: Deno1 } = globalThis;
    if (typeof Deno1?.build?.os === "string") {
        return Deno1.build.os;
    }
    const { navigator } = globalThis;
    if (navigator?.appVersion?.includes?.("Win")) {
        return "windows";
    }
    return "linux";
})();
const isWindows = osType === "windows";
function basename2(path, suffix = "") {
    return isWindows ? basename(path, suffix) : basename1(path, suffix);
}
const SEPARATOR2 = isWindows ? "\\" : "/";
const SEPARATOR_PATTERN2 = isWindows ? /[\\/]+/ : /\/+/;
function dirname2(path) {
    return isWindows ? dirname(path) : dirname1(path);
}
function extname2(path) {
    return isWindows ? extname(path) : extname1(path);
}
function fromFileUrl2(url) {
    return isWindows ? fromFileUrl(url) : fromFileUrl1(url);
}
function isAbsolute2(path) {
    return isWindows ? isAbsolute(path) : isAbsolute1(path);
}
function join2(...paths) {
    return isWindows ? join(...paths) : join1(...paths);
}
function normalize2(path) {
    return isWindows ? normalize(path) : normalize1(path);
}
function relative2(from, to) {
    return isWindows ? relative(from, to) : relative1(from, to);
}
function resolve2(...pathSegments) {
    return isWindows ? resolve(...pathSegments) : resolve1(...pathSegments);
}
function toFileUrl2(path) {
    return isWindows ? toFileUrl(path) : toFileUrl1(path);
}
function globToRegExp2(glob, options = {}) {
    return options.os === "windows" || !options.os && isWindows ? globToRegExp(glob, options) : globToRegExp1(glob, options);
}
function joinGlobs2(globs, options = {}) {
    return isWindows ? joinGlobs(globs, options) : joinGlobs1(globs, options);
}
function toPathString(pathUrl) {
    return pathUrl instanceof URL ? fromFileUrl2(pathUrl) : pathUrl;
}
function createWalkEntrySync(path) {
    path = toPathString(path);
    path = normalize2(path);
    const name = basename2(path);
    const info = Deno.statSync(path);
    return {
        path,
        name,
        isFile: info.isFile,
        isDirectory: info.isDirectory,
        isSymlink: info.isSymlink
    };
}
class WalkError extends Error {
    root;
    constructor(cause, root){
        super(`${cause instanceof Error ? cause.message : cause} for path "${root}"`);
        this.cause = cause;
        this.name = "WalkError";
        this.root = root;
    }
}
function include(path, exts, match, skip) {
    if (exts && !exts.some((ext)=>path.endsWith(ext))) {
        return false;
    }
    if (match && !match.some((pattern)=>!!path.match(pattern))) {
        return false;
    }
    if (skip && skip.some((pattern)=>!!path.match(pattern))) {
        return false;
    }
    return true;
}
function wrapErrorWithPath(err, root) {
    if (err instanceof WalkError) return err;
    return new WalkError(err, root);
}
function* walkSync(root, { maxDepth = Infinity, includeFiles = true, includeDirs = true, includeSymlinks = true, followSymlinks = false, canonicalize = true, exts = undefined, match = undefined, skip = undefined } = {}) {
    root = toPathString(root);
    if (maxDepth < 0) {
        return;
    }
    if (includeDirs && include(root, exts, match, skip)) {
        yield createWalkEntrySync(root);
    }
    if (maxDepth < 1 || !include(root, undefined, undefined, skip)) {
        return;
    }
    let entries;
    try {
        entries = Deno.readDirSync(root);
    } catch (err) {
        throw wrapErrorWithPath(err, normalize2(root));
    }
    for (const entry of entries){
        let path = join2(root, entry.name);
        let { isSymlink, isDirectory } = entry;
        if (isSymlink) {
            if (!followSymlinks) {
                if (includeSymlinks && include(path, exts, match, skip)) {
                    yield {
                        path,
                        ...entry
                    };
                }
                continue;
            }
            const realPath = Deno.realPathSync(path);
            if (canonicalize) {
                path = realPath;
            }
            ({ isSymlink, isDirectory } = Deno.lstatSync(realPath));
        }
        if (isSymlink || isDirectory) {
            yield* walkSync(path, {
                maxDepth: maxDepth - 1,
                includeFiles,
                includeDirs,
                includeSymlinks,
                followSymlinks,
                exts,
                match,
                skip
            });
        } else if (includeFiles && include(path, exts, match, skip)) {
            yield {
                path,
                ...entry
            };
        }
    }
}
const isWindows1 = Deno.build.os === "windows";
function split(path) {
    const s = SEPARATOR_PATTERN2.source;
    const segments = path.replace(new RegExp(`^${s}|${s}$`, "g"), "").split(SEPARATOR_PATTERN2);
    const isAbsolute_ = isAbsolute2(path);
    return {
        segments,
        isAbsolute: isAbsolute_,
        hasTrailingSep: !!path.match(new RegExp(`${s}$`)),
        winRoot: isWindows1 && isAbsolute_ ? segments.shift() : undefined
    };
}
function throwUnlessNotFound(error) {
    if (!(error instanceof Deno.errors.NotFound)) {
        throw error;
    }
}
function comparePath(a, b) {
    if (a.path < b.path) return -1;
    if (a.path > b.path) return 1;
    return 0;
}
function* expandGlobSync(glob, { root, exclude = [], includeDirs = true, extended = true, globstar = true, caseInsensitive, followSymlinks, canonicalize } = {}) {
    const { segments, isAbsolute: isGlobAbsolute, hasTrailingSep, winRoot } = split(toPathString(glob));
    root ??= isGlobAbsolute ? winRoot ?? "/" : Deno.cwd();
    const globOptions = {
        extended,
        globstar,
        caseInsensitive
    };
    const absRoot = isGlobAbsolute ? root : resolve2(root);
    const resolveFromRoot = (path)=>resolve2(absRoot, path);
    const excludePatterns = exclude.map(resolveFromRoot).map((s)=>globToRegExp2(s, globOptions));
    const shouldInclude = (path)=>!excludePatterns.some((p)=>!!path.match(p));
    let fixedRoot = isGlobAbsolute ? winRoot !== undefined ? winRoot : "/" : absRoot;
    while(segments.length > 0 && !isGlob(segments[0])){
        const seg = segments.shift();
        assert(seg !== undefined);
        fixedRoot = joinGlobs2([
            fixedRoot,
            seg
        ], globOptions);
    }
    let fixedRootInfo;
    try {
        fixedRootInfo = createWalkEntrySync(fixedRoot);
    } catch (error) {
        return throwUnlessNotFound(error);
    }
    function* advanceMatch(walkInfo, globSegment) {
        if (!walkInfo.isDirectory) {
            return;
        } else if (globSegment === "..") {
            const parentPath = joinGlobs2([
                walkInfo.path,
                ".."
            ], globOptions);
            try {
                if (shouldInclude(parentPath)) {
                    return yield createWalkEntrySync(parentPath);
                }
            } catch (error) {
                throwUnlessNotFound(error);
            }
            return;
        } else if (globSegment === "**") {
            return yield* walkSync(walkInfo.path, {
                skip: excludePatterns,
                maxDepth: globstar ? Infinity : 1,
                followSymlinks,
                canonicalize
            });
        }
        const globPattern = globToRegExp2(globSegment, globOptions);
        for (const walkEntry of walkSync(walkInfo.path, {
            maxDepth: 1,
            skip: excludePatterns,
            followSymlinks
        })){
            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;
}
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 data = this.__data__, index = __VIRTUAL_FILE2(data, key);
    if (index < 0) {
        return false;
    }
    var lastIndex = data.length - 1;
    if (index == lastIndex) {
        data.pop();
    } else {
        splice.call(data, index, 1);
    }
    --this.size;
    return true;
}
var __VIRTUAL_FILE3 = listCacheDelete;
function listCacheGet(key) {
    var data = this.__data__, index = __VIRTUAL_FILE2(data, key);
    return index < 0 ? void 0 : data[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 data = this.__data__, index = __VIRTUAL_FILE2(data, key);
    if (index < 0) {
        ++this.size;
        data.push([
            key,
            value
        ]);
    } else {
        data[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 data = this.__data__, result1 = data["delete"](key);
    this.size = data.size;
    return result1;
}
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 result1 = nativeObjectToString.call(value);
    if (unmasked) {
        if (isOwn) {
            value[symToStringTag] = tag;
        } else {
            delete value[symToStringTag];
        }
    }
    return result1;
}
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 isObject(value) {
    var type = typeof value;
    return value != null && (type == "object" || type == "function");
}
var __VIRTUAL_FILE18 = isObject;
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 (e) {}
    }
    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 result1 = this.has(key) && delete this.__data__[key];
    this.size -= result1 ? 1 : 0;
    return result1;
}
var __VIRTUAL_FILE29 = hashDelete;
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var objectProto3 = Object.prototype;
var hasOwnProperty2 = objectProto3.hasOwnProperty;
function hashGet(key) {
    var data = this.__data__;
    if (__VIRTUAL_FILE27) {
        var result1 = data[key];
        return result1 === HASH_UNDEFINED ? void 0 : result1;
    }
    return hasOwnProperty2.call(data, key) ? data[key] : void 0;
}
var __VIRTUAL_FILE30 = hashGet;
var objectProto4 = Object.prototype;
var hasOwnProperty3 = objectProto4.hasOwnProperty;
function hashHas(key) {
    var data = this.__data__;
    return __VIRTUAL_FILE27 ? data[key] !== void 0 : hasOwnProperty3.call(data, key);
}
var __VIRTUAL_FILE31 = hashHas;
var HASH_UNDEFINED1 = "__lodash_hash_undefined__";
function hashSet(key, value) {
    var data = this.__data__;
    this.size += this.has(key) ? 0 : 1;
    data[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(map, key) {
    var data = map.__data__;
    return __VIRTUAL_FILE35(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
var __VIRTUAL_FILE36 = getMapData;
function mapCacheDelete(key) {
    var result1 = __VIRTUAL_FILE36(this, key)["delete"](key);
    this.size -= result1 ? 1 : 0;
    return result1;
}
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 data = __VIRTUAL_FILE36(this, key), size = data.size;
    data.set(key, value);
    this.size += data.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 data = this.__data__;
    if (data instanceof __VIRTUAL_FILE7) {
        var pairs = data.__data__;
        if (!__VIRTUAL_FILE26 || pairs.length < LARGE_ARRAY_SIZE - 1) {
            pairs.push([
                key,
                value
            ]);
            this.size = ++data.size;
            return this;
        }
        data = this.__data__ = new __VIRTUAL_FILE41(pairs);
    }
    data.set(key, value);
    this.size = data.size;
    return this;
}
var __VIRTUAL_FILE42 = stackSet;
function Stack(entries) {
    var data = this.__data__ = new __VIRTUAL_FILE7(entries);
    this.size = data.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(n, iteratee) {
    var index = -1, result1 = Array(n);
    while(++index < n){
        result1[index] = iteratee(index);
    }
    return result1;
}
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 module1 = {
        exports: {}
    };
    return fn(module1, module1.exports), module1.exports;
}
var __VIRTUAL_FILE55 = createCommonjsModule(function(module1, exports) {
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module1 && !module1.nodeType && module1;
    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;
    module1.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 module1 = {
        exports: {}
    };
    return fn(module1, module1.exports), module1.exports;
}
var __VIRTUAL_FILE60 = createCommonjsModule1(function(module1, exports) {
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module1 && !module1.nodeType && module1;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && __VIRTUAL_FILE12.process;
    var nodeUtil = function() {
        try {
            var types = freeModule && freeModule.require && freeModule.require("util").types;
            if (types) {
                return types;
            }
            return freeProcess && freeProcess.binding && freeProcess.binding("util");
        } catch (e) {}
    }();
    module1.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, result1 = skipIndexes ? __VIRTUAL_FILE49(value.length, String) : [], length = result1.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)))) {
            result1.push(key);
        }
    }
    return result1;
}
var __VIRTUAL_FILE62 = arrayLikeKeys;
var objectProto8 = Object.prototype;
function isPrototype(value) {
    var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto8;
    return value === proto;
}
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 result1 = [];
    for(var key in Object(object)){
        if (hasOwnProperty7.call(object, key) && key != "constructor") {
            result1.push(key);
        }
    }
    return result1;
}
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 result1 = [];
    if (object != null) {
        for(var key in Object(object)){
            result1.push(key);
        }
    }
    return result1;
}
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), result1 = [];
    for(var key in object){
        if (!(key == "constructor" && (isProto || !hasOwnProperty8.call(object, key)))) {
            result1.push(key);
        }
    }
    return result1;
}
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 module1 = {
        exports: {}
    };
    return fn(module1, module1.exports), module1.exports;
}
var __VIRTUAL_FILE74 = createCommonjsModule2(function(module1, exports) {
    var freeExports = exports && !exports.nodeType && exports;
    var freeModule = freeExports && true && module1 && !module1.nodeType && module1;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var Buffer1 = moduleExports ? __VIRTUAL_FILE13.Buffer : void 0, allocUnsafe = Buffer1 ? Buffer1.allocUnsafe : void 0;
    function cloneBuffer(buffer, isDeep) {
        if (isDeep) {
            return buffer.slice();
        }
        var length = buffer.length, result1 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
        buffer.copy(result1);
        return result1;
    }
    module1.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, result1 = [];
    while(++index < length){
        var value = array[index];
        if (predicate(value, index, array)) {
            result1[resIndex++] = value;
        }
    }
    return result1;
}
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, values) {
    var index = -1, length = values.length, offset = array.length;
    while(++index < length){
        array[offset + index] = values[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 result1 = [];
    while(object){
        __VIRTUAL_FILE80(result1, __VIRTUAL_FILE78(object));
        object = __VIRTUAL_FILE81(object);
    }
    return result1;
};
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 result1 = keysFunc(object);
    return __VIRTUAL_FILE53(object) ? result1 : __VIRTUAL_FILE80(result1, 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 WeakMap1 = __VIRTUAL_FILE25(__VIRTUAL_FILE13, "WeakMap");
var __VIRTUAL_FILE90 = WeakMap1;
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 result1 = __VIRTUAL_FILE17(value), Ctor = result1 == 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 result1;
    };
}
var __VIRTUAL_FILE91 = getTag;
var objectProto12 = Object.prototype;
var hasOwnProperty9 = objectProto12.hasOwnProperty;
function initCloneArray(array) {
    var length = array.length, result1 = new array.constructor(length);
    if (length && typeof array[0] == "string" && hasOwnProperty9.call(array, "index")) {
        result1.index = array.index;
        result1.input = array.input;
    }
    return result1;
}
var __VIRTUAL_FILE92 = initCloneArray;
var Uint8Array1 = __VIRTUAL_FILE13.Uint8Array;
var __VIRTUAL_FILE93 = Uint8Array1;
function cloneArrayBuffer(arrayBuffer) {
    var result1 = new arrayBuffer.constructor(arrayBuffer.byteLength);
    new __VIRTUAL_FILE93(result1).set(new __VIRTUAL_FILE93(arrayBuffer));
    return result1;
}
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(regexp) {
    var result1 = new regexp.constructor(regexp.source, reFlags.exec(regexp));
    result1.lastIndex = regexp.lastIndex;
    return result1;
}
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(proto) {
        if (!__VIRTUAL_FILE18(proto)) {
            return {};
        }
        if (objectCreate) {
            return objectCreate(proto);
        }
        object.prototype = proto;
        var result1 = new object();
        object.prototype = void 0;
        return result1;
    };
}();
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 result1, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
    if (customizer) {
        result1 = object ? customizer(value, key, object, stack) : customizer(value);
    }
    if (result1 !== void 0) {
        return result1;
    }
    if (!__VIRTUAL_FILE18(value)) {
        return value;
    }
    var isArr = __VIRTUAL_FILE53(value);
    if (isArr) {
        result1 = __VIRTUAL_FILE92(value);
        if (!isDeep) {
            return __VIRTUAL_FILE75(value, result1);
        }
    } 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) {
            result1 = isFlat || isFunc ? {} : __VIRTUAL_FILE101(value);
            if (!isDeep) {
                return isFlat ? __VIRTUAL_FILE83(value, __VIRTUAL_FILE73(result1, value)) : __VIRTUAL_FILE79(value, __VIRTUAL_FILE69(result1, value));
            }
        } else {
            if (!cloneableTags[tag]) {
                return object ? value : {};
            }
            result1 = __VIRTUAL_FILE99(value, tag, isDeep);
        }
    }
    stack || (stack = new __VIRTUAL_FILE43());
    var stacked = stack.get(value);
    if (stacked) {
        return stacked;
    }
    stack.set(value, result1);
    if (__VIRTUAL_FILE105(value)) {
        value.forEach(function(subValue) {
            result1.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
        });
    } else if (__VIRTUAL_FILE103(value)) {
        value.forEach(function(subValue, key2) {
            result1.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(result1, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
    });
    return result1;
}
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 reWhitespace = /\s/;
function trimmedEndIndex(string) {
    var index = string.length;
    while(index-- && reWhitespace.test(string.charAt(index))){}
    return index;
}
var __VIRTUAL_FILE109 = trimmedEndIndex;
var reTrimStart = /^\s+/;
function baseTrim(string) {
    return string ? string.slice(0, __VIRTUAL_FILE109(string) + 1).replace(reTrimStart, "") : string;
}
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 isBinary = reIsBinary.test(value);
    return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 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, result1, 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;
        result1 = func.apply(thisArg, args);
        return result1;
    }
    function leadingEdge(time) {
        lastInvokeTime = time;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time) : result1;
    }
    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 result1;
    }
    function cancel() {
        if (timerId !== void 0) {
            clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
    }
    function flush() {
        return timerId === void 0 ? result1 : 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 result1;
    }
    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(values) {
    var index = -1, length = values == null ? 0 : values.length;
    this.__data__ = new __VIRTUAL_FILE41();
    while(++index < length){
        this.add(values[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, result1 = Array(length);
    while(++index < length){
        result1[index] = iteratee(array[index], index, array);
    }
    return result1;
}
var __VIRTUAL_FILE123 = arrayMap;
function cacheHas(cache, key) {
    return cache.has(key);
}
var __VIRTUAL_FILE124 = cacheHas;
var LARGE_ARRAY_SIZE1 = 200;
function baseDifference(array, values, iteratee, comparator) {
    var index = -1, includes = __VIRTUAL_FILE121, isCommon = true, length = array.length, result1 = [], valuesLength = values.length;
    if (!length) {
        return result1;
    }
    if (iteratee) {
        values = __VIRTUAL_FILE123(values, __VIRTUAL_FILE59(iteratee));
    }
    if (comparator) {
        includes = __VIRTUAL_FILE122;
        isCommon = false;
    } else if (values.length >= LARGE_ARRAY_SIZE1) {
        includes = __VIRTUAL_FILE124;
        isCommon = false;
        values = new __VIRTUAL_FILE116(values);
    }
    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 (values[valuesIndex] === computed) {
                    continue outer;
                }
            }
            result1.push(value);
        } else if (!includes(values, computed, comparator)) {
            result1.push(value);
        }
    }
    return result1;
}
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, result1) {
    var index = -1, length = array.length;
    predicate || (predicate = __VIRTUAL_FILE126);
    result1 || (result1 = []);
    while(++index < length){
        var value = array[index];
        if (depth > 0 && predicate(value)) {
            if (depth > 1) {
                baseFlatten(value, depth - 1, predicate, isStrict, result1);
            } else {
                __VIRTUAL_FILE80(result1, value);
            }
        } else if (!isStrict) {
            result1[result1.length] = value;
        }
    }
    return result1;
}
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, string) {
    return __VIRTUAL_FILE45(func, "toString", {
        configurable: true,
        enumerable: false,
        value: __VIRTUAL_FILE131(string),
        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, values) {
    return __VIRTUAL_FILE136(array) ? __VIRTUAL_FILE125(array, __VIRTUAL_FILE127(values, 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 proto = __VIRTUAL_FILE81(value);
    if (proto === null) {
        return true;
    }
    var Ctor = hasOwnProperty10.call(proto, "constructor") && proto.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 result1 = value + "";
    return result1 == "0" && 1 / value == -INFINITY ? "-0" : result1;
}
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(string) {
    string = __VIRTUAL_FILE171(string);
    return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, __VIRTUAL_FILE169) : string;
}
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(string, options, guard) {
    var settings = __VIRTUAL_FILE175.imports._.templateSettings || __VIRTUAL_FILE175;
    if (guard && __VIRTUAL_FILE152(string, options, guard)) {
        options = void 0;
    }
    string = __VIRTUAL_FILE171(string);
    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" : "";
    string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
        interpolateValue || (interpolateValue = esTemplateValue);
        source += string.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 result1 = __VIRTUAL_FILE164(function() {
        return Function(importsKeys, sourceURL + "return " + source).apply(void 0, importsValues);
    });
    result1.source = source;
    if (__VIRTUAL_FILE163(result1)) {
        throw result1;
    }
    return result1;
}
var __VIRTUAL_FILE176 = template;
function noop() {}
var __VIRTUAL_FILE177 = noop;
function setToArray(set) {
    var index = -1, result1 = Array(set.size);
    set.forEach(function(value) {
        result1[++index] = value;
    });
    return result1;
}
var __VIRTUAL_FILE178 = setToArray;
var INFINITY1 = 1 / 0;
var createSet = !(__VIRTUAL_FILE89 && 1 / __VIRTUAL_FILE178(new __VIRTUAL_FILE89([
    ,
    -0
]))[1] == INFINITY1) ? __VIRTUAL_FILE177 : function(values) {
    return new __VIRTUAL_FILE89(values);
};
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, result1 = [], seen = result1;
    if (comparator) {
        isCommon = false;
        includes = __VIRTUAL_FILE122;
    } else if (length >= LARGE_ARRAY_SIZE2) {
        var set = iteratee ? null : __VIRTUAL_FILE179(array);
        if (set) {
            return __VIRTUAL_FILE178(set);
        }
        isCommon = false;
        includes = __VIRTUAL_FILE124;
        seen = new __VIRTUAL_FILE116();
    } else {
        seen = iteratee ? [] : result1;
    }
    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);
            }
            result1.push(value);
        } else if (!includes(seen, computed, comparator)) {
            if (seen !== result1) {
                seen.push(computed);
            }
            result1.push(value);
        }
    }
    return result1;
}
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, result1 = 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;
            }
            result1 = 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);
                }
            })) {
                result1 = false;
                break;
            }
        } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
            result1 = false;
            break;
        }
    }
    stack["delete"](array);
    stack["delete"](other);
    return result1;
}
var __VIRTUAL_FILE183 = equalArrays;
function mapToArray(map) {
    var index = -1, result1 = Array(map.size);
    map.forEach(function(value, key) {
        result1[++index] = [
            key,
            value
        ];
    });
    return result1;
}
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 result1 = __VIRTUAL_FILE183(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
            stack["delete"](object);
            return result1;
        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 result1 = 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)) {
            result1 = false;
            break;
        }
        skipCtor || (skipCtor = key == "constructor");
    }
    if (result1 && !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)) {
            result1 = false;
        }
    }
    stack["delete"](object);
    stack["delete"](other);
    return result1;
}
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 data = matchData[index];
        if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
            return false;
        }
    }
    while(++index < length){
        data = matchData[index];
        var key = data[0], objValue = object[key], srcValue = data[1];
        if (noCustomizer && data[2]) {
            if (objValue === void 0 && !(key in object)) {
                return false;
            }
        } else {
            var stack = new __VIRTUAL_FILE43();
            if (customizer) {
                var result1 = customizer(objValue, srcValue, key, object, source, stack);
            }
            if (!(result1 === void 0 ? __VIRTUAL_FILE188(srcValue, objValue, COMPARE_PARTIAL_FLAG4 | COMPARE_UNORDERED_FLAG2, customizer, stack) : result1)) {
                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 result1 = __VIRTUAL_FILE68(object), length = result1.length;
    while(length--){
        var key = result1[length], value = object[key];
        result1[length] = [
            key,
            value,
            __VIRTUAL_FILE190(value)
        ];
    }
    return result1;
}
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 memoize(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 result1 = func.apply(this, args);
        memoized.cache = cache.set(key, result1) || cache;
        return result1;
    };
    memoized.cache = new (memoize.Cache || __VIRTUAL_FILE41)();
    return memoized;
}
memoize.Cache = __VIRTUAL_FILE41;
var __VIRTUAL_FILE195 = memoize;
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped(func) {
    var result1 = __VIRTUAL_FILE195(func, function(key) {
        if (cache.size === MAX_MEMOIZE_SIZE) {
            cache.clear();
        }
        return key;
    });
    var cache = result1.cache;
    return result1;
}
var __VIRTUAL_FILE196 = memoizeCapped;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath = __VIRTUAL_FILE196(function(string) {
    var result1 = [];
    if (string.charCodeAt(0) === 46) {
        result1.push("");
    }
    string.replace(rePropName, function(match, number, quote, subString) {
        result1.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
    });
    return result1;
});
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 result1 = value + "";
    return result1 == "0" && 1 / value == -INFINITY2 ? "-0" : result1;
}
var __VIRTUAL_FILE199 = toKey;
function baseGet(object, path) {
    path = __VIRTUAL_FILE198(path, object);
    var index = 0, length = path.length;
    while(object != null && index < length){
        object = object[__VIRTUAL_FILE199(path[index++])];
    }
    return index && index == length ? object : void 0;
}
var __VIRTUAL_FILE200 = baseGet;
function get(object, path, defaultValue) {
    var result1 = object == null ? void 0 : __VIRTUAL_FILE200(object, path);
    return result1 === void 0 ? defaultValue : result1;
}
var __VIRTUAL_FILE201 = get;
function baseHasIn(object, key) {
    return object != null && key in Object(object);
}
var __VIRTUAL_FILE202 = baseHasIn;
function hasPath(object, path, hasFunc) {
    path = __VIRTUAL_FILE198(path, object);
    var index = -1, length = path.length, result1 = false;
    while(++index < length){
        var key = __VIRTUAL_FILE199(path[index]);
        if (!(result1 = object != null && hasFunc(object, key))) {
            break;
        }
        object = object[key];
    }
    if (result1 || ++index != length) {
        return result1;
    }
    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, path) {
    return object != null && __VIRTUAL_FILE203(object, path, __VIRTUAL_FILE202);
}
var __VIRTUAL_FILE204 = hasIn;
var COMPARE_PARTIAL_FLAG5 = 1, COMPARE_UNORDERED_FLAG3 = 2;
function baseMatchesProperty(path, srcValue) {
    if (__VIRTUAL_FILE194(path) && __VIRTUAL_FILE190(srcValue)) {
        return __VIRTUAL_FILE192(__VIRTUAL_FILE199(path), srcValue);
    }
    return function(object) {
        var objValue = __VIRTUAL_FILE201(object, path);
        return objValue === void 0 && objValue === srcValue ? __VIRTUAL_FILE204(object, path) : __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(path) {
    return function(object) {
        return __VIRTUAL_FILE200(object, path);
    };
}
var __VIRTUAL_FILE207 = basePropertyDeep;
function property(path) {
    return __VIRTUAL_FILE194(path) ? __VIRTUAL_FILE206(__VIRTUAL_FILE199(path)) : __VIRTUAL_FILE207(path);
}
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, result1 = __VIRTUAL_FILE67(collection) ? Array(collection.length) : [];
    __VIRTUAL_FILE142(collection, function(value, key, collection2) {
        result1[++index] = iteratee(value, key, collection2);
    });
    return result1;
}
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 result1 = __VIRTUAL_FILE214(objCriteria[index], othCriteria[index]);
        if (result1) {
            if (index >= ordersLength) {
                return result1;
            }
            var order = orders[index];
            return result1 * (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 result1 = __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(result1, 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;
function getenv(name, defaultValue) {
    const value = Deno.env.get(name);
    if (value === undefined) {
        if (defaultValue === undefined) {
            throw new Error(`Required environment variable ${name} not specified.`);
        } else {
            return defaultValue;
        }
    } else {
        return value;
    }
}
function withPath(paths) {
    const delimiter = Deno.build.os === "windows" ? ";" : ":";
    const currentPath = Deno.env.get("PATH") || "";
    if (paths.append !== undefined && paths.prepend !== undefined) {
        return currentPath;
    } else if (paths.append?.length === 0 && paths.prepend?.length === 0) {
        return currentPath;
    } else {
        const modifiedPaths = [
            currentPath
        ];
        if (paths.append) {
            modifiedPaths.unshift(...paths.append);
        }
        if (paths.prepend) {
            modifiedPaths.push(...paths.prepend);
        }
        return modifiedPaths.join(delimiter);
    }
}
class MuxAsyncIterator {
    #iteratorCount = 0;
    #yields = [];
    #throws = [];
    #signal = Promise.withResolvers();
    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.promise;
            for (const { iterator, value } of this.#yields){
                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 = Promise.withResolvers();
        }
    }
    [Symbol.asyncIterator]() {
        return this.iterate();
    }
}
const ERROR_WHILE_MAPPING_MESSAGE = "Threw while mapping.";
function pooledMap(poolLimit, array, iteratorFn) {
    const res = new TransformStream({
        async transform (p, controller) {
            try {
                const s = await p;
                controller.enqueue(s);
            } catch (e) {
                if (e instanceof AggregateError && e.message === ERROR_WHILE_MAPPING_MESSAGE) {
                    controller.error(e);
                }
            }
        }
    });
    (async ()=>{
        const writer = res.writable.getWriter();
        const executing = [];
        try {
            for await (const item of array){
                const p = Promise.resolve().then(()=>iteratorFn(item));
                writer.write(p);
                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 errors = [];
            for (const result1 of (await Promise.allSettled(executing))){
                if (result1.status === "rejected") {
                    errors.push(result1.reason);
                }
            }
            writer.write(Promise.reject(new AggregateError(errors, ERROR_WHILE_MAPPING_MESSAGE))).catch(()=>{});
        }
    })();
    return Symbol.asyncIterator in res.readable && typeof res.readable[Symbol.asyncIterator] === "function" ? res.readable[Symbol.asyncIterator]() : async function*() {
        const reader = res.readable.getReader();
        while(true){
            const { done, value } = await reader.read();
            if (done) break;
            yield value;
        }
        reader.releaseLock();
    }();
}
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 MAX_SIZE = 2 ** 32 - 2;
class Buffer1 {
    #buf;
    #off = 0;
    #readable = new ReadableStream({
        type: "bytes",
        pull: (controller)=>{
            const view = new Uint8Array(controller.byobRequest.view.buffer);
            if (this.empty()) {
                this.reset();
                controller.close();
                controller.byobRequest.respond(0);
                return;
            }
            const nread = copy(this.#buf.subarray(this.#off), view);
            this.#off += nread;
            controller.byobRequest.respond(nread);
        },
        autoAllocateChunkSize: 16_640
    });
    get readable() {
        return this.#readable;
    }
    #writable = new WritableStream({
        write: (chunk)=>{
            const m = this.#grow(chunk.byteLength);
            copy(chunk, this.#buf, m);
        }
    });
    get writable() {
        return this.#writable;
    }
    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 l1 = this.#buf.byteLength;
        if (n <= this.capacity - l1) {
            this.#reslice(l1 + n);
            return l1;
        }
        return -1;
    }
    #reslice(len) {
        assert(len <= this.#buf.buffer.byteLength);
        this.#buf = new Uint8Array(this.#buf.buffer, 0, len);
    }
    #grow(n) {
        const m = this.length;
        if (m === 0 && this.#off !== 0) {
            this.reset();
        }
        const i1 = this.#tryGrowByReslice(n);
        if (i1 >= 0) {
            return i1;
        }
        const c = this.capacity;
        if (n <= Math.floor(c / 2) - m) {
            copy(this.#buf.subarray(this.#off), this.#buf);
        } else if (c + n > MAX_SIZE) {
            throw new Error("The buffer cannot be grown beyond the maximum size.");
        } else {
            const buf = new Uint8Array(Math.min(2 * c + n, MAX_SIZE));
            copy(this.#buf.subarray(this.#off), buf);
            this.#buf = buf;
        }
        this.#off = 0;
        this.#reslice(Math.min(m + n, MAX_SIZE));
        return m;
    }
    grow(n) {
        if (n < 0) {
            throw Error("Buffer.grow: negative count");
        }
        const m = this.#grow(n);
        this.#reslice(m);
    }
}
function concat(buf) {
    let length = 0;
    for (const b of buf){
        length += b.length;
    }
    const output = new Uint8Array(length);
    let index = 0;
    for (const b of buf){
        output.set(b, index);
        index += b.length;
    }
    return output;
}
const DEFAULT_BUFFER_SIZE = 32 * 1024;
async function* iterateReader(reader, options) {
    const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
    const b = new Uint8Array(bufSize);
    while(true){
        const result1 = await reader.read(b);
        if (result1 === null) {
            break;
        }
        yield b.slice(0, result1);
    }
}
function iterateReader1(r, options) {
    return iterateReader(r, options);
}
const MIN_READ = 32 * 1024;
const MAX_SIZE1 = 2 ** 32 - 2;
class Buffer2 {
    #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 l1 = this.#buf.byteLength;
        if (n <= this.capacity - l1) {
            this.#reslice(l1 + n);
            return l1;
        }
        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 n = this.writeSync(p);
        return Promise.resolve(n);
    }
    #grow(n) {
        const m = this.length;
        if (m === 0 && this.#off !== 0) {
            this.reset();
        }
        const i1 = this.#tryGrowByReslice(n);
        if (i1 >= 0) {
            return i1;
        }
        const c = this.capacity;
        if (n <= Math.floor(c / 2) - m) {
            copy(this.#buf.subarray(this.#off), this.#buf);
        } else if (c + n > MAX_SIZE1) {
            throw new Error("The buffer cannot be grown beyond the maximum size.");
        } else {
            const buf = new Uint8Array(Math.min(2 * c + n, MAX_SIZE1));
            copy(this.#buf.subarray(this.#off), buf);
            this.#buf = buf;
        }
        this.#off = 0;
        this.#reslice(Math.min(m + n, MAX_SIZE1));
        return m;
    }
    grow(n) {
        if (n < 0) {
            throw Error("Buffer.grow: negative count");
        }
        const m = this.#grow(n);
        this.#reslice(m);
    }
    async readFrom(r) {
        let n = 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 n;
            }
            if (shouldGrow) this.writeSync(buf.subarray(0, nread));
            else this.#reslice(this.length + nread);
            n += nread;
        }
    }
    readFromSync(r) {
        let n = 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 n;
            }
            if (shouldGrow) this.writeSync(buf.subarray(0, nread));
            else this.#reslice(this.length + nread);
            n += nread;
        }
    }
}
async function writeAll(writer, data) {
    let nwritten = 0;
    while(nwritten < data.length){
        nwritten += await writer.write(data.subarray(nwritten));
    }
}
function writeAllSync(writer, data) {
    let nwritten = 0;
    while(nwritten < data.length){
        nwritten += writer.writeSync(data.subarray(nwritten));
    }
}
new TextDecoder();
const cleanupHandlers = [];
function onCleanup(handler) {
    cleanupHandlers.push(handler);
}
function exitWithCleanup(code) {
    for (const handler of cleanupHandlers){
        try {
            handler();
        } catch (error) {
            info("Error occurred during cleanup: " + error);
        }
    }
    Deno.exit(code);
}
const processList = new Map();
let processCount = 0;
let cleanupRegistered = false;
function ensureCleanup() {
    if (!cleanupRegistered) {
        cleanupRegistered = true;
        onCleanup(()=>{
            for (const process of processList.values()){
                try {
                    process.kill();
                    process.close();
                } catch (error) {
                    info("Error occurred during cleanup: " + error);
                }
            }
        });
    }
}
async function execProcess(options, stdin, mergeOutput, stderrFilter, respectStreams, timeout) {
    const withTimeout = (promise)=>{
        return timeout ? Promise.race([
            promise,
            new Promise((_, reject)=>setTimeout(()=>reject(new Error("Process timed out")), timeout))
        ]) : promise;
    };
    ensureCleanup();
    try {
        debug(`[execProcess] ${options.cmd.join(" ")}`);
        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"
        });
        const thisProcessId = ++processCount;
        processList.set(thisProcessId, process);
        if (stdin !== undefined) {
            if (!process.stdin) {
                processList.delete(processCount);
                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 window1 = buffer.subarray(offset, end);
                const written = await process.stdin.write(window1);
                offset += written;
            }
            process.stdin.close();
        }
        let stdoutText = "";
        let stderrText = "";
        if (mergeOutput) {
            const multiplexIterator = new MuxAsyncIterator();
            const addStream = (stream, filter)=>{
                if (stream !== null) {
                    const streamIter = filter ? filteredAsyncIterator(iterateReader1(stream), filter) : iterateReader1(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 {
            const promises = [];
            if (process.stdout !== null) {
                promises.push(processOutput(iterateReader1(process.stdout), options.stdout, respectStreams ? "stdout" : undefined).then((text)=>{
                    stdoutText = text;
                    process.stdout.close();
                }));
            }
            if (process.stderr != null) {
                const iterator = stderrFilter ? filteredAsyncIterator(iterateReader1(process.stderr), stderrFilter) : iterateReader1(process.stderr);
                promises.push(processOutput(iterator, options.stderr, respectStreams ? "stderr" : undefined).then((text)=>{
                    stderrText = text;
                    process.stderr.close();
                }));
            }
            await withTimeout(Promise.all(promises));
        }
        const status = await withTimeout(process.status());
        process.close();
        processList.delete(thisProcessId);
        debug(`[execProcess] Success: ${status.success}, code: ${status.code}`);
        return {
            success: status.success,
            code: status.code,
            stdout: stdoutText,
            stderr: stderrText
        };
    } catch (e) {
        throw new Error(`Error executing '${options.cmd[0]}': ${e.message}`);
    }
}
function processSuccessResult() {
    return {
        success: true,
        code: 0
    };
}
function filteredAsyncIterator(iterator, filter) {
    const encoder = new TextEncoder();
    const decoder = new TextDecoder();
    return pooledMap(1, iterator, (data)=>{
        return Promise.resolve(encoder.encode(filter(decoder.decode(data))));
    });
}
async function processOutput(iterator, output, which) {
    const decoder = new TextDecoder();
    let outputText = "";
    for await (const chunk of iterator){
        if (output === "inherit" || output === undefined) {
            if (which === "stdout") {
                Deno.stdout.writeSync(chunk);
            } else if (which === "stderr") {
                Deno.stderr.writeSync(chunk);
            } else {
                info(decoder.decode(chunk), {
                    newline: false
                });
            }
        }
        const text = decoder.decode(chunk);
        outputText += text;
    }
    return outputText;
}
const kSkipHidden = /[/\\][\.]/;
function removeIfExists(file) {
    if (existsSync(file)) {
        Deno.removeSync(file, {
            recursive: true
        });
    }
}
function safeRemoveIfExists(file) {
    try {
        removeIfExists(file);
    } catch (error) {
        warn(`Error removing file ${file}: ${error.message}`);
    }
}
function safeRemoveSync(file, options = {}) {
    try {
        Deno.removeSync(file, options);
    } catch (e) {
        if (existsSync(file)) {
            throw e;
        }
    }
}
function removeIfEmptyDir(dir) {
    if (existsSync(dir)) {
        let empty = true;
        for (const _entry of Deno.readDirSync(dir)){
            empty = false;
            break;
        }
        if (empty) {
            safeRemoveSync(dir, {
                recursive: true
            });
            return true;
        }
        return false;
    } else {
        return false;
    }
}
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(path) {
    if (path === "~") {
        return getenv("HOME", "~");
    } else {
        return path.replace(/^~\//, getenv("HOME", "~") + "/");
    }
}
function safeExistsSync(path) {
    try {
        return existsSync(path);
    } catch  {
        return false;
    }
}
async function which(cmd) {
    const args = Deno.build.os === "windows" ? [
        "CMD",
        "/C",
        "where",
        cmd
    ] : [
        "which",
        cmd
    ];
    const result1 = await execProcess({
        cmd: args,
        stderr: "piped",
        stdout: "piped"
    });
    if (result1.code === 0) {
        return Deno.build.os === "windows" ? result1.stdout?.split("\n")[0].trim() : result1.stdout?.trim();
    } else {
        return undefined;
    }
}
function filterPaths(root, paths, globs, options) {
    const expandGlobs = (targetGlobs)=>{
        const expanded = [];
        for (const glob of targetGlobs){
            const needSlash = !root.endsWith("/") && !glob.startsWith("/");
            const regex = globToRegExp2(`${root}${needSlash ? "/" : ""}${glob}`);
            const matchingFiles = paths.filter((path)=>{
                return regex.test(path);
            });
            expanded.push(...matchingFiles);
        }
        return __VIRTUAL_FILE181(expanded);
    };
    return resolveGlobs(root, globs, expandGlobs, options);
}
function resolvePathGlobs(root, globs, exclude, options) {
    const expandGlobs = (targetGlobs)=>{
        const expanded = [];
        for (const glob of targetGlobs){
            for (const file of expandGlobSync(glob, {
                root,
                exclude,
                includeDirs: true,
                extended: true,
                globstar: true
            })){
                expanded.push(file.path);
            }
        }
        return __VIRTUAL_FILE181(expanded);
    };
    return resolveGlobs(root, globs, expandGlobs, options);
}
function pathWithForwardSlashes(path) {
    return path.replace(/\\/g, "/");
}
function ensureTrailingSlash(path) {
    if (path && !path.endsWith("/")) {
        return path + "/";
    } else {
        return path;
    }
}
function resolveGlobs(root, globs, expandGlobs, options) {
    const includeGlobs = [];
    const excludeGlobs = [];
    const asFullGlob = (glob, preferSmart)=>{
        const useSmartGlobs = ()=>{
            if (options?.mode === "strict") {
                return false;
            } else if (options?.mode === "always") {
                return true;
            } else if (options?.mode === "auto") {
                if (preferSmart) {
                    return true;
                } else {
                    return isGlob(glob);
                }
            } else {
                return true;
            }
        };
        const smartGlob = useSmartGlobs();
        if (glob.startsWith("\\!")) {
            glob = glob.slice(1);
        }
        if (smartGlob) {
            glob = glob.replace(/^\.([\/\\])+/, "$1");
            if (glob.endsWith("/")) {
                glob = glob + "**/*";
            } else {
                const fullPath = join2(root, glob);
                try {
                    if (Deno.statSync(fullPath).isDirectory) {
                        glob = glob + "/**/*";
                    }
                } catch  {}
            }
        }
        if (!glob.startsWith("/")) {
            if (smartGlob && (!options || !options.explicitSubfolderSearch)) {
                return "**/" + glob;
            } else {
                return glob;
            }
        } else {
            return glob.slice(1);
        }
    };
    for (const glob of globs){
        if (glob.startsWith("!")) {
            excludeGlobs.push(asFullGlob(glob.slice(1), true));
        } else {
            includeGlobs.push(asFullGlob(glob));
        }
    }
    const includeFiles = expandGlobs(includeGlobs);
    const excludeFiles = expandGlobs(excludeGlobs);
    return {
        include: includeFiles,
        exclude: excludeFiles
    };
}
function normalizePath(path) {
    let file = path instanceof URL ? fromFileUrl2(path) : path;
    if (!isAbsolute2(file)) {
        file = join2(Deno.cwd(), file);
    }
    file = normalize2(file);
    return file.replace(/^\w:\\/, (m)=>m[0].toUpperCase() + ":\\");
}
function suggestUserBinPaths() {
    if (Deno.build.os !== "windows") {
        const possiblePaths = [
            "/usr/local/bin",
            "~/.local/bin",
            "~/bin"
        ];
        const pathRaw = Deno.env.get("PATH");
        const paths = pathRaw ? pathRaw.split(":") : [];
        return possiblePaths.filter((path)=>{
            return paths.includes(path) || paths.includes(expandPath(path));
        });
    } else {
        throw new Error("suggestUserBinPaths not currently supported on Windows");
    }
}
Deno.realPathSync = normalizePath;
function withAttempts(callable) {
    for(let i1 = 0; i1 < 5; i1++){
        try {
            return callable();
        } catch (err) {
            if (err.message) {
                debug("Error attempting to create temp file: " + err.message);
                if (i1 === 5 - 1) {
                    throw err;
                } else {
                    debug(`Retrying... ${i1 + 1} of ${5 - 1}`);
                }
            }
        }
    }
    throw new Error("Shouldn't get here");
}
function withAttemptsAsync(callable) {
    const inner = (attempt)=>{
        return callable().catch((err)=>{
            if (err.message) {
                debug("Error attempting to create temp file: " + err.message);
            }
            if (attempt === 5 - 1) {
                throw err;
            } else {
                debug(`Retrying... ${attempt + 1} of ${5 - 1}`);
                return inner(attempt + 1);
            }
        });
    };
    return inner(0);
}
const oldMakeTempFile = Deno.makeTempFile;
const oldMakeTempFileSync = Deno.makeTempFileSync;
const oldMakeTempDir = Deno.makeTempDir;
const oldMakeTempDirSync = Deno.makeTempDirSync;
function makeTempFileSync(options) {
    return withAttempts(()=>oldMakeTempFileSync(options));
}
function makeTempFile(options) {
    return withAttemptsAsync(()=>oldMakeTempFile(options));
}
function makeTempDirSync(options) {
    return withAttempts(()=>oldMakeTempDirSync(options));
}
function makeTempDir(options) {
    return withAttemptsAsync(()=>oldMakeTempDir(options));
}
Deno.makeTempFile = makeTempFile;
Deno.makeTempFileSync = makeTempFileSync;
Deno.makeTempDir = makeTempDir;
Deno.makeTempDirSync = makeTempDirSync;
const oldReadTextFile = Deno.readTextFile;
const oldReadTextFileSync = Deno.readTextFileSync;
Deno.readTextFile = async (path, options)=>{
    try {
        const result1 = await oldReadTextFile(path, options);
        return result1;
    } catch (err) {
        if (err.message) {
            err.message = err.message + "\n" + "Path: " + path;
        }
        throw err;
    }
};
Deno.readTextFileSync = (path)=>{
    try {
        const result1 = oldReadTextFileSync(path);
        return result1;
    } catch (err) {
        if (err.message) {
            err.message = err.message + "\n" + "Path: " + path;
        }
        throw err;
    }
};
const { Deno: Deno2 } = globalThis;
const noColor1 = typeof Deno2?.noColor === "boolean" ? Deno2.noColor : false;
let enabled1 = !noColor1;
function setColorEnabled(value) {
    if (Deno2?.noColor) {
        return;
    }
    enabled1 = value;
}
function getColorEnabled() {
    return enabled1;
}
function code1(open, close) {
    return {
        open: `\x1b[${open.join(";")}m`,
        close: `\x1b[${close}m`,
        regexp: new RegExp(`\\x1b\\[${close}m`, "g")
    };
}
function run1(str, code) {
    return enabled1 ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str;
}
function reset(str) {
    return run1(str, code1([
        0
    ], 0));
}
function bold1(str) {
    return run1(str, code1([
        1
    ], 22));
}
function dim1(str) {
    return run1(str, code1([
        2
    ], 22));
}
function italic(str) {
    return run1(str, code1([
        3
    ], 23));
}
function underline1(str) {
    return run1(str, code1([
        4
    ], 24));
}
function inverse(str) {
    return run1(str, code1([
        7
    ], 27));
}
function hidden(str) {
    return run1(str, code1([
        8
    ], 28));
}
function strikethrough(str) {
    return run1(str, code1([
        9
    ], 29));
}
function black(str) {
    return run1(str, code1([
        30
    ], 39));
}
function red1(str) {
    return run1(str, code1([
        31
    ], 39));
}
function green1(str) {
    return run1(str, code1([
        32
    ], 39));
}
function yellow1(str) {
    return run1(str, code1([
        33
    ], 39));
}
function blue1(str) {
    return run1(str, code1([
        34
    ], 39));
}
function magenta(str) {
    return run1(str, code1([
        35
    ], 39));
}
function cyan(str) {
    return run1(str, code1([
        36
    ], 39));
}
function white(str) {
    return run1(str, code1([
        37
    ], 39));
}
function gray(str) {
    return brightBlack(str);
}
function brightBlack(str) {
    return run1(str, code1([
        90
    ], 39));
}
function brightRed1(str) {
    return run1(str, code1([
        91
    ], 39));
}
function brightGreen(str) {
    return run1(str, code1([
        92
    ], 39));
}
function brightYellow(str) {
    return run1(str, code1([
        93
    ], 39));
}
function brightBlue(str) {
    return run1(str, code1([
        94
    ], 39));
}
function brightMagenta(str) {
    return run1(str, code1([
        95
    ], 39));
}
function brightCyan(str) {
    return run1(str, code1([
        96
    ], 39));
}
function brightWhite(str) {
    return run1(str, code1([
        97
    ], 39));
}
function bgBlack(str) {
    return run1(str, code1([
        40
    ], 49));
}
function bgRed(str) {
    return run1(str, code1([
        41
    ], 49));
}
function bgGreen(str) {
    return run1(str, code1([
        42
    ], 49));
}
function bgYellow(str) {
    return run1(str, code1([
        43
    ], 49));
}
function bgBlue(str) {
    return run1(str, code1([
        44
    ], 49));
}
function bgMagenta(str) {
    return run1(str, code1([
        45
    ], 49));
}
function bgCyan(str) {
    return run1(str, code1([
        46
    ], 49));
}
function bgWhite(str) {
    return run1(str, code1([
        47
    ], 49));
}
function bgBrightBlack(str) {
    return run1(str, code1([
        100
    ], 49));
}
function bgBrightRed(str) {
    return run1(str, code1([
        101
    ], 49));
}
function bgBrightGreen(str) {
    return run1(str, code1([
        102
    ], 49));
}
function bgBrightYellow(str) {
    return run1(str, code1([
        103
    ], 49));
}
function bgBrightBlue(str) {
    return run1(str, code1([
        104
    ], 49));
}
function bgBrightMagenta(str) {
    return run1(str, code1([
        105
    ], 49));
}
function bgBrightCyan(str) {
    return run1(str, code1([
        106
    ], 49));
}
function bgBrightWhite(str) {
    return run1(str, code1([
        107
    ], 49));
}
function clampAndTruncate(n, max = 255, min = 0) {
    return Math.trunc(Math.max(Math.min(n, max), min));
}
function rgb8(str, color) {
    return run1(str, code1([
        38,
        5,
        clampAndTruncate(color)
    ], 39));
}
function bgRgb8(str, color) {
    return run1(str, code1([
        48,
        5,
        clampAndTruncate(color)
    ], 49));
}
function rgb24(str, color) {
    if (typeof color === "number") {
        return run1(str, code1([
            38,
            2,
            color >> 16 & 0xff,
            color >> 8 & 0xff,
            color & 0xff
        ], 39));
    }
    return run1(str, code1([
        38,
        2,
        clampAndTruncate(color.r),
        clampAndTruncate(color.g),
        clampAndTruncate(color.b)
    ], 39));
}
function bgRgb24(str, color) {
    if (typeof color === "number") {
        return run1(str, code1([
            48,
            2,
            color >> 16 & 0xff,
            color >> 8 & 0xff,
            color & 0xff
        ], 49));
    }
    return run1(str, code1([
        48,
        2,
        clampAndTruncate(color.r),
        clampAndTruncate(color.g),
        clampAndTruncate(color.b)
    ], 49));
}
const ANSI_PATTERN1 = new RegExp([
    "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
    "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"
].join("|"), "g");
function stripColor1(string) {
    return string.replace(ANSI_PATTERN1, "");
}
const mod1 = {
    setColorEnabled: setColorEnabled,
    getColorEnabled: getColorEnabled,
    reset: reset,
    bold: bold1,
    dim: dim1,
    italic: italic,
    underline: underline1,
    inverse: inverse,
    hidden: hidden,
    strikethrough: strikethrough,
    black: black,
    red: red1,
    green: green1,
    yellow: yellow1,
    blue: blue1,
    magenta: magenta,
    cyan: cyan,
    white: white,
    gray: gray,
    brightBlack: brightBlack,
    brightRed: brightRed1,
    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: stripColor1
};
function distance(a, b) {
    if (a.length == 0) {
        return b.length;
    }
    if (b.length == 0) {
        return a.length;
    }
    const matrix = [];
    for(let i1 = 0; i1 <= b.length; i1++){
        matrix[i1] = [
            i1
        ];
    }
    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(str) {
    return str.replace(/-([a-z])/g, (g)=>g[1].toUpperCase());
}
function underscoreToCamelCase(str) {
    return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase().replace(/_([a-z])/g, (g)=>g[1].toUpperCase());
}
function getOption(flags, name) {
    while(name[0] === "-"){
        name = name.slice(1);
    }
    for (const flag of flags){
        if (isOption(flag, name)) {
            return flag;
        }
    }
    return;
}
function didYouMeanOption(option, options) {
    const optionNames = options.map((option)=>[
            option.name,
            ...option.aliases ?? []
        ]).flat().map((option)=>getFlag(option));
    return didYouMean(" Did you mean option", getFlag(option), optionNames);
}
function didYouMeanType(type, types) {
    return didYouMean(" Did you mean type", type, types);
}
function didYouMean(message, type, types) {
    const match = closest(type, types);
    return match ? `${message} "${match}"?` : "";
}
function getFlag(name) {
    if (name.startsWith("-")) {
        return name;
    }
    if (name.length > 1) {
        return `--${name}`;
    }
    return `-${name}`;
}
function isOption(option, name) {
    return option.name === name || option.aliases && option.aliases.indexOf(name) !== -1;
}
function matchWildCardOptions(name, flags) {
    for (const option of flags){
        if (option.name.indexOf("*") === -1) {
            continue;
        }
        let matched = matchWildCardOption(name, option);
        if (matched) {
            matched = {
                ...matched,
                name
            };
            flags.push(matched);
            return matched;
        }
    }
}
function matchWildCardOption(name, option) {
    const parts = option.name.split(".");
    const parts2 = name.split(".");
    if (parts.length !== parts2.length) {
        return false;
    }
    const count = Math.max(parts.length, parts2.length);
    for(let i1 = 0; i1 < count; i1++){
        if (parts[i1] !== parts2[i1] && parts[i1] !== "*") {
            return false;
        }
    }
    return option;
}
function closest(str, arr) {
    let minDistance = Infinity;
    let minIndex = 0;
    for(let i1 = 0; i1 < arr.length; i1++){
        const dist = distance(str, arr[i1]);
        if (dist < minDistance) {
            minDistance = dist;
            minIndex = i1;
        }
    }
    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 UnknownRequiredOptionError extends FlagsError {
    constructor(option, options){
        super(`Unknown required option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, UnknownRequiredOptionError.prototype);
    }
}
class UnknownConflictingOptionError extends FlagsError {
    constructor(option, options){
        super(`Unknown conflicting option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, UnknownConflictingOptionError.prototype);
    }
}
class UnknownTypeError extends FlagsError {
    constructor(type, types){
        super(`Unknown type "${type}".${didYouMeanType(type, types)}`);
        Object.setPrototypeOf(this, UnknownTypeError.prototype);
    }
}
class ValidationError extends FlagsError {
    constructor(message){
        super(message);
        Object.setPrototypeOf(this, ValidationError.prototype);
    }
}
class DuplicateOptionError extends ValidationError {
    constructor(name){
        super(`Option "${getFlag(name).replace(/^--no-/, "--")}" can only occur once, but was found several times.`);
        Object.setPrototypeOf(this, DuplicateOptionError.prototype);
    }
}
class InvalidOptionError extends ValidationError {
    constructor(option, options){
        super(`Invalid option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, InvalidOptionError.prototype);
    }
}
class UnknownOptionError extends ValidationError {
    constructor(option, options){
        super(`Unknown option "${getFlag(option)}".${didYouMeanOption(option, options)}`);
        Object.setPrototypeOf(this, UnknownOptionError.prototype);
    }
}
class MissingOptionValueError extends ValidationError {
    constructor(option){
        super(`Missing value for option "${getFlag(option)}".`);
        Object.setPrototypeOf(this, MissingOptionValueError.prototype);
    }
}
class InvalidOptionValueError extends ValidationError {
    constructor(option, expected, value){
        super(`Option "${getFlag(option)}" must be of type "${expected}", but got "${value}".`);
        Object.setPrototypeOf(this, InvalidOptionValueError.prototype);
    }
}
class UnexpectedOptionValueError extends ValidationError {
    constructor(option, value){
        super(`Option "${getFlag(option)}" doesn't take a value, but got "${value}".`);
        Object.setPrototypeOf(this, InvalidOptionValueError.prototype);
    }
}
class OptionNotCombinableError extends ValidationError {
    constructor(option){
        super(`Option "${getFlag(option)}" cannot be combined with other options.`);
        Object.setPrototypeOf(this, OptionNotCombinableError.prototype);
    }
}
class ConflictingOptionError extends ValidationError {
    constructor(option, conflictingOption){
        super(`Option "${getFlag(option)}" conflicts with option "${getFlag(conflictingOption)}".`);
        Object.setPrototypeOf(this, ConflictingOptionError.prototype);
    }
}
class DependingOptionError extends ValidationError {
    constructor(option, dependingOption){
        super(`Option "${getFlag(option)}" depends on option "${getFlag(dependingOption)}".`);
        Object.setPrototypeOf(this, DependingOptionError.prototype);
    }
}
class MissingRequiredOptionError extends ValidationError {
    constructor(option){
        super(`Missing required option "${getFlag(option)}".`);
        Object.setPrototypeOf(this, MissingRequiredOptionError.prototype);
    }
}
class UnexpectedRequiredArgumentError extends ValidationError {
    constructor(arg){
        super(`An required argument cannot follow an optional argument, but "${arg}"  is defined as required.`);
        Object.setPrototypeOf(this, UnexpectedRequiredArgumentError.prototype);
    }
}
class UnexpectedArgumentAfterVariadicArgumentError extends ValidationError {
    constructor(arg){
        super(`An argument cannot follow an variadic argument, but got "${arg}".`);
        Object.setPrototypeOf(this, UnexpectedArgumentAfterVariadicArgumentError.prototype);
    }
}
class InvalidTypeError extends ValidationError {
    constructor({ label, name, value, type }, expected){
        super(`${label} "${name}" must be of type "${type}", but got "${value}".` + (expected ? ` Expected values: ${expected.map((value)=>`"${value}"`).join(", ")}` : ""));
        Object.setPrototypeOf(this, MissingOptionValueError.prototype);
    }
}
var OptionType;
(function(OptionType) {
    OptionType["STRING"] = "string";
    OptionType["NUMBER"] = "number";
    OptionType["INTEGER"] = "integer";
    OptionType["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, [
        "true",
        "false",
        "1",
        "0"
    ]);
};
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(ctx, opts, options = new Map()) {
    if (!opts.flags) {
        return;
    }
    setDefaultValues(ctx, opts);
    const optionNames = Object.keys(ctx.flags);
    if (!optionNames.length && opts.allowEmpty) {
        return;
    }
    if (ctx.standalone) {
        validateStandaloneOption(ctx, options, optionNames);
        return;
    }
    for (const [name, option] of options){
        validateUnknownOption(option, opts);
        validateConflictingOptions(ctx, option);
        validateDependingOptions(ctx, option);
        validateRequiredValues(ctx, option, name);
    }
    validateRequiredOptions(ctx, options, opts);
}
function validateUnknownOption(option, opts) {
    if (!getOption(opts.flags ?? [], option.name)) {
        throw new UnknownOptionError(option.name, opts.flags ?? []);
    }
}
function setDefaultValues(ctx, opts) {
    if (!opts.flags?.length) {
        return;
    }
    for (const option of opts.flags){
        let name;
        let defaultValue = undefined;
        if (option.name.startsWith("no-")) {
            const propName = option.name.replace(/^no-/, "");
            if (typeof ctx.flags[propName] !== "undefined") {
                continue;
            }
            const positiveOption = getOption(opts.flags, propName);
            if (positiveOption) {
                continue;
            }
            name = paramCaseToCamelCase(propName);
            defaultValue = true;
        }
        if (!name) {
            name = paramCaseToCamelCase(option.name);
        }
        const hasDefaultValue = (!opts.ignoreDefaults || typeof opts.ignoreDefaults[name] === "undefined") && typeof ctx.flags[name] === "undefined" && (typeof option.default !== "undefined" || typeof defaultValue !== "undefined");
        if (hasDefaultValue) {
            ctx.flags[name] = getDefaultValue(option) ?? defaultValue;
            ctx.defaults[option.name] = true;
            if (typeof option.value === "function") {
                ctx.flags[name] = option.value(ctx.flags[name]);
            }
        }
    }
}
function validateStandaloneOption(ctx, options, optionNames) {
    if (!ctx.standalone || optionNames.length === 1) {
        return;
    }
    for (const [_, opt] of options){
        if (!ctx.defaults[opt.name] && opt !== ctx.standalone) {
            throw new OptionNotCombinableError(ctx.standalone.name);
        }
    }
}
function validateConflictingOptions(ctx, option) {
    if (!option.conflicts?.length) {
        return;
    }
    for (const flag of option.conflicts){
        if (isset(flag, ctx.flags)) {
            throw new ConflictingOptionError(option.name, flag);
        }
    }
}
function validateDependingOptions(ctx, option) {
    if (!option.depends) {
        return;
    }
    for (const flag of option.depends){
        if (!isset(flag, ctx.flags) && !ctx.defaults[option.name]) {
            throw new DependingOptionError(option.name, flag);
        }
    }
}
function validateRequiredValues(ctx, option, name) {
    if (!option.args) {
        return;
    }
    const isArray = option.args.length > 1;
    for(let i1 = 0; i1 < option.args.length; i1++){
        const arg = option.args[i1];
        if (arg.optional) {
            continue;
        }
        const hasValue = isArray ? typeof ctx.flags[name][i1] !== "undefined" : typeof ctx.flags[name] !== "undefined";
        if (!hasValue) {
            throw new MissingOptionValueError(option.name);
        }
    }
}
function validateRequiredOptions(ctx, options, opts) {
    if (!opts.flags?.length) {
        return;
    }
    const optionsValues = [
        ...options.values()
    ];
    for (const option of opts.flags){
        if (!option.required || paramCaseToCamelCase(option.name) in ctx.flags) {
            continue;
        }
        const conflicts = option.conflicts ?? [];
        const hasConflict = conflicts.find((flag)=>!!ctx.flags[flag]);
        const hasConflicts = hasConflict || optionsValues.find((opt)=>opt.conflicts?.find((flag)=>flag === option.name));
        if (hasConflicts) {
            continue;
        }
        throw new MissingRequiredOptionError(option.name);
    }
}
function isset(flagName, flags) {
    const name = paramCaseToCamelCase(flagName);
    return typeof flags[name] !== "undefined";
}
const integer = (type)=>{
    const value = Number(type.value);
    if (Number.isInteger(value)) {
        return value;
    }
    throw new InvalidTypeError(type);
};
const DefaultTypes = {
    string,
    number,
    integer,
    boolean: __boolean
};
function parseFlags(argsOrCtx, opts = {}) {
    let args;
    let ctx;
    if (Array.isArray(argsOrCtx)) {
        ctx = {};
        args = argsOrCtx;
    } else {
        ctx = argsOrCtx;
        args = argsOrCtx.unknown;
        argsOrCtx.unknown = [];
    }
    args = args.slice();
    ctx.flags ??= {};
    ctx.literal ??= [];
    ctx.unknown ??= [];
    ctx.stopEarly = false;
    ctx.stopOnUnknown = false;
    ctx.defaults ??= {};
    opts.dotted ??= true;
    validateOptions(opts);
    const options = parseArgs(ctx, args, opts);
    validateFlags(ctx, opts, options);
    if (opts.dotted) {
        parseDottedOptions(ctx);
    }
    return ctx;
}
function validateOptions(opts) {
    opts.flags?.forEach((opt)=>{
        opt.depends?.forEach((flag)=>{
            if (!opts.flags || !getOption(opts.flags, flag)) {
                throw new UnknownRequiredOptionError(flag, opts.flags ?? []);
            }
        });
        opt.conflicts?.forEach((flag)=>{
            if (!opts.flags || !getOption(opts.flags, flag)) {
                throw new UnknownConflictingOptionError(flag, opts.flags ?? []);
            }
        });
    });
}
function parseArgs(ctx, args, opts) {
    const optionsMap = new Map();
    let inLiteral = false;
    for(let argsIndex = 0; argsIndex < args.length; argsIndex++){
        let option;
        let current = args[argsIndex];
        let currentValue;
        let negate = false;
        if (inLiteral) {
            ctx.literal.push(current);
            continue;
        } else if (current === "--") {
            inLiteral = true;
            continue;
        } else if (ctx.stopEarly || ctx.stopOnUnknown) {
            ctx.unknown.push(current);
            continue;
        }
        const isFlag = current.length > 1 && current[0] === "-";
        if (!isFlag) {
            if (opts.stopEarly) {
                ctx.stopEarly = true;
            }
            ctx.unknown.push(current);
            continue;
        }
        const isShort = current[1] !== "-";
        const isLong = isShort ? false : current.length > 3 && current[2] !== "-";
        if (!isShort && !isLong) {
            throw new InvalidOptionError(current, opts.flags ?? []);
        }
        if (isShort && current.length > 2 && current[2] !== ".") {
            args.splice(argsIndex, 1, ...splitFlags(current));
            current = args[argsIndex];
        } else if (isLong && current.startsWith("--no-")) {
            negate = true;
        }
        const equalSignIndex = current.indexOf("=");
        if (equalSignIndex !== -1) {
            currentValue = current.slice(equalSignIndex + 1) || undefined;
            current = current.slice(0, equalSignIndex);
        }
        if (opts.flags) {
            option = getOption(opts.flags, current);
            if (!option) {
                const name = current.replace(/^-+/, "");
                option = matchWildCardOptions(name, opts.flags);
                if (!option) {
                    if (opts.stopOnUnknown) {
                        ctx.stopOnUnknown = true;
                        ctx.unknown.push(args[argsIndex]);
                        continue;
                    }
                    throw new UnknownOptionError(current, opts.flags);
                }
            }
        } else {
            option = {
                name: current.replace(/^-+/, ""),
                optionalValue: true,
                type: OptionType.STRING
            };
        }
        if (option.standalone) {
            ctx.standalone = option;
        }
        const positiveName = negate ? option.name.replace(/^no-?/, "") : option.name;
        const propName = paramCaseToCamelCase(positiveName);
        if (typeof ctx.flags[propName] !== "undefined") {
            if (!opts.flags?.length) {
                option.collect = true;
            } else if (!option.collect && !ctx.defaults[option.name]) {
                throw new DuplicateOptionError(current);
            }
        }
        if (option.type && !option.args?.length) {
            option.args = [
                {
                    type: option.type,
                    optional: option.optionalValue,
                    variadic: option.variadic,
                    list: option.list,
                    separator: option.separator
                }
            ];
        }
        if (opts.flags?.length && !option.args?.length && typeof currentValue !== "undefined") {
            throw new UnexpectedOptionValueError(option.name, currentValue);
        }
        let optionArgsIndex = 0;
        let inOptionalArg = false;
        const next = ()=>currentValue ?? args[argsIndex + 1];
        const previous = ctx.flags[propName];
        parseNext(option);
        if (typeof ctx.flags[propName] === "undefined") {
            if (option.args?.length && !option.args?.[optionArgsIndex].optional) {
                throw new MissingOptionValueError(option.name);
            } else if (typeof option.default !== "undefined" && (option.type || option.value || option.args?.length)) {
                ctx.flags[propName] = getDefaultValue(option);
            } else {
                setFlagValue(true);
            }
        }
        if (option.value) {
            const value = option.value(ctx.flags[propName], previous);
            setFlagValue(value);
        } else if (option.collect) {
            const value = typeof previous !== "undefined" ? Array.isArray(previous) ? previous : [
                previous
            ] : [];
            value.push(ctx.flags[propName]);
            setFlagValue(value);
        }
        optionsMap.set(propName, option);
        opts.option?.(option, ctx.flags[propName]);
        function parseNext(option) {
            if (negate) {
                setFlagValue(false);
                return;
            } else if (!option.args?.length) {
                setFlagValue(undefined);
                return;
            }
            const arg = option.args[optionArgsIndex];
            if (!arg) {
                const flag = next();
                throw new UnknownOptionError(flag, opts.flags ?? []);
            }
            if (!arg.type) {
                arg.type = OptionType.BOOLEAN;
            }
            if (!option.args?.length && arg.type === OptionType.BOOLEAN && arg.optional === undefined) {
                arg.optional = true;
            }
            if (arg.optional) {
                inOptionalArg = true;
            } else if (inOptionalArg) {
                throw new UnexpectedRequiredArgumentError(option.name);
            }
            let result1;
            let increase = false;
            if (arg.list && hasNext(arg)) {
                const parsed = next().split(arg.separator || ",").map((nextValue)=>{
                    const value = parseValue(option, arg, nextValue);
                    if (typeof value === "undefined") {
                        throw new InvalidOptionValueError(option.name, arg.type ?? "?", nextValue);
                    }
                    return value;
                });
                if (parsed?.length) {
                    result1 = parsed;
                }
            } else {
                if (hasNext(arg)) {
                    result1 = parseValue(option, arg, next());
                } else if (arg.optional && arg.type === OptionType.BOOLEAN) {
                    result1 = true;
                }
            }
            if (increase && typeof currentValue === "undefined") {
                argsIndex++;
                if (!arg.variadic) {
                    optionArgsIndex++;
                } else if (option.args[optionArgsIndex + 1]) {
                    throw new UnexpectedArgumentAfterVariadicArgumentError(next());
                }
            }
            if (typeof result1 !== "undefined" && (option.args.length > 1 || arg.variadic)) {
                if (!ctx.flags[propName]) {
                    setFlagValue([]);
                }
                ctx.flags[propName].push(result1);
                if (hasNext(arg)) {
                    parseNext(option);
                }
            } else {
                setFlagValue(result1);
            }
            function hasNext(arg) {
                if (!option.args?.length) {
                    return false;
                }
                const nextValue = currentValue ?? args[argsIndex + 1];
                if (!nextValue) {
                    return false;
                }
                if (option.args.length > 1 && optionArgsIndex >= option.args.length) {
                    return false;
                }
                if (!arg.optional) {
                    return true;
                }
                if (option.equalsSign && arg.optional && !arg.variadic && typeof currentValue === "undefined") {
                    return false;
                }
                if (arg.optional || arg.variadic) {
                    return nextValue[0] !== "-" || typeof currentValue !== "undefined" || arg.type === OptionType.NUMBER && !isNaN(Number(nextValue));
                }
                return false;
            }
            function parseValue(option, arg, value) {
                const result1 = opts.parse ? opts.parse({
                    label: "Option",
                    type: arg.type || OptionType.STRING,
                    name: `--${option.name}`,
                    value
                }) : parseDefaultType(option, arg, value);
                if (typeof result1 !== "undefined") {
                    increase = true;
                }
                return result1;
            }
        }
        function setFlagValue(value) {
            ctx.flags[propName] = value;
            if (ctx.defaults[propName]) {
                delete ctx.defaults[propName];
            }
        }
    }
    return optionsMap;
}
function parseDottedOptions(ctx) {
    ctx.flags = Object.keys(ctx.flags).reduce((result1, key)=>{
        if (~key.indexOf(".")) {
            key.split(".").reduce((result1, subKey, index, parts)=>{
                if (index === parts.length - 1) {
                    result1[subKey] = ctx.flags[key];
                } else {
                    result1[subKey] = result1[subKey] ?? {};
                }
                return result1[subKey];
            }, result1);
        } else {
            result1[key] = ctx.flags[key];
        }
        return result1;
    }, {});
}
function splitFlags(flag) {
    flag = flag.slice(1);
    const normalized = [];
    const index = flag.indexOf("=");
    const flags = (index !== -1 ? flag.slice(0, index) : flag).split("");
    if (isNaN(Number(flag[flag.length - 1]))) {
        flags.forEach((val)=>normalized.push(`-${val}`));
    } else {
        normalized.push(`-${flags.shift()}`);
        if (flags.length) {
            normalized.push(flags.join(""));
        }
    }
    if (index !== -1) {
        normalized[normalized.length - 1] += flag.slice(index);
    }
    return normalized;
}
function parseDefaultType(option, arg, value) {
    const type = arg.type || OptionType.STRING;
    const parseType = DefaultTypes[type];
    if (!parseType) {
        throw new UnknownTypeError(type, Object.keys(DefaultTypes));
    }
    return parseType({
        label: "Option",
        type,
        name: `--${option.name}`,
        value
    });
}
function didYouMeanCommand(command, commands, excludes = []) {
    const commandNames = commands.map((command)=>command.getName()).filter((command)=>!excludes.includes(command));
    return didYouMean(" Did you mean command", command, commandNames);
}
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,
        equalsSign: args.includes("=")
    };
}
function parseArgumentsDefinition(argsDefinition, validate = true, all) {
    const argumentDetails = [];
    let hasOptional = false;
    let hasVariadic = false;
    const parts = argsDefinition.split(/ +/);
    for (const arg of parts){
        if (validate && hasVariadic) {
            throw new UnexpectedArgumentAfterVariadicArgumentError(arg);
        }
        const parts = arg.split(ARGUMENT_DETAILS_REGEX);
        if (!parts[1]) {
            if (all) {
                argumentDetails.push(parts[0]);
            }
            continue;
        }
        const type = parts[2] || OptionType.STRING;
        const details = {
            optional: arg[0] === "[",
            name: parts[1],
            action: parts[3] || type,
            variadic: false,
            list: type ? arg.indexOf(type + "[]") !== -1 : false,
            type
        };
        if (validate && !details.optional && hasOptional) {
            throw new UnexpectedRequiredArgumentError(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);
            }
        }
        argumentDetails.push(details);
    }
    return argumentDetails;
}
function dedent(str) {
    const lines = str.split(/\r?\n|\r/g);
    let text = "";
    let indent = 0;
    for (const line of lines){
        if (text || line.trim()) {
            if (!text) {
                text = line.trimStart();
                indent = line.length - text.length;
            } else {
                text += line.slice(indent);
            }
            text += "\n";
        }
    }
    return text.trimEnd();
}
function getDescription(description, __short) {
    return __short ? description.trim().split("\n", 1)[0].trim() : dedent(description);
}
class CommandError extends Error {
    constructor(message){
        super(message);
        Object.setPrototypeOf(this, CommandError.prototype);
    }
}
class ValidationError1 extends CommandError {
    exitCode;
    cmd;
    constructor(message, { exitCode } = {}){
        super(message);
        Object.setPrototypeOf(this, ValidationError1.prototype);
        this.exitCode = exitCode ?? 2;
    }
}
class DuplicateOptionNameError extends CommandError {
    constructor(optionName, commandName){
        super(`An option with name '${bold1(getFlag(optionName))}' is already registered on command '${bold1(commandName)}'. If it is intended to override the option, set the '${bold1("override")}' option of the '${bold1("option")}' method to true.`);
        Object.setPrototypeOf(this, DuplicateOptionNameError.prototype);
    }
}
class MissingCommandNameCompletionsError extends CommandError {
    constructor(shell){
        super(`Failed to generate shell completions. Missing main command name. Use '${bold1('cmd.name("<comand-name>")')}' to set the name of the main command or use the '${bold1("--name")}' option from the '${bold1("completions")}' command to set the cli name: '${bold1(`<command> completions ${shell} --name <cli-name>`)}'.`);
        Object.setPrototypeOf(this, MissingCommandNameCompletionsError.prototype);
    }
}
class MissingCommandNameError extends CommandError {
    constructor(){
        super("Missing command name.");
        Object.setPrototypeOf(this, MissingCommandNameError.prototype);
    }
}
class DuplicateCommandNameError extends CommandError {
    constructor(name){
        super(`Duplicate command name "${name}".`);
        Object.setPrototypeOf(this, DuplicateCommandNameError.prototype);
    }
}
class DuplicateCommandAliasError extends CommandError {
    constructor(alias){
        super(`Duplicate command alias "${alias}".`);
        Object.setPrototypeOf(this, DuplicateCommandAliasError.prototype);
    }
}
class CommandNotFoundError extends CommandError {
    constructor(name, commands, excluded){
        super(`Unknown command "${name}".${didYouMeanCommand(name, commands, excluded)}`);
        Object.setPrototypeOf(this, CommandNotFoundError.prototype);
    }
}
class DuplicateTypeError extends CommandError {
    constructor(name){
        super(`Type with name "${name}" already exists.`);
        Object.setPrototypeOf(this, DuplicateTypeError.prototype);
    }
}
class DuplicateCompletionError extends CommandError {
    constructor(name){
        super(`Completion with name "${name}" already exists.`);
        Object.setPrototypeOf(this, DuplicateCompletionError.prototype);
    }
}
class DuplicateExampleError extends CommandError {
    constructor(name){
        super(`Example with name "${name}" already exists.`);
        Object.setPrototypeOf(this, DuplicateExampleError.prototype);
    }
}
class DuplicateEnvVarError extends CommandError {
    constructor(name){
        super(`Environment variable with name "${name}" already exists.`);
        Object.setPrototypeOf(this, DuplicateEnvVarError.prototype);
    }
}
class MissingRequiredEnvVarError extends ValidationError1 {
    constructor(envVar){
        super(`Missing required environment variable "${envVar.names[0]}".`);
        Object.setPrototypeOf(this, MissingRequiredEnvVarError.prototype);
    }
}
class TooManyEnvVarValuesError extends CommandError {
    constructor(name){
        super(`An environment variable can only have one value, but "${name}" has more than one.`);
        Object.setPrototypeOf(this, TooManyEnvVarValuesError.prototype);
    }
}
class UnexpectedOptionalEnvVarValueError extends CommandError {
    constructor(name){
        super(`An environment variable cannot have an optional value, but "${name}" is defined as optional.`);
        Object.setPrototypeOf(this, UnexpectedOptionalEnvVarValueError.prototype);
    }
}
class UnexpectedVariadicEnvVarValueError extends CommandError {
    constructor(name){
        super(`An environment variable cannot have an variadic value, but "${name}" is defined as variadic.`);
        Object.setPrototypeOf(this, UnexpectedVariadicEnvVarValueError.prototype);
    }
}
class DefaultCommandNotFoundError extends CommandError {
    constructor(name, commands){
        super(`Default command "${name}" not found.${didYouMeanCommand(name, commands)}`);
        Object.setPrototypeOf(this, DefaultCommandNotFoundError.prototype);
    }
}
class CommandExecutableNotFoundError extends CommandError {
    constructor(name){
        super(`Command executable not found: ${name}`);
        Object.setPrototypeOf(this, CommandExecutableNotFoundError.prototype);
    }
}
class UnknownCompletionCommandError extends CommandError {
    constructor(name, commands){
        super(`Auto-completion failed. Unknown command "${name}".${didYouMeanCommand(name, commands)}`);
        Object.setPrototypeOf(this, UnknownCompletionCommandError.prototype);
    }
}
class UnknownCommandError extends ValidationError1 {
    constructor(name, commands, excluded){
        super(`Unknown command "${name}".${didYouMeanCommand(name, commands, excluded)}`);
        Object.setPrototypeOf(this, UnknownCommandError.prototype);
    }
}
class NoArgumentsAllowedError extends ValidationError1 {
    constructor(name){
        super(`No arguments allowed for command "${name}".`);
        Object.setPrototypeOf(this, NoArgumentsAllowedError.prototype);
    }
}
class MissingArgumentsError extends ValidationError1 {
    constructor(names){
        super(`Missing argument(s): ${names.join(", ")}`);
        Object.setPrototypeOf(this, MissingArgumentsError.prototype);
    }
}
class MissingArgumentError extends ValidationError1 {
    constructor(name){
        super(`Missing argument: ${name}`);
        Object.setPrototypeOf(this, MissingArgumentError.prototype);
    }
}
class TooManyArgumentsError extends ValidationError1 {
    constructor(args){
        super(`Too many arguments: ${args.join(" ")}`);
        Object.setPrototypeOf(this, TooManyArgumentsError.prototype);
    }
}
class Type {
}
class BooleanType extends Type {
    parse(type) {
        return __boolean(type);
    }
    complete() {
        return [
            "true",
            "false"
        ];
    }
}
class StringType extends Type {
    parse(type) {
        return string(type);
    }
}
class FileType extends StringType {
    constructor(){
        super();
    }
}
class IntegerType extends Type {
    parse(type) {
        return integer(type);
    }
}
class NumberType extends Type {
    parse(type) {
        return number(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) {
        let cell;
        if (value instanceof Cell) {
            cell = new this(value.getValue());
            cell.options = {
                ...value.options
            };
        } else {
            cell = new this(value);
        }
        return cell;
    }
    constructor(value){
        this.value = value;
        this.options = {};
    }
    toString() {
        return this.value.toString();
    }
    getValue() {
        return this.value;
    }
    setValue(value) {
        this.value = value;
        return this;
    }
    clone(value) {
        return Cell.from(value ?? this);
    }
    border(enable = true, 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 Column {
    static from(options) {
        const opts = options instanceof Column ? options.opts : options;
        return new Column().options(opts);
    }
    opts = {};
    options(options) {
        Object.assign(this.opts, options);
        return this;
    }
    minWidth(width) {
        this.opts.minWidth = width;
        return this;
    }
    maxWidth(width) {
        this.opts.maxWidth = width;
        return this;
    }
    border(border = true) {
        this.opts.border = border;
        return this;
    }
    padding(padding) {
        this.opts.padding = padding;
        return this;
    }
    align(direction) {
        this.opts.align = direction;
        return this;
    }
    getMinWidth() {
        return this.opts.minWidth;
    }
    getMaxWidth() {
        return this.opts.maxWidth;
    }
    getBorder() {
        return this.opts.border;
    }
    getPadding() {
        return this.opts.padding;
    }
    getAlign() {
        return this.opts.align;
    }
}
const __default = JSON.parse("{\n  \"UNICODE_VERSION\": \"15.0.0\",\n  \"tables\": [\n    {\n      \"d\": \"AAECAwQFBgcICQoLDA0OAw8DDwkQCRESERIA\",\n      \"r\": \"AQEBAgEBAQEBAQEBAQEBBwEHAVABBwcBBwF4\"\n    },\n    {\n      \"d\": \"AAECAwQFBgcGCAYJCgsMDQ4PEAYREhM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BAwEEAQIBAQEBBAEBAQEBAQECAQEBAQEBAQEBAQEHAQQBAwEBAQcBAgUBBgECAQYBAQwBAQEUAQELCAYBFgMFAQYDAQoBAQMBARQBAQkBAQoBBgEVAwsBCgIPAQ0BGQEBAgEHARQBAwIBBgEBAQUBBgQBAgEJAQEBBQECAQMHAQELAQECCQEQAQECAgECAQsBDAEBAQEBCgEBAQsBAQEECQ4BCAQCAQEECAEEAQEFCAEPAQEEAQEPAQgBFAEBAQEBAQEKAQEJAQ8BEAEBEwEBAQIBCwEBDgENAwEKAQEBAQELAQEBAQECAQwBCAEBAQEBDgEDAQwBAQECAQEXAQEBAQEHAgEBBQEIAQEBAQEQAgEBBQEUAQEBAQEbAQEBAQEGARQBAQEBARkBAQEBCQEBAQEQAQIBDwEBARQBAQEBBwEBAQkBAQEBAQECAQEBCwECAQEVAQEBAQQBBQEBAQEOAQEBAQEBEgEBFgEBAgEMAQEBAQ8BAQMBFgEBDgEBBQEPAQETAQECAQMOAgUBCgIBGQEBAQEIAQMBBwEBAwECEwgBAQcLAQUBFwEBAQEDAQEBBwEBBAEBDg0BAQwBAQEDAQQBAQEDBAEBBAEBAQEBEAEPAQgBAQsBAQ4BEQEMAgEBBwEOAQEHAQEBAQQBBAEDCwECAQEBAwEBBggBAgEBAREBBQMKAQEBAwQCEQEBHgEPAQIBAQYEAQYBAwEUAQUMAQEBAQEBAQECAQEBAgEIAwEBBgsBAgEODAMBAgEBCwEBAQEBAwECAQECAQEBBwgPAQ==\"\n    }\n  ]\n}");
class AssertionError1 extends Error {
    name = "AssertionError";
    constructor(message){
        super(message);
    }
}
function assert1(expr, msg = "") {
    if (!expr) {
        throw new AssertionError1(msg);
    }
}
function runLengthDecode({ d, r }) {
    const data = atob(d);
    const runLengths = atob(r);
    let out = "";
    for (const [i1, ch] of [
        ...runLengths
    ].entries()){
        out += data[i1].repeat(ch.codePointAt(0));
    }
    return Uint8Array.from([
        ...out
    ].map((x)=>x.codePointAt(0)));
}
let tables = null;
function lookupWidth(cp) {
    if (!tables) tables = __default.tables.map(runLengthDecode);
    const t1Offset = tables[0][cp >> 13 & 0xff];
    const t2Offset = tables[1][128 * t1Offset + (cp >> 6 & 0x7f)];
    const packedWidths = tables[2][16 * t2Offset + (cp >> 2 & 0xf)];
    const width = packedWidths >> 2 * (cp & 0b11) & 0b11;
    return width === 3 ? 1 : width;
}
const cache = new Map();
function charWidth(ch) {
    if (cache.has(ch)) return cache.get(ch);
    const cp = ch.codePointAt(0);
    let v = null;
    if (cp < 0x7f) {
        v = cp >= 0x20 ? 1 : cp === 0 ? 0 : null;
    } else if (cp >= 0xa0) {
        v = lookupWidth(cp);
    } else {
        v = null;
    }
    cache.set(ch, v);
    return v;
}
function unicodeWidth(str) {
    return [
        ...str
    ].map((ch)=>charWidth(ch) ?? 0).reduce((a, b)=>a + b, 0);
}
const strLength = (str)=>{
    return unicodeWidth(stripColor1(str));
};
function consumeWords(length, content) {
    let consumed = "";
    const words = content.split("\n")[0]?.split(/ /g);
    for(let i1 = 0; i1 < words.length; i1++){
        const word = words[i1];
        if (consumed) {
            const nextLength = strLength(word);
            const consumedLength = strLength(consumed);
            if (consumedLength + nextLength >= length) {
                break;
            }
        }
        consumed += (i1 > 0 ? " " : "") + word;
    }
    return consumed;
}
function longest(index, rows, maxWidth) {
    const cellLengths = rows.map((row)=>{
        const cell = row[index];
        const cellValue = cell instanceof Cell && cell.getColSpan() > 1 ? "" : cell?.toString() || "";
        return cellValue.split("\n").map((line)=>{
            const str = typeof maxWidth === "undefined" ? line : consumeWords(maxWidth, line);
            return strLength(str) || 0;
        });
    }).flat();
    return Math.max(...cellLengths);
}
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 = true, 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";
    }
}
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 rows = this.#getRows();
        const columns = Math.max(...rows.map((row)=>row.length));
        for(let rowIndex = 0; rowIndex < rows.length; rowIndex++){
            const row = rows[rowIndex];
            const length = row.length;
            if (length < columns) {
                const diff = columns - length;
                for(let i1 = 0; i1 < diff; i1++){
                    row.push(this.createCell(null, row, rowIndex, length + i1));
                }
            }
        }
        const padding = [];
        const width = [];
        for(let colIndex = 0; colIndex < columns; colIndex++){
            const column = this.options.columns.at(colIndex);
            const minColWidth = column?.getMinWidth() ?? (Array.isArray(this.options.minColWidth) ? this.options.minColWidth[colIndex] : this.options.minColWidth);
            const maxColWidth = column?.getMaxWidth() ?? (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] = column?.getPadding() ?? (Array.isArray(this.options.padding) ? this.options.padding[colIndex] : this.options.padding);
        }
        return {
            padding,
            width,
            rows,
            columns,
            hasBorder,
            hasBodyBorder,
            hasHeaderBorder
        };
    }
    #getRows() {
        const header = this.table.getHeader();
        const rows = header ? [
            header,
            ...this.table
        ] : this.table.slice();
        const hasSpan = rows.some((row)=>row.some((cell)=>cell instanceof Cell && (cell.getColSpan() > 1 || cell.getRowSpan() > 1)));
        if (hasSpan) {
            return this.spanRows(rows);
        }
        return rows.map((row, rowIndex)=>{
            const newRow = this.createRow(row);
            for(let colIndex = 0; colIndex < row.length; colIndex++){
                newRow[colIndex] = this.createCell(row[colIndex], newRow, rowIndex, colIndex);
            }
            return newRow;
        });
    }
    spanRows(rows) {
        const rowSpan = [];
        let colSpan = 1;
        let rowIndex = -1;
        while(true){
            rowIndex++;
            if (rowIndex === rows.length && rowSpan.every((span)=>span === 1)) {
                break;
            }
            const row = rows[rowIndex] = this.createRow(rows[rowIndex] || []);
            let colIndex = -1;
            while(true){
                colIndex++;
                if (colIndex === row.length && colIndex === rowSpan.length && colSpan === 1) {
                    break;
                }
                if (colSpan > 1) {
                    colSpan--;
                    rowSpan[colIndex] = rowSpan[colIndex - 1];
                    row.splice(colIndex, this.getDeleteCount(rows, rowIndex, colIndex), row[colIndex - 1]);
                    continue;
                }
                if (rowSpan[colIndex] > 1) {
                    rowSpan[colIndex]--;
                    rows[rowIndex].splice(colIndex, this.getDeleteCount(rows, rowIndex, colIndex), rows[rowIndex - 1][colIndex]);
                    continue;
                }
                const cell = row[colIndex] = this.createCell(row[colIndex] || null, row, rowIndex, colIndex);
                colSpan = cell.getColSpan();
                rowSpan[colIndex] = cell.getRowSpan();
            }
        }
        return rows;
    }
    getDeleteCount(rows, rowIndex, colIndex) {
        return colIndex <= rows[rowIndex].length - 1 && typeof rows[rowIndex][colIndex] === "undefined" ? 1 : 0;
    }
    createRow(row) {
        return Row.from(row).border(this.table.getBorder(), false).align(this.table.getAlign(), false);
    }
    createCell(cell, row, rowIndex, colIndex) {
        const column = this.options.columns.at(colIndex);
        const isHeaderRow = this.isHeaderRow(rowIndex);
        return Cell.from(cell ?? "").border((isHeaderRow ? null : column?.getBorder()) ?? row.getBorder(), false).align((isHeaderRow ? null : column?.getAlign()) ?? row.getAlign(), false);
    }
    isHeaderRow(rowIndex) {
        return rowIndex === 0 && this.table.getHeader() !== undefined;
    }
    renderRows(opts) {
        let result1 = "";
        const rowSpan = new Array(opts.columns).fill(1);
        for(let rowIndex = 0; rowIndex < opts.rows.length; rowIndex++){
            result1 += this.renderRow(rowSpan, rowIndex, opts);
        }
        return result1.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 result1 = "";
        let colSpan = 1;
        if (!isMultiline && rowIndex === 0 && row.hasBorder()) {
            result1 += this.renderBorderRow(undefined, row, rowSpan, opts);
        }
        let isMultilineRow = false;
        result1 += " ".repeat(this.options.indent || 0);
        for(let colIndex = 0; colIndex < opts.columns; colIndex++){
            if (colSpan > 1) {
                colSpan--;
                rowSpan[colIndex] = rowSpan[colIndex - 1];
                continue;
            }
            result1 += 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()) {
                result1 += this.options.chars.right;
            } else if (opts.hasBorder) {
                result1 += " ";
            }
        }
        result1 += "\n";
        if (isMultilineRow) {
            return result1 + this.renderRow(rowSpan, rowIndex, opts, isMultilineRow);
        }
        if (opts.rows.length > 1 && (rowIndex === 0 && opts.hasHeaderBorder || rowIndex < opts.rows.length - 1 && opts.hasBodyBorder)) {
            result1 += this.renderBorderRow(row, nextRow, rowSpan, opts);
        }
        if (rowIndex === opts.rows.length - 1 && row.hasBorder()) {
            result1 += this.renderBorderRow(row, undefined, rowSpan, opts);
        }
        return result1;
    }
    renderCell(colIndex, row, opts, noBorder) {
        let result1 = "";
        const prevCell = row[colIndex - 1];
        const cell = row[colIndex];
        if (!noBorder) {
            if (colIndex === 0) {
                if (cell.getBorder()) {
                    result1 += this.options.chars.left;
                } else if (opts.hasBorder) {
                    result1 += " ";
                }
            } else {
                if (cell.getBorder() || prevCell?.getBorder()) {
                    result1 += this.options.chars.middle;
                } else if (opts.hasBorder) {
                    result1 += " ";
                }
            }
        }
        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.getValue());
        if (opts.hasBorder) {
            result1 += " ".repeat(opts.padding[colIndex]);
        }
        result1 += current;
        if (opts.hasBorder || colIndex < opts.columns - 1) {
            result1 += " ".repeat(opts.padding[colIndex]);
        }
        return result1;
    }
    renderCellValue(cell, maxLength) {
        const length = Math.min(maxLength, strLength(cell.toString()));
        let words = consumeWords(length, cell.toString());
        const breakWord = strLength(words) > length;
        if (breakWord) {
            words = words.slice(0, length);
        }
        const next = cell.toString().slice(words.length + (breakWord ? 0 : 1));
        const fillLength = maxLength - strLength(words);
        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 result1 = "";
        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;
                }
            }
            result1 += this.renderBorderCell(colIndex, prevRow, nextRow, rowSpan, opts);
            colSpan = nextRow?.[colIndex].getColSpan() ?? 1;
        }
        return result1.length ? " ".repeat(this.options.indent) + result1 + "\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 result1 = "";
        if (colIndex === 0) {
            if (rowSpan[colIndex] > 1) {
                if (b1Border) {
                    result1 += this.options.chars.left;
                } else {
                    result1 += " ";
                }
            } else if (b1Border && b2Border) {
                result1 += this.options.chars.leftMid;
            } else if (b1Border) {
                result1 += this.options.chars.bottomLeft;
            } else if (b2Border) {
                result1 += this.options.chars.topLeft;
            } else {
                result1 += " ";
            }
        } 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) {
                    result1 += this.options.chars.middle;
                } else if (hasAllColSpan && hasAllBorder && a1 === b1 && a2 === b2) {
                    result1 += this.options.chars.mid;
                } else if (a1ColSpan && b1ColSpan && a1 === b1) {
                    result1 += this.options.chars.topMid;
                } else if (a2ColSpan && b2ColSpan && a2 === b2) {
                    result1 += this.options.chars.bottomMid;
                } else if (a1RowSpan && a2RowSpan && a1 === a2) {
                    result1 += this.options.chars.leftMid;
                } else if (b1RowSpan && b2RowSpan && b1 === b2) {
                    result1 += this.options.chars.rightMid;
                } else {
                    result1 += this.options.chars.midMid;
                }
            } else if (a1Border && b1Border) {
                if (hasColSpan(a1) && hasColSpan(b1) && a1 === b1) {
                    result1 += this.options.chars.bottom;
                } else {
                    result1 += this.options.chars.bottomMid;
                }
            } else if (b1Border && b2Border) {
                if (rowSpan[colIndex] > 1) {
                    result1 += this.options.chars.left;
                } else {
                    result1 += this.options.chars.leftMid;
                }
            } else if (b2Border && a2Border) {
                if (hasColSpan(a2) && hasColSpan(b2) && a2 === b2) {
                    result1 += this.options.chars.top;
                } else {
                    result1 += this.options.chars.topMid;
                }
            } else if (a1Border && a2Border) {
                if (hasRowSpan(a1) && a1 === a2) {
                    result1 += this.options.chars.right;
                } else {
                    result1 += this.options.chars.rightMid;
                }
            } else if (a1Border) {
                result1 += this.options.chars.bottomRight;
            } else if (b1Border) {
                result1 += this.options.chars.bottomLeft;
            } else if (a2Border) {
                result1 += this.options.chars.topRight;
            } else if (b2Border) {
                result1 += this.options.chars.topLeft;
            } else {
                result1 += " ";
            }
        }
        const length = opts.padding[colIndex] + opts.width[colIndex] + opts.padding[colIndex];
        if (rowSpan[colIndex] > 1 && nextRow) {
            result1 += this.renderCell(colIndex, nextRow, opts, true);
            if (nextRow[colIndex] === nextRow[nextRow.length - 1]) {
                if (b1Border) {
                    result1 += this.options.chars.right;
                } else {
                    result1 += " ";
                }
                return result1;
            }
        } else if (b1Border && b2Border) {
            result1 += this.options.chars.mid.repeat(length);
        } else if (b1Border) {
            result1 += this.options.chars.bottom.repeat(length);
        } else if (b2Border) {
            result1 += this.options.chars.top.repeat(length);
        } else {
            result1 += " ".repeat(length);
        }
        if (colIndex === opts.columns - 1) {
            if (b1Border && b2Border) {
                result1 += this.options.chars.rightMid;
            } else if (b1Border) {
                result1 += this.options.chars.bottomRight;
            } else if (b2Border) {
                result1 += this.options.chars.topRight;
            } else {
                result1 += " ";
            }
        }
        return result1;
    }
}
class Table extends Array {
    static _chars = {
        ...border
    };
    options = {
        indent: 0,
        border: false,
        maxColWidth: Infinity,
        minColWidth: 0,
        padding: 1,
        chars: {
            ...Table._chars
        },
        columns: []
    };
    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;
    }
    columns(columns) {
        this.options.columns = columns.map((column)=>column instanceof Column ? column : Column.from(column));
        return this;
    }
    column(index, column) {
        if (column instanceof Column) {
            this.options.columns[index] = column;
        } else if (this.options.columns[index]) {
            this.options.columns[index].options(column);
        } else {
            this.options.columns[index] = Column.from(column);
        }
        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() {
        console.log(this.toString());
        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 = true, 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.options.columns.some((column)=>column.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";
    }
    getColumns() {
        return this.options.columns;
    }
    getColumn(index) {
        return this.options.columns[index] ??= new Column();
    }
}
class HelpGenerator {
    cmd;
    indent;
    options;
    static generate(cmd, options) {
        return new HelpGenerator(cmd, options).generate();
    }
    constructor(cmd, options = {}){
        this.cmd = cmd;
        this.indent = 2;
        this.options = {
            types: false,
            hints: true,
            colors: true,
            long: false,
            ...options
        };
    }
    generate() {
        const areColorsEnabled = getColorEnabled();
        setColorEnabled(this.options.colors);
        const result1 = this.generateHeader() + this.generateMeta() + this.generateDescription() + this.generateOptions() + this.generateCommands() + this.generateEnvironmentVariables() + this.generateExamples();
        setColorEnabled(areColorsEnabled);
        return result1;
    }
    generateHeader() {
        const usage = this.cmd.getUsage();
        const rows = [
            [
                bold1("Usage:"),
                brightMagenta(this.cmd.getPath() + (usage ? " " + highlightArguments(usage, this.options.types) : ""))
            ]
        ];
        const version = this.cmd.getVersion();
        if (version) {
            rows.push([
                bold1("Version:"),
                yellow1(`${this.cmd.getVersion()}`)
            ]);
        }
        return "\n" + Table.from(rows).padding(1).toString() + "\n";
    }
    generateMeta() {
        const meta = Object.entries(this.cmd.getMeta());
        if (!meta.length) {
            return "";
        }
        const rows = [];
        for (const [name, value] of meta){
            rows.push([
                bold1(`${name}: `) + value
            ]);
        }
        return "\n" + Table.from(rows).padding(1).toString() + "\n";
    }
    generateDescription() {
        if (!this.cmd.getDescription()) {
            return "";
        }
        return this.label("Description") + Table.from([
            [
                dedent(this.cmd.getDescription())
            ]
        ]).indent(this.indent).maxColWidth(140).padding(1).toString() + "\n";
    }
    generateOptions() {
        const options = this.cmd.getOptions(false);
        if (!options.length) {
            return "";
        }
        let groups = [];
        const hasGroups = options.some((option)=>option.groupName);
        if (hasGroups) {
            for (const option of options){
                let group = groups.find((group)=>group.name === option.groupName);
                if (!group) {
                    group = {
                        name: option.groupName,
                        options: []
                    };
                    groups.push(group);
                }
                group.options.push(option);
            }
        } else {
            groups = [
                {
                    name: "Options",
                    options
                }
            ];
        }
        let result1 = "";
        for (const group of groups){
            result1 += this.generateOptionGroup(group);
        }
        return result1;
    }
    generateOptionGroup(group) {
        if (!group.options.length) {
            return "";
        }
        const hasTypeDefinitions = !!group.options.find((option)=>!!option.typeDefinition);
        if (hasTypeDefinitions) {
            return this.label(group.name ?? "Options") + Table.from([
                ...group.options.map((option)=>[
                        option.flags.map((flag)=>brightBlue(flag)).join(", "),
                        highlightArguments(option.typeDefinition || "", this.options.types),
                        red1(bold1("-")),
                        getDescription(option.description, !this.options.long),
                        this.generateHints(option)
                    ])
            ]).padding([
                2,
                2,
                1,
                2
            ]).indent(this.indent).maxColWidth([
                60,
                60,
                1,
                80,
                60
            ]).toString() + "\n";
        }
        return this.label(group.name ?? "Options") + Table.from([
            ...group.options.map((option)=>[
                    option.flags.map((flag)=>brightBlue(flag)).join(", "),
                    red1(bold1("-")),
                    getDescription(option.description, !this.options.long),
                    this.generateHints(option)
                ])
        ]).indent(this.indent).maxColWidth([
            60,
            1,
            80,
            60
        ]).padding([
            2,
            1,
            2
        ]).toString() + "\n";
    }
    generateCommands() {
        const commands = this.cmd.getCommands(false);
        if (!commands.length) {
            return "";
        }
        const hasTypeDefinitions = !!commands.find((command)=>!!command.getArgsDefinition());
        if (hasTypeDefinitions) {
            return this.label("Commands") + Table.from([
                ...commands.map((command)=>[
                        [
                            command.getName(),
                            ...command.getAliases()
                        ].map((name)=>brightBlue(name)).join(", "),
                        highlightArguments(command.getArgsDefinition() || "", this.options.types),
                        red1(bold1("-")),
                        command.getShortDescription()
                    ])
            ]).indent(this.indent).maxColWidth([
                60,
                60,
                1,
                80
            ]).padding([
                2,
                2,
                1,
                2
            ]).toString() + "\n";
        }
        return this.label("Commands") + Table.from([
            ...commands.map((command)=>[
                    [
                        command.getName(),
                        ...command.getAliases()
                    ].map((name)=>brightBlue(name)).join(", "),
                    red1(bold1("-")),
                    command.getShortDescription()
                ])
        ]).maxColWidth([
            60,
            1,
            80
        ]).padding([
            2,
            1,
            2
        ]).indent(this.indent).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((name)=>brightBlue(name)).join(", "),
                    highlightArgumentDetails(envVar.details, this.options.types),
                    red1(bold1("-")),
                    this.options.long ? dedent(envVar.description) : envVar.description.trim().split("\n", 1)[0],
                    envVar.required ? `(${yellow1(`required`)})` : ""
                ])
        ]).padding([
            2,
            2,
            1,
            2
        ]).indent(this.indent).maxColWidth([
            60,
            60,
            1,
            80,
            10
        ]).toString() + "\n";
    }
    generateExamples() {
        const examples = this.cmd.getExamples();
        if (!examples.length) {
            return "";
        }
        return this.label("Examples") + Table.from(examples.map((example)=>[
                dim1(bold1(`${capitalize(example.name)}:`)),
                dedent(example.description)
            ])).padding(1).indent(this.indent).maxColWidth(150).toString() + "\n";
    }
    generateHints(option) {
        if (!this.options.hints) {
            return "";
        }
        const hints = [];
        option.required && hints.push(yellow1(`required`));
        if (typeof option.default !== "undefined") {
            const defaultValue = getDefaultValue(option);
            if (typeof defaultValue !== "undefined") {
                hints.push(bold1(`Default: `) + inspect(defaultValue, this.options.colors));
            }
        }
        option.depends?.length && hints.push(yellow1(bold1(`Depends: `)) + italic(option.depends.map(getFlag).join(", ")));
        option.conflicts?.length && hints.push(red1(bold1(`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(bold1(`Values: `) + possibleValues.map((value)=>inspect(value, this.options.colors)).join(", "));
            }
        }
        if (hints.length) {
            return `(${hints.join(", ")})`;
        }
        return "";
    }
    label(label) {
        return "\n" + bold1(`${label}:`) + "\n\n";
    }
}
function capitalize(string) {
    return (string?.charAt(0).toUpperCase() + string.slice(1)) ?? "";
}
function inspect(value, colors) {
    return Deno.inspect(value, {
        depth: 1,
        colors,
        trailingComma: false
    });
}
function highlightArguments(argsDefinition, types = true) {
    if (!argsDefinition) {
        return "";
    }
    return parseArgumentsDefinition(argsDefinition, false, true).map((arg)=>typeof arg === "string" ? arg : highlightArgumentDetails(arg, types)).join(" ");
}
function highlightArgumentDetails(arg, types = true) {
    let str = "";
    str += yellow1(arg.optional ? "[" : "<");
    let name = "";
    name += arg.name;
    if (arg.variadic) {
        name += "...";
    }
    name = brightMagenta(name);
    str += name;
    if (types) {
        str += yellow1(":");
        str += red1(arg.type);
        if (arg.list) {
            str += green1("[]");
        }
    }
    str += yellow1(arg.optional ? "]" : ">");
    return str;
}
class Command {
    types = new Map();
    rawArgs = [];
    literalArgs = [];
    _name = "COMMAND";
    _parent;
    _globalParent;
    ver;
    desc = "";
    _usage;
    actionHandler;
    globalActionHandler;
    options = [];
    commands = new Map();
    examples = [];
    envVars = [];
    aliases = [];
    completions = new Map();
    cmd = this;
    argsDefinition;
    isExecutable = false;
    throwOnError = false;
    _allowEmpty = false;
    _stopEarly = false;
    defaultCommand;
    _useRawArgs = false;
    args = [];
    isHidden = false;
    isGlobal = false;
    hasDefaults = false;
    _versionOptions;
    _helpOptions;
    _versionOption;
    _helpOption;
    _help;
    _shouldExit;
    _meta = {};
    _groupName = null;
    _noGlobals = false;
    errorHandler;
    versionOption(flags, desc, opts) {
        this._versionOptions = flags === false ? flags : {
            flags,
            desc,
            opts: typeof opts === "function" ? {
                action: opts
            } : opts
        };
        return this;
    }
    helpOption(flags, desc, opts) {
        this._helpOptions = flags === false ? flags : {
            flags,
            desc,
            opts: typeof opts === "function" ? {
                action: opts
            } : opts
        };
        return this;
    }
    command(nameAndArguments, cmdOrDescription, override) {
        this.reset();
        const result1 = splitArguments(nameAndArguments);
        const name = result1.flags.shift();
        const aliases = result1.flags;
        if (!name) {
            throw new MissingCommandNameError();
        }
        if (this.getBaseCommand(name, true)) {
            if (!override) {
                throw new DuplicateCommandNameError(name);
            }
            this.removeCommand(name);
        }
        let description;
        let cmd;
        if (typeof cmdOrDescription === "string") {
            description = cmdOrDescription;
        }
        if (cmdOrDescription instanceof Command) {
            cmd = cmdOrDescription.reset();
        } else {
            cmd = new Command();
        }
        cmd._name = name;
        cmd._parent = this;
        if (description) {
            cmd.description(description);
        }
        if (result1.typeDefinition) {
            cmd.arguments(result1.typeDefinition);
        }
        aliases.forEach((alias)=>cmd.alias(alias));
        this.commands.set(name, cmd);
        this.select(name);
        return this;
    }
    alias(alias) {
        if (this.cmd._name === alias || this.cmd.aliases.includes(alias)) {
            throw new DuplicateCommandAliasError(alias);
        }
        this.cmd.aliases.push(alias);
        return this;
    }
    reset() {
        this._groupName = null;
        this.cmd = this;
        return this;
    }
    select(name) {
        const cmd = this.getBaseCommand(name, true);
        if (!cmd) {
            throw new CommandNotFoundError(name, this.getBaseCommands(true));
        }
        this.cmd = cmd;
        return this;
    }
    name(name) {
        this.cmd._name = name;
        return this;
    }
    version(version) {
        if (typeof version === "string") {
            this.cmd.ver = ()=>version;
        } else if (typeof version === "function") {
            this.cmd.ver = version;
        }
        return this;
    }
    meta(name, value) {
        this.cmd._meta[name] = value;
        return this;
    }
    getMeta(name) {
        return typeof name === "undefined" ? this._meta : this._meta[name];
    }
    help(help) {
        if (typeof help === "string") {
            this.cmd._help = ()=>help;
        } else if (typeof help === "function") {
            this.cmd._help = help;
        } else {
            this.cmd._help = (cmd, options)=>HelpGenerator.generate(cmd, {
                    ...help,
                    ...options
                });
        }
        return this;
    }
    description(description) {
        this.cmd.desc = description;
        return this;
    }
    usage(usage) {
        this.cmd._usage = usage;
        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.actionHandler = fn;
        return this;
    }
    globalAction(fn) {
        this.cmd.globalActionHandler = fn;
        return this;
    }
    allowEmpty(allowEmpty) {
        this.cmd._allowEmpty = allowEmpty !== false;
        return this;
    }
    stopEarly(stopEarly = true) {
        this.cmd._stopEarly = stopEarly;
        return this;
    }
    useRawArgs(useRawArgs = true) {
        this.cmd._useRawArgs = useRawArgs;
        return this;
    }
    default(name) {
        this.cmd.defaultCommand = name;
        return this;
    }
    globalType(name, handler, options) {
        return this.type(name, handler, {
            ...options,
            global: true
        });
    }
    type(name, handler, options) {
        if (this.cmd.types.get(name) && !options?.override) {
            throw new DuplicateTypeError(name);
        }
        this.cmd.types.set(name, {
            ...options,
            name,
            handler: handler
        });
        if (handler instanceof Type && (typeof handler.complete !== "undefined" || typeof handler.values !== "undefined")) {
            const completeHandler = (cmd, parent)=>handler.complete?.(cmd, parent) || [];
            this.complete(name, completeHandler, options);
        }
        return this;
    }
    globalComplete(name, complete, options) {
        return this.complete(name, complete, {
            ...options,
            global: true
        });
    }
    complete(name, complete, options) {
        if (this.cmd.completions.has(name) && !options?.override) {
            throw new DuplicateCompletionError(name);
        }
        this.cmd.completions.set(name, {
            name,
            complete,
            ...options
        });
        return this;
    }
    throwErrors() {
        this.cmd.throwOnError = true;
        return this;
    }
    error(handler) {
        this.cmd.errorHandler = handler;
        return this;
    }
    getErrorHandler() {
        return this.errorHandler ?? this._parent?.errorHandler;
    }
    noExit() {
        this.cmd._shouldExit = false;
        this.throwErrors();
        return this;
    }
    noGlobals() {
        this.cmd._noGlobals = true;
        return this;
    }
    shouldThrowErrors() {
        return this.throwOnError || !!this._parent?.shouldThrowErrors();
    }
    shouldExit() {
        return this._shouldExit ?? this._parent?.shouldExit() ?? true;
    }
    group(name) {
        this.cmd._groupName = name;
        return this;
    }
    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") {
            opts = {
                value: opts
            };
        }
        const result1 = splitArguments(flags);
        const args = result1.typeDefinition ? parseArgumentsDefinition(result1.typeDefinition) : [];
        const option = {
            ...opts,
            name: "",
            description: desc,
            args,
            flags: result1.flags,
            equalsSign: result1.equalsSign,
            typeDefinition: result1.typeDefinition,
            groupName: this._groupName ?? undefined
        };
        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 name = isLong ? arg.slice(2) : arg.slice(1);
            if (this.cmd.getBaseOption(name, true)) {
                if (opts?.override) {
                    this.removeOption(name);
                } else {
                    throw new DuplicateOptionNameError(name, this.getPath());
                }
            }
            if (!option.name && isLong) {
                option.name = name;
            } else if (!option.aliases) {
                option.aliases = [
                    name
                ];
            } else {
                option.aliases.push(name);
            }
        }
        if (option.prepend) {
            this.cmd.options.unshift(option);
        } else {
            this.cmd.options.push(option);
        }
        return this;
    }
    example(name, description) {
        if (this.cmd.hasExample(name)) {
            throw new DuplicateExampleError(name);
        }
        this.cmd.examples.push({
            name,
            description
        });
        return this;
    }
    globalEnv(name, description, options) {
        return this.env(name, description, {
            ...options,
            global: true
        });
    }
    env(name, description, options) {
        const result1 = splitArguments(name);
        if (!result1.typeDefinition) {
            result1.typeDefinition = "<value:boolean>";
        }
        if (result1.flags.some((envName)=>this.cmd.getBaseEnvVar(envName, true))) {
            throw new DuplicateEnvVarError(name);
        }
        const details = parseArgumentsDefinition(result1.typeDefinition);
        if (details.length > 1) {
            throw new TooManyEnvVarValuesError(name);
        } else if (details.length && details[0].optional) {
            throw new UnexpectedOptionalEnvVarValueError(name);
        } else if (details.length && details[0].variadic) {
            throw new UnexpectedVariadicEnvVarValueError(name);
        }
        this.cmd.envVars.push({
            name: result1.flags[0],
            names: result1.flags,
            description,
            type: details[0].type,
            details: details.shift(),
            ...options
        });
        return this;
    }
    parse(args = Deno.args) {
        const ctx = {
            unknown: args.slice(),
            flags: {},
            env: {},
            literal: [],
            stopEarly: false,
            stopOnUnknown: false,
            defaults: {},
            actions: []
        };
        return this.parseCommand(ctx);
    }
    async parseCommand(ctx) {
        try {
            this.reset();
            this.registerDefaults();
            this.rawArgs = ctx.unknown.slice();
            if (this.isExecutable) {
                await this.executeExecutable(ctx.unknown);
                return {
                    options: {},
                    args: [],
                    cmd: this,
                    literal: []
                };
            } else if (this._useRawArgs) {
                await this.parseEnvVars(ctx, this.envVars);
                return await this.execute(ctx.env, ctx.unknown);
            }
            let preParseGlobals = false;
            let subCommand;
            if (ctx.unknown.length > 0) {
                subCommand = this.getSubCommand(ctx);
                if (!subCommand) {
                    const optionName = ctx.unknown[0].replace(/^-+/, "");
                    const option = this.getOption(optionName, true);
                    if (option?.global) {
                        preParseGlobals = true;
                        await this.parseGlobalOptionsAndEnvVars(ctx);
                    }
                }
            }
            if (subCommand || ctx.unknown.length > 0) {
                subCommand ??= this.getSubCommand(ctx);
                if (subCommand) {
                    subCommand._globalParent = this;
                    return subCommand.parseCommand(ctx);
                }
            }
            await this.parseOptionsAndEnvVars(ctx, preParseGlobals);
            const options = {
                ...ctx.env,
                ...ctx.flags
            };
            const args = this.parseArguments(ctx, options);
            this.literalArgs = ctx.literal;
            if (ctx.actions.length) {
                await Promise.all(ctx.actions.map((action)=>action.call(this, options, ...args)));
            }
            if (ctx.standalone) {
                return {
                    options,
                    args,
                    cmd: this,
                    literal: this.literalArgs
                };
            }
            return await this.execute(options, args);
        } catch (error) {
            this.handleError(error);
        }
    }
    getSubCommand(ctx) {
        const subCommand = this.getCommand(ctx.unknown[0], true);
        if (subCommand) {
            ctx.unknown.shift();
        }
        return subCommand;
    }
    async parseGlobalOptionsAndEnvVars(ctx) {
        const isHelpOption = this.getHelpOption()?.flags.includes(ctx.unknown[0]);
        const envVars = [
            ...this.envVars.filter((envVar)=>envVar.global),
            ...this.getGlobalEnvVars(true)
        ];
        await this.parseEnvVars(ctx, envVars, !isHelpOption);
        const options = [
            ...this.options.filter((option)=>option.global),
            ...this.getGlobalOptions(true)
        ];
        this.parseOptions(ctx, options, {
            stopEarly: true,
            stopOnUnknown: true,
            dotted: false
        });
    }
    async parseOptionsAndEnvVars(ctx, preParseGlobals) {
        const helpOption = this.getHelpOption();
        const isVersionOption = this._versionOption?.flags.includes(ctx.unknown[0]);
        const isHelpOption = helpOption && ctx.flags?.[helpOption.name] === true;
        const envVars = preParseGlobals ? this.envVars.filter((envVar)=>!envVar.global) : this.getEnvVars(true);
        await this.parseEnvVars(ctx, envVars, !isHelpOption && !isVersionOption);
        const options = this.getOptions(true);
        this.parseOptions(ctx, options);
    }
    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
        });
        !this.types.has("file") && this.type("file", new FileType(), {
            global: true
        });
        if (!this._help) {
            this.help({});
        }
        if (this._versionOptions !== false && (this._versionOptions || this.ver)) {
            this.option(this._versionOptions?.flags || "-V, --version", this._versionOptions?.desc || "Show the version number for this program.", {
                standalone: true,
                prepend: true,
                action: async function() {
                    const __long = this.getRawArgs().includes(`--${this._versionOption?.name}`);
                    if (__long) {
                        await checkVersion(this);
                        this.showLongVersion();
                    } else {
                        this.showVersion();
                    }
                    this.exit();
                },
                ...this._versionOptions?.opts ?? {}
            });
            this._versionOption = this.options[0];
        }
        if (this._helpOptions !== false) {
            this.option(this._helpOptions?.flags || "-h, --help", this._helpOptions?.desc || "Show this help.", {
                standalone: true,
                global: true,
                prepend: true,
                action: async function() {
                    const __long = this.getRawArgs().includes(`--${this.getHelpOption()?.name}`);
                    await checkVersion(this);
                    this.showHelp({
                        long: __long
                    });
                    this.exit();
                },
                ...this._helpOptions?.opts ?? {}
            });
            this._helpOption = this.options[0];
        }
        return this;
    }
    async execute(options, args) {
        if (this.defaultCommand) {
            const cmd = this.getCommand(this.defaultCommand, true);
            if (!cmd) {
                throw new DefaultCommandNotFoundError(this.defaultCommand, this.getCommands());
            }
            cmd._globalParent = this;
            return cmd.execute(options, args);
        }
        await this.executeGlobalAction(options, args);
        if (this.actionHandler) {
            await this.actionHandler(options, ...args);
        }
        return {
            options,
            args,
            cmd: this,
            literal: this.literalArgs
        };
    }
    async executeGlobalAction(options, args) {
        if (!this._noGlobals) {
            await this._parent?.executeGlobalAction(options, args);
        }
        await this.globalActionHandler?.(options, ...args);
    }
    async executeExecutable(args) {
        const command = this.getPath().replace(/\s+/g, "-");
        await Deno.permissions.request({
            name: "run",
            command
        });
        try {
            const cmd = new Deno.Command(command, {
                args
            });
            const output = await cmd.output();
            if (!output.success) {
                Deno.exit(output.code);
            }
        } catch (error) {
            if (error instanceof Deno.errors.NotFound) {
                throw new CommandExecutableNotFoundError(command);
            }
            throw error;
        }
    }
    parseOptions(ctx, options, { stopEarly = this._stopEarly, stopOnUnknown = false, dotted = true } = {}) {
        parseFlags(ctx, {
            stopEarly,
            stopOnUnknown,
            dotted,
            allowEmpty: this._allowEmpty,
            flags: options,
            ignoreDefaults: ctx.env,
            parse: (type)=>this.parseType(type),
            option: (option)=>{
                if (option.action) {
                    ctx.actions.push(option.action);
                }
            }
        });
    }
    parseType(type) {
        const typeSettings = this.getType(type.type);
        if (!typeSettings) {
            throw new UnknownTypeError(type.type, this.getTypes().map((type)=>type.name));
        }
        return typeSettings.handler instanceof Type ? typeSettings.handler.parse(type) : typeSettings.handler(type);
    }
    async parseEnvVars(ctx, envVars, validate = true) {
        for (const envVar of envVars){
            const env = await this.findEnvVar(envVar.names);
            if (env) {
                const parseType = (value)=>{
                    return this.parseType({
                        label: "Environment variable",
                        type: envVar.type,
                        name: env.name,
                        value
                    });
                };
                const propertyName = underscoreToCamelCase(envVar.prefix ? envVar.names[0].replace(new RegExp(`^${envVar.prefix}`), "") : envVar.names[0]);
                if (envVar.details.list) {
                    ctx.env[propertyName] = env.value.split(envVar.details.separator ?? ",").map(parseType);
                } else {
                    ctx.env[propertyName] = parseType(env.value);
                }
                if (envVar.value && typeof ctx.env[propertyName] !== "undefined") {
                    ctx.env[propertyName] = envVar.value(ctx.env[propertyName]);
                }
            } else if (envVar.required && validate) {
                throw new MissingRequiredEnvVarError(envVar);
            }
        }
    }
    async findEnvVar(names) {
        for (const name of names){
            const status = await Deno.permissions.query({
                name: "env",
                variable: name
            });
            if (status.state === "granted") {
                const value = Deno.env.get(name);
                if (value) {
                    return {
                        name,
                        value
                    };
                }
            }
        }
        return undefined;
    }
    parseArguments(ctx, options) {
        const params = [];
        const args = ctx.unknown.slice();
        if (!this.hasArguments()) {
            if (args.length) {
                if (this.hasCommands(true)) {
                    if (this.hasCommand(args[0], true)) {
                        throw new TooManyArgumentsError(args);
                    } else {
                        throw new UnknownCommandError(args[0], this.getCommands());
                    }
                } else {
                    throw new NoArgumentsAllowedError(this.getPath());
                }
            }
        } else {
            if (!args.length) {
                const required = this.getArguments().filter((expectedArg)=>!expectedArg.optional).map((expectedArg)=>expectedArg.name);
                if (required.length) {
                    const optionNames = Object.keys(options);
                    const hasStandaloneOption = !!optionNames.find((name)=>this.getOption(name, true)?.standalone);
                    if (!hasStandaloneOption) {
                        throw new MissingArgumentsError(required);
                    }
                }
            } else {
                for (const expectedArg of this.getArguments()){
                    if (!args.length) {
                        if (expectedArg.optional) {
                            break;
                        }
                        throw new MissingArgumentError(expectedArg.name);
                    }
                    let arg;
                    const parseArgValue = (value)=>{
                        return expectedArg.list ? value.split(",").map((value)=>parseArgType(value)) : parseArgType(value);
                    };
                    const parseArgType = (value)=>{
                        return this.parseType({
                            label: "Argument",
                            type: expectedArg.type,
                            name: expectedArg.name,
                            value
                        });
                    };
                    if (expectedArg.variadic) {
                        arg = args.splice(0, args.length).map((value)=>parseArgValue(value));
                    } else {
                        arg = parseArgValue(args.shift());
                    }
                    if (expectedArg.variadic && Array.isArray(arg)) {
                        params.push(...arg);
                    } else if (typeof arg !== "undefined") {
                        params.push(arg);
                    }
                }
                if (args.length) {
                    throw new TooManyArgumentsError(args);
                }
            }
        }
        return params;
    }
    handleError(error) {
        this.throw(error instanceof ValidationError ? new ValidationError1(error.message) : error instanceof Error ? error : new Error(`[non-error-thrown] ${error}`));
    }
    throw(error) {
        if (error instanceof ValidationError1) {
            error.cmd = this;
        }
        this.getErrorHandler()?.(error, this);
        if (this.shouldThrowErrors() || !(error instanceof ValidationError1)) {
            throw error;
        }
        this.showHelp();
        console.error(red1(`  ${bold1("error")}: ${error.message}\n`));
        Deno.exit(error instanceof ValidationError1 ? error.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(name) {
        return this._parent ? this._parent.getPath(name) + " " + this._name : name || this._name;
    }
    getArgsDefinition() {
        return this.argsDefinition;
    }
    getArgument(name) {
        return this.getArguments().find((arg)=>arg.name === name);
    }
    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;
    }
    getUsage() {
        return this._usage ?? [
            this.getArgsDefinition(),
            this.getRequiredOptionsDefinition()
        ].join(" ").trim();
    }
    getRequiredOptionsDefinition() {
        return this.getOptions().filter((option)=>option.required).map((option)=>[
                findFlag(option.flags),
                option.typeDefinition
            ].filter((v)=>v).join(" ").trim()).join(" ");
    }
    getShortDescription() {
        return getDescription(this.getDescription(), true);
    }
    getRawArgs() {
        return this.rawArgs;
    }
    getLiteralArgs() {
        return this.literalArgs;
    }
    showVersion() {
        console.log(this.getVersion());
    }
    getLongVersion() {
        return `${bold1(this.getMainCommand().getName())} ${brightBlue(this.getVersion() ?? "")}` + Object.entries(this.getMeta()).map(([k, v])=>`\n${bold1(k)} ${brightBlue(v)}`).join("");
    }
    showLongVersion() {
        console.log(this.getLongVersion());
    }
    showHelp(options) {
        console.log(this.getHelp(options));
    }
    getHelp(options) {
        this.registerDefaults();
        return this.getHelpHandler().call(this, this, options ?? {});
    }
    getHelpHandler() {
        return this._help ?? this._parent?.getHelpHandler();
    }
    exit(code = 0) {
        if (this.shouldExit()) {
            Deno.exit(code);
        }
    }
    hasOptions(hidden) {
        return this.getOptions(hidden).length > 0;
    }
    getOptions(hidden) {
        return this.getGlobalOptions(hidden).concat(this.getBaseOptions(hidden));
    }
    getBaseOptions(hidden) {
        if (!this.options.length) {
            return [];
        }
        return hidden ? this.options.slice(0) : this.options.filter((opt)=>!opt.hidden);
    }
    getGlobalOptions(hidden) {
        const helpOption = this.getHelpOption();
        const getGlobals = (cmd, noGlobals, options = [], names = [])=>{
            if (cmd.options.length) {
                for (const option of cmd.options){
                    if (option.global && !this.options.find((opt)=>opt.name === option.name) && names.indexOf(option.name) === -1 && (hidden || !option.hidden)) {
                        if (noGlobals && option !== helpOption) {
                            continue;
                        }
                        names.push(option.name);
                        options.push(option);
                    }
                }
            }
            return cmd._parent ? getGlobals(cmd._parent, noGlobals || cmd._noGlobals, options, names) : options;
        };
        return this._parent ? getGlobals(this._parent, this._noGlobals) : [];
    }
    hasOption(name, hidden) {
        return !!this.getOption(name, hidden);
    }
    getOption(name, hidden) {
        return this.getBaseOption(name, hidden) ?? this.getGlobalOption(name, hidden);
    }
    getBaseOption(name, hidden) {
        const option = this.options.find((option)=>option.name === name || option.aliases?.includes(name));
        return option && (hidden || !option.hidden) ? option : undefined;
    }
    getGlobalOption(name, hidden) {
        const helpOption = this.getHelpOption();
        const getGlobalOption = (parent, noGlobals)=>{
            const option = parent.getBaseOption(name, hidden);
            if (!option?.global) {
                return parent._parent && getGlobalOption(parent._parent, noGlobals || parent._noGlobals);
            }
            if (noGlobals && option !== helpOption) {
                return;
            }
            return option;
        };
        return this._parent && getGlobalOption(this._parent, this._noGlobals);
    }
    removeOption(name) {
        const index = this.options.findIndex((option)=>option.name === name);
        if (index === -1) {
            return;
        }
        return this.options.splice(index, 1)[0];
    }
    hasCommands(hidden) {
        return this.getCommands(hidden).length > 0;
    }
    getCommands(hidden) {
        return this.getGlobalCommands(hidden).concat(this.getBaseCommands(hidden));
    }
    getBaseCommands(hidden) {
        const commands = Array.from(this.commands.values());
        return hidden ? commands : commands.filter((cmd)=>!cmd.isHidden);
    }
    getGlobalCommands(hidden) {
        const getCommands = (command, noGlobals, commands = [], names = [])=>{
            if (command.commands.size) {
                for (const [_, cmd] of command.commands){
                    if (cmd.isGlobal && this !== cmd && !this.commands.has(cmd._name) && names.indexOf(cmd._name) === -1 && (hidden || !cmd.isHidden)) {
                        if (noGlobals && cmd?.getName() !== "help") {
                            continue;
                        }
                        names.push(cmd._name);
                        commands.push(cmd);
                    }
                }
            }
            return command._parent ? getCommands(command._parent, noGlobals || command._noGlobals, commands, names) : commands;
        };
        return this._parent ? getCommands(this._parent, this._noGlobals) : [];
    }
    hasCommand(name, hidden) {
        return !!this.getCommand(name, hidden);
    }
    getCommand(name, hidden) {
        return this.getBaseCommand(name, hidden) ?? this.getGlobalCommand(name, hidden);
    }
    getBaseCommand(name, hidden) {
        for (const cmd of this.commands.values()){
            if (cmd._name === name || cmd.aliases.includes(name)) {
                return cmd && (hidden || !cmd.isHidden) ? cmd : undefined;
            }
        }
    }
    getGlobalCommand(name, hidden) {
        const getGlobalCommand = (parent, noGlobals)=>{
            const cmd = parent.getBaseCommand(name, hidden);
            if (!cmd?.isGlobal) {
                return parent._parent && getGlobalCommand(parent._parent, noGlobals || parent._noGlobals);
            }
            if (noGlobals && cmd.getName() !== "help") {
                return;
            }
            return cmd;
        };
        return this._parent && getGlobalCommand(this._parent, this._noGlobals);
    }
    removeCommand(name) {
        const command = this.getBaseCommand(name, 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, types = [], 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);
                            types.push(type);
                        }
                    });
                }
                return getTypes(cmd._parent, types, names);
            }
            return types;
        };
        return getTypes(this._parent);
    }
    getType(name) {
        return this.getBaseType(name) ?? this.getGlobalType(name);
    }
    getBaseType(name) {
        return this.types.get(name);
    }
    getGlobalType(name) {
        if (!this._parent) {
            return;
        }
        const cmd = this._parent.getBaseType(name);
        if (!cmd?.global) {
            return this._parent.getGlobalType(name);
        }
        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(name) {
        return this.getBaseCompletion(name) ?? this.getGlobalCompletion(name);
    }
    getBaseCompletion(name) {
        return this.completions.get(name);
    }
    getGlobalCompletion(name) {
        if (!this._parent) {
            return;
        }
        const completion = this._parent.getBaseCompletion(name);
        if (!completion?.global) {
            return this._parent.getGlobalCompletion(name);
        }
        return completion;
    }
    hasEnvVars(hidden) {
        return this.getEnvVars(hidden).length > 0;
    }
    getEnvVars(hidden) {
        return this.getGlobalEnvVars(hidden).concat(this.getBaseEnvVars(hidden));
    }
    getBaseEnvVars(hidden) {
        if (!this.envVars.length) {
            return [];
        }
        return hidden ? this.envVars.slice(0) : this.envVars.filter((env)=>!env.hidden);
    }
    getGlobalEnvVars(hidden) {
        if (this._noGlobals) {
            return [];
        }
        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 && (hidden || !envVar.hidden)) {
                            names.push(envVar.names[0]);
                            envVars.push(envVar);
                        }
                    });
                }
                return getEnvVars(cmd._parent, envVars, names);
            }
            return envVars;
        };
        return getEnvVars(this._parent);
    }
    hasEnvVar(name, hidden) {
        return !!this.getEnvVar(name, hidden);
    }
    getEnvVar(name, hidden) {
        return this.getBaseEnvVar(name, hidden) ?? this.getGlobalEnvVar(name, hidden);
    }
    getBaseEnvVar(name, hidden) {
        const envVar = this.envVars.find((env)=>env.names.indexOf(name) !== -1);
        return envVar && (hidden || !envVar.hidden) ? envVar : undefined;
    }
    getGlobalEnvVar(name, hidden) {
        if (!this._parent || this._noGlobals) {
            return;
        }
        const envVar = this._parent.getBaseEnvVar(name, hidden);
        if (!envVar?.global) {
            return this._parent.getGlobalEnvVar(name, hidden);
        }
        return envVar;
    }
    hasExamples() {
        return this.examples.length > 0;
    }
    getExamples() {
        return this.examples;
    }
    hasExample(name) {
        return !!this.getExample(name);
    }
    getExample(name) {
        return this.examples.find((example)=>example.name === name);
    }
    getHelpOption() {
        return this._helpOption ?? this._parent?.getHelpOption();
    }
}
async function checkVersion(cmd) {
    const mainCommand = cmd.getMainCommand();
    const upgradeCommand = mainCommand.getCommand("upgrade");
    if (!isUpgradeCommand(upgradeCommand)) {
        return;
    }
    const latestVersion = await upgradeCommand.getLatestVersion();
    const currentVersion = mainCommand.getVersion();
    if (currentVersion === latestVersion) {
        return;
    }
    const versionHelpText = `(New version available: ${latestVersion}. Run '${mainCommand.getName()} upgrade' to upgrade to the latest version!)`;
    mainCommand.version(`${currentVersion}  ${bold1(yellow1(versionHelpText))}`);
}
function findFlag(flags) {
    for (const flag of flags){
        if (flag.startsWith("--")) {
            return flag;
        }
    }
    return flags[0];
}
function isUpgradeCommand(command) {
    return command instanceof Command && "getLatestVersion" in command;
}
class CommandType extends StringType {
    complete(_cmd, parent) {
        return parent?.getCommands(false).map((cmd)=>cmd.getName()) || [];
    }
}
class HelpCommand extends Command {
    constructor(cmd){
        super();
        return this.type("command", new CommandType()).arguments("[command:command]").description("Show this help or the help of a sub-command.").noGlobals().action(async (_, name)=>{
            if (!cmd) {
                cmd = name ? this.getGlobalParent()?.getBaseCommand(name) : this.getGlobalParent();
            }
            if (!cmd) {
                const cmds = this.getGlobalParent()?.getCommands();
                throw new UnknownCommandError(name ?? "", cmds ?? [], [
                    this.getName(),
                    ...this.getAliases()
                ]);
            }
            await checkVersion(cmd);
            cmd.showHelp();
            if (this.shouldExit()) {
                Deno.exit(0);
            }
        });
    }
}
class BashCompletionsGenerator {
    name;
    cmd;
    static generate(name, cmd) {
        if (!name || name === "COMMAND") {
            throw new MissingCommandNameCompletionsError("bash");
        }
        return new BashCompletionsGenerator(name, cmd).generate();
    }
    constructor(name, cmd){
        this.name = name;
        this.cmd = cmd;
    }
    generate() {
        const path = this.cmd.getPath(this.name);
        const version = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
        return `#!/usr/bin/env bash
# bash completion support for ${path}${version}

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

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

  _${replaceSpecialChars(this.name)}_expand() {
    [ "$cur" != "\${cur%\\\\}" ] && cur="$cur\\\\"
  
    # expand ~username type directory specifications
    if [[ "$cur" == \\~*/* ]]; then
      # shellcheck disable=SC2086
      eval cur=$cur
      
    elif [[ "$cur" == \\~* ]]; then
      cur=\${cur#\\~}
      # shellcheck disable=SC2086,SC2207
      COMPREPLY=( $( compgen -P '~' -u $cur ) )
      return \${#COMPREPLY[@]}
    fi
  }

  # shellcheck disable=SC2120
  _${replaceSpecialChars(this.name)}_file_dir() {
    listFiles=1
    local IFS=$'\\t\\n' xspec #glob
    _${replaceSpecialChars(this.name)}_expand || return 0
  
    if [ "\${1:-}" = -d ]; then
      # shellcheck disable=SC2206,SC2207,SC2086
      COMPREPLY=( \${COMPREPLY[@]:-} $( compgen -d -- $cur ) )
      #eval "$glob"    # restore glob setting.
      return 0
    fi
  
    xspec=\${1:+"!*.$1"}	# set only if glob passed in as $1
    # shellcheck disable=SC2206,SC2207
    COMPREPLY=( \${COMPREPLY[@]:-} $( compgen -f -X "$xspec" -- "$cur" ) \
          $( compgen -d -- "$cur" ) )
  }

  ${this.generateCompletions(this.name, 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 [[ listFiles -eq 1 ]]; then
    return 0
  fi

  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(path)} -o bashdefault -o default ${path}`;
    }
    generateCompletions(name, command, path = "", index = 1) {
        path = (path ? path + " " : "") + name;
        const commandCompletions = this.generateCommandCompletions(command, path, index);
        const childCommandCompletions = command.getCommands(false).filter((subCommand)=>subCommand !== command).map((subCommand)=>this.generateCompletions(subCommand.getName(), subCommand, path, index + 1)).join("");
        return `${commandCompletions}

${childCommandCompletions}`;
    }
    generateCommandCompletions(command, path, index) {
        const flags = this.getFlags(command);
        const childCommandNames = command.getCommands(false).map((childCommand)=>childCommand.getName());
        const completionsPath = ~path.indexOf(" ") ? " " + path.split(" ").slice(1).join(" ") : "";
        const optionArguments = this.generateOptionArguments(command, completionsPath);
        const completionsCmd = this.generateCommandCompletionsCommand(command, completionsPath);
        return `  __${replaceSpecialChars(path)}() {
    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(command, option.args, completionsPath, {
                    standalone: option.standalone
                });
                opts += `\n      ${flags}) ${completionsCmd} ;;`;
            }
            opts += "\n    esac";
        }
        return opts;
    }
    generateCommandCompletionsCommand(command, path) {
        const args = command.getArguments();
        if (args.length) {
            const type = command.getType(args[0].type);
            if (type && type.handler instanceof FileType) {
                return `_${replaceSpecialChars(this.name)}_file_dir`;
            }
            return `_${replaceSpecialChars(this.name)}_complete ${args[0].action}${path}`;
        }
        return "";
    }
    generateOptionCompletionsCommand(command, args, path, opts) {
        if (args.length) {
            const type = command.getType(args[0].type);
            if (type && type.handler instanceof FileType) {
                return `opts=(); _${replaceSpecialChars(this.name)}_file_dir`;
            }
            return `opts=(); _${replaceSpecialChars(this.name)}_complete ${args[0].action}${path}`;
        }
        if (opts?.standalone) {
            return "opts=()";
        }
        return "";
    }
}
function replaceSpecialChars(str) {
    return str.replace(/[^a-zA-Z0-9]/g, "_");
}
class BashCompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        return 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 ${dim1(italic("~/.bashrc"))}:

    ${dim1(italic(`source <(${baseCmd.getPath()} completions bash)`))}`;
        }).noGlobals().option("-n, --name <command-name>", "The name of the main command.").action(({ name = this.getMainCommand().getName() })=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            console.log(BashCompletionsGenerator.generate(name, baseCmd));
        });
    }
}
class FishCompletionsGenerator {
    name;
    cmd;
    static generate(name, cmd) {
        if (!name || name === "COMMAND") {
            throw new MissingCommandNameCompletionsError("fish");
        }
        return new FishCompletionsGenerator(name, cmd).generate();
    }
    constructor(name, cmd){
        this.name = name;
        this.cmd = cmd;
    }
    generate() {
        const path = this.cmd.getPath(this.name);
        const version = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
        return `#!/usr/bin/env fish
# fish completion support for ${path}${version}

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

${this.generateCompletions(this.name, this.cmd).trim()}`;
    }
    generateCompletions(name, command) {
        const parent = command.getParent();
        let result1 = ``;
        if (parent) {
            result1 += "\n" + this.complete(parent, {
                description: command.getShortDescription(),
                arguments: name
            });
        }
        const commandArgs = command.getArguments();
        if (commandArgs.length) {
            result1 += "\n" + this.complete(command, {
                arguments: commandArgs.length ? this.getCompletionCommand(command, commandArgs[0]) : undefined
            });
        }
        for (const option of command.getOptions(false)){
            result1 += "\n" + this.completeOption(command, option);
        }
        for (const subCommand of command.getCommands(false)){
            result1 += this.generateCompletions(subCommand.getName(), subCommand);
        }
        return result1;
    }
    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: getDescription(option.description),
            shortOption: shortOption,
            longOption: longOption,
            required: true,
            standalone: option.standalone,
            arguments: option.args.length ? this.getCompletionCommand(command, option.args[0]) : undefined
        });
    }
    complete(command, options) {
        const cmd = [
            "complete"
        ];
        cmd.push("-c", this.name);
        cmd.push("-n", `'__fish_${replaceSpecialChars1(this.name)}_using_command __${replaceSpecialChars1(command.getPath(this.name))}'`);
        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);
        }
        if (options.description) {
            const description = getDescription(options.description, true).replace(/'/g, "\\'");
            cmd.push("-d", `'${description}'`);
        }
        return cmd.join(" ");
    }
    getCompletionCommand(cmd, arg) {
        const type = cmd.getType(arg.type);
        if (type && type.handler instanceof FileType) {
            return `'(__fish_complete_path)'`;
        }
        return `'(${this.name} completions complete ${arg.action + " " + getCompletionsPath(cmd)})'`;
    }
}
function getCommandFnNames(name, cmd, cmds = []) {
    cmds.push(`__${replaceSpecialChars1(cmd.getPath(name))}`);
    cmd.getCommands(false).forEach((command)=>{
        getCommandFnNames(name, command, cmds);
    });
    return cmds;
}
function getCompletionsPath(command) {
    return command.getPath().split(" ").slice(1).join(" ");
}
function replaceSpecialChars1(str) {
    return str.replace(/[^a-zA-Z0-9]/g, "_");
}
class FishCompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        return 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 ${dim1(italic("~/.config/fish/config.fish"))}:

    ${dim1(italic(`source (${baseCmd.getPath()} completions fish | psub)`))}`;
        }).noGlobals().option("-n, --name <command-name>", "The name of the main command.").action(({ name = this.getMainCommand().getName() })=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            console.log(FishCompletionsGenerator.generate(name, baseCmd));
        });
    }
}
class ZshCompletionsGenerator {
    name;
    cmd;
    actions;
    static generate(name, cmd) {
        if (!name || name === "COMMAND") {
            throw new MissingCommandNameCompletionsError("zsh");
        }
        return new ZshCompletionsGenerator(name, cmd).generate();
    }
    constructor(name, cmd){
        this.name = name;
        this.cmd = cmd;
        this.actions = new Map();
    }
    generate() {
        const path = this.cmd.getPath(this.name);
        const version = this.cmd.getVersion() ? ` v${this.cmd.getVersion()}` : "";
        return `#!/usr/bin/env zsh
# zsh completion support for ${path}${version}

autoload -U is-at-least

# shellcheck disable=SC2154
(( $+functions[__${replaceSpecialChars2(this.name)}_complete] )) ||
function __${replaceSpecialChars2(this.name)}_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="$(${this.name} 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.name, this.cmd).trim()}

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

compdef _${replaceSpecialChars2(path)} ${path}`;
    }
    generateCompletions(name, command, path = "") {
        if (!command.hasCommands(false) && !command.hasOptions(false) && !command.hasArguments()) {
            return "";
        }
        path = (path ? path + " " : "") + name;
        return `# shellcheck disable=SC2154
(( $+functions[_${replaceSpecialChars2(path)}] )) ||
function _${replaceSpecialChars2(path)}() {` + (!command.getParent() ? `
  local state` : "") + this.generateCommandCompletions(command, path) + this.generateSubCommandCompletions(command, path) + this.generateArgumentCompletions(command, path) + this.generateActions(command) + `\n}\n\n` + command.getCommands(false).filter((subCommand)=>subCommand !== command).map((subCommand)=>this.generateCompletions(subCommand.getName(), subCommand, path)).join("");
    }
    generateCommandCompletions(command, path) {
        const commands = command.getCommands(false);
        let completions = commands.map((subCommand)=>`'${subCommand.getName()}:${subCommand.getShortDescription().replace(/'/g, "'\"'\"'")}'`).join("\n      ");
        if (completions) {
            completions = `
    local -a commands
    # shellcheck disable=SC2034
    commands=(
      ${completions}
    )
    _describe 'command' commands`;
        }
        if (command.hasArguments()) {
            const completionsPath = path.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.name)}_complete ${action.arg.name} ${action.arg.action} ${action.cmd}`;
            }
        }
        if (completions) {
            completions = `\n\n  function _commands() {${completions}\n  }`;
        }
        return completions;
    }
    generateSubCommandCompletions(command, path) {
        if (command.hasCommands(false)) {
            const actions = command.getCommands(false).map((command)=>`${command.getName()}) _${replaceSpecialChars2(path + " " + command.getName())} ;;`).join("\n      ");
            return `\n
  function _command_args() {
    case "\${words[1]}" in\n      ${actions}\n    esac
  }`;
        }
        return "";
    }
    generateArgumentCompletions(command, path) {
        this.actions.clear();
        const options = this.generateOptions(command, path);
        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}:command:_commands'`;
        }
        if (command.hasArguments() || command.hasCommands(false)) {
            const args = [];
            for (const arg of command.getArguments().slice(1)){
                const type = command.getType(arg.type);
                if (type && type.handler instanceof FileType) {
                    const fileCompletions = this.getFileCompletions(type);
                    if (arg.variadic) {
                        argIndex++;
                        for(let i1 = 0; i1 < 5; i1++){
                            args.push(`${argIndex + i1}${arg.optional ? "::" : ":"}${arg.name}:${fileCompletions}`);
                        }
                    } else {
                        args.push(`${++argIndex}${arg.optional ? "::" : ":"}${arg.name}:${fileCompletions}`);
                    }
                } else {
                    const completionsPath = path.split(" ").slice(1).join(" ");
                    const action = this.addAction(arg, completionsPath);
                    args.push(`${++argIndex}${arg.optional ? "::" : ":"}${arg.name}:->${action.name}`);
                }
            }
            argsCommand += args.map((arg)=>`\\\n    '${arg}'`).join("");
            if (command.hasCommands(false)) {
                argsCommand += ` \\\n    '*::sub command:->command_args'`;
            }
        }
        return argsCommand;
    }
    generateOptions(command, path) {
        const options = [];
        const cmdArgs = path.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 option of command.getOptions(false)){
            options.push(this.generateOption(command, option, completionsPath, excludedFlags));
        }
        return options;
    }
    generateOption(command, option, completionsPath, excludedOptions) {
        let args = "";
        for (const arg of option.args){
            const type = command.getType(arg.type);
            const optionalValue = arg.optional ? "::" : ":";
            if (type && type.handler instanceof FileType) {
                const fileCompletions = this.getFileCompletions(type);
                args += `${optionalValue}${arg.name}:${fileCompletions}`;
            } else {
                const action = this.addAction(arg, completionsPath);
                args += `${optionalValue}${arg.name}:->${action.name}`;
            }
        }
        const description = getDescription(option.description, true).replace(/\[/g, "\\[").replace(/]/g, "\\]").replace(/"/g, '\\"').replace(/'/g, "'\"'\"'");
        const collect = option.collect ? "*" : "";
        const equalsSign = option.equalsSign ? "=" : "";
        const flags = option.flags.map((flag)=>`${flag}${equalsSign}`);
        let result1 = "";
        if (option.standalone) {
            result1 += "'(- *)'";
        } else {
            const excludedFlags = [
                ...excludedOptions
            ];
            if (option.conflicts?.length) {
                excludedFlags.push(...option.conflicts.map((opt)=>"--" + opt.replace(/^--/, "")));
            }
            if (!option.collect) {
                excludedFlags.push(...option.flags);
            }
            if (excludedFlags.length) {
                result1 += `'(${excludedFlags.join(" ")})'`;
            }
        }
        if (collect || flags.length > 1) {
            result1 += `{${collect}${flags.join(",")}}`;
        } else {
            result1 += `${flags.join(",")}`;
        }
        return `${result1}'[${description}]${args}'`;
    }
    getFileCompletions(type) {
        if (!(type.handler instanceof FileType)) {
            return "";
        }
        return "_files";
    }
    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(([name, action])=>`${name}) __${replaceSpecialChars2(this.name)}_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(str) {
    return str.replace(/[^a-zA-Z0-9]/g, "_");
}
class ZshCompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        return 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 ${dim1(italic("~/.zshrc"))}:

    ${dim1(italic(`source <(${baseCmd.getPath()} completions zsh)`))}`;
        }).noGlobals().option("-n, --name <command-name>", "The name of the main command.", {
            default: ()=>this.getMainCommand().getName()
        }).action(({ name })=>{
            const baseCmd = this.#cmd || this.getMainCommand();
            console.log(ZshCompletionsGenerator.generate(name, baseCmd));
        });
    }
}
class CompleteCommand extends Command {
    constructor(cmd){
        super();
        return this.description("Get completions for given action from given command.").noGlobals().arguments("<action:string> [command...:string]").action(async (_, action, ...commandNames)=>{
            let parent;
            const completeCommand = commandNames?.reduce((cmd, name)=>{
                parent = cmd;
                const childCmd = cmd.getCommand(name, false);
                if (!childCmd) {
                    throw new UnknownCompletionCommandError(name, cmd.getCommands());
                }
                return childCmd;
            }, cmd || this.getMainCommand()) ?? (cmd || this.getMainCommand());
            const completion = completeCommand.getCompletion(action);
            const result1 = await completion?.complete(completeCommand, parent) ?? [];
            if (result1?.length) {
                Deno.stdout.writeSync(new TextEncoder().encode(result1.join("\n")));
            }
        }).reset();
    }
}
class CompletionsCommand extends Command {
    #cmd;
    constructor(cmd){
        super();
        this.#cmd = cmd;
        return 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 ${dim1(italic("~/.bashrc"))} or similar:

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

    For more information run ${dim1(italic(`${baseCmd.getPath()} completions [shell] --help`))}
`;
        }).noGlobals().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();
    }
}
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)}'`);
        }
        return;
    } catch (err) {
        if (!(err instanceof Deno.errors.NotFound)) {
            throw err;
        }
    }
    try {
        await Deno.mkdir(dir, {
            recursive: true
        });
    } catch (err) {
        if (!(err instanceof Deno.errors.AlreadyExists)) {
            throw err;
        }
        const fileInfo = await Deno.lstat(dir);
        if (!fileInfo.isDirectory) {
            throw new Error(`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`);
        }
    }
}
function ensureDirSync(dir) {
    try {
        const fileInfo = Deno.lstatSync(dir);
        if (!fileInfo.isDirectory) {
            throw new Error(`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`);
        }
        return;
    } catch (err) {
        if (!(err instanceof Deno.errors.NotFound)) {
            throw err;
        }
    }
    try {
        Deno.mkdirSync(dir, {
            recursive: true
        });
    } catch (err) {
        if (!(err instanceof Deno.errors.AlreadyExists)) {
            throw err;
        }
        const fileInfo = Deno.lstatSync(dir);
        if (!fileInfo.isDirectory) {
            throw new Error(`Ensure path exists, expected 'dir', got '${getFileInfoType(fileInfo)}'`);
        }
    }
}
Deno.build.os === "windows";
function isSubdir(src, dest, sep = SEPARATOR2) {
    if (src === dest) {
        return false;
    }
    src = toPathString(src);
    const srcArray = src.split(sep);
    dest = toPathString(dest);
    const destArray = dest.split(sep);
    return srcArray.every((current, i1)=>destArray[i1] === current);
}
function isSamePath(src, dest) {
    src = toPathString(src);
    dest = toPathString(dest);
    return resolve2(src) === resolve2(dest);
}
const EXISTS_ERROR = new Deno.errors.AlreadyExists("dest already exists.");
class SubdirectoryMoveError extends Error {
    constructor(src, dest){
        super(`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`);
    }
}
function moveSync(src, dest, { overwrite = false } = {}) {
    const srcStat = Deno.statSync(src);
    if (srcStat.isDirectory && (isSubdir(src, dest) || isSamePath(src, dest))) {
        throw new SubdirectoryMoveError(src, dest);
    }
    if (overwrite) {
        if (isSamePath(src, dest)) return;
        try {
            Deno.removeSync(dest, {
                recursive: true
            });
        } catch (error) {
            if (!(error instanceof Deno.errors.NotFound)) {
                throw error;
            }
        }
    } else {
        try {
            Deno.lstatSync(dest);
            throw EXISTS_ERROR;
        } catch (error) {
            if (error === EXISTS_ERROR) {
                throw error;
            }
        }
    }
    Deno.renameSync(src, dest);
}
const isWindows2 = Deno.build.os === "windows";
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 Deno.errors.AlreadyExists(`'${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 Deno.errors.AlreadyExists(`'${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 (isWindows2) {
        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 (isWindows2) {
        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);
    }
    src = toPathString(src);
    dest = toPathString(dest);
    const promises = [];
    for await (const entry of Deno.readDir(src)){
        const srcPath = join2(src, entry.name);
        const destPath = join2(dest, basename2(srcPath));
        if (entry.isSymlink) {
            promises.push(copySymLink(srcPath, destPath, options));
        } else if (entry.isDirectory) {
            promises.push(copyDir(srcPath, destPath, options));
        } else if (entry.isFile) {
            promises.push(copyFile(srcPath, destPath, options));
        }
    }
    await Promise.all(promises);
}
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);
    }
    src = toPathString(src);
    dest = toPathString(dest);
    for (const entry of Deno.readDirSync(src)){
        const srcPath = join2(src, entry.name);
        const destPath = join2(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(toPathString(src));
    dest = resolve2(toPathString(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(toPathString(src));
    dest = resolve2(toPathString(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 LF = "\n";
const CRLF = "\r\n";
const EOL = Deno?.build.os === "windows" ? CRLF : LF;
const regDetect = /(?:\r?\n)/g;
function format1(content, eol) {
    return content.replace(regDetect, 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 isObject1(value) {
    return value !== null && typeof value === "object";
}
function repeat(str, count) {
    let result1 = "";
    for(let cycle = 0; cycle < count; cycle++){
        result1 += str;
    }
    return result1;
}
function isNegativeZero(i1) {
    return i1 === 0 && Number.NEGATIVE_INFINITY === 1 / i1;
}
class Mark {
    name;
    buffer;
    position;
    line;
    column;
    constructor(name, buffer, position, line, column){
        this.name = name;
        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, name, result1) {
    const exclude = [];
    for (const includedSchema of schema.include){
        result1 = compileList(includedSchema, name, result1);
    }
    for (const currentType of schema[name]){
        for(let previousIndex = 0; previousIndex < result1.length; previousIndex++){
            const previousType = result1[previousIndex];
            if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) {
                exclude.push(previousIndex);
            }
        }
        result1.push(currentType);
    }
    return result1.filter((_type, index)=>!exclude.includes(index));
}
function compileMap(...typesList) {
    const result1 = {
        fallback: {},
        mapping: {},
        scalar: {},
        sequence: {}
    };
    for (const types of typesList){
        for (const type of types){
            if (type.kind !== null) {
                result1[type.kind][type.tag] = result1["fallback"][type.tag] = type;
            }
        }
    }
    return result1;
}
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() {}
}
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 || (()=>true);
            this.construct = options.construct || ((data)=>data);
            this.instanceOf = options.instanceOf;
            this.predicate = options.predicate;
            this.represent = options.represent;
            this.defaultStyle = options.defaultStyle;
            this.styleAliases = options.styleAliases;
        }
    }
    resolve = ()=>true;
    construct = (data)=>data;
}
const BASE64_MAP = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
function resolveYamlBinary(data) {
    if (data === null) return false;
    let code;
    let bitlen = 0;
    const max = data.length;
    const map = BASE64_MAP;
    for(let idx = 0; idx < max; idx++){
        code = map.indexOf(data.charAt(idx));
        if (code > 64) continue;
        if (code < 0) return false;
        bitlen += 6;
    }
    return bitlen % 8 === 0;
}
function constructYamlBinary(data) {
    const input = data.replace(/[\r\n=]/g, "");
    const max = input.length;
    const map = BASE64_MAP;
    const result1 = [];
    let bits = 0;
    for(let idx = 0; idx < max; idx++){
        if (idx % 4 === 0 && idx) {
            result1.push(bits >> 16 & 0xff);
            result1.push(bits >> 8 & 0xff);
            result1.push(bits & 0xff);
        }
        bits = bits << 6 | map.indexOf(input.charAt(idx));
    }
    const tailbits = max % 4 * 6;
    if (tailbits === 0) {
        result1.push(bits >> 16 & 0xff);
        result1.push(bits >> 8 & 0xff);
        result1.push(bits & 0xff);
    } else if (tailbits === 18) {
        result1.push(bits >> 10 & 0xff);
        result1.push(bits >> 2 & 0xff);
    } else if (tailbits === 12) {
        result1.push(bits >> 4 & 0xff);
    }
    return new Uint8Array(result1);
}
function representYamlBinary(object) {
    const max = object.length;
    const map = BASE64_MAP;
    let result1 = "";
    let bits = 0;
    for(let idx = 0; idx < max; idx++){
        if (idx % 3 === 0 && idx) {
            result1 += map[bits >> 18 & 0x3f];
            result1 += map[bits >> 12 & 0x3f];
            result1 += map[bits >> 6 & 0x3f];
            result1 += map[bits & 0x3f];
        }
        bits = (bits << 8) + object[idx];
    }
    const tail = max % 3;
    if (tail === 0) {
        result1 += map[bits >> 18 & 0x3f];
        result1 += map[bits >> 12 & 0x3f];
        result1 += map[bits >> 6 & 0x3f];
        result1 += map[bits & 0x3f];
    } else if (tail === 2) {
        result1 += map[bits >> 10 & 0x3f];
        result1 += map[bits >> 4 & 0x3f];
        result1 += map[bits << 2 & 0x3f];
        result1 += map[64];
    } else if (tail === 1) {
        result1 += map[bits >> 2 & 0x3f];
        result1 += map[bits << 4 & 0x3f];
        result1 += map[64];
        result1 += map[64];
    }
    return result1;
}
function isBinary(obj) {
    return obj instanceof Uint8Array;
}
const binary = new Type1("tag:yaml.org,2002:binary", {
    construct: constructYamlBinary,
    kind: "scalar",
    predicate: isBinary,
    represent: representYamlBinary,
    resolve: resolveYamlBinary
});
function resolveYamlBoolean(data) {
    const max = data.length;
    return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
}
function constructYamlBoolean(data) {
    return data === "true" || data === "True" || data === "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(data) {
    if (!YAML_FLOAT_PATTERN.test(data) || data[data.length - 1] === "_") {
        return false;
    }
    return true;
}
function constructYamlFloat(data) {
    let value = data.replace(/_/g, "").toLowerCase();
    const sign = value[0] === "-" ? -1 : 1;
    const digits = [];
    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)=>{
            digits.unshift(parseFloat(v));
        });
        let valueNb = 0.0;
        let base = 1;
        digits.forEach((d)=>{
            valueNb += d * base;
            base *= 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(code) {
    const func = new Function(`return ${code}`)();
    if (!(func instanceof Function)) {
        throw new TypeError(`Expected function but got ${typeof func}: ${code}`);
    }
    return func;
}
new Type1("tag:yaml.org,2002:js/function", {
    kind: "scalar",
    resolve (data) {
        if (data === null) {
            return false;
        }
        try {
            reconstructFunction(`${data}`);
            return true;
        } catch (_err) {
            return false;
        }
    },
    construct (data) {
        return reconstructFunction(data);
    },
    predicate (object) {
        return object instanceof Function;
    },
    represent (object) {
        return object.toString();
    }
});
function isHexCode(c) {
    return 0x30 <= c && c <= 0x39 || 0x41 <= c && c <= 0x46 || 0x61 <= c && c <= 0x66;
}
function isOctCode(c) {
    return 0x30 <= c && c <= 0x37;
}
function isDecCode(c) {
    return 0x30 <= c && c <= 0x39;
}
function resolveYamlInteger(data) {
    const max = data.length;
    let index = 0;
    let hasDigits = false;
    if (!max) return false;
    let ch = data[index];
    if (ch === "-" || ch === "+") {
        ch = data[++index];
    }
    if (ch === "0") {
        if (index + 1 === max) return true;
        ch = data[++index];
        if (ch === "b") {
            index++;
            for(; index < max; index++){
                ch = data[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 = data[index];
                if (ch === "_") continue;
                if (!isHexCode(data.charCodeAt(index))) return false;
                hasDigits = true;
            }
            return hasDigits && ch !== "_";
        }
        for(; index < max; index++){
            ch = data[index];
            if (ch === "_") continue;
            if (!isOctCode(data.charCodeAt(index))) return false;
            hasDigits = true;
        }
        return hasDigits && ch !== "_";
    }
    if (ch === "_") return false;
    for(; index < max; index++){
        ch = data[index];
        if (ch === "_") continue;
        if (ch === ":") break;
        if (!isDecCode(data.charCodeAt(index))) {
            return false;
        }
        hasDigits = true;
    }
    if (!hasDigits || ch === "_") return false;
    if (ch !== ":") return true;
    return /^(:[0-5]?[0-9])+$/.test(data.slice(index));
}
function constructYamlInteger(data) {
    let value = data;
    const digits = [];
    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)=>{
            digits.unshift(parseInt(v, 10));
        });
        let valueInt = 0;
        let base = 1;
        digits.forEach((d)=>{
            valueInt += d * base;
            base *= 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 (data) {
        return data !== null ? data : {};
    },
    kind: "mapping"
});
function resolveYamlMerge(data) {
    return data === "<<" || data === null;
}
const merge = new Type1("tag:yaml.org,2002:merge", {
    kind: "scalar",
    resolve: resolveYamlMerge
});
function resolveYamlNull(data) {
    const max = data.length;
    return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "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(data) {
    const objectKeys = [];
    let pairKey = "";
    let pairHasKey = false;
    for (const pair of data){
        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(data) {
    return data !== null ? data : [];
}
const omap = new Type1("tag:yaml.org,2002:omap", {
    construct: constructYamlOmap,
    kind: "sequence",
    resolve: resolveYamlOmap
});
const _toString1 = Object.prototype.toString;
function resolveYamlPairs(data) {
    const result1 = Array.from({
        length: data.length
    });
    for(let index = 0; index < data.length; index++){
        const pair = data[index];
        if (_toString1.call(pair) !== "[object Object]") return false;
        const keys = Object.keys(pair);
        if (keys.length !== 1) return false;
        result1[index] = [
            keys[0],
            pair[keys[0]]
        ];
    }
    return true;
}
function constructYamlPairs(data) {
    if (data === null) return [];
    const result1 = Array.from({
        length: data.length
    });
    for(let index = 0; index < data.length; index += 1){
        const pair = data[index];
        const keys = Object.keys(pair);
        result1[index] = [
            keys[0],
            pair[keys[0]]
        ];
    }
    return result1;
}
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 (data) {
        if (data === null || !data.length) {
            return false;
        }
        const regexp = `${data}`;
        if (regexp.charAt(0) === "/") {
            if (!REGEXP.test(data)) {
                return false;
            }
            const modifiers = [
                ...regexp.match(REGEXP)?.groups?.modifiers ?? ""
            ];
            if (new Set(modifiers).size < modifiers.length) {
                return false;
            }
        }
        return true;
    },
    construct (data) {
        const { regexp = `${data}`, modifiers = "" } = `${data}`.match(REGEXP)?.groups ?? {};
        return new RegExp(regexp, modifiers);
    },
    predicate (object) {
        return object instanceof RegExp;
    },
    represent (object) {
        return object.toString();
    }
});
const seq = new Type1("tag:yaml.org,2002:seq", {
    construct (data) {
        return data !== null ? data : [];
    },
    kind: "sequence"
});
const { hasOwn: hasOwn1 } = Object;
function resolveYamlSet(data) {
    if (data === null) return true;
    for(const key in data){
        if (hasOwn1(data, key)) {
            if (data[key] !== null) return false;
        }
    }
    return true;
}
function constructYamlSet(data) {
    return data !== null ? data : {};
}
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 (data) {
        return data !== null ? data : "";
    },
    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(data) {
    if (data === null) return false;
    if (YAML_DATE_REGEXP.exec(data) !== null) return true;
    if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
    return false;
}
function constructYamlTimestamp(data) {
    let match = YAML_DATE_REGEXP.exec(data);
    if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);
    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;
    lineStart;
    position;
    line;
    filename;
    onWarning;
    legacy;
    json;
    listener;
    implicitTypes;
    typeMap;
    version;
    checkLineBreaks;
    tagMap;
    anchorMap;
    tag;
    anchor;
    kind;
    result;
    constructor(input, { filename, schema, onWarning, legacy = false, json = false, listener = null }){
        super(schema);
        this.input = input;
        this.documents = [];
        this.lineIndent = 0;
        this.lineStart = 0;
        this.position = 0;
        this.line = 0;
        this.result = "";
        this.filename = filename;
        this.onWarning = onWarning;
        this.legacy = legacy;
        this.json = json;
        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 === 0x0a || c === 0x0d;
}
function isWhiteSpace(c) {
    return c === 0x09 || c === 0x20;
}
function isWsOrEol(c) {
    return c === 0x09 || c === 0x20 || c === 0x0a || c === 0x0d;
}
function isFlowIndicator(c) {
    return c === 0x2c || c === 0x5b || c === 0x5d || c === 0x7b || c === 0x7d;
}
function fromHexCode(c) {
    if (0x30 <= c && c <= 0x39) {
        return c - 0x30;
    }
    const lc = c | 0x20;
    if (0x61 <= lc && lc <= 0x66) {
        return lc - 0x61 + 10;
    }
    return -1;
}
function escapedHexLen(c) {
    if (c === 0x78) {
        return 2;
    }
    if (c === 0x75) {
        return 4;
    }
    if (c === 0x55) {
        return 8;
    }
    return 0;
}
function fromDecimalCode(c) {
    if (0x30 <= c && c <= 0x39) {
        return c - 0x30;
    }
    return -1;
}
function simpleEscapeSequence(c) {
    return c === 0x30 ? "\x00" : c === 0x61 ? "\x07" : c === 0x62 ? "\x08" : c === 0x74 ? "\x09" : c === 0x09 ? "\x09" : c === 0x6e ? "\x0A" : c === 0x76 ? "\x0B" : c === 0x66 ? "\x0C" : c === 0x72 ? "\x0D" : c === 0x65 ? "\x1B" : c === 0x20 ? " " : c === 0x22 ? "\x22" : c === 0x2f ? "/" : c === 0x5c ? "\x5C" : c === 0x4e ? "\x85" : c === 0x5f ? "\xA0" : c === 0x4c ? "\u2028" : c === 0x50 ? "\u2029" : "";
}
function charFromCodepoint(c) {
    if (c <= 0xffff) {
        return String.fromCharCode(c);
    }
    return String.fromCharCode((c - 0x010000 >> 10) + 0xd800, (c - 0x010000 & 0x03ff) + 0xdc00);
}
const simpleEscapeCheck = Array.from({
    length: 256
});
const simpleEscapeMap = Array.from({
    length: 256
});
for(let i1 = 0; i1 < 256; i1++){
    simpleEscapeCheck[i1] = simpleEscapeSequence(i1) ? 1 : 0;
    simpleEscapeMap[i1] = simpleEscapeSequence(i1);
}
function generateError(state, message) {
    return new YAMLError(message, new Mark(state.filename, state.input, state.position, state.line, state.position - state.lineStart));
}
function throwError(state, message) {
    throw generateError(state, message);
}
function throwWarning(state, message) {
    if (state.onWarning) {
        state.onWarning.call(null, generateError(state, message));
    }
}
const directiveHandlers = {
    YAML (state, _name, ...args) {
        if (state.version !== null) {
            return throwError(state, "duplication of %YAML directive");
        }
        if (args.length !== 1) {
            return throwError(state, "YAML directive accepts exactly one argument");
        }
        const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
        if (match === null) {
            return throwError(state, "ill-formed argument of the YAML directive");
        }
        const major = parseInt(match[1], 10);
        const minor = parseInt(match[2], 10);
        if (major !== 1) {
            return throwError(state, "unacceptable YAML version of the document");
        }
        state.version = args[0];
        state.checkLineBreaks = minor < 2;
        if (minor !== 1 && minor !== 2) {
            return throwWarning(state, "unsupported YAML version of the document");
        }
    },
    TAG (state, _name, ...args) {
        if (args.length !== 2) {
            return throwError(state, "TAG directive accepts exactly two arguments");
        }
        const handle = args[0];
        const prefix = args[1];
        if (!PATTERN_TAG_HANDLE.test(handle)) {
            return throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
        }
        if (state.tagMap && hasOwn2(state.tagMap, handle)) {
            return throwError(state, `there is a previously declared suffix for "${handle}" tag handle`);
        }
        if (!PATTERN_TAG_URI.test(prefix)) {
            return throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
        }
        if (typeof state.tagMap === "undefined") {
            state.tagMap = Object.create(null);
        }
        state.tagMap[handle] = prefix;
    }
};
function captureSegment(state, start, end, checkJson) {
    let result1;
    if (start < end) {
        result1 = state.input.slice(start, end);
        if (checkJson) {
            for(let position = 0, length = result1.length; position < length; position++){
                const character = result1.charCodeAt(position);
                if (!(character === 0x09 || 0x20 <= character && character <= 0x10ffff)) {
                    return throwError(state, "expected valid JSON character");
                }
            }
        } else if (PATTERN_NON_PRINTABLE.test(result1)) {
            return throwError(state, "the stream contains non-printable characters");
        }
        state.result += result1;
    }
}
function mergeMappings(state, destination, source, overridableKeys) {
    if (!isObject1(source)) {
        return throwError(state, "cannot merge mappings; the provided source object is unacceptable");
    }
    const keys = Object.keys(source);
    for(let i1 = 0, len = keys.length; i1 < len; i1++){
        const key = keys[i1];
        if (!hasOwn2(destination, key)) {
            Object.defineProperty(destination, key, {
                value: source[key],
                writable: true,
                enumerable: true,
                configurable: true
            });
            overridableKeys[key] = true;
        }
    }
}
function storeMappingPair(state, result1, 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(state, "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 (result1 === null) {
        result1 = {};
    }
    if (keyTag === "tag:yaml.org,2002:merge") {
        if (Array.isArray(valueNode)) {
            for(let index = 0, quantity = valueNode.length; index < quantity; index++){
                mergeMappings(state, result1, valueNode[index], overridableKeys);
            }
        } else {
            mergeMappings(state, result1, valueNode, overridableKeys);
        }
    } else {
        if (!state.json && !hasOwn2(overridableKeys, keyNode) && hasOwn2(result1, keyNode)) {
            state.line = startLine || state.line;
            state.position = startPos || state.position;
            return throwError(state, "duplicated mapping key");
        }
        Object.defineProperty(result1, keyNode, {
            value: valueNode,
            writable: true,
            enumerable: true,
            configurable: true
        });
        delete overridableKeys[keyNode];
    }
    return result1;
}
function readLineBreak(state) {
    const ch = state.input.charCodeAt(state.position);
    if (ch === 0x0a) {
        state.position++;
    } else if (ch === 0x0d) {
        state.position++;
        if (state.input.charCodeAt(state.position) === 0x0a) {
            state.position++;
        }
    } else {
        return throwError(state, "a line break is expected");
    }
    state.line += 1;
    state.lineStart = state.position;
}
function skipSeparationSpace(state, allowComments, checkIndent) {
    let lineBreaks = 0, ch = state.input.charCodeAt(state.position);
    while(ch !== 0){
        while(isWhiteSpace(ch)){
            ch = state.input.charCodeAt(++state.position);
        }
        if (allowComments && ch === 0x23) {
            do {
                ch = state.input.charCodeAt(++state.position);
            }while (ch !== 0x0a && ch !== 0x0d && ch !== 0)
        }
        if (isEOL(ch)) {
            readLineBreak(state);
            ch = state.input.charCodeAt(state.position);
            lineBreaks++;
            state.lineIndent = 0;
            while(ch === 0x20){
                state.lineIndent++;
                ch = state.input.charCodeAt(++state.position);
            }
        } else {
            break;
        }
    }
    if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
        throwWarning(state, "deficient indentation");
    }
    return lineBreaks;
}
function testDocumentSeparator(state) {
    let _position = state.position;
    let ch = state.input.charCodeAt(_position);
    if ((ch === 0x2d || ch === 0x2e) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
        _position += 3;
        ch = state.input.charCodeAt(_position);
        if (ch === 0 || isWsOrEol(ch)) {
            return true;
        }
    }
    return false;
}
function writeFoldedLines(state, count) {
    if (count === 1) {
        state.result += " ";
    } else if (count > 1) {
        state.result += repeat("\n", count - 1);
    }
}
function readPlainScalar(state, nodeIndent, withinFlowCollection) {
    const kind = state.kind;
    const result1 = state.result;
    let ch = state.input.charCodeAt(state.position);
    if (isWsOrEol(ch) || isFlowIndicator(ch) || ch === 0x23 || ch === 0x26 || ch === 0x2a || ch === 0x21 || ch === 0x7c || ch === 0x3e || ch === 0x27 || ch === 0x22 || ch === 0x25 || ch === 0x40 || ch === 0x60) {
        return false;
    }
    let following;
    if (ch === 0x3f || ch === 0x2d) {
        following = state.input.charCodeAt(state.position + 1);
        if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
            return false;
        }
    }
    state.kind = "scalar";
    state.result = "";
    let captureEnd, captureStart = captureEnd = state.position;
    let hasPendingContent = false;
    let line = 0;
    while(ch !== 0){
        if (ch === 0x3a) {
            following = state.input.charCodeAt(state.position + 1);
            if (isWsOrEol(following) || withinFlowCollection && isFlowIndicator(following)) {
                break;
            }
        } else if (ch === 0x23) {
            const preceding = state.input.charCodeAt(state.position - 1);
            if (isWsOrEol(preceding)) {
                break;
            }
        } else if (state.position === state.lineStart && testDocumentSeparator(state) || withinFlowCollection && isFlowIndicator(ch)) {
            break;
        } else if (isEOL(ch)) {
            line = state.line;
            const lineStart = state.lineStart;
            const lineIndent = state.lineIndent;
            skipSeparationSpace(state, false, -1);
            if (state.lineIndent >= nodeIndent) {
                hasPendingContent = true;
                ch = state.input.charCodeAt(state.position);
                continue;
            } else {
                state.position = captureEnd;
                state.line = line;
                state.lineStart = lineStart;
                state.lineIndent = lineIndent;
                break;
            }
        }
        if (hasPendingContent) {
            captureSegment(state, captureStart, captureEnd, false);
            writeFoldedLines(state, state.line - line);
            captureStart = captureEnd = state.position;
            hasPendingContent = false;
        }
        if (!isWhiteSpace(ch)) {
            captureEnd = state.position + 1;
        }
        ch = state.input.charCodeAt(++state.position);
    }
    captureSegment(state, captureStart, captureEnd, false);
    if (state.result) {
        return true;
    }
    state.kind = kind;
    state.result = result1;
    return false;
}
function readSingleQuotedScalar(state, nodeIndent) {
    let ch, captureStart, captureEnd;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 0x27) {
        return false;
    }
    state.kind = "scalar";
    state.result = "";
    state.position++;
    captureStart = captureEnd = state.position;
    while((ch = state.input.charCodeAt(state.position)) !== 0){
        if (ch === 0x27) {
            captureSegment(state, captureStart, state.position, true);
            ch = state.input.charCodeAt(++state.position);
            if (ch === 0x27) {
                captureStart = state.position;
                state.position++;
                captureEnd = state.position;
            } else {
                return true;
            }
        } else if (isEOL(ch)) {
            captureSegment(state, captureStart, captureEnd, true);
            writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
            captureStart = captureEnd = state.position;
        } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
            return throwError(state, "unexpected end of the document within a single quoted scalar");
        } else {
            state.position++;
            captureEnd = state.position;
        }
    }
    return throwError(state, "unexpected end of the stream within a single quoted scalar");
}
function readDoubleQuotedScalar(state, nodeIndent) {
    let ch = state.input.charCodeAt(state.position);
    if (ch !== 0x22) {
        return false;
    }
    state.kind = "scalar";
    state.result = "";
    state.position++;
    let captureEnd, captureStart = captureEnd = state.position;
    let tmp;
    while((ch = state.input.charCodeAt(state.position)) !== 0){
        if (ch === 0x22) {
            captureSegment(state, captureStart, state.position, true);
            state.position++;
            return true;
        }
        if (ch === 0x5c) {
            captureSegment(state, captureStart, state.position, true);
            ch = state.input.charCodeAt(++state.position);
            if (isEOL(ch)) {
                skipSeparationSpace(state, false, nodeIndent);
            } else if (ch < 256 && simpleEscapeCheck[ch]) {
                state.result += simpleEscapeMap[ch];
                state.position++;
            } else if ((tmp = escapedHexLen(ch)) > 0) {
                let hexLength = tmp;
                let hexResult = 0;
                for(; hexLength > 0; hexLength--){
                    ch = state.input.charCodeAt(++state.position);
                    if ((tmp = fromHexCode(ch)) >= 0) {
                        hexResult = (hexResult << 4) + tmp;
                    } else {
                        return throwError(state, "expected hexadecimal character");
                    }
                }
                state.result += charFromCodepoint(hexResult);
                state.position++;
            } else {
                return throwError(state, "unknown escape sequence");
            }
            captureStart = captureEnd = state.position;
        } else if (isEOL(ch)) {
            captureSegment(state, captureStart, captureEnd, true);
            writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
            captureStart = captureEnd = state.position;
        } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
            return throwError(state, "unexpected end of the document within a double quoted scalar");
        } else {
            state.position++;
            captureEnd = state.position;
        }
    }
    return throwError(state, "unexpected end of the stream within a double quoted scalar");
}
function readFlowCollection(state, nodeIndent) {
    let ch = state.input.charCodeAt(state.position);
    let terminator;
    let isMapping = true;
    let result1 = {};
    if (ch === 0x5b) {
        terminator = 0x5d;
        isMapping = false;
        result1 = [];
    } else if (ch === 0x7b) {
        terminator = 0x7d;
    } else {
        return false;
    }
    if (state.anchor !== null && typeof state.anchor !== "undefined" && typeof state.anchorMap !== "undefined") {
        state.anchorMap[state.anchor] = result1;
    }
    ch = state.input.charCodeAt(++state.position);
    const tag = state.tag, anchor = state.anchor;
    let readNext = true;
    let valueNode, keyNode, keyTag = keyNode = valueNode = null, isExplicitPair, isPair = isExplicitPair = false;
    let following = 0, line = 0;
    const overridableKeys = Object.create(null);
    while(ch !== 0){
        skipSeparationSpace(state, true, nodeIndent);
        ch = state.input.charCodeAt(state.position);
        if (ch === terminator) {
            state.position++;
            state.tag = tag;
            state.anchor = anchor;
            state.kind = isMapping ? "mapping" : "sequence";
            state.result = result1;
            return true;
        }
        if (!readNext) {
            return throwError(state, "missed comma between flow collection entries");
        }
        keyTag = keyNode = valueNode = null;
        isPair = isExplicitPair = false;
        if (ch === 0x3f) {
            following = state.input.charCodeAt(state.position + 1);
            if (isWsOrEol(following)) {
                isPair = isExplicitPair = true;
                state.position++;
                skipSeparationSpace(state, true, nodeIndent);
            }
        }
        line = state.line;
        composeNode(state, nodeIndent, 1, false, true);
        keyTag = state.tag || null;
        keyNode = state.result;
        skipSeparationSpace(state, true, nodeIndent);
        ch = state.input.charCodeAt(state.position);
        if ((isExplicitPair || state.line === line) && ch === 0x3a) {
            isPair = true;
            ch = state.input.charCodeAt(++state.position);
            skipSeparationSpace(state, true, nodeIndent);
            composeNode(state, nodeIndent, 1, false, true);
            valueNode = state.result;
        }
        if (isMapping) {
            storeMappingPair(state, result1, overridableKeys, keyTag, keyNode, valueNode);
        } else if (isPair) {
            result1.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode));
        } else {
            result1.push(keyNode);
        }
        skipSeparationSpace(state, true, nodeIndent);
        ch = state.input.charCodeAt(state.position);
        if (ch === 0x2c) {
            readNext = true;
            ch = state.input.charCodeAt(++state.position);
        } else {
            readNext = false;
        }
    }
    return throwError(state, "unexpected end of the stream within a flow collection");
}
function readBlockScalar(state, nodeIndent) {
    let chomping = 1, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false;
    let ch = state.input.charCodeAt(state.position);
    let folding = false;
    if (ch === 0x7c) {
        folding = false;
    } else if (ch === 0x3e) {
        folding = true;
    } else {
        return false;
    }
    state.kind = "scalar";
    state.result = "";
    let tmp = 0;
    while(ch !== 0){
        ch = state.input.charCodeAt(++state.position);
        if (ch === 0x2b || ch === 0x2d) {
            if (1 === chomping) {
                chomping = ch === 0x2b ? CHOMPING_KEEP : CHOMPING_STRIP;
            } else {
                return throwError(state, "repeat of a chomping mode identifier");
            }
        } else if ((tmp = fromDecimalCode(ch)) >= 0) {
            if (tmp === 0) {
                return throwError(state, "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(state, "repeat of an indentation width identifier");
            }
        } else {
            break;
        }
    }
    if (isWhiteSpace(ch)) {
        do {
            ch = state.input.charCodeAt(++state.position);
        }while (isWhiteSpace(ch))
        if (ch === 0x23) {
            do {
                ch = state.input.charCodeAt(++state.position);
            }while (!isEOL(ch) && ch !== 0)
        }
    }
    while(ch !== 0){
        readLineBreak(state);
        state.lineIndent = 0;
        ch = state.input.charCodeAt(state.position);
        while((!detectedIndent || state.lineIndent < textIndent) && ch === 0x20){
            state.lineIndent++;
            ch = state.input.charCodeAt(++state.position);
        }
        if (!detectedIndent && state.lineIndent > textIndent) {
            textIndent = state.lineIndent;
        }
        if (isEOL(ch)) {
            emptyLines++;
            continue;
        }
        if (state.lineIndent < textIndent) {
            if (chomping === 3) {
                state.result += repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (chomping === 1) {
                if (didReadContent) {
                    state.result += "\n";
                }
            }
            break;
        }
        if (folding) {
            if (isWhiteSpace(ch)) {
                atMoreIndented = true;
                state.result += repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (atMoreIndented) {
                atMoreIndented = false;
                state.result += repeat("\n", emptyLines + 1);
            } else if (emptyLines === 0) {
                if (didReadContent) {
                    state.result += " ";
                }
            } else {
                state.result += repeat("\n", emptyLines);
            }
        } else {
            state.result += repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
        }
        didReadContent = true;
        detectedIndent = true;
        emptyLines = 0;
        const captureStart = state.position;
        while(!isEOL(ch) && ch !== 0){
            ch = state.input.charCodeAt(++state.position);
        }
        captureSegment(state, captureStart, state.position, false);
    }
    return true;
}
function readBlockSequence(state, nodeIndent) {
    let line, following, detected = false, ch;
    const tag = state.tag, anchor = state.anchor, result1 = [];
    if (state.anchor !== null && typeof state.anchor !== "undefined" && typeof state.anchorMap !== "undefined") {
        state.anchorMap[state.anchor] = result1;
    }
    ch = state.input.charCodeAt(state.position);
    while(ch !== 0){
        if (ch !== 0x2d) {
            break;
        }
        following = state.input.charCodeAt(state.position + 1);
        if (!isWsOrEol(following)) {
            break;
        }
        detected = true;
        state.position++;
        if (skipSeparationSpace(state, true, -1)) {
            if (state.lineIndent <= nodeIndent) {
                result1.push(null);
                ch = state.input.charCodeAt(state.position);
                continue;
            }
        }
        line = state.line;
        composeNode(state, nodeIndent, 3, false, true);
        result1.push(state.result);
        skipSeparationSpace(state, true, -1);
        ch = state.input.charCodeAt(state.position);
        if ((state.line === line || state.lineIndent > nodeIndent) && ch !== 0) {
            return throwError(state, "bad indentation of a sequence entry");
        } else if (state.lineIndent < nodeIndent) {
            break;
        }
    }
    if (detected) {
        state.tag = tag;
        state.anchor = anchor;
        state.kind = "sequence";
        state.result = result1;
        return true;
    }
    return false;
}
function readBlockMapping(state, nodeIndent, flowIndent) {
    const tag = state.tag, anchor = state.anchor, result1 = {}, overridableKeys = Object.create(null);
    let following, allowCompact = false, line, pos, keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
    if (state.anchor !== null && typeof state.anchor !== "undefined" && typeof state.anchorMap !== "undefined") {
        state.anchorMap[state.anchor] = result1;
    }
    ch = state.input.charCodeAt(state.position);
    while(ch !== 0){
        following = state.input.charCodeAt(state.position + 1);
        line = state.line;
        pos = state.position;
        if ((ch === 0x3f || ch === 0x3a) && isWsOrEol(following)) {
            if (ch === 0x3f) {
                if (atExplicitKey) {
                    storeMappingPair(state, result1, overridableKeys, keyTag, keyNode, null);
                    keyTag = keyNode = valueNode = null;
                }
                detected = true;
                atExplicitKey = true;
                allowCompact = true;
            } else if (atExplicitKey) {
                atExplicitKey = false;
                allowCompact = true;
            } else {
                return throwError(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
            }
            state.position += 1;
            ch = following;
        } else if (composeNode(state, flowIndent, 2, false, true)) {
            if (state.line === line) {
                ch = state.input.charCodeAt(state.position);
                while(isWhiteSpace(ch)){
                    ch = state.input.charCodeAt(++state.position);
                }
                if (ch === 0x3a) {
                    ch = state.input.charCodeAt(++state.position);
                    if (!isWsOrEol(ch)) {
                        return throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
                    }
                    if (atExplicitKey) {
                        storeMappingPair(state, result1, overridableKeys, keyTag, keyNode, null);
                        keyTag = keyNode = valueNode = null;
                    }
                    detected = true;
                    atExplicitKey = false;
                    allowCompact = false;
                    keyTag = state.tag;
                    keyNode = state.result;
                } else if (detected) {
                    return throwError(state, "can not read an implicit mapping pair; a colon is missed");
                } else {
                    state.tag = tag;
                    state.anchor = anchor;
                    return true;
                }
            } else if (detected) {
                return throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
            } else {
                state.tag = tag;
                state.anchor = anchor;
                return true;
            }
        } else {
            break;
        }
        if (state.line === line || state.lineIndent > nodeIndent) {
            if (composeNode(state, nodeIndent, 4, true, allowCompact)) {
                if (atExplicitKey) {
                    keyNode = state.result;
                } else {
                    valueNode = state.result;
                }
            }
            if (!atExplicitKey) {
                storeMappingPair(state, result1, overridableKeys, keyTag, keyNode, valueNode, line, pos);
                keyTag = keyNode = valueNode = null;
            }
            skipSeparationSpace(state, true, -1);
            ch = state.input.charCodeAt(state.position);
        }
        if (state.lineIndent > nodeIndent && ch !== 0) {
            return throwError(state, "bad indentation of a mapping entry");
        } else if (state.lineIndent < nodeIndent) {
            break;
        }
    }
    if (atExplicitKey) {
        storeMappingPair(state, result1, overridableKeys, keyTag, keyNode, null);
    }
    if (detected) {
        state.tag = tag;
        state.anchor = anchor;
        state.kind = "mapping";
        state.result = result1;
    }
    return detected;
}
function readTagProperty(state) {
    let position, isVerbatim = false, isNamed = false, tagHandle = "", tagName, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 0x21) return false;
    if (state.tag !== null) {
        return throwError(state, "duplication of a tag property");
    }
    ch = state.input.charCodeAt(++state.position);
    if (ch === 0x3c) {
        isVerbatim = true;
        ch = state.input.charCodeAt(++state.position);
    } else if (ch === 0x21) {
        isNamed = true;
        tagHandle = "!!";
        ch = state.input.charCodeAt(++state.position);
    } else {
        tagHandle = "!";
    }
    position = state.position;
    if (isVerbatim) {
        do {
            ch = state.input.charCodeAt(++state.position);
        }while (ch !== 0 && ch !== 0x3e)
        if (state.position < state.length) {
            tagName = state.input.slice(position, state.position);
            ch = state.input.charCodeAt(++state.position);
        } else {
            return throwError(state, "unexpected end of the stream within a verbatim tag");
        }
    } else {
        while(ch !== 0 && !isWsOrEol(ch)){
            if (ch === 0x21) {
                if (!isNamed) {
                    tagHandle = state.input.slice(position - 1, state.position + 1);
                    if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
                        return throwError(state, "named tag handle cannot contain such characters");
                    }
                    isNamed = true;
                    position = state.position + 1;
                } else {
                    return throwError(state, "tag suffix cannot contain exclamation marks");
                }
            }
            ch = state.input.charCodeAt(++state.position);
        }
        tagName = state.input.slice(position, state.position);
        if (PATTERN_FLOW_INDICATORS.test(tagName)) {
            return throwError(state, "tag suffix cannot contain flow indicator characters");
        }
    }
    if (tagName && !PATTERN_TAG_URI.test(tagName)) {
        return throwError(state, `tag name cannot contain such characters: ${tagName}`);
    }
    if (isVerbatim) {
        state.tag = tagName;
    } else if (typeof state.tagMap !== "undefined" && hasOwn2(state.tagMap, tagHandle)) {
        state.tag = state.tagMap[tagHandle] + tagName;
    } else if (tagHandle === "!") {
        state.tag = `!${tagName}`;
    } else if (tagHandle === "!!") {
        state.tag = `tag:yaml.org,2002:${tagName}`;
    } else {
        return throwError(state, `undeclared tag handle "${tagHandle}"`);
    }
    return true;
}
function readAnchorProperty(state) {
    let ch = state.input.charCodeAt(state.position);
    if (ch !== 0x26) return false;
    if (state.anchor !== null) {
        return throwError(state, "duplication of an anchor property");
    }
    ch = state.input.charCodeAt(++state.position);
    const position = state.position;
    while(ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)){
        ch = state.input.charCodeAt(++state.position);
    }
    if (state.position === position) {
        return throwError(state, "name of an anchor node must contain at least one character");
    }
    state.anchor = state.input.slice(position, state.position);
    return true;
}
function readAlias(state) {
    let ch = state.input.charCodeAt(state.position);
    if (ch !== 0x2a) return false;
    ch = state.input.charCodeAt(++state.position);
    const _position = state.position;
    while(ch !== 0 && !isWsOrEol(ch) && !isFlowIndicator(ch)){
        ch = state.input.charCodeAt(++state.position);
    }
    if (state.position === _position) {
        return throwError(state, "name of an alias node must contain at least one character");
    }
    const alias = state.input.slice(_position, state.position);
    if (typeof state.anchorMap !== "undefined" && !hasOwn2(state.anchorMap, alias)) {
        return throwError(state, `unidentified alias "${alias}"`);
    }
    if (typeof state.anchorMap !== "undefined") {
        state.result = state.anchorMap[alias];
    }
    skipSeparationSpace(state, true, -1);
    return true;
}
function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
    let allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, type, flowIndent, blockIndent;
    if (state.listener && state.listener !== null) {
        state.listener("open", state);
    }
    state.tag = null;
    state.anchor = null;
    state.kind = null;
    state.result = null;
    const allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT === nodeContext || CONTEXT_BLOCK_IN === nodeContext;
    if (allowToSeek) {
        if (skipSeparationSpace(state, true, -1)) {
            atNewLine = true;
            if (state.lineIndent > parentIndent) {
                indentStatus = 1;
            } else if (state.lineIndent === parentIndent) {
                indentStatus = 0;
            } else if (state.lineIndent < parentIndent) {
                indentStatus = -1;
            }
        }
    }
    if (indentStatus === 1) {
        while(readTagProperty(state) || readAnchorProperty(state)){
            if (skipSeparationSpace(state, true, -1)) {
                atNewLine = true;
                allowBlockCollections = allowBlockStyles;
                if (state.lineIndent > parentIndent) {
                    indentStatus = 1;
                } else if (state.lineIndent === parentIndent) {
                    indentStatus = 0;
                } else if (state.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 = state.position - state.lineStart;
        if (indentStatus === 1) {
            if (allowBlockCollections && (readBlockSequence(state, blockIndent) || readBlockMapping(state, blockIndent, flowIndent)) || readFlowCollection(state, flowIndent)) {
                hasContent = true;
            } else {
                if (allowBlockScalars && readBlockScalar(state, flowIndent) || readSingleQuotedScalar(state, flowIndent) || readDoubleQuotedScalar(state, flowIndent)) {
                    hasContent = true;
                } else if (readAlias(state)) {
                    hasContent = true;
                    if (state.tag !== null || state.anchor !== null) {
                        return throwError(state, "alias node should not have Any properties");
                    }
                } else if (readPlainScalar(state, flowIndent, 1 === nodeContext)) {
                    hasContent = true;
                    if (state.tag === null) {
                        state.tag = "?";
                    }
                }
                if (state.anchor !== null && typeof state.anchorMap !== "undefined") {
                    state.anchorMap[state.anchor] = state.result;
                }
            }
        } else if (indentStatus === 0) {
            hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
        }
    }
    if (state.tag !== null && state.tag !== "!") {
        if (state.tag === "?") {
            for(let typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex++){
                type = state.implicitTypes[typeIndex];
                if (type.resolve(state.result)) {
                    state.result = type.construct(state.result);
                    state.tag = type.tag;
                    if (state.anchor !== null && typeof state.anchorMap !== "undefined") {
                        state.anchorMap[state.anchor] = state.result;
                    }
                    break;
                }
            }
        } else if (hasOwn2(state.typeMap[state.kind || "fallback"], state.tag)) {
            type = state.typeMap[state.kind || "fallback"][state.tag];
            if (state.result !== null && type.kind !== state.kind) {
                return throwError(state, `unacceptable node kind for !<${state.tag}> tag; it should be "${type.kind}", not "${state.kind}"`);
            }
            if (!type.resolve(state.result)) {
                return throwError(state, `cannot resolve a node with !<${state.tag}> explicit tag`);
            } else {
                state.result = type.construct(state.result);
                if (state.anchor !== null && typeof state.anchorMap !== "undefined") {
                    state.anchorMap[state.anchor] = state.result;
                }
            }
        } else {
            return throwError(state, `unknown tag !<${state.tag}>`);
        }
    }
    if (state.listener && state.listener !== null) {
        state.listener("close", state);
    }
    return state.tag !== null || state.anchor !== null || hasContent;
}
function readDocument(state) {
    const documentStart = state.position;
    let position, directiveName, directiveArgs, hasDirectives = false, ch;
    state.version = null;
    state.checkLineBreaks = state.legacy;
    state.tagMap = Object.create(null);
    state.anchorMap = Object.create(null);
    while((ch = state.input.charCodeAt(state.position)) !== 0){
        skipSeparationSpace(state, true, -1);
        ch = state.input.charCodeAt(state.position);
        if (state.lineIndent > 0 || ch !== 0x25) {
            break;
        }
        hasDirectives = true;
        ch = state.input.charCodeAt(++state.position);
        position = state.position;
        while(ch !== 0 && !isWsOrEol(ch)){
            ch = state.input.charCodeAt(++state.position);
        }
        directiveName = state.input.slice(position, state.position);
        directiveArgs = [];
        if (directiveName.length < 1) {
            return throwError(state, "directive name must not be less than one character in length");
        }
        while(ch !== 0){
            while(isWhiteSpace(ch)){
                ch = state.input.charCodeAt(++state.position);
            }
            if (ch === 0x23) {
                do {
                    ch = state.input.charCodeAt(++state.position);
                }while (ch !== 0 && !isEOL(ch))
                break;
            }
            if (isEOL(ch)) break;
            position = state.position;
            while(ch !== 0 && !isWsOrEol(ch)){
                ch = state.input.charCodeAt(++state.position);
            }
            directiveArgs.push(state.input.slice(position, state.position));
        }
        if (ch !== 0) readLineBreak(state);
        if (hasOwn2(directiveHandlers, directiveName)) {
            directiveHandlers[directiveName](state, directiveName, ...directiveArgs);
        } else {
            throwWarning(state, `unknown document directive "${directiveName}"`);
        }
    }
    skipSeparationSpace(state, true, -1);
    if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 0x2d && state.input.charCodeAt(state.position + 1) === 0x2d && state.input.charCodeAt(state.position + 2) === 0x2d) {
        state.position += 3;
        skipSeparationSpace(state, true, -1);
    } else if (hasDirectives) {
        return throwError(state, "directives end mark is expected");
    }
    composeNode(state, state.lineIndent - 1, 4, false, true);
    skipSeparationSpace(state, true, -1);
    if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
        throwWarning(state, "non-ASCII line breaks are interpreted as content");
    }
    state.documents.push(state.result);
    if (state.position === state.lineStart && testDocumentSeparator(state)) {
        if (state.input.charCodeAt(state.position) === 0x2e) {
            state.position += 3;
            skipSeparationSpace(state, true, -1);
        }
        return;
    }
    if (state.position < state.length - 1) {
        return throwError(state, "end of the stream or a document separator is expected");
    }
}
function loadDocuments(input, options) {
    input = String(input);
    options = options || {};
    if (input.length !== 0) {
        if (input.charCodeAt(input.length - 1) !== 0x0a && input.charCodeAt(input.length - 1) !== 0x0d) {
            input += "\n";
        }
        if (input.charCodeAt(0) === 0xfeff) {
            input = input.slice(1);
        }
    }
    const state = new LoaderState(input, options);
    state.input += "\0";
    while(state.input.charCodeAt(state.position) === 0x20){
        state.lineIndent += 1;
        state.position += 1;
    }
    while(state.position < state.length - 1){
        readDocument(state);
    }
    return state.documents;
}
function load(input, options) {
    const documents = loadDocuments(input, options);
    if (documents.length === 0) {
        return null;
    }
    if (documents.length === 1) {
        return documents[0];
    }
    throw new YAMLError("expected a single document in the stream, but found more");
}
function parse1(content, options) {
    return load(content, options);
}
const { hasOwn: hasOwn3 } = Object;
function compileStyleMap(schema, map) {
    if (typeof map === "undefined" || map === null) return {};
    let type;
    const result1 = {};
    const keys = Object.keys(map);
    let tag, style;
    for(let index = 0, length = keys.length; index < length; index += 1){
        tag = keys[index];
        style = String(map[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];
        }
        result1[tag] = style;
    }
    return result1;
}
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[0x00] = "\\0";
ESCAPE_SEQUENCES[0x07] = "\\a";
ESCAPE_SEQUENCES[0x08] = "\\b";
ESCAPE_SEQUENCES[0x09] = "\\t";
ESCAPE_SEQUENCES[0x0a] = "\\n";
ESCAPE_SEQUENCES[0x0b] = "\\v";
ESCAPE_SEQUENCES[0x0c] = "\\f";
ESCAPE_SEQUENCES[0x0d] = "\\r";
ESCAPE_SEQUENCES[0x1b] = "\\e";
ESCAPE_SEQUENCES[0x22] = '\\"';
ESCAPE_SEQUENCES[0x5c] = "\\\\";
ESCAPE_SEQUENCES[0x85] = "\\N";
ESCAPE_SEQUENCES[0xa0] = "\\_";
ESCAPE_SEQUENCES[0x2028] = "\\L";
ESCAPE_SEQUENCES[0x2029] = "\\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 string = character.toString(16).toUpperCase();
    let handle;
    let length;
    if (character <= 0xff) {
        handle = "x";
        length = 2;
    } else if (character <= 0xffff) {
        handle = "u";
        length = 4;
    } else if (character <= 0xffffffff) {
        handle = "U";
        length = 8;
    } else {
        throw new YAMLError("code point within a string may not be greater than 0xFFFFFFFF");
    }
    return `\\${handle}${repeat("0", length - string.length)}${string}`;
}
function indentString(string, spaces) {
    const ind = repeat(" ", spaces), length = string.length;
    let position = 0, next = -1, result1 = "", line;
    while(position < length){
        next = string.indexOf("\n", position);
        if (next === -1) {
            line = string.slice(position);
            position = length;
        } else {
            line = string.slice(position, next + 1);
            position = next + 1;
        }
        if (line.length && line !== "\n") result1 += ind;
        result1 += line;
    }
    return result1;
}
function generateNextLine(state, level) {
    return `\n${repeat(" ", state.indent * level)}`;
}
function testImplicitResolving(state, str) {
    let type;
    for(let index = 0, length = state.implicitTypes.length; index < length; index += 1){
        type = state.implicitTypes[index];
        if (type.resolve(str)) {
            return true;
        }
    }
    return false;
}
function isWhitespace(c) {
    return c === 0x20 || c === 0x09;
}
function isPrintable(c) {
    return 0x00020 <= c && c <= 0x00007e || 0x000a1 <= c && c <= 0x00d7ff && c !== 0x2028 && c !== 0x2029 || 0x0e000 <= c && c <= 0x00fffd && c !== 0xfeff || 0x10000 <= c && c <= 0x10ffff;
}
function isPlainSafe(c) {
    return isPrintable(c) && c !== 0xfeff && c !== 0x2c && c !== 0x5b && c !== 0x5d && c !== 0x7b && c !== 0x7d && c !== 0x3a && c !== 0x23;
}
function isPlainSafeFirst(c) {
    return isPrintable(c) && c !== 0xfeff && !isWhitespace(c) && c !== 0x2d && c !== 0x3f && c !== 0x3a && c !== 0x2c && c !== 0x5b && c !== 0x5d && c !== 0x7b && c !== 0x7d && c !== 0x23 && c !== 0x26 && c !== 0x2a && c !== 0x21 && c !== 0x7c && c !== 0x3e && c !== 0x27 && c !== 0x22 && c !== 0x25 && c !== 0x40 && c !== 0x60;
}
function needIndentIndicator(string) {
    const leadingSpaceRe = /^\n* /;
    return leadingSpaceRe.test(string);
}
const STYLE_PLAIN = 1, STYLE_SINGLE = 2, STYLE_LITERAL = 3, STYLE_FOLDED = 4, STYLE_DOUBLE = 5;
function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) {
    const shouldTrackWidth = lineWidth !== -1;
    let hasLineBreak = false, hasFoldableLine = false, previousLineBreak = -1, plain = isPlainSafeFirst(string.charCodeAt(0)) && !isWhitespace(string.charCodeAt(string.length - 1));
    let __char, i1;
    if (singleLineOnly) {
        for(i1 = 0; i1 < string.length; i1++){
            __char = string.charCodeAt(i1);
            if (!isPrintable(__char)) {
                return 5;
            }
            plain = plain && isPlainSafe(__char);
        }
    } else {
        for(i1 = 0; i1 < string.length; i1++){
            __char = string.charCodeAt(i1);
            if (__char === 0x0a) {
                hasLineBreak = true;
                if (shouldTrackWidth) {
                    hasFoldableLine = hasFoldableLine || i1 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
                    previousLineBreak = i1;
                }
            } else if (!isPrintable(__char)) {
                return 5;
            }
            plain = plain && isPlainSafe(__char);
        }
        hasFoldableLine = hasFoldableLine || shouldTrackWidth && i1 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
    }
    if (!hasLineBreak && !hasFoldableLine) {
        return plain && !testAmbiguousType(string) ? 1 : 2;
    }
    if (indentPerLevel > 9 && needIndentIndicator(string)) {
        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 result1 = "";
    while(match = breakRe.exec(line)){
        next = match.index;
        if (next - start > width) {
            end = curr > start ? curr : next;
            result1 += `\n${line.slice(start, end)}`;
            start = end + 1;
        }
        curr = next;
    }
    result1 += "\n";
    if (line.length - start > width && curr > start) {
        result1 += `${line.slice(start, curr)}\n${line.slice(curr + 1)}`;
    } else {
        result1 += line.slice(start);
    }
    return result1.slice(1);
}
function dropEndingNewline(string) {
    return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
}
function foldString(string, width) {
    const lineRe = /(\n+)([^\n]*)/g;
    let result1 = (()=>{
        let nextLF = string.indexOf("\n");
        nextLF = nextLF !== -1 ? nextLF : string.length;
        lineRe.lastIndex = nextLF;
        return foldLine(string.slice(0, nextLF), width);
    })();
    let prevMoreIndented = string[0] === "\n" || string[0] === " ";
    let moreIndented;
    let match;
    while(match = lineRe.exec(string)){
        const prefix = match[1], line = match[2];
        moreIndented = line[0] === " ";
        result1 += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
        prevMoreIndented = moreIndented;
    }
    return result1;
}
function escapeString(string) {
    let result1 = "";
    let __char, nextChar;
    let escapeSeq;
    for(let i1 = 0; i1 < string.length; i1++){
        __char = string.charCodeAt(i1);
        if (__char >= 0xd800 && __char <= 0xdbff) {
            nextChar = string.charCodeAt(i1 + 1);
            if (nextChar >= 0xdc00 && nextChar <= 0xdfff) {
                result1 += encodeHex((__char - 0xd800) * 0x400 + nextChar - 0xdc00 + 0x10000);
                i1++;
                continue;
            }
        }
        escapeSeq = ESCAPE_SEQUENCES[__char];
        result1 += !escapeSeq && isPrintable(__char) ? string[i1] : escapeSeq || encodeHex(__char);
    }
    return result1;
}
function blockHeader(string, indentPerLevel) {
    const indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : "";
    const clip = string[string.length - 1] === "\n";
    const keep = clip && (string[string.length - 2] === "\n" || string === "\n");
    const chomp = keep ? "+" : clip ? "" : "-";
    return `${indentIndicator}${chomp}\n`;
}
function writeScalar(state, string, level, iskey) {
    state.dump = (()=>{
        if (string.length === 0) {
            return "''";
        }
        if (!state.noCompatMode && DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) {
            return `'${string}'`;
        }
        const indent = state.indent * Math.max(1, level);
        const lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
        const singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
        function testAmbiguity(str) {
            return testImplicitResolving(state, str);
        }
        switch(chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)){
            case STYLE_PLAIN:
                return string;
            case STYLE_SINGLE:
                return `'${string.replace(/'/g, "''")}'`;
            case STYLE_LITERAL:
                return `|${blockHeader(string, state.indent)}${dropEndingNewline(indentString(string, indent))}`;
            case STYLE_FOLDED:
                return `>${blockHeader(string, state.indent)}${dropEndingNewline(indentString(foldString(string, lineWidth), indent))}`;
            case STYLE_DOUBLE:
                return `"${escapeString(string)}"`;
            default:
                throw new YAMLError("impossible error: invalid scalar style");
        }
    })();
}
function writeFlowSequence(state, level, object) {
    let _result = "";
    const _tag = state.tag;
    for(let index = 0, length = object.length; index < length; index += 1){
        if (writeNode(state, level, object[index], false, false)) {
            if (index !== 0) _result += `,${!state.condenseFlow ? " " : ""}`;
            _result += state.dump;
        }
    }
    state.tag = _tag;
    state.dump = `[${_result}]`;
}
function writeBlockSequence(state, level, object, compact = false) {
    let _result = "";
    const _tag = state.tag;
    for(let index = 0, length = object.length; index < length; index += 1){
        if (writeNode(state, level + 1, object[index], true, true)) {
            if (!compact || index !== 0) {
                _result += generateNextLine(state, level);
            }
            if (state.dump && 0x0a === state.dump.charCodeAt(0)) {
                _result += "-";
            } else {
                _result += "- ";
            }
            _result += state.dump;
        }
    }
    state.tag = _tag;
    state.dump = _result || "[]";
}
function writeFlowMapping(state, level, object) {
    let _result = "";
    const _tag = state.tag, objectKeyList = Object.keys(object);
    let pairBuffer, objectKey, objectValue;
    for(let index = 0, length = objectKeyList.length; index < length; index += 1){
        pairBuffer = state.condenseFlow ? '"' : "";
        if (index !== 0) pairBuffer += ", ";
        objectKey = objectKeyList[index];
        objectValue = object[objectKey];
        if (!writeNode(state, level, objectKey, false, false)) {
            continue;
        }
        if (state.dump.length > 1024) pairBuffer += "? ";
        pairBuffer += `${state.dump}${state.condenseFlow ? '"' : ""}:${state.condenseFlow ? "" : " "}`;
        if (!writeNode(state, level, objectValue, false, false)) {
            continue;
        }
        pairBuffer += state.dump;
        _result += pairBuffer;
    }
    state.tag = _tag;
    state.dump = `{${_result}}`;
}
function writeBlockMapping(state, level, object, compact = false) {
    const _tag = state.tag, objectKeyList = Object.keys(object);
    let _result = "";
    if (state.sortKeys === true) {
        objectKeyList.sort();
    } else if (typeof state.sortKeys === "function") {
        objectKeyList.sort(state.sortKeys);
    } else if (state.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(state, level);
        }
        objectKey = objectKeyList[index];
        objectValue = object[objectKey];
        if (!writeNode(state, level + 1, objectKey, true, true, true)) {
            continue;
        }
        explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
        if (explicitPair) {
            if (state.dump && 0x0a === state.dump.charCodeAt(0)) {
                pairBuffer += "?";
            } else {
                pairBuffer += "? ";
            }
        }
        pairBuffer += state.dump;
        if (explicitPair) {
            pairBuffer += generateNextLine(state, level);
        }
        if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
            continue;
        }
        if (state.dump && 0x0a === state.dump.charCodeAt(0)) {
            pairBuffer += ":";
        } else {
            pairBuffer += ": ";
        }
        pairBuffer += state.dump;
        _result += pairBuffer;
    }
    state.tag = _tag;
    state.dump = _result || "{}";
}
function detectType(state, object, explicit = false) {
    const typeList = explicit ? state.explicitTypes : state.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))) {
            state.tag = explicit ? type.tag : "?";
            if (type.represent) {
                style = state.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`);
                }
                state.dump = _result;
            }
            return true;
        }
    }
    return false;
}
function writeNode(state, level, object, block, compact, iskey = false) {
    state.tag = null;
    state.dump = object;
    if (!detectType(state, object, false)) {
        detectType(state, object, true);
    }
    const type = _toString2.call(state.dump);
    if (block) {
        block = state.flowLevel < 0 || state.flowLevel > level;
    }
    const objectOrArray = type === "[object Object]" || type === "[object Array]";
    let duplicateIndex = -1;
    let duplicate = false;
    if (objectOrArray) {
        duplicateIndex = state.duplicates.indexOf(object);
        duplicate = duplicateIndex !== -1;
    }
    if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
        compact = false;
    }
    if (duplicate && state.usedDuplicates[duplicateIndex]) {
        state.dump = `*ref_${duplicateIndex}`;
    } else {
        if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
            state.usedDuplicates[duplicateIndex] = true;
        }
        if (type === "[object Object]") {
            if (block && Object.keys(state.dump).length !== 0) {
                writeBlockMapping(state, level, state.dump, compact);
                if (duplicate) {
                    state.dump = `&ref_${duplicateIndex}${state.dump}`;
                }
            } else {
                writeFlowMapping(state, level, state.dump);
                if (duplicate) {
                    state.dump = `&ref_${duplicateIndex} ${state.dump}`;
                }
            }
        } else if (type === "[object Array]") {
            const arrayLevel = state.noArrayIndent && level > 0 ? level - 1 : level;
            if (block && state.dump.length !== 0) {
                writeBlockSequence(state, arrayLevel, state.dump, compact);
                if (duplicate) {
                    state.dump = `&ref_${duplicateIndex}${state.dump}`;
                }
            } else {
                writeFlowSequence(state, arrayLevel, state.dump);
                if (duplicate) {
                    state.dump = `&ref_${duplicateIndex} ${state.dump}`;
                }
            }
        } else if (type === "[object String]") {
            if (state.tag !== "?") {
                writeScalar(state, state.dump, level, iskey);
            }
        } else {
            if (state.skipInvalid) return false;
            throw new YAMLError(`unacceptable kind of an object to dump ${type}`);
        }
        if (state.tag !== null && state.tag !== "?") {
            state.dump = `!<${state.tag}> ${state.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, state) {
    const objects = [], duplicatesIndexes = [];
    inspectNode(object, objects, duplicatesIndexes);
    const length = duplicatesIndexes.length;
    for(let index = 0; index < length; index += 1){
        state.duplicates.push(objects[duplicatesIndexes[index]]);
    }
    state.usedDuplicates = Array.from({
        length
    });
}
function dump(input, options) {
    options = options || {};
    const state = new DumperState(options);
    if (!state.noRefs) getDuplicateReferences(input, state);
    if (writeNode(state, 0, input, true, true)) return `${state.dump}\n`;
    return "";
}
function stringify(obj, options) {
    return dump(obj, options);
}
const State1 = {
    PASSTHROUGH: 0,
    PERCENT: 1,
    POSITIONAL: 2,
    PRECISION: 3,
    WIDTH: 4
};
const WorP = {
    WIDTH: 0,
    PRECISION: 1
};
const F = {
    sign: 1,
    mantissa: 2,
    fractional: 3,
    esign: 4,
    exponent: 5
};
class Flags {
    plus;
    dash;
    sharp;
    space;
    zero;
    lessthan;
    width = -1;
    precision = -1;
}
const min = Math.min;
const UNICODE_REPLACEMENT_CHARACTER = "\ufffd";
const FLOAT_REGEXP = /(-?)(\d)\.?(\d*)e([+-])(\d+)/;
class Printf {
    format;
    args;
    i;
    state = State1.PASSTHROUGH;
    verb = "";
    buf = "";
    argNum = 0;
    flags = new Flags();
    haveSeen;
    tmpError;
    constructor(format, ...args){
        this.format = format;
        this.args = args;
        this.haveSeen = Array.from({
            length: args.length
        });
        this.i = 0;
    }
    doPrintf() {
        for(; this.i < this.format.length; ++this.i){
            const c = this.format[this.i];
            switch(this.state){
                case State1.PASSTHROUGH:
                    if (c === "%") {
                        this.state = State1.PERCENT;
                    } else {
                        this.buf += c;
                    }
                    break;
                case State1.PERCENT:
                    if (c === "%") {
                        this.buf += c;
                        this.state = State1.PASSTHROUGH;
                    } else {
                        this.handleFormat();
                    }
                    break;
                default:
                    throw Error("Should be unreachable, certainly a bug in the lib.");
            }
        }
        let extras = false;
        let err = "%!(EXTRA";
        for(let i1 = 0; i1 !== this.haveSeen.length; ++i1){
            if (!this.haveSeen[i1]) {
                extras = true;
                err += ` '${Deno.inspect(this.args[i1])}'`;
            }
        }
        err += ")";
        if (extras) {
            this.buf += err;
        }
        return this.buf;
    }
    handleFormat() {
        this.flags = new Flags();
        const flags = this.flags;
        for(; this.i < this.format.length; ++this.i){
            const c = this.format[this.i];
            switch(this.state){
                case State1.PERCENT:
                    switch(c){
                        case "[":
                            this.handlePositional();
                            this.state = State1.POSITIONAL;
                            break;
                        case "+":
                            flags.plus = true;
                            break;
                        case "<":
                            flags.lessthan = true;
                            break;
                        case "-":
                            flags.dash = true;
                            flags.zero = false;
                            break;
                        case "#":
                            flags.sharp = true;
                            break;
                        case " ":
                            flags.space = true;
                            break;
                        case "0":
                            flags.zero = !flags.dash;
                            break;
                        default:
                            if ("1" <= c && c <= "9" || c === "." || c === "*") {
                                if (c === ".") {
                                    this.flags.precision = 0;
                                    this.state = State1.PRECISION;
                                    this.i++;
                                } else {
                                    this.state = State1.WIDTH;
                                }
                                this.handleWidthAndPrecision(flags);
                            } else {
                                this.handleVerb();
                                return;
                            }
                    }
                    break;
                case State1.POSITIONAL:
                    if (c === "*") {
                        const worp = this.flags.precision === -1 ? WorP.WIDTH : WorP.PRECISION;
                        this.handleWidthOrPrecisionRef(worp);
                        this.state = State1.PERCENT;
                        break;
                    } else {
                        this.handleVerb();
                        return;
                    }
                default:
                    throw new Error(`Should not be here ${this.state}, library bug!`);
            }
        }
    }
    handleWidthOrPrecisionRef(wOrP) {
        if (this.argNum >= this.args.length) {
            return;
        }
        const arg = this.args[this.argNum];
        this.haveSeen[this.argNum] = true;
        if (typeof arg === "number") {
            switch(wOrP){
                case WorP.WIDTH:
                    this.flags.width = arg;
                    break;
                default:
                    this.flags.precision = arg;
            }
        } else {
            const tmp = wOrP === WorP.WIDTH ? "WIDTH" : "PREC";
            this.tmpError = `%!(BAD ${tmp} '${this.args[this.argNum]}')`;
        }
        this.argNum++;
    }
    handleWidthAndPrecision(flags) {
        const fmt = this.format;
        for(; this.i !== this.format.length; ++this.i){
            const c = fmt[this.i];
            switch(this.state){
                case State1.WIDTH:
                    switch(c){
                        case ".":
                            this.flags.precision = 0;
                            this.state = State1.PRECISION;
                            break;
                        case "*":
                            this.handleWidthOrPrecisionRef(WorP.WIDTH);
                            break;
                        default:
                            {
                                const val = parseInt(c);
                                if (isNaN(val)) {
                                    this.i--;
                                    this.state = State1.PERCENT;
                                    return;
                                }
                                flags.width = flags.width === -1 ? 0 : flags.width;
                                flags.width *= 10;
                                flags.width += val;
                            }
                    }
                    break;
                case State1.PRECISION:
                    {
                        if (c === "*") {
                            this.handleWidthOrPrecisionRef(WorP.PRECISION);
                            break;
                        }
                        const val = parseInt(c);
                        if (isNaN(val)) {
                            this.i--;
                            this.state = State1.PERCENT;
                            return;
                        }
                        flags.precision *= 10;
                        flags.precision += val;
                        break;
                    }
                default:
                    throw new Error("can't be here. bug.");
            }
        }
    }
    handlePositional() {
        if (this.format[this.i] !== "[") {
            throw new Error("Can't happen? Bug.");
        }
        let positional = 0;
        const format = this.format;
        this.i++;
        let err = false;
        for(; this.i !== this.format.length; ++this.i){
            if (format[this.i] === "]") {
                break;
            }
            positional *= 10;
            const val = parseInt(format[this.i]);
            if (isNaN(val)) {
                this.tmpError = "%!(BAD INDEX)";
                err = true;
            }
            positional += val;
        }
        if (positional - 1 >= this.args.length) {
            this.tmpError = "%!(BAD INDEX)";
            err = true;
        }
        this.argNum = err ? this.argNum : positional - 1;
    }
    handleLessThan() {
        const arg = this.args[this.argNum];
        if ((arg || {}).constructor.name !== "Array") {
            throw new Error(`arg ${arg} is not an array. Todo better error handling`);
        }
        let str = "[ ";
        for(let i1 = 0; i1 !== arg.length; ++i1){
            if (i1 !== 0) str += ", ";
            str += this._handleVerb(arg[i1]);
        }
        return str + " ]";
    }
    handleVerb() {
        const verb = this.format[this.i];
        this.verb = verb;
        if (this.tmpError) {
            this.buf += this.tmpError;
            this.tmpError = undefined;
            if (this.argNum < this.haveSeen.length) {
                this.haveSeen[this.argNum] = true;
            }
        } else if (this.args.length <= this.argNum) {
            this.buf += `%!(MISSING '${verb}')`;
        } else {
            const arg = this.args[this.argNum];
            this.haveSeen[this.argNum] = true;
            if (this.flags.lessthan) {
                this.buf += this.handleLessThan();
            } else {
                this.buf += this._handleVerb(arg);
            }
        }
        this.argNum++;
        this.state = State1.PASSTHROUGH;
    }
    _handleVerb(arg) {
        switch(this.verb){
            case "t":
                return this.pad(arg.toString());
            case "b":
                return this.fmtNumber(arg, 2);
            case "c":
                return this.fmtNumberCodePoint(arg);
            case "d":
                return this.fmtNumber(arg, 10);
            case "o":
                return this.fmtNumber(arg, 8);
            case "x":
                return this.fmtHex(arg);
            case "X":
                return this.fmtHex(arg, true);
            case "e":
                return this.fmtFloatE(arg);
            case "E":
                return this.fmtFloatE(arg, true);
            case "f":
            case "F":
                return this.fmtFloatF(arg);
            case "g":
                return this.fmtFloatG(arg);
            case "G":
                return this.fmtFloatG(arg, true);
            case "s":
                return this.fmtString(arg);
            case "T":
                return this.fmtString(typeof arg);
            case "v":
                return this.fmtV(arg);
            case "j":
                return this.fmtJ(arg);
            case "i":
                return this.fmtI(arg, false);
            case "I":
                return this.fmtI(arg, true);
            default:
                return `%!(BAD VERB '${this.verb}')`;
        }
    }
    pad(s) {
        const padding = this.flags.zero ? "0" : " ";
        if (this.flags.dash) {
            return s.padEnd(this.flags.width, padding);
        }
        return s.padStart(this.flags.width, padding);
    }
    padNum(nStr, neg) {
        let sign;
        if (neg) {
            sign = "-";
        } else if (this.flags.plus || this.flags.space) {
            sign = this.flags.plus ? "+" : " ";
        } else {
            sign = "";
        }
        const zero = this.flags.zero;
        if (!zero) {
            nStr = sign + nStr;
        }
        const pad = zero ? "0" : " ";
        const len = zero ? this.flags.width - sign.length : this.flags.width;
        if (this.flags.dash) {
            nStr = nStr.padEnd(len, pad);
        } else {
            nStr = nStr.padStart(len, pad);
        }
        if (zero) {
            nStr = sign + nStr;
        }
        return nStr;
    }
    fmtNumber(n, radix, upcase = false) {
        let num = Math.abs(n).toString(radix);
        const prec = this.flags.precision;
        if (prec !== -1) {
            this.flags.zero = false;
            num = n === 0 && prec === 0 ? "" : num;
            while(num.length < prec){
                num = "0" + num;
            }
        }
        let prefix = "";
        if (this.flags.sharp) {
            switch(radix){
                case 2:
                    prefix += "0b";
                    break;
                case 8:
                    prefix += num.startsWith("0") ? "" : "0";
                    break;
                case 16:
                    prefix += "0x";
                    break;
                default:
                    throw new Error("cannot handle base: " + radix);
            }
        }
        num = num.length === 0 ? num : prefix + num;
        if (upcase) {
            num = num.toUpperCase();
        }
        return this.padNum(num, n < 0);
    }
    fmtNumberCodePoint(n) {
        let s = "";
        try {
            s = String.fromCodePoint(n);
        } catch  {
            s = UNICODE_REPLACEMENT_CHARACTER;
        }
        return this.pad(s);
    }
    fmtFloatSpecial(n) {
        if (isNaN(n)) {
            this.flags.zero = false;
            return this.padNum("NaN", false);
        }
        if (n === Number.POSITIVE_INFINITY) {
            this.flags.zero = false;
            this.flags.plus = true;
            return this.padNum("Inf", false);
        }
        if (n === Number.NEGATIVE_INFINITY) {
            this.flags.zero = false;
            return this.padNum("Inf", true);
        }
        return "";
    }
    roundFractionToPrecision(fractional, precision) {
        let round = false;
        if (fractional.length > precision) {
            fractional = "1" + fractional;
            let tmp = parseInt(fractional.slice(0, precision + 2)) / 10;
            tmp = Math.round(tmp);
            fractional = Math.floor(tmp).toString();
            round = fractional[0] === "2";
            fractional = fractional.slice(1);
        } else {
            while(fractional.length < precision){
                fractional += "0";
            }
        }
        return [
            fractional,
            round
        ];
    }
    fmtFloatE(n, upcase = false) {
        const special = this.fmtFloatSpecial(n);
        if (special !== "") {
            return special;
        }
        const m = n.toExponential().match(FLOAT_REGEXP);
        if (!m) {
            throw Error("can't happen, bug");
        }
        let fractional = m[F.fractional];
        const precision = this.flags.precision !== -1 ? this.flags.precision : 6;
        let rounding = false;
        [fractional, rounding] = this.roundFractionToPrecision(fractional, precision);
        let e = m[F.exponent];
        let esign = m[F.esign];
        let mantissa = parseInt(m[F.mantissa]);
        if (rounding) {
            mantissa += 1;
            if (10 <= mantissa) {
                mantissa = 1;
                const r = parseInt(esign + e) + 1;
                e = r.toString();
                esign = r < 0 ? "-" : "+";
            }
        }
        e = e.length === 1 ? "0" + e : e;
        const val = `${mantissa}.${fractional}${upcase ? "E" : "e"}${esign}${e}`;
        return this.padNum(val, n < 0);
    }
    fmtFloatF(n) {
        const special = this.fmtFloatSpecial(n);
        if (special !== "") {
            return special;
        }
        function expandNumber(n) {
            if (Number.isSafeInteger(n)) {
                return n.toString() + ".";
            }
            const t = n.toExponential().split("e");
            let m = t[0].replace(".", "");
            const e = parseInt(t[1]);
            if (e < 0) {
                let nStr = "0.";
                for(let i1 = 0; i1 !== Math.abs(e) - 1; ++i1){
                    nStr += "0";
                }
                return nStr += m;
            } else {
                const splIdx = e + 1;
                while(m.length < splIdx){
                    m += "0";
                }
                return m.slice(0, splIdx) + "." + m.slice(splIdx);
            }
        }
        const val = expandNumber(Math.abs(n));
        const arr = val.split(".");
        let dig = arr[0];
        let fractional = arr[1];
        const precision = this.flags.precision !== -1 ? this.flags.precision : 6;
        let round = false;
        [fractional, round] = this.roundFractionToPrecision(fractional, precision);
        if (round) {
            dig = (parseInt(dig) + 1).toString();
        }
        return this.padNum(`${dig}.${fractional}`, n < 0);
    }
    fmtFloatG(n, upcase = false) {
        const special = this.fmtFloatSpecial(n);
        if (special !== "") {
            return special;
        }
        let P = this.flags.precision !== -1 ? this.flags.precision : 6;
        P = P === 0 ? 1 : P;
        const m = n.toExponential().match(FLOAT_REGEXP);
        if (!m) {
            throw Error("can't happen");
        }
        const X = parseInt(m[F.exponent]) * (m[F.esign] === "-" ? -1 : 1);
        let nStr = "";
        if (P > X && X >= -4) {
            this.flags.precision = P - (X + 1);
            nStr = this.fmtFloatF(n);
            if (!this.flags.sharp) {
                nStr = nStr.replace(/\.?0*$/, "");
            }
        } else {
            this.flags.precision = P - 1;
            nStr = this.fmtFloatE(n);
            if (!this.flags.sharp) {
                nStr = nStr.replace(/\.?0*e/, upcase ? "E" : "e");
            }
        }
        return nStr;
    }
    fmtString(s) {
        if (this.flags.precision !== -1) {
            s = s.slice(0, this.flags.precision);
        }
        return this.pad(s);
    }
    fmtHex(val, upper = false) {
        switch(typeof val){
            case "number":
                return this.fmtNumber(val, 16, upper);
            case "string":
                {
                    const sharp = this.flags.sharp && val.length !== 0;
                    let hex = sharp ? "0x" : "";
                    const prec = this.flags.precision;
                    const end = prec !== -1 ? min(prec, val.length) : val.length;
                    for(let i1 = 0; i1 !== end; ++i1){
                        if (i1 !== 0 && this.flags.space) {
                            hex += sharp ? " 0x" : " ";
                        }
                        const c = (val.charCodeAt(i1) & 0xff).toString(16);
                        hex += c.length === 1 ? `0${c}` : c;
                    }
                    if (upper) {
                        hex = hex.toUpperCase();
                    }
                    return this.pad(hex);
                }
            default:
                throw new Error("currently only number and string are implemented for hex");
        }
    }
    fmtV(val) {
        if (this.flags.sharp) {
            const options = this.flags.precision !== -1 ? {
                depth: this.flags.precision
            } : {};
            return this.pad(Deno.inspect(val, options));
        } else {
            const p = this.flags.precision;
            return p === -1 ? val.toString() : val.toString().slice(0, p);
        }
    }
    fmtJ(val) {
        return JSON.stringify(val);
    }
    fmtI(val, compact) {
        return Deno.inspect(val, {
            colors: !Deno?.noColor,
            compact,
            depth: Infinity,
            iterableLimit: Infinity
        });
    }
}
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;
}
class InternalError extends Error {
    constructor(message, printName = true, printStack = true){
        super(message);
        this.name = "Internal Error";
        this.printName = printName;
        this.printStack = printStack;
    }
    printName;
    printStack;
}
class UnreachableError extends InternalError {
    constructor(){
        super("Unreachable code was reached.", true, true);
    }
}
class ErrorEx extends Error {
    constructor(name, message, printName = true, printStack = true){
        super(message);
        this.name = name;
        this.printName = printName;
        this.printStack = printStack;
    }
    printName;
    printStack;
}
function asErrorEx(e, defaultShowStack = true) {
    if (e instanceof ErrorEx) {
        return e;
    } else if (e instanceof Error) {
        e.printName = e.name !== "Error";
        e.printStack = defaultShowStack && !!e.message;
        return e;
    } else {
        return new ErrorEx("Error", String(e), false, true);
    }
}
let Deno3;
try {
    Deno3 = globalThis.Deno;
} catch (_e) {}
const noColor2 = typeof (Deno3 && Deno3.noColor) === "boolean" ? Deno3.noColor : true;
let enabled2 = !noColor2;
function code2(open, close) {
    return {
        open: `\x1b[${open.join(";")}m`,
        close: `\x1b[${close}m`,
        regexp: new RegExp(`\\x1b\\[${close}m`, "g")
    };
}
function run2(str, code) {
    return enabled2 ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str;
}
function red2(str) {
    return run2(str, code2([
        31
    ], 39));
}
function blue2(str) {
    return run2(str, code2([
        34
    ], 39));
}
const ANSI_PATTERN2 = 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 stripColor2(string) {
    return string.replace(ANSI_PATTERN2, "");
}
function platformHasNonAsciiCharacters() {
    try {
        return Deno.build.os !== "windows";
    } catch (_e) {
        return false;
    }
}
function tidyverseInfo(msg) {
    if (platformHasNonAsciiCharacters()) {
        return `${blue2("ℹ")} ${msg}`;
    } else {
        return `${blue2("i")} ${msg}`;
    }
}
function tidyverseError(msg) {
    if (platformHasNonAsciiCharacters()) {
        return `${red2("✖")} ${msg}`;
    } else {
        return `${red2("x")} ${msg}`;
    }
}
function tidyverseFormatError(msg) {
    let { heading, error, info } = msg;
    if (msg.location) {
        heading = `${locationString(msg.location)} ${heading}`;
    }
    if (msg.fileName) {
        heading = `In file ${msg.fileName}\n${heading}`;
    }
    const strings = [
        heading,
        msg.sourceContext,
        ...error.map(tidyverseError),
        ...Object.values(info).map(tidyverseInfo),
        ""
    ];
    return strings.join("\n");
}
function quotedStringColor(msg) {
    return blue2(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)=>blue2(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 trimEmptyLines(lines, trim = "all") {
    if (trim === "all" || trim === "leading") {
        const firstNonEmpty = lines.findIndex((line)=>line.trim().length > 0);
        if (firstNonEmpty === -1) {
            return [];
        }
        lines = lines.slice(firstNonEmpty);
    }
    if (trim === "all" || trim === "trailing") {
        let lastNonEmpty = -1;
        for(let i1 = lines.length - 1; i1 >= 0; i1--){
            if (lines[i1].trim().length > 0) {
                lastNonEmpty = i1;
                break;
            }
        }
        if (lastNonEmpty > -1) {
            lines = lines.slice(0, lastNonEmpty + 1);
        }
    }
    return lines;
}
function* matchAll(text, regexp) {
    if (!regexp.global) {
        throw new Error("matchAll requires global regexps");
    }
    let match;
    while((match = regexp.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 indexToLineCol(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 lineColToIndex(text) {
    const offsets = Array.from(lineOffsets(text));
    return function(position) {
        return offsets[position.line] + position.column;
    };
}
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 result1 = [];
    for(let i1 = firstLine; i1 <= lastLine; ++i1){
        const numberStr = `${pad}${i1 + 1}: `.slice(-(lineWidth + 2));
        const lineStr = ls[i1];
        result1.push({
            lineNumber: i1,
            content: numberStr + quotedStringColor(lineStr),
            rawLine: ls[i1]
        });
    }
    return {
        prefixWidth: lineWidth + 2,
        lines: result1
    };
}
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 i1 = 0; i1 < s1; ++i1){
        for(let j = 0; j < s2; ++j){
            if (i1 === 0 && j === 0) {
                continue;
            } else if (i1 === 0) {
                v[i1 * s2 + j] = v[i1 * s2 + (j - 1)] + cost(w2[j - 1]);
            } else if (j === 0) {
                v[i1 * s2 + j] = v[(i1 - 1) * s2 + j] + cost(w1[i1 - 1]);
            } else {
                v[i1 * s2 + j] = Math.min(v[(i1 - 1) * s2 + (j - 1)] + cost2(w1[i1 - 1], w2[j - 1]), v[i1 * s2 + (j - 1)] + cost(w2[j - 1]), v[(i1 - 1) * s2 + j] + cost(w1[i1 - 1]));
            }
        }
    }
    return v[(w1.length + 1) * (w2.length + 1) - 1];
}
function detectCaseConvention(key) {
    if (key.toLocaleLowerCase() !== key) {
        return "capitalizationCase";
    }
    const underscoreIndex = key.indexOf("_");
    if (underscoreIndex !== -1 && underscoreIndex !== 0 && underscoreIndex !== key.length - 1) {
        return "underscore_case";
    }
    const dashIndex = key.indexOf("-");
    if (dashIndex !== -1 && dashIndex !== 0 && dashIndex !== key.length - 1) {
        return "dash-case";
    }
    return undefined;
}
function resolveCaseConventionRegex(keys, conventions) {
    if (conventions !== undefined) {
        if (conventions.length === 0) {
            throw new InternalError("resolveCaseConventionRegex requires nonempty `conventions`");
        }
        return {
            pattern: conventions.map((c)=>`(${c})`).join("|"),
            list: conventions
        };
    }
    const disallowedNearMisses = [];
    const keySet = new Set(keys);
    const addNearMiss = (value)=>{
        if (!keySet.has(value)) {
            disallowedNearMisses.push(value);
        }
    };
    const foundConventions = new Set();
    for (const key of keys){
        const found = detectCaseConvention(key);
        if (found) {
            foundConventions.add(found);
        }
        switch(found){
            case "capitalizationCase":
                addNearMiss(toUnderscoreCase(key));
                addNearMiss(toDashCase(key));
                break;
            case "dash-case":
                addNearMiss(toUnderscoreCase(key));
                addNearMiss(toCapitalizationCase(key));
                break;
            case "underscore_case":
                addNearMiss(toDashCase(key));
                addNearMiss(toCapitalizationCase(key));
                break;
        }
    }
    if (foundConventions.size === 0) {
        return {
            pattern: undefined,
            list: []
        };
    }
    return {
        pattern: `(?!(${disallowedNearMisses.map((c)=>`^${c}$`).join("|")}))`,
        list: Array.from(foundConventions)
    };
}
function toDashCase(str) {
    return toUnderscoreCase(str).replace(/_/g, "-");
}
function toUnderscoreCase(str) {
    return str.replace(/([A-Z]+)/g, (_match, p1)=>`-${p1}`).replace(/-/g, "_").split("_").filter((x)=>x.length).join("_").toLocaleLowerCase();
}
function toCapitalizationCase(str) {
    return toUnderscoreCase(str).replace(/_(.)/g, (_match, p1)=>p1.toLocaleUpperCase());
}
function capitalizeWord(str) {
    return str.slice(0, 1).toUpperCase() + str.slice(1);
}
function capitalizeTitle(str) {
    return str.split(/\s+/).map((str, index, arr)=>{
        if (index === 0 || index === arr.length - 1 || !isNotCapitalized(str)) {
            return capitalizeWord(str);
        } else {
            return str;
        }
    }).join(" ");
}
function isNotCapitalized(str) {
    return [
        "a",
        "an",
        "the",
        "for",
        "and",
        "nor",
        "but",
        "or",
        "yet",
        "so",
        "with",
        "at",
        "by",
        "to",
        "in",
        "for",
        "from",
        "of",
        "on"
    ].includes(str);
}
const kLastPunctuationRegex = /([\S\s]*)[\.\?\!]/;
function trimSentence(text) {
    const match = text.match(kLastPunctuationRegex);
    if (match) {
        return {
            text: match[0],
            trimmed: true
        };
    } else {
        return {
            text,
            trimmed: false
        };
    }
}
function trimLength(text, length) {
    if (text.length < length) {
        return {
            text,
            trimmed: false
        };
    } else {
        return {
            text: text.substring(0, length),
            trimmed: true
        };
    }
}
function trimSpace(text) {
    const lastSpace = text.lastIndexOf(" ");
    if (lastSpace > 0) {
        return {
            text: text.substring(0, lastSpace),
            trimmed: true
        };
    } else {
        return {
            text,
            trimmed: false
        };
    }
}
function truncateText(text, length, breakAt) {
    const trimEnd = (text)=>{
        if ([
            ",",
            "/",
            ":"
        ].includes(text.charAt(text.length - 1))) {
            return text.substring(0, text.length - 1);
        } else {
            return text;
        }
    };
    const trimAtSpace = (text)=>{
        const spaceResult = trimSpace(text.substring(0, text.length - 1));
        return trimEnd(spaceResult.text) + "…";
    };
    const trimPunc = (text)=>{
        const puncResult = trimSentence(text);
        if (puncResult.trimmed) {
            return puncResult.text;
        } else {
            return trimAtSpace(puncResult.text);
        }
    };
    const lengthResult = trimLength(text, length);
    if (lengthResult.trimmed) {
        if (breakAt === "punctuation") {
            return trimPunc(lengthResult.text);
        } else {
            return trimAtSpace(lengthResult.text);
        }
    } else {
        return lengthResult.text;
    }
}
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 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)}`;
    }
}
let globalInternalIdCounter = 0;
function internalId() {
    return {
        _internalId: ++globalInternalIdCounter
    };
}
function tagSchema(schema, tags) {
    return {
        ...schema,
        tags: {
            ...schema.tags || {},
            ...tags
        }
    };
}
function anySchema(description) {
    return {
        ...internalId(),
        description,
        "type": "any"
    };
}
function enumSchema(...args) {
    if (args.length === 0) {
        throw new InternalError("Empty enum schema not supported.");
    }
    return {
        ...internalId(),
        "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 result1 = {
        ...internalId(),
        "type": "string",
        "pattern": arg
    };
    if (description) {
        result1.description = description;
    } else {
        result1.description = `be a string that satisfies regex "${arg}"`;
    }
    return result1;
}
function anyOfSchema(...args) {
    return {
        ...internalId(),
        "type": "anyOf",
        "anyOf": args,
        "description": `be at least one of: ${args.map((x)=>schemaDescription(x).slice(3)).join(", ")}`
    };
}
function allOfSchema(...args) {
    return {
        ...internalId(),
        "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, closed } = params;
    required = required || [];
    properties = properties || {};
    patternProperties = patternProperties || {};
    let tags = {};
    let tagsAreSet = false;
    let propertyNames = propertyNamesSchema;
    if (completionsParam) {
        tags["completions"] = completionsParam;
        tagsAreSet = true;
    }
    const createCaseConventionSchema = (props)=>{
        if (namingConvention === "ignore") {
            return undefined;
        }
        const objectKeys = Object.getOwnPropertyNames(props);
        const { pattern, list } = resolveCaseConventionRegex(objectKeys, namingConvention);
        if (pattern === undefined) {
            return undefined;
        }
        if (propertyNames !== undefined) {
            console.error("Warning: propertyNames and case convention detection are mutually exclusive.");
            console.error("Add `namingConvention: 'ignore'` to your schema definition to remove this warning.");
            return undefined;
        }
        const tags = {
            "case-convention": list,
            "error-importance": -5,
            "case-detection": true
        };
        return {
            errorMessage: "property ${value} does not match case convention " + `${objectKeys.join(",")}`,
            "type": "string",
            pattern,
            tags
        };
    };
    const hasDescription = description !== undefined;
    description = description || "be an object";
    let result1 = undefined;
    if (baseSchema) {
        if (!Array.isArray(baseSchema)) {
            baseSchema = [
                baseSchema
            ];
        }
        if (baseSchema.some((s)=>s.type !== "object")) {
            throw new InternalError("Attempted to extend a non-object schema");
        }
        if (baseSchema.length <= 0) {
            throw new InternalError("base schema cannot be empty list");
        }
        let temp = {
            ...internalId()
        };
        for (const base of baseSchema){
            temp = Object.assign(temp, base);
        }
        result1 = temp;
        if (result1 === undefined) {
            throw new UnreachableError();
        }
        if (result1.$id) {
            delete result1.$id;
        }
        for (const base of baseSchema){
            if (base.exhaustiveCompletions) {
                result1.exhaustiveCompletions = true;
            }
        }
        if (hasDescription) {
            result1.description = description;
        }
        const m = new Map();
        for (const base of baseSchema){
            for (const [k, v] of Object.entries(base.properties || {})){
                if (!m.has(k)) {
                    m.set(k, []);
                }
                m.get(k).push([
                    v,
                    base.$id
                ]);
            }
        }
        const errorMsgs = new Set();
        for (const [k, l1] of m){
            if (l1.length > 1) {
                errorMsgs.add(`Internal Error: base schemas ${l1.map((x)=>x[1]).join(", ")} share property ${k}.`);
            }
        }
        if (errorMsgs.size > 0) {
            console.error([
                ...errorMsgs
            ].toSorted((a, b)=>a.localeCompare(b)).join("\n"));
            console.error("This is a bug in quarto's schemas.");
            console.error("Note that we don't throw in order to allow build-js to finish, but the generated schemas will be invalid.");
        }
        result1.properties = Object.assign({}, ...baseSchema.map((s)=>s.properties), properties);
        result1.patternProperties = Object.assign({}, ...baseSchema.map((s)=>s.patternProperties).filter((s)=>s !== undefined), patternProperties);
        result1.required = [
            ...baseSchema.map((s)=>s.required || []),
            required || []
        ].flat();
        if (result1.required && result1.required.length === 0) {
            result1.required = undefined;
        }
        const additionalPropArray = baseSchema.map((s)=>s.additionalProperties).filter((s)=>s !== undefined);
        if (additionalProperties) {
            additionalPropArray.push(additionalProperties);
        }
        if (additionalPropArray.length) {
            result1.additionalProperties = allOfSchema(...additionalPropArray);
        }
        const propNamesArray = baseSchema.map((s)=>s.propertyNames).filter((s)=>{
            if (typeof s !== "object") return true;
            if (s.tags === undefined) return true;
            if (s.tags["case-detection"] === true) {
                return false;
            }
            return true;
        }).filter((s)=>s !== undefined);
        if (propNamesArray.length === 1) {
            result1.propertyNames = propNamesArray[0];
        } else if (propNamesArray.length > 1) {
            result1.propertyNames = anyOfSchema(...propNamesArray);
        } else {
            delete result1.propertyNames;
        }
        result1.closed = closed || baseSchema.some((s)=>s.closed);
    } else {
        const caseConventionSchema = createCaseConventionSchema(properties);
        if (caseConventionSchema !== undefined) {
            propertyNames = caseConventionSchema;
            tags = {
                ...tags,
                ...caseConventionSchema.tags
            };
            tagsAreSet = true;
        }
        result1 = {
            ...internalId(),
            "type": "object",
            description
        };
        if (exhaustive) {
            result1.exhaustiveCompletions = true;
        }
        if (properties) {
            result1.properties = properties;
        }
        if (patternProperties) {
            result1.patternProperties = patternProperties;
        }
        if (required && required.length > 0) {
            result1.required = required;
        }
        result1.closed = closed;
        if (additionalProperties !== undefined) {
            result1.additionalProperties = additionalProperties;
        }
        if (propertyNames !== undefined) {
            result1.propertyNames = propertyNames;
        }
    }
    if (tagsAreSet) {
        result1.tags = tags;
    }
    return result1;
}
function arraySchema(items) {
    if (items) {
        return {
            ...internalId(),
            "type": "array",
            "description": `be an array of values, where each element must ${schemaDescription(items)}`,
            items
        };
    } else {
        return {
            ...internalId(),
            "type": "array",
            "description": `be an array of values`
        };
    }
}
function documentSchema(schema, doc) {
    const result1 = Object.assign({}, schema);
    result1.documentation = doc;
    return result1;
}
function describeSchema(schema, description) {
    const result1 = Object.assign({}, schema);
    result1.description = `be ${description}`;
    return result1;
}
function completeSchema(schema, ...completions) {
    const result1 = Object.assign({}, schema);
    const prevCompletions = (schema.completions || []).slice();
    prevCompletions.push(...completions);
    result1.completions = prevCompletions;
    return result1;
}
function completeSchemaOverwrite(schema, ...completions) {
    const result1 = Object.assign({}, schema);
    result1.completions = completions;
    return result1;
}
function idSchema(schema, id) {
    const result1 = Object.assign({}, schema);
    result1["$id"] = id;
    return result1;
}
function errorMessageSchema(schema, errorMessage) {
    return {
        ...schema,
        errorMessage
    };
}
function refSchema($ref, description) {
    return {
        ...internalId(),
        "type": "ref",
        $ref,
        description
    };
}
function valueSchema(val, description) {
    return {
        ...internalId(),
        "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 InternalError(`Schema ${key} not found.`);
    }
    return definitionsObject[key];
}
function setSchemaDefinition(schema) {
    if (schema.$id === undefined) {
        throw new InternalError("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 result1 = [];
    lst = lst.slice();
    for(let i1 = 0; i1 < lst.length; ++i1){
        const el = lst[i1];
        if (el.startsWith("$")) {
            const v = aliases[el.slice(1)];
            if (v === undefined) {
                throw new InternalError(`${el} doesn't have an entry in the aliases map`);
            }
            lst.push(...v);
        } else {
            result1.push(el);
        }
    }
    return result1;
}
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 result1 = schemaCall(cursor, {
                ref: (s)=>getSchemaDefinition(s.$ref)
            });
            if (result1 === undefined) {
                throw new InternalError("couldn't resolve schema ${JSON.stringify(cursor)}");
            }
            return result1;
        };
    }
    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 matchAll1(str, regex) {
    let match;
    regex = new RegExp(regex);
    const result1 = [];
    while((match = regex.exec(str)) != null){
        result1.push(match);
    }
    return result1;
}
function rangedLines(text, includeNewLines = false) {
    const regex = /\r?\n/g;
    const result1 = [];
    let startOffset = 0;
    if (!includeNewLines) {
        for (const r of matchAll1(text, regex)){
            result1.push({
                substring: text.substring(startOffset, r.index),
                range: {
                    start: startOffset,
                    end: r.index
                }
            });
            startOffset = r.index + r[0].length;
        }
        result1.push({
            substring: text.substring(startOffset, text.length),
            range: {
                start: startOffset,
                end: text.length
            }
        });
        return result1;
    } else {
        const matches = matchAll1(text, regex);
        let prevOffset = 0;
        for (const r of matches){
            const stringEnd = r.index + r[0].length;
            result1.push({
                substring: text.substring(prevOffset, stringEnd),
                range: {
                    start: prevOffset,
                    end: stringEnd
                }
            });
            prevOffset = stringEnd;
        }
        result1.push({
            substring: text.substring(prevOffset, text.length),
            range: {
                start: prevOffset,
                end: text.length
            }
        });
        return result1;
    }
}
function mappedSubstring(source, start, end) {
    if (typeof source === "string") {
        source = asMappedString(source);
    }
    const value = source.value.substring(start, end);
    const mappedSource = source;
    return {
        value,
        fileName: mappedSource.fileName,
        map: (index, closest)=>{
            if (closest) {
                index = Math.max(0, Math.min(value.length, index - 1));
            }
            if (index === 0 && index === value.length) {
                return mappedSource.map(index + start, closest);
            }
            if (index < 0 || index >= value.length) {
                return undefined;
            }
            return mappedSource.map(index + start, closest);
        }
    };
}
function mappedString(source, pieces, fileName) {
    if (typeof source === "string") {
        source = asMappedString(source, fileName);
    }
    const mappedPieces = pieces.map((piece)=>{
        if (typeof piece === "string") {
            return asMappedString(piece);
        } else if (piece.value !== undefined) {
            return piece;
        } else {
            const { start, end } = piece;
            return mappedSubstring(source, start, end);
        }
    });
    return mappedConcat(mappedPieces);
}
function asMappedString(str, fileName) {
    if (typeof str === "string") {
        return {
            value: str,
            fileName,
            map: function(index, closest) {
                if (closest) {
                    index = Math.min(str.length - 1, Math.max(0, index));
                }
                if (index < 0 || index >= str.length) {
                    return undefined;
                }
                return {
                    index,
                    originalString: this
                };
            }
        };
    } else if (fileName !== undefined) {
        throw new InternalError("can't change the fileName of an existing MappedString");
    } else {
        return str;
    }
}
function mappedConcat(strings) {
    if (strings.length === 0) {
        return {
            value: "",
            map: (_index, _closest)=>undefined
        };
    }
    if (strings.every((s)=>typeof s === "string")) {
        return asMappedString(strings.join(""));
    }
    const mappedStrings = strings.map((s)=>{
        if (typeof s === "string") {
            return asMappedString(s);
        } else return s;
    });
    let currentOffset = 0;
    const offsets = [
        0
    ];
    for (const s of mappedStrings){
        currentOffset += s.value.length;
        offsets.push(currentOffset);
    }
    const value = mappedStrings.map((s)=>s.value).join("");
    return {
        value,
        map: (offset, closest)=>{
            if (closest) {
                offset = Math.max(0, Math.min(offset, value.length - 1));
            }
            if (offset === 0 && offset == value.length && mappedStrings.length) {
                return mappedStrings[0].map(0, closest);
            }
            if (offset < 0 || offset >= value.length) {
                return undefined;
            }
            const ix = glb(offsets, offset);
            const v = mappedStrings[ix];
            return v.map(offset - offsets[ix]);
        }
    };
}
function mappedIndexToLineCol(eitherText) {
    const text = asMappedString(eitherText);
    return function(offset) {
        const mapResult = text.map(offset, true);
        if (mapResult === undefined) {
            throw new InternalError("bad offset in mappedIndexRowCol");
        }
        const { index, originalString } = mapResult;
        return indexToLineCol(originalString.value)(index);
    };
}
function join3(mappedStrs, sep) {
    const innerStrings = [];
    const mappedSep = asMappedString(sep);
    for(let i1 = 0; i1 < mappedStrs.length; ++i1){
        const mappedStr = mappedStrs[i1];
        if (typeof mappedStr === "string") {
            innerStrings.push(asMappedString(mappedStr));
        } else {
            innerStrings.push(mappedStr);
        }
        if (i1 < mappedStrs.length) {
            innerStrings.push(mappedSep);
        }
    }
    return mappedConcat(innerStrings);
}
function mappedLines(str, keepNewLines = false) {
    const lines = rangedLines(str.value, keepNewLines);
    return lines.map((v)=>mappedString(str, [
            v.range
        ]));
}
function findSpaceStart(string) {
    const result1 = string.value.match(/^\s+/);
    if (result1 === null || result1.length === 0) {
        return 0;
    }
    return result1[0].length;
}
function findSpaceEnd(string) {
    const result1 = string.value.match(/\s+$/);
    if (result1 === null || result1.length === 0) {
        return 0;
    }
    return result1[0].length;
}
function mappedTrim(string) {
    const start = findSpaceStart(string);
    const end = findSpaceEnd(string);
    if (start === 0 && end === 0) {
        return string;
    }
    if (start > string.value.length - end) {
        return mappedSubstring(string, 0, 0);
    }
    return mappedSubstring(string, start, string.value.length - end);
}
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");
function navigateSchemaBySchemaPathSingle(schema, path) {
    const ensurePathFragment = (fragment, expected)=>{
        if (fragment !== expected) {
            throw new InternalError(`navigateSchemaBySchemaPathSingle: ${fragment} !== ${expected}`);
        }
    };
    const inner = (subschema, index)=>{
        subschema = resolveSchema(subschema);
        if (subschema === undefined) {
            throw new InternalError(`navigateSchemaBySchemaPathSingle: invalid path navigation`);
        }
        if (index === path.length) {
            return subschema;
        }
        const st = schemaType(subschema);
        switch(st){
            case "anyOf":
                ensurePathFragment(path[index], "anyOf");
                return inner(subschema.anyOf[path[index + 1]], index + 2);
            case "allOf":
                ensurePathFragment(path[index], "allOf");
                return inner(subschema.allOf[path[index + 1]], index + 2);
            case "array":
                ensurePathFragment(path[index], "array");
                return inner(subschema.arrayOf.schema, index + 2);
            case "object":
                ensurePathFragment(path[index], "object");
                if (path[index + 1] === "properties") {
                    return inner(subschema.properties[path[index + 2]], index + 3);
                } else if (path[index + 1] === "patternProperties") {
                    return inner(subschema.patternProperties[path[index + 2]], index + 3);
                } else if (path[index + 1] === "additionalProperties") {
                    return inner(subschema.additionalProperties, index + 2);
                } else {
                    throw new InternalError(`navigateSchemaBySchemaPathSingle: bad path fragment ${path[index]} in object navigation`);
                }
            default:
                throw new InternalError(`navigateSchemaBySchemaPathSingle: can't navigate schema type ${st}`);
        }
    };
    return inner(schema, 0);
}
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 schemaCompletions(s) {
    if (s === true || s === false) {
        return [];
    }
    let schema = resolveSchema(s);
    schema = resolveSchema(schema, (_schema)=>{}, (schema)=>{
        return schema.tags !== undefined && schema.tags["complete-from"] !== undefined;
    }, (schema)=>{
        return navigateSchemaBySchemaPathSingle(schema, schema.tags["complete-from"]);
    });
    if (schema === true || schema === false) {
        return [];
    }
    const normalize = (completions)=>{
        const result1 = (completions || []).map((c)=>{
            if (typeof c === "string") {
                return {
                    type: "value",
                    display: c,
                    value: c,
                    description: "",
                    suggest_on_accept: false,
                    schema
                };
            }
            return {
                ...c,
                description: resolveDescription(c.description),
                schema
            };
        });
        return result1;
    };
    if (schema.completions && schema.completions.length) {
        return normalize(schema.completions);
    }
    if (schema.tags && schema.tags.completions) {
        if (Array.isArray(schema.tags.completions) && schema.tags.completions.length) {
            return normalize(schema.tags.completions);
        } else {
            return normalize(Object.values(schema.tags.completions));
        }
    }
    return schemaCall(schema, {
        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 normalize(s.cachedCompletions);
        }
    }, (_)=>[]);
}
function getObjectCompletions(s) {
    const completionsParam = s.tags && s.tags.completions || [];
    return schemaCall(s, {
        "object": (schema)=>{
            const properties = schema.properties;
            const objectKeys = completionsParam.length ? completionsParam : Object.getOwnPropertyNames(properties);
            const completions = [];
            for (const k of objectKeys){
                const schema = properties && properties[k];
                const maybeDescriptions = [];
                let hidden = false;
                if (schema !== undefined && schema !== true && schema !== false) {
                    if (schema.documentation) {
                        maybeDescriptions.push(schemaDocString(schema.documentation));
                    } else {
                        let described = false;
                        const visitor = (schema)=>{
                            if (schema === false || schema === true) {
                                return;
                            }
                            if (schema.hidden) {
                                hidden = true;
                            }
                            if (described) {
                                return;
                            }
                            if (schema.documentation) {
                                maybeDescriptions.push(schemaDocString(schema.documentation));
                                described = true;
                            }
                        };
                        try {
                            resolveSchema(schema, visitor);
                        } catch (_e) {}
                        if (!described) {
                            schemaDispatch(schema, {
                                ref: (schema)=>maybeDescriptions.push({
                                        $ref: schema.$ref
                                    })
                            });
                        }
                    }
                }
                if (hidden) {
                    continue;
                }
                let description = "";
                for (const md of maybeDescriptions){
                    if (md !== undefined) {
                        description = md;
                        break;
                    }
                }
                completions.push({
                    type: "key",
                    display: "",
                    value: `${k}: `,
                    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 setDefaultErrorHandlers(validator) {
    validator.addHandler(ignoreExprViolations);
    validator.addHandler(expandEmptySpan);
    validator.addHandler(improveErrorHeadingForValueErrors);
    validator.addHandler(checkForTypeMismatch);
    validator.addHandler(checkForBadBoolean);
    validator.addHandler(checkForBadColon);
    validator.addHandler(checkForBadEquals);
    validator.addHandler(identifyKeyErrors);
    validator.addHandler(checkForNearbyCorrection);
    validator.addHandler(checkForNearbyRequired);
    validator.addHandler(schemaDefinedErrors);
}
function errorKeyword(error) {
    if (error.schemaPath.length === 0) {
        return "";
    }
    return String(error.schemaPath[error.schemaPath.length - 1]);
}
function schemaPathMatches(error, strs) {
    const schemaPath = error.schemaPath.slice(-strs.length);
    if (schemaPath.length !== strs.length) {
        return false;
    }
    return strs.every((str, i1)=>str === schemaPath[i1]);
}
function getBadKey(error) {
    if (error.schemaPath.indexOf("propertyNames") === -1 && error.schemaPath.indexOf("closed") === -1) {
        return undefined;
    }
    const result1 = error.violatingObject.result;
    if (typeof result1 !== "string") {
        throw new InternalError("propertyNames error has a violating non-string.");
    }
    return result1;
}
function getVerbatimInput(error) {
    return error.source.value;
}
function navigate(path, annotation, returnKey = false, pathIndex = 0) {
    if (annotation === undefined) {
        throw new Error("Can't navigate an undefined annotation");
    }
    if (pathIndex >= path.length) {
        return annotation;
    }
    if (annotation.kind === "mapping" || annotation.kind === "block_mapping") {
        const { components } = annotation;
        const searchKey = path[pathIndex];
        const lastKeyIndex = ~~((components.length - 1) / 2) * 2;
        for(let i1 = lastKeyIndex; i1 >= 0; i1 -= 2){
            const key = components[i1].result;
            if (key === searchKey) {
                if (returnKey && pathIndex === path.length - 1) {
                    return navigate(path, components[i1], returnKey, pathIndex + 1);
                } else {
                    return navigate(path, components[i1 + 1], returnKey, pathIndex + 1);
                }
            }
        }
        return annotation;
    } else if ([
        "sequence",
        "block_sequence",
        "flow_sequence"
    ].indexOf(annotation.kind) !== -1) {
        const searchKey = Number(path[pathIndex]);
        if (isNaN(searchKey) || searchKey < 0 || searchKey >= annotation.components.length) {
            return annotation;
        }
        return navigate(path, annotation.components[searchKey], returnKey, pathIndex + 1);
    } else {
        return annotation;
    }
}
function isEmptyValue(error) {
    const rawVerbatimInput = getVerbatimInput(error);
    return rawVerbatimInput.trim().length === 0;
}
function getLastFragment(instancePath) {
    if (instancePath.length === 0) {
        return undefined;
    }
    return instancePath[instancePath.length - 1];
}
function reindent(str) {
    const s = new Set();
    const ls = lines(str);
    for (const l1 of ls){
        const r = l1.match("^[ ]+");
        if (r) {
            s.add(r[0].length);
        }
    }
    if (s.size === 0) {
        return str;
    } else if (s.size === 1) {
        const v = Array.from(s)[0];
        const oldIndent = " ".repeat(v);
        if (v <= 2) {
            return str;
        }
        return ls.map((l1)=>l1.startsWith(oldIndent) ? l1.slice(v - 2) : l1).join("\n");
    } else {
        const [first, second] = Array.from(s);
        const oldIndent = " ".repeat(first);
        const newIndent = second - first;
        if (newIndent >= first) {
            return str;
        }
        return ls.map((l1)=>l1.startsWith(oldIndent) ? l1.slice(first - newIndent) : l1).join("\n");
    }
}
function ignoreExprViolations(error, _parse, _schema) {
    const { result: result1 } = error.violatingObject;
    if (typeof result1 !== "object" || Array.isArray(result1) || result1 === null || error.schemaPath.slice(-1)[0] !== "type") {
        return error;
    }
    if (result1.tag === "!expr" && typeof result1.value === "string") {
        return null;
    } else {
        return error;
    }
}
function formatHeadingForKeyError(_error, _parse, _schema, key) {
    return `property name ${blue2(key)} is invalid`;
}
function formatHeadingForValueError(error, _parse, _schema) {
    const rawVerbatimInput = reindent(getVerbatimInput(error));
    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 empty = isEmptyValue(error);
    const lastFragment = getLastFragment(error.instancePath);
    switch(typeof lastFragment){
        case "undefined":
            if (empty) {
                return "YAML value is missing.";
            } else {
                return `YAML value ${verbatimInput} must ${schemaDescription(error.schema)}.`;
            }
        case "number":
            if (empty) {
                return `Array entry ${lastFragment + 1} is empty but it must instead ${schemaDescription(error.schema)}.`;
            } else {
                return `Array entry ${lastFragment + 1} with value ${verbatimInput} failed to ${schemaDescription(error.schema)}.`;
            }
        case "string":
            {
                const formatLastFragment = '"' + blue2(lastFragment) + '"';
                if (empty) {
                    return `Field ${formatLastFragment} has empty value but it must instead ${schemaDescription(error.schema)}`;
                } else {
                    if (verbatimInput.indexOf("\n") !== -1) {
                        return `Field ${formatLastFragment} has value

${verbatimInput}

The value must instead ${schemaDescription(error.schema)}.`;
                    } else {
                        return `Field ${formatLastFragment} has value ${verbatimInput}, which must instead ${schemaDescription(error.schema)}`;
                    }
                }
            }
    }
}
function identifyKeyErrors(error, parse, schema) {
    if (error.schemaPath.indexOf("propertyNames") === -1 && error.schemaPath.indexOf("closed") === -1) {
        return error;
    }
    const badKey = getBadKey(error);
    if (badKey) {
        if (error.instancePath.length && error.instancePath[error.instancePath.length - 1] !== badKey) {
            addInstancePathInfo(error.niceError, [
                ...error.instancePath,
                badKey
            ]);
        } else {
            addInstancePathInfo(error.niceError, error.instancePath);
        }
        error.niceError.heading = formatHeadingForKeyError(error, parse, schema, badKey);
    }
    return error;
}
function improveErrorHeadingForValueErrors(error, parse, schema) {
    if (error.schemaPath.indexOf("propertyNames") !== -1 || error.schemaPath.indexOf("closed") !== -1 || errorKeyword(error) === "required") {
        return error;
    }
    return {
        ...error,
        niceError: {
            ...error.niceError,
            heading: formatHeadingForValueError(error, parse, schema)
        }
    };
}
function expandEmptySpan(error, parse, _schema) {
    if (error.location.start.line !== error.location.end.line || error.location.start.column !== error.location.end.column || !isEmptyValue(error) || typeof getLastFragment(error.instancePath) === "undefined") {
        return error;
    }
    const lastKey = navigate(error.instancePath, parse, true);
    const locF = mappedIndexToLineCol(parse.source);
    try {
        const location = {
            start: locF(lastKey.start),
            end: locF(lastKey.end)
        };
        return {
            ...error,
            location,
            niceError: {
                ...error.niceError,
                location
            }
        };
    } catch (_e) {
        return error;
    }
}
function checkForTypeMismatch(error, parse, schema) {
    const rawVerbatimInput = getVerbatimInput(error);
    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(error) === "type" && rawVerbatimInput.length > 0) {
        const reindented = reindent(verbatimInput);
        const subject = reindented.indexOf("\n") === -1 ? `The value ${reindented} ` : `The value

${reindented}

`;
        const newError = {
            ...error.niceError,
            heading: formatHeadingForValueError(error, parse, schema),
            error: [
                `${subject}is of type ${goodType(error.violatingObject.result)}.`
            ],
            info: {},
            location: error.niceError.location
        };
        addInstancePathInfo(newError, error.instancePath);
        addFileInfo(newError, error.source);
        return {
            ...error,
            niceError: newError
        };
    }
    return error;
}
function checkForBadBoolean(error, parse, _schema) {
    const schema = error.schema;
    if (!(typeof error.violatingObject.result === "string" && errorKeyword(error) === "type" && schemaType(schema) === "boolean")) {
        return error;
    }
    const strValue = error.violatingObject.result;
    const verbatimInput = quotedStringColor(getVerbatimInput(error));
    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 error;
    }
    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(error, parse, schema),
        error: [
            errorMessage
        ],
        info: {},
        location: error.niceError.location
    };
    addInstancePathInfo(newError, error.instancePath);
    addFileInfo(newError, error.source);
    newError.info["yaml-version-1.2"] = suggestion1;
    newError.info["suggestion-fix"] = suggestion2;
    return {
        ...error,
        niceError: newError
    };
}
function checkForBadColon(error, parse, schema) {
    if (typeof error.violatingObject.result !== "string") {
        return error;
    }
    if (!schemaPathMatches(error, [
        "object",
        "type"
    ])) {
        return error;
    }
    if (!error.violatingObject.result.match(/^.+:[^ ].*$/)) {
        return error;
    }
    const verbatimInput = quotedStringColor(getVerbatimInput(error));
    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(error)).replace(/:/g, ": "))} instead?`;
    const newError = {
        heading: formatHeadingForValueError(error, parse, schema),
        error: [
            errorMessage
        ],
        info: {},
        location: error.niceError.location
    };
    addInstancePathInfo(newError, error.instancePath);
    addFileInfo(newError, error.source);
    newError.info["yaml-key-value-pairs"] = suggestion1;
    newError.info["suggestion-fix"] = suggestion2;
    return {
        ...error,
        niceError: newError
    };
}
function checkForBadEquals(error, parse, schema) {
    if (typeof error.violatingObject.result !== "string") {
        return error;
    }
    if (!schemaPathMatches(error, [
        "object",
        "type"
    ]) && !schemaPathMatches(error, [
        "object",
        "propertyNames",
        "string",
        "pattern"
    ])) {
        return error;
    }
    if (!error.violatingObject.result.match(/^.+ *= *.+$/)) {
        return error;
    }
    const verbatimInput = quotedStringColor(getVerbatimInput(error));
    const errorMessage = `The value ${verbatimInput} is a string.`;
    const suggestion1 = `In YAML, key-value pairs in objects must be separated by a colon and a space.`;
    const suggestion2 = `Did you mean ${quotedStringColor(quotedStringColor(getVerbatimInput(error)).replace(/ *= */g, ": "))} instead?`;
    const newError = {
        heading: formatHeadingForValueError(error, parse, schema),
        error: [
            errorMessage
        ],
        info: {},
        location: error.niceError.location
    };
    addInstancePathInfo(newError, error.instancePath);
    addFileInfo(newError, error.source);
    newError.info["yaml-key-value-pairs"] = suggestion1;
    newError.info["suggestion-fix"] = suggestion2;
    return {
        ...error,
        niceError: newError
    };
}
function createErrorFragments(error) {
    const rawVerbatimInput = getVerbatimInput(error);
    const verbatimInput = quotedStringColor(reindent(rawVerbatimInput));
    const pathFragments = error.instancePath.map((s)=>blue2(String(s)));
    return {
        location: locationString(error.location),
        fullPath: pathFragments.join(":"),
        key: pathFragments[pathFragments.length - 1],
        value: verbatimInput
    };
}
function schemaDefinedErrors(error, _parse, _schema) {
    const schema = error.schema;
    if (schema === true || schema === false) {
        return error;
    }
    if (schema.errorMessage === undefined) {
        return error;
    }
    if (typeof schema.errorMessage !== "string") {
        return error;
    }
    let result1 = schema.errorMessage;
    for (const [k, v] of Object.entries(createErrorFragments(error))){
        result1 = result1.replace("${" + k + "}", v);
    }
    return {
        ...error,
        niceError: {
            ...error.niceError,
            heading: result1
        }
    };
}
function checkForNearbyRequired(error, _parse, _schema) {
    const schema = error.schema;
    if (errorKeyword(error) !== "required") {
        return error;
    }
    const missingKeys = [];
    const errObj = error.violatingObject.result;
    const keys = Object.keys(errObj);
    schemaCall(schema, {
        object (s) {
            if (s.required === undefined) {
                throw new InternalError("required schema error without a required field");
            }
            for (const r of s.required){
                if (keys.indexOf(r) === -1) {
                    missingKeys.push(r);
                }
            }
        }
    }, (_)=>{
        throw new InternalError("required error on a non-object schema");
    });
    for (const missingKey of missingKeys){
        let bestCorrection;
        let bestDistance = Infinity;
        for (const correction of keys){
            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)=>blue2(s));
        if (suggestions.length === 1) {
            error.niceError.info[`did-you-mean-key`] = `Is ${suggestions[0]} a typo of ${blue2(missingKey)}?`;
        } else if (suggestions.length === 2) {
            error.niceError.info[`did-you-mean-key`] = `Is ${suggestions[0]} or ${suggestions[1]} a typo of ${blue2(missingKey)}?`;
        } else {
            suggestions[suggestions.length - 1] = `or ${suggestions[suggestions.length - 1]}`;
            error.niceError.info[`did-you-mean-key`] = `Is one of ${suggestions.join(", ")} a typo of ${blue2(missingKey)}?`;
        }
    }
    return error;
}
function checkForNearbyCorrection(error, parse, _schema) {
    const schema = error.schema;
    const corrections = [];
    let errVal = "";
    let keyOrValue = "";
    const key = getBadKey(error);
    if (key) {
        errVal = key;
        corrections.push(...possibleSchemaKeys(schema));
        keyOrValue = "key";
    } else {
        const val = navigate(error.instancePath, parse);
        if (typeof val.result !== "string") {
            return error;
        }
        errVal = val.result;
        corrections.push(...possibleSchemaValues(schema));
        keyOrValue = "value";
    }
    if (corrections.length === 0) {
        return error;
    }
    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 error;
    }
    const suggestions = bestCorrection.map((s)=>blue2(s));
    if (suggestions.length === 1) {
        error.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions[0]}?`;
    } else if (suggestions.length === 2) {
        error.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions[0]} or ${suggestions[1]}?`;
    } else {
        suggestions[suggestions.length - 1] = `or ${suggestions[suggestions.length - 1]}`;
        error.niceError.info[`did-you-mean-${keyOrValue}`] = `Did you mean ${suggestions.join(", ")}?`;
    }
    return error;
}
function createSourceContext(src, location) {
    if (src.value.length === 0) {
        return "";
    }
    const startMapResult = src.map(location.start, true);
    const endMapResult = src.map(location.end, true);
    const locF = mappedIndexToLineCol(src);
    let sourceLocation;
    try {
        sourceLocation = {
            start: locF(location.start),
            end: locF(location.end)
        };
    } catch (_e) {
        sourceLocation = {
            start: {
                line: 0,
                column: 0
            },
            end: {
                line: 0,
                column: 0
            }
        };
    }
    if (startMapResult === undefined || endMapResult === undefined) {
        throw new InternalError(`createSourceContext called with bad location ${location.start}-${location.end}.`);
    }
    if (startMapResult.originalString !== endMapResult.originalString) {
        throw new InternalError("don't know how to create source context across different source files");
    }
    const originalString = startMapResult.originalString;
    const nLines = lines(originalString.value).length;
    const { start, end } = sourceLocation;
    const { prefixWidth, lines: formattedLines } = formatLineRange(originalString.value, 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 - 1) + "~".repeat(endColumn - startColumn + 1));
            }
        }
    }
    return contextLines.join("\n");
}
function createLocalizedError(obj) {
    const { violatingObject, instancePath, schemaPath, source, message, schema } = obj;
    const locF = mappedIndexToLineCol(source);
    let location;
    try {
        location = {
            start: locF(violatingObject.start),
            end: locF(violatingObject.end)
        };
    } catch (_e) {
        location = {
            start: {
                line: 0,
                column: 0
            },
            end: {
                line: 0,
                column: 0
            }
        };
    }
    const mapResult = source.map(violatingObject.start);
    const fileName = mapResult ? mapResult.originalString.fileName : undefined;
    return {
        source: mappedString(source, [
            {
                start: violatingObject.start,
                end: violatingObject.end
            }
        ]),
        violatingObject: violatingObject,
        instancePath,
        schemaPath,
        schema,
        message,
        location: location,
        niceError: {
            heading: message,
            error: [],
            info: {},
            fileName,
            location: location,
            sourceContext: createSourceContext(violatingObject.source, {
                start: violatingObject.start,
                end: violatingObject.end
            })
        }
    };
}
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 result1 = [];
            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("propertyNames") !== -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 (typeof e.schema === "object") {
                        if (e.schema.tags && e.schema.tags["error-importance"] && typeof e.schema.tags["error-importance"] === "number") {
                            return e.schema.tags["error-importance"];
                        }
                    }
                    if (e.schemaPath.indexOf("propertyNames") !== -1) {
                        return 10;
                    }
                    if (t[0] === "required") {
                        return 0;
                    }
                    if (t[0] === "type") {
                        if (t[1] === "null") {
                            return 10;
                        }
                        return 1;
                    }
                    return 1;
                };
                const errorComparator = (a, b)=>{
                    for(let i1 = 0; i1 < a.length; ++i1){
                        if (a[i1] < b[i1]) {
                            return -1;
                        }
                        if (a[i1] > b[i1]) {
                            return 1;
                        }
                    }
                    return 0;
                };
                let bestResults = [];
                let bestError = [
                    Infinity,
                    Infinity
                ];
                for (const resultGroup of innerResults){
                    let maxQuality = -Infinity;
                    let totalSpan = 0;
                    for (const result1 of resultGroup){
                        totalSpan += result1.value.end - result1.value.start;
                        maxQuality = Math.max(maxQuality, errorTypeQuality(result1));
                    }
                    const thisError = [
                        maxQuality,
                        totalSpan
                    ];
                    if (errorComparator(thisError, bestError) === -1) {
                        bestError = thisError;
                        bestResults = resultGroup;
                    }
                }
                return bestResults;
            } else {
                result1.push(...node.errors);
                for (const child of node.children){
                    result1.push(...inner(child));
                }
                return result1;
            }
        };
        const errors = inner(this.root);
        const result1 = errors.map((validationError)=>createLocalizedError({
                violatingObject: validationError.value,
                instancePath: validationError.instancePath,
                schemaPath: validationError.schemaPath,
                schema: validationError.schema,
                message: validationError.message,
                source
            }));
        return result1;
    }
}
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,
            "any": (schema)=>validateAny(value, schema, context),
            "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 validateAny(_value, _schema, _context) {
    return true;
}
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 result1 = true;
    if (schema.minimum !== undefined) {
        result1 = 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) {
        result1 = 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) {
        result1 = 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) {
        result1 = 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 result1;
}
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 i1 = 0; i1 < schema.anyOf.length; ++i1){
        const subSchema = schema.anyOf[i1];
        context.withSchemaPath(i1, ()=>{
            if (validateGeneric(value, subSchema, context)) {
                passingSchemas++;
                return true;
            }
            return false;
        });
    }
    return passingSchemas > 0;
}
function validateAllOf(value, schema, context) {
    let passingSchemas = 0;
    for(let i1 = 0; i1 < schema.allOf.length; ++i1){
        const subSchema = schema.allOf[i1];
        context.withSchemaPath(i1, ()=>{
            if (validateGeneric(value, subSchema, context)) {
                passingSchemas++;
                return true;
            }
            return false;
        });
    }
    return passingSchemas === schema.allOf.length;
}
function validateArray(value, schema, context) {
    let result1 = 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;
        });
        result1 = 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;
        });
        result1 = false;
    }
    if (schema.items !== undefined) {
        result1 = context.withSchemaPath("items", ()=>{
            let result1 = true;
            for(let i1 = 0; i1 < value.components.length; ++i1){
                context.pushInstance(i1);
                result1 = validateGeneric(value.components[i1], schema.items, context) && result1;
                context.popInstance();
            }
            return result1;
        }) && result1;
    }
    return result1;
}
function validateObject(value, schema, context) {
    const isObject = typeof value.result === "object" && !Array.isArray(value.result) && value.result !== null;
    if (!typeIsValid(value, schema, context, isObject)) {
        return false;
    }
    let result1 = true;
    const ownProperties = new Set(Object.getOwnPropertyNames(value.result));
    const objResult = value.result;
    const locate = (key, keyOrValue = "value")=>{
        for(let i1 = 0; i1 < value.components.length; i1 += 2){
            if (String(value.components[i1].result) === key) {
                if (keyOrValue === "value") {
                    return value.components[i1 + 1];
                } else {
                    return value.components[i1];
                }
            }
        }
        throw new InternalError(`Couldn't locate key ${key}`);
    };
    const inspectedProps = new Set();
    if (schema.closed) {
        result1 = context.withSchemaPath("closed", ()=>{
            if (schema.properties === undefined) {
                throw new InternalError("Closed schemas need properties");
            }
            let innerResult = true;
            for (const key of ownProperties){
                if (!schema.properties[key]) {
                    context.error(locate(key, "key"), schema, `object has invalid field ${key}`);
                    innerResult = false;
                }
            }
            return innerResult;
        }) && result1;
    }
    if (schema.properties !== undefined) {
        result1 = context.withSchemaPath("properties", ()=>{
            let result1 = true;
            for (const [key, subSchema] of Object.entries(schema.properties)){
                if (ownProperties.has(key)) {
                    inspectedProps.add(key);
                    context.pushInstance(key);
                    result1 = context.withSchemaPath(key, ()=>validateGeneric(locate(key), subSchema, context)) && result1;
                    context.popInstance();
                }
            }
            return result1;
        }) && result1;
    }
    if (schema.patternProperties !== undefined) {
        result1 = context.withSchemaPath("patternProperties", ()=>{
            let result1 = 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 regexp = schema.compiledPatterns[key];
                for (const [objectKey, _val] of Object.entries(objResult)){
                    if (objectKey.match(regexp)) {
                        inspectedProps.add(objectKey);
                        context.pushInstance(objectKey);
                        result1 = context.withSchemaPath(key, ()=>validateGeneric(locate(objectKey), subSchema, context)) && result1;
                        context.popInstance();
                    }
                }
            }
            return result1;
        }) && result1;
    }
    if (schema.additionalProperties !== undefined) {
        result1 = context.withSchemaPath("additionalProperties", ()=>{
            return Object.keys(objResult).filter((objectKey)=>!inspectedProps.has(objectKey)).every((objectKey)=>validateGeneric(locate(objectKey), schema.additionalProperties, context));
        }) && result1;
    }
    if (schema.propertyNames !== undefined) {
        result1 = context.withSchemaPath("propertyNames", ()=>{
            return Array.from(ownProperties).every((key)=>validateGeneric(locate(key, "key"), schema.propertyNames, context));
        }) && result1;
    }
    if (schema.required !== undefined) {
        result1 = context.withSchemaPath("required", ()=>{
            let result1 = true;
            for (const reqKey of schema.required){
                if (!ownProperties.has(reqKey)) {
                    context.error(value, schema, `object is missing required property ${reqKey}`);
                    result1 = false;
                }
            }
            return result1;
        }) && result1;
    }
    return result1;
}
function validate(value, schema, source, pruneErrors = true) {
    const context = new ValidationContext();
    return context.validate(schema, source, value, pruneErrors);
}
class YAMLSchema {
    schema;
    errorHandlers;
    constructor(schema){
        this.errorHandlers = [];
        this.schema = schema;
    }
    addHandler(handler) {
        this.errorHandlers.push(handler);
    }
    transformErrors(annotation, errors) {
        return errors.map((error)=>{
            for (const handler of this.errorHandlers){
                const localError = handler(error, annotation, this.schema);
                if (localError === null) {
                    return null;
                }
                error = localError;
            }
            return error;
        }).filter((error)=>error !== null);
    }
    async validateParse(src, annotation, pruneErrors = true) {
        const validationErrors = validate(annotation, this.schema, src, pruneErrors);
        if (validationErrors.length) {
            const localizedErrors = this.transformErrors(annotation, validationErrors);
            return {
                result: annotation.result,
                errors: localizedErrors
            };
        } else {
            return {
                result: annotation.result,
                errors: []
            };
        }
    }
    reportErrorsInSource(result1, _src, message, error, log) {
        if (result1.errors.length) {
            if (message.length) {
                error(message);
            }
            for (const err of result1.errors){
                log(err.niceError);
            }
        }
        return result1;
    }
    async validateParseWithErrors(src, annotation, message, error, log) {
        const result1 = await this.validateParse(src, annotation);
        this.reportErrorsInSource(result1, src, message, error, log);
        return result1;
    }
}
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 result1;
    let error;
    try {
        const validator = getValidator(schema);
        result1 = await fun(validator);
    } catch (e) {
        error = e;
    }
    if (error !== undefined) {
        throw error;
    }
    return result1;
}
function addValidatorErrorHandler(schema, handler) {
    return withValidator(schema, async (validator)=>{
        validator.addHandler(handler);
    });
}
function memoize1(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 globToRegExp3(glob, { extended = true, globstar: globstarOption = true, caseInsensitive = false } = {}) {
    if (glob == "") {
        return /(?!)/;
    }
    const sep = "/+";
    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 i1 = j;
        for(; i1 < glob.length && !seps.includes(glob[i1]); i1++){
            if (inEscape) {
                inEscape = false;
                const escapeChars = inRange ? rangeEscapeChars1 : regExpEscapeChars1;
                segment += escapeChars.includes(glob[i1]) ? `\\${glob[i1]}` : glob[i1];
                continue;
            }
            if (glob[i1] == escapePrefix) {
                inEscape = true;
                continue;
            }
            if (glob[i1] == "[") {
                if (!inRange) {
                    inRange = true;
                    segment += "[";
                    if (glob[i1 + 1] == "!") {
                        i1++;
                        segment += "^";
                    } else if (glob[i1 + 1] == "^") {
                        i1++;
                        segment += "\\^";
                    }
                    continue;
                } else if (glob[i1 + 1] == ":") {
                    let k = i1 + 1;
                    let value = "";
                    while(glob[k + 1] != null && glob[k + 1] != ":"){
                        value += glob[k + 1];
                        k++;
                    }
                    if (glob[k + 1] == ":" && glob[k + 2] == "]") {
                        i1 = 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[i1] == "]" && inRange) {
                inRange = false;
                segment += "]";
                continue;
            }
            if (inRange) {
                if (glob[i1] == "\\") {
                    segment += `\\\\`;
                } else {
                    segment += glob[i1];
                }
                continue;
            }
            if (glob[i1] == ")" && 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[i1] == "|" && groupStack.length > 0 && groupStack[groupStack.length - 1] != "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i1] == "+" && extended && glob[i1 + 1] == "(") {
                i1++;
                groupStack.push("+");
                segment += "(?:";
                continue;
            }
            if (glob[i1] == "@" && extended && glob[i1 + 1] == "(") {
                i1++;
                groupStack.push("@");
                segment += "(?:";
                continue;
            }
            if (glob[i1] == "?") {
                if (extended && glob[i1 + 1] == "(") {
                    i1++;
                    groupStack.push("?");
                    segment += "(?:";
                } else {
                    segment += ".";
                }
                continue;
            }
            if (glob[i1] == "!" && extended && glob[i1 + 1] == "(") {
                i1++;
                groupStack.push("!");
                segment += "(?!";
                continue;
            }
            if (glob[i1] == "{") {
                groupStack.push("BRACE");
                segment += "(?:";
                continue;
            }
            if (glob[i1] == "}" && groupStack[groupStack.length - 1] == "BRACE") {
                groupStack.pop();
                segment += ")";
                continue;
            }
            if (glob[i1] == "," && groupStack[groupStack.length - 1] == "BRACE") {
                segment += "|";
                continue;
            }
            if (glob[i1] == "*") {
                if (extended && glob[i1 + 1] == "(") {
                    i1++;
                    groupStack.push("*");
                    segment += "(?:";
                } else {
                    const prevChar = glob[i1 - 1];
                    let numStars = 1;
                    while(glob[i1 + 1] == "*"){
                        i1++;
                        numStars++;
                    }
                    const nextChar = glob[i1 + 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[i1]) ? `\\${glob[i1]}` : glob[i1];
        }
        if (groupStack.length > 0 || inRange || inEscape) {
            segment = "";
            for (const c of glob.slice(j, i1)){
                segment += regExpEscapeChars1.includes(c) ? `\\${c}` : c;
                endsWithSep = false;
            }
        }
        regExpString += segment;
        if (!endsWithSep) {
            regExpString += i1 < glob.length ? sep : sepMaybe;
            endsWithSep = true;
        }
        while(seps.includes(glob[i1]))i1++;
        if (!(i1 > j)) {
            throw new Error("Assertion failure: i > j (potential infinite loop)");
        }
        j = i1;
    }
    regExpString = `^${regExpString}$`;
    return new RegExp(regExpString, caseInsensitive ? "i" : "");
}
function isGlob1(str) {
    const chars = {
        "{": "}",
        "(": ")",
        "[": "]"
    };
    const regex = /\\(.)|(^!|\*|\?|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
    if (str === "") {
        return false;
    }
    let match;
    while(match = regex.exec(str)){
        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 = str.indexOf(close, idx);
            if (n !== -1) {
                idx = n + 1;
            }
        }
        str = str.slice(idx);
    }
    return false;
}
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 InternalError(`getYamlIntelligenceResource called with missing resource ${filename}`);
    }
    return _resources[filename];
}
function expandResourceGlob(glob) {
    return Object.keys(_resources).filter((key)=>key.match(globToRegExp3(glob))).map((key)=>[
            key,
            getYamlIntelligenceResource(key)
        ]);
}
function fromEntries(iterable) {
    return [
        ...iterable
    ].reduce((obj, [key, val])=>{
        obj[key] = val;
        return obj;
    }, {});
}
let _parser;
function setTreeSitter(parser) {
    _parser = parser;
}
function getTreeSitterSync() {
    if (_parser === undefined) {
        throw new Error("tree-sitter uninitialized");
    }
    return _parser;
}
function isNothing(subject) {
    return typeof subject === "undefined" || subject === null;
}
function isObject2(subject) {
    return typeof subject === "object" && subject !== null;
}
function toArray(sequence) {
    if (Array.isArray(sequence)) return sequence;
    else if (isNothing(sequence)) return [];
    return [
        sequence
    ];
}
function extend(target, source) {
    var index, length, key, sourceKeys;
    if (source) {
        sourceKeys = Object.keys(source);
        for(index = 0, length = sourceKeys.length; index < length; index += 1){
            key = sourceKeys[index];
            target[key] = source[key];
        }
    }
    return target;
}
function repeat1(string, count) {
    var result1 = "", cycle;
    for(cycle = 0; cycle < count; cycle += 1){
        result1 += string;
    }
    return result1;
}
function isNegativeZero1(number) {
    return number === 0 && Number.NEGATIVE_INFINITY === 1 / number;
}
var isNothing_1 = isNothing;
var isObject_1 = isObject2;
var toArray_1 = toArray;
var repeat_1 = repeat1;
var isNegativeZero_1 = isNegativeZero1;
var extend_1 = extend;
var common1 = {
    isNothing: isNothing_1,
    isObject: isObject_1,
    toArray: toArray_1,
    repeat: repeat_1,
    isNegativeZero: isNegativeZero_1,
    extend: extend_1
};
function formatError(exception2, compact) {
    var where = "", message = exception2.reason || "(unknown reason)";
    if (!exception2.mark) return message;
    if (exception2.mark.name) {
        where += 'in "' + exception2.mark.name + '" ';
    }
    where += "(" + (exception2.mark.line + 1) + ":" + (exception2.mark.column + 1) + ")";
    if (!compact && exception2.mark.snippet) {
        where += "\n\n" + exception2.mark.snippet;
    }
    return message + " " + where;
}
function YAMLException$1(reason, mark) {
    Error.call(this);
    this.name = "YAMLException";
    this.reason = reason;
    this.mark = mark;
    this.message = formatError(this, false);
    if (Error.captureStackTrace) {
        Error.captureStackTrace(this, this.constructor);
    } else {
        this.stack = new Error().stack || "";
    }
}
YAMLException$1.prototype = Object.create(Error.prototype);
YAMLException$1.prototype.constructor = YAMLException$1;
YAMLException$1.prototype.toString = function toString(compact) {
    return this.name + ": " + formatError(this, compact);
};
var exception = YAMLException$1;
function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
    var head = "";
    var tail = "";
    var maxHalfLength = Math.floor(maxLineLength / 2) - 1;
    if (position - lineStart > maxHalfLength) {
        head = " ... ";
        lineStart = position - maxHalfLength + head.length;
    }
    if (lineEnd - position > maxHalfLength) {
        tail = " ...";
        lineEnd = position + maxHalfLength - tail.length;
    }
    return {
        str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
        pos: position - lineStart + head.length
    };
}
function padStart(string, max) {
    return common1.repeat(" ", max - string.length) + string;
}
function makeSnippet(mark, options) {
    options = Object.create(options || null);
    if (!mark.buffer) return null;
    if (!options.maxLength) options.maxLength = 79;
    if (typeof options.indent !== "number") options.indent = 1;
    if (typeof options.linesBefore !== "number") options.linesBefore = 3;
    if (typeof options.linesAfter !== "number") options.linesAfter = 2;
    var re = /\r?\n|\r|\0/g;
    var lineStarts = [
        0
    ];
    var lineEnds = [];
    var match;
    var foundLineNo = -1;
    while(match = re.exec(mark.buffer)){
        lineEnds.push(match.index);
        lineStarts.push(match.index + match[0].length);
        if (mark.position <= match.index && foundLineNo < 0) {
            foundLineNo = lineStarts.length - 2;
        }
    }
    if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
    var result1 = "", i1, line;
    var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
    var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);
    for(i1 = 1; i1 <= options.linesBefore; i1++){
        if (foundLineNo - i1 < 0) break;
        line = getLine(mark.buffer, lineStarts[foundLineNo - i1], lineEnds[foundLineNo - i1], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i1]), maxLineLength);
        result1 = common1.repeat(" ", options.indent) + padStart((mark.line - i1 + 1).toString(), lineNoLength) + " | " + line.str + "\n" + result1;
    }
    line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
    result1 += common1.repeat(" ", options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + " | " + line.str + "\n";
    result1 += common1.repeat("-", options.indent + lineNoLength + 3 + line.pos) + "^\n";
    for(i1 = 1; i1 <= options.linesAfter; i1++){
        if (foundLineNo + i1 >= lineEnds.length) break;
        line = getLine(mark.buffer, lineStarts[foundLineNo + i1], lineEnds[foundLineNo + i1], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i1]), maxLineLength);
        result1 += common1.repeat(" ", options.indent) + padStart((mark.line + i1 + 1).toString(), lineNoLength) + " | " + line.str + "\n";
    }
    return result1.replace(/\n$/, "");
}
var snippet = makeSnippet;
var TYPE_CONSTRUCTOR_OPTIONS = [
    "kind",
    "multi",
    "resolve",
    "construct",
    "instanceOf",
    "predicate",
    "represent",
    "representName",
    "defaultStyle",
    "styleAliases"
];
var YAML_NODE_KINDS = [
    "scalar",
    "sequence",
    "mapping"
];
function compileStyleAliases(map2) {
    var result1 = {};
    if (map2 !== null) {
        Object.keys(map2).forEach(function(style) {
            map2[style].forEach(function(alias) {
                result1[String(alias)] = style;
            });
        });
    }
    return result1;
}
function Type$1(tag, options) {
    options = options || {};
    Object.keys(options).forEach(function(name) {
        if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
            throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
        }
    });
    this.options = options;
    this.tag = tag;
    this.kind = options["kind"] || null;
    this.resolve = options["resolve"] || function() {
        return true;
    };
    this.construct = options["construct"] || function(data) {
        return data;
    };
    this.instanceOf = options["instanceOf"] || null;
    this.predicate = options["predicate"] || null;
    this.represent = options["represent"] || null;
    this.representName = options["representName"] || null;
    this.defaultStyle = options["defaultStyle"] || null;
    this.multi = options["multi"] || false;
    this.styleAliases = compileStyleAliases(options["styleAliases"] || null);
    if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
        throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
    }
}
var type = Type$1;
function compileList1(schema2, name) {
    var result1 = [];
    schema2[name].forEach(function(currentType) {
        var newIndex = result1.length;
        result1.forEach(function(previousType, previousIndex) {
            if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) {
                newIndex = previousIndex;
            }
        });
        result1[newIndex] = currentType;
    });
    return result1;
}
function compileMap1() {
    var result1 = {
        scalar: {},
        sequence: {},
        mapping: {},
        fallback: {},
        multi: {
            scalar: [],
            sequence: [],
            mapping: [],
            fallback: []
        }
    }, index, length;
    function collectType(type2) {
        if (type2.multi) {
            result1.multi[type2.kind].push(type2);
            result1.multi["fallback"].push(type2);
        } else {
            result1[type2.kind][type2.tag] = result1["fallback"][type2.tag] = type2;
        }
    }
    for(index = 0, length = arguments.length; index < length; index += 1){
        arguments[index].forEach(collectType);
    }
    return result1;
}
function Schema$1(definition) {
    return this.extend(definition);
}
Schema$1.prototype.extend = function extend2(definition) {
    var implicit = [];
    var explicit = [];
    if (definition instanceof type) {
        explicit.push(definition);
    } else if (Array.isArray(definition)) {
        explicit = explicit.concat(definition);
    } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
        if (definition.implicit) implicit = implicit.concat(definition.implicit);
        if (definition.explicit) explicit = explicit.concat(definition.explicit);
    } else {
        throw new exception("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");
    }
    implicit.forEach(function(type$1) {
        if (!(type$1 instanceof type)) {
            throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
        }
        if (type$1.loadKind && type$1.loadKind !== "scalar") {
            throw new exception("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");
        }
        if (type$1.multi) {
            throw new exception("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.");
        }
    });
    explicit.forEach(function(type$1) {
        if (!(type$1 instanceof type)) {
            throw new exception("Specified list of YAML types (or a single Type object) contains a non-Type object.");
        }
    });
    var result1 = Object.create(Schema$1.prototype);
    result1.implicit = (this.implicit || []).concat(implicit);
    result1.explicit = (this.explicit || []).concat(explicit);
    result1.compiledImplicit = compileList1(result1, "implicit");
    result1.compiledExplicit = compileList1(result1, "explicit");
    result1.compiledTypeMap = compileMap1(result1.compiledImplicit, result1.compiledExplicit);
    return result1;
};
var schema = Schema$1;
var str1 = new type("tag:yaml.org,2002:str", {
    kind: "scalar",
    construct: function(data) {
        return data !== null ? data : "";
    }
});
var seq1 = new type("tag:yaml.org,2002:seq", {
    kind: "sequence",
    construct: function(data) {
        return data !== null ? data : [];
    }
});
var map1 = new type("tag:yaml.org,2002:map", {
    kind: "mapping",
    construct: function(data) {
        return data !== null ? data : {};
    }
});
var failsafe1 = new schema({
    explicit: [
        str1,
        seq1,
        map1
    ]
});
function resolveYamlNull1(data) {
    if (data === null) return true;
    var max = data.length;
    return max === 1 && data === "~" || max === 4 && (data === "null" || data === "Null" || data === "NULL");
}
function constructYamlNull1() {
    return null;
}
function isNull1(object) {
    return object === null;
}
var _null = new type("tag:yaml.org,2002:null", {
    kind: "scalar",
    resolve: resolveYamlNull1,
    construct: constructYamlNull1,
    predicate: isNull1,
    represent: {
        canonical: function() {
            return "~";
        },
        lowercase: function() {
            return "null";
        },
        uppercase: function() {
            return "NULL";
        },
        camelcase: function() {
            return "Null";
        },
        empty: function() {
            return "";
        }
    },
    defaultStyle: "lowercase"
});
function resolveYamlBoolean1(data) {
    if (data === null) return false;
    var max = data.length;
    return max === 4 && (data === "true" || data === "True" || data === "TRUE") || max === 5 && (data === "false" || data === "False" || data === "FALSE");
}
function constructYamlBoolean1(data) {
    return data === "true" || data === "True" || data === "TRUE";
}
function isBoolean1(object) {
    return Object.prototype.toString.call(object) === "[object Boolean]";
}
var bool1 = new type("tag:yaml.org,2002:bool", {
    kind: "scalar",
    resolve: resolveYamlBoolean1,
    construct: constructYamlBoolean1,
    predicate: isBoolean1,
    represent: {
        lowercase: function(object) {
            return object ? "true" : "false";
        },
        uppercase: function(object) {
            return object ? "TRUE" : "FALSE";
        },
        camelcase: function(object) {
            return object ? "True" : "False";
        }
    },
    defaultStyle: "lowercase"
});
function isHexCode1(c) {
    return 48 <= c && c <= 57 || 65 <= c && c <= 70 || 97 <= c && c <= 102;
}
function isOctCode1(c) {
    return 48 <= c && c <= 55;
}
function isDecCode1(c) {
    return 48 <= c && c <= 57;
}
function resolveYamlInteger1(data) {
    if (data === null) return false;
    var max = data.length, index = 0, hasDigits = false, ch;
    if (!max) return false;
    ch = data[index];
    if (ch === "-" || ch === "+") {
        ch = data[++index];
    }
    if (ch === "0") {
        if (index + 1 === max) return true;
        ch = data[++index];
        if (ch === "b") {
            index++;
            for(; index < max; index++){
                ch = data[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 = data[index];
                if (ch === "_") continue;
                if (!isHexCode1(data.charCodeAt(index))) return false;
                hasDigits = true;
            }
            return hasDigits && ch !== "_";
        }
        if (ch === "o") {
            index++;
            for(; index < max; index++){
                ch = data[index];
                if (ch === "_") continue;
                if (!isOctCode1(data.charCodeAt(index))) return false;
                hasDigits = true;
            }
            return hasDigits && ch !== "_";
        }
    }
    if (ch === "_") return false;
    for(; index < max; index++){
        ch = data[index];
        if (ch === "_") continue;
        if (!isDecCode1(data.charCodeAt(index))) {
            return false;
        }
        hasDigits = true;
    }
    if (!hasDigits || ch === "_") return false;
    return true;
}
function constructYamlInteger1(data) {
    var value = data, sign = 1, ch;
    if (value.indexOf("_") !== -1) {
        value = value.replace(/_/g, "");
    }
    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.slice(2), 16);
        if (value[1] === "o") return sign * parseInt(value.slice(2), 8);
    }
    return sign * parseInt(value, 10);
}
function isInteger1(object) {
    return Object.prototype.toString.call(object) === "[object Number]" && object % 1 === 0 && !common1.isNegativeZero(object);
}
var __int1 = new type("tag:yaml.org,2002:int", {
    kind: "scalar",
    resolve: resolveYamlInteger1,
    construct: constructYamlInteger1,
    predicate: isInteger1,
    represent: {
        binary: function(obj) {
            return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
        },
        octal: function(obj) {
            return obj >= 0 ? "0o" + obj.toString(8) : "-0o" + obj.toString(8).slice(1);
        },
        decimal: function(obj) {
            return obj.toString(10);
        },
        hexadecimal: function(obj) {
            return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
        }
    },
    defaultStyle: "decimal",
    styleAliases: {
        binary: [
            2,
            "bin"
        ],
        octal: [
            8,
            "oct"
        ],
        decimal: [
            10,
            "dec"
        ],
        hexadecimal: [
            16,
            "hex"
        ]
    }
});
var YAML_FLOAT_PATTERN1 = new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
function resolveYamlFloat1(data) {
    if (data === null) return false;
    if (!YAML_FLOAT_PATTERN1.test(data) || data[data.length - 1] === "_") {
        return false;
    }
    return true;
}
function constructYamlFloat1(data) {
    var value, sign;
    value = data.replace(/_/g, "").toLowerCase();
    sign = value[0] === "-" ? -1 : 1;
    if ("+-".indexOf(value[0]) >= 0) {
        value = value.slice(1);
    }
    if (value === ".inf") {
        return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
    } else if (value === ".nan") {
        return NaN;
    }
    return sign * parseFloat(value, 10);
}
var SCIENTIFIC_WITHOUT_DOT1 = /^[-+]?[0-9]+e/;
function representYamlFloat1(object, style) {
    var res;
    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 (common1.isNegativeZero(object)) {
        return "-0.0";
    }
    res = object.toString(10);
    return SCIENTIFIC_WITHOUT_DOT1.test(res) ? res.replace("e", ".e") : res;
}
function isFloat1(object) {
    return Object.prototype.toString.call(object) === "[object Number]" && (object % 1 !== 0 || common1.isNegativeZero(object));
}
var __float1 = new type("tag:yaml.org,2002:float", {
    kind: "scalar",
    resolve: resolveYamlFloat1,
    construct: constructYamlFloat1,
    predicate: isFloat1,
    represent: representYamlFloat1,
    defaultStyle: "lowercase"
});
var json1 = failsafe1.extend({
    implicit: [
        _null,
        bool1,
        __int1,
        __float1
    ]
});
var core1 = json1;
var YAML_DATE_REGEXP1 = new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
var YAML_TIMESTAMP_REGEXP1 = 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 resolveYamlTimestamp1(data) {
    if (data === null) return false;
    if (YAML_DATE_REGEXP1.exec(data) !== null) return true;
    if (YAML_TIMESTAMP_REGEXP1.exec(data) !== null) return true;
    return false;
}
function constructYamlTimestamp1(data) {
    var match, year, month, day, hour, minute, second, fraction = 0, delta = null, tz_hour, tz_minute, date;
    match = YAML_DATE_REGEXP1.exec(data);
    if (match === null) match = YAML_TIMESTAMP_REGEXP1.exec(data);
    if (match === null) throw new Error("Date resolve error");
    year = +match[1];
    month = +match[2] - 1;
    day = +match[3];
    if (!match[4]) {
        return new Date(Date.UTC(year, month, day));
    }
    hour = +match[4];
    minute = +match[5];
    second = +match[6];
    if (match[7]) {
        fraction = match[7].slice(0, 3);
        while(fraction.length < 3){
            fraction += "0";
        }
        fraction = +fraction;
    }
    if (match[9]) {
        tz_hour = +match[10];
        tz_minute = +(match[11] || 0);
        delta = (tz_hour * 60 + tz_minute) * 6e4;
        if (match[9] === "-") delta = -delta;
    }
    date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
    if (delta) date.setTime(date.getTime() - delta);
    return date;
}
function representYamlTimestamp1(object) {
    return object.toISOString();
}
var timestamp1 = new type("tag:yaml.org,2002:timestamp", {
    kind: "scalar",
    resolve: resolveYamlTimestamp1,
    construct: constructYamlTimestamp1,
    instanceOf: Date,
    represent: representYamlTimestamp1
});
function resolveYamlMerge1(data) {
    return data === "<<" || data === null;
}
var merge1 = new type("tag:yaml.org,2002:merge", {
    kind: "scalar",
    resolve: resolveYamlMerge1
});
var BASE64_MAP1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";
function resolveYamlBinary1(data) {
    if (data === null) return false;
    var code, idx, bitlen = 0, max = data.length, map2 = BASE64_MAP1;
    for(idx = 0; idx < max; idx++){
        code = map2.indexOf(data.charAt(idx));
        if (code > 64) continue;
        if (code < 0) return false;
        bitlen += 6;
    }
    return bitlen % 8 === 0;
}
function constructYamlBinary1(data) {
    var idx, tailbits, input = data.replace(/[\r\n=]/g, ""), max = input.length, map2 = BASE64_MAP1, bits = 0, result1 = [];
    for(idx = 0; idx < max; idx++){
        if (idx % 4 === 0 && idx) {
            result1.push(bits >> 16 & 255);
            result1.push(bits >> 8 & 255);
            result1.push(bits & 255);
        }
        bits = bits << 6 | map2.indexOf(input.charAt(idx));
    }
    tailbits = max % 4 * 6;
    if (tailbits === 0) {
        result1.push(bits >> 16 & 255);
        result1.push(bits >> 8 & 255);
        result1.push(bits & 255);
    } else if (tailbits === 18) {
        result1.push(bits >> 10 & 255);
        result1.push(bits >> 2 & 255);
    } else if (tailbits === 12) {
        result1.push(bits >> 4 & 255);
    }
    return new Uint8Array(result1);
}
function representYamlBinary1(object) {
    var result1 = "", bits = 0, idx, tail, max = object.length, map2 = BASE64_MAP1;
    for(idx = 0; idx < max; idx++){
        if (idx % 3 === 0 && idx) {
            result1 += map2[bits >> 18 & 63];
            result1 += map2[bits >> 12 & 63];
            result1 += map2[bits >> 6 & 63];
            result1 += map2[bits & 63];
        }
        bits = (bits << 8) + object[idx];
    }
    tail = max % 3;
    if (tail === 0) {
        result1 += map2[bits >> 18 & 63];
        result1 += map2[bits >> 12 & 63];
        result1 += map2[bits >> 6 & 63];
        result1 += map2[bits & 63];
    } else if (tail === 2) {
        result1 += map2[bits >> 10 & 63];
        result1 += map2[bits >> 4 & 63];
        result1 += map2[bits << 2 & 63];
        result1 += map2[64];
    } else if (tail === 1) {
        result1 += map2[bits >> 2 & 63];
        result1 += map2[bits << 4 & 63];
        result1 += map2[64];
        result1 += map2[64];
    }
    return result1;
}
function isBinary1(obj) {
    return Object.prototype.toString.call(obj) === "[object Uint8Array]";
}
var binary1 = new type("tag:yaml.org,2002:binary", {
    kind: "scalar",
    resolve: resolveYamlBinary1,
    construct: constructYamlBinary1,
    predicate: isBinary1,
    represent: representYamlBinary1
});
var _hasOwnProperty$3 = Object.prototype.hasOwnProperty;
var _toString$2 = Object.prototype.toString;
function resolveYamlOmap1(data) {
    if (data === null) return true;
    var objectKeys = [], index, length, pair, pairKey, pairHasKey, object = data;
    for(index = 0, length = object.length; index < length; index += 1){
        pair = object[index];
        pairHasKey = false;
        if (_toString$2.call(pair) !== "[object Object]") return false;
        for(pairKey in pair){
            if (_hasOwnProperty$3.call(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 constructYamlOmap1(data) {
    return data !== null ? data : [];
}
var omap1 = new type("tag:yaml.org,2002:omap", {
    kind: "sequence",
    resolve: resolveYamlOmap1,
    construct: constructYamlOmap1
});
var _toString$1 = Object.prototype.toString;
function resolveYamlPairs1(data) {
    if (data === null) return true;
    var index, length, pair, keys, result1, object = data;
    result1 = new Array(object.length);
    for(index = 0, length = object.length; index < length; index += 1){
        pair = object[index];
        if (_toString$1.call(pair) !== "[object Object]") return false;
        keys = Object.keys(pair);
        if (keys.length !== 1) return false;
        result1[index] = [
            keys[0],
            pair[keys[0]]
        ];
    }
    return true;
}
function constructYamlPairs1(data) {
    if (data === null) return [];
    var index, length, pair, keys, result1, object = data;
    result1 = new Array(object.length);
    for(index = 0, length = object.length; index < length; index += 1){
        pair = object[index];
        keys = Object.keys(pair);
        result1[index] = [
            keys[0],
            pair[keys[0]]
        ];
    }
    return result1;
}
var pairs1 = new type("tag:yaml.org,2002:pairs", {
    kind: "sequence",
    resolve: resolveYamlPairs1,
    construct: constructYamlPairs1
});
var _hasOwnProperty$2 = Object.prototype.hasOwnProperty;
function resolveYamlSet1(data) {
    if (data === null) return true;
    var key, object = data;
    for(key in object){
        if (_hasOwnProperty$2.call(object, key)) {
            if (object[key] !== null) return false;
        }
    }
    return true;
}
function constructYamlSet1(data) {
    return data !== null ? data : {};
}
var set1 = new type("tag:yaml.org,2002:set", {
    kind: "mapping",
    resolve: resolveYamlSet1,
    construct: constructYamlSet1
});
var _default = core1.extend({
    implicit: [
        timestamp1,
        merge1
    ],
    explicit: [
        binary1,
        omap1,
        pairs1,
        set1
    ]
});
var _hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var CONTEXT_FLOW_IN = 1;
var CONTEXT_FLOW_OUT = 2;
var CONTEXT_BLOCK_IN1 = 3;
var CONTEXT_BLOCK_OUT1 = 4;
var CHOMPING_CLIP = 1;
var CHOMPING_STRIP1 = 2;
var CHOMPING_KEEP1 = 3;
var PATTERN_NON_PRINTABLE1 = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
var PATTERN_NON_ASCII_LINE_BREAKS1 = /[\x85\u2028\u2029]/;
var PATTERN_FLOW_INDICATORS1 = /[,\[\]\{\}]/;
var PATTERN_TAG_HANDLE1 = /^(?:!|!!|![a-z\-]+!)$/i;
var PATTERN_TAG_URI1 = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;
function _class1(obj) {
    return Object.prototype.toString.call(obj);
}
function is_EOL(c) {
    return c === 10 || c === 13;
}
function is_WHITE_SPACE(c) {
    return c === 9 || c === 32;
}
function is_WS_OR_EOL(c) {
    return c === 9 || c === 32 || c === 10 || c === 13;
}
function is_FLOW_INDICATOR(c) {
    return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
}
function fromHexCode1(c) {
    var lc;
    if (48 <= c && c <= 57) {
        return c - 48;
    }
    lc = c | 32;
    if (97 <= lc && lc <= 102) {
        return lc - 97 + 10;
    }
    return -1;
}
function escapedHexLen1(c) {
    if (c === 120) {
        return 2;
    }
    if (c === 117) {
        return 4;
    }
    if (c === 85) {
        return 8;
    }
    return 0;
}
function fromDecimalCode1(c) {
    if (48 <= c && c <= 57) {
        return c - 48;
    }
    return -1;
}
function simpleEscapeSequence1(c) {
    return c === 48 ? "\0" : c === 97 ? "\x07" : c === 98 ? "\b" : c === 116 ? "	" : c === 9 ? "	" : c === 110 ? "\n" : c === 118 ? "\v" : c === 102 ? "\f" : c === 114 ? "\r" : c === 101 ? "" : c === 32 ? " " : c === 34 ? '"' : c === 47 ? "/" : c === 92 ? "\\" : c === 78 ? "\x85" : c === 95 ? "\xA0" : c === 76 ? "\u2028" : c === 80 ? "\u2029" : "";
}
function charFromCodepoint1(c) {
    if (c <= 65535) {
        return String.fromCharCode(c);
    }
    return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
}
var simpleEscapeCheck1 = new Array(256);
var simpleEscapeMap1 = new Array(256);
for(var i1 = 0; i1 < 256; i1++){
    simpleEscapeCheck1[i1] = simpleEscapeSequence1(i1) ? 1 : 0;
    simpleEscapeMap1[i1] = simpleEscapeSequence1(i1);
}
function State$1(input, options) {
    this.input = input;
    this.filename = options["filename"] || null;
    this.schema = options["schema"] || _default;
    this.onWarning = options["onWarning"] || null;
    this.legacy = options["legacy"] || false;
    this.json = options["json"] || false;
    this.listener = options["listener"] || null;
    this.implicitTypes = this.schema.compiledImplicit;
    this.typeMap = this.schema.compiledTypeMap;
    this.length = input.length;
    this.position = 0;
    this.line = 0;
    this.lineStart = 0;
    this.lineIndent = 0;
    this.firstTabInLine = -1;
    this.documents = [];
}
function generateError1(state, message) {
    var mark = {
        name: state.filename,
        buffer: state.input.slice(0, -1),
        position: state.position,
        line: state.line,
        column: state.position - state.lineStart
    };
    mark.snippet = snippet(mark);
    return new exception(message, mark);
}
function throwError1(state, message) {
    throw generateError1(state, message);
}
function throwWarning1(state, message) {
    if (state.onWarning) {
        state.onWarning.call(null, generateError1(state, message));
    }
}
var directiveHandlers1 = {
    YAML: function handleYamlDirective(state, name, args) {
        var match, major, minor;
        if (state.version !== null) {
            throwError1(state, "duplication of %YAML directive");
        }
        if (args.length !== 1) {
            throwError1(state, "YAML directive accepts exactly one argument");
        }
        match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
        if (match === null) {
            throwError1(state, "ill-formed argument of the YAML directive");
        }
        major = parseInt(match[1], 10);
        minor = parseInt(match[2], 10);
        if (major !== 1) {
            throwError1(state, "unacceptable YAML version of the document");
        }
        state.version = args[0];
        state.checkLineBreaks = minor < 2;
        if (minor !== 1 && minor !== 2) {
            throwWarning1(state, "unsupported YAML version of the document");
        }
    },
    TAG: function handleTagDirective(state, name, args) {
        var handle, prefix;
        if (args.length !== 2) {
            throwError1(state, "TAG directive accepts exactly two arguments");
        }
        handle = args[0];
        prefix = args[1];
        if (!PATTERN_TAG_HANDLE1.test(handle)) {
            throwError1(state, "ill-formed tag handle (first argument) of the TAG directive");
        }
        if (_hasOwnProperty$1.call(state.tagMap, handle)) {
            throwError1(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
        }
        if (!PATTERN_TAG_URI1.test(prefix)) {
            throwError1(state, "ill-formed tag prefix (second argument) of the TAG directive");
        }
        try {
            prefix = decodeURIComponent(prefix);
        } catch (err) {
            throwError1(state, "tag prefix is malformed: " + prefix);
        }
        state.tagMap[handle] = prefix;
    }
};
function captureSegment1(state, start, end, checkJson) {
    var _position, _length, _character, _result;
    if (start < end) {
        _result = state.input.slice(start, end);
        if (checkJson) {
            for(_position = 0, _length = _result.length; _position < _length; _position += 1){
                _character = _result.charCodeAt(_position);
                if (!(_character === 9 || 32 <= _character && _character <= 1114111)) {
                    throwError1(state, "expected valid JSON character");
                }
            }
        } else if (PATTERN_NON_PRINTABLE1.test(_result)) {
            throwError1(state, "the stream contains non-printable characters");
        }
        state.result += _result;
    }
}
function mergeMappings1(state, destination, source, overridableKeys) {
    var sourceKeys, key, index, quantity;
    if (!common1.isObject(source)) {
        throwError1(state, "cannot merge mappings; the provided source object is unacceptable");
    }
    sourceKeys = Object.keys(source);
    for(index = 0, quantity = sourceKeys.length; index < quantity; index += 1){
        key = sourceKeys[index];
        if (!_hasOwnProperty$1.call(destination, key)) {
            destination[key] = source[key];
            overridableKeys[key] = true;
        }
    }
}
function storeMappingPair1(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startLineStart, startPos) {
    var index, quantity;
    if (Array.isArray(keyNode)) {
        keyNode = Array.prototype.slice.call(keyNode);
        for(index = 0, quantity = keyNode.length; index < quantity; index += 1){
            if (Array.isArray(keyNode[index])) {
                throwError1(state, "nested arrays are not supported inside keys");
            }
            if (typeof keyNode === "object" && _class1(keyNode[index]) === "[object Object]") {
                keyNode[index] = "[object Object]";
            }
        }
    }
    if (typeof keyNode === "object" && _class1(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(index = 0, quantity = valueNode.length; index < quantity; index += 1){
                mergeMappings1(state, _result, valueNode[index], overridableKeys);
            }
        } else {
            mergeMappings1(state, _result, valueNode, overridableKeys);
        }
    } else {
        if (!state.json && !_hasOwnProperty$1.call(overridableKeys, keyNode) && _hasOwnProperty$1.call(_result, keyNode)) {
            state.line = startLine || state.line;
            state.lineStart = startLineStart || state.lineStart;
            state.position = startPos || state.position;
            throwError1(state, "duplicated mapping key");
        }
        if (keyNode === "__proto__") {
            Object.defineProperty(_result, keyNode, {
                configurable: true,
                enumerable: true,
                writable: true,
                value: valueNode
            });
        } else {
            _result[keyNode] = valueNode;
        }
        delete overridableKeys[keyNode];
    }
    return _result;
}
function readLineBreak1(state) {
    var ch;
    ch = state.input.charCodeAt(state.position);
    if (ch === 10) {
        state.position++;
    } else if (ch === 13) {
        state.position++;
        if (state.input.charCodeAt(state.position) === 10) {
            state.position++;
        }
    } else {
        throwError1(state, "a line break is expected");
    }
    state.line += 1;
    state.lineStart = state.position;
    state.firstTabInLine = -1;
}
function skipSeparationSpace1(state, allowComments, checkIndent) {
    var lineBreaks = 0, ch = state.input.charCodeAt(state.position);
    while(ch !== 0){
        while(is_WHITE_SPACE(ch)){
            if (ch === 9 && state.firstTabInLine === -1) {
                state.firstTabInLine = state.position;
            }
            ch = state.input.charCodeAt(++state.position);
        }
        if (allowComments && ch === 35) {
            do {
                ch = state.input.charCodeAt(++state.position);
            }while (ch !== 10 && ch !== 13 && ch !== 0)
        }
        if (is_EOL(ch)) {
            readLineBreak1(state);
            ch = state.input.charCodeAt(state.position);
            lineBreaks++;
            state.lineIndent = 0;
            while(ch === 32){
                state.lineIndent++;
                ch = state.input.charCodeAt(++state.position);
            }
        } else {
            break;
        }
    }
    if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
        throwWarning1(state, "deficient indentation");
    }
    return lineBreaks;
}
function testDocumentSeparator1(state) {
    var _position = state.position, ch;
    ch = state.input.charCodeAt(_position);
    if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(_position + 1) && ch === state.input.charCodeAt(_position + 2)) {
        _position += 3;
        ch = state.input.charCodeAt(_position);
        if (ch === 0 || is_WS_OR_EOL(ch)) {
            return true;
        }
    }
    return false;
}
function writeFoldedLines1(state, count) {
    if (count === 1) {
        state.result += " ";
    } else if (count > 1) {
        state.result += common1.repeat("\n", count - 1);
    }
}
function readPlainScalar1(state, nodeIndent, withinFlowCollection) {
    var preceding, following, captureStart, captureEnd, hasPendingContent, _line, _lineStart, _lineIndent, _kind = state.kind, _result = state.result, ch;
    ch = state.input.charCodeAt(state.position);
    if (is_WS_OR_EOL(ch) || is_FLOW_INDICATOR(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;
    }
    if (ch === 63 || ch === 45) {
        following = state.input.charCodeAt(state.position + 1);
        if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
            return false;
        }
    }
    state.kind = "scalar";
    state.result = "";
    captureStart = captureEnd = state.position;
    hasPendingContent = false;
    while(ch !== 0){
        if (ch === 58) {
            following = state.input.charCodeAt(state.position + 1);
            if (is_WS_OR_EOL(following) || withinFlowCollection && is_FLOW_INDICATOR(following)) {
                break;
            }
        } else if (ch === 35) {
            preceding = state.input.charCodeAt(state.position - 1);
            if (is_WS_OR_EOL(preceding)) {
                break;
            }
        } else if (state.position === state.lineStart && testDocumentSeparator1(state) || withinFlowCollection && is_FLOW_INDICATOR(ch)) {
            break;
        } else if (is_EOL(ch)) {
            _line = state.line;
            _lineStart = state.lineStart;
            _lineIndent = state.lineIndent;
            skipSeparationSpace1(state, false, -1);
            if (state.lineIndent >= nodeIndent) {
                hasPendingContent = true;
                ch = state.input.charCodeAt(state.position);
                continue;
            } else {
                state.position = captureEnd;
                state.line = _line;
                state.lineStart = _lineStart;
                state.lineIndent = _lineIndent;
                break;
            }
        }
        if (hasPendingContent) {
            captureSegment1(state, captureStart, captureEnd, false);
            writeFoldedLines1(state, state.line - _line);
            captureStart = captureEnd = state.position;
            hasPendingContent = false;
        }
        if (!is_WHITE_SPACE(ch)) {
            captureEnd = state.position + 1;
        }
        ch = state.input.charCodeAt(++state.position);
    }
    captureSegment1(state, captureStart, captureEnd, false);
    if (state.result) {
        return true;
    }
    state.kind = _kind;
    state.result = _result;
    return false;
}
function readSingleQuotedScalar1(state, nodeIndent) {
    var ch, captureStart, captureEnd;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 39) {
        return false;
    }
    state.kind = "scalar";
    state.result = "";
    state.position++;
    captureStart = captureEnd = state.position;
    while((ch = state.input.charCodeAt(state.position)) !== 0){
        if (ch === 39) {
            captureSegment1(state, captureStart, state.position, true);
            ch = state.input.charCodeAt(++state.position);
            if (ch === 39) {
                captureStart = state.position;
                state.position++;
                captureEnd = state.position;
            } else {
                return true;
            }
        } else if (is_EOL(ch)) {
            captureSegment1(state, captureStart, captureEnd, true);
            writeFoldedLines1(state, skipSeparationSpace1(state, false, nodeIndent));
            captureStart = captureEnd = state.position;
        } else if (state.position === state.lineStart && testDocumentSeparator1(state)) {
            throwError1(state, "unexpected end of the document within a single quoted scalar");
        } else {
            state.position++;
            captureEnd = state.position;
        }
    }
    throwError1(state, "unexpected end of the stream within a single quoted scalar");
}
function readDoubleQuotedScalar1(state, nodeIndent) {
    var captureStart, captureEnd, hexLength, hexResult, tmp, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 34) {
        return false;
    }
    state.kind = "scalar";
    state.result = "";
    state.position++;
    captureStart = captureEnd = state.position;
    while((ch = state.input.charCodeAt(state.position)) !== 0){
        if (ch === 34) {
            captureSegment1(state, captureStart, state.position, true);
            state.position++;
            return true;
        } else if (ch === 92) {
            captureSegment1(state, captureStart, state.position, true);
            ch = state.input.charCodeAt(++state.position);
            if (is_EOL(ch)) {
                skipSeparationSpace1(state, false, nodeIndent);
            } else if (ch < 256 && simpleEscapeCheck1[ch]) {
                state.result += simpleEscapeMap1[ch];
                state.position++;
            } else if ((tmp = escapedHexLen1(ch)) > 0) {
                hexLength = tmp;
                hexResult = 0;
                for(; hexLength > 0; hexLength--){
                    ch = state.input.charCodeAt(++state.position);
                    if ((tmp = fromHexCode1(ch)) >= 0) {
                        hexResult = (hexResult << 4) + tmp;
                    } else {
                        throwError1(state, "expected hexadecimal character");
                    }
                }
                state.result += charFromCodepoint1(hexResult);
                state.position++;
            } else {
                throwError1(state, "unknown escape sequence");
            }
            captureStart = captureEnd = state.position;
        } else if (is_EOL(ch)) {
            captureSegment1(state, captureStart, captureEnd, true);
            writeFoldedLines1(state, skipSeparationSpace1(state, false, nodeIndent));
            captureStart = captureEnd = state.position;
        } else if (state.position === state.lineStart && testDocumentSeparator1(state)) {
            throwError1(state, "unexpected end of the document within a double quoted scalar");
        } else {
            state.position++;
            captureEnd = state.position;
        }
    }
    throwError1(state, "unexpected end of the stream within a double quoted scalar");
}
function readFlowCollection1(state, nodeIndent) {
    var readNext = true, _line, _lineStart, _pos, _tag = state.tag, _result, _anchor = state.anchor, following, terminator, isPair, isExplicitPair, isMapping, overridableKeys = Object.create(null), keyNode, keyTag, valueNode, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch === 91) {
        terminator = 93;
        isMapping = false;
        _result = [];
    } else if (ch === 123) {
        terminator = 125;
        isMapping = true;
        _result = {};
    } else {
        return false;
    }
    if (state.anchor !== null) {
        state.anchorMap[state.anchor] = _result;
    }
    ch = state.input.charCodeAt(++state.position);
    while(ch !== 0){
        skipSeparationSpace1(state, true, nodeIndent);
        ch = state.input.charCodeAt(state.position);
        if (ch === terminator) {
            state.position++;
            state.tag = _tag;
            state.anchor = _anchor;
            state.kind = isMapping ? "mapping" : "sequence";
            state.result = _result;
            return true;
        } else if (!readNext) {
            throwError1(state, "missed comma between flow collection entries");
        } else if (ch === 44) {
            throwError1(state, "expected the node content, but found ','");
        }
        keyTag = keyNode = valueNode = null;
        isPair = isExplicitPair = false;
        if (ch === 63) {
            following = state.input.charCodeAt(state.position + 1);
            if (is_WS_OR_EOL(following)) {
                isPair = isExplicitPair = true;
                state.position++;
                skipSeparationSpace1(state, true, nodeIndent);
            }
        }
        _line = state.line;
        _lineStart = state.lineStart;
        _pos = state.position;
        composeNode1(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
        keyTag = state.tag;
        keyNode = state.result;
        skipSeparationSpace1(state, true, nodeIndent);
        ch = state.input.charCodeAt(state.position);
        if ((isExplicitPair || state.line === _line) && ch === 58) {
            isPair = true;
            ch = state.input.charCodeAt(++state.position);
            skipSeparationSpace1(state, true, nodeIndent);
            composeNode1(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
            valueNode = state.result;
        }
        if (isMapping) {
            storeMappingPair1(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
        } else if (isPair) {
            _result.push(storeMappingPair1(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
        } else {
            _result.push(keyNode);
        }
        skipSeparationSpace1(state, true, nodeIndent);
        ch = state.input.charCodeAt(state.position);
        if (ch === 44) {
            readNext = true;
            ch = state.input.charCodeAt(++state.position);
        } else {
            readNext = false;
        }
    }
    throwError1(state, "unexpected end of the stream within a flow collection");
}
function readBlockScalar1(state, nodeIndent) {
    var captureStart, folding, chomping = CHOMPING_CLIP, didReadContent = false, detectedIndent = false, textIndent = nodeIndent, emptyLines = 0, atMoreIndented = false, tmp, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch === 124) {
        folding = false;
    } else if (ch === 62) {
        folding = true;
    } else {
        return false;
    }
    state.kind = "scalar";
    state.result = "";
    while(ch !== 0){
        ch = state.input.charCodeAt(++state.position);
        if (ch === 43 || ch === 45) {
            if (CHOMPING_CLIP === chomping) {
                chomping = ch === 43 ? CHOMPING_KEEP1 : CHOMPING_STRIP1;
            } else {
                throwError1(state, "repeat of a chomping mode identifier");
            }
        } else if ((tmp = fromDecimalCode1(ch)) >= 0) {
            if (tmp === 0) {
                throwError1(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
            } else if (!detectedIndent) {
                textIndent = nodeIndent + tmp - 1;
                detectedIndent = true;
            } else {
                throwError1(state, "repeat of an indentation width identifier");
            }
        } else {
            break;
        }
    }
    if (is_WHITE_SPACE(ch)) {
        do {
            ch = state.input.charCodeAt(++state.position);
        }while (is_WHITE_SPACE(ch))
        if (ch === 35) {
            do {
                ch = state.input.charCodeAt(++state.position);
            }while (!is_EOL(ch) && ch !== 0)
        }
    }
    while(ch !== 0){
        readLineBreak1(state);
        state.lineIndent = 0;
        ch = state.input.charCodeAt(state.position);
        while((!detectedIndent || state.lineIndent < textIndent) && ch === 32){
            state.lineIndent++;
            ch = state.input.charCodeAt(++state.position);
        }
        if (!detectedIndent && state.lineIndent > textIndent) {
            textIndent = state.lineIndent;
        }
        if (is_EOL(ch)) {
            emptyLines++;
            continue;
        }
        if (state.lineIndent < textIndent) {
            if (chomping === CHOMPING_KEEP1) {
                state.result += common1.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (chomping === CHOMPING_CLIP) {
                if (didReadContent) {
                    state.result += "\n";
                }
            }
            break;
        }
        if (folding) {
            if (is_WHITE_SPACE(ch)) {
                atMoreIndented = true;
                state.result += common1.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
            } else if (atMoreIndented) {
                atMoreIndented = false;
                state.result += common1.repeat("\n", emptyLines + 1);
            } else if (emptyLines === 0) {
                if (didReadContent) {
                    state.result += " ";
                }
            } else {
                state.result += common1.repeat("\n", emptyLines);
            }
        } else {
            state.result += common1.repeat("\n", didReadContent ? 1 + emptyLines : emptyLines);
        }
        didReadContent = true;
        detectedIndent = true;
        emptyLines = 0;
        captureStart = state.position;
        while(!is_EOL(ch) && ch !== 0){
            ch = state.input.charCodeAt(++state.position);
        }
        captureSegment1(state, captureStart, state.position, false);
    }
    return true;
}
function readBlockSequence1(state, nodeIndent) {
    var _line, _tag = state.tag, _anchor = state.anchor, _result = [], following, detected = false, ch;
    if (state.firstTabInLine !== -1) return false;
    if (state.anchor !== null) {
        state.anchorMap[state.anchor] = _result;
    }
    ch = state.input.charCodeAt(state.position);
    while(ch !== 0){
        if (state.firstTabInLine !== -1) {
            state.position = state.firstTabInLine;
            throwError1(state, "tab characters must not be used in indentation");
        }
        if (ch !== 45) {
            break;
        }
        following = state.input.charCodeAt(state.position + 1);
        if (!is_WS_OR_EOL(following)) {
            break;
        }
        detected = true;
        state.position++;
        if (skipSeparationSpace1(state, true, -1)) {
            if (state.lineIndent <= nodeIndent) {
                _result.push(null);
                ch = state.input.charCodeAt(state.position);
                continue;
            }
        }
        _line = state.line;
        composeNode1(state, nodeIndent, CONTEXT_BLOCK_IN1, false, true);
        _result.push(state.result);
        skipSeparationSpace1(state, true, -1);
        ch = state.input.charCodeAt(state.position);
        if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
            throwError1(state, "bad indentation of a sequence entry");
        } else if (state.lineIndent < nodeIndent) {
            break;
        }
    }
    if (detected) {
        state.tag = _tag;
        state.anchor = _anchor;
        state.kind = "sequence";
        state.result = _result;
        return true;
    }
    return false;
}
function readBlockMapping1(state, nodeIndent, flowIndent) {
    var following, allowCompact, _line, _keyLine, _keyLineStart, _keyPos, _tag = state.tag, _anchor = state.anchor, _result = {}, overridableKeys = Object.create(null), keyTag = null, keyNode = null, valueNode = null, atExplicitKey = false, detected = false, ch;
    if (state.firstTabInLine !== -1) return false;
    if (state.anchor !== null) {
        state.anchorMap[state.anchor] = _result;
    }
    ch = state.input.charCodeAt(state.position);
    while(ch !== 0){
        if (!atExplicitKey && state.firstTabInLine !== -1) {
            state.position = state.firstTabInLine;
            throwError1(state, "tab characters must not be used in indentation");
        }
        following = state.input.charCodeAt(state.position + 1);
        _line = state.line;
        if ((ch === 63 || ch === 58) && is_WS_OR_EOL(following)) {
            if (ch === 63) {
                if (atExplicitKey) {
                    storeMappingPair1(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
                    keyTag = keyNode = valueNode = null;
                }
                detected = true;
                atExplicitKey = true;
                allowCompact = true;
            } else if (atExplicitKey) {
                atExplicitKey = false;
                allowCompact = true;
            } else {
                throwError1(state, "incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line");
            }
            state.position += 1;
            ch = following;
        } else {
            _keyLine = state.line;
            _keyLineStart = state.lineStart;
            _keyPos = state.position;
            if (!composeNode1(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
                break;
            }
            if (state.line === _line) {
                ch = state.input.charCodeAt(state.position);
                while(is_WHITE_SPACE(ch)){
                    ch = state.input.charCodeAt(++state.position);
                }
                if (ch === 58) {
                    ch = state.input.charCodeAt(++state.position);
                    if (!is_WS_OR_EOL(ch)) {
                        throwError1(state, "a whitespace character is expected after the key-value separator within a block mapping");
                    }
                    if (atExplicitKey) {
                        storeMappingPair1(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
                        keyTag = keyNode = valueNode = null;
                    }
                    detected = true;
                    atExplicitKey = false;
                    allowCompact = false;
                    keyTag = state.tag;
                    keyNode = state.result;
                } else if (detected) {
                    throwError1(state, "can not read an implicit mapping pair; a colon is missed");
                } else {
                    state.tag = _tag;
                    state.anchor = _anchor;
                    return true;
                }
            } else if (detected) {
                throwError1(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
            } else {
                state.tag = _tag;
                state.anchor = _anchor;
                return true;
            }
        }
        if (state.line === _line || state.lineIndent > nodeIndent) {
            if (atExplicitKey) {
                _keyLine = state.line;
                _keyLineStart = state.lineStart;
                _keyPos = state.position;
            }
            if (composeNode1(state, nodeIndent, CONTEXT_BLOCK_OUT1, true, allowCompact)) {
                if (atExplicitKey) {
                    keyNode = state.result;
                } else {
                    valueNode = state.result;
                }
            }
            if (!atExplicitKey) {
                storeMappingPair1(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
                keyTag = keyNode = valueNode = null;
            }
            skipSeparationSpace1(state, true, -1);
            ch = state.input.charCodeAt(state.position);
        }
        if ((state.line === _line || state.lineIndent > nodeIndent) && ch !== 0) {
            throwError1(state, "bad indentation of a mapping entry");
        } else if (state.lineIndent < nodeIndent) {
            break;
        }
    }
    if (atExplicitKey) {
        storeMappingPair1(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
    }
    if (detected) {
        state.tag = _tag;
        state.anchor = _anchor;
        state.kind = "mapping";
        state.result = _result;
    }
    return detected;
}
function readTagProperty1(state) {
    var _position, isVerbatim = false, isNamed = false, tagHandle, tagName, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 33) return false;
    if (state.tag !== null) {
        throwError1(state, "duplication of a tag property");
    }
    ch = state.input.charCodeAt(++state.position);
    if (ch === 60) {
        isVerbatim = true;
        ch = state.input.charCodeAt(++state.position);
    } else if (ch === 33) {
        isNamed = true;
        tagHandle = "!!";
        ch = state.input.charCodeAt(++state.position);
    } else {
        tagHandle = "!";
    }
    _position = state.position;
    if (isVerbatim) {
        do {
            ch = state.input.charCodeAt(++state.position);
        }while (ch !== 0 && ch !== 62)
        if (state.position < state.length) {
            tagName = state.input.slice(_position, state.position);
            ch = state.input.charCodeAt(++state.position);
        } else {
            throwError1(state, "unexpected end of the stream within a verbatim tag");
        }
    } else {
        while(ch !== 0 && !is_WS_OR_EOL(ch)){
            if (ch === 33) {
                if (!isNamed) {
                    tagHandle = state.input.slice(_position - 1, state.position + 1);
                    if (!PATTERN_TAG_HANDLE1.test(tagHandle)) {
                        throwError1(state, "named tag handle cannot contain such characters");
                    }
                    isNamed = true;
                    _position = state.position + 1;
                } else {
                    throwError1(state, "tag suffix cannot contain exclamation marks");
                }
            }
            ch = state.input.charCodeAt(++state.position);
        }
        tagName = state.input.slice(_position, state.position);
        if (PATTERN_FLOW_INDICATORS1.test(tagName)) {
            throwError1(state, "tag suffix cannot contain flow indicator characters");
        }
    }
    if (tagName && !PATTERN_TAG_URI1.test(tagName)) {
        throwError1(state, "tag name cannot contain such characters: " + tagName);
    }
    try {
        tagName = decodeURIComponent(tagName);
    } catch (err) {
        throwError1(state, "tag name is malformed: " + tagName);
    }
    if (isVerbatim) {
        state.tag = tagName;
    } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) {
        state.tag = state.tagMap[tagHandle] + tagName;
    } else if (tagHandle === "!") {
        state.tag = "!" + tagName;
    } else if (tagHandle === "!!") {
        state.tag = "tag:yaml.org,2002:" + tagName;
    } else {
        throwError1(state, 'undeclared tag handle "' + tagHandle + '"');
    }
    return true;
}
function readAnchorProperty1(state) {
    var _position, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 38) return false;
    if (state.anchor !== null) {
        throwError1(state, "duplication of an anchor property");
    }
    ch = state.input.charCodeAt(++state.position);
    _position = state.position;
    while(ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)){
        ch = state.input.charCodeAt(++state.position);
    }
    if (state.position === _position) {
        throwError1(state, "name of an anchor node must contain at least one character");
    }
    state.anchor = state.input.slice(_position, state.position);
    return true;
}
function readAlias1(state) {
    var _position, alias, ch;
    ch = state.input.charCodeAt(state.position);
    if (ch !== 42) return false;
    ch = state.input.charCodeAt(++state.position);
    _position = state.position;
    while(ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)){
        ch = state.input.charCodeAt(++state.position);
    }
    if (state.position === _position) {
        throwError1(state, "name of an alias node must contain at least one character");
    }
    alias = state.input.slice(_position, state.position);
    if (!_hasOwnProperty$1.call(state.anchorMap, alias)) {
        throwError1(state, 'unidentified alias "' + alias + '"');
    }
    state.result = state.anchorMap[alias];
    skipSeparationSpace1(state, true, -1);
    return true;
}
function composeNode1(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
    var allowBlockStyles, allowBlockScalars, allowBlockCollections, indentStatus = 1, atNewLine = false, hasContent = false, typeIndex, typeQuantity, typeList, type2, flowIndent, blockIndent;
    if (state.listener !== null) {
        state.listener("open", state);
    }
    state.tag = null;
    state.anchor = null;
    state.kind = null;
    state.result = null;
    allowBlockStyles = allowBlockScalars = allowBlockCollections = CONTEXT_BLOCK_OUT1 === nodeContext || CONTEXT_BLOCK_IN1 === nodeContext;
    if (allowToSeek) {
        if (skipSeparationSpace1(state, true, -1)) {
            atNewLine = true;
            if (state.lineIndent > parentIndent) {
                indentStatus = 1;
            } else if (state.lineIndent === parentIndent) {
                indentStatus = 0;
            } else if (state.lineIndent < parentIndent) {
                indentStatus = -1;
            }
        }
    }
    if (indentStatus === 1) {
        while(readTagProperty1(state) || readAnchorProperty1(state)){
            if (skipSeparationSpace1(state, true, -1)) {
                atNewLine = true;
                allowBlockCollections = allowBlockStyles;
                if (state.lineIndent > parentIndent) {
                    indentStatus = 1;
                } else if (state.lineIndent === parentIndent) {
                    indentStatus = 0;
                } else if (state.lineIndent < parentIndent) {
                    indentStatus = -1;
                }
            } else {
                allowBlockCollections = false;
            }
        }
    }
    if (allowBlockCollections) {
        allowBlockCollections = atNewLine || allowCompact;
    }
    if (indentStatus === 1 || CONTEXT_BLOCK_OUT1 === nodeContext) {
        if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
            flowIndent = parentIndent;
        } else {
            flowIndent = parentIndent + 1;
        }
        blockIndent = state.position - state.lineStart;
        if (indentStatus === 1) {
            if (allowBlockCollections && (readBlockSequence1(state, blockIndent) || readBlockMapping1(state, blockIndent, flowIndent)) || readFlowCollection1(state, flowIndent)) {
                hasContent = true;
            } else {
                if (allowBlockScalars && readBlockScalar1(state, flowIndent) || readSingleQuotedScalar1(state, flowIndent) || readDoubleQuotedScalar1(state, flowIndent)) {
                    hasContent = true;
                } else if (readAlias1(state)) {
                    hasContent = true;
                    if (state.tag !== null || state.anchor !== null) {
                        throwError1(state, "alias node should not have any properties");
                    }
                } else if (readPlainScalar1(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
                    hasContent = true;
                    if (state.tag === null) {
                        state.tag = "?";
                    }
                }
                if (state.anchor !== null) {
                    state.anchorMap[state.anchor] = state.result;
                }
            }
        } else if (indentStatus === 0) {
            hasContent = allowBlockCollections && readBlockSequence1(state, blockIndent);
        }
    }
    if (state.tag === null) {
        if (state.anchor !== null) {
            state.anchorMap[state.anchor] = state.result;
        }
    } else if (state.tag === "?") {
        if (state.result !== null && state.kind !== "scalar") {
            throwError1(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
        }
        for(typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1){
            type2 = state.implicitTypes[typeIndex];
            if (type2.resolve(state.result)) {
                state.result = type2.construct(state.result);
                state.tag = type2.tag;
                if (state.anchor !== null) {
                    state.anchorMap[state.anchor] = state.result;
                }
                break;
            }
        }
    } else if (state.tag !== "!") {
        if (_hasOwnProperty$1.call(state.typeMap[state.kind || "fallback"], state.tag)) {
            type2 = state.typeMap[state.kind || "fallback"][state.tag];
        } else {
            type2 = null;
            typeList = state.typeMap.multi[state.kind || "fallback"];
            for(typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1){
                if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
                    type2 = typeList[typeIndex];
                    break;
                }
            }
        }
        if (!type2) {
            throwError1(state, "unknown tag !<" + state.tag + ">");
        }
        if (state.result !== null && type2.kind !== state.kind) {
            throwError1(state, "unacceptable node kind for !<" + state.tag + '> tag; it should be "' + type2.kind + '", not "' + state.kind + '"');
        }
        if (!type2.resolve(state.result, state.tag)) {
            throwError1(state, "cannot resolve a node with !<" + state.tag + "> explicit tag");
        } else {
            state.result = type2.construct(state.result, state.tag);
            if (state.anchor !== null) {
                state.anchorMap[state.anchor] = state.result;
            }
        }
    }
    if (state.listener !== null) {
        state.listener("close", state);
    }
    return state.tag !== null || state.anchor !== null || hasContent;
}
function readDocument1(state) {
    var documentStart = state.position, _position, directiveName, directiveArgs, hasDirectives = false, ch;
    state.version = null;
    state.checkLineBreaks = state.legacy;
    state.tagMap = Object.create(null);
    state.anchorMap = Object.create(null);
    while((ch = state.input.charCodeAt(state.position)) !== 0){
        skipSeparationSpace1(state, true, -1);
        ch = state.input.charCodeAt(state.position);
        if (state.lineIndent > 0 || ch !== 37) {
            break;
        }
        hasDirectives = true;
        ch = state.input.charCodeAt(++state.position);
        _position = state.position;
        while(ch !== 0 && !is_WS_OR_EOL(ch)){
            ch = state.input.charCodeAt(++state.position);
        }
        directiveName = state.input.slice(_position, state.position);
        directiveArgs = [];
        if (directiveName.length < 1) {
            throwError1(state, "directive name must not be less than one character in length");
        }
        while(ch !== 0){
            while(is_WHITE_SPACE(ch)){
                ch = state.input.charCodeAt(++state.position);
            }
            if (ch === 35) {
                do {
                    ch = state.input.charCodeAt(++state.position);
                }while (ch !== 0 && !is_EOL(ch))
                break;
            }
            if (is_EOL(ch)) break;
            _position = state.position;
            while(ch !== 0 && !is_WS_OR_EOL(ch)){
                ch = state.input.charCodeAt(++state.position);
            }
            directiveArgs.push(state.input.slice(_position, state.position));
        }
        if (ch !== 0) readLineBreak1(state);
        if (_hasOwnProperty$1.call(directiveHandlers1, directiveName)) {
            directiveHandlers1[directiveName](state, directiveName, directiveArgs);
        } else {
            throwWarning1(state, 'unknown document directive "' + directiveName + '"');
        }
    }
    skipSeparationSpace1(state, true, -1);
    if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45) {
        state.position += 3;
        skipSeparationSpace1(state, true, -1);
    } else if (hasDirectives) {
        throwError1(state, "directives end mark is expected");
    }
    composeNode1(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT1, false, true);
    skipSeparationSpace1(state, true, -1);
    if (state.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS1.test(state.input.slice(documentStart, state.position))) {
        throwWarning1(state, "non-ASCII line breaks are interpreted as content");
    }
    state.documents.push(state.result);
    if (state.position === state.lineStart && testDocumentSeparator1(state)) {
        if (state.input.charCodeAt(state.position) === 46) {
            state.position += 3;
            skipSeparationSpace1(state, true, -1);
        }
        return;
    }
    if (state.position < state.length - 1) {
        throwError1(state, "end of the stream or a document separator is expected");
    } else {
        return;
    }
}
function loadDocuments1(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);
        }
    }
    var state = new State$1(input, options);
    var nullpos = input.indexOf("\0");
    if (nullpos !== -1) {
        state.position = nullpos;
        throwError1(state, "null byte is not allowed in input");
    }
    state.input += "\0";
    while(state.input.charCodeAt(state.position) === 32){
        state.lineIndent += 1;
        state.position += 1;
    }
    while(state.position < state.length - 1){
        readDocument1(state);
    }
    return state.documents;
}
function loadAll$1(input, iterator, options) {
    if (iterator !== null && typeof iterator === "object" && typeof options === "undefined") {
        options = iterator;
        iterator = null;
    }
    var documents = loadDocuments1(input, options);
    if (typeof iterator !== "function") {
        return documents;
    }
    for(var index = 0, length = documents.length; index < length; index += 1){
        iterator(documents[index]);
    }
}
function load$1(input, options) {
    var documents = loadDocuments1(input, options);
    if (documents.length === 0) {
        return void 0;
    } else if (documents.length === 1) {
        return documents[0];
    }
    throw new exception("expected a single document in the stream, but found more");
}
var loadAll_1 = loadAll$1;
var load_1 = load$1;
var loader = {
    loadAll: loadAll_1,
    load: load_1
};
var _toString3 = Object.prototype.toString;
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var CHAR_BOM = 65279;
var CHAR_TAB = 9;
var CHAR_LINE_FEED = 10;
var CHAR_CARRIAGE_RETURN = 13;
var CHAR_SPACE = 32;
var CHAR_EXCLAMATION = 33;
var CHAR_DOUBLE_QUOTE = 34;
var CHAR_SHARP = 35;
var CHAR_PERCENT = 37;
var CHAR_AMPERSAND = 38;
var CHAR_SINGLE_QUOTE = 39;
var CHAR_ASTERISK = 42;
var CHAR_COMMA = 44;
var CHAR_MINUS = 45;
var CHAR_COLON = 58;
var CHAR_EQUALS = 61;
var CHAR_GREATER_THAN = 62;
var CHAR_QUESTION = 63;
var CHAR_COMMERCIAL_AT = 64;
var CHAR_LEFT_SQUARE_BRACKET = 91;
var CHAR_RIGHT_SQUARE_BRACKET = 93;
var CHAR_GRAVE_ACCENT = 96;
var CHAR_LEFT_CURLY_BRACKET = 123;
var CHAR_VERTICAL_LINE = 124;
var CHAR_RIGHT_CURLY_BRACKET = 125;
var ESCAPE_SEQUENCES1 = {};
ESCAPE_SEQUENCES1[0] = "\\0";
ESCAPE_SEQUENCES1[7] = "\\a";
ESCAPE_SEQUENCES1[8] = "\\b";
ESCAPE_SEQUENCES1[9] = "\\t";
ESCAPE_SEQUENCES1[10] = "\\n";
ESCAPE_SEQUENCES1[11] = "\\v";
ESCAPE_SEQUENCES1[12] = "\\f";
ESCAPE_SEQUENCES1[13] = "\\r";
ESCAPE_SEQUENCES1[27] = "\\e";
ESCAPE_SEQUENCES1[34] = '\\"';
ESCAPE_SEQUENCES1[92] = "\\\\";
ESCAPE_SEQUENCES1[133] = "\\N";
ESCAPE_SEQUENCES1[160] = "\\_";
ESCAPE_SEQUENCES1[8232] = "\\L";
ESCAPE_SEQUENCES1[8233] = "\\P";
var DEPRECATED_BOOLEANS_SYNTAX1 = [
    "y",
    "Y",
    "yes",
    "Yes",
    "YES",
    "on",
    "On",
    "ON",
    "n",
    "N",
    "no",
    "No",
    "NO",
    "off",
    "Off",
    "OFF"
];
var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;
function compileStyleMap1(schema2, map2) {
    var result1, keys, index, length, tag, style, type2;
    if (map2 === null) return {};
    result1 = {};
    keys = Object.keys(map2);
    for(index = 0, length = keys.length; index < length; index += 1){
        tag = keys[index];
        style = String(map2[tag]);
        if (tag.slice(0, 2) === "!!") {
            tag = "tag:yaml.org,2002:" + tag.slice(2);
        }
        type2 = schema2.compiledTypeMap["fallback"][tag];
        if (type2 && _hasOwnProperty.call(type2.styleAliases, style)) {
            style = type2.styleAliases[style];
        }
        result1[tag] = style;
    }
    return result1;
}
function encodeHex1(character) {
    var string, handle, length;
    string = character.toString(16).toUpperCase();
    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 exception("code point within a string may not be greater than 0xFFFFFFFF");
    }
    return "\\" + handle + common1.repeat("0", length - string.length) + string;
}
var QUOTING_TYPE_SINGLE = 1, QUOTING_TYPE_DOUBLE = 2;
function State2(options) {
    this.schema = options["schema"] || _default;
    this.indent = Math.max(1, options["indent"] || 2);
    this.noArrayIndent = options["noArrayIndent"] || false;
    this.skipInvalid = options["skipInvalid"] || false;
    this.flowLevel = common1.isNothing(options["flowLevel"]) ? -1 : options["flowLevel"];
    this.styleMap = compileStyleMap1(this.schema, options["styles"] || null);
    this.sortKeys = options["sortKeys"] || false;
    this.lineWidth = options["lineWidth"] || 80;
    this.noRefs = options["noRefs"] || false;
    this.noCompatMode = options["noCompatMode"] || false;
    this.condenseFlow = options["condenseFlow"] || false;
    this.quotingType = options["quotingType"] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
    this.forceQuotes = options["forceQuotes"] || false;
    this.replacer = typeof options["replacer"] === "function" ? options["replacer"] : null;
    this.implicitTypes = this.schema.compiledImplicit;
    this.explicitTypes = this.schema.compiledExplicit;
    this.tag = null;
    this.result = "";
    this.duplicates = [];
    this.usedDuplicates = null;
}
function indentString1(string, spaces) {
    var ind = common1.repeat(" ", spaces), position = 0, next = -1, result1 = "", line, length = string.length;
    while(position < length){
        next = string.indexOf("\n", position);
        if (next === -1) {
            line = string.slice(position);
            position = length;
        } else {
            line = string.slice(position, next + 1);
            position = next + 1;
        }
        if (line.length && line !== "\n") result1 += ind;
        result1 += line;
    }
    return result1;
}
function generateNextLine1(state, level) {
    return "\n" + common1.repeat(" ", state.indent * level);
}
function testImplicitResolving1(state, str2) {
    var index, length, type2;
    for(index = 0, length = state.implicitTypes.length; index < length; index += 1){
        type2 = state.implicitTypes[index];
        if (type2.resolve(str2)) {
            return true;
        }
    }
    return false;
}
function isWhitespace1(c) {
    return c === CHAR_SPACE || c === CHAR_TAB;
}
function isPrintable1(c) {
    return 32 <= c && c <= 126 || 161 <= c && c <= 55295 && c !== 8232 && c !== 8233 || 57344 <= c && c <= 65533 && c !== CHAR_BOM || 65536 <= c && c <= 1114111;
}
function isNsCharOrWhitespace(c) {
    return isPrintable1(c) && c !== CHAR_BOM && c !== CHAR_CARRIAGE_RETURN && c !== CHAR_LINE_FEED;
}
function isPlainSafe1(c, prev, inblock) {
    var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
    var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace1(c);
    return (inblock ? cIsNsCharOrWhitespace : cIsNsCharOrWhitespace && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET) && c !== CHAR_SHARP && !(prev === CHAR_COLON && !cIsNsChar) || isNsCharOrWhitespace(prev) && !isWhitespace1(prev) && c === CHAR_SHARP || prev === CHAR_COLON && cIsNsChar;
}
function isPlainSafeFirst1(c) {
    return isPrintable1(c) && c !== CHAR_BOM && !isWhitespace1(c) && c !== CHAR_MINUS && c !== CHAR_QUESTION && c !== CHAR_COLON && c !== CHAR_COMMA && c !== CHAR_LEFT_SQUARE_BRACKET && c !== CHAR_RIGHT_SQUARE_BRACKET && c !== CHAR_LEFT_CURLY_BRACKET && c !== CHAR_RIGHT_CURLY_BRACKET && c !== CHAR_SHARP && c !== CHAR_AMPERSAND && c !== CHAR_ASTERISK && c !== CHAR_EXCLAMATION && c !== CHAR_VERTICAL_LINE && c !== CHAR_EQUALS && c !== CHAR_GREATER_THAN && c !== CHAR_SINGLE_QUOTE && c !== CHAR_DOUBLE_QUOTE && c !== CHAR_PERCENT && c !== CHAR_COMMERCIAL_AT && c !== CHAR_GRAVE_ACCENT;
}
function isPlainSafeLast(c) {
    return !isWhitespace1(c) && c !== CHAR_COLON;
}
function codePointAt(string, pos) {
    var first = string.charCodeAt(pos), second;
    if (first >= 55296 && first <= 56319 && pos + 1 < string.length) {
        second = string.charCodeAt(pos + 1);
        if (second >= 56320 && second <= 57343) {
            return (first - 55296) * 1024 + second - 56320 + 65536;
        }
    }
    return first;
}
function needIndentIndicator1(string) {
    var leadingSpaceRe = /^\n* /;
    return leadingSpaceRe.test(string);
}
var STYLE_PLAIN1 = 1, STYLE_SINGLE1 = 2, STYLE_LITERAL1 = 3, STYLE_FOLDED1 = 4, STYLE_DOUBLE1 = 5;
function chooseScalarStyle1(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType, quotingType, forceQuotes, inblock) {
    var i1;
    var __char = 0;
    var prevChar = null;
    var hasLineBreak = false;
    var hasFoldableLine = false;
    var shouldTrackWidth = lineWidth !== -1;
    var previousLineBreak = -1;
    var plain = isPlainSafeFirst1(codePointAt(string, 0)) && isPlainSafeLast(codePointAt(string, string.length - 1));
    if (singleLineOnly || forceQuotes) {
        for(i1 = 0; i1 < string.length; __char >= 65536 ? i1 += 2 : i1++){
            __char = codePointAt(string, i1);
            if (!isPrintable1(__char)) {
                return STYLE_DOUBLE1;
            }
            plain = plain && isPlainSafe1(__char, prevChar, inblock);
            prevChar = __char;
        }
    } else {
        for(i1 = 0; i1 < string.length; __char >= 65536 ? i1 += 2 : i1++){
            __char = codePointAt(string, i1);
            if (__char === CHAR_LINE_FEED) {
                hasLineBreak = true;
                if (shouldTrackWidth) {
                    hasFoldableLine = hasFoldableLine || i1 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
                    previousLineBreak = i1;
                }
            } else if (!isPrintable1(__char)) {
                return STYLE_DOUBLE1;
            }
            plain = plain && isPlainSafe1(__char, prevChar, inblock);
            prevChar = __char;
        }
        hasFoldableLine = hasFoldableLine || shouldTrackWidth && i1 - previousLineBreak - 1 > lineWidth && string[previousLineBreak + 1] !== " ";
    }
    if (!hasLineBreak && !hasFoldableLine) {
        if (plain && !forceQuotes && !testAmbiguousType(string)) {
            return STYLE_PLAIN1;
        }
        return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE1 : STYLE_SINGLE1;
    }
    if (indentPerLevel > 9 && needIndentIndicator1(string)) {
        return STYLE_DOUBLE1;
    }
    if (!forceQuotes) {
        return hasFoldableLine ? STYLE_FOLDED1 : STYLE_LITERAL1;
    }
    return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE1 : STYLE_SINGLE1;
}
function writeScalar1(state, string, level, iskey, inblock) {
    state.dump = function() {
        if (string.length === 0) {
            return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
        }
        if (!state.noCompatMode) {
            if (DEPRECATED_BOOLEANS_SYNTAX1.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
                return state.quotingType === QUOTING_TYPE_DOUBLE ? '"' + string + '"' : "'" + string + "'";
            }
        }
        var indent = state.indent * Math.max(1, level);
        var lineWidth = state.lineWidth === -1 ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);
        var singleLineOnly = iskey || state.flowLevel > -1 && level >= state.flowLevel;
        function testAmbiguity(string2) {
            return testImplicitResolving1(state, string2);
        }
        switch(chooseScalarStyle1(string, singleLineOnly, state.indent, lineWidth, testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)){
            case STYLE_PLAIN1:
                return string;
            case STYLE_SINGLE1:
                return "'" + string.replace(/'/g, "''") + "'";
            case STYLE_LITERAL1:
                return "|" + blockHeader1(string, state.indent) + dropEndingNewline1(indentString1(string, indent));
            case STYLE_FOLDED1:
                return ">" + blockHeader1(string, state.indent) + dropEndingNewline1(indentString1(foldString1(string, lineWidth), indent));
            case STYLE_DOUBLE1:
                return '"' + escapeString1(string) + '"';
            default:
                throw new exception("impossible error: invalid scalar style");
        }
    }();
}
function blockHeader1(string, indentPerLevel) {
    var indentIndicator = needIndentIndicator1(string) ? String(indentPerLevel) : "";
    var clip = string[string.length - 1] === "\n";
    var keep = clip && (string[string.length - 2] === "\n" || string === "\n");
    var chomp = keep ? "+" : clip ? "" : "-";
    return indentIndicator + chomp + "\n";
}
function dropEndingNewline1(string) {
    return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
}
function foldString1(string, width) {
    var lineRe = /(\n+)([^\n]*)/g;
    var result1 = function() {
        var nextLF = string.indexOf("\n");
        nextLF = nextLF !== -1 ? nextLF : string.length;
        lineRe.lastIndex = nextLF;
        return foldLine1(string.slice(0, nextLF), width);
    }();
    var prevMoreIndented = string[0] === "\n" || string[0] === " ";
    var moreIndented;
    var match;
    while(match = lineRe.exec(string)){
        var prefix = match[1], line = match[2];
        moreIndented = line[0] === " ";
        result1 += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine1(line, width);
        prevMoreIndented = moreIndented;
    }
    return result1;
}
function foldLine1(line, width) {
    if (line === "" || line[0] === " ") return line;
    var breakRe = / [^ ]/g;
    var match;
    var start = 0, end, curr = 0, next = 0;
    var result1 = "";
    while(match = breakRe.exec(line)){
        next = match.index;
        if (next - start > width) {
            end = curr > start ? curr : next;
            result1 += "\n" + line.slice(start, end);
            start = end + 1;
        }
        curr = next;
    }
    result1 += "\n";
    if (line.length - start > width && curr > start) {
        result1 += line.slice(start, curr) + "\n" + line.slice(curr + 1);
    } else {
        result1 += line.slice(start);
    }
    return result1.slice(1);
}
function escapeString1(string) {
    var result1 = "";
    var __char = 0;
    var escapeSeq;
    for(var i1 = 0; i1 < string.length; __char >= 65536 ? i1 += 2 : i1++){
        __char = codePointAt(string, i1);
        escapeSeq = ESCAPE_SEQUENCES1[__char];
        if (!escapeSeq && isPrintable1(__char)) {
            result1 += string[i1];
            if (__char >= 65536) result1 += string[i1 + 1];
        } else {
            result1 += escapeSeq || encodeHex1(__char);
        }
    }
    return result1;
}
function writeFlowSequence1(state, level, object) {
    var _result = "", _tag = state.tag, index, length, value;
    for(index = 0, length = object.length; index < length; index += 1){
        value = object[index];
        if (state.replacer) {
            value = state.replacer.call(object, String(index), value);
        }
        if (writeNode1(state, level, value, false, false) || typeof value === "undefined" && writeNode1(state, level, null, false, false)) {
            if (_result !== "") _result += "," + (!state.condenseFlow ? " " : "");
            _result += state.dump;
        }
    }
    state.tag = _tag;
    state.dump = "[" + _result + "]";
}
function writeBlockSequence1(state, level, object, compact) {
    var _result = "", _tag = state.tag, index, length, value;
    for(index = 0, length = object.length; index < length; index += 1){
        value = object[index];
        if (state.replacer) {
            value = state.replacer.call(object, String(index), value);
        }
        if (writeNode1(state, level + 1, value, true, true, false, true) || typeof value === "undefined" && writeNode1(state, level + 1, null, true, true, false, true)) {
            if (!compact || _result !== "") {
                _result += generateNextLine1(state, level);
            }
            if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
                _result += "-";
            } else {
                _result += "- ";
            }
            _result += state.dump;
        }
    }
    state.tag = _tag;
    state.dump = _result || "[]";
}
function writeFlowMapping1(state, level, object) {
    var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer;
    for(index = 0, length = objectKeyList.length; index < length; index += 1){
        pairBuffer = "";
        if (_result !== "") pairBuffer += ", ";
        if (state.condenseFlow) pairBuffer += '"';
        objectKey = objectKeyList[index];
        objectValue = object[objectKey];
        if (state.replacer) {
            objectValue = state.replacer.call(object, objectKey, objectValue);
        }
        if (!writeNode1(state, level, objectKey, false, false)) {
            continue;
        }
        if (state.dump.length > 1024) pairBuffer += "? ";
        pairBuffer += state.dump + (state.condenseFlow ? '"' : "") + ":" + (state.condenseFlow ? "" : " ");
        if (!writeNode1(state, level, objectValue, false, false)) {
            continue;
        }
        pairBuffer += state.dump;
        _result += pairBuffer;
    }
    state.tag = _tag;
    state.dump = "{" + _result + "}";
}
function writeBlockMapping1(state, level, object, compact) {
    var _result = "", _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer;
    if (state.sortKeys === true) {
        objectKeyList.sort();
    } else if (typeof state.sortKeys === "function") {
        objectKeyList.sort(state.sortKeys);
    } else if (state.sortKeys) {
        throw new exception("sortKeys must be a boolean or a function");
    }
    for(index = 0, length = objectKeyList.length; index < length; index += 1){
        pairBuffer = "";
        if (!compact || _result !== "") {
            pairBuffer += generateNextLine1(state, level);
        }
        objectKey = objectKeyList[index];
        objectValue = object[objectKey];
        if (state.replacer) {
            objectValue = state.replacer.call(object, objectKey, objectValue);
        }
        if (!writeNode1(state, level + 1, objectKey, true, true, true)) {
            continue;
        }
        explicitPair = state.tag !== null && state.tag !== "?" || state.dump && state.dump.length > 1024;
        if (explicitPair) {
            if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
                pairBuffer += "?";
            } else {
                pairBuffer += "? ";
            }
        }
        pairBuffer += state.dump;
        if (explicitPair) {
            pairBuffer += generateNextLine1(state, level);
        }
        if (!writeNode1(state, level + 1, objectValue, true, explicitPair)) {
            continue;
        }
        if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
            pairBuffer += ":";
        } else {
            pairBuffer += ": ";
        }
        pairBuffer += state.dump;
        _result += pairBuffer;
    }
    state.tag = _tag;
    state.dump = _result || "{}";
}
function detectType1(state, object, explicit) {
    var _result, typeList, index, length, type2, style;
    typeList = explicit ? state.explicitTypes : state.implicitTypes;
    for(index = 0, length = typeList.length; index < length; index += 1){
        type2 = typeList[index];
        if ((type2.instanceOf || type2.predicate) && (!type2.instanceOf || typeof object === "object" && object instanceof type2.instanceOf) && (!type2.predicate || type2.predicate(object))) {
            if (explicit) {
                if (type2.multi && type2.representName) {
                    state.tag = type2.representName(object);
                } else {
                    state.tag = type2.tag;
                }
            } else {
                state.tag = "?";
            }
            if (type2.represent) {
                style = state.styleMap[type2.tag] || type2.defaultStyle;
                if (_toString3.call(type2.represent) === "[object Function]") {
                    _result = type2.represent(object, style);
                } else if (_hasOwnProperty.call(type2.represent, style)) {
                    _result = type2.represent[style](object, style);
                } else {
                    throw new exception("!<" + type2.tag + '> tag resolver accepts not "' + style + '" style');
                }
                state.dump = _result;
            }
            return true;
        }
    }
    return false;
}
function writeNode1(state, level, object, block, compact, iskey, isblockseq) {
    state.tag = null;
    state.dump = object;
    if (!detectType1(state, object, false)) {
        detectType1(state, object, true);
    }
    var type2 = _toString3.call(state.dump);
    var inblock = block;
    var tagStr;
    if (block) {
        block = state.flowLevel < 0 || state.flowLevel > level;
    }
    var objectOrArray = type2 === "[object Object]" || type2 === "[object Array]", duplicateIndex, duplicate;
    if (objectOrArray) {
        duplicateIndex = state.duplicates.indexOf(object);
        duplicate = duplicateIndex !== -1;
    }
    if (state.tag !== null && state.tag !== "?" || duplicate || state.indent !== 2 && level > 0) {
        compact = false;
    }
    if (duplicate && state.usedDuplicates[duplicateIndex]) {
        state.dump = "*ref_" + duplicateIndex;
    } else {
        if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
            state.usedDuplicates[duplicateIndex] = true;
        }
        if (type2 === "[object Object]") {
            if (block && Object.keys(state.dump).length !== 0) {
                writeBlockMapping1(state, level, state.dump, compact);
                if (duplicate) {
                    state.dump = "&ref_" + duplicateIndex + state.dump;
                }
            } else {
                writeFlowMapping1(state, level, state.dump);
                if (duplicate) {
                    state.dump = "&ref_" + duplicateIndex + " " + state.dump;
                }
            }
        } else if (type2 === "[object Array]") {
            if (block && state.dump.length !== 0) {
                if (state.noArrayIndent && !isblockseq && level > 0) {
                    writeBlockSequence1(state, level - 1, state.dump, compact);
                } else {
                    writeBlockSequence1(state, level, state.dump, compact);
                }
                if (duplicate) {
                    state.dump = "&ref_" + duplicateIndex + state.dump;
                }
            } else {
                writeFlowSequence1(state, level, state.dump);
                if (duplicate) {
                    state.dump = "&ref_" + duplicateIndex + " " + state.dump;
                }
            }
        } else if (type2 === "[object String]") {
            if (state.tag !== "?") {
                writeScalar1(state, state.dump, level, iskey, inblock);
            }
        } else if (type2 === "[object Undefined]") {
            return false;
        } else {
            if (state.skipInvalid) return false;
            throw new exception("unacceptable kind of an object to dump " + type2);
        }
        if (state.tag !== null && state.tag !== "?") {
            tagStr = encodeURI(state.tag[0] === "!" ? state.tag.slice(1) : state.tag).replace(/!/g, "%21");
            if (state.tag[0] === "!") {
                tagStr = "!" + tagStr;
            } else if (tagStr.slice(0, 18) === "tag:yaml.org,2002:") {
                tagStr = "!!" + tagStr.slice(18);
            } else {
                tagStr = "!<" + tagStr + ">";
            }
            state.dump = tagStr + " " + state.dump;
        }
    }
    return true;
}
function getDuplicateReferences1(object, state) {
    var objects = [], duplicatesIndexes = [], index, length;
    inspectNode1(object, objects, duplicatesIndexes);
    for(index = 0, length = duplicatesIndexes.length; index < length; index += 1){
        state.duplicates.push(objects[duplicatesIndexes[index]]);
    }
    state.usedDuplicates = new Array(length);
}
function inspectNode1(object, objects, duplicatesIndexes) {
    var objectKeyList, index, length;
    if (object !== null && typeof object === "object") {
        index = objects.indexOf(object);
        if (index !== -1) {
            if (duplicatesIndexes.indexOf(index) === -1) {
                duplicatesIndexes.push(index);
            }
        } else {
            objects.push(object);
            if (Array.isArray(object)) {
                for(index = 0, length = object.length; index < length; index += 1){
                    inspectNode1(object[index], objects, duplicatesIndexes);
                }
            } else {
                objectKeyList = Object.keys(object);
                for(index = 0, length = objectKeyList.length; index < length; index += 1){
                    inspectNode1(object[objectKeyList[index]], objects, duplicatesIndexes);
                }
            }
        }
    }
}
function dump$1(input, options) {
    options = options || {};
    var state = new State2(options);
    if (!state.noRefs) getDuplicateReferences1(input, state);
    var value = input;
    if (state.replacer) {
        value = state.replacer.call({
            "": value
        }, "", value);
    }
    if (writeNode1(state, 0, value, true, true)) return state.dump + "\n";
    return "";
}
var dump_1 = dump$1;
var dumper = {
    dump: dump_1
};
function renamed(from, to) {
    return function() {
        throw new Error("Function yaml." + from + " is removed in js-yaml 4. Use yaml." + to + " instead, which is now safe by default.");
    };
}
var Type2 = type;
var Schema1 = schema;
var load1 = loader.load;
loader.loadAll;
dumper.dump;
renamed("safeLoad", "load");
renamed("safeLoadAll", "loadAll");
renamed("safeDump", "dump");
const QuartoJSONSchema = new Schema1({
    implicit: [
        _null,
        bool1,
        __int1,
        __float1
    ],
    include: [
        failsafe1
    ],
    explicit: [
        new Type2("!expr", {
            kind: "scalar",
            construct (data) {
                const result1 = data !== null ? data : "";
                return {
                    value: result1,
                    tag: "!expr"
                };
            }
        })
    ]
});
function postProcessAnnotation(parse) {
    if (parse.components.length === 1 && parse.start === parse.components[0].start && parse.end === parse.components[0].end) {
        return postProcessAnnotation(parse.components[0]);
    } else {
        parse.components = parse.components.map(postProcessAnnotation);
        return parse;
    }
}
function jsYamlParseLenient(yml) {
    try {
        return load1(yml, {
            schema: QuartoJSONSchema
        });
    } catch (_e) {
        return yml;
    }
}
function readAnnotatedYamlFromMappedString(mappedSource, lenient = false) {
    if (lenient) {
        const parser = getTreeSitterSync();
        const tree = parser.parse(mappedSource.value);
        const treeSitterAnnotation = buildTreeSitterAnnotation(tree, mappedSource);
        if (treeSitterAnnotation) {
            return treeSitterAnnotation;
        }
    }
    try {
        return buildJsYamlAnnotation(mappedSource);
    } catch (e) {
        if (e.name === "YAMLError") {
            e.name = "YAML Parsing";
        }
        const m = e.stack.split("\n")[0].match(/^.+ \((\d+):(\d+)\)$/);
        if (m) {
            const m1 = mappedSource.value.match(/([^\s]+):([^\s]+)/);
            if (m1 && e.reason.match(/a multiline key may not be an implicit key/)) {
                e.name = "YAML Parse Error";
                e.reason = "block has incorrect key formatting";
                const { originalString } = mappedSource.map(m1.index, true);
                const filename = originalString.fileName;
                const map = mappedSource.map(m1.index);
                const { line, column } = indexToLineCol(map.originalString.value)(map.index);
                const sourceContext = createSourceContext(mappedSource, {
                    start: m1.index + 1,
                    end: m1.index + m1[0].length
                });
                e.stack = `${e.reason} (${filename}, ${line + 1}:${column + 1})\n${sourceContext}`;
                e.message = e.stack;
                e.message = `${e.message}\n${tidyverseInfo("Is it possible you missed a space after a colon in the key-value mapping?")}`;
            } else {
                const f = lineColToIndex(mappedSource.value);
                const location = {
                    line: Number(m[1]) - 1,
                    column: Number(m[2] - 1)
                };
                const offset = f(location);
                const { originalString } = mappedSource.map(offset, true);
                const filename = originalString.fileName;
                const f2 = mappedIndexToLineCol(mappedSource);
                const { line, column } = f2(offset);
                const sourceContext = createSourceContext(mappedSource, {
                    start: offset,
                    end: offset + 1
                });
                e.stack = `${e.reason} (${filename}, ${line + 1}:${column + 1})\n${sourceContext}`;
                e.message = e.stack;
                if (mappedLines(mappedSource)[location.line].value.indexOf("!expr") !== -1 && e.reason.match(/bad indentation of a mapping entry/)) {
                    e.message = `${e.message}\n${tidyverseInfo("YAML tags like !expr must be followed by YAML strings.")}\n${tidyverseInfo("Is it possible you need to quote the value you passed to !expr ?")}`;
                }
            }
            e.stack = "";
        }
        throw e;
    }
}
function buildJsYamlAnnotation(mappedYaml) {
    const yml = mappedYaml.value;
    const stack = [];
    const results = [];
    function listener(what, state) {
        const { result: result1, position, kind } = state;
        if (what === "close") {
            const { position: openPosition, kind: openKind } = 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.trimStart().length;
            const rightTrim = rawRange.length - rawRange.trimEnd().length;
            if (openKind === null && kind === null) {} else if (rawRange.trim().length === 0) {
                results.push({
                    start: position - rightTrim,
                    end: position - rightTrim,
                    result: result1,
                    components,
                    kind,
                    source: mappedYaml
                });
            } else {
                results.push({
                    start: openPosition + leftTrim,
                    end: position - rightTrim,
                    result: result1,
                    components,
                    kind,
                    source: mappedYaml
                });
            }
        } else {
            stack.push({
                position,
                kind
            });
        }
    }
    load1(yml, {
        listener,
        schema: QuartoJSONSchema
    });
    if (results.length === 0) {
        return {
            start: 0,
            end: 0,
            result: null,
            kind: "null",
            components: [],
            source: mappedYaml
        };
    }
    if (results.length !== 1) {
        throw new InternalError(`Expected a single result, got ${results.length} instead`);
    }
    JSON.stringify(results[0]);
    return postProcessAnnotation(results[0]);
}
function buildTreeSitterAnnotation(tree, mappedSource) {
    const errors = [];
    const singletonBuild = (node)=>{
        let tag = undefined;
        for (const child of node.children){
            if (child.type === "tag") {
                tag = child;
                continue;
            }
            if (child.type !== "comment") {
                const result1 = buildNode(child, node.endIndex);
                if (tag) {
                    return annotateTag(result1, tag, node);
                } else {
                    return result1;
                }
            }
        }
        return annotateEmpty(node.endIndex);
    };
    const buildNode = (node, endIndex)=>{
        if (node === null) {
            return annotateEmpty(endIndex === undefined ? -1 : endIndex);
        }
        if (dispatch[node.type] === undefined) {
            return annotateEmpty(endIndex || node.endIndex || -1);
        }
        return dispatch[node.type](node);
    };
    const annotateEmpty = (position)=>{
        return {
            start: position,
            end: position,
            result: null,
            kind: "<<EMPTY>>",
            components: [],
            source: mappedSource
        };
    };
    const annotate = (node, result1, components)=>{
        return {
            start: node.startIndex,
            end: node.endIndex,
            result: result1,
            kind: node.type,
            components,
            source: mappedSource
        };
    };
    const annotateTag = (innerParse, tagNode, outerNode)=>{
        const tagParse = annotate(tagNode, tagNode.text, []);
        const result1 = annotate(outerNode, {
            tag: tagNode.text,
            value: innerParse.result
        }, [
            tagParse,
            innerParse
        ]);
        return result1;
    };
    const buildPair = (node)=>{
        let key, value;
        const children = node.children.filter((n)=>n.type !== "comment");
        if (children.length === 3) {
            key = annotate(children[0], children[0].text, []);
            value = buildNode(children[2], node.endIndex);
        } else if (children.length === 2) {
            key = annotate(children[0], children[0].text, []);
            value = annotateEmpty(node.endIndex);
        } else {
            key = annotateEmpty(node.endIndex);
            value = annotateEmpty(node.endIndex);
        }
        return annotate(node, {
            key: key.result,
            value: value.result
        }, [
            key,
            value
        ]);
    };
    const dispatch = {
        "stream": singletonBuild,
        "document": singletonBuild,
        "block_node": singletonBuild,
        "flow_node": singletonBuild,
        "double_quote_scalar": (node)=>{
            return annotate(node, jsYamlParseLenient(node.text), []);
        },
        "single_quote_scalar": (node)=>{
            return annotate(node, jsYamlParseLenient(node.text), []);
        },
        "plain_scalar": (node)=>{
            return annotate(node, jsYamlParseLenient(node.text), []);
        },
        "block_scalar": (node)=>{
            return annotate(node, jsYamlParseLenient(node.text), []);
        },
        "block_sequence": (node)=>{
            const result1 = [], components = [];
            for(let i1 = 0; i1 < node.childCount; ++i1){
                const child = node.child(i1);
                if (child.type !== "block_sequence_item") {
                    continue;
                }
                const component = buildNode(child, node.endIndex);
                components.push(component);
                result1.push(component && component.result);
            }
            return annotate(node, result1, components);
        },
        "block_sequence_item": (node)=>{
            if (node.childCount < 2) {
                return annotateEmpty(node.endIndex);
            } else {
                return buildNode(node.child(1), node.endIndex);
            }
        },
        "flow_sequence": (node)=>{
            const result1 = [], components = [];
            for(let i1 = 0; i1 < node.childCount; ++i1){
                const child = node.child(i1);
                if (child.type !== "flow_node") {
                    continue;
                }
                const component = buildNode(child, node.endIndex);
                components.push(component);
                result1.push(component.result);
            }
            return annotate(node, result1, components);
        },
        "block_mapping": (node)=>{
            const result1 = {}, components = [];
            for(let i1 = 0; i1 < node.childCount; ++i1){
                const child = node.child(i1);
                let component;
                if (child.type === "ERROR") {
                    result1[child.text] = "<<ERROR>>";
                    const key = annotate(child, child.text, []);
                    const value = annotateEmpty(child.endIndex);
                    component = annotate(child, {
                        key: key.result,
                        value: value.result
                    }, [
                        key,
                        value
                    ]);
                } else if (child.type !== "block_mapping_pair") {
                    continue;
                } else {
                    component = buildNode(child, node.endIndex);
                }
                const { key, value } = component.result;
                result1[String(key)] = value;
                components.push(...component.components);
            }
            return annotate(node, result1, components);
        },
        "flow_pair": buildPair,
        "flow_mapping": (node)=>{
            const result1 = {}, components = [];
            for(let i1 = 0; i1 < node.childCount; ++i1){
                const child = node.child(i1);
                if (child.type === "flow_node") {
                    continue;
                }
                if (child.type === "flow_pair") {
                    const component = buildNode(child, node.endIndex);
                    const { key, value } = component.result;
                    result1[String(key)] = value;
                    components.push(...component.components);
                }
            }
            return annotate(node, result1, components);
        },
        "block_mapping_pair": buildPair
    };
    const result1 = buildNode(tree.rootNode, tree.rootNode.endIndex);
    if (errors.length) {
        result1.errors = errors;
    }
    const parsedSize = tree.rootNode.text.trim().length;
    const codeSize = mappedSource.value.trim().length;
    const lossage = parsedSize / codeSize;
    if (lossage < 0.95) {
        return null;
    }
    return result1;
}
function locateAnnotation(annotation, position, kind) {
    const originalSource = annotation.source;
    kind = kind || "value";
    for(let i1 = 0; i1 < position.length; ++i1){
        const value = position[i1];
        if (typeof value === "number") {
            const inner = annotation.components[value];
            if (inner === undefined) {
                throw new InternalError("invalid path for locateAnnotation");
            }
            annotation = inner;
        } else {
            let found = false;
            for(let j = 0; j < annotation.components.length; j += 2){
                if (originalSource.value.substring(annotation.components[j].start, annotation.components[j].end).trim() === value) {
                    if (i1 === position.length - 1) {
                        if (kind === "key") {
                            annotation = annotation.components[j];
                        } else {
                            annotation = annotation.components[j + 1];
                        }
                    }
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new InternalError("invalid path for locateAnnotation");
            }
        }
    }
    return annotation;
}
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;
    }
}
const isObject3 = (value)=>{
    const type = typeof value;
    return value !== null && (type === "object" || type === "function");
};
async function readAndValidateYamlFromMappedString(mappedYaml, schema, pruneErrors = true, lenient = false) {
    const annotation = await readAnnotatedYamlFromMappedString(mappedYaml, lenient);
    if (annotation === null) {
        throw new Error("Parse error in readAnnotatedYamlFromMappedString");
    }
    const validateYaml = !isObject3(annotation.result) || annotation.result["validate-yaml"] !== false;
    if (!validateYaml) {
        return {
            yaml: annotation.result,
            yamlValidationErrors: []
        };
    }
    const validate = async (validator)=>{
        const valResult = await validator.validateParse(mappedYaml, annotation, pruneErrors);
        return {
            yaml: annotation.result,
            yamlValidationErrors: valResult.errors
        };
    };
    if (typeof annotation.result === "object" && !Array.isArray(annotation.result)) {
        const preCheckResult = await withValidator(getSchemaDefinition("bad-parse-schema"), validate);
        if (preCheckResult.yamlValidationErrors.length !== 0) {
            return preCheckResult;
        }
    }
    const result1 = await withValidator(schema, validate);
    return result1;
}
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 result1 = Object.assign({}, schema);
    if (yaml.errorDescription) {
        result1.description = yaml.errorDescription;
    }
    if (yaml.errorMessage) {
        result1.errorMessage = yaml.errorMessage;
    }
    return result1;
}
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 result1 = arraySchema(convertFromYaml(yaml.arrayOf.schema));
        return setBaseSchemaProperties(yaml, setBaseSchemaProperties(yaml.arrayOf, result1));
    } 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 && typeof schema.namingConvention === "string") {
        switch(schema.namingConvention){
            case "ignore":
                params.namingConvention = "ignore";
                break;
            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 InternalError(`Unrecognized naming convention ${schema.namingConvention} should have failed validation`);
        }
    } else {
        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.closed = true;
    }
    if (schema.additionalProperties !== undefined) {
        if (schema.additionalProperties === false) {
            params.additionalProperties = false;
        } else {
            params.additionalProperties = convertFromYaml(schema.additionalProperties);
        }
    }
    if (schema["super"]) {
        if (Array.isArray(schema["super"])) {
            params.baseSchema = schema["super"].map((s)=>convertFromYaml(s));
        } else {
            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: "any",
            schema: anySchema()
        },
        {
            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 InternalError("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 result1 = obj || {};
    for (const field of yaml){
        let schema = convertFromYaml(field.schema);
        schema = annotateSchemaFromField(field, schema);
        result1[field.name] = schema;
        if (field.alias) {
            result1[field.alias] = schema;
        }
    }
    return result1;
}
function schemaFieldsFromGlob(globPath, testFun) {
    const result1 = [];
    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)) {
                result1.push({
                    schemaId,
                    field
                });
            }
        }
    }
    return result1;
}
memoize1(()=>{
    const groups = getYamlIntelligenceResource("schema/groups.yml");
    const result1 = [];
    for (const [topLevel, sub] of Object.entries(groups)){
        for (const key of Object.keys(sub)){
            result1.push(`${topLevel}-${key}`);
        }
    }
    return result1;
}, ()=>"const");
function objectRefSchemaFromContextGlob(contextGlob, testFun) {
    const regexp = globToRegExp3(contextGlob);
    return objectRefSchemaFromGlob("schema/{document,cell}-*.yml", (field, path)=>{
        if (testFun !== undefined && !testFun(field, path)) {
            return false;
        }
        const pathContext = path.split("/").slice(-1)[0].slice(0, -4);
        const schemaContexts = field !== undefined && field.tags !== undefined && field.tags.contexts || [];
        if (pathContext.match(regexp)) {
            return true;
        }
        return schemaContexts.some((c)=>c.match(regexp));
    });
}
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 path = "schema/{cell-*,document-*,project}.yml";
    for (const [file, fields] of expandResourceGlob(path)){
        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 result1 = await thunk();
        const { errorHandlers } = result1;
        schema = result1.schema;
        if (schemaId !== schema.$id) {
            schema = idSchema(schema, schemaId);
        }
        define1(schema);
        for (const fun of errorHandlers){
            addValidatorErrorHandler(schema, fun);
        }
        return refSchema(schema.$id, schema.description || `be a {schema['$id']}`);
    };
}
function define1(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 InternalError(`Unnamed schema in definitions`);
        }
        setSchemaDefinition(schema);
    }));
}
function getFormatExecuteOptionsSchema() {
    const schema = idSchema(objectRefSchemaFromContextGlob("document-execute"), "front-matter-execute");
    define1(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, format) {
    const formats = schema && schema.tags && schema.tags.formats;
    if (formats === undefined) {
        return true;
    }
    const disabled = formats.filter((f)=>f.startsWith("!")).map((f)=>f.slice(1));
    const enabled = formats.filter((f)=>!f.startsWith("!"));
    if (disabled.length > 0 && expandFormatAliases(disabled).indexOf(format) !== -1) {
        return false;
    }
    if (enabled.length > 0 && expandFormatAliases(enabled).indexOf(format) === -1) {
        return false;
    }
    return true;
}
function getFormatSchema(format) {
    const schema = objectRefSchemaFromContextGlob("document-*", (field)=>{
        const schema = schemaFromField(field);
        return useSchema(schema, format);
    });
    return anyOfSchema(schema, enumSchema("default"));
}
function pandocFormatsResource() {
    return getYamlIntelligenceResource("pandoc/formats.yml");
}
async function makeFrontMatterFormatSchema(nonStrict = false) {
    const hideFormat = (format)=>{
        const hideList = [
            "html",
            "epub",
            "docbook"
        ];
        const hidden = hideList.some((h)=>format.startsWith(h) && format.length > h.length);
        return {
            name: format,
            hidden
        };
    };
    const formatSchemaDescriptorList = (await pandocFormatsResource()).concat("md", "hugo", "dashboard", "email").map((format)=>{
        const { name, hidden } = hideFormat(format);
        return {
            regex: `^(.+-)?${name}([-+].+)?$`,
            schema: getFormatSchema(name),
            name,
            hidden
        };
    });
    const formatSchemas = formatSchemaDescriptorList.map(({ regex, schema })=>[
            regex,
            schema
        ]);
    const plusFormatStringSchemas = formatSchemaDescriptorList.map(({ regex, name, hidden })=>{
        const schema = regexSchema(regex, `be '${name}'`);
        if (hidden) {
            return schema;
        }
        return completeSchema(schema, name);
    });
    const luaFilenameS = regexSchema("^.+\.lua$");
    plusFormatStringSchemas.push(luaFilenameS);
    const completionsObject = fromEntries(formatSchemaDescriptorList.filter(({ hidden })=>!hidden).map(({ name })=>[
            name,
            {
                type: "key",
                display: name,
                value: `${name}: `,
                description: `be '${name}'`,
                suggest_on_accept: true
            }
        ]));
    return errorMessageSchema(anyOfSchema(describeSchema(anyOfSchema(...plusFormatStringSchemas), "the name of a pandoc-supported output format"), objectSchema({
        propertyNames: luaFilenameS
    }), 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, refSchema("quarto-dev-schema", ""))),
        errorHandlers: []
    };
}, "front-matter");
function Diff() {}
Diff.prototype = {
    diff: function diff(oldString, newString) {
        var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
        var callback = options.callback;
        if (typeof options === 'function') {
            callback = options;
            options = {};
        }
        this.options = options;
        var self1 = this;
        function done(value) {
            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;
        if (options.maxEditLength) {
            maxEditLength = Math.min(maxEditLength, options.maxEditLength);
        }
        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 addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
                if (addPath) {
                    bestPath[diagonalPath - 1] = undefined;
                }
                var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
                if (!canAdd && !canRemove) {
                    bestPath[diagonalPath] = undefined;
                    continue;
                }
                if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
                    basePath = clonePath(removePath);
                    self1.pushComponent(basePath.components, undefined, true);
                } else {
                    basePath = addPath;
                    basePath.newPos++;
                    self1.pushComponent(basePath.components, true, undefined);
                }
                _oldPos = self1.extractCommon(basePath, newString, oldString, diagonalPath);
                if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
                    return done(buildValues(self1, basePath.components, newString, oldString, self1.useLongestToken));
                } else {
                    bestPath[diagonalPath] = basePath;
                }
            }
            editLength++;
        }
        while(editLength <= maxEditLength){
            var ret = execEditLength();
            if (callback && callback(ret, editLength, maxEditLength)) {
                return ret;
            }
            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: added,
                removed: removed
            };
        } else {
            components.push({
                count: 1,
                added: added,
                removed: 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 i1 = 0; i1 < array.length; i1++){
            if (array[i1]) {
                ret.push(array[i1]);
            }
        }
        return ret;
    },
    castInput: function castInput(value) {
        return value;
    },
    tokenize: function tokenize(value) {
        return value.split('');
    },
    join: function join(chars) {
        return chars.join('');
    }
};
function buildValues(diff, 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(value, i1) {
                    var oldValue = oldString[oldPos + i1];
                    return oldValue.length > value.length ? oldValue : value;
                });
                component.value = diff.join(value);
            } else {
                component.value = diff.join(newString.slice(newPos, newPos + component.count));
            }
            newPos += component.count;
            if (!component.added) {
                oldPos += component.count;
            }
        } else {
            component.value = diff.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) && diff.equals('', lastComponent.value)) {
        components[componentLen - 2].value += lastComponent.value;
        components.pop();
    }
    return components;
}
function clonePath(path) {
    return {
        newPos: path.newPos,
        components: path.components.slice(0)
    };
}
new Diff();
var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
var reWhitespace1 = /\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 && !reWhitespace1.test(left) && !reWhitespace1.test(right);
};
wordDiff.tokenize = function(value) {
    var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
    for(var i1 = 0; i1 < tokens.length - 1; i1++){
        if (!tokens[i1 + 1] && tokens[i1 + 2] && extendedWordChars.test(tokens[i1]) && extendedWordChars.test(tokens[i1 + 2])) {
            tokens[i1] += tokens[i1 + 2];
            tokens.splice(i1 + 1, 2);
            i1--;
        }
    }
    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 i1 = 0; i1 < linesAndNewlines.length; i1++){
        var line = linesAndNewlines[i1];
        if (i1 % 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(obj) {
            return typeof obj;
        };
    } else {
        _typeof = function(obj) {
            return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
    }
    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 i1;
    for(i1 = 0; i1 < stack.length; i1 += 1){
        if (stack[i1] === obj) {
            return replacementStack[i1];
        }
    }
    var canonicalizedObj;
    if ('[object Array]' === objectPrototypeToString.call(obj)) {
        stack.push(obj);
        canonicalizedObj = new Array(obj.length);
        replacementStack.push(canonicalizedObj);
        for(i1 = 0; i1 < obj.length; i1 += 1){
            canonicalizedObj[i1] = canonicalize(obj[i1], 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(i1 = 0; i1 < sortedKeys.length; i1 += 1){
            _key = sortedKeys[i1];
            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;
};
const nodeStack = [
    {
        name: "global",
        children: [
            {
                name: "deno-init",
                start: 0,
                end: performance.now(),
                elapsed: performance.now(),
                children: []
            }
        ],
        start: 0,
        end: 0
    }
];
function withTiming(name, fun) {
    push(name);
    try {
        const result1 = fun();
        return result1;
    } finally{
        pop();
    }
}
async function withTimingAsync(name, fun) {
    push(name);
    try {
        const result1 = await fun();
        pop();
        return result1;
    } catch (e) {
        pop();
        throw e;
    }
}
function push(name) {
    nodeStack.push({
        name,
        start: performance.now(),
        end: 0,
        children: []
    });
}
function pop(at) {
    if (nodeStack.length <= 1) {
        throw new Error("Can't pop top node");
    }
    const node = nodeStack.pop();
    node.end = at ?? performance.now();
    node.elapsed = node.end - node.start;
    nodeStack[nodeStack.length - 1].children.push(node);
}
function getData() {
    nodeStack[0].end = performance.now();
    nodeStack[0].elapsed = nodeStack[0].end - nodeStack[0].start;
    return nodeStack[0];
}
function insertExplicitTimingEntries(start, end, entries, groupName) {
    const [theirStart, ourStart] = start;
    const [theirEnd, _] = end;
    nodeStack.push({
        name: groupName,
        start: ourStart,
        end: 0,
        children: []
    });
    let prevTime = ourStart;
    if (entries.length && entries[0].name === "_start") {
        prevTime = entries[0].time - theirStart + ourStart;
        entries = entries.slice(1);
    }
    for (const entry of entries){
        nodeStack.push({
            name: entry.name,
            start: prevTime,
            end: 0,
            children: []
        });
        prevTime = entry.time - theirStart + ourStart;
        pop(prevTime);
    }
    prevTime = theirEnd - theirStart + ourStart;
    pop(prevTime);
}
async function getLuaTiming() {
    if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
        return [
            Number((await execProcess({
                cmd: [
                    "python",
                    "-c",
                    "import time; print(time.time() * 1000)"
                ],
                stdout: "piped"
            })).stdout),
            performance.now()
        ];
    } else {
        return [
            0,
            0
        ];
    }
}
function mappedDiff(source, target) {
    return withTiming("mapped-diff", ()=>{
        const sourceLineRanges = rangedLines(source.value).map((x)=>x.range);
        let sourceCursor = 0;
        const resultChunks = [];
        const started = performance.now();
        const diffResult = diffLines(source.value, target, ()=>{
            const now = performance.now();
            if (now - started > 200) {
                return true;
            }
        });
        if (diffResult === undefined) {
            debug("The computation used to determine source line information from the engine timed out.\nLine number information will be unavailable and/or inaccurate.");
            return asMappedString(target);
        }
        for (const action of diffResult){
            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 mappedStringFromFile(filename) {
    const value = Deno.readTextFileSync(filename);
    if (filename.startsWith("/")) {
        filename = relative2(Deno.cwd(), filename);
    }
    return asMappedString(value, filename);
}
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 result1 = parseWithNiceErrors(decoder.decode(yml));
        try {
            JSON.stringify(result1);
            return result1;
        } 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 parseWithNiceErrors(yml);
}
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){
            let yamlBlock = removeYamlDelimiters(match[2]);
            yamlBlock = lines(yamlBlock).map((x)=>x.trimEnd()).join("\n");
            if (!yamlBlock.match(/^\n\s*\n/) && !yamlBlock.match(/^\n\s*\n---/m) && yamlBlock.trim().length > 0) {
                parseWithNiceErrors(yamlBlock, {
                    json: true,
                    schema: QuartoJSONSchema1
                });
                yaml += yamlBlock;
            }
            match = kRegExYAML.exec(markdown);
        }
        kRegExYAML.lastIndex = 0;
        const metadata = parseWithNiceErrors(yaml, {
            json: true,
            schema: QuartoJSONSchema1
        });
        return metadata || {};
    } else {
        return {};
    }
}
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*$/, "");
}
class YAMLValidationError extends ErrorEx {
    constructor(message){
        super("YAMLValidationError", message, false, false);
    }
}
const QuartoJSONSchema1 = new Schema({
    implicit: [
        nil,
        bool,
        __int,
        __float
    ],
    include: [
        failsafe
    ],
    explicit: [
        new Type1("!expr", {
            kind: "scalar",
            construct (data) {
                const result1 = data !== null ? data : "";
                return {
                    value: result1,
                    tag: "!expr"
                };
            }
        })
    ]
});
function parseWithNiceErrors(content, options) {
    try {
        return parse1(content, options || {
            json: true,
            schema: QuartoJSONSchema1
        });
    } catch (e) {
        throw improveYamlParseErrorMessage(e);
    }
}
function improveYamlParseErrorMessage(e) {
    if (e.message.match(/unknown tag/)) {
        e.message = `${e.message}\nDid you try to use a '!' in a YAML string? If so, you need to add explicit quotes to your string.`;
    }
    return e;
}
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 globalThis.crypto.randomUUID();
            } else {
                return JSON.stringify(value);
            }
        });
    }
}
function camelToKebab(camel) {
    camel = camel.replace(/([A-Z])([A-Z]+)$/g, function(_, p1, p2) {
        return p1 + p2.toLowerCase();
    });
    camel = camel.replaceAll(/([A-Z])([A-Z]+)([A-Z])/g, function(_, p1, p2, p3) {
        return p1 + p2.toLowerCase() + p3;
    });
    const kebab = [];
    for(let i1 = 0; i1 < camel.length; i1++){
        const ch = camel.charAt(i1);
        if (ch === ch.toUpperCase() && !/^\d+/.test(ch)) {
            if (i1 > 0) {
                kebab.push("-");
            }
            kebab.push(ch.toLowerCase());
        } else {
            kebab.push(ch);
        }
    }
    return kebab.join("");
}
function kebabToCamel(kebab, leadingUppercase = false) {
    const camel = [];
    for(let i1 = 0; i1 < kebab.length; i1++){
        const ch = kebab.charAt(i1);
        if (ch === "-") {
            camel.push(kebab.charAt(++i1).toUpperCase());
        } else if (i1 === 0 && leadingUppercase) {
            camel.push(ch.toUpperCase());
        } else {
            camel.push(ch);
        }
    }
    return camel.join("");
}
const kMetadataFormat = "format";
const kDisplayName = "display-name";
const kExtensionName = "extension-name";
const kTargetFormat = "target-format";
const kBaseFormat = "base-format";
const kIdentifierDefaults = "indentifier";
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 kFigAsp = "fig-asp";
const kMermaidFormat = "mermaid-format";
const kDfPrint = "df-print";
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 kFormatResources = "format-resources";
const kSupporting = "supporting";
const kIpynbProduceSourceNotebook = "produce-source-notebook";
const kEnableCrossRef = "enable-crossref";
const kFormatLinks = "format-links";
const kNotebookLinks = "notebook-links";
const kOtherLinks = "other-links";
const kCodeLinks = "code-links";
const kNotebookSubarticles = "notebook-subarticles";
const kNotebookView = "notebook-view";
const kNotebookViewStyle = "notebook-view-style";
const kNotebookPreserveCells = "notebook-preserve-cells";
const kClearCellOptions = "clear-cell-options";
const kDownloadUrl = "download-url";
const kLightbox = "lightbox";
const kCanonicalUrl = "canonical-url";
const kMath = "math";
const kNotebookPreviewOptions = "notebook-preview-options";
const kKeepHidden = "keep-hidden";
const kRemoveHidden = "remove-hidden";
const kClearHiddenClasses = "clear-hidden-classes";
const kUnrollMarkdownCells = "unroll-markdown-cells";
const kExecuteEnabled = "enabled";
const kExecuteIpynb = "ipynb";
const kExecuteDaemon = "daemon";
const kExecuteDaemonRestart = "daemon-restart";
const kExecuteDebug = "debug";
const kIpynbFilter = "ipynb-filter";
const kIpynbFilters = "ipynb-filters";
const kIpynbShellInteractivity = "ipynb-shell-interactivity";
const kIPynbTitleBlockTemplate = "ipynb-title-block";
const kPlotlyConnected = "plotly-connected";
const kJatsSubarticleId = "jats-subarticle-id";
const kShortcodes = "shortcodes";
const kKeepMd = "keep-md";
const kKeepTex = "keep-tex";
const kKeepTyp = "keep-typ";
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 kTblCap = "tbl-cap";
const kTblColwidths = "tbl-colwidths";
const kMergeIncludes = "merge-includes";
const kInlineIncludes = "inline-includes";
const kPreserveYaml = "preserve-yaml";
const kPreferHtml = "prefer-html";
const kSelfContainedMath = "self-contained-math";
const kBodyClasses = "body-classes";
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 kLatexInputPaths = "latex-input-paths";
const kLatexMakeIndex = "latex-makeindex";
const kLatexMakeIndexOpts = "latex-makeindex-opts";
const kLatexTinyTex = "latex-tinytex";
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 kQuartoVersion = "quarto-version";
const kQuartoRequired = "quarto-required";
const kPreviewMode = "preview-mode";
const kPreviewModeRaw = "raw";
const kFontPaths = "font-paths";
const kHtmlTableProcessing = "html-table-processing";
const kHtmlPreTagProcessing = "html-pre-tag-processing";
const kCssPropertyProcessing = "css-property-processing";
const kUseRsvgConvert = "use-rsvg-convert";
const kValidateYaml = "validate-yaml";
const kIdentifierDefaultsKeys = [
    kTargetFormat,
    kDisplayName,
    kExtensionName
];
const kExecuteDefaultsKeys = [
    kFigWidth,
    kFigHeight,
    kFigFormat,
    kFigDpi,
    kFigAsp,
    kMermaidFormat,
    kDfPrint,
    kError,
    kEval,
    kEngine,
    kCache,
    kFreeze,
    kEcho,
    kOutput,
    kWarning,
    kInclude,
    kKeepMd,
    kKeepIpynb,
    kExecuteEnabled,
    kExecuteIpynb,
    kExecuteDaemon,
    kExecuteDaemonRestart,
    kExecuteDebug,
    kIpynbFilter,
    kIpynbFilters,
    kIpynbShellInteractivity,
    kPlotlyConnected
];
const kRenderDefaultsKeys = [
    kKeepTex,
    kKeepTyp,
    kKeepSource,
    kKeepHidden,
    kRemoveHidden,
    kClearHiddenClasses,
    kVariant,
    kOutputExt,
    kOutputDivs,
    kPreferHtml,
    kPageWidth,
    kFigAlign,
    kFigPos,
    kFigEnv,
    kCodeFold,
    kCodeLink,
    kCodeLineNumbers,
    kCodeOverflow,
    kCodeTools,
    kShortcodes,
    kTblColwidths,
    kInlineIncludes,
    kPreserveYaml,
    kMergeIncludes,
    kSelfContainedMath,
    kLatexAutoMk,
    kLatexAutoInstall,
    kLatexMinRuns,
    kLatexMaxRuns,
    kLatexClean,
    kLatexInputPaths,
    kLatexMakeIndex,
    kLatexMakeIndexOpts,
    kLatexTlmgrOpts,
    kLatexOutputDir,
    kLatexTinyTex,
    kLinkExternalIcon,
    kLinkExternalNewwindow,
    kLinkExternalFilter,
    kFormatResources,
    kFormatLinks,
    kIpynbProduceSourceNotebook,
    kNotebookLinks,
    kNotebookSubarticles,
    kNotebookView,
    kNotebookViewStyle,
    kNotebookPreserveCells,
    kClearCellOptions,
    kHtmlTableProcessing,
    kValidateYaml,
    kCanonicalUrl,
    kBodyClasses
];
const kTocTitleDocument = "toc-title-document";
const kTocTitleWebsite = "toc-title-website";
const kRelatedFormatsTitle = "related-formats-title";
const kRelatedNotebooksTitle = "related-notebooks-title";
const kOtherLinksTitle = "other-links-title";
const kCodeLinksTitle = "code-links-title";
const kLaunchDevContainerTitle = "launch-dev-container-title";
const kLaunchBinderTitle = "launch-binder-title";
const kSourceNotebookPrefix = "source-notebooks-prefix";
const kCalloutTipCaption = "callout-tip-title";
const kCalloutNoteCaption = "callout-note-title";
const kCalloutWarningCaption = "callout-warning-title";
const kCalloutImportantCaption = "callout-important-title";
const kCalloutCautionCaption = "callout-caution-title";
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 kSectionTitleCopyright = "section-title-copyright";
const kSectionTitleCitation = "section-title-citation";
const kAppendixAttributionBibTex = "appendix-attribution-bibtex";
const kAppendixAttributionCiteAs = "appendix-attribution-cite-as";
const kAppendixViewLicense = "appendix-view-license";
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 kTitleBlockModified = "title-block-modified";
const kTitleBlockKeywords = "title-block-keywords";
const kCodeSummary = "code-summary";
const kCodeLine = "code-line";
const kCodeLines = "code-lines";
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 kSearchLabel = "search-label";
const kToolsShare = "tools-share";
const kToolsDownload = "tools-download";
const kToggleSection = "toggle-section";
const kToggleSidebar = "toggle-sidebar";
const kToggleDarkMode = "toggle-dark-mode";
const kToggleReaderMode = "toggle-reader-mode";
const kToggleNavigation = "toggle-navigation";
const kCopyButtonTooltip = "copy-button-tooltip";
const kCopyButtonTooltipSuccess = "copy-button-tooltip-success";
const kBackToTop = "back-to-top";
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 kSearchTextPlaceholder = "search-text-placeholder";
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 kCrossrefChPrefix = "crossref-ch-prefix";
const kCrossrefApxPrefix = "crossref-apx-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 kEnvironmentProofTitle = "environment-proof-title";
const kEnvironmentRemarkTitle = "environment-remark-title";
const kEnvironmentSolutionTitle = "environment-solution-title";
const kListingPageOrderBy = "listing-page-order-by";
const kListingPageFilter = "listing-page-filter";
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 kListingPageFieldWordCount = "listing-page-field-wordcount";
const kListingPageFieldCategories = "listing-page-field-categories";
const kListingPageMinutesCompact = "listing-page-minutes-compact";
const kListingPageWords = "listing-page-words";
const kListingPageCategoryAll = "listing-page-category-all";
const kListingPageNoMatches = "listing-page-no-matches";
const kNotebookPreviewDownload = "notebook-preview-download";
const kNotebookPreviewDownloadSrc = "notebook-preview-download-src";
const kNotebookPreviewBack = "notebook-preview-back";
const kArticleNotebookLabel = "article-notebook-label";
const kManuscriptMecaBundle = "manuscript-meca-bundle";
const kDraftLabel = "draft";
const kLanguageDefaultsKeys = [
    kTocTitleDocument,
    kTocTitleWebsite,
    kRelatedFormatsTitle,
    kOtherLinksTitle,
    kCodeLinksTitle,
    kLaunchDevContainerTitle,
    kLaunchBinderTitle,
    kRelatedNotebooksTitle,
    kSourceNotebookPrefix,
    kCalloutTipCaption,
    kCalloutNoteCaption,
    kCalloutWarningCaption,
    kCalloutImportantCaption,
    kCalloutCautionCaption,
    kSectionTitleAbstract,
    kSectionTitleFootnotes,
    kSectionTitleReferences,
    kSectionTitleAppendices,
    kSectionTitleReuse,
    kSectionTitleCopyright,
    kSectionTitleCitation,
    kAppendixAttributionBibTex,
    kAppendixAttributionCiteAs,
    kAppendixViewLicense,
    kTitleBlockAuthorSingle,
    kTitleBlockPublished,
    kTitleBlockModified,
    kTitleBlockKeywords,
    kCodeSummary,
    kCodeLine,
    kCodeLines,
    kCodeToolsMenuCaption,
    kCodeToolsShowAllCode,
    kCodeToolsHideAllCode,
    kCodeToolsViewSource,
    kCodeToolsSourceCode,
    kToolsShare,
    kToolsDownload,
    kSearchNoResultsText,
    kSearchLabel,
    kToggleDarkMode,
    kToggleNavigation,
    kToggleReaderMode,
    kToggleSidebar,
    kToggleSection,
    kCopyButtonTooltip,
    kCopyButtonTooltipSuccess,
    kBackToTop,
    kRepoActionLinksEdit,
    kRepoActionLinksSource,
    kRepoActionLinksIssue,
    kSearchMatchingDocumentsText,
    kSearchCopyLinkTitle,
    kSearchHideMatchesText,
    kSearchMoreMatchText,
    kSearchMoreMatchesText,
    kSearchClearButtonTitle,
    kSearchTextPlaceholder,
    kSearchDetatchedCancelButtonTitle,
    kSearchSubmitButtonTitle,
    kCrossrefFigTitle,
    kCrossrefTblTitle,
    kCrossrefLstTitle,
    kCrossrefThmTitle,
    kCrossrefLemTitle,
    kCrossrefCorTitle,
    kCrossrefPrfTitle,
    kCrossrefCnjTitle,
    kCrossrefDefTitle,
    kCrossrefExmTitle,
    kCrossrefExrTitle,
    kCrossrefFigPrefix,
    kCrossrefTblPrefix,
    kCrossrefLstPrefix,
    kCrossrefChPrefix,
    kCrossrefApxPrefix,
    kCrossrefSecPrefix,
    kCrossrefEqPrefix,
    kCrossrefThmPrefix,
    kCrossrefLemPrefix,
    kCrossrefCorPrefix,
    kCrossrefPrpPrefix,
    kCrossrefCnjPrefix,
    kCrossrefDefPrefix,
    kCrossrefExmPrefix,
    kCrossrefExrPrefix,
    kCrossrefLofTitle,
    kCrossrefLotTitle,
    kCrossrefLolTitle,
    kEnvironmentProofTitle,
    kEnvironmentRemarkTitle,
    kEnvironmentSolutionTitle,
    kListingPageFilter,
    kListingPageOrderBy,
    kListingPageOrderByDefault,
    kListingPageOrderByDateAsc,
    kListingPageOrderByDateDesc,
    kListingPageOrderByNumberAsc,
    kListingPageOrderByNumberDesc,
    kListingPageFieldDate,
    kListingPageFieldTitle,
    kListingPageFieldDescription,
    kListingPageFieldAuthor,
    kListingPageFieldFileName,
    kListingPageFieldFileModified,
    kListingPageFieldSubtitle,
    kListingPageFieldReadingTime,
    kListingPageFieldWordCount,
    kListingPageFieldCategories,
    kListingPageMinutesCompact,
    kListingPageWords,
    kListingPageCategoryAll,
    kListingPageNoMatches,
    kTitleBlockAuthorSingle,
    kTitleBlockAuthorPlural,
    kTitleBlockAffiliationSingle,
    kTitleBlockAffiliationPlural,
    kTitleBlockPublished,
    kTitleBlockModified,
    kTitleBlockKeywords,
    kNotebookPreviewDownload,
    kNotebookPreviewDownloadSrc,
    kNotebookPreviewBack,
    kArticleNotebookLabel,
    kDraftLabel,
    kManuscriptMecaBundle
];
const kTo = "to";
const kFrom = "from";
const kReader = "reader";
const kWriter = "writer";
const kOutputFile = "output-file";
const kInputFiles = "input-files";
const kMarkdownHeadings = "markdown-headings";
const kTemplate = "template";
const kWrap = "wrap";
const kColumns = "columns";
const kStandalone = "standalone";
const kSelfContained = "self-contained";
const kEmbedResources = "embed-resources";
const kIncludeBeforeBody = "include-before-body";
const kIncludeAfterBody = "include-after-body";
const kIncludeInHeader = "include-in-header";
const kResourcePath = "resource-path";
const kCiteproc = "citeproc";
const kCiteMethod = "cite-method";
const kFilters = "filters";
const kQuartoFilters = "quarto-filters";
const kFilterParams = "filter-params";
const kPdfEngine = "pdf-engine";
const kNotebooks = "notebooks";
const kPdfEngineOpts = "pdf-engine-opts";
const kPdfEngineOpt = "pdf-engine-opt";
const kListings = "listings";
const kNumberSections = "number-sections";
const kSectionNumbering = "section-numbering";
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 kTocDepth = "toc-depth";
const kTocIndent = "toc-indent";
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 kQuartoTemplateParams = "quarto-template-params";
const kRevealJsScripts = "reveal-jsscripts";
const kQuartoInternal = "quarto-internal";
const kTitle = "title";
const kSubtitle = "subtitle";
const kAuthor = "author";
const kDate = "date";
const kDateFormat = "date-format";
const kDateModified = "date-modified";
const kDoi = "doi";
const kAbstract = "abstract";
const kAbstractTitle = "abstract-title";
const kDescription = "description";
const kHideDescription = "hide-description";
const kTocTitle = "toc-title";
const kTocLocation = "toc-location";
const kTocExpand = "toc-expand";
const kLang = "lang";
const kOrder = "order";
const kDisableArticleLayout = "disable-article-layout";
const kAuthors = "authors";
const kInstitute = "institute";
const kInstitutes = "institutes";
const kServer = "server";
const kPageTitle = "pagetitle";
const kTitlePrefix = "title-prefix";
const kCsl = "csl";
const kNoCite = "nocite";
const kCss = "css";
const kBibliography = "bibliography";
const kReferences = "references";
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 kCrossrefChaptersAppendix = "chapters-appendix";
const kCrossrefChaptersAlpha = "chapters-alpha";
const kCrossrefChapterId = "chapter-id";
const kGrid = "grid";
const kContentMode = "content-mode";
const kFigResponsive = "fig-responsive";
const kOutputLocation = "output-location";
const kCapLoc = "cap-location";
const kFigCapLoc = "fig-cap-location";
const kTblCapLoc = "tbl-cap-location";
const kCapTop = "top";
const kCapBottom = "bottom";
const kPositionedRefs = "positioned-refs";
const kPandocDefaultsKeys = [
    kTo,
    kFrom,
    kReader,
    kWriter,
    kOutputFile,
    kInputFiles,
    "defaults",
    kTemplate,
    kStandalone,
    kSelfContained,
    kEmbedResources,
    kVariables,
    "metadata",
    kMetadataFiles,
    kMetadataFile,
    kIncludeBeforeBody,
    kIncludeAfterBody,
    kIncludeInHeader,
    kResourcePath,
    kCiteproc,
    kCiteMethod,
    "citation-abbreviations",
    "filters",
    "file-scope",
    "data-dir",
    "verbosity",
    kLogFile,
    kTopLevelDivision,
    "abbreviations",
    kPdfEngine,
    kPdfEngineOpts,
    kPdfEngineOpt,
    kWrap,
    kColumns,
    "dpi",
    "extract-media",
    kToc,
    kTableOfContents,
    kTocDepth,
    kNumberSections,
    kNumberOffset,
    kShiftHeadingLevelBy,
    kSectionDivs,
    "identifier-prefix",
    kTitlePrefix,
    "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,
    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 kCellLanguage = "language";
const kCellSlideshow = "slideshow";
const kCellSlideshowSlideType = "slide_type";
const kCellRawMimeType = "raw_mimetype";
const kCellUserExpressions = "user_expressions";
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 kCellWidth = "width";
const kCellHeight = "height";
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";
const kCliffyImplicitCwd = "5a6d2e4f-f9a2-43bc-8019-8149fbb76c85";
const kSourceMappingRegexes = [
    /^\/\/#\s*sourceMappingURL\=.*\.map$/gm,
    /\/\*\# sourceMappingURL=.* \*\//g
];
const kFormatIdentifier = "format-identifier";
const kRenderFileLifetime = "render-file";
const kRenderServicesLifetime = "render-services";
const kQuartoPre = "pre-quarto";
const kQuartoPost = "post-render";
async function readAndValidateYamlFromFile(file, schema, errorMessage, defaultContents) {
    if (!existsSync(file)) {
        throw new Error(`YAML file ${file} not found.`);
    }
    let shortFileName = file;
    if (shortFileName.startsWith("/")) {
        shortFileName = relative2(Deno.cwd(), shortFileName);
    }
    let fileContents = Deno.readTextFileSync(file).trimEnd();
    if (fileContents.trim().length === 0 && defaultContents) {
        fileContents = defaultContents;
    }
    const contents = asMappedString(fileContents, shortFileName);
    const { yaml, yamlValidationErrors } = await readAndValidateYamlFromMappedString(contents, schema);
    if (yamlValidationErrors.length) {
        throw new ValidationError2(errorMessage, yamlValidationErrors);
    }
    return yaml;
}
const kGfmCommonmarkExtensions = [
    "+autolink_bare_uris",
    "+emoji",
    "+footnotes",
    "+gfm_auto_identifiers",
    "+pipe_tables",
    "+strikeout",
    "+task_lists",
    "+tex_math_dollars"
];
const kGfmCommonmarkVariant = kGfmCommonmarkExtensions.join("");
`commonmark${kGfmCommonmarkVariant}`;
const kQmdExtensions = [
    ".qmd"
];
const kMarkdownEngine = "markdown";
const kKnitrEngine = "knitr";
const kJupyterEngine = "jupyter";
const kJuliaEngine = "julia";
async function includedMetadata(dir, baseMetadata, schema) {
    const yamlFiles = [];
    const metadataFile = baseMetadata[kMetadataFile];
    if (metadataFile) {
        yamlFiles.push(join2(dir, metadataFile));
    }
    const metadataFiles = baseMetadata[kMetadataFiles];
    if (metadataFiles && Array.isArray(metadataFiles)) {
        metadataFiles.forEach((file)=>yamlFiles.push(join2(dir, file)));
    }
    const filesMetadata = await Promise.all(yamlFiles.map(async (yamlFile)=>{
        if (existsSync(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, debug) {
    const typedFormat = {
        identifier: {},
        render: {},
        execute: {},
        pandoc: {},
        language: {},
        metadata: {}
    };
    let format = typedFormat;
    const configFormats = baseFormat.metadata[kMetadataFormat];
    if (configFormats instanceof Object) {
        const configFormat = configFormats[to];
        if (configFormat === "default" || configFormat === true) {
            format = metadataAsFormat({});
        } else if (configFormat instanceof Object) {
            format = metadataAsFormat(configFormat);
        }
    }
    const mergedFormat = mergeFormatMetadata(baseFormat, format);
    if (debug) {
        mergedFormat.execute[kKeepMd] = true;
        mergedFormat.render[kKeepTex] = true;
        mergedFormat.render[kKeepTyp] = 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 format = metadata[kMetadataFormat][key];
            return format !== null && format !== false;
        });
    } else {
        return [];
    }
}
function isQuartoMetadata(key) {
    return kRenderDefaultsKeys.includes(key) || kExecuteDefaultsKeys.includes(key) || kPandocDefaultsKeys.includes(key) || kLanguageDefaultsKeys.includes(key) || [
        kKnitrEngine,
        kJupyterEngine
    ].includes(key);
}
function isIncludeMetadata(key) {
    return [
        kHeaderIncludes,
        kIncludeBefore,
        kIncludeAfter
    ].includes(key);
}
function metadataAsFormat(metadata) {
    const typedFormat = {
        identifier: {},
        render: {},
        execute: {},
        pandoc: {},
        language: {},
        metadata: {}
    };
    const format = typedFormat;
    Object.keys(metadata).forEach((key)=>{
        if ([
            kIdentifierDefaults,
            kRenderDefaults,
            kExecuteDefaults,
            kPandocDefaults,
            kLanguageDefaults,
            kPandocMetadata
        ].includes(key)) {
            if (typeof metadata[key] == "boolean") {
                if (key === kExecuteDefaults) {
                    format[key] = format[key] || {};
                    format[kExecuteDefaults][kExecuteEnabled] = metadata[key];
                }
            } else {
                format[key] = {
                    ...format[key],
                    ...metadata[key]
                };
            }
        } else {
            if (kIdentifierDefaultsKeys.includes(key)) {
                format.identifier[key] = metadata[key];
            } else if (kRenderDefaultsKeys.includes(key)) {
                format.render[key] = metadata[key];
            } else if (kExecuteDefaultsKeys.includes(key)) {
                format.execute[key] = metadata[key];
            } else if (kPandocDefaultsKeys.includes(key)) {
                format.pandoc[key] = metadata[key];
            } else {
                format.metadata[key] = metadata[key];
            }
        }
    });
    if (typeof format.metadata[kServer] === "string") {
        format.metadata[kServer] = {
            type: format.metadata[kServer]
        };
    }
    const filter = format.execute[kIpynbFilter];
    if (typeof filter === "string") {
        typedFormat.execute[kIpynbFilters] = typedFormat.execute[kIpynbFilters] || [];
        typedFormat.execute[kIpynbFilters]?.push(filter);
        delete typedFormat.execute[kIpynbFilter];
    }
    if (typeof typedFormat.render.variant === "string") {
        typedFormat.render.variant = typedFormat.render.variant.replace(/^gfm/, kGfmCommonmarkVariant);
    }
    return typedFormat;
}
function metadataGetDeep(metadata, property) {
    let values = [];
    __VIRTUAL_FILE145(metadata, (value, key)=>{
        if (key === property) {
            values.push(value);
        } else if (__VIRTUAL_FILE18(value)) {
            values = values.concat(metadataGetDeep(value, property));
        }
    });
    return values;
}
function mergeFormatMetadata(config, ...configs) {
    const kUnmergeableKeys = [
        kTblColwidths
    ];
    const kBooleanDisableArrays = [
        kCodeLinks,
        kOtherLinks
    ];
    return mergeConfigsCustomized((objValue, srcValue, key)=>{
        if (kUnmergeableKeys.includes(key)) {
            return srcValue;
        } else if (key === kVariant) {
            return mergePandocVariant(objValue, srcValue);
        } else if (kBooleanDisableArrays.includes(key)) {
            return mergeDisablableArray(objValue, srcValue);
        } else {
            return undefined;
        }
    }, config, ...configs);
}
function mergeProjectMetadata(config, ...configs) {
    const kExandableStringKeys = [
        "contents"
    ];
    return mergeConfigsCustomized((objValue, srcValue, key)=>{
        if (kExandableStringKeys.includes(key) && typeof objValue === "string") {
            return srcValue;
        } else {
            return undefined;
        }
    }, config, ...configs);
}
function mergeConfigsCustomized(customizer, config, ...configs) {
    config = cloneDeep1(config);
    configs = cloneDeep1(configs);
    return __VIRTUAL_FILE154(config, ...configs, (objValue, srcValue, key)=>{
        const custom = customizer(objValue, srcValue, key);
        if (custom !== undefined) {
            return custom;
        } else {
            return mergeArrayCustomizer(objValue, srcValue);
        }
    });
}
function mergeDisablableArray(objValue, srcValue) {
    if (Array.isArray(objValue) && Array.isArray(srcValue)) {
        return mergeArrayCustomizer(objValue, srcValue);
    } else {
        if (srcValue === false) {
            return [];
        } else {
            const srcArr = srcValue !== undefined ? Array.isArray(srcValue) ? srcValue : [
                srcValue
            ] : [];
            const objArr = objValue !== undefined ? Array.isArray(objValue) ? objValue : [
                objValue
            ] : [];
            return mergeArrayCustomizer(objArr, srcArr);
        }
    }
}
function mergePandocVariant(objValue, srcValue) {
    if (typeof objValue === "string" && typeof srcValue === "string" && objValue !== srcValue) {
        const extensions = {};
        [
            ...parsePandocVariant(objValue),
            ...parsePandocVariant(srcValue)
        ].forEach((extension)=>{
            extensions[extension.name] = extension.enabled;
        });
        return Object.keys(extensions).map((name)=>`${extensions[name] ? "+" : "-"}${name}`).join("");
    } else {
        return undefined;
    }
}
function parsePandocVariant(variant) {
    variant = variant.split("\n").join();
    const extensions = [];
    const re = /([+-])([a-z_]+)/g;
    let match = re.exec(variant);
    while(match){
        extensions.push({
            name: match[2],
            enabled: match[1] === "+"
        });
        match = re.exec(variant);
    }
    return extensions;
}
function removeFlags(flags, remove) {
    let removeNext = false;
    return flags.reduce((args, arg)=>{
        if (!remove.has(arg)) {
            if (!removeNext) {
                args.push(arg);
            }
            removeNext = false;
        } else {
            removeNext = remove.get(arg);
        }
        return args;
    }, new Array());
}
const kStdOut = "-";
async function parseRenderFlags(args) {
    const flags = {};
    const argsStack = [
        ...args
    ];
    let arg = argsStack.shift();
    while(arg !== undefined){
        const equalSignIndex = arg.indexOf("=");
        if (arg.startsWith("--") && equalSignIndex > 0) {
            argsStack.unshift(arg.slice(equalSignIndex + 1));
            arg = arg.slice(0, equalSignIndex);
        }
        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 {
                    if (arg.match(SEPARATOR_PATTERN2)) {
                        throw new Error("--output option cannot specify a relative or absolute path");
                    }
                    flags.output = arg;
                }
                break;
            case "--output-dir":
                arg = argsStack.shift();
                flags.outputDir = arg;
                break;
            case "--site-url":
                arg = argsStack.shift();
                flags.siteUrl = arg;
                break;
            case "--standalone":
                flags[kStandalone] = true;
                arg = argsStack.shift();
                break;
            case "--self-contained":
                flags[kSelfContained] = true;
                arg = argsStack.shift();
                break;
            case "--embed-resources":
                flags[kEmbedResources] = 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 include = arg.replace("^--", "");
                    const includeFlags = flags;
                    includeFlags[include] = includeFlags[include] || [];
                    arg = argsStack.shift();
                    includeFlags[include].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();
                if (arg) {
                    if (isAbsolute2(arg)) {
                        flags.executeDir = arg;
                    } else {
                        flags.executeDir = normalizePath(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 = await readYamlFromString(Deno.readTextFileSync(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 getPandocArg(pandocArgs, arg) {
    const argIndex = pandocArgs.indexOf(arg);
    if (argIndex !== -1 && argIndex + 1 < pandocArgs.length) {
        return pandocArgs[argIndex + 1];
    } else {
        return undefined;
    }
}
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("--site-url", 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);
    removeArgs.set("--profile", true);
    pandocArgs = removePandocArgs(pandocArgs, removeArgs);
    return removeQuartoMetadataFlags(pandocArgs);
}
function removePandocArgs(pandocArgs, removeArgs) {
    return removeFlags(pandocArgs, removeArgs);
}
function removePandocToArg(args) {
    const removeArgs = new Map();
    removeArgs.set("--to", true);
    removeArgs.set("-t", true);
    return removePandocArgs(args, removeArgs);
}
function removePandocTo(renderOptions) {
    renderOptions = cloneDeep1(renderOptions);
    delete renderOptions.flags?.to;
    if (renderOptions.pandocArgs) {
        renderOptions.pandocArgs = removePandocToArg(renderOptions.pandocArgs);
    }
    return renderOptions;
}
function removeQuartoMetadataFlags(pandocArgs) {
    const args = [];
    for(let i1 = 0; i1 < pandocArgs.length; i1++){
        const arg = pandocArgs[i1];
        if (arg === "--metadata" || arg === "-M") {
            const flagValue = parseMetadataFlagValue(pandocArgs[i1 + 1] || "");
            if (flagValue !== undefined && (isQuartoMetadata(flagValue.name) || kQuartoForwardedMetadataFields.includes(flagValue.name))) {
                i1++;
            } else {
                args.push(arg);
            }
        } else {
            args.push(arg);
        }
    }
    return args;
}
const kQuartoForwardedMetadataFields = [
    kAuthor,
    kDate
];
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((number)=>parseInt(number.trim(), 10)).filter((number)=>!isNaN(number));
        if (numbers.length > 0) {
            return numbers;
        }
    }
    throw new Error(`Invalid value for ${flag} (should be a comma separated list of numbers)`);
}
const importMeta = {
    url: "file:///home/runner/work/quarto-cli/quarto-cli/src/vendor/deno.land/x/deno_dom@v0.1.35-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 len = arg.length;
    let ptr = malloc(len);
    const mem = getUint8Memory0();
    let offset = 0;
    for(; offset < len; offset++){
        const code = arg.charCodeAt(offset);
        if (code > 0x7F) break;
        mem[ptr + offset] = code;
    }
    if (offset !== len) {
        if (offset !== 0) {
            arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len, len = offset + arg.length * 3);
        const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
        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, len) {
    return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
function parse2(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 load2(module1, imports) {
    if (typeof Response === "function" && module1 instanceof Response) {
        if (typeof WebAssembly.instantiateStreaming === "function") {
            try {
                return await WebAssembly.instantiateStreaming(module1, imports);
            } catch (e) {
                if (module1.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 module1.arrayBuffer();
        return await WebAssembly.instantiate(bytes, imports);
    } else {
        const instance = await WebAssembly.instantiate(module1, imports);
        if (instance instanceof WebAssembly.Instance) {
            return {
                instance,
                module: module1
            };
        } 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("[encoded data, 710468 characters]"), (c)=>c.charCodeAt(0));
    const { instance, module: module1 } = await load2(input, imports);
    wasm = instance.exports;
    init.__wbindgen_wasm_module = module1;
    return wasm;
}
let parse3 = (_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 = parse3;
function register(func, fragFunc) {
    if (parse3 !== originalParse) {
        return;
    }
    parse3 = func;
    parseFrag = fragFunc;
}
const __default1 = {
    Element: null,
    Document: null,
    DocumentFragment: null
};
(()=>{
    return class HTMLCollection {
        constructor(){
            throw new TypeError("Illegal constructor");
        }
        static [Symbol.hasInstance](value) {
            return value.constructor === HTMLCollectionClass;
        }
    };
})();
const HTMLCollectionMutatorSym = Symbol();
const HTMLCollectionClass = (()=>{
    class HTMLCollection 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 HTMLCollection;
})();
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();
var NodeType;
(()=>{
    return class NodeList {
        constructor(){
            throw new TypeError("Illegal constructor");
        }
        static [Symbol.hasInstance](value) {
            return value.constructor === NodeListClass;
        }
    };
})();
(function(NodeType) {
    NodeType[NodeType["ELEMENT_NODE"] = 1] = "ELEMENT_NODE";
    NodeType[NodeType["ATTRIBUTE_NODE"] = 2] = "ATTRIBUTE_NODE";
    NodeType[NodeType["TEXT_NODE"] = 3] = "TEXT_NODE";
    NodeType[NodeType["CDATA_SECTION_NODE"] = 4] = "CDATA_SECTION_NODE";
    NodeType[NodeType["ENTITY_REFERENCE_NODE"] = 5] = "ENTITY_REFERENCE_NODE";
    NodeType[NodeType["ENTITY_NODE"] = 6] = "ENTITY_NODE";
    NodeType[NodeType["PROCESSING_INSTRUCTION_NODE"] = 7] = "PROCESSING_INSTRUCTION_NODE";
    NodeType[NodeType["COMMENT_NODE"] = 8] = "COMMENT_NODE";
    NodeType[NodeType["DOCUMENT_NODE"] = 9] = "DOCUMENT_NODE";
    NodeType[NodeType["DOCUMENT_TYPE_NODE"] = 10] = "DOCUMENT_TYPE_NODE";
    NodeType[NodeType["DOCUMENT_FRAGMENT_NODE"] = 11] = "DOCUMENT_FRAGMENT_NODE";
    NodeType[NodeType["NOTATION_NODE"] = 12] = "NOTATION_NODE";
})(NodeType || (NodeType = {}));
function getElementsByClassName(element, className, search) {
    for (const child of element.childNodes){
        if (child.nodeType === NodeType.ELEMENT_NODE) {
            const classList = className.trim().split(/\s+/);
            let matchesCount = 0;
            for (const singleClassName of classList){
                if (child.classList.contains(singleClassName)) {
                    matchesCount++;
                }
            }
            if (matchesCount === classList.length) {
                search.push(child);
            }
            getElementsByClassName(child, className, search);
        }
    }
    return search;
}
function getInnerHtmlFromNodes(nodes, tagName) {
    let out = "";
    for (const child of nodes){
        switch(child.nodeType){
            case NodeType.ELEMENT_NODE:
                out += child.outerHTML;
                break;
            case NodeType.COMMENT_NODE:
                out += `<!--${child.data}-->`;
                break;
            case NodeType.TEXT_NODE:
                switch(tagName){
                    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;
}
function getElementAttributesString(element) {
    let out = "";
    for (const attribute of element.getAttributeNames()){
        out += ` ${attribute.toLowerCase()}`;
        out += `="${element.getAttribute(attribute).replace(/&/g, "&amp;").replace(/\xA0/g, "&nbsp;").replace(/"/g, "&quot;")}"`;
    }
    return out;
}
function isDocumentFragment(node) {
    let obj = node;
    if (!(obj && typeof obj === "object")) {
        return false;
    }
    while(true){
        switch(obj.constructor){
            case __default1.DocumentFragment:
                return true;
            case Node:
            case __default1.Element:
                return false;
            case Object:
            case null:
            case undefined:
                return false;
            default:
                obj = Reflect.getPrototypeOf(obj);
        }
    }
}
function moveDocumentFragmentChildren(fragment, newParent) {
    const childCount = fragment.childNodes.length;
    for (const child of fragment.childNodes){
        child._setParent(newParent);
    }
    const mutator = fragment._getChildNodesMutator();
    mutator.splice(0, childCount);
}
const nodesAndTextNodes = (nodes, parentNode)=>{
    return nodes.flatMap((n)=>{
        if (isDocumentFragment(n)) {
            const children = Array.from(n.childNodes);
            moveDocumentFragmentChildren(n, parentNode);
            return children;
        } else {
            const node = n instanceof Node ? n : new Text("" + n);
            if (n === node && parentNode) {
                parentNode._assertNotAncestor(node);
            }
            node._remove(true);
            node._setParent(parentNode, true);
            return [
                node
            ];
        }
    });
};
function insertBeforeAfter(node, nodes, before) {
    const parentNode = node.parentNode;
    const mutator = parentNode._getChildNodesMutator();
    let viablePrevNextSibling = null;
    {
        const difference = before ? -1 : +1;
        for(let i1 = mutator.indexOf(node) + difference; 0 <= i1 && i1 < parentNode.childNodes.length; i1 += difference){
            if (!nodes.includes(parentNode.childNodes[i1])) {
                viablePrevNextSibling = parentNode.childNodes[i1];
                break;
            }
        }
    }
    nodes = nodesAndTextNodes(nodes, parentNode);
    let index;
    if (viablePrevNextSibling) {
        index = mutator.indexOf(viablePrevNextSibling) + (before ? 1 : 0);
    } else {
        index = before ? 0 : parentNode.childNodes.length;
    }
    mutator.splice(index, 0, ...nodes);
}
const nodeListMutatorSym = Symbol();
const nodeListCachedMutator = Symbol();
const { push: push1, splice: splice1, slice, indexOf, filter } = Array.prototype;
class Node extends EventTarget {
    nodeName;
    nodeType;
    #nodeValue;
    childNodes;
    parentNode;
    parentElement;
    #childNodesMutator;
    #ownerDocument;
    _ancestors;
    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.parentNode = null;
        this.#ownerDocument = null;
        this._ancestors = new Set();
        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(document1) {
        if (this.#ownerDocument !== document1) {
            this.#ownerDocument = document1;
            for (const child of this.childNodes){
                child._setOwnerDocument(document1);
            }
        }
    }
    contains(child) {
        return child._ancestors.has(this) || child === this;
    }
    get ownerDocument() {
        return this.#ownerDocument;
    }
    get nodeValue() {
        return this.#nodeValue;
    }
    set nodeValue(value) {}
    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 Boolean(this.childNodes.length);
    }
    cloneNode(deep = false) {
        const copy = this._shallowClone();
        copy._setOwnerDocument(this.ownerDocument);
        if (deep) {
            for (const child of this.childNodes){
                copy.appendChild(child.cloneNode(true));
            }
        }
        return copy;
    }
    _shallowClone() {
        throw new Error("Illegal invocation");
    }
    _remove(skipSetParent = false) {
        const parent = this.parentNode;
        if (parent) {
            const nodeList = parent._getChildNodesMutator();
            const idx = nodeList.indexOf(this);
            nodeList.splice(idx, 1);
            if (!skipSetParent) {
                this._setParent(null);
            }
        }
    }
    appendChild(child) {
        if (isDocumentFragment(child)) {
            const mutator = this._getChildNodesMutator();
            mutator.push(...child.childNodes);
            moveDocumentFragmentChildren(child, this);
            return child;
        } else {
            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) {
                child._remove();
                return child;
            } 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;
    }
    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");
        }
        if (isDocumentFragment(newNode)) {
            mutator.splice(index, 0, ...newNode.childNodes);
            moveDocumentFragmentChildren(newNode, this);
        } else {
            const oldParentNode = newNode.parentNode;
            const oldMutator = oldParentNode?._getChildNodesMutator();
            if (oldMutator) {
                oldMutator.splice(oldMutator.indexOf(newNode), 1);
            }
            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();
            let viableNextSibling = null;
            {
                const thisIndex = mutator.indexOf(this);
                for(let i1 = thisIndex + 1; i1 < parentNode.childNodes.length; i1++){
                    if (!nodes.includes(parentNode.childNodes[i1])) {
                        viableNextSibling = parentNode.childNodes[i1];
                        break;
                    }
                }
            }
            nodes = nodesAndTextNodes(nodes, parentNode);
            let index = viableNextSibling ? mutator.indexOf(viableNextSibling) : parentNode.childNodes.length;
            let deleteNumber;
            if (parentNode.childNodes[index - 1] === this) {
                index--;
                deleteNumber = 1;
            } else {
                deleteNumber = 0;
            }
            mutator.splice(index, deleteNumber, ...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 i1 = shorterHierarchy.length - 1; i1 >= 0; i1--){
            const shorterHierarchyNode = shorterHierarchy[i1];
            const longerHierarchyNode = longerHierarchy[longerStart + i1];
            if (longerHierarchyNode !== shorterHierarchyNode) {
                const siblings = shorterHierarchyNode.parentNode._getChildNodesMutator();
                if (siblings.indexOf(shorterHierarchyNode) < siblings.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;
    }
    getRootNode(opts = {}) {
        if (this.parentNode) {
            return this.parentNode.getRootNode(opts);
        }
        if (opts.composed && this.host) {
            return this.host.getRootNode(opts);
        }
        return this;
    }
}
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;
        this.elementViews = [];
    }
    push(...items) {
        for (const view of this.elementViews){
            for (const item of items){
                if (item.nodeType === Node.ELEMENT_NODE) {
                    push1.call(view, item);
                }
            }
        }
        return push1.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, fromIndex = 0) {
        return indexOf.call(this.arrayInstance, item, fromIndex);
    }
    indexOfElementsView(item, fromIndex = 0) {
        return indexOf.call(this.elementsView(), item, fromIndex);
    }
    elementsView() {
        let view = this.elementViews[0];
        if (!view) {
            view = new HTMLCollection();
            this.elementViews.push(view);
            push1.call(view, ...filter.call(this.arrayInstance, (item)=>item.nodeType === Node.ELEMENT_NODE));
        }
        return view;
    }
}
const NodeListClass = (()=>{
    class NodeList 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 NodeList;
})();
for (const staticMethod of [
    "from",
    "isArray",
    "of"
]){
    NodeListClass[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"
]){
    NodeListClass.prototype[instanceMethod] = undefined;
}
const NodeList = NodeListClass;
class CharacterData extends Node {
    #nodeValue = "";
    constructor(data, nodeName, nodeType, parentNode, key){
        super(nodeName, nodeType, parentNode, key);
        this.#nodeValue = data;
    }
    get nodeValue() {
        return this.#nodeValue;
    }
    set nodeValue(value) {
        this.#nodeValue = String(value ?? "");
    }
    get data() {
        return this.#nodeValue;
    }
    set data(value) {
        this.nodeValue = value;
    }
    get textContent() {
        return this.#nodeValue;
    }
    set textContent(value) {
        this.nodeValue = value;
    }
    get length() {
        return this.data.length;
    }
    before(...nodes) {
        if (this.parentNode) {
            insertBeforeAfter(this, nodes, true);
        }
    }
    after(...nodes) {
        if (this.parentNode) {
            insertBeforeAfter(this, nodes, false);
        }
    }
    remove() {
        this._remove();
    }
    replaceWith(...nodes) {
        this._replaceWith(...nodes);
    }
}
class Text extends CharacterData {
    constructor(text = ""){
        super(String(text), "#text", NodeType.TEXT_NODE, null, CTOR_KEY);
    }
    _shallowClone() {
        return new Text(this.textContent);
    }
    get textContent() {
        return this.nodeValue;
    }
}
class Comment extends CharacterData {
    constructor(text = ""){
        super(String(text), "#comment", NodeType.COMMENT_NODE, null, CTOR_KEY);
    }
    _shallowClone() {
        return new Comment(this.textContent);
    }
    get textContent() {
        return this.nodeValue;
    }
}
const customByTagNameSym = Symbol();
const customByClassNameSym = Symbol();
class DocumentFragment1 extends Node {
    constructor(){
        super("#document-fragment", NodeType.DOCUMENT_FRAGMENT_NODE, null, CTOR_KEY);
    }
    get childElementCount() {
        return this._getChildNodesMutator().elementsView().length;
    }
    get children() {
        return this._getChildNodesMutator().elementsView();
    }
    get firstElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[0] ?? null;
    }
    get lastElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[elements.length - 1] ?? null;
    }
    append(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.push(...nodesAndTextNodes(nodes, this));
    }
    prepend(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.splice(0, 0, ...nodesAndTextNodes(nodes, this));
    }
    replaceChildren(...nodes) {
        const mutator = this._getChildNodesMutator();
        for (const child of this.childNodes){
            child._setParent(null);
        }
        mutator.splice(0, this.childNodes.length);
        mutator.splice(0, 0, ...nodesAndTextNodes(nodes, 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;
    }
    querySelector(selectors) {
        if (!this.ownerDocument) {
            throw new Error("DocumentFragment must have an owner document");
        }
        return this.ownerDocument._nwapi.first(selectors, this);
    }
    querySelectorAll(selectors) {
        if (!this.ownerDocument) {
            throw new Error("DocumentFragment must have an owner document");
        }
        const nodeList = new NodeList();
        const mutator = nodeList[nodeListMutatorSym]();
        mutator.push(...this.ownerDocument._nwapi.select(selectors, this));
        return nodeList;
    }
}
__default1.DocumentFragment = DocumentFragment1;
function documentFragmentGetElementsByTagName(tagName) {
    const search = [];
    if (tagName === "*") {
        return documentFragmentGetElementsByTagNameWildcard(this, 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;
}
function documentFragmentGetElementsByClassName(className) {
    return getElementsByClassName(this, className, []);
}
function documentFragmentGetElementsByTagNameWildcard(fragment, search) {
    for (const child of fragment.childNodes){
        if (child.nodeType === NodeType.ELEMENT_NODE) {
            search.push(child);
            child._getElementsByTagNameWildcard(search);
        }
    }
    return search;
}
DocumentFragment1.prototype[customByTagNameSym] = documentFragmentGetElementsByTagName;
DocumentFragment1.prototype[customByClassNameSym] = documentFragmentGetElementsByClassName;
const __default2 = (document1)=>{
    const NW = Factory({
        document: document1,
        DOMException
    }, "null");
    NW.configure({
        IDS_DUPES: false,
        LOGERRORS: false
    });
    return NW;
};
function Factory(global1, Export) {
    var version = 'nwsapi-2.2.0', doc = global1.document, root = doc.documentElement, slice = 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: '(is|where|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: '(any-link|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 i1 = 0, l1 = nodes.length, list = Array(l1);
        while(l1 > i1){
            if (false === callback(list[i1] = nodes[i1])) break;
            ++i1;
        }
        return list;
    }, concatList = function(list, nodes) {
        var i1 = -1, l1 = nodes.length;
        while(l1--){
            list[list.length] = nodes[++i1];
        }
        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 i1 = 0, j = -1, l1 = nodes.length + 1, list = [];
        while(--l1){
            if (nodes[i1++] === nodes[i1]) continue;
            list[++j] = nodes[i1 - 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 = doc;
        doc = context.ownerDocument || context;
        if (force || oldDoc !== doc) {
            root = doc.documentElement;
            HTML_DOCUMENT = isHTML(doc);
            QUIRKS_MODE = HTML_DOCUMENT && doc.compatMode.indexOf('CSS') < 0;
            NAMESPACE = root && root.namespaceURI;
            Snapshot.doc = doc;
            Snapshot.root = root;
        }
        return Snapshot.from = context;
    }, codePointToUTF16 = function(codePoint) {
        if (codePoint < 1 || codePoint > 0x10ffff || codePoint > 0xd7ff && codePoint < 0xe000) {
            return '\\ufffd';
        }
        if (codePoint < 0x10000) {
            var lowHex = '000' + codePoint.toString(16);
            return '\\u' + lowHex.substr(lowHex.length - 4);
        }
        return '\\u' + ((codePoint - 0x10000 >> 0x0a) + 0xd800).toString(16) + '\\u' + ((codePoint - 0x10000) % 0x400 + 0xdc00).toString(16);
    }, stringFromCodePoint = function(codePoint) {
        if (codePoint < 1 || codePoint > 0x10ffff || codePoint > 0xd7ff && codePoint < 0xe000) {
            return '\ufffd';
        }
        if (codePoint < 0x10000) {
            return String.fromCharCode(codePoint);
        }
        return String.fromCodePoint ? String.fromCodePoint(codePoint) : String.fromCharCode((codePoint - 0x10000 >> 0x0a) + 0xd800, (codePoint - 0x10000) % 0x400 + 0xdc00);
    }, convertEscapes = function(str) {
        return REX.HasEscapes.test(str) ? str.replace(REX.FixEscapes, function(substring, p1, p2) {
            return p2 ? '\\' + p2 : REX.HexNumbers.test(p1) ? codePointToUTF16(parseInt(p1, 16)) : REX.EscOrQuote.test(p1) ? substring : p1;
        }) : str;
    }, unescapeIdentifier = function(str) {
        return REX.HasEscapes.test(str) ? str.replace(REX.FixEscapes, function(substring, p1, p2) {
            return p2 ? p2 : REX.HexNumbers.test(p1) ? stringFromCodePoint(parseInt(p1, 16)) : REX.EscOrQuote.test(p1) ? substring : p1;
        }) : str;
    }, method = {
        '#': 'getElementById',
        '*': 'getElementsByTagNameNS',
        '.': 'getElementsByClassName'
    }, compat = {
        '#': function(c, n) {
            REX.HasEscapes.test(n) && (n = unescapeIdentifier(n));
            return function(e, f) {
                return byId(n, c);
            };
        },
        '*': function(c, n) {
            REX.HasEscapes.test(n) && (n = unescapeIdentifier(n));
            return function(e, f) {
                return byTag(n, c);
            };
        },
        '.': function(c, n) {
            REX.HasEscapes.test(n) && (n = unescapeIdentifier(n));
            return function(e, f) {
                return byClass(n, 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 slice.call(context[api]('*', tag));
        } else {
            tag = tag.toLowerCase();
            if (e = context.firstElementChild) {
                if (!(e.nextElementSibling || tag == '*' || e.localName == tag)) {
                    return slice.call(e[api]('*', tag));
                } else {
                    nodes = [];
                    do {
                        if (tag == '*' || e.localName == 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 slice.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 slice.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, name) {
        var i1, l1, attr = e.getAttributeNames();
        name = RegExp(':?' + name + '$', HTML_DOCUMENT ? 'i' : '');
        for(i1 = 0, l1 = attr.length; l1 > i1; ++i1){
            if (name.test(attr[i1])) return true;
        }
        return false;
    }, nthElement = function() {
        var idx = 0, len = 0, set = 0, parent = undefined, parents = Array(), nodes = Array();
        return function(element, dir) {
            if (dir == 2) {
                idx = 0;
                len = 0;
                set = 0;
                nodes.length = 0;
                parents.length = 0;
                parent = undefined;
                return -1;
            }
            var e, i1, j, k, l1;
            if (parent === element.parentElement) {
                i1 = set;
                j = idx;
                l1 = len;
            } else {
                l1 = parents.length;
                parent = element.parentElement;
                for(i1 = -1, j = 0, k = l1 - 1; l1 > j; ++j, --k){
                    if (parents[j] === parent) {
                        i1 = j;
                        break;
                    }
                    if (parents[k] === parent) {
                        i1 = k;
                        break;
                    }
                }
                if (i1 < 0) {
                    parents[i1 = l1] = parent;
                    l1 = 0;
                    nodes[i1] = Array();
                    e = parent && parent.firstElementChild || element;
                    while(e){
                        nodes[i1][l1] = e;
                        if (e === element) j = l1;
                        e = e.nextElementSibling;
                        ++l1;
                    }
                    set = i1;
                    idx = 0;
                    len = l1;
                    if (l1 < 2) return l1;
                } else {
                    l1 = nodes[i1].length;
                    set = i1;
                }
            }
            if (element !== nodes[i1][j] && element !== nodes[i1][j = 0]) {
                for(j = 0, e = nodes[i1], k = l1 - 1; l1 > j; ++j, --k){
                    if (e[j] === element) {
                        break;
                    }
                    if (e[k] === element) {
                        j = k;
                        break;
                    }
                }
            }
            idx = j + 1;
            len = l1;
            return dir ? l1 - j : idx;
        };
    }(), nthOfType = function() {
        var idx = 0, len = 0, set = 0, parent = undefined, parents = Array(), nodes = Array();
        return function(element, dir) {
            if (dir == 2) {
                idx = 0;
                len = 0;
                set = 0;
                nodes.length = 0;
                parents.length = 0;
                parent = undefined;
                return -1;
            }
            var e, i1, j, k, l1, name = element.localName;
            if (nodes[set] && nodes[set][name] && parent === element.parentElement) {
                i1 = set;
                j = idx;
                l1 = len;
            } else {
                l1 = parents.length;
                parent = element.parentElement;
                for(i1 = -1, j = 0, k = l1 - 1; l1 > j; ++j, --k){
                    if (parents[j] === parent) {
                        i1 = j;
                        break;
                    }
                    if (parents[k] === parent) {
                        i1 = k;
                        break;
                    }
                }
                if (i1 < 0 || !nodes[i1][name]) {
                    parents[i1 = l1] = parent;
                    nodes[i1] || (nodes[i1] = Object());
                    l1 = 0;
                    nodes[i1][name] = Array();
                    e = parent && parent.firstElementChild || element;
                    while(e){
                        if (e === element) j = l1;
                        if (e.localName == name) {
                            nodes[i1][name][l1] = e;
                            ++l1;
                        }
                        e = e.nextElementSibling;
                    }
                    set = i1;
                    idx = j;
                    len = l1;
                    if (l1 < 2) return l1;
                } else {
                    l1 = nodes[i1][name].length;
                    set = i1;
                }
            }
            if (element !== nodes[i1][name][j] && element !== nodes[i1][name][j = 0]) {
                for(j = 0, e = nodes[i1][name], k = l1 - 1; l1 > j; ++j, --k){
                    if (e[j] === element) {
                        break;
                    }
                    if (e[k] === element) {
                        j = k;
                        break;
                    }
                }
            }
            idx = j + 1;
            len = l1;
            return dir ? l1 - 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').localName == 'div';
    }, configure = function(option, clear) {
        if (typeof option == 'string') {
            return !!Config[option];
        }
        if (typeof option != 'object') {
            return Config;
        }
        for(var i1 in option){
            Config[i1] = !!option[i1];
        }
        if (clear) {
            matchResolvers = {};
            selectResolvers = {};
        }
        setIdentifierSyntax();
        return true;
    }, emit = function(message, proto) {
        var err;
        if (Config.VERBOSITY) {
            if (proto) {
                err = new proto(message);
            } else {
                err = new global1.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 factory, 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;
        }
        factory = Function('s', F_INIT + '{' + head + vars + ';' + loop + 'return r;}')(Snapshot);
        return mode || mode === null ? selectLambdas[selector] = factory : matchLambdas[selector] = factory;
    }, compileSelector = function(expression, source, mode, callback, not) {
        var a, b, n, f, name, NS, N = not ? '!' : '', D = not ? '' : '!', compat, expr, match, result1, 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.localName' + (Config.MIXEDCASE || hasMixedCaseTagNames(doc) ? '=="' + 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' && root.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);
                    name = match[1];
                    expr = name.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,"' + name + '")' : 'e.hasAttribute&&e.hasAttribute("' + name + '")' : !match[4] && ATTR_STD_OPS[match[2]] && match[2] != '~=' ? 'e.getAttribute&&e.getAttribute("' + name + '")==""' : '(/' + test.p1 + match[4] + test.p2 + '/' + type + ').test(e.getAttribute&&e.getAttribute("' + name + '"))==' + 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.localName;' + 'n=e;while((n=n.nextElementSibling)&&n.localName!=o);if(!n){' + 'n=e;while((n=n.previousElementSibling)&&n.localName!=o);}if(' + D + 'n){' + source + '}';
                                break;
                            case 'last-of-type':
                                source = 'n=e;o=e.localName;while((n=n.nextElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}';
                                break;
                            case 'first-of-type':
                                source = 'n=e;o=e.localName;while((n=n.previousElementSibling)&&n.localName!=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.localName;' + 'while((n=n.' + test + 'ElementSibling)&&n.localName!=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]);
                                        n = match[2].split('n');
                                        a = parseInt(n[0], 10) || 0;
                                        b = parseInt(n[1], 10) || 0;
                                        if (n[0] == '-') {
                                            a = -1;
                                        }
                                        if (n[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 ? n[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 'is':
                            case 'where':
                            case 'matches':
                                expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
                                source = 'if(s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}';
                                break;
                            case 'not':
                                expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
                                source = 'if(!s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}';
                                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 'any-link':
                                source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")||e.visited)){' + source + '}';
                                break;
                            case 'link':
                                source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href"))){' + source + '}';
                                break;
                            case 'visited':
                                source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&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 doc && doc.hasFocus() ? 'if(' + N + '(e===s.doc.hoverElement)){' + source + '}' : 'if(' + D + 'true){' + source + '}';
                                break;
                            case 'active':
                                source = 'hasFocus' in doc && doc.hasFocus() ? 'if(' + N + '(e===s.doc.activeElement)){' + source + '}' : 'if(' + D + 'true){' + source + '}';
                                break;
                            case 'focus':
                                source = 'hasFocus' in doc ? '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 doc ? '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.localName))&&"disabled" in e &&e.disabled===false' + ')){' + source + '}';
                                break;
                            case 'disabled':
                                source = 'if(' + N + '(("form" in e||/^optgroup$/i.test(e.localName))&&"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.localName)&&(e.readOnly||e.disabled))||' + '("|password|text|".includes("|"+e.type+"|")&&e.readOnly)' + ')){' + source + '}';
                                break;
                            case 'read-write':
                                source = 'if(' + N + '(' + '((/^textarea$/i.test(e.localName)&&!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.localName))&&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.localName))&&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.localName)&&' + '("|radio|checkbox|".includes("|"+e.type+"|")&&e.checked)||' + '(/^option$/i.test(e.localName)&&(e.selected||e.checked))' + ')){' + source + '}';
                                break;
                            case 'indeterminate':
                                source = 'if(' + N + '(/^progress$/i.test(e.localName)&&!e.hasAttribute("value"))||' + '(/^input$/i.test(e.localName)&&("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.localName)&&e.required)' + '){' + source + '}';
                                break;
                            case 'optional':
                                source = 'if(' + N + '(/^input|select|textarea$/i.test(e.localName)&&!e.required)' + '){' + source + '}';
                                break;
                            case 'invalid':
                                source = 'if(' + N + '((' + '(/^form$/i.test(e.localName)&&!e.noValidate)||' + '(e.willValidate&&!e.formNoValidate))&&!e.checkValidity())||' + '(/^fieldset$/i.test(e.localName)&&s.first(":invalid",e))' + '){' + source + '}';
                                break;
                            case 'valid':
                                source = 'if(' + N + '((' + '(/^form$/i.test(e.localName)&&!e.noValidate)||' + '(e.willValidate&&!e.formNoValidate))&&e.checkValidity())||' + '(/^fieldset$/i.test(e.localName)&&s.first(":valid",e))' + '){' + source + '}';
                                break;
                            case 'in-range':
                                source = 'if(' + N + '(/^input$/i.test(e.localName))&&' + '(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.localName))&&' + '(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(e.element&&e.type.toLowerCase()=="' + ':' + match[0].toLowerCase() + '"){e=e.element;' + source + '}';
                    } else if (match = selector.match(Patterns.pseudo_dbl)) {
                        source = 'if(e.element&&e.type.toLowerCase()=="' + match[0].toLowerCase() + '"){e=e.element;' + source + '}';
                    } else {
                        expr = false;
                        status = false;
                        for(expr in Selectors){
                            if (match = selector.match(Selectors[expr].Expression)) {
                                result1 = Selectors[expr].Callback(match, source, mode, callback);
                                if ('match' in result1) {
                                    match = result1.match;
                                }
                                vars = result1.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 = result1.source;
                                status = result1.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.localName + (element.id ? '#' + element.id : '') + (element.className ? '.' + element.classList[0] : ''));
    }, ancestor = function _closest(selectors, element, callback) {
        if (/:scope/i.test(selectors)) {
            selectors = makeref(selectors, element);
        }
        while(element){
            if (match(selectors, element, callback)) break;
            element = element.parentElement;
        }
        return element;
    }, match_assert = function(f, element, callback) {
        for(var i1 = 0, l1 = f.length, r = false; l1 > i1; ++i1)f[i1](element, callback, null, false) && (r = true);
        return r;
    }, match_collect = function(selectors, callback) {
        for(var i1 = 0, l1 = selectors.length, f = []; l1 > i1; ++i1)f[i1] = compile(selectors[i1], false, callback);
        return {
            factory: f
        };
    }, match = 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 = doc);
        if (selectors) {
            if (resolver = selectResolvers[selectors]) {
                if (resolver.context === context && resolver.callback === callback) {
                    var f = resolver.factory, h = resolver.htmlset, n = resolver.nodeset, nodes = [];
                    if (n.length > 1) {
                        for(var i1 = 0, l1 = n.length, list; l1 > i1; ++i1){
                            list = compat[n[i1][0]](context, n[i1].slice(1))();
                            if (f[i1] !== null) {
                                f[i1](list, callback, context, nodes);
                            } else {
                                nodes = nodes.concat(list);
                            }
                        }
                        if (l1 > 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 i1, l1, seen = {}, token = [
            '',
            '*',
            '*'
        ], optimized = selectors, factory = [], htmlset = [], nodeset = [], results = [], type;
        for(i1 = 0, l1 = selectors.length; l1 > i1; ++i1){
            if (!seen[selectors[i1]] && (seen[selectors[i1]] = true)) {
                type = selectors[i1].match(reOptimizer);
                if (type && type[1] != ':' && (token = type)) {
                    token[1] || (token[1] = '*');
                    optimized[i1] = optimize(optimized[i1], token);
                } else {
                    token = [
                        '',
                        '*',
                        '*'
                    ];
                }
            }
            nodeset[i1] = token[1] + token[2];
            htmlset[i1] = compat[token[1]](context, token[2]);
            factory[i1] = compile(optimized[i1], true, null);
            factory[i1] ? factory[i1](htmlset[i1](), callback, context, results) : result.concat(htmlset[i1]());
        }
        if (l1 > 1) {
            results.sort(documentOrder);
            hasDupes && (results = unique(results));
        }
        return {
            callback: callback,
            context: context,
            factory: factory,
            htmlset: htmlset,
            nodeset: nodeset,
            results: results
        };
    }, _closest, _matches, _querySelector, _querySelectorAll, install = 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 ? ancestor.apply(this, []) : arguments.length < 2 ? ancestor.apply(this, [
                arguments[0],
                this
            ]) : ancestor.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 ? match.apply(this, []) : arguments.length < 2 ? match.apply(this, [
                arguments[0],
                this
            ]) : match.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.localName)) {
                    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);
        }
    }, uninstall = 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: doc,
        from: doc,
        root: root,
        byTag: byTag,
        first: first,
        match: match,
        ancestor: ancestor,
        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: match,
        first: first,
        select: select,
        closest: ancestor,
        compile: compile,
        configure: configure,
        emit: emit,
        Config: Config,
        Snapshot: Snapshot,
        Version: version,
        install: install,
        uninstall: uninstall,
        Operators: Operators,
        Selectors: Selectors,
        registerCombinator: function(combinator, resolver) {
            var i1 = 0, l1 = combinator.length, symbol;
            for(; l1 > i1; ++i1){
                if (combinator[i1] != '=') {
                    symbol = combinator[i1];
                    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 i1 = 0, l1 = operator.length, symbol;
            for(; l1 > i1; ++i1){
                if (operator[i1] != '=') {
                    symbol = operator[i1];
                    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(name, rexp, func) {
            Selectors[name] || (Selectors[name] = {
                Expression: rexp,
                Callback: func
            });
        }
    };
    initialize(doc);
    return Dom;
}
function SetupSizzle(window1) {
    var i1, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, setDocument, document1, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, expando = "sizzle" + 1 * new Date(), preferredDoc = window1.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function(a, b) {
        if (a === b) {
            hasDuplicate = true;
        }
        return 0;
    }, hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, indexOf = function(list, elem) {
        var i1 = 0, len = list.length;
        for(; i1 < len; i1++){
            if (list[i1] === elem) {
                return i1;
            }
        }
        return -1;
    }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", whitespace = "[\\x20\\t\\r\\n\\f]", identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + "*([*^$|!~]?=)" + whitespace + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + ".*" + ")\\)|)", rwhitespace = new RegExp(whitespace + "+", "g"), rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"), rdescend = new RegExp(whitespace + "|>"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = {
        ID: new RegExp("^#(" + identifier + ")"),
        CLASS: new RegExp("^\\.(" + identifier + ")"),
        TAG: new RegExp("^(" + identifier + "|[*])"),
        ATTR: new RegExp("^" + attributes),
        PSEUDO: new RegExp("^" + pseudos),
        CHILD: new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
        bool: new RegExp("^(?:" + booleans + ")$", "i"),
        needsContext: new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
    }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, runescape = new RegExp("\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g"), funescape = function(escape, nonHex) {
        var high = "0x" + escape.slice(1) - 0x10000;
        return nonHex ? nonHex : high < 0 ? String.fromCharCode(high + 0x10000) : String.fromCharCode(high >> 10 | 0xd800, high & 0x3ff | 0xdc00);
    }, rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function(ch, asCodePoint) {
        if (asCodePoint) {
            if (ch === "\0") {
                return "\uFFFD";
            }
            return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " ";
        }
        return "\\" + ch;
    }, unloadHandler = function() {
        setDocument();
    }, inDisabledFieldset = addCombinator(function(elem) {
        return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
    }, {
        dir: "parentNode",
        next: "legend"
    });
    try {
        push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes);
        arr[preferredDoc.childNodes.length].nodeType;
    } catch (e) {
        push = {
            apply: arr.length ? function(target, els) {
                pushNative.apply(target, slice.call(els));
            } : function(target, els) {
                var j = target.length, i1 = 0;
                while(target[j++] = els[i1++]){}
                target.length = j - 1;
            }
        };
    }
    function Sizzle(selector, context, results, seed) {
        var m, i1, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, nodeType = context ? context.nodeType : 9;
        results = results || [];
        if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) {
            return results;
        }
        if (!seed) {
            setDocument(context);
            context = context || document1;
            if (documentIsHTML) {
                if (nodeType !== 11 && (match = rquickExpr.exec(selector))) {
                    if (m = match[1]) {
                        if (nodeType === 9) {
                            if (elem = context.getElementById(m)) {
                                if (elem.id === m) {
                                    results.push(elem);
                                    return results;
                                }
                            } else {
                                return results;
                            }
                        } else {
                            if (newContext && (elem = newContext.getElementById(m)) && contains(context, elem) && elem.id === m) {
                                results.push(elem);
                                return results;
                            }
                        }
                    } else if (match[2]) {
                        push.apply(results, context.getElementsByTagName(selector));
                        return results;
                    } else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) {
                        push.apply(results, context.getElementsByClassName(m));
                        return results;
                    }
                }
                if (support.qsa && !nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector)) && (nodeType !== 1 || context.nodeName.toLowerCase() !== "object")) {
                    newSelector = selector;
                    newContext = context;
                    if (nodeType === 1 && (rdescend.test(selector) || rcombinators.test(selector))) {
                        newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
                        if (newContext !== context || !support.scope) {
                            if (nid = context.getAttribute("id")) {
                                nid = nid.replace(rcssescape, fcssescape);
                            } else {
                                context.setAttribute("id", nid = expando);
                            }
                        }
                        groups = tokenize(selector);
                        i1 = groups.length;
                        while(i1--){
                            groups[i1] = (nid ? "#" + nid : ":scope") + " " + toSelector(groups[i1]);
                        }
                        newSelector = groups.join(",");
                    }
                    try {
                        push.apply(results, newContext.querySelectorAll(newSelector));
                        return results;
                    } catch (qsaError) {
                        nonnativeSelectorCache(selector, true);
                    } finally{
                        if (nid === expando) {
                            context.removeAttribute("id");
                        }
                    }
                }
            }
        }
        return select(selector.replace(rtrim, "$1"), context, results, seed);
    }
    function createCache() {
        var keys = [];
        function cache(key, value) {
            if (keys.push(key + " ") > Expr.cacheLength) {
                delete cache[keys.shift()];
            }
            return cache[key + " "] = value;
        }
        return cache;
    }
    function markFunction(fn) {
        fn[expando] = true;
        return fn;
    }
    function assert(fn) {
        return true;
        var el = document1.createElement("fieldset");
        try {
            return !!fn(el);
        } catch (e) {
            return false;
        } finally{
            if (el.parentNode) {
                el.parentNode.removeChild(el);
            }
            el = null;
        }
    }
    function addHandle(attrs, handler) {
        var arr = attrs.split("|"), i1 = arr.length;
        while(i1--){
            Expr.attrHandle[arr[i1]] = handler;
        }
    }
    function siblingCheck(a, b) {
        var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex;
        if (diff) {
            return diff;
        }
        if (cur) {
            while(cur = cur.nextSibling){
                if (cur === b) {
                    return -1;
                }
            }
        }
        return a ? 1 : -1;
    }
    function createInputPseudo(type) {
        return function(elem) {
            var name = elem.nodeName.toLowerCase();
            return name === "input" && elem.type === type;
        };
    }
    function createButtonPseudo(type) {
        return function(elem) {
            var name = elem.nodeName.toLowerCase();
            return (name === "input" || name === "button") && elem.type === type;
        };
    }
    function createDisabledPseudo(disabled) {
        return function(elem) {
            if ("form" in elem) {
                if (elem.parentNode && elem.disabled === false) {
                    if ("label" in elem) {
                        if ("label" in elem.parentNode) {
                            return elem.parentNode.disabled === disabled;
                        } else {
                            return elem.disabled === disabled;
                        }
                    }
                    return elem.isDisabled === disabled || elem.isDisabled !== !disabled && inDisabledFieldset(elem) === disabled;
                }
                return elem.disabled === disabled;
            } else if ("label" in elem) {
                return elem.disabled === disabled;
            }
            return false;
        };
    }
    function createPositionalPseudo(fn) {
        return markFunction(function(argument) {
            argument = +argument;
            return markFunction(function(seed, matches) {
                var j, matchIndexes = fn([], seed.length, argument), i1 = matchIndexes.length;
                while(i1--){
                    if (seed[j = matchIndexes[i1]]) {
                        seed[j] = !(matches[j] = seed[j]);
                    }
                }
            });
        });
    }
    function testContext(context) {
        return context && typeof context.getElementsByTagName !== "undefined" && context;
    }
    support = Sizzle.support = {};
    isXML = Sizzle.isXML = function(elem) {
        var namespace = elem && elem.namespaceURI, docElem = elem && (elem.ownerDocument || elem).documentElement;
        return !rhtml.test(namespace || docElem && docElem.nodeName || "HTML");
    };
    setDocument = Sizzle.setDocument = function(node) {
        var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc;
        if (doc == document1 || doc.nodeType !== 9 || !doc.documentElement) {
            return document1;
        }
        document1 = doc;
        docElem = document1.documentElement;
        documentIsHTML = !isXML(document1);
        if (preferredDoc != document1 && (subWindow = document1.defaultView) && subWindow.top !== subWindow) {
            if (subWindow.addEventListener) {
                subWindow.addEventListener("unload", unloadHandler, false);
            } else if (subWindow.attachEvent) {
                subWindow.attachEvent("onunload", unloadHandler);
            }
        }
        support.scope = assert(function(el) {
            docElem.appendChild(el).appendChild(document1.createElement("div"));
            return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll(":scope fieldset div").length;
        });
        support.attributes = assert(function(el) {
            el.className = "i";
            return !el.getAttribute("className");
        });
        support.getElementsByTagName = assert(function(el) {
            el.appendChild(document1.createComment(""));
            return !el.getElementsByTagName("*").length;
        });
        support.getElementsByClassName = rnative.test(document1.getElementsByClassName);
        support.getById = assert(function(el) {
            docElem.appendChild(el).id = expando;
            return !document1.getElementsByName || !document1.getElementsByName(expando).length;
        });
        if (support.getById) {
            Expr.filter["ID"] = function(id) {
                var attrId = id.replace(runescape, funescape);
                return function(elem) {
                    return elem.getAttribute("id") === attrId;
                };
            };
            Expr.find["ID"] = function(id, context) {
                if (typeof context.getElementById !== "undefined" && documentIsHTML) {
                    var elem = context.getElementById(id);
                    return elem ? [
                        elem
                    ] : [];
                }
            };
        } else {
            Expr.filter["ID"] = function(id) {
                var attrId = id.replace(runescape, funescape);
                return function(elem) {
                    var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
                    return node && node.value === attrId;
                };
            };
            Expr.find["ID"] = function(id, context) {
                if (typeof context.getElementById !== "undefined" && documentIsHTML) {
                    var node, i1, elems, elem = context.getElementById(id);
                    if (elem) {
                        node = elem.getAttributeNode("id");
                        if (node && node.value === id) {
                            return [
                                elem
                            ];
                        }
                        elems = context.getElementsByName(id);
                        i1 = 0;
                        while(elem = elems[i1++]){
                            node = elem.getAttributeNode("id");
                            if (node && node.value === id) {
                                return [
                                    elem
                                ];
                            }
                        }
                    }
                    return [];
                }
            };
        }
        Expr.find["TAG"] = support.getElementsByTagName ? function(tag, context) {
            if (typeof context.getElementsByTagName !== "undefined") {
                return context.getElementsByTagName(tag);
            } else if (context[customByTagNameSym]) {
                return context[customByTagNameSym](tag);
            } else if (support.qsa) {
                return context.querySelectorAll(tag);
            }
        } : function(tag, context) {
            var elem, tmp = [], i1 = 0, results = context.getElementsByTagName(tag);
            if (tag === "*") {
                while(elem = results[i1++]){
                    if (elem.nodeType === 1) {
                        tmp.push(elem);
                    }
                }
                return tmp;
            }
            return results;
        };
        Expr.find["CLASS"] = support.getElementsByClassName && function(className, context) {
            if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) {
                return context.getElementsByClassName(className);
            } else if (context[customByClassNameSym]) {
                return context[customByClassNameSym](className);
            }
        };
        rbuggyMatches = [];
        rbuggyQSA = [];
        if (support.qsa = rnative.test(document1.querySelectorAll)) {
            assert(function(el) {
                var input;
                docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>";
                if (el.querySelectorAll("[msallowcapture^='']").length) {
                    rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")");
                }
                if (!el.querySelectorAll("[selected]").length) {
                    rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
                }
                if (!el.querySelectorAll("[id~=" + expando + "-]").length) {
                    rbuggyQSA.push("~=");
                }
                input = document1.createElement("input");
                input.setAttribute("name", "");
                el.appendChild(input);
                if (!el.querySelectorAll("[name='']").length) {
                    rbuggyQSA.push("\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")");
                }
                if (!el.querySelectorAll(":checked").length) {
                    rbuggyQSA.push(":checked");
                }
                if (!el.querySelectorAll("a#" + expando + "+*").length) {
                    rbuggyQSA.push(".#.+[+~]");
                }
                el.querySelectorAll("\\\f");
                rbuggyQSA.push("[\\r\\n\\f]");
            });
            assert(function(el) {
                el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>";
                var input = document1.createElement("input");
                input.setAttribute("type", "hidden");
                el.appendChild(input).setAttribute("name", "D");
                if (el.querySelectorAll("[name=d]").length) {
                    rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
                }
                if (el.querySelectorAll(":enabled").length !== 2) {
                    rbuggyQSA.push(":enabled", ":disabled");
                }
                docElem.appendChild(el).disabled = true;
                if (el.querySelectorAll(":disabled").length !== 2) {
                    rbuggyQSA.push(":enabled", ":disabled");
                }
                el.querySelectorAll("*,:x");
                rbuggyQSA.push(",.*:");
            });
        }
        if (support.matchesSelector = rnative.test(matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)) {
            assert(function(el) {
                support.disconnectedMatch = matches.call(el, "*");
                matches.call(el, "[s!='']:x");
                rbuggyMatches.push("!=", pseudos);
            });
        }
        rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
        rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
        hasCompare = rnative.test(docElem.compareDocumentPosition);
        contains = hasCompare || rnative.test(docElem.contains) ? function(a, b) {
            var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode;
            return a === bup || !!(bup && bup.nodeType === 1 && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16));
        } : function(a, b) {
            if (b) {
                while(b = b.parentNode){
                    if (b === a) {
                        return true;
                    }
                }
            }
            return false;
        };
        sortOrder = hasCompare ? function(a, b) {
            if (a === b) {
                hasDuplicate = true;
                return 0;
            }
            var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
            if (compare) {
                return compare;
            }
            compare = (a.ownerDocument || a) == (b.ownerDocument || b) ? a.compareDocumentPosition(b) : 1;
            if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) {
                if (a == document1 || a.ownerDocument == preferredDoc && contains(preferredDoc, a)) {
                    return -1;
                }
                if (b == document1 || b.ownerDocument == preferredDoc && contains(preferredDoc, b)) {
                    return 1;
                }
                return sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
            }
            return compare & 4 ? -1 : 1;
        } : function(a, b) {
            if (a === b) {
                hasDuplicate = true;
                return 0;
            }
            var cur, i1 = 0, aup = a.parentNode, bup = b.parentNode, ap = [
                a
            ], bp = [
                b
            ];
            if (!aup || !bup) {
                return a == document1 ? -1 : b == document1 ? 1 : aup ? -1 : bup ? 1 : sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
            } else if (aup === bup) {
                return siblingCheck(a, b);
            }
            cur = a;
            while(cur = cur.parentNode){
                ap.unshift(cur);
            }
            cur = b;
            while(cur = cur.parentNode){
                bp.unshift(cur);
            }
            while(ap[i1] === bp[i1]){
                i1++;
            }
            return i1 ? siblingCheck(ap[i1], bp[i1]) : ap[i1] == preferredDoc ? -1 : bp[i1] == preferredDoc ? 1 : 0;
        };
        return document1;
    };
    Sizzle.matches = function(expr, elements) {
        return Sizzle(expr, null, null, elements);
    };
    Sizzle.matchesSelector = function(elem, expr) {
        setDocument(elem);
        if (support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
            try {
                var ret = matches.call(elem, expr);
                if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
                    return ret;
                }
            } catch (e) {
                nonnativeSelectorCache(expr, true);
            }
        }
        return Sizzle(expr, document1, null, [
            elem
        ]).length > 0;
    };
    Sizzle.contains = function(context, elem) {
        if ((context.ownerDocument || context) != document1) {
            setDocument(context);
        }
        return contains(context, elem);
    };
    Sizzle.attr = function(elem, name) {
        if ((elem.ownerDocument || elem) != document1) {
            setDocument(elem);
        }
        var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined;
        return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
    };
    Sizzle.escape = function(sel) {
        return (sel + "").replace(rcssescape, fcssescape);
    };
    Sizzle.error = function(msg) {
        throw new DOMException(`'${msg}' is not a valid selector`);
    };
    Sizzle.uniqueSort = function(results) {
        var elem, duplicates = [], j = 0, i1 = 0;
        hasDuplicate = !support.detectDuplicates;
        sortInput = !support.sortStable && results.slice(0);
        results.sort(sortOrder);
        if (hasDuplicate) {
            while(elem = results[i1++]){
                if (elem === results[i1]) {
                    j = duplicates.push(i1);
                }
            }
            while(j--){
                results.splice(duplicates[j], 1);
            }
        }
        sortInput = null;
        return results;
    };
    getText = Sizzle.getText = function(elem) {
        var node, ret = "", i1 = 0, nodeType = elem.nodeType;
        if (!nodeType) {
            while(node = elem[i1++]){
                ret += getText(node);
            }
        } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
            if (typeof elem.textContent === "string") {
                return elem.textContent;
            } else {
                for(elem = elem.firstChild; elem; elem = elem.nextSibling){
                    ret += getText(elem);
                }
            }
        } else if (nodeType === 3 || nodeType === 4) {
            return elem.nodeValue;
        }
        return ret;
    };
    Expr = Sizzle.selectors = {
        cacheLength: 50,
        createPseudo: markFunction,
        match: matchExpr,
        attrHandle: {},
        find: {},
        relative: {
            ">": {
                dir: "parentNode",
                first: true
            },
            " ": {
                dir: "parentNode"
            },
            "+": {
                dir: "previousSibling",
                first: true
            },
            "~": {
                dir: "previousSibling"
            }
        },
        preFilter: {
            ATTR: function(match) {
                match[1] = match[1].replace(runescape, funescape);
                match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape);
                if (match[2] === "~=") {
                    match[3] = " " + match[3] + " ";
                }
                return match.slice(0, 4);
            },
            CHILD: function(match) {
                match[1] = match[1].toLowerCase();
                if (match[1].slice(0, 3) === "nth") {
                    if (!match[3]) {
                        Sizzle.error(match[0]);
                    }
                    match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd"));
                    match[5] = +(match[7] + match[8] || match[3] === "odd");
                } else if (match[3]) {
                    Sizzle.error(match[0]);
                }
                return match;
            },
            PSEUDO: function(match) {
                var excess, unquoted = !match[6] && match[2];
                if (matchExpr["CHILD"].test(match[0])) {
                    return null;
                }
                if (match[3]) {
                    match[2] = match[4] || match[5] || "";
                } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
                    match[0] = match[0].slice(0, excess);
                    match[2] = unquoted.slice(0, excess);
                }
                return match.slice(0, 3);
            }
        },
        filter: {
            TAG: function(nodeNameSelector) {
                var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
                return nodeNameSelector === "*" ? function() {
                    return true;
                } : function(elem) {
                    return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
                };
            },
            CLASS: function(className) {
                var pattern = classCache[className + " "];
                return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function(elem) {
                    return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "");
                });
            },
            ATTR: function(name, operator, check) {
                return function(elem) {
                    var result1 = Sizzle.attr(elem, name);
                    if (result1 == null) {
                        return operator === "!=";
                    }
                    if (!operator) {
                        return true;
                    }
                    result1 += "";
                    return operator === "=" ? result1 === check : operator === "!=" ? result1 !== check : operator === "^=" ? check && result1.indexOf(check) === 0 : operator === "*=" ? check && result1.indexOf(check) > -1 : operator === "$=" ? check && result1.slice(-check.length) === check : operator === "~=" ? (" " + result1.replace(rwhitespace, " ") + " ").indexOf(check) > -1 : operator === "|=" ? result1 === check || result1.slice(0, check.length + 1) === check + "-" : false;
                };
            },
            CHILD: function(type, what, _argument, first, last) {
                var simple = type.slice(0, 3) !== "nth", forward = type.slice(-4) !== "last", ofType = what === "of-type";
                return first === 1 && last === 0 ? function(elem) {
                    return !!elem.parentNode;
                } : function(elem, _context, xml) {
                    var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false;
                    if (parent) {
                        if (simple) {
                            while(dir){
                                node = elem;
                                while(node = node[dir]){
                                    if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
                                        return false;
                                    }
                                }
                                start = dir = type === "only" && !start && "nextSibling";
                            }
                            return true;
                        }
                        start = [
                            forward ? parent.firstChild : parent.lastChild
                        ];
                        if (forward && useCache) {
                            node = parent;
                            outerCache = node[expando] || (node[expando] = {});
                            uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                            cache = uniqueCache[type] || [];
                            nodeIndex = cache[0] === dirruns && cache[1];
                            diff = nodeIndex && cache[2];
                            node = nodeIndex && parent.childNodes[nodeIndex];
                            while(node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()){
                                if (node.nodeType === 1 && ++diff && node === elem) {
                                    uniqueCache[type] = [
                                        dirruns,
                                        nodeIndex,
                                        diff
                                    ];
                                    break;
                                }
                            }
                        } else {
                            if (useCache) {
                                node = elem;
                                outerCache = node[expando] || (node[expando] = {});
                                uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                                cache = uniqueCache[type] || [];
                                nodeIndex = cache[0] === dirruns && cache[1];
                                diff = nodeIndex;
                            }
                            if (diff === false) {
                                while(node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()){
                                    if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) {
                                        if (useCache) {
                                            outerCache = node[expando] || (node[expando] = {});
                                            uniqueCache = outerCache[node.uniqueID] || (outerCache[node.uniqueID] = {});
                                            uniqueCache[type] = [
                                                dirruns,
                                                diff
                                            ];
                                        }
                                        if (node === elem) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        diff -= last;
                        return diff === first || diff % first === 0 && diff / first >= 0;
                    }
                };
            },
            PSEUDO: function(pseudo, argument) {
                var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
                if (fn[expando]) {
                    return fn(argument);
                }
                if (fn.length > 1) {
                    args = [
                        pseudo,
                        pseudo,
                        "",
                        argument
                    ];
                    return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches) {
                        var idx, matched = fn(seed, argument), i1 = matched.length;
                        while(i1--){
                            idx = indexOf(seed, matched[i1]);
                            seed[idx] = !(matches[idx] = matched[i1]);
                        }
                    }) : function(elem) {
                        return fn(elem, 0, args);
                    };
                }
                return fn;
            }
        },
        pseudos: {
            not: markFunction(function(selector) {
                var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1"));
                return matcher[expando] ? markFunction(function(seed, matches, _context, xml) {
                    var elem, unmatched = matcher(seed, null, xml, []), i1 = seed.length;
                    while(i1--){
                        if (elem = unmatched[i1]) {
                            seed[i1] = !(matches[i1] = elem);
                        }
                    }
                }) : function(elem, _context, xml) {
                    input[0] = elem;
                    matcher(input, null, xml, results);
                    input[0] = null;
                    return !results.pop();
                };
            }),
            has: markFunction(function(selector) {
                return function(elem) {
                    return Sizzle(selector, elem).length > 0;
                };
            }),
            contains: markFunction(function(text) {
                text = text.replace(runescape, funescape);
                return function(elem) {
                    return (elem.textContent || getText(elem)).indexOf(text) > -1;
                };
            }),
            lang: markFunction(function(lang) {
                if (!ridentifier.test(lang || "")) {
                    Sizzle.error("unsupported lang: " + lang);
                }
                lang = lang.replace(runescape, funescape).toLowerCase();
                return function(elem) {
                    var elemLang;
                    do {
                        if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) {
                            elemLang = elemLang.toLowerCase();
                            return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
                        }
                    }while ((elem = elem.parentNode) && elem.nodeType === 1)
                    return false;
                };
            }),
            target: function(elem) {
                var hash = window1.location && window1.location.hash;
                return hash && hash.slice(1) === elem.id;
            },
            root: function(elem) {
                return elem === docElem;
            },
            focus: function(elem) {
                return elem === document1.activeElement && (!document1.hasFocus || document1.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
            },
            enabled: createDisabledPseudo(false),
            disabled: createDisabledPseudo(true),
            checked: function(elem) {
                var nodeName = elem.nodeName.toLowerCase();
                return nodeName === "input" && !!elem.checked || nodeName === "option" && !!elem.selected;
            },
            selected: function(elem) {
                if (elem.parentNode) {
                    elem.parentNode.selectedIndex;
                }
                return elem.selected === true;
            },
            empty: function(elem) {
                for(elem = elem.firstChild; elem; elem = elem.nextSibling){
                    if (elem.nodeType < 6) {
                        return false;
                    }
                }
                return true;
            },
            parent: function(elem) {
                return !Expr.pseudos["empty"](elem);
            },
            header: function(elem) {
                return rheader.test(elem.nodeName);
            },
            input: function(elem) {
                return rinputs.test(elem.nodeName);
            },
            button: function(elem) {
                var name = elem.nodeName.toLowerCase();
                return name === "input" && elem.type === "button" || name === "button";
            },
            text: function(elem) {
                var attr;
                return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text");
            },
            first: createPositionalPseudo(function() {
                return [
                    0
                ];
            }),
            last: createPositionalPseudo(function(_matchIndexes, length) {
                return [
                    length - 1
                ];
            }),
            eq: createPositionalPseudo(function(_matchIndexes, length, argument) {
                return [
                    argument < 0 ? argument + length : argument
                ];
            }),
            even: createPositionalPseudo(function(matchIndexes, length) {
                var i1 = 0;
                for(; i1 < length; i1 += 2){
                    matchIndexes.push(i1);
                }
                return matchIndexes;
            }),
            odd: createPositionalPseudo(function(matchIndexes, length) {
                var i1 = 1;
                for(; i1 < length; i1 += 2){
                    matchIndexes.push(i1);
                }
                return matchIndexes;
            }),
            lt: createPositionalPseudo(function(matchIndexes, length, argument) {
                var i1 = argument < 0 ? argument + length : argument > length ? length : argument;
                for(; --i1 >= 0;){
                    matchIndexes.push(i1);
                }
                return matchIndexes;
            }),
            gt: createPositionalPseudo(function(matchIndexes, length, argument) {
                var i1 = argument < 0 ? argument + length : argument;
                for(; ++i1 < length;){
                    matchIndexes.push(i1);
                }
                return matchIndexes;
            })
        }
    };
    Expr.pseudos["nth"] = Expr.pseudos["eq"];
    for(i1 in {
        radio: true,
        checkbox: true,
        file: true,
        password: true,
        image: true
    }){
        Expr.pseudos[i1] = createInputPseudo(i1);
    }
    for(i1 in {
        submit: true,
        reset: true
    }){
        Expr.pseudos[i1] = createButtonPseudo(i1);
    }
    function setFilters() {}
    setFilters.prototype = Expr.filters = Expr.pseudos;
    Expr.setFilters = new setFilters();
    tokenize = Sizzle.tokenize = function(selector, parseOnly) {
        var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + " "];
        if (cached) {
            return parseOnly ? 0 : cached.slice(0);
        }
        soFar = selector;
        groups = [];
        preFilters = Expr.preFilter;
        while(soFar){
            if (!matched || (match = rcomma.exec(soFar))) {
                if (match) {
                    soFar = soFar.slice(match[0].length) || soFar;
                }
                groups.push(tokens = []);
            }
            matched = false;
            if (match = rcombinators.exec(soFar)) {
                matched = match.shift();
                tokens.push({
                    value: matched,
                    type: match[0].replace(rtrim, " ")
                });
                soFar = soFar.slice(matched.length);
            }
            for(type in Expr.filter){
                if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) {
                    matched = match.shift();
                    tokens.push({
                        value: matched,
                        type: type,
                        matches: match
                    });
                    soFar = soFar.slice(matched.length);
                }
            }
            if (!matched) {
                break;
            }
        }
        return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups).slice(0);
    };
    function toSelector(tokens) {
        var i1 = 0, len = tokens.length, selector = "";
        for(; i1 < len; i1++){
            selector += tokens[i1].value;
        }
        return selector;
    }
    function addCombinator(matcher, combinator, base) {
        var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++;
        return combinator.first ? function(elem, context, xml) {
            while(elem = elem[dir]){
                if (elem.nodeType === 1 || checkNonElements) {
                    return matcher(elem, context, xml);
                }
            }
            return false;
        } : function(elem, context, xml) {
            var oldCache, uniqueCache, outerCache, newCache = [
                dirruns,
                doneName
            ];
            if (xml) {
                while(elem = elem[dir]){
                    if (elem.nodeType === 1 || checkNonElements) {
                        if (matcher(elem, context, xml)) {
                            return true;
                        }
                    }
                }
            } else {
                while(elem = elem[dir]){
                    if (elem.nodeType === 1 || checkNonElements) {
                        outerCache = elem[expando] || (elem[expando] = {});
                        uniqueCache = outerCache[elem.uniqueID] || (outerCache[elem.uniqueID] = {});
                        if (skip && skip === elem.nodeName.toLowerCase()) {
                            elem = elem[dir] || elem;
                        } else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) {
                            return newCache[2] = oldCache[2];
                        } else {
                            uniqueCache[key] = newCache;
                            if (newCache[2] = matcher(elem, context, xml)) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        };
    }
    function elementMatcher(matchers) {
        return matchers.length > 1 ? function(elem, context, xml) {
            var i1 = matchers.length;
            while(i1--){
                if (!matchers[i1](elem, context, xml)) {
                    return false;
                }
            }
            return true;
        } : matchers[0];
    }
    function multipleContexts(selector, contexts, results) {
        var i1 = 0, len = contexts.length;
        for(; i1 < len; i1++){
            Sizzle(selector, contexts[i1], results);
        }
        return results;
    }
    function condense(unmatched, map, filter, context, xml) {
        var elem, newUnmatched = [], i1 = 0, len = unmatched.length, mapped = map != null;
        for(; i1 < len; i1++){
            if (elem = unmatched[i1]) {
                if (!filter || filter(elem, context, xml)) {
                    newUnmatched.push(elem);
                    if (mapped) {
                        map.push(i1);
                    }
                }
            }
        }
        return newUnmatched;
    }
    function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
        if (postFilter && !postFilter[expando]) {
            postFilter = setMatcher(postFilter);
        }
        if (postFinder && !postFinder[expando]) {
            postFinder = setMatcher(postFinder, postSelector);
        }
        return markFunction(function(seed, results, context, xml) {
            var temp, i1, elem, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts(selector || "*", context.nodeType ? [
                context
            ] : context, []), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
            if (matcher) {
                matcher(matcherIn, matcherOut, context, xml);
            }
            if (postFilter) {
                temp = condense(matcherOut, postMap);
                postFilter(temp, [], context, xml);
                i1 = temp.length;
                while(i1--){
                    if (elem = temp[i1]) {
                        matcherOut[postMap[i1]] = !(matcherIn[postMap[i1]] = elem);
                    }
                }
            }
            if (seed) {
                if (postFinder || preFilter) {
                    if (postFinder) {
                        temp = [];
                        i1 = matcherOut.length;
                        while(i1--){
                            if (elem = matcherOut[i1]) {
                                temp.push(matcherIn[i1] = elem);
                            }
                        }
                        postFinder(null, matcherOut = [], temp, xml);
                    }
                    i1 = matcherOut.length;
                    while(i1--){
                        if ((elem = matcherOut[i1]) && (temp = postFinder ? indexOf(seed, elem) : preMap[i1]) > -1) {
                            seed[temp] = !(results[temp] = elem);
                        }
                    }
                }
            } else {
                matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut);
                if (postFinder) {
                    postFinder(null, results, matcherOut, xml);
                } else {
                    push.apply(results, matcherOut);
                }
            }
        });
    }
    function matcherFromTokens(tokens) {
        var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i1 = leadingRelative ? 1 : 0, matchContext = addCombinator(function(elem) {
            return elem === checkContext;
        }, implicitRelative, true), matchAnyContext = addCombinator(function(elem) {
            return indexOf(checkContext, elem) > -1;
        }, implicitRelative, true), matchers = [
            function(elem, context, xml) {
                var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
                checkContext = null;
                return ret;
            }
        ];
        for(; i1 < len; i1++){
            if (matcher = Expr.relative[tokens[i1].type]) {
                matchers = [
                    addCombinator(elementMatcher(matchers), matcher)
                ];
            } else {
                matcher = Expr.filter[tokens[i1].type].apply(null, tokens[i1].matches);
                if (matcher[expando]) {
                    j = ++i1;
                    for(; j < len; j++){
                        if (Expr.relative[tokens[j].type]) {
                            break;
                        }
                    }
                    return setMatcher(i1 > 1 && elementMatcher(matchers), i1 > 1 && toSelector(tokens.slice(0, i1 - 1).concat({
                        value: tokens[i1 - 2].type === " " ? "*" : ""
                    })).replace(rtrim, "$1"), matcher, i1 < j && matcherFromTokens(tokens.slice(i1, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
                }
                matchers.push(matcher);
            }
        }
        return elementMatcher(matchers);
    }
    function matcherFromGroupMatchers(elementMatchers, setMatchers) {
        var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed, context, xml, results, outermost) {
            var elem, j, matcher, matchedCount = 0, i1 = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find["TAG"]("*", outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length;
            if (outermost) {
                outermostContext = context == document1 || context || outermost;
            }
            for(; i1 !== len && (elem = elems[i1]) != null; i1++){
                if (byElement && elem) {
                    j = 0;
                    if (!context && elem.ownerDocument != document1) {
                        setDocument(elem);
                        xml = !documentIsHTML;
                    }
                    while(matcher = elementMatchers[j++]){
                        if (matcher(elem, context || document1, xml)) {
                            results.push(elem);
                            break;
                        }
                    }
                    if (outermost) {
                        dirruns = dirrunsUnique;
                    }
                }
                if (bySet) {
                    if (elem = !matcher && elem) {
                        matchedCount--;
                    }
                    if (seed) {
                        unmatched.push(elem);
                    }
                }
            }
            matchedCount += i1;
            if (bySet && i1 !== matchedCount) {
                j = 0;
                while(matcher = setMatchers[j++]){
                    matcher(unmatched, setMatched, context, xml);
                }
                if (seed) {
                    if (matchedCount > 0) {
                        while(i1--){
                            if (!(unmatched[i1] || setMatched[i1])) {
                                setMatched[i1] = pop.call(results);
                            }
                        }
                    }
                    setMatched = condense(setMatched);
                }
                push.apply(results, setMatched);
                if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) {
                    Sizzle.uniqueSort(results);
                }
            }
            if (outermost) {
                dirruns = dirrunsUnique;
                outermostContext = contextBackup;
            }
            return unmatched;
        };
        return bySet ? markFunction(superMatcher) : superMatcher;
    }
    compile = Sizzle.compile = function(selector, match) {
        var i1, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + " "];
        if (!cached) {
            if (!match) {
                match = tokenize(selector);
            }
            i1 = match.length;
            while(i1--){
                cached = matcherFromTokens(match[i1]);
                if (cached[expando]) {
                    setMatchers.push(cached);
                } else {
                    elementMatchers.push(cached);
                }
            }
            cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
            cached.selector = selector;
        }
        return cached;
    };
    select = Sizzle.select = function(selector, context, results, seed) {
        var i1, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize(selector = compiled.selector || selector);
        results = results || [];
        if (match.length === 1) {
            tokens = match[0] = match[0].slice(0);
            if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) {
                context = (Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [])[0];
                if (!context) {
                    return results;
                } else if (compiled) {
                    context = context.parentNode;
                }
                selector = selector.slice(tokens.shift().value.length);
            }
            i1 = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
            while(i1--){
                token = tokens[i1];
                if (Expr.relative[type = token.type]) {
                    break;
                }
                if (find = Expr.find[type]) {
                    if (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context)) {
                        tokens.splice(i1, 1);
                        selector = seed.length && toSelector(tokens);
                        if (!selector) {
                            push.apply(results, seed);
                            return results;
                        }
                        break;
                    }
                }
            }
        }
        (compiled || compile(selector, match))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context);
        return results;
    };
    support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
    support.detectDuplicates = !!hasDuplicate;
    setDocument();
    support.sortDetached = assert(function(el) {
        return el.compareDocumentPosition(document1.createElement("fieldset")) & 1;
    });
    if (!assert(function(el) {
        el.innerHTML = "<a href='#'></a>";
        return el.firstChild.getAttribute("href") === "#";
    })) {
        addHandle("type|href|height|width", function(elem, name, isXML) {
            if (!isXML) {
                return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
            }
        });
    }
    if (!support.attributes || !assert(function(el) {
        el.innerHTML = "<input/>";
        el.firstChild.setAttribute("value", "");
        return el.firstChild.getAttribute("value") === "";
    })) {
        addHandle("value", function(elem, _name, isXML) {
            if (!isXML && elem.nodeName.toLowerCase() === "input") {
                return elem.defaultValue;
            }
        });
    }
    if (!assert(function(el) {
        return el.getAttribute("disabled") == null;
    })) {
        addHandle(booleans, function(elem, name, isXML) {
            var val;
            if (!isXML) {
                return elem[name] === true ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
            }
        });
    }
    var _sizzle = window1.Sizzle;
    Sizzle.noConflict = function() {
        if (window1.Sizzle === Sizzle) {
            window1.Sizzle = _sizzle;
        }
        return Sizzle;
    };
    if (typeof define === "function" && define.amd) {
        define(function() {
            return Sizzle;
        });
    } else if (typeof module !== "undefined" && module.exports) {
        module.exports = Sizzle;
    } else {
        window1.Sizzle = Sizzle;
    }
}
const __default3 = (document1)=>{
    const sizzleWindow = {
        document: document1
    };
    SetupSizzle(sizzleWindow);
    const { Sizzle } = sizzleWindow;
    return {
        first (selectors, context) {
            return Sizzle(selectors, context)[0] ?? null;
        },
        select (selectors, context) {
            return Sizzle(selectors, context);
        },
        match (selectors, context) {
            return Sizzle.matchesSelector(context, selectors);
        }
    };
};
let codeGenerationAllowed = null;
function getSelectorEngine() {
    if (codeGenerationAllowed === null) {
        try {
            new Function("");
            codeGenerationAllowed = true;
        } catch (e) {
            codeGenerationAllowed = false;
        }
    }
    if (codeGenerationAllowed) {
        return __default2;
    } else {
        return __default3;
    }
}
class DOMTokenList {
    #_value = "";
    get #value() {
        return this.#_value;
    }
    set #value(value) {
        this.#_value = value;
        this.#onChange(value);
    }
    #set = new Set();
    #onChange;
    constructor(onChange, key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor");
        }
        this.#onChange = onChange;
    }
    static #invalidToken(token) {
        return token === "" || /[\t\n\f\r ]/.test(token);
    }
    #setIndices() {
        const classes = Array.from(this.#set);
        for(let i1 = 0; i1 < classes.length; i1++){
            this[i1] = classes[i1];
        }
    }
    set value(input) {
        this.#value = input;
        this.#set = new Set(input.trim().split(/[\t\n\f\r\s]+/g).filter(Boolean));
        this.#setIndices();
    }
    get value() {
        return this.#_value;
    }
    get length() {
        return this.#set.size;
    }
    *entries() {
        const array = Array.from(this.#set);
        for(let i1 = 0; i1 < array.length; i1++){
            yield [
                i1,
                array[i1]
            ];
        }
    }
    *values() {
        yield* this.#set.values();
    }
    *keys() {
        for(let i1 = 0; i1 < this.#set.size; i1++){
            yield i1;
        }
    }
    *[Symbol.iterator]() {
        yield* this.#set.values();
    }
    item(index) {
        index = Number(index);
        if (Number.isNaN(index) || index === Infinity) index = 0;
        return this[Math.trunc(index) % 2 ** 32] ?? null;
    }
    contains(element) {
        return this.#set.has(element);
    }
    add(...elements) {
        for (const element of elements){
            if (DOMTokenList.#invalidToken(element)) {
                throw new DOMException("Failed to execute 'add' on 'DOMTokenList': The token provided must not be empty.");
            }
            const { size } = this.#set;
            this.#set.add(element);
            if (size < this.#set.size) {
                this[size] = element;
            }
        }
        this.#updateClassString();
    }
    remove(...elements) {
        const { size } = this.#set;
        for (const element of elements){
            if (DOMTokenList.#invalidToken(element)) {
                throw new DOMException("Failed to execute 'remove' on 'DOMTokenList': The token provided must not be empty.");
            }
            this.#set.delete(element);
        }
        if (size !== this.#set.size) {
            for(let i1 = this.#set.size; i1 < size; i1++){
                delete this[i1];
            }
            this.#setIndices();
        }
        this.#updateClassString();
    }
    replace(oldToken, newToken) {
        if ([
            oldToken,
            newToken
        ].some((v)=>DOMTokenList.#invalidToken(v))) {
            throw new DOMException("Failed to execute 'replace' on 'DOMTokenList': The token provided must not be empty.");
        }
        if (!this.#set.has(oldToken)) {
            return false;
        }
        if (this.#set.has(newToken)) {
            this.remove(oldToken);
        } else {
            this.#set.delete(oldToken);
            this.#set.add(newToken);
            this.#setIndices();
            this.#updateClassString();
        }
        return true;
    }
    supports() {
        throw new Error("Not implemented");
    }
    toggle(element, force) {
        if (force !== undefined) {
            const operation = force ? "add" : "remove";
            this[operation](element);
            return false;
        } else {
            const contains = this.contains(element);
            const operation = contains ? "remove" : "add";
            this[operation](element);
            return !contains;
        }
    }
    forEach(callback) {
        for (const [i1, value] of this.entries()){
            callback(value, i1, this);
        }
    }
    #updateClassString() {
        this.#value = Array.from(this.#set).join(" ");
    }
}
const setNamedNodeMapOwnerElementSym = Symbol();
const setAttrValueSym = Symbol();
class Attr extends Node {
    #namedNodeMap = null;
    #name = "";
    #value = "";
    #ownerElement = null;
    constructor(map, name, value, key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor");
        }
        super(name, NodeType.ATTRIBUTE_NODE, null, CTOR_KEY);
        this.#name = name;
        this.#value = value;
        this.#namedNodeMap = map;
    }
    [setNamedNodeMapOwnerElementSym](ownerElement) {
        this.#ownerElement = ownerElement;
        this.#namedNodeMap = ownerElement?.attributes ?? null;
        if (ownerElement) {
            this._setOwnerDocument(ownerElement.ownerDocument);
        }
    }
    [setAttrValueSym](value) {
        this.#value = value;
    }
    _shallowClone() {
        const newAttr = new Attr(null, this.#name, this.#value, CTOR_KEY);
        newAttr._setOwnerDocument(this.ownerDocument);
        return newAttr;
    }
    cloneNode() {
        return super.cloneNode();
    }
    appendChild() {
        throw new DOMException("Cannot add children to an Attribute");
    }
    replaceChild() {
        throw new DOMException("Cannot add children to an Attribute");
    }
    insertBefore() {
        throw new DOMException("Cannot add children to an Attribute");
    }
    removeChild() {
        throw new DOMException("The node to be removed is not a child of this node");
    }
    get name() {
        return this.#name;
    }
    get localName() {
        return this.#name;
    }
    get value() {
        return this.#value;
    }
    set value(value) {
        this.#value = String(value);
        if (this.#namedNodeMap) {
            this.#namedNodeMap[setNamedNodeMapValueSym](this.#name, this.#value, true);
        }
    }
    get ownerElement() {
        return this.#ownerElement ?? null;
    }
    get specified() {
        return true;
    }
    get prefix() {
        return null;
    }
}
const setNamedNodeMapValueSym = Symbol();
const getNamedNodeMapValueSym = Symbol();
const getNamedNodeMapAttrNamesSym = Symbol();
const getNamedNodeMapAttrNodeSym = Symbol();
const removeNamedNodeMapAttrSym = Symbol();
class NamedNodeMap {
    static #indexedAttrAccess = function(map, index) {
        if (index + 1 > this.length) {
            return undefined;
        }
        const attribute = Object.keys(map).filter((attribute)=>map[attribute] !== undefined)[index];
        return this[getNamedNodeMapAttrNodeSym](attribute);
    };
    #onAttrNodeChange;
    constructor(ownerElement, onAttrNodeChange, key){
        if (key !== CTOR_KEY) {
            throw new TypeError("Illegal constructor.");
        }
        this.#ownerElement = ownerElement;
        this.#onAttrNodeChange = onAttrNodeChange;
    }
    #attrNodeCache = {};
    #map = {};
    #length = 0;
    #capacity = 0;
    #ownerElement = null;
    [getNamedNodeMapAttrNodeSym](attribute) {
        let attrNode = this.#attrNodeCache[attribute];
        if (!attrNode) {
            attrNode = this.#attrNodeCache[attribute] = new Attr(this, attribute, this.#map[attribute], CTOR_KEY);
            attrNode[setNamedNodeMapOwnerElementSym](this.#ownerElement);
        }
        return attrNode;
    }
    [getNamedNodeMapAttrNamesSym]() {
        const names = [];
        for (const [name, value] of Object.entries(this.#map)){
            if (value !== undefined) {
                names.push(name);
            }
        }
        return names;
    }
    [getNamedNodeMapValueSym](attribute) {
        return this.#map[attribute];
    }
    [setNamedNodeMapValueSym](attribute, value, bubble = false) {
        if (this.#map[attribute] === undefined) {
            this.#length++;
            if (this.#length > this.#capacity) {
                this.#capacity = this.#length;
                const index = this.#capacity - 1;
                Object.defineProperty(this, String(this.#capacity - 1), {
                    get: NamedNodeMap.#indexedAttrAccess.bind(this, this.#map, index)
                });
            }
        } else if (this.#attrNodeCache[attribute]) {
            this.#attrNodeCache[attribute][setAttrValueSym](value);
        }
        this.#map[attribute] = value;
        if (bubble) {
            this.#onAttrNodeChange(attribute, value);
        }
    }
    [removeNamedNodeMapAttrSym](attribute) {
        if (this.#map[attribute] !== undefined) {
            this.#length--;
            this.#map[attribute] = undefined;
            this.#onAttrNodeChange(attribute, null);
            const attrNode = this.#attrNodeCache[attribute];
            if (attrNode) {
                attrNode[setNamedNodeMapOwnerElementSym](null);
                this.#attrNodeCache[attribute] = undefined;
            }
        }
    }
    *[Symbol.iterator]() {
        for(let i1 = 0; i1 < this.length; i1++){
            yield this[i1];
        }
    }
    get length() {
        return this.#length;
    }
    item(index) {
        if (index >= this.#length) {
            return null;
        }
        return this[index];
    }
    getNamedItem(attribute) {
        if (this.#map[attribute] !== undefined) {
            return this[getNamedNodeMapAttrNodeSym](attribute);
        }
        return null;
    }
    setNamedItem(attrNode) {
        if (attrNode.ownerElement) {
            throw new DOMException("Attribute already in use");
        }
        const previousAttr = this.#attrNodeCache[attrNode.name];
        if (previousAttr) {
            previousAttr[setNamedNodeMapOwnerElementSym](null);
            this.#map[attrNode.name] = undefined;
        }
        attrNode[setNamedNodeMapOwnerElementSym](this.#ownerElement);
        this.#attrNodeCache[attrNode.name] = attrNode;
        this[setNamedNodeMapValueSym](attrNode.name, attrNode.value, true);
    }
    removeNamedItem(attribute) {
        if (this.#map[attribute] !== undefined) {
            const attrNode = this[getNamedNodeMapAttrNodeSym](attribute);
            this[removeNamedNodeMapAttrSym](attribute);
            return attrNode;
        }
        throw new DOMException("Node was not found");
    }
}
class Element1 extends Node {
    tagName;
    localName;
    attributes;
    #currentId;
    #classList;
    constructor(tagName, parentNode, attributes, key){
        super(tagName, NodeType.ELEMENT_NODE, parentNode, key);
        this.tagName = tagName;
        this.attributes = new NamedNodeMap(this, (attribute, value)=>{
            if (value === null) {
                value = "";
            }
            switch(attribute){
                case "class":
                    this.#classList.value = value;
                    break;
                case "id":
                    this.#currentId = value;
                    break;
            }
        }, CTOR_KEY);
        this.#currentId = "";
        this.#classList = new DOMTokenList((className)=>{
            if (this.hasAttribute("class") || className !== "") {
                this.attributes[setNamedNodeMapValueSym]("class", className);
            }
        }, CTOR_KEY);
        for (const attr of attributes){
            this.setAttribute(attr[0], attr[1]);
            switch(attr[0]){
                case "class":
                    this.#classList.value = attr[1];
                    break;
                case "id":
                    this.#currentId = attr[1];
                    break;
            }
        }
        this.tagName = this.nodeName = tagName.toUpperCase();
        this.localName = tagName.toLowerCase();
    }
    _shallowClone() {
        const attributes = [];
        for (const attribute of this.getAttributeNames()){
            attributes.push([
                attribute,
                this.getAttribute(attribute)
            ]);
        }
        return new Element1(this.nodeName, null, attributes, CTOR_KEY);
    }
    get childElementCount() {
        return this._getChildNodesMutator().elementsView().length;
    }
    get className() {
        return this.getAttribute("class") ?? "";
    }
    set className(className) {
        this.setAttribute("class", className);
        this.#classList.value = className;
    }
    get classList() {
        return this.#classList;
    }
    get outerHTML() {
        const tagName = this.tagName.toLowerCase();
        let out = "<" + tagName;
        out += getElementAttributesString(this);
        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() {
        return getInnerHtmlFromNodes(this.childNodes, this.tagName);
    }
    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 this.attributes[getNamedNodeMapAttrNamesSym]();
    }
    getAttribute(name) {
        return this.attributes[getNamedNodeMapValueSym](name.toLowerCase()) ?? null;
    }
    setAttribute(rawName, value) {
        const name = String(rawName?.toLowerCase());
        const strValue = String(value);
        this.attributes[setNamedNodeMapValueSym](name, strValue);
        if (name === "id") {
            this.#currentId = strValue;
        } else if (name === "class") {
            this.#classList.value = strValue;
        }
    }
    removeAttribute(rawName) {
        const name = String(rawName?.toLowerCase());
        this.attributes[removeNamedNodeMapAttrSym](name);
        if (name === "class") {
            this.#classList.value = "";
        }
    }
    hasAttribute(name) {
        return this.attributes[getNamedNodeMapValueSym](String(name?.toLowerCase())) !== undefined;
    }
    hasAttributeNS(_namespace, name) {
        return this.attributes[getNamedNodeMapValueSym](String(name?.toLowerCase())) !== undefined;
    }
    replaceWith(...nodes) {
        this._replaceWith(...nodes);
    }
    remove() {
        this._remove();
    }
    append(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.push(...nodesAndTextNodes(nodes, this));
    }
    prepend(...nodes) {
        const mutator = this._getChildNodesMutator();
        mutator.splice(0, 0, ...nodesAndTextNodes(nodes, this));
    }
    before(...nodes) {
        if (this.parentNode) {
            insertBeforeAfter(this, nodes, true);
        }
    }
    after(...nodes) {
        if (this.parentNode) {
            insertBeforeAfter(this, nodes, false);
        }
    }
    get firstElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[0] ?? null;
    }
    get lastElementChild() {
        const elements = this._getChildNodesMutator().elementsView();
        return elements[elements.length - 1] ?? null;
    }
    get nextElementSibling() {
        const parent = this.parentNode;
        if (!parent) {
            return null;
        }
        const mutator = parent._getChildNodesMutator();
        const index = mutator.indexOfElementsView(this);
        const elements = mutator.elementsView();
        return elements[index + 1] ?? null;
    }
    get previousElementSibling() {
        const parent = this.parentNode;
        if (!parent) {
            return null;
        }
        const mutator = parent._getChildNodesMutator();
        const index = mutator.indexOfElementsView(this);
        const elements = mutator.elementsView();
        return elements[index - 1] ?? null;
    }
    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) {
        const fixCaseTagName = tagName.toUpperCase();
        if (fixCaseTagName === "*") {
            return this._getElementsByTagNameWildcard([]);
        } else {
            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 getElementsByClassName(this, className, []);
    }
    getElementsByTagNameNS(_namespace, localName) {
        return this.getElementsByTagName(localName);
    }
}
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 Element1("html", doc, [], CTOR_KEY);
        html._setOwnerDocument(doc);
        const head = new Element1("head", html, [], CTOR_KEY);
        const body = new Element1("body", html, [], CTOR_KEY);
        const title = new Element1("title", head, [], CTOR_KEY);
        const titleText = new Text(titleStr);
        title.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(parse3(html));
    const node = nodeFromArray(parsed, null);
    return node;
}
class HTMLTemplateElement extends Element1 {
    __contentIsSet = false;
    #content = null;
    constructor(parentNode, attributes, key, content){
        super("TEMPLATE", parentNode, attributes, key);
        this.#content = content;
        this.__contentIsSet = true;
    }
    get content() {
        return this.#content;
    }
    _setOwnerDocument(document1) {
        super._setOwnerDocument(document1);
        if (this.__contentIsSet) {
            this.content._setOwnerDocument(document1);
        }
    }
    _shallowClone() {
        const frag = new DocumentFragment1();
        const attributes = this.getAttributeNames().map((name)=>[
                name,
                this.getAttribute(name)
            ]);
        return new HTMLTemplateElement(null, attributes, CTOR_KEY, frag);
    }
    cloneNode(deep = false) {
        const newNode = super.cloneNode(deep);
        if (deep) {
            const destContent = newNode.content;
            for (const child of this.content.childNodes){
                destContent.appendChild(child.cloneNode(deep));
            }
        }
        return newNode;
    }
    get innerHTML() {
        return getInnerHtmlFromNodes(this.content.childNodes, "template");
    }
    set innerHTML(html) {
        const content = this.content;
        for (const child of content.childNodes){
            child._setParent(null);
        }
        const mutator = content._getChildNodesMutator();
        mutator.splice(0, content.childNodes.length);
        if (html.length) {
            const parsed = fragmentNodesFromString(html);
            mutator.push(...parsed.childNodes[0].childNodes);
            for (const child of content.childNodes){
                child._setParent(content);
                child._setOwnerDocument(content.ownerDocument);
            }
        }
    }
    get outerHTML() {
        return `<template${getElementAttributesString(this)}>${this.innerHTML}</template>`;
    }
}
class DocumentType extends Node {
    #qualifiedName = "";
    #publicId = "";
    #systemId = "";
    constructor(name, publicId, systemId, key){
        super("html", NodeType.DOCUMENT_TYPE_NODE, null, key);
        this.#qualifiedName = name;
        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 = null;
    constructor(){
        super("#document", NodeType.DOCUMENT_NODE, null, CTOR_KEY);
        this.implementation = new DOMImplementation(CTOR_KEY);
    }
    _shallowClone() {
        return new Document1();
    }
    get _nwapi() {
        return this.#nwapi || (this.#nwapi = getSelectorEngine()(this));
    }
    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();
        switch(tagName){
            case "TEMPLATE":
                {
                    const frag = new DocumentFragment1();
                    const elm = new HTMLTemplateElement(null, [], CTOR_KEY, frag);
                    elm._setOwnerDocument(this);
                    return elm;
                }
            default:
                {
                    const elm = new Element1(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(data) {
        return new Text(data);
    }
    createComment(data) {
        return new Comment(data);
    }
    createDocumentFragment() {
        const fragment = new DocumentFragment1();
        fragment._setOwnerDocument(this);
        return fragment;
    }
    importNode(node, deep = false) {
        const copy = node.cloneNode(deep);
        copy._setOwnerDocument(this);
        return copy;
    }
    adoptNode(node) {
        if (node instanceof Document1) {
            throw new DOMException("Adopting a Document node is not supported.", "NotSupportedError");
        }
        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 getElementsByClassName(this, className, []);
    }
    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);
    }
}
__default1.Document = Document1;
__default1.Element = Element1;
function fragmentNodesFromString(html) {
    const parsed = JSON.parse(parseFrag(html));
    const node = nodeFromArray(parsed, null);
    return node;
}
function nodeFromArray(data, parentNode) {
    if (data[1] === "template") {
        const content = nodeFromArray(data[3], null);
        const contentFrag = new DocumentFragment1();
        const fragMutator = contentFrag._getChildNodesMutator();
        for (const child of content.childNodes){
            fragMutator.push(child);
            child._setParent(contentFrag);
        }
        return new HTMLTemplateElement(parentNode, data[2], CTOR_KEY, contentFrag);
    }
    const elm = new Element1(data[1], parentNode, data[2], CTOR_KEY);
    const childNodes = elm._getChildNodesMutator();
    let childNode;
    for (const child of data.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.insertBefore(docType, doc.childNodes[0]);
            }
        }
        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);
        }
    },
    configurable: true
});
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);
        }
    },
    configurable: true
});
async function initParser() {
    await init();
    register(parse2, parse_frag);
}
async function getDomParser() {
    await initDenoDom();
    return new DOMParser();
}
async function parseHtml(src) {
    await initDenoDom();
    const result1 = new DOMParser().parseFromString(src, "text/html");
    if (!result1) {
        throw new Error("Couldn't parse string into HTML");
    }
    return result1;
}
async function writeDomToHtmlFile(doc, path, doctype) {
    if (doc.documentElement === null) {
        throw new Error("Document has no root element");
    }
    const output = doctype ? doctype + "\n" + doc.documentElement.outerHTML : doc.documentElement.outerHTML;
    await Deno.writeTextFile(path, output);
}
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: [
                            "buffer",
                            "usize",
                            "buffer"
                        ],
                        result: "void"
                    },
                    deno_dom_parse_frag_sync: {
                        parameters: [
                            "buffer",
                            "usize",
                            "buffer"
                        ],
                        result: "void"
                    },
                    deno_dom_is_big_endian: {
                        parameters: [],
                        result: "u32"
                    },
                    deno_dom_copy_buf: {
                        parameters: [
                            "buffer",
                            "buffer"
                        ],
                        result: "void"
                    }
                };
                const symbols = _symbols;
                const dylib = Deno.dlopen(denoNativePluginPath, symbols);
                const utf8Encoder = new TextEncoder();
                const utf8Decoder = new TextDecoder();
                const usizeBytes = Number(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 parse = (html)=>{
                    return genericParse(dylibParseSync, html);
                };
                const parseFrag = (html)=>{
                    return genericParse(dylibParseFragSync, html);
                };
                debug("Loaded deno-dom-native");
                register(parse, parseFrag);
                s_DenoDomInitialized = true;
                return;
            }
        } catch (e) {
            debug("Error loading deno-dom-native: " + e.message);
        }
    }
    if (!s_DenoDomInitialized) {
        await initParser();
        s_DenoDomInitialized = true;
    }
}
function appendLogOptions(cmd) {
    const addLogOptions = (cmd)=>{
        return cmd.option("--log <file>", "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
        });
    };
    const subCommands = cmd.getCommands();
    if (subCommands.length > 0) {
        subCommands.forEach((command)=>{
            addLogOptions(command);
        });
        return cmd;
    } else {
        return addLogOptions(cmd);
    }
}
function logOptions(args) {
    const logOptions = {};
    logOptions.log = args.l || args.log || Deno.env.get("QUARTO_LOG");
    if (logOptions.log) {
        ensureDirSync(dirname2(logOptions.log));
    }
    logOptions.level = args.ll || args["log-level"] || Deno.env.get("QUARTO_LOG_LEVEL");
    logOptions.quiet = args.q || args.quiet;
    logOptions.format = parseFormat(args.lf || args["log-format"] || Deno.env.get("QUARTO_LOG_FORMAT"));
    return logOptions;
}
let currentLogLevel = "INFO";
function logLevel() {
    return currentLogLevel;
}
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.WARN) {
            msg = `${logRecord.levelName}: ${msg}`;
        }
        switch(logRecord.level){
            case LogLevels.INFO:
            case LogLevels.DEBUG:
                msg = applyMsgOptions(msg, options);
                break;
            case LogLevels.WARN:
                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 })=>`${msg}`
        });
    }
    handle(logRecord) {
        if (this.level > logRecord.level) return;
        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.WARN) {
                return `(${logRecord.levelName}) ${msg}`;
            } else {
                return msg;
            }
        } else {
            return JSON.stringify(logRecord, undefined, 0) + "\n";
        }
    }
    async log(msg) {
        if (msg !== "") {
            msg = stripColor(msg);
            if (!this._file) {
                throw new Error("Internal error: logging file not open");
            }
            let buf = this._encoder.encode(msg);
            let total = 0;
            while(total < buf.length){
                const offset = this._file.writeSync(buf);
                total += offset;
                buf = buf.subarray(offset);
            }
            Deno.fsyncSync(this._file.rid);
        }
    }
}
async function initializeLogger(logOptions) {
    const handlers = {};
    const defaultHandlers = [];
    const file = logOptions.log;
    currentLogLevel = logOptions.level ? parseLevel(logOptions.level) : "INFO";
    handlers["events"] = new LogEventsHandler(logLevel());
    defaultHandlers.push("events");
    if (!logOptions.quiet) {
        handlers["console"] = new StdErrOutputHandler(logLevel(), {
            formatter: ({ msg })=>`${msg}`
        });
        defaultHandlers.push("console");
    }
    if (file) {
        handlers["file"] = new LogFileHandler(logLevel(), {
            filename: file,
            mode: "w",
            format: logOptions.format
        });
        defaultHandlers.push("file");
    }
    await setup({
        handlers,
        loggers: {
            default: {
                level: "DEBUG",
                handlers: defaultHandlers
            }
        }
    });
    onCleanup(cleanupLogger);
}
async function cleanupLogger() {
    const logger = getLogger();
    for (const handler of logger.handlers){
        await handler.destroy();
    }
    logger.handlers = [];
}
function logProgress(message) {
    info(bold(blue(message)));
}
function logError(e, defaultShowStack = true) {
    const err = asErrorEx(e, defaultShowStack);
    let message = err.printName ? `${err.name}: ${err.message}` : err.message;
    if (e instanceof InternalError) {
        message = message + `\n\nThis is a bug in quarto. We apologize for the inconvenience.
Please consider reporting it at https://github.com/quarto-dev/quarto-cli. Thank you!`;
    }
    const isDebug = getenv("QUARTO_DEBUG", "false") === "true" || getenv("QUARTO_PRINT_STACK", "false") === "true";
    if (err.stack && (isDebug || err.printStack)) {
        if (!message) {
            message = err.stack;
        } else {
            message = message + "\n\nStack trace:\n" + err.stack.split("\n").slice(1).join("\n");
        }
    }
    if (message) {
        error(message);
    }
}
function warnOnce(msg) {
    if (!warnings[msg]) {
        warnings[msg] = true;
        warn(msg);
    }
}
const warnings = {};
function debugOnce(msg) {
    if (!debugs[msg]) {
        debugs[msg] = true;
        debug(msg);
    }
}
const debugs = {};
function applyMsgOptions(msg, options) {
    if (options.indent) {
        const pad = " ".repeat(options.indent);
        msg = lines(msg).map((msg)=>pad + msg).join("\n");
    }
    if (options.bold) {
        msg = bold(msg);
    }
    if (options.dim) {
        msg = dim(msg);
    }
    if (options.format) {
        msg = options.format(msg);
    }
    return msg;
}
function parseFormat(format) {
    if (format) {
        format = format.toLowerCase();
        switch(format){
            case "plain":
            case "json-stream":
                return format;
            default:
                return "plain";
        }
    } else {
        return "plain";
    }
}
function parseLevel(level) {
    const lvl = levelMap[level.toLowerCase()];
    if (lvl) {
        return lvl;
    } else {
        return "WARN";
    }
}
const levelMap = {
    debug: "DEBUG",
    info: "INFO",
    warning: "WARN",
    error: "ERROR"
};
const RE_KeyValue = /^\s*(?:export\s+)?(?<key>[a-zA-Z_]+[a-zA-Z0-9_]*?)\s*=[\ \t]*('\n?(?<notInterpolated>(.|\n)*?)\n?'|"\n?(?<interpolated>(.|\n)*?)\n?"|(?<unquoted>[^\n#]*)) *#*.*$/gm;
const RE_ExpandValue = /(\${(?<inBrackets>.+?)(\:-(?<inBracketsDefault>.+))?}|(?<!\\)\$(?<notInBrackets>\w+)(\:-(?<notInBracketsDefault>.+))?)/g;
function expandCharacters(str) {
    const charactersMap = {
        "\\n": "\n",
        "\\r": "\r",
        "\\t": "\t"
    };
    return str.replace(/\\([nrt])/g, ($1)=>charactersMap[$1] || "");
}
function expand(str, variablesMap) {
    if (RE_ExpandValue.test(str)) {
        return expand(str.replace(RE_ExpandValue, function(...params) {
            const { inBrackets, inBracketsDefault, notInBrackets, notInBracketsDefault } = params[params.length - 1];
            const expandValue = inBrackets || notInBrackets;
            const defaultValue = inBracketsDefault || notInBracketsDefault;
            let value = variablesMap[expandValue];
            if (value === undefined) {
                value = Deno.env.get(expandValue);
            }
            return value === undefined ? expand(defaultValue, variablesMap) : value;
        }), variablesMap);
    } else {
        return str;
    }
}
function parse4(rawDotenv) {
    const env = {};
    let match;
    const keysForExpandCheck = [];
    while((match = RE_KeyValue.exec(rawDotenv)) !== null){
        const { key, interpolated, notInterpolated, unquoted } = match?.groups;
        if (unquoted) {
            keysForExpandCheck.push(key);
        }
        env[key] = typeof notInterpolated === "string" ? notInterpolated : typeof interpolated === "string" ? expandCharacters(interpolated) : unquoted.trim();
    }
    const variablesMap = {
        ...env
    };
    keysForExpandCheck.forEach((key)=>{
        env[key] = expand(env[key], variablesMap);
    });
    return env;
}
function stringify1(object) {
    const lines = [];
    for (const [key, value] of Object.entries(object)){
        let quote;
        let escapedValue = value ?? "";
        if (key.startsWith("#")) {
            console.warn(`key starts with a '#' indicates a comment and is ignored: '${key}'`);
            continue;
        } else if (escapedValue.includes("\n")) {
            escapedValue = escapedValue.replaceAll("\n", "\\n");
            quote = `"`;
        } else if (escapedValue.match(/\W/)) {
            quote = "'";
        }
        if (quote) {
            escapedValue = escapedValue.replaceAll(quote, `\\${quote}`);
            escapedValue = `${quote}${escapedValue}${quote}`;
        }
        const line = `${key}=${escapedValue}`;
        lines.push(line);
    }
    return lines.join("\n");
}
async function load3({ envPath = ".env", examplePath = ".env.example", defaultsPath = ".env.defaults", export: _export = false, allowEmptyValues = false } = {}) {
    const conf = envPath ? await parseFile(envPath) : {};
    if (defaultsPath) {
        const confDefaults = await parseFile(defaultsPath);
        for (const [key, value] of Object.entries(confDefaults)){
            if (!(key in conf)) {
                conf[key] = value;
            }
        }
    }
    if (examplePath) {
        const confExample = await parseFile(examplePath);
        assertSafe(conf, confExample, allowEmptyValues);
    }
    if (_export) {
        for (const [key, value] of Object.entries(conf)){
            if (Deno.env.get(key) !== undefined) continue;
            Deno.env.set(key, value);
        }
    }
    return conf;
}
async function parseFile(filepath) {
    try {
        return parse4(await Deno.readTextFile(filepath));
    } catch (e) {
        if (e instanceof Deno.errors.NotFound) return {};
        throw e;
    }
}
function assertSafe(conf, confExample, allowEmptyValues) {
    const missingEnvVars = [];
    for(const key in confExample){
        if (key in conf) {
            if (!allowEmptyValues && conf[key] === "") {
                missingEnvVars.push(key);
            }
        } else if (Deno.env.get(key) !== undefined) {
            if (!allowEmptyValues && Deno.env.get(key) === "") {
                missingEnvVars.push(key);
            }
        } else {
            missingEnvVars.push(key);
        }
    }
    if (missingEnvVars.length > 0) {
        const errorMessages = [
            `The following variables were defined in the example file but are not present in the environment:\n  ${missingEnvVars.join(", ")}`,
            `Make sure to add them to your env file.`,
            !allowEmptyValues && `If you expect any of these variables to be empty, you can set the allowEmptyValues option to true.`
        ];
        throw new MissingEnvVarsError(errorMessages.filter(Boolean).join("\n\n"), missingEnvVars);
    }
}
class MissingEnvVarsError extends Error {
    missing;
    constructor(message, missing){
        super(message);
        this.name = "MissingEnvVarsError";
        this.missing = missing;
        Object.setPrototypeOf(this, new.target.prototype);
    }
}
const kQuartoProfile = "QUARTO_PROFILE";
function activeProfiles() {
    return readProfile(Deno.env.get(kQuartoProfile));
}
function readProfile(profile) {
    if (profile) {
        return profile.split(/[ ,]+/);
    } else {
        return [];
    }
}
function setProfileFromArg(args) {
    if (args.profile) {
        Deno.env.set(kQuartoProfile, args.profile);
        return true;
    } else {
        return false;
    }
}
function appendProfileArg(cmd) {
    return cmd.option("--profile", "Active project profile(s)", {
        global: true
    });
}
let tempDir;
let tempContext;
function initSessionTempDir() {
    const tmpEnv = Deno.env.get("TMPDIR");
    if (tmpEnv) {
        try {
            if (!existsSync(tmpEnv)) {
                ensureDirSync(tmpEnv);
            }
        } catch (err) {
            if (err.message) {
                debug("Error attempting to create TMPDIR: " + err.message);
            }
        }
    }
    tempDir = Deno.makeTempDirSync({
        prefix: "quarto-session"
    });
}
function cleanupSessionTempDir() {
    if (tempContext) {
        tempContext.cleanup();
        tempContext = undefined;
    }
    if (tempDir) {
        removeIfExists(tempDir);
        tempDir = undefined;
    }
}
function globalTempContext() {
    if (tempContext === undefined) {
        tempContext = createTempContext();
    }
    return tempContext;
}
function createTempContext(options) {
    let dir = Deno.makeTempDirSync({
        ...options,
        dir: tempDir
    });
    return {
        baseDir: dir,
        createFile: (options)=>{
            return Deno.makeTempFileSync({
                ...options,
                dir
            });
        },
        createDir: (options)=>{
            return Deno.makeTempDirSync({
                ...options,
                dir
            });
        },
        cleanup: ()=>{
            if (dir) {
                safeRemoveIfExists(dir);
                dir = undefined;
            }
        }
    };
}
const kQuartoEnv = "_environment";
const kQuartoEnvLocal = `${kQuartoEnv}.local`;
const kQuartoEnvRequired = `${kQuartoEnv}.required`;
async function dotenvQuartoProfile(projectDir) {
    const conf = await load3({
        defaultsPath: join2(projectDir, kQuartoEnv),
        envPath: join2(projectDir, kQuartoEnvLocal)
    });
    return conf[kQuartoProfile];
}
const dotenvVariablesSet = [];
let prevDotenvVariablesDefined;
async function dotenvSetVariables(projectDir) {
    dotenvVariablesSet.forEach(Deno.env.delete);
    dotenvVariablesSet.splice(0, dotenvVariablesSet.length);
    const dotenvFiles = [
        join2(projectDir, kQuartoEnv),
        ...activeProfiles().reverse().map((profile)=>join2(projectDir, `_environment-${profile}`)),
        join2(projectDir, kQuartoEnvLocal)
    ].filter(safeExistsSync).reverse();
    const dotenvVariablesDefined = {};
    for (const dotenvFile of dotenvFiles){
        const conf = await load3({
            envPath: dotenvFile
        });
        for(const key in conf){
            if (Deno.env.get(key) === undefined) {
                Deno.env.set(key, conf[key]);
                dotenvVariablesSet.push(key);
            }
            if (dotenvVariablesDefined[key] === undefined) {
                dotenvVariablesDefined[key] = conf[key];
            }
        }
    }
    const dotenvRequired = join2(projectDir, kQuartoEnvRequired);
    if (existsSync(dotenvRequired)) {
        const definedEnvTempPath = globalTempContext().createFile({
            suffix: ".yml"
        });
        Deno.writeTextFileSync(definedEnvTempPath, stringify1(dotenvVariablesDefined));
        await load3({
            envPath: definedEnvTempPath,
            examplePath: dotenvRequired,
            allowEmptyValues: true
        });
    }
    if (prevDotenvVariablesDefined && !__VIRTUAL_FILE211(dotenvVariablesDefined, prevDotenvVariablesDefined)) {
        fireDotenvChanged();
    }
    prevDotenvVariablesDefined = dotenvVariablesDefined;
    return dotenvFiles;
}
const listeners = new Array();
function fireDotenvChanged() {
    listeners.forEach((listener)=>listener());
}
function onDotenvChanged(listener) {
    listeners.push(listener);
}
const kQuartoProfileConfig = "profile";
let baseQuartoProfile;
async function initializeProfileConfig(dir, config, schema) {
    const firstRun = baseQuartoProfile === undefined;
    if (firstRun) {
        baseQuartoProfile = Deno.env.get(kQuartoProfile) || "";
    }
    const profileConfig = __VIRTUAL_FILE18(config[kQuartoProfileConfig]) ? config[kQuartoProfileConfig] : undefined;
    delete config[kQuartoProfileConfig];
    let quartoProfile = baseQuartoProfile || await dotenvQuartoProfile(dir) || await localConfigQuartoProfile(dir, schema) || "";
    if (!quartoProfile) {
        if (Array.isArray(profileConfig?.default)) {
            quartoProfile = profileConfig.default.map((value)=>String(value)).join(",");
        } else if (typeof profileConfig?.default === "string") {
            quartoProfile = profileConfig.default;
        }
    }
    const active = readProfile(quartoProfile);
    if (active.length === 0) {
        if (Deno.env.get("RSTUDIO_PRODUCT") === "CONNECT") {
            active.push("connect");
        }
    }
    const groups = readProfileGroups(profileConfig);
    for (const group of groups){
        if (!group.some((name)=>active.includes(name))) {
            active.push(group[0]);
        }
    }
    const updatedQuartoProfile = active.join(",");
    if (!firstRun) {
        if (Deno.env.get(kQuartoProfile) !== updatedQuartoProfile) {
            fireActiveProfileChanged(updatedQuartoProfile);
        }
    }
    Deno.env.set(kQuartoProfile, active.join(","));
    return await mergeProfiles(dir, config, schema);
}
const listeners1 = new Array();
function fireActiveProfileChanged(profile) {
    listeners1.forEach((listener)=>listener(profile));
}
function onActiveProfileChanged(listener) {
    listeners1.push(listener);
}
async function localConfigQuartoProfile(dir, schema) {
    const localConfigPath = localProjectConfigFile(dir);
    if (localConfigPath) {
        const yaml = await readAndValidateYamlFromFile(localConfigPath, schema, `Validation of configuration profile file ${basename2(localConfigPath)} failed.`, "{}");
        const profile = yaml[kQuartoProfileConfig];
        if (Array.isArray(profile?.default)) {
            return profile?.default.join(",");
        } else if (typeof profile?.default === "string") {
            return profile?.default;
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
async function mergeProfiles(dir, config, schema) {
    const files = [];
    const mergeProfile = async (profilePath)=>{
        try {
            const yaml = await readAndValidateYamlFromFile(profilePath, schema, `Validation of configuration profile file ${basename2(profilePath)} failed.`, "{}");
            config = mergeProjectMetadata(config, yaml);
            files.push(profilePath);
        } catch (e) {
            error("\nError reading configuration profile file from " + basename2(profilePath) + "\n");
            throw e;
        }
    };
    for (const profileName of activeProfiles().reverse()){
        const profilePath = [
            ".yml",
            ".yaml"
        ].map((ext)=>join2(dir, `_quarto-${profileName}${ext}`)).find(safeExistsSync);
        if (profilePath) {
            await mergeProfile(profilePath);
        }
    }
    const localConfigPath = localProjectConfigFile(dir);
    if (localConfigPath) {
        await mergeProfile(localConfigPath);
    }
    return {
        config,
        files
    };
}
function localProjectConfigFile(dir) {
    return [
        ".yml",
        ".yaml"
    ].map((ext)=>join2(dir, `_quarto${ext}.local`)).find(safeExistsSync);
}
function readProfileGroups(profileConfig) {
    const groups = [];
    const configGroup = profileConfig?.group;
    if (Array.isArray(configGroup)) {
        if (configGroup.every((value)=>typeof value === "string")) {
            groups.push(configGroup);
        } else if (configGroup.every(Array.isArray)) {
            groups.push(...configGroup);
        }
    }
    return groups;
}
function buildQuartoPreviewJs(srcDir, denoDir, force) {
    const args = [
        "run",
        "-A",
        "build.ts"
    ];
    if (force) {
        args.push("--force");
    }
    const buildCmd = new Deno.Command(Deno.execPath(), {
        args: args,
        cwd: quartoPreviewJsDir(srcDir),
        env: denoDir ? {
            DENO_DIR: denoDir
        } : undefined,
        stderr: "inherit",
        stdout: "inherit"
    });
    return buildCmd.outputSync();
}
function quartoPreviewJsDir(srcDir) {
    return join2(srcDir, "webui", "quarto-preview");
}
const kLocalDevelopment = "99.9.9";
let dotenvConfig;
const quartoConfig = {
    binPath: ()=>getenv("QUARTO_BIN_PATH"),
    toolsPath: ()=>join2(getenv("QUARTO_BIN_PATH"), "tools"),
    sharePath: ()=>getenv("QUARTO_SHARE_PATH"),
    isDebug: ()=>getenv("QUARTO_DEBUG", "false") === "true",
    version: ()=>{
        const forceVersion = getenv("QUARTO_FORCE_VERSION", "");
        if (forceVersion !== "") {
            return forceVersion;
        }
        const versionPath = join2(getenv("QUARTO_SHARE_PATH"), "version");
        if (existsSync(versionPath)) {
            return Deno.readTextFileSync(versionPath);
        } else {
            return kLocalDevelopment;
        }
    },
    cliPath: ()=>{
        const binPath = quartoConfig.binPath();
        if (Deno.build.os !== "windows") {
            return join2(binPath, "quarto");
        }
        const cliPath = join2(binPath, "quarto.exe");
        if (safeExistsSync(cliPath)) {
            return cliPath;
        }
        return join2(binPath, "quarto.cmd");
    },
    dotenv: async (forceReload)=>{
        if (forceReload || !dotenvConfig) {
            const options = {
                defaultsPath: join2(quartoConfig.sharePath(), "env", "env.defaults"),
                envPath: quartoConfig.isDebug() ? join2(quartoConfig.sharePath(), "..", "..", ".env") : null,
                examplePath: null
            };
            dotenvConfig = await load3(options);
        }
        return dotenvConfig;
    }
};
function previewEnsureResources(cleanup) {
    if (quartoConfig.isDebug()) {
        buildPreviewJs(quartoSrcDir(), cleanup);
    }
}
function previewMonitorResources(cleanup) {
    onActiveProfileChanged(()=>{
        terminatePreview("active profile changed", cleanup);
    });
    onDotenvChanged(()=>{
        terminatePreview("environment variables changed", cleanup);
    });
    if (quartoConfig.isDebug()) {
        const srcDir = quartoSrcDir();
        const watcher = Deno.watchFs([
            srcDir
        ], {
            recursive: true
        });
        const watchForChanges = async ()=>{
            for await (const event of watcher){
                if (event.paths.some((path)=>extname2(path).toLowerCase().startsWith(".ts"))) {
                    terminatePreview("quarto src code changed", cleanup);
                }
            }
        };
        watchForChanges();
    }
}
function terminatePreview(reason, cleanup) {
    info(bold(blue(`\n${reason}: preview terminating\n`)));
    if (cleanup) {
        cleanup();
    }
    exitWithCleanup(1);
}
function quartoSrcDir() {
    return normalizePath(join2(quartoConfig.binPath(), "../../../src"));
}
function buildPreviewJs(srcDir, cleanup) {
    const output = buildQuartoPreviewJs(srcDir);
    if (!output.success) {
        terminatePreview("Error building quarto-preview.js", cleanup);
    }
}
const kHKeyCurrentUser = "HKCU";
const kHKeyLocalMachine = "HKLM";
async function registryReadString(root, key, value) {
    if (Array.isArray(root)) {
        for (const r of root){
            const val = await registryReadString(r, key, value);
            if (val !== undefined) {
                return val;
            }
        }
        return undefined;
    }
    const kTypeString = "REG_SZ";
    const cmd = [
        "reg",
        "query",
        `${root}\\${key}`,
        "/v",
        value
    ];
    let result1;
    try {
        result1 = await execProcess({
            cmd,
            stdout: "piped",
            stderr: "null"
        });
    } catch (e) {
        debugOnce(`Fail to read from registry: ${e}`);
        return undefined;
    }
    if (result1.success && result1.stdout) {
        const typePos = result1.stdout?.indexOf(kTypeString);
        if (typePos !== -1) {
            return result1.stdout.substring(typePos + kTypeString.length).trim();
        }
    }
    return undefined;
}
function resourcePath(resource) {
    const sharePath = quartoConfig.sharePath();
    if (resource) {
        return join2(sharePath, resource);
    } else {
        return sharePath;
    }
}
function formatResourcePath(format, resource) {
    return join2(resourcePath("formats"), format, resource);
}
function architectureToolsPath(binary) {
    const arch = Deno.build.arch;
    const archBinaryPath = join2(arch, binary);
    return toolsPath(binary, archBinaryPath);
}
function toolsPath(binary, defaultPath) {
    const displayWarning = ()=>{
        warnOnce(`Specified ${binaryEnvKey} does not exist, using built in ${binary}`);
    };
    const binaryEnvKey = `QUARTO_${binary.toUpperCase()}`;
    const binaryPath = Deno.env.get(binaryEnvKey);
    if (binaryPath) {
        if (!existsSync(binaryPath)) {
            if (Deno.build.os === "windows") {
                const exeExists = !binary.endsWith(".exe") || [
                    binary + ".exe"
                ].some((path)=>{
                    return existsSync(path);
                });
                if (!exeExists) {
                    displayWarning();
                }
            } else {
                displayWarning();
            }
        } else {
            if (Deno.statSync(binaryPath).isFile) {
                return binaryPath;
            } else {
                const fullPath = join2(binaryPath, binary);
                if (!existsSync(fullPath)) {
                    displayWarning();
                } else {
                    return fullPath;
                }
            }
        }
    }
    return join2(quartoConfig.toolsPath(), defaultPath || binary);
}
function pandocBinaryPath() {
    return Deno.build.os === "windows" ? toolsPath("pandoc") : architectureToolsPath("pandoc");
}
async function rBinaryPath(binary) {
    debug(`-- Searching for R binary --`);
    const quartoR = Deno.env.get("QUARTO_R");
    debug(`Looking for '${binary}' in QUARTO_R: ${quartoR}`);
    if (quartoR) {
        if (existsSync(quartoR)) {
            const rBinDir = Deno.statSync(quartoR).isDirectory ? quartoR : dirname2(quartoR);
            debug(`Found in ${rBinDir}`);
            return join2(rBinDir, binary);
        } else {
            warnOnce(`Specified QUARTO_R '${quartoR}' does not exist.`);
        }
    }
    const rHome = Deno.env.get("R_HOME");
    debug(`Looking for '${binary}' in R_HOME: ${rHome}`);
    if (rHome) {
        let rHomeBin = join2(rHome, "bin", binary);
        if (safeExistsSync(rHomeBin)) {
            debug(`Found in ${rHomeBin}`);
            return rHomeBin;
        }
        if (Deno.build.os === "windows") {
            rHomeBin = join2(rHome, "bin", "x64", binary);
            if (safeExistsSync(rHomeBin)) {
                debug(`Found in ${rHomeBin}`);
                return rHomeBin;
            }
        }
    }
    debug(`Looking for '${binary}' in PATH.`);
    const path = await which(binary);
    if (path) {
        debug(`Found in PATH at ${path}`);
        return path;
    }
    if (Deno.build.os === "windows") {
        debug(`Looking for '${binary}' in Windows Registry.`);
        const version = await registryReadString([
            kHKeyCurrentUser,
            kHKeyLocalMachine
        ], "Software\\R-core\\R", "Current Version");
        if (version) {
            const installPath = await registryReadString([
                kHKeyCurrentUser,
                kHKeyLocalMachine
            ], `Software\\R-core\\R\\${version}`, "InstallPath");
            if (installPath) {
                debug(`Found in Windows Registry at ${join2(installPath, "bin")}`);
                return join2(installPath, "bin", binary);
            }
        }
        debug(`Looking for '${binary}' in Windows PROGRAMFILES.`);
        const progFiles = Deno.env.get("programfiles");
        if (progFiles) {
            for (const entry of Deno.readDirSync(progFiles)){
                if (entry.isDirectory && entry.name === "R") {
                    for (const walk of walkSync(join2(progFiles, "R"))){
                        if (walk.isDirectory && walk.name === "bin") {
                            debug(`Found ${walk.path}`);
                            return join2(walk.path, binary);
                        }
                    }
                }
            }
        }
    }
    debug(`Quarto did no found ${binary} and will try to use it directly.`);
    return binary;
}
function projectTypeResourcePath(projectType) {
    return resourcePath(join2("projects", projectType));
}
const kDarkSuffix = "dark";
const kLightSuffix = "light";
function textHighlightThemePath(theme, style) {
    const names = [
        `${theme}-${style === "dark" ? kDarkSuffix : kLightSuffix}`,
        theme
    ];
    const themePath = names.map((name)=>{
        return resourcePath(join2("pandoc", "highlight-styles", `${name}.theme`));
    }).find((path)=>existsSync(path));
    return themePath;
}
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;
}
function isServerShiny(format) {
    const server = format?.metadata[kServer];
    return server?.["type"] === "shiny";
}
function isServerShinyPython(format, engine) {
    return isServerShiny(format) && engine === kJupyterEngine;
}
function isServerShinyKnitr(format, engine) {
    return isServerShiny(format) && engine === kKnitrEngine;
}
function formatOutputFile(format) {
    let outputFile = format.pandoc[kOutputFile];
    if (outputFile) {
        if (format.render[kOutputExt]) {
            const existingExtension = extname2(outputFile);
            if (!existingExtension || existingExtension.substring(1) !== format.render[kOutputExt]) {
                outputFile = `${outputFile}.${format.render[kOutputExt]}`;
            }
        }
    }
    return outputFile;
}
function pandocAttrParseText(attr) {
    attr = attr.trim();
    let id = "";
    const classes = [];
    let remainder = "";
    let current = "";
    const resolveCurrent = ()=>{
        const resolve = current;
        current = "";
        if (resolve.length === 0) {
            return true;
        } else if (resolve.startsWith("#")) {
            if (id.length === 0 && resolve.length > 1) {
                id = resolve.substr(1);
                return true;
            } else {
                return false;
            }
        } else if (resolve.startsWith(".")) {
            if (resolve.length > 1) {
                classes.push(resolve.substr(1));
                return true;
            } else {
                return false;
            }
        } else if (resolve === "-") {
            classes.push("unnumbered");
            return true;
        } else {
            remainder = resolve;
            return true;
        }
    };
    for(let i1 = 0; i1 < attr.length; i1++){
        let inQuotes = false;
        const ch = attr[i1];
        inQuotes = ch === '"' ? !inQuotes : inQuotes;
        if (ch !== " " && !inQuotes) {
            current += ch;
        } else if (resolveCurrent()) {
            if (remainder.length > 0) {
                remainder = remainder + attr.substr(i1);
                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 i1 = 0; i1 < text.length; i1++){
            let ch = text.charAt(i1);
            if (ch === '"') {
                inQuotes = !inQuotes;
            } else if (ch === " " && !inQuotes) {
                ch = "\n";
            }
            convertedText += ch;
        }
        text = convertedText;
    }
    const lines = text.trim().split("\n");
    return lines.map((line)=>{
        const parts = line.trim().split("=");
        return [
            parts[0],
            (parts[1] || "").replace(/^"/, "").replace(/"$/, "")
        ];
    });
}
const kPandocTitleRegex = /^\#{1,}\s(?:(.*)\s)?\{(.*)\}$/;
const kRemoveHeadingRegex = /^#{1,}\s*/;
function parsePandocTitle(title) {
    title = title ? title.trim() : title;
    const match = title.match(kPandocTitleRegex);
    if (match) {
        const titleRaw = match[1];
        const attrRaw = match[2];
        const parsed = pandocAttrParseText(attrRaw);
        if (parsed) {
            return {
                heading: titleRaw,
                attr: parsed
            };
        } else {
            return {
                heading: titleRaw
            };
        }
    } else {
        return {
            heading: title.replace(kRemoveHeadingRegex, "").trim()
        };
    }
}
function partitionMarkdown(markdown) {
    const partitioned = partitionYamlFrontMatter(markdown);
    markdown = partitioned ? partitioned.markdown : markdown;
    const { lines, headingText, headingAttr } = markdownWithExtractedHeading(markdown);
    const containsRefs = lines.some((line)=>/^:::\s*{#refs([\s}]|.*?})\s*$/.test(line));
    return {
        yaml: partitioned ? readYamlFromMarkdown(partitioned.yaml) : undefined,
        headingText,
        headingAttr,
        containsRefs,
        markdown: lines.join("\n"),
        srcMarkdownNoYaml: partitioned?.markdown || ""
    };
}
function markdownWithExtractedHeading(markdown) {
    const mdLines = [];
    let headingText;
    let headingAttr;
    let contentBeforeHeading = false;
    for (const line of lines(markdown)){
        if (!headingText) {
            if (line.match(/^\#{1,}\s/)) {
                const parsedHeading = parsePandocTitle(line);
                headingText = parsedHeading.heading;
                headingAttr = parsedHeading.attr;
                contentBeforeHeading = mdLines.length !== 0;
            } else if (line.match(/^=+\s*$/) || line.match(/^-+\s*$/)) {
                const prevLine = mdLines[mdLines.length - 1];
                if (prevLine) {
                    headingText = prevLine;
                    mdLines.splice(mdLines.length - 1);
                    contentBeforeHeading = mdLines.length !== 0;
                } else {
                    mdLines.push(line);
                }
            } else {
                mdLines.push(line);
            }
        } else {
            mdLines.push(line);
        }
    }
    return {
        lines: mdLines,
        headingText,
        headingAttr,
        contentBeforeHeading
    };
}
const MAX_SAFE_COMPONENT_LENGTH = 16;
const re = [];
const src = [];
let R = 0;
const NUMERICIDENTIFIER = R++;
src[NUMERICIDENTIFIER] = "0|[1-9]\\d*";
const NUMERICIDENTIFIERLOOSE = R++;
src[NUMERICIDENTIFIERLOOSE] = "[0-9]+";
const NONNUMERICIDENTIFIER = R++;
src[NONNUMERICIDENTIFIER] = "\\d*[a-zA-Z-][a-zA-Z0-9-]*";
const MAINVERSION = R++;
const nid = src[NUMERICIDENTIFIER];
src[MAINVERSION] = `(${nid})\\.(${nid})\\.(${nid})`;
const MAINVERSIONLOOSE = R++;
const nidl = src[NUMERICIDENTIFIERLOOSE];
src[MAINVERSIONLOOSE] = `(${nidl})\\.(${nidl})\\.(${nidl})`;
const PRERELEASEIDENTIFIER = R++;
src[PRERELEASEIDENTIFIER] = "(?:" + src[NUMERICIDENTIFIER] + "|" + src[NONNUMERICIDENTIFIER] + ")";
const PRERELEASEIDENTIFIERLOOSE = R++;
src[PRERELEASEIDENTIFIERLOOSE] = "(?:" + src[NUMERICIDENTIFIERLOOSE] + "|" + src[NONNUMERICIDENTIFIER] + ")";
const PRERELEASE = R++;
src[PRERELEASE] = "(?:-(" + src[PRERELEASEIDENTIFIER] + "(?:\\." + src[PRERELEASEIDENTIFIER] + ")*))";
const PRERELEASELOOSE = R++;
src[PRERELEASELOOSE] = "(?:-?(" + src[PRERELEASEIDENTIFIERLOOSE] + "(?:\\." + src[PRERELEASEIDENTIFIERLOOSE] + ")*))";
const BUILDIDENTIFIER = R++;
src[BUILDIDENTIFIER] = "[0-9A-Za-z-]+";
const BUILD = R++;
src[BUILD] = "(?:\\+(" + src[BUILDIDENTIFIER] + "(?:\\." + src[BUILDIDENTIFIER] + ")*))";
const FULL = R++;
const FULLPLAIN = "v?" + src[MAINVERSION] + src[PRERELEASE] + "?" + src[BUILD] + "?";
src[FULL] = "^" + FULLPLAIN + "$";
const LOOSEPLAIN = "[v=\\s]*" + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + "?" + src[BUILD] + "?";
const LOOSE = R++;
src[LOOSE] = "^" + LOOSEPLAIN + "$";
const GTLT = R++;
src[GTLT] = "((?:<|>)?=?)";
const XRANGEIDENTIFIERLOOSE = R++;
src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + "|x|X|\\*";
const XRANGEIDENTIFIER = R++;
src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + "|x|X|\\*";
const XRANGEPLAIN = R++;
src[XRANGEPLAIN] = "[v=\\s]*(" + src[XRANGEIDENTIFIER] + ")" + "(?:\\.(" + src[XRANGEIDENTIFIER] + ")" + "(?:\\.(" + src[XRANGEIDENTIFIER] + ")" + "(?:" + src[PRERELEASE] + ")?" + src[BUILD] + "?" + ")?)?";
const XRANGEPLAINLOOSE = R++;
src[XRANGEPLAINLOOSE] = "[v=\\s]*(" + src[XRANGEIDENTIFIERLOOSE] + ")" + "(?:\\.(" + src[XRANGEIDENTIFIERLOOSE] + ")" + "(?:\\.(" + src[XRANGEIDENTIFIERLOOSE] + ")" + "(?:" + src[PRERELEASELOOSE] + ")?" + src[BUILD] + "?" + ")?)?";
const XRANGE = R++;
src[XRANGE] = "^" + src[GTLT] + "\\s*" + src[XRANGEPLAIN] + "$";
const XRANGELOOSE = R++;
src[XRANGELOOSE] = "^" + src[GTLT] + "\\s*" + src[XRANGEPLAINLOOSE] + "$";
const COERCE = R++;
src[COERCE] = "(?:^|[^\\d])" + "(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "})" + "(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?" + "(?:\\.(\\d{1," + MAX_SAFE_COMPONENT_LENGTH + "}))?" + "(?:$|[^\\d])";
const LONETILDE = R++;
src[LONETILDE] = "(?:~>?)";
const TILDETRIM = R++;
src[TILDETRIM] = "(\\s*)" + src[LONETILDE] + "\\s+";
re[TILDETRIM] = new RegExp(src[TILDETRIM], "g");
const tildeTrimReplace = "$1~";
const TILDE = R++;
src[TILDE] = "^" + src[LONETILDE] + src[XRANGEPLAIN] + "$";
const TILDELOOSE = R++;
src[TILDELOOSE] = "^" + src[LONETILDE] + src[XRANGEPLAINLOOSE] + "$";
const LONECARET = R++;
src[LONECARET] = "(?:\\^)";
const CARETTRIM = R++;
src[CARETTRIM] = "(\\s*)" + src[LONECARET] + "\\s+";
re[CARETTRIM] = new RegExp(src[CARETTRIM], "g");
const caretTrimReplace = "$1^";
const CARET = R++;
src[CARET] = "^" + src[LONECARET] + src[XRANGEPLAIN] + "$";
const CARETLOOSE = R++;
src[CARETLOOSE] = "^" + src[LONECARET] + src[XRANGEPLAINLOOSE] + "$";
const COMPARATORLOOSE = R++;
src[COMPARATORLOOSE] = "^" + src[GTLT] + "\\s*(" + LOOSEPLAIN + ")$|^$";
const COMPARATOR = R++;
src[COMPARATOR] = "^" + src[GTLT] + "\\s*(" + FULLPLAIN + ")$|^$";
const COMPARATORTRIM = R++;
src[COMPARATORTRIM] = "(\\s*)" + src[GTLT] + "\\s*(" + LOOSEPLAIN + "|" + src[XRANGEPLAIN] + ")";
re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], "g");
const comparatorTrimReplace = "$1$2$3";
const HYPHENRANGE = R++;
src[HYPHENRANGE] = "^\\s*(" + src[XRANGEPLAIN] + ")" + "\\s+-\\s+" + "(" + src[XRANGEPLAIN] + ")" + "\\s*$";
const HYPHENRANGELOOSE = R++;
src[HYPHENRANGELOOSE] = "^\\s*(" + src[XRANGEPLAINLOOSE] + ")" + "\\s+-\\s+" + "(" + src[XRANGEPLAINLOOSE] + ")" + "\\s*$";
const STAR = R++;
src[STAR] = "(<|>)?=?\\s*\\*";
for(let i1 = 0; i1 < R; i1++){
    if (!re[i1]) {
        re[i1] = new RegExp(src[i1]);
    }
}
function parse5(version, optionsOrLoose) {
    if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
        optionsOrLoose = {
            loose: !!optionsOrLoose,
            includePrerelease: false
        };
    }
    if (version instanceof SemVer) {
        return version;
    }
    if (typeof version !== "string") {
        return null;
    }
    if (version.length > 256) {
        return null;
    }
    const r = optionsOrLoose.loose ? re[LOOSE] : re[FULL];
    if (!r.test(version)) {
        return null;
    }
    try {
        return new SemVer(version, optionsOrLoose);
    } catch (er) {
        return null;
    }
}
class SemVer {
    raw;
    loose;
    options;
    major;
    minor;
    patch;
    version;
    build;
    prerelease;
    constructor(version, optionsOrLoose){
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
            optionsOrLoose = {
                loose: !!optionsOrLoose,
                includePrerelease: false
            };
        }
        if (version instanceof SemVer) {
            if (version.loose === optionsOrLoose.loose) {
                return version;
            } else {
                version = version.version;
            }
        } else if (typeof version !== "string") {
            throw new TypeError("Invalid Version: " + version);
        }
        if (version.length > 256) {
            throw new TypeError("version is longer than " + 256 + " characters");
        }
        if (!(this instanceof SemVer)) {
            return new SemVer(version, optionsOrLoose);
        }
        this.options = optionsOrLoose;
        this.loose = !!optionsOrLoose.loose;
        const m = version.trim().match(optionsOrLoose.loose ? re[LOOSE] : re[FULL]);
        if (!m) {
            throw new TypeError("Invalid Version: " + version);
        }
        this.raw = version;
        this.major = +m[1];
        this.minor = +m[2];
        this.patch = +m[3];
        if (this.major > Number.MAX_SAFE_INTEGER || this.major < 0) {
            throw new TypeError("Invalid major version");
        }
        if (this.minor > Number.MAX_SAFE_INTEGER || this.minor < 0) {
            throw new TypeError("Invalid minor version");
        }
        if (this.patch > Number.MAX_SAFE_INTEGER || this.patch < 0) {
            throw new TypeError("Invalid patch version");
        }
        if (!m[4]) {
            this.prerelease = [];
        } else {
            this.prerelease = m[4].split(".").map((id)=>{
                if (/^[0-9]+$/.test(id)) {
                    const num = +id;
                    if (num >= 0 && num < Number.MAX_SAFE_INTEGER) {
                        return num;
                    }
                }
                return id;
            });
        }
        this.build = m[5] ? m[5].split(".") : [];
        this.format();
    }
    format() {
        this.version = this.major + "." + this.minor + "." + this.patch;
        if (this.prerelease.length) {
            this.version += "-" + this.prerelease.join(".");
        }
        return this.version;
    }
    compare(other) {
        if (!(other instanceof SemVer)) {
            other = new SemVer(other, this.options);
        }
        return this.compareMain(other) || this.comparePre(other);
    }
    compareMain(other) {
        if (!(other instanceof SemVer)) {
            other = new SemVer(other, this.options);
        }
        return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
    }
    comparePre(other) {
        if (!(other instanceof SemVer)) {
            other = new SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
            return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
            return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
            return 0;
        }
        let i1 = 0;
        do {
            const a = this.prerelease[i1];
            const b = other.prerelease[i1];
            if (a === undefined && b === undefined) {
                return 0;
            } else if (b === undefined) {
                return 1;
            } else if (a === undefined) {
                return -1;
            } else if (a === b) {
                continue;
            } else {
                return compareIdentifiers(a, b);
            }
        }while (++i1)
        return 1;
    }
    compareBuild(other) {
        if (!(other instanceof SemVer)) {
            other = new SemVer(other, this.options);
        }
        let i1 = 0;
        do {
            const a = this.build[i1];
            const b = other.build[i1];
            if (a === undefined && b === undefined) {
                return 0;
            } else if (b === undefined) {
                return 1;
            } else if (a === undefined) {
                return -1;
            } else if (a === b) {
                continue;
            } else {
                return compareIdentifiers(a, b);
            }
        }while (++i1)
        return 1;
    }
    inc(release, identifier) {
        switch(release){
            case "premajor":
                this.prerelease.length = 0;
                this.patch = 0;
                this.minor = 0;
                this.major++;
                this.inc("pre", identifier);
                break;
            case "preminor":
                this.prerelease.length = 0;
                this.patch = 0;
                this.minor++;
                this.inc("pre", identifier);
                break;
            case "prepatch":
                this.prerelease.length = 0;
                this.inc("patch", identifier);
                this.inc("pre", identifier);
                break;
            case "prerelease":
                if (this.prerelease.length === 0) {
                    this.inc("patch", identifier);
                }
                this.inc("pre", identifier);
                break;
            case "major":
                if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
                    this.major++;
                }
                this.minor = 0;
                this.patch = 0;
                this.prerelease = [];
                break;
            case "minor":
                if (this.patch !== 0 || this.prerelease.length === 0) {
                    this.minor++;
                }
                this.patch = 0;
                this.prerelease = [];
                break;
            case "patch":
                if (this.prerelease.length === 0) {
                    this.patch++;
                }
                this.prerelease = [];
                break;
            case "pre":
                if (this.prerelease.length === 0) {
                    this.prerelease = [
                        0
                    ];
                } else {
                    let i1 = this.prerelease.length;
                    while(--i1 >= 0){
                        if (typeof this.prerelease[i1] === "number") {
                            this.prerelease[i1]++;
                            i1 = -2;
                        }
                    }
                    if (i1 === -1) {
                        this.prerelease.push(0);
                    }
                }
                if (identifier) {
                    if (this.prerelease[0] === identifier) {
                        if (isNaN(this.prerelease[1])) {
                            this.prerelease = [
                                identifier,
                                0
                            ];
                        }
                    } else {
                        this.prerelease = [
                            identifier,
                            0
                        ];
                    }
                }
                break;
            default:
                throw new Error("invalid increment argument: " + release);
        }
        this.format();
        this.raw = this.version;
        return this;
    }
    toString() {
        return this.version;
    }
}
const numeric = /^[0-9]+$/;
function compareIdentifiers(a, b) {
    const anum = numeric.test(a);
    const bnum = numeric.test(b);
    if (a === null || b === null) throw "Comparison against null invalid";
    if (anum && bnum) {
        a = +a;
        b = +b;
    }
    return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
}
function compare(v1, v2, optionsOrLoose) {
    return new SemVer(v1, optionsOrLoose).compare(new SemVer(v2, optionsOrLoose));
}
function gt(v1, v2, optionsOrLoose) {
    return compare(v1, v2, optionsOrLoose) > 0;
}
function lt(v1, v2, optionsOrLoose) {
    return compare(v1, v2, optionsOrLoose) < 0;
}
function eq1(v1, v2, optionsOrLoose) {
    return compare(v1, v2, optionsOrLoose) === 0;
}
function neq(v1, v2, optionsOrLoose) {
    return compare(v1, v2, optionsOrLoose) !== 0;
}
function gte(v1, v2, optionsOrLoose) {
    return compare(v1, v2, optionsOrLoose) >= 0;
}
function lte(v1, v2, optionsOrLoose) {
    return compare(v1, v2, optionsOrLoose) <= 0;
}
function cmp(v1, operator, v2, optionsOrLoose) {
    switch(operator){
        case "===":
            if (typeof v1 === "object") v1 = v1.version;
            if (typeof v2 === "object") v2 = v2.version;
            return v1 === v2;
        case "!==":
            if (typeof v1 === "object") v1 = v1.version;
            if (typeof v2 === "object") v2 = v2.version;
            return v1 !== v2;
        case "":
        case "=":
        case "==":
            return eq1(v1, v2, optionsOrLoose);
        case "!=":
            return neq(v1, v2, optionsOrLoose);
        case ">":
            return gt(v1, v2, optionsOrLoose);
        case ">=":
            return gte(v1, v2, optionsOrLoose);
        case "<":
            return lt(v1, v2, optionsOrLoose);
        case "<=":
            return lte(v1, v2, optionsOrLoose);
        default:
            throw new TypeError("Invalid operator: " + operator);
    }
}
const ANY = {};
class Comparator {
    semver;
    operator;
    value;
    loose;
    options;
    constructor(comp, optionsOrLoose){
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
            optionsOrLoose = {
                loose: !!optionsOrLoose,
                includePrerelease: false
            };
        }
        if (comp instanceof Comparator) {
            if (comp.loose === !!optionsOrLoose.loose) {
                return comp;
            } else {
                comp = comp.value;
            }
        }
        if (!(this instanceof Comparator)) {
            return new Comparator(comp, optionsOrLoose);
        }
        this.options = optionsOrLoose;
        this.loose = !!optionsOrLoose.loose;
        this.parse(comp);
        if (this.semver === ANY) {
            this.value = "";
        } else {
            this.value = this.operator + this.semver.version;
        }
    }
    parse(comp) {
        const r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
        const m = comp.match(r);
        if (!m) {
            throw new TypeError("Invalid comparator: " + comp);
        }
        const m1 = m[1];
        this.operator = m1 !== undefined ? m1 : "";
        if (this.operator === "=") {
            this.operator = "";
        }
        if (!m[2]) {
            this.semver = ANY;
        } else {
            this.semver = new SemVer(m[2], this.options.loose);
        }
    }
    test(version) {
        if (this.semver === ANY || version === ANY) {
            return true;
        }
        if (typeof version === "string") {
            version = new SemVer(version, this.options);
        }
        return cmp(version, this.operator, this.semver, this.options);
    }
    intersects(comp, optionsOrLoose) {
        if (!(comp instanceof Comparator)) {
            throw new TypeError("a Comparator is required");
        }
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
            optionsOrLoose = {
                loose: !!optionsOrLoose,
                includePrerelease: false
            };
        }
        let rangeTmp;
        if (this.operator === "") {
            if (this.value === "") {
                return true;
            }
            rangeTmp = new Range(comp.value, optionsOrLoose);
            return satisfies(this.value, rangeTmp, optionsOrLoose);
        } else if (comp.operator === "") {
            if (comp.value === "") {
                return true;
            }
            rangeTmp = new Range(this.value, optionsOrLoose);
            return satisfies(comp.semver, rangeTmp, optionsOrLoose);
        }
        const sameDirectionIncreasing = (this.operator === ">=" || this.operator === ">") && (comp.operator === ">=" || comp.operator === ">");
        const sameDirectionDecreasing = (this.operator === "<=" || this.operator === "<") && (comp.operator === "<=" || comp.operator === "<");
        const sameSemVer = this.semver.version === comp.semver.version;
        const differentDirectionsInclusive = (this.operator === ">=" || this.operator === "<=") && (comp.operator === ">=" || comp.operator === "<=");
        const oppositeDirectionsLessThan = cmp(this.semver, "<", comp.semver, optionsOrLoose) && (this.operator === ">=" || this.operator === ">") && (comp.operator === "<=" || comp.operator === "<");
        const oppositeDirectionsGreaterThan = cmp(this.semver, ">", comp.semver, optionsOrLoose) && (this.operator === "<=" || this.operator === "<") && (comp.operator === ">=" || comp.operator === ">");
        return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
    }
    toString() {
        return this.value;
    }
}
class Range {
    range;
    raw;
    loose;
    options;
    includePrerelease;
    set;
    constructor(range, optionsOrLoose){
        if (!optionsOrLoose || typeof optionsOrLoose !== "object") {
            optionsOrLoose = {
                loose: !!optionsOrLoose,
                includePrerelease: false
            };
        }
        if (range instanceof Range) {
            if (range.loose === !!optionsOrLoose.loose && range.includePrerelease === !!optionsOrLoose.includePrerelease) {
                return range;
            } else {
                return new Range(range.raw, optionsOrLoose);
            }
        }
        if (range instanceof Comparator) {
            return new Range(range.value, optionsOrLoose);
        }
        if (!(this instanceof Range)) {
            return new Range(range, optionsOrLoose);
        }
        this.options = optionsOrLoose;
        this.loose = !!optionsOrLoose.loose;
        this.includePrerelease = !!optionsOrLoose.includePrerelease;
        this.raw = range;
        this.set = range.split(/\s*\|\|\s*/).map((range)=>this.parseRange(range.trim())).filter((c)=>{
            return c.length;
        });
        if (!this.set.length) {
            throw new TypeError("Invalid SemVer Range: " + range);
        }
        this.format();
    }
    format() {
        this.range = this.set.map((comps)=>comps.join(" ").trim()).join("||").trim();
        return this.range;
    }
    parseRange(range) {
        const loose = this.options.loose;
        range = range.trim();
        const hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
        range = range.replace(hr, hyphenReplace);
        range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
        range = range.replace(re[TILDETRIM], tildeTrimReplace);
        range = range.replace(re[CARETTRIM], caretTrimReplace);
        range = range.split(/\s+/).join(" ");
        const compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
        let set = range.split(" ").map((comp)=>parseComparator(comp, this.options)).join(" ").split(/\s+/);
        if (this.options.loose) {
            set = set.filter((comp)=>{
                return !!comp.match(compRe);
            });
        }
        return set.map((comp)=>new Comparator(comp, this.options));
    }
    test(version) {
        if (typeof version === "string") {
            version = new SemVer(version, this.options);
        }
        for(var i1 = 0; i1 < this.set.length; i1++){
            if (testSet(this.set[i1], version, this.options)) {
                return true;
            }
        }
        return false;
    }
    intersects(range, optionsOrLoose) {
        if (!(range instanceof Range)) {
            throw new TypeError("a Range is required");
        }
        return this.set.some((thisComparators)=>{
            return isSatisfiable(thisComparators, optionsOrLoose) && range.set.some((rangeComparators)=>{
                return isSatisfiable(rangeComparators, optionsOrLoose) && thisComparators.every((thisComparator)=>{
                    return rangeComparators.every((rangeComparator)=>{
                        return thisComparator.intersects(rangeComparator, optionsOrLoose);
                    });
                });
            });
        });
    }
    toString() {
        return this.range;
    }
}
function testSet(set, version, options) {
    for(let i1 = 0; i1 < set.length; i1++){
        if (!set[i1].test(version)) {
            return false;
        }
    }
    if (version.prerelease.length && !options.includePrerelease) {
        for(let i1 = 0; i1 < set.length; i1++){
            if (set[i1].semver === ANY) {
                continue;
            }
            if (set[i1].semver.prerelease.length > 0) {
                const allowed = set[i1].semver;
                if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
                    return true;
                }
            }
        }
        return false;
    }
    return true;
}
function isSatisfiable(comparators, options) {
    let result1 = true;
    const remainingComparators = comparators.slice();
    let testComparator = remainingComparators.pop();
    while(result1 && remainingComparators.length){
        result1 = remainingComparators.every((otherComparator)=>{
            return testComparator?.intersects(otherComparator, options);
        });
        testComparator = remainingComparators.pop();
    }
    return result1;
}
function parseComparator(comp, options) {
    comp = replaceCarets(comp, options);
    comp = replaceTildes(comp, options);
    comp = replaceXRanges(comp, options);
    comp = replaceStars(comp, options);
    return comp;
}
function isX(id) {
    return !id || id.toLowerCase() === "x" || id === "*";
}
function replaceTildes(comp, options) {
    return comp.trim().split(/\s+/).map((comp)=>replaceTilde(comp, options)).join(" ");
}
function replaceTilde(comp, options) {
    const r = options.loose ? re[TILDELOOSE] : re[TILDE];
    return comp.replace(r, (_, M, m, p, pr)=>{
        let ret;
        if (isX(M)) {
            ret = "";
        } else if (isX(m)) {
            ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
        } else if (isX(p)) {
            ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
        } else if (pr) {
            ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
        } else {
            ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
        }
        return ret;
    });
}
function replaceCarets(comp, options) {
    return comp.trim().split(/\s+/).map((comp)=>replaceCaret(comp, options)).join(" ");
}
function replaceCaret(comp, options) {
    const r = options.loose ? re[CARETLOOSE] : re[CARET];
    return comp.replace(r, (_, M, m, p, pr)=>{
        let ret;
        if (isX(M)) {
            ret = "";
        } else if (isX(m)) {
            ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
        } else if (isX(p)) {
            if (M === "0") {
                ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
            } else {
                ret = ">=" + M + "." + m + ".0 <" + (+M + 1) + ".0.0";
            }
        } else if (pr) {
            if (M === "0") {
                if (m === "0") {
                    ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + m + "." + (+p + 1);
                } else {
                    ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + M + "." + (+m + 1) + ".0";
                }
            } else {
                ret = ">=" + M + "." + m + "." + p + "-" + pr + " <" + (+M + 1) + ".0.0";
            }
        } else {
            if (M === "0") {
                if (m === "0") {
                    ret = ">=" + M + "." + m + "." + p + " <" + M + "." + m + "." + (+p + 1);
                } else {
                    ret = ">=" + M + "." + m + "." + p + " <" + M + "." + (+m + 1) + ".0";
                }
            } else {
                ret = ">=" + M + "." + m + "." + p + " <" + (+M + 1) + ".0.0";
            }
        }
        return ret;
    });
}
function replaceXRanges(comp, options) {
    return comp.split(/\s+/).map((comp)=>replaceXRange(comp, options)).join(" ");
}
function replaceXRange(comp, options) {
    comp = comp.trim();
    const r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
    return comp.replace(r, (ret, gtlt, M, m, p, pr)=>{
        const xM = isX(M);
        const xm = xM || isX(m);
        const xp = xm || isX(p);
        const anyX = xp;
        if (gtlt === "=" && anyX) {
            gtlt = "";
        }
        if (xM) {
            if (gtlt === ">" || gtlt === "<") {
                ret = "<0.0.0";
            } else {
                ret = "*";
            }
        } else if (gtlt && anyX) {
            if (xm) {
                m = 0;
            }
            p = 0;
            if (gtlt === ">") {
                gtlt = ">=";
                if (xm) {
                    M = +M + 1;
                    m = 0;
                    p = 0;
                } else {
                    m = +m + 1;
                    p = 0;
                }
            } else if (gtlt === "<=") {
                gtlt = "<";
                if (xm) {
                    M = +M + 1;
                } else {
                    m = +m + 1;
                }
            }
            ret = gtlt + M + "." + m + "." + p;
        } else if (xm) {
            ret = ">=" + M + ".0.0 <" + (+M + 1) + ".0.0";
        } else if (xp) {
            ret = ">=" + M + "." + m + ".0 <" + M + "." + (+m + 1) + ".0";
        }
        return ret;
    });
}
function replaceStars(comp, options) {
    return comp.trim().replace(re[STAR], "");
}
function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
    if (isX(fM)) {
        from = "";
    } else if (isX(fm)) {
        from = ">=" + fM + ".0.0";
    } else if (isX(fp)) {
        from = ">=" + fM + "." + fm + ".0";
    } else {
        from = ">=" + from;
    }
    if (isX(tM)) {
        to = "";
    } else if (isX(tm)) {
        to = "<" + (+tM + 1) + ".0.0";
    } else if (isX(tp)) {
        to = "<" + tM + "." + (+tm + 1) + ".0";
    } else if (tpr) {
        to = "<=" + tM + "." + tm + "." + tp + "-" + tpr;
    } else {
        to = "<=" + to;
    }
    return (from + " " + to).trim();
}
function satisfies(version, range, optionsOrLoose) {
    try {
        range = new Range(range, optionsOrLoose);
    } catch (er) {
        return false;
    }
    return range.test(version);
}
function coerce(version, optionsOrLoose) {
    if (version instanceof SemVer) {
        return version;
    }
    if (typeof version !== "string") {
        return null;
    }
    const match = version.match(re[COERCE]);
    if (match == null) {
        return null;
    }
    return parse5(match[1] + "." + (match[2] || "0") + "." + (match[3] || "0"), optionsOrLoose);
}
const pkgVersRequirement = {
    knitr: {
        type: ">=",
        version: "1.30"
    },
    rmarkdown: {
        type: ">=",
        version: "2.3"
    }
};
async function checkRBinary() {
    const rBin = await rBinaryPath("Rscript");
    try {
        const result1 = await execProcess({
            cmd: [
                rBin,
                "--version"
            ],
            stdout: "piped",
            stderr: "piped"
        });
        if (result1.success && (result1.stdout || /R scripting front-end version/.test(result1.stderr ?? ''))) {
            debug(`\n++R found at ${rBin} is working.`);
            return rBin;
        } else {
            debug(`\n++R found at ${rBin} is not working properly.`);
            return undefined;
        }
    } catch  {
        debug(`\n++ Error while checking R binary found at ${rBin}`);
        return undefined;
    }
}
async function knitrCapabilities(rBin) {
    if (!rBin) return undefined;
    try {
        debug(`-- Checking knitr engine capabilities --`);
        const result1 = await execProcess({
            cmd: [
                rBin,
                resourcePath("capabilities/knitr.R")
            ],
            stdout: "piped"
        });
        if (result1.success && result1.stdout) {
            debug("\n++ Parsing results to get informations about knitr capabilities");
            const yamlLines = result1.stdout.replace(/^.*--- YAML_START ---/sm, "").replace(/--- YAML_END ---.*$/sm, "");
            const caps = readYamlFromString(yamlLines);
            const knitrVersion = caps.packages.knitr ? coerce(caps.packages.knitr) : undefined;
            caps.packages.knitrVersOk = knitrVersion ? satisfies(knitrVersion, Object.values(pkgVersRequirement["knitr"]).join(" ")) : false;
            const rmarkdownVersion = caps.packages.rmarkdown ? coerce(caps.packages.rmarkdown) : undefined;
            caps.packages.rmarkdownVersOk = rmarkdownVersion ? satisfies(rmarkdownVersion, Object.values(pkgVersRequirement["rmarkdown"]).join(" ")) : false;
            return caps;
        } else {
            debug("\n++ Problem with results of knitr capabilities check.");
            debug(`    Return Code: ${result1.code} (success is ${result1.success})`);
            result1.stdout ? debug(`    with stdout from R:\n${result1.stdout}`) : debug("    with no stdout");
            if (result1.stderr) {
                debug(`    with stderr from R:\n${result1.stderr}`);
            }
            return undefined;
        }
    } catch  {
        debug(`\n++ Error while running 'capabilities/knitr.R' ${rBin ? "with " + rBin : ""}`);
        return undefined;
    }
}
function knitrCapabilitiesMessage(caps, indent = "") {
    const lines = [
        `Version: ${caps.versionMajor}.${caps.versionMinor}.${caps.versionPatch}`,
        `Path: ${caps.home}`,
        `LibPaths:`
    ];
    for (const path of caps.libPaths){
        lines.push(`  - ${path}`);
    }
    lines.push(`knitr: ${caps.packages.knitr || "(None)"}`);
    if (caps.packages.knitr && !caps.packages.knitrVersOk) {
        lines.push(`NOTE: knitr version ${caps.packages.knitr} is too old. Please upgrade to ${pkgVersRequirement.knitr.version} or later.`);
    }
    lines.push(`rmarkdown: ${caps.packages.rmarkdown || "(None)"}`);
    if (caps.packages.rmarkdown && !caps.packages.rmarkdownVersOk) {
        lines.push(`NOTE: rmarkdown version ${caps.packages.rmarkdown} is too old. Please upgrade to ${pkgVersRequirement.rmarkdown.version} or later.`);
    }
    return lines.map((line)=>`${indent}${line}`).join("\n");
}
function knitrInstallationMessage(indent = "", pkg = "rmarkdown", update = false) {
    const lines = [
        `The ${pkg} package is ${update ? "outdated" : "not available"} in this R installation.`
    ];
    if (update) {
        lines.push("Update with " + bold(`update.packages("${pkg}")`));
    } else {
        lines.push("Install with " + bold(`install.packages("${pkg}")`));
    }
    return lines.map((line)=>`${indent}${line}`).join("\n");
}
function rInstallationMessage(indent = "") {
    const lines = [
        "Unable to locate an installed version of R.",
        "Install R from " + bold("https://cloud.r-project.org/")
    ];
    return lines.map((line)=>`${indent}${line}`).join("\n");
}
const kTextHtml = "text/html";
const kTextMarkdown = "text/markdown";
const kTextLatex = "text/latex";
const kTextPlain = "text/plain";
const kTextXml = "text/xml";
const kTextCss = "text/css";
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 kDocxDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
const kRestructuredText = "text/restructuredtext";
const kApplicationRtf = "application/rtf";
function extensionForMimeImageType(mimeType, defaultType = "bin") {
    switch(mimeType){
        case kImagePng:
            return "png";
        case kImageJpeg:
            return "jpeg";
        case kImageSvg:
            return "svg";
        case kApplicationPdf:
            return "pdf";
        default:
            return defaultType;
    }
}
function contentType(path) {
    return MEDIA_TYPES[extname2(path.toLowerCase())];
}
function isPdfContent(path) {
    return !!path && contentType(path) === kApplicationPdf;
}
function isDocxContent(path) {
    return !!path && contentType(path) === kDocxDocument;
}
function isHtmlContent(path) {
    return !!path && contentType(path) === kTextHtml;
}
function isTextContent(path) {
    return !!path && (contentType(path) === kTextMarkdown || contentType(path) === kTextPlain || contentType(path) === kTextXml);
}
const MEDIA_TYPES = {
    ".md": kTextMarkdown,
    ".markdown": kTextMarkdown,
    ".html": kTextHtml,
    ".htm": kTextHtml,
    ".json": "application/json",
    ".ipynb": "application/x-ipynb+json",
    ".map": "application/json",
    ".txt": kTextPlain,
    ".tex": kTextPlain,
    ".adoc": kTextPlain,
    ".asciidoc": kTextPlain,
    ".xml": kTextXml,
    ".ts": "text/typescript",
    ".tsx": "text/tsx",
    ".js": kApplicationJavascript,
    ".jsx": "text/jsx",
    ".gz": "application/gzip",
    ".css": kTextCss,
    ".wasm": "application/wasm",
    ".mjs": kApplicationJavascript,
    ".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",
    ".textile": kTextPlain,
    ".texinfo": kTextPlain,
    ".tei": kTextPlain,
    ".rst": kTextPlain,
    ".org": kTextPlain,
    ".opml": kTextPlain,
    ".muse": kTextPlain,
    ".ms": kTextPlain,
    ".native": kTextPlain,
    ".man": kTextPlain,
    ".dokuwiki": kTextPlain,
    ".haddock": kTextPlain,
    ".icml": kTextPlain,
    ".jira": kTextPlain,
    ".mediawiki": kTextPlain,
    ".xwiki": kTextPlain,
    ".zim": kTextPlain,
    ".typ": kTextPlain,
    ".docx": kDocxDocument
};
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);
    }
    if (displayDataHasHtmlTable(output) && !displayPriority.includes(kTextHtml)) {
        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 displayDataLatexIsMath(latex) {
    if (latex.length > 0) {
        const first = latex[0];
        const last = latex[latex.length - 1];
        return first.startsWith("$") && last.endsWith("$") || first.startsWith("\\begin{") && last.includes("\\end{");
    }
    return false;
}
function displayDataWithMarkdownMath(output) {
    if (Array.isArray(output.data[kTextLatex]) && !output.data[kTextMarkdown]) {
        const latex = output.data[kTextLatex];
        if (displayDataLatexIsMath(latex)) {
            output = cloneDeep1(output);
            output.data[kTextMarkdown] = output.data[kTextLatex];
            return output;
        }
    }
    return output;
}
function displayDataHasHtmlTable(output) {
    const html = Array.isArray(output.data[kTextHtml]) ? output.data[kTextHtml] : typeof output.data[kTextHtml] === "string" ? [
        output.data[kTextHtml]
    ] : undefined;
    if (html) {
        const htmlLower = html.map((line)=>line.toLowerCase());
        return htmlLower.some((line)=>!!line.match(/<[Tt][Aa][Bb][Ll][Ee]/)) && htmlLower.some((line)=>!!line.match(/<\/[Tt][Aa][Bb][Ll][Ee]/));
    } else {
        return false;
    }
}
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 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" + globalThis.crypto.randomUUID().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 postProcessRestorePreservedHtml(options) {
    const outputPath = isAbsolute2(options.output) ? options.output : join2(dirname2(options.target.input), options.output);
    let output = Deno.readTextFileSync(outputPath);
    output = restorePreservedHtml(output, options.preserve);
    Deno.writeTextFileSync(outputPath, output);
}
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 executeInlineCodeHandler(language, exec) {
    const exprPattern = new RegExp("(^|[^`])`{" + language + "}[ \t]([^`]+)`", "g");
    return (code)=>{
        return code.replaceAll(exprPattern, (match, prefix, expr)=>{
            const result1 = exec(expr.trim());
            if (result1) {
                return `${prefix}${result1}`;
            } else {
                return match;
            }
        });
    };
}
function executeInlineCodeHandlerMapped(language, exec) {
    const exprPattern = new RegExp("(^|[^`])`{" + language + "}[ \t]([^`]+)`", "g");
    return (code)=>{
        let matches;
        const result1 = [];
        let prevIndex = 0;
        while(matches = exprPattern.exec(code.value)){
            result1.push(mappedSubstring(code, prevIndex, matches.index));
            const matchMapped = mappedSubstring(code, matches.index, matches.index + matches[0].length);
            const prefixMapped = mappedSubstring(code, matches.index, matches.index + matches[1].length);
            const exprStr = matches[2];
            const exprResult = exec(exprStr.trim());
            if (exprResult) {
                result1.push(prefixMapped);
                result1.push(asMappedString(exprResult));
            } else {
                result1.push(matchMapped);
            }
            prevIndex = matches.index + matches[0].length;
        }
        result1.push(mappedSubstring(code, prevIndex));
        return mappedConcat(result1);
    };
}
const kRmdExtensions = [
    ".rmd",
    ".rmarkdown"
];
const knitrEngine = {
    name: kKnitrEngine,
    defaultExt: ".qmd",
    defaultYaml: ()=>[],
    defaultContent: ()=>[
            "```{r}",
            "1 + 1",
            "```"
        ],
    validExtensions: ()=>kRmdExtensions.concat(kRmdExtensions),
    claimsFile: (file, ext)=>{
        return kRmdExtensions.includes(ext.toLowerCase()) || isKnitrSpinScript(file);
    },
    claimsLanguage: (language)=>{
        return language.toLowerCase() === "r";
    },
    async markdownForFile (file) {
        const isSpin = isKnitrSpinScript(file);
        if (isSpin) {
            return asMappedString(await markdownFromKnitrSpinScript(file));
        }
        return mappedStringFromFile(file);
    },
    target: async (file, _quiet, markdown, project)=>{
        markdown = await project.resolveFullMarkdownForFile(knitrEngine, file, markdown);
        let metadata;
        try {
            metadata = readYamlFromMarkdown(markdown.value);
        } catch (e) {
            error(`Error reading metadata from ${file}.\n${e.message}`);
            throw e;
        }
        const target = {
            source: file,
            input: file,
            markdown,
            metadata
        };
        return Promise.resolve(target);
    },
    partitionedMarkdown: async (file)=>{
        if (isKnitrSpinScript(file)) {
            return partitionMarkdown(await markdownFromKnitrSpinScript(file));
        } else {
            return partitionMarkdown(Deno.readTextFileSync(file));
        }
    },
    execute: async (options)=>{
        const inputBasename = basename2(options.target.input);
        const inputStem = basename2(inputBasename, extname2(inputBasename));
        const result1 = await callR("execute", {
            ...options,
            target: undefined,
            input: options.target.input,
            markdown: resolveInlineExecute(options.target.markdown.value)
        }, options.tempDir, options.project?.isSingleFile ? undefined : options.projectDir, options.quiet, (output)=>{
            output = output.replaceAll(`${inputStem}.rmarkdown`, inputBasename);
            const m = output.match(/^Quitting from lines (\d+)-(\d+)/m);
            if (m) {
                const f1 = lineColToIndex(options.target.markdown.value);
                const f2 = mappedIndexToLineCol(options.target.markdown);
                const newLine1 = f2(f1({
                    line: Number(m[1]) - 1,
                    column: 0
                })).line + 1;
                const newLine2 = f2(f1({
                    line: Number(m[2]) - 1,
                    column: 0
                })).line + 1;
                output = output.replace(/^Quitting from lines (\d+)-(\d+)/m, `\n\nQuitting from lines ${newLine1}-${newLine2}`);
            }
            output = filterAlwaysAllowHtml(output);
            return output;
        });
        const includes = result1.includes;
        if (Array.isArray(includes) && includes.length === 0) {
            result1.includes = {};
        }
        return result1;
    },
    dependencies: (options)=>{
        return callR("dependencies", {
            ...options,
            target: undefined,
            input: options.target.input
        }, options.tempDir, options.projectDir, options.quiet);
    },
    postprocess: async (options)=>{
        postProcessRestorePreservedHtml(options);
        if (options.format.render?.[kCodeLink]) {
            if (isServerShiny(options.format)) {
                warn(`'code-link' option will be ignored as it is not supported for 'server: shiny' due to 'downlit' R package limitation (https://github.com/quarto-dev/quarto-cli/issues/9208).`);
                return Promise.resolve();
            }
            await callR("postprocess", {
                ...options,
                target: undefined,
                preserve: undefined,
                input: options.target.input
            }, options.tempDir, options.projectDir, options.quiet, undefined, false).then(()=>{
                return Promise.resolve();
            }, ()=>{
                warn(`Unable to perform code-link (code-link requires R packages rmarkdown, downlit, and xml2)`);
                return Promise.resolve();
            });
        }
    },
    canFreeze: true,
    generatesFigures: true,
    ignoreDirs: ()=>{
        return [
            "renv",
            "packrat",
            "rsconnect"
        ];
    },
    run: (options)=>{
        let running = false;
        return callR("run", options, options.tempDir, options.projectDir, undefined, (output)=>{
            const kListeningPattern = /(Listening on) (https?:\/\/[^\n]*)/;
            if (!running) {
                const listeningMatch = output.match(kListeningPattern);
                if (listeningMatch) {
                    running = true;
                    output = output.replace(kListeningPattern, "");
                    if (options.onReady) {
                        options.onReady();
                    }
                }
            }
            return output;
        });
    }
};
async function callR(action, params, tempDir, projectDir, quiet, outputFilter, reportError = true) {
    const cwd = withinActiveRenv() ? Deno.cwd() : projectDir ?? Deno.cwd();
    const resultsFile = Deno.makeTempFileSync({
        dir: tempDir,
        prefix: "r-results",
        suffix: ".json"
    });
    const input = JSON.stringify({
        action,
        params,
        results: resultsFile,
        wd: cwd
    });
    try {
        const result1 = await execProcess({
            cmd: [
                await rBinaryPath("Rscript"),
                resourcePath("rmd/rmd.R")
            ],
            cwd,
            stderr: quiet ? "piped" : "inherit"
        }, input, "stdout>stderr", (output)=>{
            if (outputFilter) {
                output = outputFilter(output);
            }
            return red(output);
        });
        if (result1.success) {
            const results = await Deno.readTextFile(resultsFile);
            await Deno.remove(resultsFile);
            const resultsJson = JSON.parse(results);
            return resultsJson;
        } else {
            if (quiet) {
                error(result1.stderr || "");
            }
            if (reportError) {
                await printCallRDiagnostics();
            }
            return Promise.reject();
        }
    } catch (e) {
        if (reportError) {
            if (e?.message) {
                info("");
                error(e.message);
            }
            await printCallRDiagnostics();
        }
        return Promise.reject();
    }
}
function withinActiveRenv() {
    const kRProfile = ".Rprofile";
    const kREnvActivate = 'source("renv/activate.R")';
    if (existsSync(".Rprofile")) {
        const profile = Deno.readTextFileSync(kRProfile);
        return profile.includes(kREnvActivate) && !profile.includes("# " + kREnvActivate);
    } else {
        return false;
    }
}
async function printCallRDiagnostics() {
    const rBin = await checkRBinary();
    if (rBin === undefined) {
        info("");
        info(rInstallationMessage());
        info("");
    } else {
        const caps = await knitrCapabilities(rBin);
        if (caps === undefined) {
            info(`Problem with running R found at ${rBin} to check environment configurations.`);
            info("Please check your installation of R.");
            info("");
        } else {
            if (!caps?.packages.rmarkdown || !caps?.packages.knitr || !caps?.packages.knitrVersOk || !caps?.packages.rmarkdownVersOk) {
                info("R installation:");
                info(knitrCapabilitiesMessage(caps, "  "));
                if (!!!caps?.packages.knitr || !caps?.packages.knitrVersOk) {
                    info("");
                    info(knitrInstallationMessage("", "knitr", !!caps.packages.knitr && !caps.packages.knitrVersOk));
                }
                if (!!!caps?.packages.rmarkdown || !caps?.packages.rmarkdownVersOk) {
                    info("");
                    info(knitrInstallationMessage("", "rmarkdown", !!caps?.packages.rmarkdown && !caps?.packages.rmarkdownVersOk));
                }
                info("");
            }
        }
    }
}
function filterAlwaysAllowHtml(s) {
    if (s.indexOf("Functions that produce HTML output found in document targeting") !== -1) {
        s = s.replace("your rmarkdown file", "your quarto file").replace("always_allow_html: true", "prefer-html: true");
    }
    return s;
}
function resolveInlineExecute(code) {
    return executeInlineCodeHandler("r", (expr)=>`${"`"}r .QuartoInlineRender(${expr})${"`"}`)(code);
}
function isKnitrSpinScript(file) {
    const ext = extname2(file).toLowerCase();
    if (ext == ".r") {
        const text = Deno.readTextFileSync(file);
        return /^\s*#'\s*---[\s\S]+?\s*#'\s*---/.test(text);
    } else {
        return false;
    }
}
async function markdownFromKnitrSpinScript(file) {
    const tempDir = globalTempContext().createDir();
    const result1 = await callR("spin", {
        input: file
    }, tempDir, undefined, true);
    return result1;
}
function isWindows3() {
    return Deno.build.os === "windows";
}
function isWSL() {
    return !!Deno.env.get("WSL_DISTRO_NAME");
}
function isRStudio() {
    return !!Deno.env.get("RSTUDIO");
}
function isVSCodeOutputChannel() {
    return !!Deno.env.get("VSCODE_PID");
}
function isVSCodeTerminal() {
    return Deno.env.get("TERM_PROGRAM") === "vscode";
}
function isVSCodeServer() {
    return !!vsCodeServerProxyUri();
}
function isRStudioWorkbench() {
    return !!Deno.env.get("RS_SERVER_URL") && !!Deno.env.get("RS_SESSION_URL");
}
function isRStudioTerminal() {
    return !!Deno.env.get("RSTUDIO_TERM");
}
function isServerSession() {
    return isRStudioServer() || isRStudioWorkbench() || isJupyterServer() || isJupyterHubServer() || isVSCodeServer();
}
function isRStudioServer() {
    return isRStudio() && Deno.env.get("RSTUDIO_PROGRAM_MODE") === "server";
}
function isRStudioPreview() {
    return isRStudio() && !isRStudioTerminal();
}
function isJupyterServer() {
    return !!Deno.env.get("JUPYTER_SERVER_URL");
}
function isJupyterHubServer() {
    return !!jupyterHubUser() && !!jupyterHubServicePrefix();
}
function vsCodeServerProxyUri() {
    return Deno.env.get("VSCODE_PROXY_URI");
}
function jupyterHubHttpReferrer() {
    return Deno.env.get("JUPYTERHUB_HTTP_REFERER");
}
function jupyterHubUser() {
    return Deno.env.get("JUPYTERHUB_USER");
}
function jupyterHubServicePrefix() {
    return Deno.env.get("JUPYTERHUB_SERVICE_PREFIX");
}
function isInteractiveTerminal() {
    return Deno.isatty(Deno.stderr.rid);
}
function isInteractiveSession() {
    return isRStudio() || isInteractiveTerminal() || isVSCodeOutputChannel();
}
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 encoder = new TextEncoder();
function getTypeName(value) {
    const type = typeof value;
    if (type !== "object") {
        return type;
    } else if (value === null) {
        return "null";
    } else {
        return value?.constructor?.name ?? "object";
    }
}
function validateBinaryLike(source) {
    if (typeof source === "string") {
        return encoder.encode(source);
    } else if (source instanceof Uint8Array) {
        return source;
    } else if (source instanceof ArrayBuffer) {
        return new Uint8Array(source);
    }
    throw new TypeError(`The input must be a Uint8Array, a string, or an ArrayBuffer. Received a value of the type ${getTypeName(source)}.`);
}
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 encodeBase64(data) {
    const uint8 = validateBinaryLike(data);
    let result1 = "", i1;
    const l1 = uint8.length;
    for(i1 = 2; i1 < l1; i1 += 3){
        result1 += base64abc[uint8[i1 - 2] >> 2];
        result1 += base64abc[(uint8[i1 - 2] & 0x03) << 4 | uint8[i1 - 1] >> 4];
        result1 += base64abc[(uint8[i1 - 1] & 0x0f) << 2 | uint8[i1] >> 6];
        result1 += base64abc[uint8[i1] & 0x3f];
    }
    if (i1 === l1 + 1) {
        result1 += base64abc[uint8[i1 - 2] >> 2];
        result1 += base64abc[(uint8[i1 - 2] & 0x03) << 4];
        result1 += "==";
    }
    if (i1 === l1) {
        result1 += base64abc[uint8[i1 - 2] >> 2];
        result1 += base64abc[(uint8[i1 - 2] & 0x03) << 4 | uint8[i1 - 1] >> 4];
        result1 += base64abc[(uint8[i1 - 1] & 0x0f) << 2];
        result1 += "=";
    }
    return result1;
}
function decodeBase64(b64) {
    const binString = atob(b64);
    const size = binString.length;
    const bytes = new Uint8Array(size);
    for(let i1 = 0; i1 < size; i1++){
        bytes[i1] = binString.charCodeAt(i1);
    }
    return bytes;
}
function checkForEqualsInChunk(error, _parse, _schema) {
    if (typeof error.violatingObject.result !== "string") {
        return error;
    }
    const badObject = error.source.value.substring(error.violatingObject.start, error.violatingObject.end);
    if (errorKeyword(error) !== "type") {
        return error;
    }
    let m;
    const heading = `${error.location}: ${quotedStringColor(badObject)} must be a YAML mapping.`;
    const errorMsg = [
        `${quotedStringColor(badObject)} is a string.`
    ];
    const newError = {
        heading,
        error: errorMsg,
        info: {}
    };
    addFileInfo(newError, error.source);
    addInstancePathInfo(newError, error.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 error;
    }
    return {
        ...error,
        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 InternalError(`bad engine tag ${engineTag}`);
        }
    }), `engine-${engine}`);
const markdownEngineSchema = defineCached(async ()=>{
    return {
        schema: makeEngineSchema("markdown"),
        errorHandlers: []
    };
}, "engine-markdown");
const knitrEngineSchema = defineCached(async ()=>{
    const result1 = await makeEngineSchema("knitr");
    return {
        schema: result1,
        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((l1)=>l1.match(noIndentOrColon)).length === 0) {
        return "yaml";
    }
    if (chunkLines.some((l1)=>l1.trim() !== "" && !l1.trimRight().endsWith(",") && l1.indexOf("=") === -1)) {
        return "yaml";
    }
    return "knitr";
}
function mappedSource(source, substrs) {
    const params = [];
    for (const { range } of substrs){
        params.push(range);
    }
    return mappedString(source, params);
}
function partitionCellOptions(language, source) {
    const commentChars = langCommentChars(language);
    const optionPattern = optionCommentPattern(commentChars[0]);
    const optionSuffix = commentChars[1] || "";
    const optionsSource = [];
    const yamlLines = [];
    for (const line of source){
        const optionMatch = line.match(optionPattern);
        if (optionMatch) {
            if (!optionSuffix || line.trimEnd().endsWith(optionSuffix)) {
                let yamlOption = line.substring(optionMatch[0].length);
                if (optionSuffix) {
                    yamlOption = yamlOption.trimEnd();
                    yamlOption = yamlOption.substring(0, yamlOption.length - optionSuffix.length);
                    if (line.endsWith("\r\n")) {
                        yamlOption += "\r\n";
                    } else if (line.endsWith("\r") || line.endsWith("\n")) {
                        yamlOption += line[line.length - 1];
                    }
                }
                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;
    if (yamlLines.length > 0) {
        yaml = readAnnotatedYamlFromMappedString(asMappedString(yamlLines.join("\n"))).result;
    }
    return {
        yaml: yaml,
        optionsSource,
        source: source.slice(yamlLines.length),
        sourceStartLine: yamlLines.length
    };
}
async function parseAndValidateCellOptions(mappedYaml, language, validate = false, engine = "", lenient = false) {
    if (mappedYaml.value.trim().length === 0) {
        return undefined;
    }
    const engineOptionsSchema = await getEngineOptionsSchema();
    let schema = engineOptionsSchema[engine];
    const languages = getYamlIntelligenceResource("handlers/languages.yml");
    if (languages.indexOf(language) !== -1) {
        try {
            schema = getYamlIntelligenceResource(`handlers/${language}/schema.yml`);
        } catch (_e) {
            schema = undefined;
        }
    }
    if (schema === undefined || !validate) {
        return readAnnotatedYamlFromMappedString(mappedYaml, lenient).result;
    }
    const { yaml, yamlValidationErrors } = await readAndValidateYamlFromMappedString(mappedYaml, schema, undefined, lenient);
    if (yamlValidationErrors.length > 0) {
        throw new ValidationError2(`Validation of YAML metadata for cell with engine ${engine} failed`, yamlValidationErrors);
    }
    return yaml;
}
function partitionCellOptionsText(language, source) {
    const commentChars = langCommentChars(language);
    const optionPattern = optionCommentPattern(commentChars[0]);
    const optionSuffix = commentChars[1] || "";
    const optionsSource = [];
    const yamlLines = [];
    let endOfYaml = 0;
    for (const line of rangedLines(source.value, true)){
        const optionMatch = line.substring.match(optionPattern);
        if (optionMatch) {
            if (!optionSuffix || line.substring.trimEnd().endsWith(optionSuffix)) {
                let yamlOption = line.substring.substring(optionMatch[0].length);
                if (optionSuffix) {
                    yamlOption = yamlOption.trimEnd();
                    yamlOption = yamlOption.substring(0, yamlOption.length - optionSuffix.length).trimEnd();
                }
                endOfYaml = line.range.start + optionMatch[0].length + yamlOption.length;
                const rangedYamlOption = {
                    substring: yamlOption,
                    range: {
                        start: line.range.start + optionMatch[0].length,
                        end: endOfYaml
                    }
                };
                yamlLines.push(rangedYamlOption);
                if (optionSuffix) {
                    if (line.substring.endsWith("\r\n")) {
                        yamlLines.push({
                            substring: "\r\n",
                            range: {
                                start: line.range.end - 2,
                                end: line.range.end
                            }
                        });
                    } else if (line.substring.endsWith("\r") || line.substring.endsWith("\n")) {
                        yamlLines.push({
                            substring: line.substring[line.substring.length - 1],
                            range: {
                                start: line.range.end - 1,
                                end: line.range.end
                            }
                        });
                    }
                }
                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
    };
}
async function partitionCellOptionsMapped(language, outerSource, validate = false, engine = "", lenient = false) {
    const { yaml: mappedYaml, optionsSource, source, sourceStartLine } = partitionCellOptionsText(language, outerSource);
    if (language !== "r" || guessChunkOptionsFormat((mappedYaml || asMappedString("")).value) === "yaml") {
        const yaml = await parseAndValidateCellOptions(mappedYaml || asMappedString(""), language, validate, engine, lenient);
        return {
            yaml: yaml,
            optionsSource,
            source,
            sourceStartLine
        };
    } else {
        return {
            yaml: undefined,
            optionsSource,
            source,
            sourceStartLine
        };
    }
}
function langCommentChars(lang) {
    const chars = kLangCommentChars[lang] || "#";
    if (!Array.isArray(chars)) {
        return [
            chars
        ];
    } else {
        return chars;
    }
}
function optionCommentPattern(comment) {
    return new RegExp("^" + escapeRegExp(comment) + "\\s*\\| ?");
}
function addLanguageComment(language, comment) {
    kLangCommentChars[language] = comment;
}
function optionCommentPatternFromLanguage(language) {
    return optionCommentPattern(langCommentChars(language)[0]);
}
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: "#",
    prql: "#",
    ruby: "#",
    tikz: "%",
    js: "//",
    d3: "//",
    node: "//",
    sass: "//",
    scss: "//",
    coffee: "#",
    go: "//",
    asy: "//",
    haskell: "--",
    dot: "//",
    ojs: "//",
    apl: "⍝",
    ocaml: [
        "(*",
        "*)"
    ],
    rust: "//"
};
function escapeRegExp(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function shortUuid() {
    return globalThis.crypto.randomUUID().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 = .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 i1 = position; i1 < start + count; i1++){
        value += byteArray[i1] << 8 * (count - (i1 - start) - 1);
    }
    return value;
}
function bytesToString(byteArray, start = 0, count) {
    if (count === undefined) {
        count = byteArray.length;
    }
    let result1 = "";
    for(let i1 = start; i1 < start + count; i1++){
        const __byte = byteArray[i1];
        if (__byte === 0) {
            result1 += "00";
        } else if (__byte < 10) {
            result1 += `0${__byte.toString()}`;
        } else {
            result1 += __byte.toString();
        }
    }
    return result1;
}
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 gfmAutoIdentifier(text, asciify) {
    if (asciify) {
        text = pandocAsciify(text);
    }
    return text.replace(/[!"#$%&')*+,\.\/:;<=>?@\[\\\]^`{|}~]/g, "").replace(/\s/g, "-").toLowerCase();
}
function pandocAsciify(text) {
    const chars = [];
    const len = text.length;
    let newch;
    for(let i1 = 0; i1 < len; i1++){
        newch = "";
        const ch = text.charCodeAt(i1);
        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 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 fileResponse;
        if (options.onFile) {
            fileResponse = await options.onFile(filePath, req);
        }
        if (!fileResponse) {
            fileResponse = {
                contentType: contentType(filePath),
                body: Deno.readFileSync(filePath)
            };
        }
        return httpContentResponse(fileResponse.body, fileResponse.contentType);
    }
    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,
                response: {
                    body: encoder.encode("Not Found")
                }
            };
            const ignoreFileNames = [
                "favicon.ico",
                "listings.json",
                /jupyter-.*.js/,
                /apple-touch-icon-/
            ];
            handle404.print = handle404.print && !!options.printUrls && (!fsPath || !ignoreFileNames.find((name)=>{
                return basename2(fsPath).match(name);
            }) && extname2(fsPath) !== ".map");
            if (handle404.print) {
                printUrl(url, false);
            }
            return Promise.resolve(new Response(handle404.response.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 = join2(fsPath, options.defaultFile || "index.html");
            }
            if (fileInfo?.isDirectory && !normalizedUrl.endsWith("/")) {
                response = serveRedirect(normalizedUrl + "/");
            } else {
                response = await serveFile(fsPath, req);
                if (normalizedUrl === "/" && !isBrowserPreviewable(fsPath)) {
                    response.headers.append("content-disposition", 'attachment; filename="' + options.defaultFile + '"');
                }
                if (options.printUrls === "all") {
                    printUrl(normalizedUrl);
                }
            }
        } catch (e) {
            if (fsPath) {
                fsPath = normalize2(fsPath);
            }
            response = await serveFallback(req, e, fsPath);
        }
        return response;
    };
}
function httpContentResponse(content, contentType) {
    if (typeof content === "string") {
        content = new TextEncoder().encode(content);
    }
    const headers = new Headers();
    headers.set("Content-Length", content.byteLength.toString());
    if (contentType) {
        headers.set("Content-Type", contentType);
    }
    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 (e) {
        if (!(e instanceof TypeError)) {
            throw e;
        }
    }
    if (normalizedUrl[0] !== "/") {
        throw new URIError("The request URI is malformed.");
    }
    normalizedUrl = mod.normalize(normalizedUrl);
    const startOfParams = normalizedUrl.indexOf("?");
    return startOfParams > -1 ? normalizedUrl.slice(0, startOfParams) : normalizedUrl;
}
function isBrowserPreviewable(file) {
    return isHtmlContent(file) || isPdfContent(file) || isTextContent(file);
}
function maybeDisplaySocketError(e) {
    if (!(e instanceof Deno.errors.NotFound) && !(e instanceof Deno.errors.BrokenPipe) && !(e instanceof Deno.errors.NotConnected) && !(e instanceof Deno.errors.ConnectionAborted) && !(e instanceof Deno.errors.ConnectionReset) && !(e instanceof Deno.errors.ConnectionRefused) && !(e instanceof DOMException)) {
        logError(e);
    }
}
function serveRedirect(url) {
    const headers = new Headers();
    headers.set("Cache-Control", "no-store, max-age=0");
    headers.set("Location", url);
    return new Response(null, {
        status: 301,
        headers
    });
}
function printUrl(url, found = true) {
    const format = !found ? red : undefined;
    const urlDisplay = url + (found ? "" : " (404: Not Found)");
    if (isHtmlContent(url) || url.endsWith("/") || extname2(url) === "") {
        info(`GET: ${urlDisplay}`, {
            bold: false,
            format: format || green
        });
    } else if (!found) {
        info(urlDisplay, {
            dim: found,
            format,
            indent: 2
        });
    }
}
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 = normalizePath(file);
                const css = Deno.readTextFileSync(file);
                const cssRefs = cssFileRefs(css).map((ref)=>join2(dirname2(file), ref));
                allRefs.push(...cssRefs);
                allRefs.push(...cssFileResourceReferences(cssRefs));
            }
        }
        return allRefs;
    }, []);
}
function isCssFile(path) {
    return extname2(path).toLowerCase() === ".css";
}
function fixupCssReferences(css, resolveRef) {
    let destCss = css.replaceAll(kCssUrlRegex, (_match, p1, p2)=>{
        const path = resolveRef(p2);
        return `url(${p1 || ""}${path}${p1 || ""})`;
    });
    destCss = destCss.replaceAll(kCssImportRegex, (_match, p1, p2)=>{
        const path = resolveRef(p2);
        return `@import ${p1 || ""}${path}${p1 || ""}`;
    });
    return destCss;
}
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 str = String(value);
        const match = str.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 str = String(value);
        if (str !== "0" && !str.match(/[^0-9]$/)) {
            return str + "px";
        } else {
            return str;
        }
    }
}
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 asHtmlId(text) {
    return pandocAutoIdentifier(text, false);
}
function getDecodedAttribute(element, attrib) {
    const value = element.getAttribute(attrib);
    if (value) {
        try {
            return decodeURI(value);
        } catch (e) {
            if (e instanceof URIError) {
                warn(`Invalid URI '${value}' in attribute '${attrib}' of element '${element.tagName}'`);
                return value;
            } else {
                throw e;
            }
        }
    } else {
        return value;
    }
}
const kTagBrackets = {
    "<": "&lt;",
    ">": "&gt;"
};
const kAttrReplacements = {
    '"': "&quot;",
    "'": "&#039;",
    ...kTagBrackets,
    "&": "&amp;"
};
function encodeAttributeValue(value) {
    if (typeof value === "string") {
        let result1 = value;
        Object.keys(kAttrReplacements).forEach((key)=>{
            result1 = result1.replace(key, kAttrReplacements[key]);
        });
        return result1;
    } else {
        return value;
    }
}
function encodeHtml(value) {
    Object.keys(kTagBrackets).forEach((key)=>{
        value = value.replaceAll(key, kTagBrackets[key]);
    });
    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"
    ],
    "source": [
        "src"
    ]
};
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 i1 = 0; i1 < styles.length; i1++){
        const style = styles[i1];
        if (style.innerHTML) {
            refs.push(...cssFileRefs(style.innerHTML));
        }
    }
    return Promise.resolve({
        resources: refs,
        supporting: []
    });
}
function fixEmptyHrefs(doc) {
    const anchors = doc.querySelectorAll("a");
    for(let i1 = 0; i1 < anchors.length; ++i1){
        const anchor = anchors[i1];
        if (!anchor.getAttribute("href")) {
            anchor.setAttribute("href", "");
        }
    }
    return Promise.resolve({
        resources: [],
        supporting: []
    });
}
function processFileResourceRefs(doc, tag, attrib, onRef) {
    const tags = doc.querySelectorAll(tag);
    for(let i1 = 0; i1 < tags.length; i1++){
        const tag = tags[i1];
        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, ref)=>refs.push(ref));
    return refs;
}
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(htmlLibrariesText(htmlText));
                        return false;
                    }
                }
                return true;
            });
        }
    });
    return {
        jsWidgets,
        jupyterWidgets,
        htmlLibraries,
        widgetsState: nb.metadata.widgets?.[kApplicationJupyterWidgetState]
    };
}
function includesForJupyterWidgetDependencies(dependencies, tempDir) {
    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" data-relocate-top="true"></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) {
        const stateStr = JSON.stringify(widgetsState);
        if (stateStr.includes("</script>")) {
            afterBody.push(`<script>
      (() => {
        const scriptTag = document.createElement("script");
        const base64State = "${btoa(encodeURIComponent(stateStr))}";
        scriptTag.type = "${kApplicationJupyterWidgetState}";
        scriptTag.textContent = decodeURIComponent(atob(base64State));
        document.body.appendChild(scriptTag);
      })();
      </script>`);
        } else {
            afterBody.push(`<script type=${kApplicationJupyterWidgetState}>`);
            afterBody.push(JSON.stringify(widgetsState));
            afterBody.push("</script>");
        }
    }
    const widgetTempFile = (lines)=>{
        const tempFile = Deno.makeTempFileSync({
            dir: tempDir,
            prefix: "jupyter-widgets-",
            suffix: ".html"
        });
        Deno.writeTextFileSync(tempFile, lines.join("\n") + "\n");
        return tempFile;
    };
    const result1 = {
        inHeader: "",
        afterBody: ""
    };
    if (head.length > 0) {
        result1.inHeader = widgetTempFile(head);
    }
    if (afterBody.length > 0) {
        result1.afterBody = widgetTempFile(afterBody);
    }
    return result1;
}
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 htmlLibrariesText(htmlText) {
    const htmlLines = lines(htmlText);
    const leadingSpace = htmlLines.reduce((leading, line)=>{
        const spaces = line.search(/\S/);
        if (spaces !== -1) {
            return Math.min(leading, spaces);
        } else {
            return leading;
        }
    }, Number.MAX_SAFE_INTEGER);
    if (leadingSpace !== Number.MAX_SAFE_INTEGER) {
        return htmlLines.map((line)=>{
            if (line.trim().length === 0) {
                return "";
            } else {
                return line.replace(" ".repeat(leadingSpace), "");
            }
        }).join("\n");
    } else {
        return htmlText;
    }
}
const kNoLanguage = "(none)";
const jupyterCapsCache = new Map();
async function jupyterCapabilities(kernelspec) {
    const language = kernelspec?.language || kNoLanguage;
    if (!jupyterCapsCache.has(language)) {
        let juliaCaps;
        if (language === "julia") {
            juliaCaps = await getVerifiedJuliaCondaJupyterCapabilities();
            if (juliaCaps) {
                jupyterCapsCache.set(language, juliaCaps);
                return juliaCaps;
            }
        }
        const quartoCaps = await getQuartoJupyterCapabilities();
        if (quartoCaps) {
            jupyterCapsCache.set(language, quartoCaps);
            return quartoCaps;
        }
        if (isWindows3() && pyPython()) {
            const pyLauncherCaps = await getPyLauncherJupyterCapabilities();
            if (pyLauncherCaps) {
                jupyterCapsCache.set(language, pyLauncherCaps);
            }
        }
        if (!jupyterCapsCache.has(language)) {
            const condaCaps = await getJupyterCapabilities([
                "python"
            ]);
            if (condaCaps?.conda) {
                jupyterCapsCache.set(language, condaCaps);
            } else {
                const caps = isWindows3() ? await getPyLauncherJupyterCapabilities() : await getJupyterCapabilities([
                    "python3"
                ]);
                if (caps) {
                    jupyterCapsCache.set(language, caps);
                }
            }
            if (!jupyterCapsCache.get(language)?.jupyter_core && juliaCaps) {
                jupyterCapsCache.set(language, juliaCaps);
            }
        }
    }
    return jupyterCapsCache.get(language);
}
async function getVerifiedJuliaCondaJupyterCapabilities() {
    let juliaHome = Deno.env.get("JULIA_HOME");
    if (!juliaHome) {
        const home = isWindows3() ? Deno.env.get("USERPROFILE") : Deno.env.get("HOME");
        if (home) {
            juliaHome = join2(home, ".julia");
        }
    }
    if (juliaHome) {
        const juliaCondaPath = join2(juliaHome, "conda", "3");
        const bin = isWindows3() ? [
            "python3.exe",
            "python.exe"
        ] : [
            join2("bin", "python3"),
            join2("bin", "python")
        ];
        for (const pythonBin of bin){
            const juliaPython = join2(juliaCondaPath, pythonBin);
            if (existsSync(juliaPython)) {
                const caps = await getJupyterCapabilities([
                    juliaPython
                ]);
                if (caps?.jupyter_core) {
                    return caps;
                }
            }
        }
        for (const path of expandGlobSync(join2(juliaCondaPath, "**", "python*"), {
            globstar: true
        })){
            const file = Deno.statSync(path.path);
            if (!(file.isFile && file.mode && file.mode & 0o100)) {
                continue;
            }
            const caps = await getJupyterCapabilities([
                path.path
            ]);
            if (caps?.jupyter_core) {
                return caps;
            }
        }
    }
}
async function getQuartoJupyterCapabilities() {
    let quartoJupyter = Deno.env.get("QUARTO_PYTHON");
    if (quartoJupyter) {
        if (!isAbsolute2(quartoJupyter)) {
            const path = await which(quartoJupyter);
            if (path) {
                quartoJupyter = path;
            }
        }
        if (existsSync(quartoJupyter)) {
            let quartoJupyterBin = quartoJupyter;
            if (Deno.statSync(quartoJupyter).isDirectory) {
                const bin = [
                    "python3",
                    "python",
                    "python3.exe",
                    "python.exe"
                ].find((bin)=>{
                    return existsSync(join2(quartoJupyter, bin));
                });
                if (bin) {
                    quartoJupyterBin = join2(quartoJupyter, bin);
                } else {
                    quartoJupyterBin = undefined;
                }
            }
            if (quartoJupyterBin) {
                return getJupyterCapabilities([
                    quartoJupyterBin
                ]);
            }
        } else {
            warnOnce(`Specified QUARTO_PYTHON '${quartoJupyter}' does not exist`);
        }
        warnOnce(`No python binary found in specified QUARTO_PYTHON location '${quartoJupyter}'`);
        return undefined;
    } else {
        return undefined;
    }
}
async function jupyterCapabilitiesNoConda() {
    const caps = await getQuartoJupyterCapabilities();
    if (caps && !caps.conda) {
        return caps;
    }
    if (isWindows3()) {
        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(join2(dir, "pyvenv.cfg")) || existsSync(join2(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 result1 = await execProcess({
            cmd: [
                ...cmd,
                resourcePath("capabilities/jupyter.py")
            ],
            stdout: "piped",
            stderr: "piped",
            env: {
                ["PYDEVD_DISABLE_FILE_VALIDATION"]: "1"
            }
        });
        if (result1.success && result1.stdout) {
            const caps = readYamlFromString(result1.stdout);
            if (caps.versionMajor >= 3) {
                caps.pyLauncher = pyLauncher;
                return caps;
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    } catch  {
        return undefined;
    }
}
async function pythonExec(kernelspec, binaryOnly = false) {
    const caps = await jupyterCapabilities(kernelspec);
    return pythonExecForCaps(caps, binaryOnly);
}
function pythonExecForCaps(caps, binaryOnly = false) {
    if (caps?.pyLauncher) {
        return [
            "py"
        ];
    } else if (isWindows3()) {
        return [
            binaryOnly ? "python" : caps?.executable || "python"
        ];
    } else {
        return [
            binaryOnly ? "python3" : caps?.executable || "python3"
        ];
    }
}
async function jupyterExec(kernelspec) {
    return [
        ...await pythonExec(kernelspec),
        "-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 jupyterKernelspecForLanguage(language) {
    const kernelspecs = await jupyterKernelspecs();
    const defaultResolver = ()=>{
        for (const kernelspec of kernelspecs.values()){
            if (kernelspec.language === language) {
                return kernelspec;
            }
        }
    };
    const python = ()=>{
        const env = Deno.env.get("VIRTUAL_ENV");
        if (env) {
            for (const kernelspec of kernelspecs.values()){
                if (kernelspec.language === "python" && kernelspec.path?.includes(env)) {
                    debug("Preferring a venv-based python kernel at " + kernelspec.path);
                    return kernelspec;
                }
            }
        }
        return defaultResolver();
    };
    const resolvers = {
        python
    };
    const resolver = resolvers[language] || defaultResolver;
    return resolver();
}
async function jupyterKernelspec(name) {
    const kernelspecs = await jupyterKernelspecs();
    return kernelspecs.get(name);
}
let kJupyterKernelspecs = undefined;
async function jupyterKernelspecs() {
    if (kJupyterKernelspecs) {
        return kJupyterKernelspecs;
    }
    kJupyterKernelspecs = await computeJupyterKernelspecs();
    return kJupyterKernelspecs;
}
async function computeJupyterKernelspecs() {
    try {
        const result1 = await execProcess({
            cmd: [
                ...await jupyterExec(),
                "--paths",
                "--json"
            ],
            stdout: "piped",
            stderr: "piped"
        });
        if (result1.success) {
            const kernelmap = new Map();
            const dataPaths = JSON.parse(result1.stdout).data;
            for (const path of dataPaths){
                if (!existsSync(path)) {
                    continue;
                }
                const kernels = join2(path, "kernels");
                if (!existsSync(kernels)) {
                    continue;
                }
                for (const walk of walkSync(kernels, {
                    maxDepth: 1
                })){
                    if (walk.path === kernels || !walk.isDirectory) {
                        continue;
                    }
                    const kernelConfig = join2(walk.path, "kernel.json");
                    if (existsSync(kernelConfig)) {
                        const config = JSON.parse(Deno.readTextFileSync(kernelConfig));
                        const name = basename2(walk.path);
                        kernelmap.set(name, {
                            name,
                            language: config.language,
                            display_name: config.display_name,
                            path: walk.path
                        });
                    }
                }
            }
            if (kernelmap.size > 0) {
                return kernelmap;
            } else {
                return kDefaultKernelspecs;
            }
        } else {
            return kDefaultKernelspecs;
        }
    } catch (e) {
        debug("Error reading kernelspecs: " + e.message);
        return kDefaultKernelspecs;
    }
}
function jupyterDefaultPythonKernelspec() {
    return {
        "display_name": "Python 3",
        "language": "python",
        "name": "python3"
    };
}
const kDefaultKernelspecs = new Map();
kDefaultKernelspecs.set("python3", jupyterDefaultPythonKernelspec());
var __makeTemplateObject = function(cooked, raw) {
    if (Object.defineProperty) {
        Object.defineProperty(cooked, "raw", {
            value: raw
        });
    } else {
        cooked.raw = raw;
    }
    return cooked;
};
var PacketKind;
(function(PacketKind2) {
    PacketKind2[PacketKind2["EOS"] = 0] = "EOS";
    PacketKind2[PacketKind2["Text"] = 1] = "Text";
    PacketKind2[PacketKind2["Incomplete"] = 2] = "Incomplete";
    PacketKind2[PacketKind2["ESC"] = 3] = "ESC";
    PacketKind2[PacketKind2["Unknown"] = 4] = "Unknown";
    PacketKind2[PacketKind2["SGR"] = 5] = "SGR";
    PacketKind2[PacketKind2["OSCURL"] = 6] = "OSCURL";
})(PacketKind || (PacketKind = {}));
class AnsiUp {
    constructor(){
        this.VERSION = "6.0.2";
        this.setup_palettes();
        this._use_classes = false;
        this.bold = false;
        this.faint = false;
        this.italic = false;
        this.underline = false;
        this.fg = this.bg = null;
        this._buffer = "";
        this._url_allowlist = {
            http: 1,
            https: 1
        };
        this._escape_html = true;
        this.boldStyle = "font-weight:bold";
        this.faintStyle = "opacity:0.7";
        this.italicStyle = "font-style:italic";
        this.underlineStyle = "text-decoration:underline";
    }
    set use_classes(arg) {
        this._use_classes = arg;
    }
    get use_classes() {
        return this._use_classes;
    }
    set url_allowlist(arg) {
        this._url_allowlist = arg;
    }
    get url_allowlist() {
        return this._url_allowlist;
    }
    set escape_html(arg) {
        this._escape_html = arg;
    }
    get escape_html() {
        return this._escape_html;
    }
    set boldStyle(arg) {
        this._boldStyle = arg;
    }
    get boldStyle() {
        return this._boldStyle;
    }
    set faintStyle(arg) {
        this._faintStyle = arg;
    }
    get faintStyle() {
        return this._faintStyle;
    }
    set italicStyle(arg) {
        this._italicStyle = arg;
    }
    get italicStyle() {
        return this._italicStyle;
    }
    set underlineStyle(arg) {
        this._underlineStyle = arg;
    }
    get underlineStyle() {
        return this._underlineStyle;
    }
    setup_palettes() {
        this.ansi_colors = [
            [
                {
                    rgb: [
                        0,
                        0,
                        0
                    ],
                    class_name: "ansi-black"
                },
                {
                    rgb: [
                        187,
                        0,
                        0
                    ],
                    class_name: "ansi-red"
                },
                {
                    rgb: [
                        0,
                        187,
                        0
                    ],
                    class_name: "ansi-green"
                },
                {
                    rgb: [
                        187,
                        187,
                        0
                    ],
                    class_name: "ansi-yellow"
                },
                {
                    rgb: [
                        0,
                        0,
                        187
                    ],
                    class_name: "ansi-blue"
                },
                {
                    rgb: [
                        187,
                        0,
                        187
                    ],
                    class_name: "ansi-magenta"
                },
                {
                    rgb: [
                        0,
                        187,
                        187
                    ],
                    class_name: "ansi-cyan"
                },
                {
                    rgb: [
                        255,
                        255,
                        255
                    ],
                    class_name: "ansi-white"
                }
            ],
            [
                {
                    rgb: [
                        85,
                        85,
                        85
                    ],
                    class_name: "ansi-bright-black"
                },
                {
                    rgb: [
                        255,
                        85,
                        85
                    ],
                    class_name: "ansi-bright-red"
                },
                {
                    rgb: [
                        0,
                        255,
                        0
                    ],
                    class_name: "ansi-bright-green"
                },
                {
                    rgb: [
                        255,
                        255,
                        85
                    ],
                    class_name: "ansi-bright-yellow"
                },
                {
                    rgb: [
                        85,
                        85,
                        255
                    ],
                    class_name: "ansi-bright-blue"
                },
                {
                    rgb: [
                        255,
                        85,
                        255
                    ],
                    class_name: "ansi-bright-magenta"
                },
                {
                    rgb: [
                        85,
                        255,
                        255
                    ],
                    class_name: "ansi-bright-cyan"
                },
                {
                    rgb: [
                        255,
                        255,
                        255
                    ],
                    class_name: "ansi-bright-white"
                }
            ]
        ];
        this.palette_256 = [];
        this.ansi_colors.forEach((palette)=>{
            palette.forEach((rec)=>{
                this.palette_256.push(rec);
            });
        });
        let levels = [
            0,
            95,
            135,
            175,
            215,
            255
        ];
        for(let r = 0; r < 6; ++r){
            for(let g = 0; g < 6; ++g){
                for(let b = 0; b < 6; ++b){
                    let col = {
                        rgb: [
                            levels[r],
                            levels[g],
                            levels[b]
                        ],
                        class_name: "truecolor"
                    };
                    this.palette_256.push(col);
                }
            }
        }
        let grey_level = 8;
        for(let i1 = 0; i1 < 24; ++i1, grey_level += 10){
            let gry = {
                rgb: [
                    grey_level,
                    grey_level,
                    grey_level
                ],
                class_name: "truecolor"
            };
            this.palette_256.push(gry);
        }
    }
    escape_txt_for_html(txt) {
        if (!this._escape_html) return txt;
        return txt.replace(/[&<>"']/gm, (str)=>{
            if (str === "&") return "&amp;";
            if (str === "<") return "&lt;";
            if (str === ">") return "&gt;";
            if (str === '"') return "&quot;";
            if (str === "'") return "&#x27;";
        });
    }
    append_buffer(txt) {
        var str = this._buffer + txt;
        this._buffer = str;
    }
    get_next_packet() {
        var pkt = {
            kind: PacketKind.EOS,
            text: "",
            url: ""
        };
        var len = this._buffer.length;
        if (len == 0) return pkt;
        var pos = this._buffer.indexOf("");
        if (pos == -1) {
            pkt.kind = PacketKind.Text;
            pkt.text = this._buffer;
            this._buffer = "";
            return pkt;
        }
        if (pos > 0) {
            pkt.kind = PacketKind.Text;
            pkt.text = this._buffer.slice(0, pos);
            this._buffer = this._buffer.slice(pos);
            return pkt;
        }
        if (pos == 0) {
            if (len < 3) {
                pkt.kind = PacketKind.Incomplete;
                return pkt;
            }
            var next_char = this._buffer.charAt(1);
            if (next_char != "[" && next_char != "]" && next_char != "(") {
                pkt.kind = PacketKind.ESC;
                pkt.text = this._buffer.slice(0, 1);
                this._buffer = this._buffer.slice(1);
                return pkt;
            }
            if (next_char == "[") {
                if (!this._csi_regex) {
                    this._csi_regex = rgx(templateObject_1 || (templateObject_1 = __makeTemplateObject([
                        "\n                        ^                           # beginning of line\n                                                    #\n                                                    # First attempt\n                        (?:                         # legal sequence\n                          [                      # CSI\n                          ([<-?]?)              # private-mode char\n                          ([d;]*)                    # any digits or semicolons\n                          ([ -/]?               # an intermediate modifier\n                          [@-~])                # the command\n                        )\n                        |                           # alternate (second attempt)\n                        (?:                         # illegal sequence\n                          [                      # CSI\n                          [ -~]*                # anything legal\n                          ([\0-:])              # anything illegal\n                        )\n                    "
                    ], [
                        "\n                        ^                           # beginning of line\n                                                    #\n                                                    # First attempt\n                        (?:                         # legal sequence\n                          \\x1b\\[                      # CSI\n                          ([\\x3c-\\x3f]?)              # private-mode char\n                          ([\\d;]*)                    # any digits or semicolons\n                          ([\\x20-\\x2f]?               # an intermediate modifier\n                          [\\x40-\\x7e])                # the command\n                        )\n                        |                           # alternate (second attempt)\n                        (?:                         # illegal sequence\n                          \\x1b\\[                      # CSI\n                          [\\x20-\\x7e]*                # anything legal\n                          ([\\x00-\\x1f:])              # anything illegal\n                        )\n                    "
                    ])));
                }
                let match = this._buffer.match(this._csi_regex);
                if (match === null) {
                    pkt.kind = PacketKind.Incomplete;
                    return pkt;
                }
                if (match[4]) {
                    pkt.kind = PacketKind.ESC;
                    pkt.text = this._buffer.slice(0, 1);
                    this._buffer = this._buffer.slice(1);
                    return pkt;
                }
                if (match[1] != "" || match[3] != "m") pkt.kind = PacketKind.Unknown;
                else pkt.kind = PacketKind.SGR;
                pkt.text = match[2];
                var rpos = match[0].length;
                this._buffer = this._buffer.slice(rpos);
                return pkt;
            } else if (next_char == "]") {
                if (len < 4) {
                    pkt.kind = PacketKind.Incomplete;
                    return pkt;
                }
                if (this._buffer.charAt(2) != "8" || this._buffer.charAt(3) != ";") {
                    pkt.kind = PacketKind.ESC;
                    pkt.text = this._buffer.slice(0, 1);
                    this._buffer = this._buffer.slice(1);
                    return pkt;
                }
                if (!this._osc_st) {
                    this._osc_st = rgxG(templateObject_2 || (templateObject_2 = __makeTemplateObject([
                        "\n                        (?:                         # legal sequence\n                          (\\)                    # ESC                           |                           # alternate\n                          (\x07)                      # BEL (what xterm did)\n                        )\n                        |                           # alternate (second attempt)\n                        (                           # illegal sequence\n                          [\0-]                 # anything illegal\n                          |                           # alternate\n                          [\b-]                 # anything illegal\n                          |                           # alternate\n                          [-]                 # anything illegal\n                        )\n                    "
                    ], [
                        "\n                        (?:                         # legal sequence\n                          (\\x1b\\\\)                    # ESC \\\n                          |                           # alternate\n                          (\\x07)                      # BEL (what xterm did)\n                        )\n                        |                           # alternate (second attempt)\n                        (                           # illegal sequence\n                          [\\x00-\\x06]                 # anything illegal\n                          |                           # alternate\n                          [\\x08-\\x1a]                 # anything illegal\n                          |                           # alternate\n                          [\\x1c-\\x1f]                 # anything illegal\n                        )\n                    "
                    ])));
                }
                this._osc_st.lastIndex = 0;
                {
                    let match2 = this._osc_st.exec(this._buffer);
                    if (match2 === null) {
                        pkt.kind = PacketKind.Incomplete;
                        return pkt;
                    }
                    if (match2[3]) {
                        pkt.kind = PacketKind.ESC;
                        pkt.text = this._buffer.slice(0, 1);
                        this._buffer = this._buffer.slice(1);
                        return pkt;
                    }
                }
                {
                    let match2 = this._osc_st.exec(this._buffer);
                    if (match2 === null) {
                        pkt.kind = PacketKind.Incomplete;
                        return pkt;
                    }
                    if (match2[3]) {
                        pkt.kind = PacketKind.ESC;
                        pkt.text = this._buffer.slice(0, 1);
                        this._buffer = this._buffer.slice(1);
                        return pkt;
                    }
                }
                if (!this._osc_regex) {
                    this._osc_regex = rgx(templateObject_3 || (templateObject_3 = __makeTemplateObject([
                        "\n                        ^                           # beginning of line\n                                                    #\n                        ]8;                    # OSC Hyperlink\n                        [ -:<-~]*       # params (excluding ;)\n                        ;                           # end of params\n                        ([!-~]{0,512})        # URL capture\n                        (?:                         # ST\n                          (?:\\)                  # ESC                           |                           # alternate\n                          (?:\x07)                    # BEL (what xterm did)\n                        )\n                        ([ -~]+)              # TEXT capture\n                        ]8;;                   # OSC Hyperlink End\n                        (?:                         # ST\n                          (?:\\)                  # ESC                           |                           # alternate\n                          (?:\x07)                    # BEL (what xterm did)\n                        )\n                    "
                    ], [
                        "\n                        ^                           # beginning of line\n                                                    #\n                        \\x1b\\]8;                    # OSC Hyperlink\n                        [\\x20-\\x3a\\x3c-\\x7e]*       # params (excluding ;)\n                        ;                           # end of params\n                        ([\\x21-\\x7e]{0,512})        # URL capture\n                        (?:                         # ST\n                          (?:\\x1b\\\\)                  # ESC \\\n                          |                           # alternate\n                          (?:\\x07)                    # BEL (what xterm did)\n                        )\n                        ([\\x20-\\x7e]+)              # TEXT capture\n                        \\x1b\\]8;;                   # OSC Hyperlink End\n                        (?:                         # ST\n                          (?:\\x1b\\\\)                  # ESC \\\n                          |                           # alternate\n                          (?:\\x07)                    # BEL (what xterm did)\n                        )\n                    "
                    ])));
                }
                let match = this._buffer.match(this._osc_regex);
                if (match === null) {
                    pkt.kind = PacketKind.ESC;
                    pkt.text = this._buffer.slice(0, 1);
                    this._buffer = this._buffer.slice(1);
                    return pkt;
                }
                pkt.kind = PacketKind.OSCURL;
                pkt.url = match[1];
                pkt.text = match[2];
                var rpos = match[0].length;
                this._buffer = this._buffer.slice(rpos);
                return pkt;
            } else if (next_char == "(") {
                pkt.kind = PacketKind.Unknown;
                this._buffer = this._buffer.slice(3);
                return pkt;
            }
        }
    }
    ansi_to_html(txt) {
        this.append_buffer(txt);
        var blocks = [];
        while(true){
            var packet = this.get_next_packet();
            if (packet.kind == PacketKind.EOS || packet.kind == PacketKind.Incomplete) break;
            if (packet.kind == PacketKind.ESC || packet.kind == PacketKind.Unknown) continue;
            if (packet.kind == PacketKind.Text) blocks.push(this.transform_to_html(this.with_state(packet)));
            else if (packet.kind == PacketKind.SGR) this.process_ansi(packet);
            else if (packet.kind == PacketKind.OSCURL) blocks.push(this.process_hyperlink(packet));
        }
        return blocks.join("");
    }
    with_state(pkt) {
        return {
            bold: this.bold,
            faint: this.faint,
            italic: this.italic,
            underline: this.underline,
            fg: this.fg,
            bg: this.bg,
            text: pkt.text
        };
    }
    process_ansi(pkt) {
        let sgr_cmds = pkt.text.split(";");
        while(sgr_cmds.length > 0){
            let sgr_cmd_str = sgr_cmds.shift();
            let num = parseInt(sgr_cmd_str, 10);
            if (isNaN(num) || num === 0) {
                this.fg = null;
                this.bg = null;
                this.bold = false;
                this.faint = false;
                this.italic = false;
                this.underline = false;
            } else if (num === 1) {
                this.bold = true;
            } else if (num === 2) {
                this.faint = true;
            } else if (num === 3) {
                this.italic = true;
            } else if (num === 4) {
                this.underline = true;
            } else if (num === 21) {
                this.bold = false;
            } else if (num === 22) {
                this.faint = false;
                this.bold = false;
            } else if (num === 23) {
                this.italic = false;
            } else if (num === 24) {
                this.underline = false;
            } else if (num === 39) {
                this.fg = null;
            } else if (num === 49) {
                this.bg = null;
            } else if (num >= 30 && num < 38) {
                this.fg = this.ansi_colors[0][num - 30];
            } else if (num >= 40 && num < 48) {
                this.bg = this.ansi_colors[0][num - 40];
            } else if (num >= 90 && num < 98) {
                this.fg = this.ansi_colors[1][num - 90];
            } else if (num >= 100 && num < 108) {
                this.bg = this.ansi_colors[1][num - 100];
            } else if (num === 38 || num === 48) {
                if (sgr_cmds.length > 0) {
                    let is_foreground = num === 38;
                    let mode_cmd = sgr_cmds.shift();
                    if (mode_cmd === "5" && sgr_cmds.length > 0) {
                        let palette_index = parseInt(sgr_cmds.shift(), 10);
                        if (palette_index >= 0 && palette_index <= 255) {
                            if (is_foreground) this.fg = this.palette_256[palette_index];
                            else this.bg = this.palette_256[palette_index];
                        }
                    }
                    if (mode_cmd === "2" && sgr_cmds.length > 2) {
                        let r = parseInt(sgr_cmds.shift(), 10);
                        let g = parseInt(sgr_cmds.shift(), 10);
                        let b = parseInt(sgr_cmds.shift(), 10);
                        if (r >= 0 && r <= 255 && g >= 0 && g <= 255 && b >= 0 && b <= 255) {
                            let c = {
                                rgb: [
                                    r,
                                    g,
                                    b
                                ],
                                class_name: "truecolor"
                            };
                            if (is_foreground) this.fg = c;
                            else this.bg = c;
                        }
                    }
                }
            }
        }
    }
    transform_to_html(fragment) {
        let txt = fragment.text;
        if (txt.length === 0) return txt;
        txt = this.escape_txt_for_html(txt);
        if (!fragment.bold && !fragment.italic && !fragment.underline && fragment.fg === null && fragment.bg === null) return txt;
        let styles = [];
        let classes = [];
        let fg = fragment.fg;
        let bg = fragment.bg;
        if (fragment.bold) styles.push(this._boldStyle);
        if (fragment.faint) styles.push(this._faintStyle);
        if (fragment.italic) styles.push(this._italicStyle);
        if (fragment.underline) styles.push(this._underlineStyle);
        if (!this._use_classes) {
            if (fg) styles.push(`color:rgb(${fg.rgb.join(",")})`);
            if (bg) styles.push(`background-color:rgb(${bg.rgb})`);
        } else {
            if (fg) {
                if (fg.class_name !== "truecolor") {
                    classes.push(`${fg.class_name}-fg`);
                } else {
                    styles.push(`color:rgb(${fg.rgb.join(",")})`);
                }
            }
            if (bg) {
                if (bg.class_name !== "truecolor") {
                    classes.push(`${bg.class_name}-bg`);
                } else {
                    styles.push(`background-color:rgb(${bg.rgb.join(",")})`);
                }
            }
        }
        let class_string = "";
        let style_string = "";
        if (classes.length) class_string = ` class="${classes.join(" ")}"`;
        if (styles.length) style_string = ` style="${styles.join(";")}"`;
        return `<span${style_string}${class_string}>${txt}</span>`;
    }
    process_hyperlink(pkt) {
        let parts = pkt.url.split(":");
        if (parts.length < 1) return "";
        if (!this._url_allowlist[parts[0]]) return "";
        let result1 = `<a href="${this.escape_txt_for_html(pkt.url)}">${this.escape_txt_for_html(pkt.text)}</a>`;
        return result1;
    }
}
function rgx(tmplObj, ...subst) {
    let regexText = tmplObj.raw[0];
    let wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm;
    let txt2 = regexText.replace(wsrgx, "");
    return new RegExp(txt2);
}
function rgxG(tmplObj, ...subst) {
    let regexText = tmplObj.raw[0];
    let wsrgx = /^\s+|\s+\n|\s*#[\s\S]*?\n|\n/gm;
    let txt2 = regexText.replace(wsrgx, "");
    return new RegExp(txt2, "g");
}
var templateObject_1, templateObject_2, templateObject_3;
function hasAnsiEscapeCodes(str) {
    return !!str.match(/\x1b\[\d+(?:;\d+)*m/);
}
async function convertToHtmlSpans(str) {
    const a = new AnsiUp();
    a.use_classes = true;
    const html = a.ansi_to_html(str);
    const doc = await parseHtml(`<pre>${html}</pre>`);
    for (const node of doc.querySelectorAll("span")){
        const el = node;
        if (el.getAttribute("style") === "font-weight:bold") {
            el.removeAttribute("style");
            el.classList.add("ansi-bold");
        }
    }
    return doc.querySelector("pre").innerHTML;
}
const kProjectType = "type";
const kProjectTitle = "title";
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 kProjectWatchInputs = "watch-inputs";
const kProject404File = "404.html";
const kCollapseLevel = "collapse-level";
const kCollapseBelow = "collapse-below";
const kLogoAlt = "logo-alt";
const kLogoHref = "logo-href";
const kSidebarMenus = "sidebar-menus";
function isPdfOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return format === "pdf" || format === "beamer";
}
function isLatexOutput(format) {
    return [
        "pdf",
        "latex",
        "beamer"
    ].includes(format.to || "");
}
function isTypstOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return format === "typst";
}
function isBeamerOutput(format) {
    return [
        "beamer"
    ].includes(format.to || "");
}
function isEpubOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return [
        "epub",
        "epub2",
        "epub3"
    ].includes(format || "");
}
function isDocxOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return format === "docx";
}
function isHtmlFileOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return isHtmlDocOutput(format) || isHtmlSlideOutput(format);
}
function isHtmlOutput(format, strict) {
    if (typeof format !== "string") {
        format = format?.to;
    }
    format = format || "html";
    if (isHtmlDocOutput(format) || isHtmlDashboardOutput(format)) {
        return true;
    } else if (!strict) {
        return isHtmlSlideOutput(format) || isEpubOutput(format);
    } else {
        return false;
    }
}
function isHtmlDocOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return [
        "html",
        "html4",
        "html5"
    ].includes(format);
}
function isHtmlSlideOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return [
        "s5",
        "dzslides",
        "slidy",
        "slideous",
        "revealjs"
    ].includes(format);
}
function isHtmlDashboardOutput(format) {
    return format === "dashboard" || format?.endsWith("-dashboard");
}
function isJatsOutput(format) {
    if (typeof format !== "string") {
        format = format?.to || "html";
    }
    return [
        "jats",
        "jats_archiving",
        "jats_articleauthoring",
        "jats_publishing"
    ].find((formatStr)=>{
        return format.startsWith(formatStr);
    }) !== undefined;
}
function isPresentationOutput(format) {
    if (format.to) {
        return [
            "s5",
            "dzslides",
            "slidy",
            "slideous",
            "revealjs",
            "beamer",
            "pptx"
        ].some((to)=>format.to?.startsWith(to));
    } else {
        return false;
    }
}
function isRevealjsOutput(format) {
    if (typeof format !== "string") {
        format = format?.to;
    }
    format = format || "html";
    return format.startsWith("revealjs");
}
function isNativeOutput(format) {
    return isFormatTo(format, "native");
}
function isJsonOutput(format) {
    return isFormatTo(format, "json");
}
function isAstOutput(format) {
    return isNativeOutput(format) || isJsonOutput(format);
}
function isIpynbOutput(format) {
    return isFormatTo(format, "ipynb");
}
function isFormatTo(format, to) {
    return !!format.to && format.to.startsWith(to);
}
function isMarkdownOutput(format, flavors = [
    "markdown",
    "markdown_github",
    "markdown_mmd",
    "markdown_phpextra",
    "markdown_strict",
    "gfm",
    "commonmark",
    "commonmark_x",
    "markua"
]) {
    const to = format.identifier[kBaseFormat] || "html";
    return flavors.includes(to) || isIpynbOutput(format.pandoc);
}
function isHtmlCompatible(format) {
    return isHtmlOutput(format.pandoc) || isMarkdownOutput(format) && format.render[kPreferHtml] || isIpynbOutput(format.pandoc);
}
function isJavascriptCompatible(format) {
    return isHtmlCompatible(format) && !isEpubOutput(format.pandoc);
}
const jupyterCellSrcAsStr = (cell)=>{
    return typeof cell.source === "string" ? cell.source : cell.source.join("");
};
const jupyterCellSrcAsLines = (cell)=>{
    return typeof cell.source === "string" ? lines(cell.source) : cell.source;
};
async function jupyterCapabilitiesMessage(caps, indent = "") {
    const lines = [
        `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(", ");
        lines.push(`Kernels: ${kernels}`);
    }
    return lines.map((line)=>`${indent}${line}`).join("\n");
}
function jupyterInstallationMessage(caps, indent = "") {
    const lines = [
        "Jupyter is not available in this Python installation.",
        "Install with " + bold(`${caps.conda ? "conda" : pythonExecForCaps(caps, true).join(" ") + " -m pip"} install jupyter`)
    ];
    return lines.map((line)=>`${indent}${line}`).join("\n");
}
function jupyterUnactivatedEnvMessage(caps, indent = "") {
    for (const path of Deno.readDirSync(Deno.cwd())){
        if (path.isDirectory) {
            const targetPath = join2(Deno.cwd(), path.name);
            try {
                if (isEnvDir(targetPath)) {
                    try {
                        if (!pathWithForwardSlashes(caps.executable).startsWith(pathWithForwardSlashes(targetPath))) {
                            return indent + "There is an unactivated Python environment in " + bold(path.name) + ". Did you forget to activate it?";
                        }
                    } catch  {
                        return undefined;
                    }
                }
            } catch (err) {
                if (!(err instanceof Deno.errors.NotFound)) {
                    throw err;
                }
            }
        }
    }
    const kRequirementsTxt = "requirements.txt";
    const kEnvironmentYaml = "environment.yml";
    for (const envFile of [
        kRequirementsTxt,
        kEnvironmentYaml
    ]){
        if (existsSync(join2(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 lines = [
        "Unable to locate an installed version of Python 3.",
        "Install Python 3 from " + bold("https://www.python.org/downloads/")
    ];
    return lines.map((line)=>`${indent}${line}`).join("\n");
}
function fixupStreams(nb) {
    for (const cell of nb.cells){
        if (cell.cell_type !== "code" || cell.outputs === undefined) {
            continue;
        }
        if (cell.outputs.length === 0) {
            continue;
        }
        const newOutputs = [
            cell.outputs[0]
        ];
        let i1 = 1;
        while(i1 < cell.outputs.length){
            const prevOutput = newOutputs[newOutputs.length - 1];
            const thisOutput = cell.outputs[i1];
            if (thisOutput.output_type === "stream" && prevOutput.output_type === "stream" && thisOutput.name === prevOutput.name) {
                prevOutput.text = [
                    ...prevOutput.text ?? [],
                    ...thisOutput.text ?? []
                ];
            } else {
                newOutputs.push(thisOutput);
            }
            i1++;
        }
        cell.outputs = newOutputs;
    }
    return nb;
}
function fixupBokehCells(nb) {
    for (const cell of nb.cells){
        if (cell.cell_type === "code") {
            let needsFixup = false;
            for (const output of cell?.outputs ?? []){
                if (output.data === undefined) {
                    continue;
                }
                if (output.data["application/vnd.bokehjs_load.v0+json"]) {
                    needsFixup = true;
                }
            }
            if (!needsFixup) {
                continue;
            }
            const asTextHtml = (data)=>{
                if (data["text/html"]) {
                    return data["text/html"];
                }
                if (data["application/javascript"]) {
                    return [
                        "<script>",
                        ...data["application/javascript"],
                        "</script>"
                    ];
                }
                warn("jupyter-fixups: unknown data types " + JSON.stringify(Object.keys(data)));
                warn("will not fixup this bokeh cell.");
                throw new Error("");
            };
            try {
                const oldOutputs = cell.outputs;
                const newOutputs = [
                    {
                        metadata: {},
                        output_type: "display_data",
                        data: {
                            "text/html": [
                                asTextHtml(oldOutputs[0].data),
                                asTextHtml(oldOutputs[1].data),
                                asTextHtml(oldOutputs[2].data)
                            ].flat()
                        }
                    }
                ];
                for(let i1 = 3; i1 < oldOutputs.length; i1 += 2){
                    newOutputs.push({
                        metadata: {},
                        output_type: "display_data",
                        data: {
                            "text/html": [
                                asTextHtml(oldOutputs[i1].data),
                                asTextHtml(oldOutputs[i1 + 1].data)
                            ].flat()
                        }
                    });
                }
                cell.outputs = newOutputs;
            } catch  {
                warn("jupyter-fixup: cells without output data. Will not fixup bokeh cell");
            }
        }
    }
    return nb;
}
function asYamlText(yaml) {
    return stringify(yaml, {
        indent: 2,
        lineWidth: -1,
        sortKeys: false,
        skipInvalid: true
    });
}
function fixupFrontMatter(nb) {
    const nbLines = (lns)=>{
        return lns.map((line)=>line.endsWith("\n") ? line : `${line}\n`);
    };
    let partitioned;
    const frontMatterCellIndex = nb.cells.findIndex((cell)=>{
        if (cell.cell_type === "raw" || cell.cell_type === "markdown") {
            partitioned = partitionYamlFrontMatter(jupyterCellSrcAsStr(cell)) || undefined;
            if (partitioned) {
                cell.cell_type = "raw";
                return true;
            } else {
                return false;
            }
        }
    });
    const yaml = partitioned ? readYamlFromMarkdown(partitioned.yaml) : undefined;
    if (yaml?.title) {
        return nb;
    }
    let title;
    let currentCellIdx = 0;
    for (const cell of nb.cells){
        if (cell.cell_type === "markdown") {
            const { lines, headingText, contentBeforeHeading } = markdownWithExtractedHeading(nbLines(jupyterCellSrcAsLines(cell)).join(""));
            if (headingText && !contentBeforeHeading) {
                title = headingText;
                cell.source = nbLines(lines);
                break;
            } else if (currentCellIdx !== frontMatterCellIndex) {
                break;
            }
        }
        currentCellIdx++;
    }
    if (!title) {
        return nb;
    }
    if (yaml) {
        yaml[kTitle] = title;
        const yamlText = asYamlText(yaml);
        const frontMatterCell = nb.cells[frontMatterCellIndex];
        frontMatterCell.source = nbLines(lines(`---\n${yamlText}---\n\n${partitioned?.markdown || ""}`));
    } else {
        const yamlText = asYamlText({
            title
        });
        nb.cells.unshift({
            cell_type: "raw",
            source: nbLines(lines(`---\n${yamlText}---\n`)),
            metadata: {}
        });
    }
    return nb;
}
const defaultFixups = [
    fixupBokehCells,
    fixupFrontMatter,
    fixupStreams
];
const minimalFixups = [
    fixupBokehCells,
    fixupStreams
];
const bookFixups = minimalFixups;
function fixupJupyterNotebook(nb, fixups) {
    let nbFixups;
    if (fixups === "minimal") {
        nbFixups = minimalFixups;
    } else if (fixups === "default") {
        nbFixups = defaultFixups;
    } else {
        nbFixups = fixups;
    }
    for (const fixup of nbFixups){
        nb = fixup(nb);
    }
    return nb;
}
function userExpressionsFromCell(cell) {
    const userExpressions = (cell.metadata[kCellUserExpressions] || []).reduce((userExpressions, userExpression)=>{
        userExpressions.set(userExpression.expression, userExpression.result);
        return userExpressions;
    }, new Map());
    return userExpressions;
}
function asEscapedMarkdown(s) {
    const singleQuote = "'", doubleQuote = '"';
    if (s.startsWith(singleQuote) && s.endsWith(singleQuote) || s.startsWith(doubleQuote) && s.endsWith(doubleQuote)) {
        s = s.slice(1, -1);
        return s.replace(/\\/g, "\\\\").replace(/([\\`*_{}\[\]()>#+-.!])/g, "\\$1");
    } else {
        return s;
    }
}
function resolveUserExpressions(source, userExpressions, options) {
    const executeInlineCode = executeInlineCodeHandler(options.language, (expr)=>{
        if (options.execute.cache === true || options.execute.cache === "refresh") {
            throw new Error(`Inline expression encountered (${expr}). Inline expressions cannot be used with Jupyter Cache.`);
        }
        const result1 = userExpressions.get(expr);
        if (result1) {
            const mimeType = displayDataMimeType(result1, options);
            if (mimeType) {
                let data = result1.data[mimeType];
                if (Array.isArray(data)) {
                    data = data.map(String).join("");
                }
                switch(mimeType){
                    case kTextHtml:
                        return `${"`"}${data}${"`"}{=html}`;
                    case kTextLatex:
                        return `${"`"}${data}${"`"}{=tex}`;
                    case kTextMarkdown:
                        return `${data}`;
                    case kTextPlain:
                    default:
                        return asEscapedMarkdown(`${data}`);
                }
            }
        }
    });
    for(let i1 = 0; i1 < source.length; i1++){
        source[i1] = executeInlineCode(source[i1]);
    }
}
const kQuartoMimeType = "quarto_mimetype";
const kQuartoOutputOrder = "quarto_order";
const kQuartoOutputDisplay = "quarto_display";
const kJupyterNotebookExtensions = [
    ".ipynb"
];
function isJupyterNotebook(file) {
    return kJupyterNotebookExtensions.includes(extname2(file).toLowerCase());
}
const kJupyterCellInternalOptionKeys = [
    kEval,
    kEcho,
    kWarning,
    kError,
    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,
    kHtmlTableProcessing
];
const kJupyterCellOptionKeys = kJupyterCellInternalOptionKeys.concat([
    kLayoutAlign,
    kLayoutVAlign,
    kLayoutNcol,
    kLayoutNrow,
    kLayout,
    kTblCap,
    kTblColwidths
]);
const kJupyterCellStandardMetadataKeys = [
    kCellCollapsed,
    kCellAutoscroll,
    kCellDeletable,
    kCellFormat,
    kCellName
];
const kJupyterCellThirdPartyMetadataKeys = [
    kCellId,
    kCellColab,
    kCellColabType,
    kCellColbOutputId,
    kCellLinesToNext,
    kCellLanguage
];
const countTicks = (code)=>{
    const countLeadingTicks = (s)=>{
        const m = s.match(/^\s*`+/);
        if (m) {
            return m[0].length;
        } else {
            return 0;
        }
    };
    return Math.max(0, ...code.map((s)=>countLeadingTicks(s)));
};
const ticksForCode = (code)=>{
    const n = Math.max(3, countTicks(code) + 1);
    return "`".repeat(n);
};
async function quartoMdToJupyter(markdown, includeIds, project) {
    const [kernelspec, metadata] = await jupyterKernelspecFromMarkdown(markdown, project);
    const nb = {
        cells: [],
        metadata: {
            kernelspec,
            ...metadata
        },
        nbformat: 4,
        nbformat_minor: includeIds ? 5 : 4
    };
    const yamlRegEx = /^---\s*$/;
    /^\s*```+\s*\{([a-zA-Z0-9_]+)( *[ ,].*)?\}\s*$/;
    const startCodeCellRegEx = new RegExp("^(\\s*)(```+)\\s*\\{" + kernelspec.language.toLowerCase() + "( *[ ,].*)?\\}\\s*$");
    const startCodeRegEx = /^(\s*)```/;
    const endCodeRegEx = (indent = "", backtickCount = 0)=>{
        return new RegExp("^" + indent + "`".repeat(backtickCount) + "\\s*$");
    };
    const inputContent = markdown;
    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(jupyterCellSrcAsStr(cell));
                if (yaml.jupyter) {
                    delete yaml.jupyter;
                    if (Object.keys(yaml).length > 0) {
                        const yamlFrontMatter = trimEmptyLines(lines(stringify(yaml, {
                            indent: 2,
                            lineWidth: -1,
                            sortKeys: false,
                            skipInvalid: true
                        })));
                        cell.source = [
                            "---\n",
                            ...yamlFrontMatter.map((line)=>line + "\n"),
                            "---"
                        ];
                    } else {
                        cell.source = [];
                    }
                }
            } else if (cell_type === "code") {
                const cellSrcLines = typeof cell.source === "string" ? lines(cell.source) : cell.source;
                const { yaml, source } = partitionCellOptions(kernelspec.language.toLowerCase(), cellSrcLines);
                if (yaml && !Array.isArray(yaml) && typeof yaml === "object") {
                    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 = [];
            }
            const cellSrcLines = typeof cell.source === "string" ? lines(cell.source) : cell.source;
            cell.source = trimEmptyLines(cellSrcLines);
            if (cell.source.length > 0) {
                nb.cells.push(cell);
            }
            lineBuffer.splice(0, lineBuffer.length);
        }
    };
    let parsedFrontMatter = false, inYaml = false, inCodeCell = false, inCode = false, backtickCount = 0;
    let currentLine = 0;
    const contentLines = lines(inputContent);
    for(currentLine = 0; currentLine < contentLines.length; ++currentLine){
        const line = contentLines[currentLine];
        if (yamlRegEx.test(line) && !inCodeCell && !inCode && contentLines[currentLine + 1]?.trim() !== "") {
            if (inYaml) {
                lineBuffer.push(line);
                flushLineBuffer("raw", !parsedFrontMatter);
                parsedFrontMatter = true;
                inYaml = false;
            } else {
                flushLineBuffer("markdown");
                lineBuffer.push(line);
                inYaml = true;
            }
        } else if (!inCodeCell && startCodeCellRegEx.test(line)) {
            flushLineBuffer("markdown");
            inCodeCell = true;
            codeIndent = line.match(startCodeCellRegEx)[1];
            backtickCount = line.match(startCodeCellRegEx)[2].length;
        } else if (inCodeCell && endCodeRegEx(codeIndent, backtickCount).test(line)) {
            if (inCodeCell) {
                inCodeCell = false;
                flushLineBuffer("code");
                codeIndent = "";
            } else {
                inCode = !inCode;
                codeIndent = "";
                lineBuffer.push(line);
            }
        } else if (!inCodeCell && startCodeRegEx.test(line)) {
            codeIndent = line.match(startCodeRegEx)[1];
            inCode = true;
            lineBuffer.push(line);
        } else {
            lineBuffer.push(line);
        }
    }
    flushLineBuffer("markdown");
    return nb;
}
async function jupyterKernelspecFromMarkdown(markdown, project) {
    const config = project?.config;
    const yaml = config ? mergeConfigs(config, readYamlFromMarkdown(markdown)) : readYamlFromMarkdown(markdown);
    const yamlJupyter = yaml.jupyter;
    if (!yamlJupyter) {
        const languages = languagesInMarkdown(markdown);
        languages.add("python");
        for (const language of languages){
            const kernelspec = await jupyterKernelspecForLanguage(language);
            if (kernelspec) {
                return [
                    kernelspec,
                    {}
                ];
            }
        }
        const kernelspecs = await jupyterKernelspecs();
        return Promise.reject(new Error(`No kernel found for any language checked (${Array.from(languages).join(", ")}) in any of the kernelspecs checked (${Array.from(kernelspecs.values()).map((k)=>k.name).join(", ")}).`));
    } else 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. Known kernels: ${Array.from((await jupyterKernelspecs()).values()).map((kernel)=>kernel.name).join(", ")}. Run 'quarto check jupyter' with your python environment activated to check python version used.`));
        }
    } 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. Known kernels: ${Array.from((await jupyterKernelspecs()).values()).map((kernel)=>kernel.name).join(", ")}. Run 'quarto check jupyter' with your python environment activated to check python version used.`));
            }
        } 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);
    return jupyterFromJSON(nbContents);
}
function jupyterFromJSON(nbContents) {
    const nbJSON = JSON.parse(nbContents);
    const nb = nbJSON;
    if (!nb.metadata.kernelspec?.language) {
        if (nb.metadata.kernelspec) {
            nb.metadata.kernelspec.language = nbJSON.metadata.language_info?.name;
            if (!nb.metadata.kernelspec.language && nb.metadata.kernelspec.name?.includes("python")) {
                nb.metadata.kernelspec.language = "python";
            }
        } else {
            nb.metadata.kernelspec = jupyterDefaultPythonKernelspec();
        }
    }
    if (!nb.metadata.kernelspec.language) {
        throw new Error("No language set for Jupyter notebook");
    }
    if (!nb.cells) {
        throw new Error("No cells available in Jupyter notebook");
    }
    return nb;
}
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 = normalizePath(input);
    const files_dir = join2(dirname2(input), inputFilesDir(input));
    const figures_dir = join2(files_dir, figuresDir(to));
    ensureDirSync(figures_dir);
    let supporting_dir = files_dir;
    for (const walk of walkSync(join2(files_dir), {
        maxDepth: 1
    })){
        if (walk.path !== files_dir && walk.path !== figures_dir) {
            supporting_dir = figures_dir;
            break;
        }
    }
    const base_dir = dirname2(input);
    return {
        base_dir,
        files_dir: pathWithForwardSlashes(relative2(base_dir, files_dir)),
        figures_dir: pathWithForwardSlashes(relative2(base_dir, figures_dir)),
        supporting_dir: pathWithForwardSlashes(relative2(base_dir, supporting_dir))
    };
}
async function jupyterToMarkdown(nb, options) {
    const project = options.executeOptions.project;
    const projType = project?.config?.project?.[kProjectType];
    if (projType === "book") {
        nb = fixupJupyterNotebook(nb, bookFixups);
    } else if (project?.isSingleFile) {
        nb = fixupJupyterNotebook(nb, options.fixups || "default");
    } else if (project?.config?.title !== undefined && (projType === "default" || projType === undefined)) {
        nb = fixupJupyterNotebook(nb, minimalFixups);
    } else {
        nb = fixupJupyterNotebook(nb, options.fixups || "default");
    }
    const isHtml = options.toHtml && !options.toIpynb;
    const dependencies = isHtml ? extractJupyterWidgetDependencies(nb) : undefined;
    const htmlPreserve = isHtml ? removeAndPreserveHtml(nb) : undefined;
    const cellOutputs = [];
    const validateCellLabel = cellLabelValidator();
    let codeCellIndex = 0;
    let frontMatter = undefined;
    for(let i1 = 0; i1 < nb.cells.length; i1++){
        const md = [];
        const cell = jupyterCellWithOptions(i1, nb.metadata.kernelspec.language.toLowerCase(), nb.cells[i1]);
        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":
                {
                    const markdownOptions = {
                        ...options
                    };
                    if (frontMatter === undefined) {
                        frontMatter = partitionYamlFrontMatter(jupyterCellSrcAsStr(cell))?.yaml;
                        if (frontMatter) {
                            markdownOptions.preserveCellMetadata = false;
                        }
                    }
                    md.push(...mdFromContentCell(cell, markdownOptions));
                }
                break;
            case "raw":
                md.push(...mdFromRawCell(cell, options));
                break;
            case "code":
                md.push(...await 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");
        cellOutputs.push({
            id: cell.id,
            markdown: md.join(""),
            metadata: cell.metadata,
            options: cell.options
        });
    }
    let notebookOutputs = undefined;
    if (options.toIpynb) {
        const md = [];
        md.push("---\n");
        const widgets = nb.metadata.widgets ? encodeBase64(JSON.stringify(nb.metadata.widgets)) : undefined;
        const jupyterMetadata = {
            jupyter: {
                ...nb.metadata,
                widgets
            }
        };
        const yamlText = stringify(jupyterMetadata, {
            indent: 2,
            lineWidth: -1,
            sortKeys: false,
            skipInvalid: true
        });
        md.push(yamlText);
        md.push("---\n");
        notebookOutputs = {
            suffix: md.join("")
        };
    }
    return {
        cellOutputs,
        notebookOutputs,
        dependencies,
        htmlPreserve
    };
}
function jupyterCellWithOptions(index, language, cell) {
    const { yaml, optionsSource, source } = partitionCellOptions(language, jupyterCellSrcAsLines(cell));
    const metadataOptions = kJupyterCellOptionKeys.reduce((options, key)=>{
        if (cell.metadata[key] !== undefined) {
            options[key] = cell.metadata[key];
        }
        return options;
    }, {});
    const explicitOptions = {
        ...metadataOptions,
        ...yaml
    };
    [
        kLayout,
        kTblColwidths
    ].forEach((option)=>{
        if (explicitOptions[option] && typeof explicitOptions[option] !== "string") {
            explicitOptions[option] = JSON.stringify(explicitOptions[option]);
        }
    });
    const tags = cell.metadata.tags;
    const tagOptions = tagsToOptions(tags || []);
    const options = {
        ...tagOptions,
        ...explicitOptions
    };
    const cellId = (cell)=>{
        if (options && options[kCellLabel] && typeof options[kCellLabel] === "string") {
            return `cell-${options[kCellLabel]}`;
        } else if (cell.id) {
            return cell.id;
        } else {
            return `cell-${index}`;
        }
    };
    return {
        ...cell,
        id: cellId(cell),
        source,
        optionsSource,
        options
    };
}
function jupyterCellOptionsAsComment(language, options, stringifyOptions) {
    if (Object.keys(options).length > 0) {
        const cellYaml = stringify(options, {
            indent: 2,
            lineWidth: -1,
            sortKeys: false,
            skipInvalid: true,
            ...stringifyOptions
        });
        const commentChars = langCommentChars1(language);
        const yamlOutput = trimEmptyLines(lines(cellYaml)).map((line)=>{
            line = optionCommentPrefix(commentChars[0]) + line + optionCommentSuffix(commentChars[1]);
            return line + "\n";
        });
        return yamlOutput;
    } else {
        return [];
    }
}
function mdFromContentCell(cell, options) {
    const contentCellEnvelope = createCellEnvelope([
        "cell",
        "markdown"
    ], options);
    const source = __VIRTUAL_FILE107(cell.source);
    if (options && source) {
        const userExpressions = userExpressionsFromCell(cell);
        resolveUserExpressions(source, userExpressions, options);
    }
    if (options && cell.attachments && source) {
        Object.keys(cell.attachments).forEach((file, index)=>{
            const attachment = cell.attachments[file];
            for (const mimeType of Object.keys(attachment)){
                if (extensionForMimeImageType(mimeType, undefined)) {
                    const imageFile = options.assets.figures_dir + `/${cell.id}-${index + 1}-${file}`;
                    const outputFile = join2(options.assets.base_dir, imageFile);
                    ensureDirSync(dirname2(outputFile));
                    const data = attachment[mimeType];
                    const imageText = Array.isArray(data) ? data.join("") : data;
                    if (!imageText.trimStart().startsWith("<svg")) {
                        const imageData = decodeBase64(imageText);
                        Deno.writeFileSync(outputFile, imageData);
                    } else {
                        Deno.writeTextFileSync(outputFile, imageText);
                    }
                    for(let i1 = 0; i1 < source.length; i1++){
                        source[i1] = source[i1].replaceAll(`attachment:${file}`, imageFile);
                    }
                    break;
                }
            }
        });
    }
    return contentCellEnvelope(cell.id, mdEnsureTrailingNewline(source));
}
function mdFormatOutput(format, source) {
    const ticks = ticksForCode(source);
    return mdEnclosedOutput(ticks + "{=" + format + "}", source, ticks);
}
function mdRawOutput(mimeType, source) {
    switch(mimeType){
        case kTextHtml:
            return mdHtmlOutput(source);
        case kTextLatex:
            return mdLatexOutput(source);
        case kRestructuredText:
            return mdFormatOutput("rst", source);
        case kApplicationRtf:
            return mdFormatOutput("rtf", source);
        case kApplicationJavascript:
            return mdScriptOutput(mimeType, source);
    }
}
function mdFromRawCell(cell, options) {
    const rawCellEnvelope = createCellEnvelope([
        "cell",
        "raw"
    ], options);
    const mimeType = cell.metadata?.[kCellRawMimeType];
    if (mimeType) {
        const rawOutput = mdRawOutput(mimeType, jupyterCellSrcAsLines(cell));
        if (rawOutput) {
            return rawCellEnvelope(cell.id, rawOutput);
        }
    }
    return mdFromContentCell(cell, options ? {
        ...options,
        preserveCellMetadata: false
    } : undefined);
}
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;
    }
}
const kHideCell = "hide-cell";
const kHideCode = "hide-code";
const kHideOutput = "hide-output";
const kHideWarnings = "hide-warnings";
const kShowCode = "show-code";
const kShowOutput = "show-output";
const kShowWarnings = "show-warnings";
const kRemoveCell = "remove-cell";
const tagMapping = {
    [kHideCell]: {
        include: false
    },
    [kHideCode]: {
        echo: false
    },
    [kHideOutput]: {
        output: false
    },
    [kHideWarnings]: {
        warning: false
    },
    [kShowCode]: {
        echo: true
    },
    [kShowOutput]: {
        output: true
    },
    [kShowWarnings]: {
        warning: true
    },
    [kRemoveCell]: {
        include: false
    }
};
function createCellEnvelope(classes, options) {
    return (id, source)=>{
        if (options && options.preserveCellMetadata) {
            const wrappedSource = [
                ...source
            ];
            wrappedSource.unshift(`:::{#${id} ${classes.map((clz)=>`.${clz}`).join(" ")}}\n`);
            wrappedSource.push(`:::`);
            return mdEnsureTrailingNewline(wrappedSource);
        } else {
            return source;
        }
    };
}
function tagsToOptions(tags) {
    const result1 = {};
    tags.forEach((tag)=>{
        const mapping = tagMapping[tag];
        if (mapping) {
            const keys = Object.keys(mapping);
            keys.forEach((key)=>{
                result1[key] = mapping[key];
            });
        }
    });
    return result1;
}
function optionCommentPrefix(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: "//",
    mermaid: "%%",
    apl: "⍝",
    ocaml: [
        "(*",
        "*)"
    ],
    rust: "//"
};
function cleanJupyterOutputDisplayData(output) {
    const rawOutput = output;
    const outputData = {};
    for (const [key, value] of Object.entries(rawOutput.data)){
        const strValue = typeof value === "string" ? [
            value
        ] : Array.isArray(value) && value.every((x)=>typeof x === "string") ? value : undefined;
        if (strValue === undefined) {
            outputData[key] = value;
        } else {
            outputData[key] = strValue;
        }
    }
    return {
        ...output,
        data: outputData,
        metadata: rawOutput.metadata,
        noCaption: rawOutput.noCaption
    };
}
async function mdFromCodeCell(cell, cellIndex, options) {
    if (!includeCell(cell, options)) {
        return [];
    }
    const haveImage = !!cell.outputs?.some((output)=>isImage(output, options));
    const outputs = (cell.outputs || []).filter((output)=>{
        if (output.output_type === "stream" && output.name === "stderr" && !includeWarnings(cell, options)) {
            return false;
        }
        if (isDiscardableTextExecuteResult(output, haveImage)) {
            return false;
        }
        return true;
    }).map((output)=>{
        if (!options.toLatex && isDisplayData(output) && output.data[kTextLatex]) {
            return displayDataWithMarkdownMath(output);
        } else {
            return output;
        }
    });
    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} `);
    } else if ((isIpynbOutput(options.executeOptions.format.pandoc) || isJatsOutput(options.executeOptions.format.pandoc) || isHtmlOutput(options.executeOptions.format.pandoc)) && cell.id) {
        divMd.push(`#${cell.id} `);
    }
    let { cellCaption, outputCaptions } = resolveCaptions(cell);
    outputCaptions = outputCaptions.map((caption)=>caption.trim().replaceAll("\n", " "));
    divMd.push(`.cell `);
    if (hideCell(cell, options)) {
        divMd.push(`.hidden `);
    }
    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]}`);
    }
    if (classes.length > 0) {
        const classText = classes.map((clz)=>{
            clz = toString1(clz);
            return clz.startsWith(".") ? clz : "." + clz;
        }).join(" ");
        divMd.push(classText + " ");
    }
    const cellOptions = {
        ...cell.metadata,
        ...cell.options
    };
    let forwardedAttrs = false;
    for (const key of Object.keys(cellOptions)){
        if (!kCellOptionsFilter.includes(key.toLowerCase())) {
            let value = cellOptions[key];
            if (value !== undefined) {
                if (typeof value !== "string") {
                    value = JSON.stringify(value);
                }
                value = value.replaceAll("'", `\\'`);
                divMd.push(`${key}='${value}' `);
                forwardedAttrs = true;
            }
        }
    }
    const needCell = label && labelCellContainer || classes.length > 0 || forwardedAttrs || cellCaption !== undefined || outputCaptions.length > 0;
    if (typeof cell.execution_count === "number") {
        divMd.push(`execution_count=${cell.execution_count} `);
    }
    const divBeginMd = divMd.join("").replace(/ $/, "").concat("}\n");
    if (includeCode(cell, options) || options.preserveCodeCellYaml) {
        const fenced = echoFenced(cell, options);
        const ticks = "`".repeat(Math.max(countTicks(jupyterCellSrcAsLines(cell)) + 1, fenced ? 4 : 3));
        md.push(ticks + " {");
        if (!options.preserveCodeCellYaml) {
            if (typeof cell.options[kCellLstLabel] === "string") {
                let label = cell.options[kCellLstLabel];
                if (!label.startsWith("#")) {
                    label = "#" + label;
                }
                md.push(label + " ");
            }
            if (!fenced) {
                md.push("." + (cellOptions.language || 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(` lst-cap=\"${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 = trimEmptyLines(source, "trailing");
            } else {
                source = trimEmptyLines(source, "all");
            }
            source.unshift(...optionsSource);
            source.unshift("```{{" + options.language + "}}\n");
            source.push("\n```\n");
        } else if (cell.optionsSource.length > 0) {
            source = trimEmptyLines(source, "leading");
        }
        if (options.preserveCodeCellYaml) {
            md.push(...cell.optionsSource);
        }
        md.push(...source, "\n");
        md.push(ticks + "\n");
    }
    if (includeOutput(cell, options)) {
        const labelName = label ? label.replace(/^#/, "").replaceAll(":", "-") : "cell-" + (cellIndex + 1);
        const outputName = `${options.outputPrefix ? options.outputPrefix + "-" : ""}${pandocAutoIdentifier(labelName, true)}-output`;
        let nextOutputSuffix = 1;
        const sortedOutputs = outputs.map((value, index)=>({
                index,
                output: value
            })).sort((a, b)=>{
            const aIdx = a.output.metadata?.[kQuartoOutputOrder] !== undefined ? a.output.metadata?.[kQuartoOutputOrder] : Number.MAX_SAFE_INTEGER;
            const bIdx = b.output.metadata?.[kQuartoOutputOrder] !== undefined ? b.output.metadata?.[kQuartoOutputOrder] : Number.MAX_SAFE_INTEGER;
            return aIdx - bIdx;
        });
        for (const { index, output } of sortedOutputs){
            const outputLabel = label && labelCellContainer && isDisplayData(output) ? label + "-" + nextOutputSuffix++ : label;
            if (output.metadata?.[kQuartoOutputDisplay] === false) {
                continue;
            }
            if (!asis) {
                md.push("\n::: {");
                if (outputLabel && shouldLabelOutputContainer(output, cell.options, options)) {
                    md.push(outputLabel + " ");
                }
                md.push(".cell-output ");
                if (output.output_type === "stream") {
                    const stream = output;
                    md.push(`.cell-output-${stream.name}`);
                } else {
                    md.push(`.${outputTypeCssClass(output.output_type)}`);
                }
                if (isMarkdown(output, options)) {
                    md.push(` .${outputTypeCssClass("markdown")}`);
                }
                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}`);
                }
                if (cell.options[kHtmlTableProcessing] === "none") {
                    md.push(" html-table-processing=none");
                }
                md.push("}\n");
            }
            if (options.toLatex && !options.figPos && !cell.options[kCellFigPos] && !hasLayoutOptions(cell) && includeCode(cell, options)) {
                cell.options[kCellFigPos] = "H";
            }
            const figureOptions = {};
            const broadcastFigureOption = (name)=>{
                const value = cell.options[name];
                if (value) {
                    if (Array.isArray(value)) {
                        return value[index];
                    } 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") {
                    let text = [];
                    if (typeof stream.text === "string") {
                        text = [
                            stream.text
                        ];
                    } else {
                        text = stream.text;
                    }
                    md.push(text.join(""));
                } else {
                    md.push(mdOutputStream(stream));
                }
            } else if (output.output_type === "error") {
                md.push(await mdOutputError(output, options));
            } else if (isDisplayData(output)) {
                const fixedOutput = cleanJupyterOutputDisplayData(output);
                if (Object.keys(fixedOutput.data).length > 0) {
                    const caption = isCaptionableData(output) ? outputCaptions.shift() || null : null;
                    md.push(await mdOutputDisplayData(outputLabel, caption, outputName + "-" + (index + 1), fixedOutput, 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 && (needCell || !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 isDiscardableTextExecuteResult(output, haveImage) {
    if (output.output_type === "execute_result") {
        const data = output.data;
        if (Object.keys(data).length === 1) {
            const textPlain = data?.[kTextPlain];
            if (textPlain && textPlain.length) {
                if (haveImage && textPlain.length === 1) {
                    return /^([<(\[]).*?([>)\]])$/.test(textPlain[0].trim());
                } else {
                    return [
                        "[<matplotlib",
                        "<matplotlib",
                        "<seaborn.",
                        "<ggplot:"
                    ].some((startsWith)=>textPlain[0].startsWith(startsWith));
                }
            }
        }
    }
    return false;
}
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 isMarkdown(output, options) {
    return isDisplayDataType(output, options, displayDataIsMarkdown);
}
function mdOutputStream(output) {
    let text = [];
    if (typeof output.text === "string") {
        text = [
            output.text
        ];
    } else {
        text = output.text;
    }
    if (output.name === "stderr") {
        if (text[0]) {
            const firstLine = text[0].replace(/<ipython-input.*?>:\d+:\s+/, "");
            return mdCodeOutput([
                firstLine,
                ...text.slice(1)
            ].map(stripColor));
        }
    }
    return mdCodeOutput(text.map(stripColor));
}
async function mdOutputError(output, options) {
    const traceback = output.traceback.join("\n");
    if (!options.toHtml || !hasAnsiEscapeCodes(output.evalue) && !hasAnsiEscapeCodes(traceback)) {
        if (output.traceback.length > 0) {
            return mdCodeOutput([
                output.ename + ": " + output.evalue + "\n" + traceback
            ]);
        } else {
            return mdCodeOutput([
                output.ename + ": " + output.evalue
            ]);
        }
    }
    const tracebackHtml = await convertToHtmlSpans(traceback);
    return mdMarkdownOutput([
        "\n::: {.ansi-escaped-output}\n```{=html}\n<pre>",
        tracebackHtml,
        "</pre>\n```\n:::\n"
    ]);
}
async 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)) {
            const json = output.data[mimeType];
            json[kQuartoMimeType] = mimeType;
            return mdJsonOutput(mimeType, json, options);
        } else if (displayDataIsJavascript(mimeType)) {
            return mdScriptOutput(mimeType, output.data[mimeType]);
        } else if (displayDataIsTextPlain(mimeType)) {
            const data = output.data[mimeType];
            if (!Array.isArray(data) || data.some((s)=>typeof s !== "string")) {
                return mdWarningOutput(`Unable to process text plain output data 
which does not appear to be plain text: ${JSON.stringify(data)}`);
            }
            const lines = data;
            if (lines.length === 1 && lines[0].startsWith("'<table") && lines[0].endsWith("</table>'")) {
                lines[0] = lines[0].slice(1, -1);
                return mdMarkdownOutput(lines);
            } else {
                if (options.toHtml) {
                    if (lines.some(hasAnsiEscapeCodes)) {
                        const html = await Promise.all(lines.map(convertToHtmlSpans));
                        return mdMarkdownOutput([
                            "\n::: {.ansi-escaped-output}\n```{=html}\n<pre>",
                            ...html,
                            "</pre>\n```\n:::\n"
                        ]);
                    } else {
                        return mdCodeOutput(lines);
                    }
                } else {
                    return mdCodeOutput(lines.map(stripColor));
                }
            }
        }
    }
    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 data = output.data[mimeType];
    const metadata = output.metadata[mimeType];
    function metadataValue(key, defaultValue) {
        if (metadata) {
            return metadata[key] ? metadata[key] : defaultValue;
        }
        return defaultValue;
    }
    let width = metadataValue(kCellOutWidth) ?? metadataValue(kCellWidth, 0);
    let height = metadataValue(kCellOutHeight) ?? metadataValue(kCellHeight, 0);
    const alt = caption || "";
    const ext = extensionForMimeImageType(mimeType);
    const imageFile = options.assets.figures_dir + "/" + filename + "." + ext;
    const imageText = Array.isArray(data) ? data.join("") : data;
    const outputFile = join2(options.assets.base_dir, imageFile);
    if (mimeType !== kImageSvg || !/<svg/.test(imageText)) {
        const imageData = decodeBase64(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);
    }
    const kFigOptions = [
        kCellFigAlign,
        kCellFigEnv,
        kCellFigAlt,
        kCellFigPos,
        kCellFigScap
    ];
    let image = `![${alt}](${imageFile})`;
    if (label || width || height || Object.keys(figureOptions).some((option)=>kFigOptions.includes(option))) {
        image += "{";
        if (label) {
            image += `${label} `;
        }
        if (width) {
            image += `width=${width} `;
        }
        if (height) {
            image += `height=${height} `;
        }
        kFigOptions.forEach((attrib)=>{
            const value = figureOptions[attrib];
            if (value) {
                image += `${attrib}='${value.replaceAll("'", "\\'")}' `;
            }
        });
        image = image.trimRight() + "}";
    }
    if (figureOptions[kCellFigLink]) {
        image = `[${image}](${figureOptions[kCellFigLink]})`;
    }
    return mdMarkdownOutput([
        image
    ]);
}
function mdMarkdownOutput(md) {
    return md.join("") + "\n";
}
function mdLatexOutput(latex) {
    return mdFormatOutput("tex", latex);
}
function mdHtmlOutput(html) {
    return mdFormatOutput("html", html);
}
function mdJsonOutput(mimeType, json, options) {
    if (options.toIpynb) {
        return mdCodeOutput([
            JSON.stringify(json)
        ], "json");
    } else {
        return mdScriptOutput(mimeType, [
            JSON.stringify(json)
        ]);
    }
}
function mdScriptOutput(mimeType, script) {
    const scriptTag = [
        `<script type="${mimeType}">\n`,
        ...script,
        "\n</script>"
    ];
    return mdHtmlOutput(scriptTag);
}
function mdCodeOutput(code, clz) {
    const ticks = ticksForCode(code);
    const open = ticks + (clz ? `{.${clz}}` : "");
    return mdEnclosedOutput(open, code, ticks);
}
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}`;
}
const sleep = (delay)=>{
    return new Promise((resolve)=>{
        setTimeout(resolve, delay);
    });
};
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 ? join2(dir, subdir) : dir;
    ensureDirSync(fullDir);
    return fullDir;
}
function userDataDir(appName, roaming = false) {
    switch(Deno.build.os){
        case "darwin":
            return darwinUserDataDir(appName);
        case "windows":
            return windowsUserDataDir(appName, roaming);
        default:
            return xdgUserDataDir(appName);
    }
}
function userCacheDir(appName) {
    switch(Deno.build.os){
        case "darwin":
            return darwinUserCacheDir(appName);
        case "windows":
            return windowsUserDataDir(appName);
        default:
            return xdgUserCacheDir(appName);
    }
}
function userRuntimeDir(appName) {
    switch(Deno.build.os){
        case "darwin":
            return darwinUserCacheDir(appName);
        case "windows":
            return windowsUserDataDir(appName);
        default:
            return xdgUserRuntimeDir(appName);
    }
}
function darwinUserDataDir(appName) {
    return join2(Deno.env.get("HOME") || "", "Library", "Application Support", appName);
}
function darwinUserCacheDir(appName) {
    return join2(Deno.env.get("HOME") || "", "Library", "Caches", appName);
}
function xdgUserDataDir(appName) {
    const dataHome = Deno.env.get("XDG_DATA_HOME") || join2(Deno.env.get("HOME") || "", ".local", "share");
    return join2(dataHome, appName);
}
function xdgUserCacheDir(appName) {
    const cacheHome = Deno.env.get("XDG_CACHE_HOME") || join2(Deno.env.get("HOME") || "", ".cache");
    return join2(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 join2(dir, appName);
}
let wasm1;
const heap = new Array(128).fill(undefined);
heap.push(undefined, null, true, false);
function getObject(idx) {
    return heap[idx];
}
let heap_next = heap.length;
function dropObject(idx) {
    if (idx < 132) return;
    heap[idx] = heap_next;
    heap_next = idx;
}
function takeObject(idx) {
    const ret = getObject(idx);
    dropObject(idx);
    return ret;
}
function addHeapObject(obj) {
    if (heap_next === heap.length) heap.push(heap.length + 1);
    const idx = heap_next;
    heap_next = heap[idx];
    heap[idx] = obj;
    return idx;
}
const cachedTextDecoder1 = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8", {
    ignoreBOM: true,
    fatal: true
}) : {
    decode: ()=>{
        throw Error("TextDecoder not available");
    }
};
if (typeof TextDecoder !== "undefined") cachedTextDecoder1.decode();
let cachedUint8Memory0 = null;
function getUint8Memory01() {
    if (cachedUint8Memory0 === null || cachedUint8Memory0.byteLength === 0) {
        cachedUint8Memory0 = new Uint8Array(wasm1.memory.buffer);
    }
    return cachedUint8Memory0;
}
function getStringFromWasm01(ptr, len) {
    ptr = ptr >>> 0;
    return cachedTextDecoder1.decode(getUint8Memory01().subarray(ptr, ptr + len));
}
let WASM_VECTOR_LEN1 = 0;
const cachedTextEncoder1 = typeof TextEncoder !== "undefined" ? new TextEncoder("utf-8") : {
    encode: ()=>{
        throw Error("TextEncoder not available");
    }
};
const encodeString1 = function(arg, view) {
    return cachedTextEncoder1.encodeInto(arg, view);
};
function passStringToWasm01(arg, malloc, realloc) {
    if (realloc === undefined) {
        const buf = cachedTextEncoder1.encode(arg);
        const ptr = malloc(buf.length, 1) >>> 0;
        getUint8Memory01().subarray(ptr, ptr + buf.length).set(buf);
        WASM_VECTOR_LEN1 = buf.length;
        return ptr;
    }
    let len = arg.length;
    let ptr = malloc(len, 1) >>> 0;
    const mem = getUint8Memory01();
    let offset = 0;
    for(; offset < len; offset++){
        const code = arg.charCodeAt(offset);
        if (code > 0x7F) break;
        mem[ptr + offset] = code;
    }
    if (offset !== len) {
        if (offset !== 0) {
            arg = arg.slice(offset);
        }
        ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
        const view = getUint8Memory01().subarray(ptr + offset, ptr + len);
        const ret = encodeString1(arg, view);
        offset += ret.written;
    }
    WASM_VECTOR_LEN1 = offset;
    return ptr;
}
function isLikeNone(x) {
    return x === undefined || x === null;
}
let cachedInt32Memory0 = null;
function getInt32Memory01() {
    if (cachedInt32Memory0 === null || cachedInt32Memory0.byteLength === 0) {
        cachedInt32Memory0 = new Int32Array(wasm1.memory.buffer);
    }
    return cachedInt32Memory0;
}
function getArrayU8FromWasm0(ptr, len) {
    ptr = ptr >>> 0;
    return getUint8Memory01().subarray(ptr / 1, ptr / 1 + len);
}
function digest(algorithm, data, length) {
    try {
        const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
        const ptr0 = passStringToWasm01(algorithm, wasm1.__wbindgen_malloc, wasm1.__wbindgen_realloc);
        const len0 = WASM_VECTOR_LEN1;
        wasm1.digest(retptr, ptr0, len0, addHeapObject(data), !isLikeNone(length), isLikeNone(length) ? 0 : length);
        var r0 = getInt32Memory01()[retptr / 4 + 0];
        var r1 = getInt32Memory01()[retptr / 4 + 1];
        var r2 = getInt32Memory01()[retptr / 4 + 2];
        var r3 = getInt32Memory01()[retptr / 4 + 3];
        if (r3) {
            throw takeObject(r2);
        }
        var v2 = getArrayU8FromWasm0(r0, r1).slice();
        wasm1.__wbindgen_free(r0, r1 * 1, 1);
        return v2;
    } finally{
        wasm1.__wbindgen_add_to_stack_pointer(16);
    }
}
const DigestContextFinalization = new FinalizationRegistry((ptr)=>wasm1.__wbg_digestcontext_free(ptr >>> 0));
class DigestContext {
    static __wrap(ptr) {
        ptr = ptr >>> 0;
        const obj = Object.create(DigestContext.prototype);
        obj.__wbg_ptr = ptr;
        DigestContextFinalization.register(obj, obj.__wbg_ptr, obj);
        return obj;
    }
    __destroy_into_raw() {
        const ptr = this.__wbg_ptr;
        this.__wbg_ptr = 0;
        DigestContextFinalization.unregister(this);
        return ptr;
    }
    free() {
        const ptr = this.__destroy_into_raw();
        wasm1.__wbg_digestcontext_free(ptr);
    }
    constructor(algorithm){
        try {
            const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
            const ptr0 = passStringToWasm01(algorithm, wasm1.__wbindgen_malloc, wasm1.__wbindgen_realloc);
            const len0 = WASM_VECTOR_LEN1;
            wasm1.digestcontext_new(retptr, ptr0, len0);
            var r0 = getInt32Memory01()[retptr / 4 + 0];
            var r1 = getInt32Memory01()[retptr / 4 + 1];
            var r2 = getInt32Memory01()[retptr / 4 + 2];
            if (r2) {
                throw takeObject(r1);
            }
            this.__wbg_ptr = r0 >>> 0;
            return this;
        } finally{
            wasm1.__wbindgen_add_to_stack_pointer(16);
        }
    }
    update(data) {
        try {
            const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
            wasm1.digestcontext_update(retptr, this.__wbg_ptr, addHeapObject(data));
            var r0 = getInt32Memory01()[retptr / 4 + 0];
            var r1 = getInt32Memory01()[retptr / 4 + 1];
            if (r1) {
                throw takeObject(r0);
            }
        } finally{
            wasm1.__wbindgen_add_to_stack_pointer(16);
        }
    }
    digest(length) {
        try {
            const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
            wasm1.digestcontext_digest(retptr, this.__wbg_ptr, !isLikeNone(length), isLikeNone(length) ? 0 : length);
            var r0 = getInt32Memory01()[retptr / 4 + 0];
            var r1 = getInt32Memory01()[retptr / 4 + 1];
            var r2 = getInt32Memory01()[retptr / 4 + 2];
            var r3 = getInt32Memory01()[retptr / 4 + 3];
            if (r3) {
                throw takeObject(r2);
            }
            var v1 = getArrayU8FromWasm0(r0, r1).slice();
            wasm1.__wbindgen_free(r0, r1 * 1, 1);
            return v1;
        } finally{
            wasm1.__wbindgen_add_to_stack_pointer(16);
        }
    }
    digestAndReset(length) {
        try {
            const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
            wasm1.digestcontext_digestAndReset(retptr, this.__wbg_ptr, !isLikeNone(length), isLikeNone(length) ? 0 : length);
            var r0 = getInt32Memory01()[retptr / 4 + 0];
            var r1 = getInt32Memory01()[retptr / 4 + 1];
            var r2 = getInt32Memory01()[retptr / 4 + 2];
            var r3 = getInt32Memory01()[retptr / 4 + 3];
            if (r3) {
                throw takeObject(r2);
            }
            var v1 = getArrayU8FromWasm0(r0, r1).slice();
            wasm1.__wbindgen_free(r0, r1 * 1, 1);
            return v1;
        } finally{
            wasm1.__wbindgen_add_to_stack_pointer(16);
        }
    }
    digestAndDrop(length) {
        try {
            const ptr = this.__destroy_into_raw();
            const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
            wasm1.digestcontext_digestAndDrop(retptr, ptr, !isLikeNone(length), isLikeNone(length) ? 0 : length);
            var r0 = getInt32Memory01()[retptr / 4 + 0];
            var r1 = getInt32Memory01()[retptr / 4 + 1];
            var r2 = getInt32Memory01()[retptr / 4 + 2];
            var r3 = getInt32Memory01()[retptr / 4 + 3];
            if (r3) {
                throw takeObject(r2);
            }
            var v1 = getArrayU8FromWasm0(r0, r1).slice();
            wasm1.__wbindgen_free(r0, r1 * 1, 1);
            return v1;
        } finally{
            wasm1.__wbindgen_add_to_stack_pointer(16);
        }
    }
    reset() {
        try {
            const retptr = wasm1.__wbindgen_add_to_stack_pointer(-16);
            wasm1.digestcontext_reset(retptr, this.__wbg_ptr);
            var r0 = getInt32Memory01()[retptr / 4 + 0];
            var r1 = getInt32Memory01()[retptr / 4 + 1];
            if (r1) {
                throw takeObject(r0);
            }
        } finally{
            wasm1.__wbindgen_add_to_stack_pointer(16);
        }
    }
    clone() {
        const ret = wasm1.digestcontext_clone(this.__wbg_ptr);
        return DigestContext.__wrap(ret);
    }
}
const imports = {
    __wbindgen_placeholder__: {
        __wbg_new_d331494ab60a8491: function(arg0, arg1) {
            const ret = new TypeError(getStringFromWasm01(arg0, arg1));
            return addHeapObject(ret);
        },
        __wbindgen_object_drop_ref: function(arg0) {
            takeObject(arg0);
        },
        __wbg_byteLength_a8d894d93425b2e0: function(arg0) {
            const ret = getObject(arg0).byteLength;
            return ret;
        },
        __wbg_byteOffset_89d0a5265d5bde53: function(arg0) {
            const ret = getObject(arg0).byteOffset;
            return ret;
        },
        __wbg_buffer_3da2aecfd9814cd8: function(arg0) {
            const ret = getObject(arg0).buffer;
            return addHeapObject(ret);
        },
        __wbg_newwithbyteoffsetandlength_d695c7957788f922: function(arg0, arg1, arg2) {
            const ret = new Uint8Array(getObject(arg0), arg1 >>> 0, arg2 >>> 0);
            return addHeapObject(ret);
        },
        __wbg_length_f0764416ba5bb237: function(arg0) {
            const ret = getObject(arg0).length;
            return ret;
        },
        __wbindgen_memory: function() {
            const ret = wasm1.memory;
            return addHeapObject(ret);
        },
        __wbg_buffer_5d1b598a01b41a42: function(arg0) {
            const ret = getObject(arg0).buffer;
            return addHeapObject(ret);
        },
        __wbg_new_ace717933ad7117f: function(arg0) {
            const ret = new Uint8Array(getObject(arg0));
            return addHeapObject(ret);
        },
        __wbg_set_74906aa30864df5a: function(arg0, arg1, arg2) {
            getObject(arg0).set(getObject(arg1), arg2 >>> 0);
        },
        __wbindgen_throw: function(arg0, arg1) {
            throw new Error(getStringFromWasm01(arg0, arg1));
        }
    }
};
function instantiate() {
    return instantiateWithInstance().exports;
}
let instanceWithExports;
function instantiateWithInstance() {
    if (instanceWithExports == null) {
        const instance = instantiateInstance();
        wasm1 = instance.exports;
        cachedInt32Memory0 = new Int32Array(wasm1.memory.buffer);
        cachedUint8Memory0 = new Uint8Array(wasm1.memory.buffer);
        instanceWithExports = {
            instance,
            exports: {
                digest,
                DigestContext
            }
        };
    }
    return instanceWithExports;
}
function instantiateInstance() {
    const wasmBytes = base64decode("\
AGFzbQEAAAABsQEZYAAAYAABf2ABfwBgAX8Bf2ACf38AYAJ/fwF/YAN/f38AYAN/f38Bf2AEf39/fw\
BgBH9/f38Bf2AFf39/f38AYAV/f39/fwF/YAZ/f39/f38AYAZ/f39/f38Bf2AHf39/f35/fwBgBX9/\
f35/AGAHf39/fn9/fwF/YAN/f34AYAV/f35/fwBgBX9/fX9/AGAFf398f38AYAJ/fgBgBH9+f38AYA\
R/fX9/AGAEf3x/fwACpAUMGF9fd2JpbmRnZW5fcGxhY2Vob2xkZXJfXxpfX3diZ19uZXdfZDMzMTQ5\
NGFiNjBhODQ5MQAFGF9fd2JpbmRnZW5fcGxhY2Vob2xkZXJfXxpfX3diaW5kZ2VuX29iamVjdF9kcm\
9wX3JlZgACGF9fd2JpbmRnZW5fcGxhY2Vob2xkZXJfXyFfX3diZ19ieXRlTGVuZ3RoX2E4ZDg5NGQ5\
MzQyNWIyZTAAAxhfX3diaW5kZ2VuX3BsYWNlaG9sZGVyX18hX193YmdfYnl0ZU9mZnNldF84OWQwYT\
UyNjVkNWJkZTUzAAMYX193YmluZGdlbl9wbGFjZWhvbGRlcl9fHV9fd2JnX2J1ZmZlcl8zZGEyYWVj\
ZmQ5ODE0Y2Q4AAMYX193YmluZGdlbl9wbGFjZWhvbGRlcl9fMV9fd2JnX25ld3dpdGhieXRlb2Zmc2\
V0YW5kbGVuZ3RoX2Q2OTVjNzk1Nzc4OGY5MjIABxhfX3diaW5kZ2VuX3BsYWNlaG9sZGVyX18dX193\
YmdfbGVuZ3Ro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ADcDACAEQcAAakEoaiAFQShqKQMANwMAIARBwABqQTBqIAVBMGop\
AwA3AwAgBEHAAGpBOGogBUE4aikDADcDACAEQcAAakHIAWogBUHIAWotAAA6AAAgBCAPNwOAASAEIA\
UpAwA3A0AgByAEQcAAakHQARCQARoMGQtBAC0AgNhAGkHQARAZIgdFDRsgBSkDQCEPIARBwABqQcgA\
aiAFQcgAahBnIARBwABqQQhqIAVBCGopAwA3AwAgBEHAAGpBEGogBUEQaikDADcDACAEQcAAakEYai\
AFQRhqKQMANwMAIARBwABqQSBqIAVBIGopAwA3AwAgBEHAAGpBKGogBUEoaikDADcDACAEQcAAakEw\
aiAFQTBqKQMANwMAIARBwABqQThqIAVBOGopAwA3AwAgBEHAAGpByAFqIAVByAFqLQAAOgAAIAQgDz\
cDgAEgBCAFKQMANwNAIAcgBEHAAGpB0AEQkAEaDBgLQQAtAIDYQBpB0AEQGSIHRQ0aIAUpA0AhDyAE\
QcAAakHIAGogBUHIAGoQZyAEQcAAakEIaiAFQQhqKQMANwMAIARBwABqQRBqIAVBEGopAwA3AwAgBE\
HAAGpBGGogBUEYaikDADcDACAEQcAAakEgaiAFQSBqKQMANwMAIARBwABqQShqIAVBKGopAwA3AwAg\
BEHAAGpBMGogBUEwaikDADcDACAEQcAAakE4aiAFQThqKQMANwMAIARBwABqQcgBaiAFQcgBai0AAD\
oAACAEIA83A4ABIAQgBSkDADcDQCAHIARBwABqQdABEJABGgwXC0EALQCA2EAaQdABEBkiB0UNGSAF\
KQNAIQ8gBEHAAGpByABqIAVByABqEGcgBEHAAGpBCGogBUEIaikDADcDACAEQcAAakEQaiAFQRBqKQ\
MANwMAIARBwABqQRhqIAVBGGopAwA3AwAgBEHAAGpBIGogBUEgaikDADcDACAEQcAAakEoaiAFQShq\
KQMANwMAIARBwABqQTBqIAVBMGopAwA3AwAgBEHAAGpBOGogBUE4aikDADcDACAEQcAAakHIAWogBU\
HIAWotAAA6AAAgBCAPNwOAASAEIAUpAwA3A0AgByAEQcA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wAAIA1BIGoiDSAORg0BIAhBN0YNGSAMQSBqIA0p\
AAA3AAAgDEE4aiANQRhqKQAANwAAIAxBMGogDUEQaikAADcAACAMQShqIA1BCGopAAA3AAAgDEHAAG\
ohDCAIQQJqIQggDUEgaiINIA5HDQALIAhBf2ohCAsgBCAINgKgHSAEQcAAakEFaiAEQcAPakHkDRCQ\
ARogBEHAD2pBCGogBUEIaikDADcDACAEQcAPakEQaiAFQRBqKQMANwMAIARBwA9qQRhqIAVBGGopAw\
A3AwAgBCAFKQMANwPADyAEQcAPakEgaiAEQZAgakHgABCQARogByAEQcAPakGAARCQASIFIAk6AIoB\
IAUgCjoAiQEgBSALOgCIASAFIA83A4ABIAVBiwFqIARBwABqQekNEJABGgwTC0EALQCA2EAaQegCEB\
kiB0UNFSAFKALIASEMIARBwABqQdABaiAFQdABahBoIAVB4AJqLQAAIQ0gBEHAAGogBUHIARCQARog\
BEHAAGpB4AJqIA06AAAgBCAMNgKIAiAHIARBwABqQegCEJABGgwSC0EALQCA2EAaQeACEBkiB0UNFC\
AFKALIASEMIARBwABqQdABaiAFQdABahBpIAVB2AJqLQAAIQ0gBEHAAGogBUHIARCQARogBEHAAGpB\
2AJqIA06AAAgBCAMNgKIAiAHIARBwABqQeACEJABGgwRC0EALQCA2EAaQcACEBkiB0UNEyAFKALIAS\
EMIARBwABqQdABaiAFQdABahBqIAVBuAJqLQAAIQ0gBEHAAGogBUHIARCQARogBEHAAGpBuAJqIA06\
AAAgBCAMNgKIAiAHIARBwABqQcACEJABGgwQC0EALQCA2EAaQaACEBkiB0UNEiAFKALIASEMIARBwA\
BqQdABaiAFQdABahBrIAVBmAJqLQAAIQ0gBEHAAGogBUHIARCQARogBEHAAGpBmAJqIA06AAAgBCAM\
NgKIAiAHIARBwABqQaACEJABGgwPC0EALQCA2EAaQeAAEBkiB0UNESAFKQMQIQ8gBSkDACEQIAUpAw\
ghESAEQcAAakEYaiAFQRhqEFUgBEHAAGpB2ABqIAVB2ABqLQAAOgAA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6AAAgBEH3AGogKzoAACAEICg6AIwBIAQgFjoAiAEgBCApOgCEASAEIAw6AIABIA\
QgKjoAfCAEICc6AHggBCAuOgB0IAQgMjoAcCAEIDE6AHEgBCAwOgByIAQgLzoAc0GMksAAIARB8ABq\
QeyGwABBxIXAABBfAAsgBSAAaiACIAMQkAEaIAEgACADajoA4AIMSAsgBSAAaiACIAYQkAEaIARB8A\
BqIAVBARA7IAIgBmohAiADIAZrIQMMNwsgBSAAaiACIAMQkAEaIAEgACADajoA2AIMRgsgBSAAaiAC\
IAYQkAEaIARB8ABqIAVBARBCIAIgBmohAiADIAZrIQMMNAsgBSAAaiACIAMQkAEaIAEgACADajoAuA\
IMRAsgBSAAaiACIAYQkAEaIARB8ABqIAVBARBSIAIgBmohAiADIAZrIQMMMQsgBSAAaiACIAMQkAEa\
IAEgACADajoAmAIMQgsgBSAAaiACIAYQkAEaIARB8ABqIAVBARBYIAIgBmohAiADIAZrIQMMLgsgBS\
AAaiACIAMQkAEaIAEgACADajoAWAxACyAFIABqIAIgBhCQARogASABKQMQQgF8NwMQIAEgBRAjIAMg\
BmshAyACIAZqIQIMKwsgBSAAaiACIAMQkAEaIAEgACADajoAWAw+CyAFIABqIAIgBhCQARogBEHwAG\
ogBUEBEBsgAiAGaiECIAMgBmshAwwoCyAGIABqIAIgAxCQARogASAAIANqOgBgDDwLIAYgAGogAiAF\
EJABGiABIAEpAwBCAXw3AwAgAUEIaiAGEBIgAyAFayEDIAIgBWohAgwlCyAFIABqIAIgAxCQARogAS\
AAIANqOgBgDDoLIAUgAGogAiAGEJABGiABIAEpAwBCAXw3AwAgAUEIaiAFQQEQFCACIAZqIQIgAyAG\
ayEDDCILIAUgAGogAiADEJABGiABIAAgA2o6AOACDDgLIAUgAGogAiAGEJABGiAEQfAAaiAFQQEQOy\
ACIAZqIQIgAyAGayEDDB8LIAUgAGogAiADEJABGiABIAAgA2o6ANgCDDYLIAUgAGogAiAGEJABGiAE\
QfAAaiAFQQEQQiACIAZqIQIgAyAGayEDDBwLIAUgAGogAiADEJABGiABIAAgA2o6ALgCDDQLIAUgAG\
ogAiAGEJABGiAEQfAAaiAFQQEQUiACIAZqIQIgAyAGayEDDBkLIAUgAGogAiADEJABGiABIAAgA2o6\
AJgCDDILIAUgAGogAiAGEJABGiAEQfAAaiAFQQEQWCACIAZqIQIgAyAGayEDDBYLIAUgAGogAiADEJ\
ABGiABIAAgA2o6AGgMMAsgBSAAaiACIAYQkAEaIAEgASkDIEIBfDcDICABIAVBARAOIAIgBmohAiAD\
IAZrIQMMEwsgBSAAaiACIAMQkAEaIAEgACADajoAaAwuCyAFIABqIAIgBhCQARogASABKQMgQgF8Nw\
MgIAEgBUEBEA4gAiAGaiECIAMgBmshAwwQCyAFIABqIAIgAxCQARogASAAIANqOgDQAQwsCyAFIABq\
IAIgBhCQARogASABKQNAQgF8Ij03A0AgAUHIAGoiACAAKQMAID1QrXw3AwAgASAFQQEQDCACIAZqIQ\
IgAyAGayEDDA0LIAUgAGogAiADEJABGiABIAAgA2o6ANABDCoLIAUgAGogAiAGEJABGiABIAEpA0BC\
AXwiPTcDQCABQcgAaiIAIAApAwAgPVCtfDcDACABIAVBARAMIAIgBmohAiADIAZrIQMMCgsgBSAAai\
ACIAMQkAEaIAEgACADajoA+AIMKAsgBSAAaiACIAYQkAEaIARB8ABqIAVBARAzIAIgBmohAiADIAZr\
IQMMBwsgBSAAaiACIAMQkAEaIAEgACADajoA2AIMJgsgBSAAaiACIAYQkAEaIARB8ABqIAVBARBCIA\
IgBmohAiADIAZrIQMMBAsgBiAAaiACIAMQkAEaIAAgA2ohBwwCCyAGIABqIAIgBRCQARogASABKQMA\
QgF8NwMAIAFBCGogBhAVIAMgBWshAyACIAVqIQILIANBP3EhByACIANBQHEiAGohDAJAIANBwABJDQ\
AgASABKQMAIANBBnatfDcDACABQQhqIQUDQCAFIAIQFSACQcAAaiECIABBQGoiAA0ACwsgBiAMIAcQ\
kAEaCyABIAc6AGAMIQsgAyADQYgBbiIHQY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GQAUkNACAEQfAAaiACIAcQOwsCQCAAQZEBTw0AIA\
UgAiAGaiAAEJABGiABIAA6AOACDBgLIABBkAFBgIDAABBgAAsgA0E/cSEAIAIgA0FAcWohBgJAIANB\
wABJDQAgASABKQMAIANBBnYiA618NwMAIAFBCGogAiADEBQLIAUgBiAAEJABGiABIAA6AGAMFgsgA0\
E/cSEHIAIgA0FAcSIAaiEMAkAgA0HAAEkNACABIAEpAwAgA0EGdq18NwMAIAFBCGohBQNAIAUgAhAS\
IAJBwABqIQIgAEFAaiIADQALCyAGIAwgBxCQARogASAHOgBgDBULIANBP3EhACACIANBQHFqIQYCQC\
ADQcAASQ0AIARB8ABqIAIgA0EGdhAbCyAFIAYgABCQARogASAAOgBYDBQLIANBP3EhBiACIANBQHEi\
AGohBwJAIANBwABJDQAgASABKQMQIANBBnatfDcDEANAIAEgAhAjIAJBwABqIQIgAEFAaiIADQALCy\
AFIAcgBhCQARogASAGOgBYDBMLIAMgA0HIAG4iB0HIAGwiBmshAAJAIANByABJDQAgBEHwAGogAiAH\
EFgLAkAgAEHJAE8NACAFIAIgBmogABCQARogASAAOgCYAgwTCyAAQcgAQYCAwAAQYAALIAMgA0HoAG\
4iB0HoAGwiBmshAAJAIANB6ABJDQAgBEHwAGogAiAHEFILAkAgAEHpAE8NACAFIAIgBmogABCQARog\
ASAAOgC4AgwSCyAAQegAQYCAwAAQYAALIAMgA0GIAW4iB0GIAWwiBmshAAJAIANBiAFJDQAgBEHwAG\
ogAiAHEEILAkAgAEGJAU8NACAFIAIgBmogABCQARogASAAOgDYAgwRCyAAQYgBQYCAwAAQYAALIAMg\
A0GQAW4iB0GQAWwiBmshAAJAIANBkAFJDQAgBEHwAGogAiAHEDsLAkAgAEGRAU8NACAFIAIgBmogAB\
CQARogASAAOgDgAgwQCyAAQZABQYCAwAAQYAALAkACQAJAAkACQAJAAkACQAJAIANBgQhJDQAgAUGQ\
AWohFiABQYABaikDACE+IARBwABqIRUgBEHwAGpBwABqIQwgBEEg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AFQRBqIBRBEGopAAA3AAAgBUEIai\
AUQQhqKQAANwAAIAEgBkEBajYC8A4MAQsgBEHwAGpBCGpCADcDACAEQfAAakEQakIANwMAIARB8ABq\
QRhqQgA3AwAgBEHwAGpBIGpCADcDACAEQfAAakEoakIANwMAIARB8ABqQTBqQgA3AwAgBEHwAGpBOG\
pCADcDACAMIAEpAwA3AwAgDEEIaiIGIAFBCGopAwA3AwAgDEEQaiIHIAFBEGopAwA3AwAgDEEYaiIX\
IAFBGGopAwA3AwAgBEIANwNwIARBADsB2AEgBCA+NwPQASAEIAEtAIoBOgDaASAEQfAAaiACIAAQLy\
EFIBUgDCkDADcDACAVQQhqIAYpAwA3AwAgFUEQaiAHKQMANwMAIBVBGGogFykDADcDACAEQQhqIAVB\
CGopAwA3AwAgBEEQaiAFQRBqKQMANwMAIARBGGogBUEYaikDADcDACAUIAVBIGopAwA3AwAgBEEoai\
AFQShqKQMANwMAIARBMGogBUEwaikDADcDACAEQThqIAVBOGopAwA3AwAgBCAFKQMANwMAIAQtANoB\
IQUgBC0A2QEhGCAEKQPQASE+IAQgBC0A2AEiGToAaCAEID43A2AgBCAFIBhFckECciIFOgBpIARB4A\
FqQRhqIhggFykCADcDACAEQeABakEQaiIXIAcpAgA3AwAgBEHgAWpBCGoiByAGKQIANwMAIAQgDCkC\
ADcD4AEgBEHgAWogBCAZID4gBRAXIA0tAAAhGSAOLQAAIRogDy0AACEbIBAtAAAhHCARLQAAIR0gEi\
0AACEeIBgtAAAhGCATLQAAIR8gMy0AACEgIDQtAAAhISA1LQAAISIgNi0AACEjIDctAAAhJCAXLQAA\
IRcgOC0AACElIDktAAAhJiA6LQAAIScgOy0AACEoIARB4AFqQQpqLQAAISkgPC0AACEqIActAAAhBy\
AELQD8ASErIAQtAPQBISwgBC0A7AEhLSAELQDnASEuIAQtAOYBIS8gBC0A5QEhMCAELQDkASExIAQt\
AOMBITIgBC0A4gEhCSAELQDhASEKIAQtAOABIQsgASABKQOAARAiIAEoAvAOI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MANwMAIAFByAFqIAJByAFqLQAAOgAAIAEgDDcDQCABIA\
IpAwA3AwAgBCABQdABEJABGgwaC0EALQCA2EAaQdABEBkiBEUNHCACKQNAIQwgAUHIAGogAkHIAGoQ\
ZyABQQhqIAJBCGopAwA3AwAgAUEQaiACQRBqKQMANwMAIAFBGGogAkEYaikDADcDACABQSBqIAJBIG\
opAwA3AwAgAUEoaiACQShqKQMANwMAIAFBMGogAkEwaikDADcDACABQThqIAJBOGopAwA3AwAgAUHI\
AWogAkHIAWotAAA6AAAgASAMNwNAIAEgAikDADcDACAEIAFB0AEQkAEaDBkLQQAtAIDYQBpB0AEQGS\
IERQ0bIAIpA0AhDCABQcgAaiACQcgAahBnIAFBCGogAkEIaikDADcDACABQRBqIAJBEGopAwA3AwAg\
AUEYaiACQRhqKQMANwMAIAFBIGogAkEgaikDADcDACABQShqIAJBKGopAwA3AwAgAUEwaiACQTBqKQ\
MANwMAIAFBOGogAkE4aikDADcDACABQcgBaiACQcgBai0AADoAACABIAw3A0AgASACKQMANwMAIAQg\
AUHQARCQARoMGAtBAC0AgNhAGkHQARAZIgRFDRogAikDQCEMIAFByABqIAJByABqEGcgAUEIaiACQQ\
hqKQMANwMAIAFBEGogAkEQaikDADcDACABQRhqIAJBGGopAwA3AwAgAUEgaiACQSBqKQMANwMAIAFB\
KGogAkEoaikDADcDACABQTBqIAJBMGopAwA3AwAgAUE4aiACQThqKQMANwMAIAFByAFqIAJByAFqLQ\
AAOgAAIAEgDDcDQCABIAIpAwA3AwAgBCABQdABEJABGgwXC0EALQCA2EAaQdABEBkiBEUNGSACKQNA\
IQwgAUHIAGogAkHIAGoQZyABQQhqIAJBCGopAwA3AwAgAUEQaiACQRBqKQMANwMAIAFBGGogAkEYai\
kDADcDACABQSBqIAJBIGopAwA3AwAgAUEoaiACQShqKQMANwMAIAFBMGogAkEwaikDADcDACABQThq\
IAJBOGopAwA3AwAgAUHIAWogAkHIAWotAAA6AAAgASAMNwNAIAEgAikDADcDACAEIAFB0AEQkAEaDB\
YLQQAtAIDYQBpB0AEQGSIERQ0YIAIpA0AhDCABQcgAaiACQcgAahBnIAFBCGogAkEIaikDADcDACAB\
QRBqIAJBEGopAwA3AwAgAUEYaiACQRhqKQMANwMAIAFBIGogAkEgaikDADcDACABQShqIAJBKGopAw\
A3AwAgAUEwaiACQTBqKQMANwMAIAFBOGogAkE4aikDADcDACABQcgBaiACQcgBai0AADoAACABIAw3\
A0AgASACKQMANwMAIAQgAUHQARCQARoMFQtBAC0AgNhAGkHwABAZIgRFDRcgAikDICEMIAFBKGogAk\
EoahBVIAFBCGogAkEIaikDADcDACABQRBqIAJBEGopAwA3AwAgAUEYaiACQRhqKQMANwMAIAFB6ABq\
IAJB6ABqLQAAOgAAIAEgDDcDICABIAIpAwA3AwAgBCABQfAAEJABGgwUC0EAIQVBAC0AgNhAGkH4Dh\
AZIgRFDRYgAUH4DWpB2ABqIAJB+ABqKQMANwMAIAFB+A1qQdAAaiACQfAAaikDADcDACABQfgNakHI\
AGogAkHoAGopAwA3AwAgAUH4DWpBCGogAkEoaikDADcDACABQfgNakEQaiACQTBqKQMANwMAIAFB+A\
1qQRhqIAJBOGopAwA3AwAgAUH4DWpBIGogAkHAAGopAwA3AwAgAUH4DWpBKGogAkHIAGopAwA3AwAg\
AUH4DWpBMGogAkHQAGopAwA3AwAgAUH4DWpBOGogAkHYAGopAwA3AwAgASACQeAAaikDADcDuA4gAS\
ACKQMgNwP4DSACQYABaikDACEMIAJBigFqLQAAIQYgAkGJAWotAAAhByACQYgBai0AACEIAkAgAkHw\
DmooAgAiCUUNACACQZABaiIKIAlBBXRqIQtBASEFIAFB2A5qIQkDQCAJIAopAAA3AAAgCUEYaiAKQR\
hqKQAANwAAIAlBEGogCkEQaikAADcAACAJQQhqIApBCGopAAA3AAAgCkEgaiIKIAtGDQEgBUE3Rg0Z\
IAlBIGogCikAADcAACAJQThqIApBGGopAAA3AAAgCUEwaiAKQRBqKQAANwAAIAlBKGogCkEIaikAAD\
cA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Q0PIAFBGGogAkEYaigCADYCACABQRBqIAJBEGopAwA3AwAgASACKQMINwMIIAIpAwAhDCABQSBq\
IAJBIGoQVSABQeAAaiACQeAAai0AADoAACABIAw3AwAgBCABQegAEJABGgwMC0EALQCA2EAaQegAEB\
kiBEUNDiABQRhqIAJBGGooAgA2AgAgAUEQaiACQRBqKQMANwMAIAEgAikDCDcDCCACKQMAIQwgAUEg\
aiACQSBqEFUgAUHgAGogAkHgAGotAAA6AAAgASAMNwMAIAQgAUHoABCQARoMCwtBAC0AgNhAGkHoAh\
AZIgRFDQ0gAigCyAEhCSABQdABaiACQdABahBoIAJB4AJqLQAAIQogASACQcgBEJABIgJB4AJqIAo6\
AAAgAiAJNgLIASAEIAJB6AIQkAEaDAoLQQAtAIDYQBpB4AIQGSIERQ0MIAIoAsgBIQkgAUHQAWogAk\
HQAWoQaSACQdgCai0AACEKIAEgAkHIARCQASICQdgCaiAKOgAAIAIgCTYCyAEgBCACQeACEJABGgwJ\
C0EALQCA2EAaQcACEBkiBEUNCyACKALIASEJIAFB0AFqIAJB0AFqEGogAkG4AmotAAAhCiABIAJByA\
EQkAEiAkG4AmogCjoAACACIAk2AsgBIAQgAkHAAhCQARoMCAtBAC0AgNhAGkGgAhAZIgRFDQogAigC\
yAEhCSABQdABaiACQdABahBrIAJBmAJqLQAAIQogASACQcgBEJABIgJBmAJqIAo6AAAgAiAJNgLIAS\
AEIAJBoAIQkAEaDAcLQQAtAIDYQBpB8AAQGSIERQ0JIAIpAyAhDCABQShqIAJBKGoQVSABQQhqIAJB\
CGopAwA3AwAgAUEQaiACQRBqKQMANwMAIAFBGGogAkEYaikDADcDACABQegAaiACQegAai0AADoAAC\
ABIAw3AyAgASACKQMANwMAIAQgAUHwABCQARoMBgtBAC0AgNhAGkHwABAZIgRFDQggAikDICEMIAFB\
KGogAkEoahBVIAFBCGogAkEIaikDADcDACABQRBqIAJBEGopAwA3AwAgAUEYaiACQRhqKQMANwMAIA\
FB6ABqIAJB6ABqLQAAOgAAIAEgDDcDICABIAIpAwA3AwAgBCABQfAAEJABGgwFC0EALQCA2EAaQdgB\
EBkiBEUNByACQcgAaikDACEMIAIpA0AhDSABQdAAaiACQdAAahBnIAFByABqIAw3AwAgAUEIaiACQQ\
hqKQMANwMAIAFBEGogAkEQaikDADcDACABQRhqIAJBGGopAwA3AwAgAUEgaiACQSBqKQMANwMAIAFB\
KGogAkEoaikDADcDACABQTBqIAJBMGopAwA3AwAgAUE4aiACQThqKQMANwMAIAFB0AFqIAJB0AFqLQ\
AAOgAAIAEgDTcDQCABIAIpAwA3AwAgBCABQdgBEJABGgwEC0EALQCA2EAaQdgBEBkiBEUNBiACQcgA\
aikDACEMIAIpA0AhDSABQdAAaiACQdAAahBnIAFByABqIAw3AwAgAUEIaiACQQhqKQMANwMAIAFBEG\
ogAkEQaikDADcDACABQRhqIAJBGGopAwA3AwAgAUEgaiACQSBqKQMANwMAIAFBKGogAkEoaikDADcD\
ACABQTBqIAJBMGopAwA3AwAgAUE4aiACQThqKQMANwMAIAFB0AFqIAJB0AFqLQAAOgAAIAEgDTcDQC\
ABIAIpAwA3AwAgBCABQdgBEJABGgwDC0EALQCA2EAaQYADEBkiBEUNBSACKALIASEJIAFB0AFqIAJB\
0AFqEGwgAkH4AmotAAAhCiABIAJByAEQkAEiAkH4AmogCjoAACACIAk2AsgBIAQgAkGAAxCQARoMAg\
tBAC0AgNhAGkHgAhAZIgRFDQQgAigCyAEhCSABQdABaiACQdABahBpIAJB2AJqLQAAIQogASACQcgB\
EJABIgJB2AJqIAo6AAAgAiAJNgLIASAEIAJB4AIQkAEaDAELQQAtAIDYQBpB6AAQGSIERQ0DIAFBEG\
ogAkEQaikDADcDACABQRhqIAJBGGopAwA3AwAgASACKQMINwMIIAIpAwAhDCABQSBqIAJBIGoQVSAB\
QeAAaiACQeAAai0AADoAACABIAw3AwAgBCABQegAEJABGgsgACAAKAIAQX9qNgIAQQAtAIDYQBpBDB\
AZIgJFDQIgAiAENgIIIAIgAzYC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gAEGAAWpBwAAgAyAEEBcgByAAQcABakHAACADIAQQFyAHIABBgAJqQcAAIAMgBBAXIAcgAEHAAm\
pBwAAgAyAEEBcgByAAQYADakHAACADIAQQFyAHIABBwANqQcAAIAMgBBAXIAcgAEGABGpBwAAgAyAE\
EBcgByAAQcAEakHAACADIAQQFyAHIABBgAVqQcAAIAMgBBAXIAcgAEHABWpBwAAgAyAEEBcgByAAQY\
AGakHAACADIAQQFyAHIABBwAZqQcAAIAMgBBAXIAcgAEGAB2pBwAAgAyAEEBcgByAAQcAHakHAACAD\
IARBAnIQFyAFIAgpAwA3ABggBSALKQMANwAQIAUgDCkDADcACCAFIAcpAwA3AAALIAFFDQEgB0GAAW\
pBOGpCADcDACAHQYABakEwakIANwMAIAdBgAFqQShqQgA3AwAgB0GAAWpBIGpCADcDACAHQYABakEY\
akIANwMAIAdBgAFqQRBqQgA3AwAgB0GAAWpBCGpCADcDACAHQYABakHIAGoiCCACQQhqKQIANwMAIA\
dBgAFqQdAAaiILIAJBEGopAgA3AwAgB0GAAWpB2ABqIgwgAkEYaikCADcDACAHQgA3A4ABIAcgBDoA\
6gEgB0EAOwHoASAHIAIpAgA3A8ABIAcgCq0gA3w3A+ABIAdBgAFqIAAgCWogARAvIQQgB0HIAGogCC\
kDADcDACAHQdAAaiALKQMANwMAIAdB2ABqIAwpAwA3AwAgB0EIaiAEQQhqKQMANwMAIAdBEGogBEEQ\
aikDADcDACAHQRhqIARBGGopAwA3AwAgB0EgaiAEQSBqKQMANwMAIAdBKGogBEEoaikDADcDACAHQT\
BqIARBMGopAwA3AwAgB0E4aiAEQThqKQMANwMAIAcgBykDwAE3A0AgByAEKQMANwMAIActAOoBIQQg\
By0A6QEhACAHKQPgASEDIAcgBy0A6AEiAToAaCAHIAM3A2AgByAEIABFckECciIEOgBpIAdB8AFqQR\
hqIgAgDCkDADcDACAHQfABakEQaiICIAspAwA3AwAgB0HwAWpBCGoiCSAIKQMANwMAIAcgBykDwAE3\
A/ABIAdB8AF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uRo7Pw2wA3AzggA0Lr+obav7X2wR83AzAgA0Kf2PnZwpHagpt/NwMoIANC0Y\
Wa7/rPlIfRADcDICADQvHt9Pilp/2npX83AxggA0Kr8NP0r+68tzw3AxAgA0K7zqqm2NDrs7t/NwMI\
IANClJL3lf/M+YTqADcDACADQcgBakEAOgAADBcLIAFBCGooAgAiA0IANwNAIANC+cL4m5Gjs/DbAD\
cDOCADQuv6htq/tfbBHzcDMCADQp/Y+dnCkdqCm383AyggA0LRhZrv+s+Uh9EANwMgIANC8e30+KWn\
/aelfzcDGCADQqvw0/Sv7ry3PDcDECADQrvOqqbY0Ouzu383AwggA0KokveV/8z5hOoANwMAIANByA\
FqQQA6AAAMFgsgAUEIaigCACIDQgA3A0AgA0L5wvibkaOz8NsANwM4IANC6/qG2r+19sEfNwMwIANC\
n9j52cKR2oKbfzcDKCADQtGFmu/6z5SH0QA3AyAgA0Lx7fT4paf9p6V/NwMYIANCq/DT9K/uvLc8Nw\
MQIANCu86qptjQ67O7fzcDCCADQriS95X/zPmE6gA3AwAgA0HIAWpBADoAAAwVCyABQQhqKAIAIgNC\
ADcDICADQquzj/yRo7Pw2wA3AxggA0L/pLmIxZHagpt/NwMQIANC8ua746On/aelfzcDCCADQsfMo9\
jW0Ouzu383AwAgA0HoAGpBADoAAAwUCyABQQhqKAIAIQMgAkEIakIANwMAIAJBEGpCADcDACACQRhq\
QgA3AwAgAkEgakIANwMAIAJBKGpCADcDACACQTBqQgA3AwAgAkE4akIANwMAIAJByABqIANBCGopAw\
A3AwAgAkHQAGogA0EQaikDADcDACACQdgAaiADQRhqKQMANwMAIAJCADcDACACIAMpAwA3A0AgA0GK\
AWoiBC0AACEFIANBIGogAkHgABCQARogBCAFOgAAIANBiAFqQQA7AQAgA0GAAWpCADcDACADQfAOai\
gCAEUNEyADQQA2AvAODBMLIAFBCGooAgBBAEHIARCOASIDQeACakEAOgAAIANBGDYCyAEMEgsgAUEI\
aigCAEEAQcgBEI4BIgNB2AJqQQA6AAAgA0EYNgLIAQwRCyABQQhqKAIAQQBByAEQjgEiA0G4AmpBAD\
oAACADQRg2AsgBDBALIAFBCGooAgBBAEHIARCOASIDQZgCakEAOgAAIANBGDYCyAEMDwsgAUEIaigC\
ACIDQv6568XpjpWZEDcDCCADQoHGlLqW8ermbzcDACADQgA3AxAgA0HYAGpBADoAAAwOCyABQQhqKA\
IAIgNC/rnrxemOlZkQNwMIIANCgcaUupbx6uZvNwMAIANCADcDECADQdgAakEAOgAADA0LIAFBCGoo\
AgAiA0IANwMAIANBACkDoIxANwMIIANBEGpBACkDqIxANwMAIANBGGpBACgCsIxANgIAIANB4ABqQQ\
A6AAAMDAsgAUEIaigCACIDQfDDy558NgIYIANC/rnrxemOlZkQNwMQIANCgcaUupbx6uZvNwMIIANC\
ADcDACADQeAAakEAOgAADAsLIAFBCGooAgBBAEHIARCOASIDQeACakEAOgAAIANBGDYCyAEMCgsgAU\
EIaigCAEEAQcgBEI4BIgNB2AJqQQA6AAAgA0EYNgLIAQwJCyABQQhqKAIAQQBByAEQjgEiA0G4AmpB\
ADoAACADQRg2AsgBDAgLIAFBCGooAgBBAEHIARCOASIDQZgCakEAOgAAIANBGDYCyAEMBwsgAUEIai\
gCACIDQQApA7iMQDcDACADQgA3AyAgA0EIakEAKQPAjEA3AwAgA0EQakEAKQPIjEA3AwAgA0EYakEA\
KQPQjEA3AwAgA0HoAGpBADoAAAwGCyABQQhqKAIAIgNBACkD2IxANwMAIANCADcDICADQQhqQQApA+\
CMQDcDACADQRBqQQApA+iMQDcDACADQRhqQQApA/CMQDcDACADQegAakEAOgAADAULIAFBCGooAgAi\
A0IANwNAIANBACkD+IxANwMAIANByABqQgA3AwAgA0EIakEAKQOAjUA3AwAgA0EQakEAKQOIjUA3Aw\
AgA0EYakEAKQOQjUA3AwAgA0EgakEAKQOYjUA3AwAgA0EoakEAKQOgjUA3AwAgA0EwakEAKQOojUA3\
AwAgA0E4akEAKQOwjUA3AwAgA0HQAWpBADoAAAwECyABQQhqK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AgAEEoaiABQcgAaikDADcDACAAQTBqIAFB0ABqKQMANwMAIABB\
OGogAUHYAGopAwA3AwAgAUGKAWotAAAhBCABQYkBai0AACEFIAFBgAFqKQMAIRYgACABQYgBai0AAD\
oAaCAAIBY3A2AgACAEIAVFckECcjoAaQwBCyABQZABaiEGAkACQAJAAkAgAUGJAWotAAAiBEEGdEEA\
IAFBiAFqLQAAIgdrRw0AIANBfmohBCADQQFNDQEgAUGKAWotAAAhCCACQRhqIAYgBEEFdGoiBUEYai\
kAACIWNwMAIAJBEGogBUEQaikAACIXNwMAIAJBCGogBUEIaikAACIYNwMAIAJBIGogA0EFdCAGakFg\
aiIJKQAAIhk3AwAgAkEoaiAJQQhqKQAAIho3AwAgAkEwaiAJQRBqKQAAIhs3AwAgAkE4aiAJQRhqKQ\
AAIhw3AwAgAiAFKQAAIh03AwAgAkHwAGpBOGogHDcDACACQfAAakEwaiAbNwMAIAJB8ABqQShqIBo3\
AwAgAkHwAGpBIGogGTcDACACQfAAakEYaiAWNwMAIAJB8ABqQRBqIBc3AwAgAkHwAGpBCGogGDcDAC\
ACIB03A3AgAkHIAWogAUEYaikDADcDACACQcABaiABQRBqKQMANwMAIAJBuAFqIAFBCGopAwA3AwAg\
AiABKQMANwOwASACIAJB8ABqQeAAEJABIgUgCEEEciIJOgBpQcAAIQcgBUHAADoAaEIAIRYgBUIANw\
NgIAkhCiAERQ0DDAILIAJB8ABqQcgAaiABQegAaikDADcDACACQfAAakHQAGogAUHwAGopAwA3AwAg\
AkHwAGpB2ABqIAFB+ABqKQMANwMAIAJB+ABqIAFBKGopAwA3AwAgAkGAAWogAUEwaikDADcDACACQY\
gBaiABQThqKQMANwMAIAJBkAFqIAFBwABqKQMANwMAIAJB8ABqQShqIAFByABqKQMANwMAIAJB8ABq\
QTBqIAFB0ABqKQMANwMAIAJB8ABqQThqIAFB2ABqKQMANwMAIAIgASkDIDcDcCACIAFB4ABqKQMANw\
OwASABQYABaikDACEWIAFBigFqLQAAIQUgAi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AkEQaiEKIAJBGGohCyADQX5qQTdJIQwgAkGvAWohDSACQa4BaiEOIAJBrQFq\
IQ8gAkGrAWohECACQaoBaiERIAJBqQFqIRIgAkGnAWohEyACQaYBaiEUIAJBpQFqIRUgAkGjAWohFi\
ACQaIBaiEXIAJBoQFqIRggAkGfAWohGSACQZ4BaiEaIAJBnQFqIRsgAkGbAWohHCACQZoBaiEdIAJB\
mQFqIR4DQCAAIAY2AvAOIAkgACAFaiIDQfgAaikAADcDACAKIANBgAFqKQAANwMAIAsgA0GIAWopAA\
A3AwAgAiADQfAAaikAADcDACAGRQ0CIAAgBkF/aiIfNgLwDiACQZABakEYaiIgIANB6ABqIiEpAAAi\
ATcDACACQZABakEQaiIiIANB4ABqIiMpAAAiRDcDACACQZABakEIaiIkIANB2ABqIiUpAAAiRTcDAC\
ACIANB0ABqIiYpAAAiRjcDkAEgCCACKQMANwAAIAhBCGogCSkDADcAACAIQRBqIAopAwA3AAAgCEEY\
aiALKQMANwAAIAJBIGpBCGogRTcDACACQSBqQRBqIEQ3AwAgAkEgakEYaiABNwMAIAJBIGpBIGogCC\
kDADcDACACQSBqQShqIAJBkAFqQShqKQMANwMAIAJBIGpBMGogAkGQAWpBMGopAwA3AwAgAkEgakE4\
aiACQZABakE4aikDADcDACACIEY3AyAgAC0AigEhJyAHQRhqIABBGGoiKCkDADcDACAHQRBqIABBEG\
oiKSkDADcDACAHQQhqIABBCGoiKikDADcDACAHIAApAwA3AwAgAkHAADoAiAEgAkIANwOAASACICdB\
BHIiJzoAiQEgICAoKQIANwMAICIgKSkCADcDACAkICopAgA3AwAgAiAAKQIANwOQASACQZABaiACQS\
BqQcAAQgAgJxAXIA0tAAAhJyAOLQAAISggDy0AACEpIBAtAAAhKiARLQAAISsgEi0AACEsICAtAAAh\
ICATLQAAIS0gFC0AACEuIBUtAAAhLyAWLQAAITAgFy0AACExIBgtAAAhMiAiLQAAISIgGS0AACEzIB\
otAAAhNCAbLQAAITUgHC0AACE2IB0tAAAhNyAeLQAAITggJC0AACEkIAItAKwBITkgAi0ApAEhOiAC\
LQCcASE7IAItAJcBITwgAi0AlgEhPSACLQCVASE+IAItAJQBIT8gAi0AkwEhQCACLQCSASFBIAItAJ\
EBIUIgAi0AkAEhQyAMRQ0DICYgQzoAACAmIEI6AAEgA0HuAGogKDoAACADQe0AaiApOgAAIANB7ABq\
IDk6AAAgA0HqAGogKzoAACADQekAaiAsOgAAICEgIDoAACADQeYAaiAuOgAAIANB5QBqIC86AAAgA0\
HkAGogOjoAACADQeIAaiAxOgAAIANB4QBqIDI6AAAgIyAiOgAAIANB3gBqIDQ6AAAgA0HdAGogNToA\
ACADQdwAaiA7OgAAIANB2gBqIDc6AAAgA0HZAGogODoAACAlICQ6AAAgA0HWAGogPToAACADQdUAai\
A+OgAAIANB1ABqID86AAAgJiBBOgACIANB7wBqICc6AAAgA0HrAGogKjoAACADQecAaiAtOgAAIANB\
4wBqIDA6AAAgA0HfAGogMzoAACADQdsAaiA2OgAAIANB1wBqIDw6AAAgJkEDaiBAOgAAIAAgBjYC8A\
4gBUFgaiEFIB8hBiAfIARPDQALCyACQdABaiQADwtBuJLAAEErQaSFwAAQcQALIAJBrQFqICk6AAAg\
AkGpAWogLDoAACACQaUBaiAvOgAAIAJBoQFqIDI6AAAgAkGdAWogNToAACACQZkBaiA4OgAAIAJBlQ\
FqID46AAAgAkGuAWogKDoAACACQaoBaiArOgAAIAJBpgFqIC46AAAgAkGiAWogMToAACACQZ4BaiA0\
OgAAIAJBmgFqIDc6AAAgAkGWAWogPToAACACQa8BaiAnOgAAIAJBqwFqICo6AAAgAkGnAWogLToAAC\
ACQaMBaiAwOgAAIAJBnwFqIDM6AAAgAkGbAWogNjoAACACQZcBaiA8OgAAIAIgOToArAEgAiAgOgCo\
ASACIDo6AKQBIAIgIjoAoAEgAiA7OgCcASACICQ6AJgBIAIgPzoAlAEgAiBDOgCQASACIEI6AJEBIA\
IgQToAkgEgAiBAOgCTAUGMksAAIAJBkAFqQeyGwABBt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AtBICABQZSEwAAQYAALQSAgCUGkhMAAEGIA\
C5gEAgt/A34jAEGgAWsiAiQAIAEgASkDQCABQcgBai0AACIDrXw3A0AgAUHIAGohBAJAIANBgAFGDQ\
AgBCADakEAQYABIANrEI4BGgsgAUEAOgDIASABIARCfxAQIAJBIGpBCGoiAyABQQhqIgUpAwAiDTcD\
ACACQSBqQRBqIgQgAUEQaiIGKQMAIg43AwAgAkEgakEYaiIHIAFBGGoiCCkDACIPNwMAIAJBIGpBIG\
ogASkDIDcDACACQSBqQShqIAFBKGoiCSkDADcDACACQQhqIgogDTcDACACQRBqIgsgDjcDACACQRhq\
IgwgDzcDACACIAEpAwAiDTcDICACIA03AwAgAUEAOgDIASABQgA3A0AgAUE4akL5wvibkaOz8NsANw\
MAIAFBMGpC6/qG2r+19sEfNwMAIAlCn9j52cKR2oKbfzcDACABQtGFmu/6z5SH0QA3AyAgCELx7fT4\
paf9p6V/NwMAIAZCq/DT9K/uvLc8NwMAIAVCu86qptjQ67O7fzcDACABQqiS95X/zPmE6gA3AwAgBy\
AMKQMANwMAIAQgCykDADcDACADIAopAwA3AwAgAiACKQMANwMgQQAtAIDYQBoCQEEgEBkiAQ0AAAsg\
ASACKQMgNwAAIAFBGGogBykDADcAACABQRBqIAQpAwA3AAAgAUEIaiADKQMANwAAIABBIDYCBCAAIA\
E2AgAgAkGgAWokAAu/AwIGfwF+IwBBkANrIgIkACACQSBqIAFB0AEQkAEaIAIgAikDYCACQegBai0A\
ACIDrXw3A2AgAkHoAGohBAJAIANBgAFGDQAgBCADakEAQYABIANrEI4BGgsgAkEAOgDoASACQSBqIA\
RCfxAQIAJBkAJqQQhqIgMgAkEgakEIaikDADcDACACQZACakEQaiIEIAJBIGpBEGopAwA3AwAgAkGQ\
AmpBGGoiBSACQSBqQRhqKQMANwMAIAJBkAJqQSBqIAIpA0A3AwAgAkGQAmpBKGogAkEgakEoaikDAD\
cDACACQZACakEwaiACQSBqQTBqKQMANwMAIAJBkAJqQThqIAJBIG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QFxIAFyQQJyNgIAIAIgAWoiBCAEKAIEQQFy\
NgIEIAIgARAkDAELIAIoAgAhAiAAIAQ2AgQgACACIAFqNgIACwJAIAAoAgQiAUEDcUUNACABQXhxIg\
IgA0EQak0NACAAIAFBAXEgA3JBAnI2AgQgACADaiIBIAIgA2siA0EDcjYCBCAAIAJqIgIgAigCBEEB\
cjYCBCABIAMQJAsgAEEIaiECCyACC7gDAQF/IAIgAi0AqAEiA2pBAEGoASADaxCOASEDIAJBADoAqA\
EgA0EfOgAAIAIgAi0ApwFBgAFyOgCnASABIAEpAwAgAikAAIU3AwAgASABKQMIIAIpAAiFNwMIIAEg\
ASkDECACKQAQhTcDECABIAEpAxggAikAGIU3AxggASABKQMgIAIpACCFNwMgIAEgASkDKCACKQAohT\
cDKCABIAEpAzAgAikAMIU3AzAgASABKQM4IAIpADiFNwM4IAEgASkDQCACKQBAhTcDQCABIAEpA0gg\
AikASIU3A0ggASABKQNQIAIpAFCFNwNQIAEgASkDWCACKQBYhTcDWCABIAEpA2AgAikAYIU3A2AgAS\
ABKQNoIAIpAGiFNwNoIAEgASkDcCACKQBwhTcDcCABIAEpA3ggAikAeIU3A3ggASABKQOAASACKQCA\
AYU3A4ABIAEgASkDiAEgAikAiAGFNwOIASABIAEpA5ABIAIpAJABhTcDkAEgASABKQOYASACKQCYAY\
U3A5gBIAEgASkDoAEgAikAoAGFNwOgASABIAEoAsgBECUgACABQcgBEJABIAEoAsgBNgLIAQvtAgEE\
fyMAQeABayIDJAACQAJAAkACQCACDQBBASEEDAELIAJBf0wNASACEBkiBEUNAiAEQXxqLQAAQQNxRQ\
0AIARBACACEI4BGgsgA0EIaiABECEgA0GAAWpBCGpCADcDACADQYABakEQakIANwMAIANBgAFqQRhq\
QgA3AwAgA0GAAWpBIGpCADcDACADQagBakIANwMAIANBsAFqQgA3AwAgA0G4AWpCADcDACADQcgBai\
ABQQhqKQMANwMAIANB0AFqIAFBEGopAwA3AwAgA0HYAWogAUEYaikDADcDACADQgA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IAcpAwA3AwAgAkEg\
akEQaiIHIAYpAwA3AwAgAyAFKQMANwMAIAIgAikDADcDIEEALQCA2EAaAkBBIBAZIgENAAALIAEgAi\
kDIDcAACABQRhqIAQpAwA3AAAgAUEQaiAHKQMANwAAIAFBCGogAykDADcAACAAQSA2AgQgACABNgIA\
IAJB4ABqJAALkwMBAX8gASABLQCQASIDakEAQZABIANrEI4BIQMgAUEAOgCQASADQQE6AAAgASABLQ\
CPAUGAAXI6AI8BIAAgACkDACABKQAAhTcDACAAIAApAwggASkACIU3AwggACAAKQMQIAEpABCFNwMQ\
IAAgACkDGCABKQAYhTcDGCAAIAApAyAgASkAIIU3AyAgACAAKQMoIAEpACiFNwMoIAAgACkDMCABKQ\
AwhTcDMCAAIAApAzggASkAOIU3AzggACAAKQNAIAEpAECFNwNAIAAgACkDSCABKQBIhTcDSCAAIAAp\
A1AgASkAUIU3A1AgACAAKQNYIAEpAFiFNwNYIAAgACkDYCABKQBghTcDYCAAIAApA2ggASkAaIU3A2\
ggACAAKQNwIAEpAHCFNwNwIAAgACkDeCABKQB4hTcDeCAAIAApA4ABIAEpAIABhTcDgAEgACAAKQOI\
ASABKQCIAYU3A4gBIAAgACgCyAEQJSACIAApAwA3AAAgAiAAKQMINwAIIAIgACkDEDcAECACIAApAx\
g+ABgLkwMBAX8gASABLQCQASIDakEAQZABIANrEI4BIQMgAUEAOgCQASADQQY6AAAgASABLQCPAUGA\
AXI6AI8BIAAgACkDACABKQAAhTcDACAAIAApAwggASkACIU3AwggACAAKQMQIAEpABCFNwMQIAAgAC\
kDGCABKQAYhTcDGCAAIAApAyAgASkAIIU3AyAgACAAKQMoIAEpACiFNwMoIAAgACkDMCABKQAwhTcD\
MCAAIAApAzggASkAOIU3AzggACAAKQNAIAEpAECFNwNAIAAgACkDSCABKQBIhTcDSCAAIAApA1AgAS\
kAUIU3A1AgACAAKQNYIAEpAFiFNwNYIAAgACkDYCABKQBghTcDYCAAIAApA2ggASkAaIU3A2ggACAA\
KQN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xA3ABAgAiAA\
KQMYNwAYC4ADAQF/IAEgAS0AiAEiA2pBAEGIASADaxCOASEDIAFBADoAiAEgA0EBOgAAIAEgAS0Ahw\
FBgAFyOgCHASAAIAApAwAgASkAAIU3AwAgACAAKQMIIAEpAAiFNwMIIAAgACkDECABKQAQhTcDECAA\
IAApAxggASkAGIU3AxggACAAKQMgIAEpACCFNwMgIAAgACkDKCABKQAohTcDKCAAIAApAzAgASkAMI\
U3AzAgACAAKQM4IAEpADiFNwM4IAAgACkDQCABKQBAhTcDQCAAIAApA0ggASkASIU3A0ggACAAKQNQ\
IAEpAFCFNwNQIAAgACkDWCABKQBYhTcDWCAAIAApA2AgASkAYIU3A2AgACAAKQNoIAEpAGiFNwNoIA\
AgACkDcCABKQBwhTcDcCAAIAApA3ggASkAeIU3A3ggACAAKQOAASABKQCAAYU3A4ABIAAgACgCyAEQ\
JSACIAApAwA3AAAgAiAAKQMINwAIIAIgACkDEDcAECACIAApAxg3ABgL7AIBAX8gAiACLQCIASIDak\
EAQYgBIANrEI4BIQMgAkEAOgCIASADQR86AAAgAiACLQCHAUGAAXI6AIcBIAEgASkDACACKQAAhTcD\
ACABIAEpAwggAikACIU3AwggASABKQMQIAIpABCFNwMQIAEgASkDGCACKQAYhTcDGCABIAEpAyAgAi\
kAIIU3AyAgASABKQMoIAIpACiFNwMoIAEgASkDMCACKQAwhTcDMCABIAEpAzggAikAOIU3AzggASAB\
KQNAIAIpAECFNwNAIAEgASkDSCACKQBIhTcDSCABIAEpA1AgAikAUIU3A1AgASABKQNYIAIpAFiFNw\
NYIAEgASkDYCACKQBghTcDYCABIAEpA2ggAikAaIU3A2ggASABKQNwIAIpAHCFNwNwIAEgASkDeCAC\
KQB4hTcDeCABIAEpA4ABIAIpAIABhTcDgAEgASABKALIARAlIAAgAUHIARCQASABKALIATYCyAEL3g\
IBAX8CQCACRQ0AIAEgAkGQAWxqIQMgACgCACECA0AgAiACKQMAIAEpAACFNwMAIAIgAikDCCABKQAI\
hTcDCCACIAIpAxAgASkAEIU3AxAgAiACKQMYIAEpABiFNwMYIAIgAikDICABKQAghTcDICACIAIpAy\
ggASkAKIU3AyggAiACKQMwIAEpADCFNwMwIAIgAikDOCABKQA4hTcDOCACIAIpA0AgASkAQIU3A0Ag\
AiACKQNIIAEpAEiFNwNIIAIgAikDUCABKQBQhTcDUCACIAIpA1ggASkAWIU3A1ggAiACKQNgIAEpAG\
CFNwNgIAIgAikDaCABKQBohTcDaCACIAIpA3AgASkAcIU3A3AgAiACKQN4IAEpAHiFNwN4IAIgAikD\
gAEgASkAgAGFNwOAASACIAIpA4gBIAEpAIgBhTcDiAEgAiACKALIARAlIAFBkAFqIgEgA0cNAAsLC7\
oCAgN/An4jAEHgAGsiAyQAIAApAwAhBiABIAEtAEAiBGoiBUGAAToAACADQQhqQRBqIABBGGooAgA2\
AgAgA0EIakEIaiAAQRBqKQIANwMAIAMgACkCCDcDCCAGQgmGIQYgBK1CA4YhBwJAIARBP3MiAEUNAC\
AFQQFqQQAgABCOARoLIAYgB4QhBgJAAkAgBEE4c0EISQ0AIAEgBjcAOCADQQhqIAEQEgwBCyADQQhq\
IAEQEiADQdAAakIANwMAIANByABqQgA3AwAgA0HAAGpCADcDACADQThqQgA3AwAgA0EwakIANwMAIA\
NBKGpCADcDACADQgA3AyAgAyAGNwNYIANBCGogA0EgahASCyABQQA6AEAgAiADKAIINgAAIAIgAykC\
DDcABCACIAMpAhQ3AAwgA0HgAGokAAvoAgIBfxV+AkAgAkUNACABIAJBqAFsaiEDA0AgACgCACICKQ\
MAIQQgAikDCCEFIAIpAxAhBiACKQMYIQcgAikDICEIIAIpAyghCSACKQMwIQogAikDOCELIAIpA0Ah\
DCACKQNIIQ0gAikDUCEOIAIpA1ghDyACKQNgIRAgAikDaCERIAIpA3AhEiACKQN4IRMgAikDgAEhFC\
ACKQOIASEVIAIpA5ABIRYgAikDmAEhFyACKQOgASEYIAIgAigCyAEQJSABIBg3AKABIAEgFzcAmAEg\
ASAWNwCQASABIBU3AIgBIAEgFDcAgAEgASATNwB4IAEgEjcAcCABIBE3AGggASAQNwBgIAEgDzcAWC\
ABIA43AFAgASANNwBIIAEgDDcAQCABIAs3ADggASAKNwAwIAEgCTcAKCABIAg3ACAgASAHNwAYIAEg\
BjcAECABIAU3AAggASAENwAAIAFBqAFqIgEgA0cNAAsLC74CAQV/IAAoAhghAQJAAkACQCAAKAIMIg\
IgAEcNACAAQRRBECAAQRRqIgIoAgAiAxtqKAIAIgQNAUEAIQIMAgsgACgCCCIEIAI2AgwgAiAENgII\
DAELIAIgAEEQaiADGyEDA0AgAyEFIAQiAkEUaiIEIAJBEGogBCgCACIEGyEDIAJBFEEQIAQbaigCAC\
IEDQALIAVBADYCAAsCQCABRQ0AAkACQCAAKAIcQQJ0QZzUwABqIgQoAgAgAEYNACABQRBBFCABKAIQ\
IABGG2ogAjYCACACDQEMAgsgBCACNgIAIAINAEEAQQAoArjXQEF+IAAoAhx3cTYCuNdADwsgAiABNg\
IYAkAgACgCECIERQ0AIAIgBDYCECAEIAI2AhgLIABBFGooAgAiBEUNACACQRRqIAQ2AgAgBCACNgIY\
DwsLwAICBX8CfiMAQfABayICJAAgAkEgaiABQfAAEJABGiACIAIpA0AgAkGIAWotAAAiA618NwNAIA\
JByABqIQQCQCADQcAARg0AIAQgA2pBAEHAACADaxCOARoLIAJBADoAiAEgAkEgaiAEQX8QEyACQZAB\
akEIaiACQSBqQQhqKQMAIgc3AwAgAkGQAWpBGGogAkEgakEYaikDACIINwMAIAJBGGoiBCAINwMAIA\
JBEGoiBSACKQMwNwMAIAJBCGoiBiAHNwMAIAIgAikDICIHNwOwASACIAc3A5ABIAIgBzcDAEEALQCA\
2EAaAkBBIBAZIgMNAAALIAMgAikDADcAACADQRhqIAQpAwA3AAAgA0EQaiAFKQMANwAAIANBCGogBi\
kDADcAACABECAgAEEgNgIEIAAgAzYCACACQfABaiQAC7gCAQN/IwBBgAZrIgMkAAJAAkACQAJAAkAC\
QCACDQBBASEEDAELIAJ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IU3A2AgAiACKQNoIAEpAGiFNwNoIAIgAikDcCABKQBwhTcDcCACIAIpA3ggAS\
kAeIU3A3ggAiACKQOAASABKQCAAYU3A4ABIAIgAigCyAEQJSABQYgBaiIBIANHDQALCwvNAgEBfyAB\
IAEtAGgiA2pBAEHoACADaxCOASEDIAFBADoAaCADQQE6AAAgASABLQBnQYABcjoAZyAAIAApAwAgAS\
kAAIU3AwAgACAAKQMIIAEpAAiFNwMIIAAgACkDECABKQAQhTcDECAAIAApAxggASkAGIU3AxggACAA\
KQMgIAEpACCFNwMgIAAgACkDKCABKQAohTcDKCAAIAApAzAgASkAMIU3AzAgACAAKQM4IAEpADiFNw\
M4IAAgACkDQCABKQBAhTcDQCAAIAApA0ggASkASIU3A0ggACAAKQNQIAEpAFCFNwNQIAAgACkDWCAB\
KQBYhTcDWCAAIAApA2AgASkAYIU3A2AgACAAKALIARAlIAIgACkDADcAACACIAApAwg3AAggAiAAKQ\
MQNwAQIAIgACkDGDcAGCACIAApAyA3ACAgAiAAKQMoNwAoC80CAQF/IAEgAS0AaCIDakEAQegAIANr\
EI4BIQMgAUEAOgBoIANBBjoAACABIAEtAGdBgAFyOgBnIAAgACkDACABKQAAhTcDACAAIAApAwggAS\
kACIU3AwggACAAKQMQIAEpABCFNwMQIAAgACkDGCABKQAYhTcDGCAAIAApAyAgASkAIIU3AyAgACAA\
KQMoIAEpACiFNwMoIAAgACkDMCABKQAwhTcDMCAAIAApAzggASkAOIU3AzggACAAKQNAIAEpAECFNw\
NAIAAgACkDSCABKQBIhTcDSCAAIAApA1AgASkAUIU3A1AgACAAKQNYIAEpAFiFNwNYIAAgACkDYCAB\
KQBghTcDYCAAIAAoAsgBECUgAiAAKQMANwAAIAIgACkDCDcACCACIAApAxA3ABAgAiAAKQMYNwAYIA\
IgACkDIDcAICACIAApAyg3ACgLrwIBA38jAEGwBGsiAyQAAkACQAJAAkACQAJAIAINAEEBIQQMAQsg\
AkF/TA0BIAIQGSIERQ0CIARBfGotAABBA3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MANwAQIANBwABqJAALoQIBAX8gASABLQBIIgNqQQBByAAgA2sQjg\
EhAyABQQA6AEggA0EBOgAAIAEgAS0AR0GAAXI6AEcgACAAKQMAIAEpAACFNwMAIAAgACkDCCABKQAI\
hTcDCCAAIAApAxAgASkAEIU3AxAgACAAKQMYIAEpABiFNwMYIAAgACkDICABKQAghTcDICAAIAApAy\
ggASkAKIU3AyggACAAKQMwIAEpADCFNwMwIAAgACkDOCABKQA4hTcDOCAAIAApA0AgASkAQIU3A0Ag\
ACAAKALIARAlIAIgACkDADcAACACIAApAwg3AAggAiAAKQMQNwAQIAIgACkDGDcAGCACIAApAyA3AC\
AgAiAAKQMoNwAoIAIgACkDMDcAMCACIAApAzg3ADgLoQIBAX8gASABLQBIIgNqQQBByAAgA2sQjgEh\
AyABQQA6AEggA0EGOgAAIAEgAS0AR0GAAXI6AEcgACAAKQMAIAEpAACFNwMAIAAgACkDCCABKQAIhT\
cDCCAAIAApAxAgASkAEIU3AxAgACAAKQMYIAEpABiFNwMYIAAgACkDICABKQAghTcDICAAIAApAygg\
ASkAKIU3AyggACAAKQMwIAEpADCFNwMwIAAgACkDOCABKQA4hTcDOCAAIAApA0AgASkAQIU3A0AgAC\
AAKALIARAlIAIgACkDADcAACACIAApAwg3AAggAiAAKQMQNwAQIAIgACkDGDcAGCACIAApAyA3ACAg\
AiAAKQMoNwAoIAIgACkDMDcAMCACIAApAzg3ADgLgAIBBX8jAEHAAGsiAiQAIAJBIGpBGGoiA0IANw\
MAIAJBIGpBEGoiBEIANwMAIAJBIGpBCGoiBUIANwMAIAJCADcDICABIAFB0AFqIAJBIGoQOSABQQBB\
yAEQjgEiAUHYAmpBADoAACABQRg2AsgBIAJBCGoiBiAFKQMANwMAIAJBEGoiBSAEKQMANwMAIAJBGG\
oiBCADKQMANwMAIAIgAikDIDcDAEEALQCA2EAaAkBBIBAZIgENAAALIAEgAikDADcAACABQRhqIAQp\
AwA3AAAgAUEQaiAFKQMANwAAIAFBCGogBikDADcAAC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iACQYADakEYaiIDQgA3AwAgAkGAA2pBEG\
oiBEIANwMAIAJBgANqQQhqIgVCADcDACACQgA3A4ADIAJBIGogAkHwAWogAkGAA2oQOCACQRhqIgYg\
AykDADcDACACQRBqIgcgBCkDADcDACACQQhqIgQgBSkDADcDACACIAIpA4ADNwMAQQAtAIDYQBoCQE\
EgEBkiAw0AAAsgAyACKQMANwAAIANBGGogBikDADcAACADQRBqIAcpAwA3AAAgA0EIaiAEKQMANwAA\
IAEQICAAQSA2AgQgACADNgIAIAJBoANqJAALiAIBAX8CQCACRQ0AIAEgAkHoAGxqIQMgACgCACECA0\
AgAiACKQMAIAEpAACFNwMAIAIgAikDCCABKQAIhTcDCCACIAIpAxAgASkAEIU3AxAgAiACKQMYIAEp\
ABiFNwMYIAIgAikDICABKQAghTcDICACIAIpAyggASkAKIU3AyggAiACKQMwIAEpADCFNwMwIAIgAi\
kDOCABKQA4hTcDOCACIAIpA0AgASkAQIU3A0AgAiACKQNIIAEpAEiFNwNIIAIgAikDUCABKQBQhTcD\
UCACIAIpA1ggASkAWIU3A1ggAiACKQNgIAEpAGCFNwNgIAIgAigCyAEQJSABQegAaiIBIANHDQALCw\
vuAQEHfyMAQRBrIgMkACACEAIhBCACEAMhBSACEAQhBgJAAkAgBEGBgARJDQBBACEHIAQhCANAIANB\
BGogBiAFIAdqIAhBgIAEIAhBgIAESRsQBSIJEFwCQCAJQYQBSQ0AIAkQAQsgACABIAMoAgQiCSADKA\
IMEA8CQCADKAIIRQ0AIAkQIAsgCEGAgHxqIQggB0GAgARqIgcgBEkNAAwCCwsgA0EEaiACEFwgACAB\
IAMoAgQiCCADKAIMEA8gAygCCEUNACAIECALAkAgBkGEAUkNACAGEAELAkAgAkGEAUkNACACEAELIA\
NBEGokAAvfAQEDfyMAQSBrIgYkACAGQRRqIAEgAhAaAkACQCAGKAIUDQAgBkEcaigCACEHIAYoAhgh\
CAwBCyAGKAIYIAZBHGooAgAQACEHQRshCAsCQCACRQ0AIAEQIAsCQ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QSBrIgIkACACQQxqQgE3AgAgAk\
EBNgIEIAJBtIbAADYCACACQQI2AhwgAkHUhsAANgIYIAFBGGooAgAhAyACIAJBGGo2AgggASgCFCAD\
IAIQKiEBIAJBIGokACABC2MBAn8jAEEgayICJAAgAkEMakIBNwIAIAJBATYCBCACQbSGwAA2AgAgAk\
ECNgIcIAJB1IbAADYCGCABQRhqKAIAIQMgAiACQRhqNgIIIAEoAhQgAyACECohASACQSBqJAAgAQtd\
AQJ/AkACQCAARQ0AIAAoAgANASAAQQA2AgAgAEEIaigCACEBIAAoAgQhAiAAECACQCACQQdHDQAgAU\
HwDmooAgBFDQAgAUEANgLwDgsgARAgDwsQigEACxCLAQALWAECfyMAQZABayICJAAgAkEANgKMAUGA\
fyEDA0AgAkEMaiADakGAAWogASADakGAAWooAAA2AgAgA0EEaiIDDQALIAAgAkEMakGAARCQARogAk\
GQAWokAAtYAQJ/IwBBoAFrIgIkACACQQA2ApwBQfB+IQMDQCACQQxqIANqQZABaiABIANqQZABaigA\
ADYCACADQQRqIgMNAAsgACACQQxqQZABEJABGiACQaABaiQAC1gBAn8jAEGQAWsiAiQAIAJBADYCjA\
FB+H4hAwNAIAJBBGogA2pBiAFqIAEgA2pBiAFqKAAANgIAIANBBGoiAw0ACyAAIAJBBGpBiAEQkAEa\
IAJBkAFqJAALVwECfyMAQfAAayICJAAgAkEANgJsQZh/IQMDQCACQQRqIANqQegAaiABIANqQegAai\
gAADYCACADQQRqIgMNAAsgACACQQRqQegAEJABGiACQfAAaiQAC1cBAn8jAEHQAGsiAiQAIAJBADYC\
TEG4fyEDA0AgAkEEaiADakHIAGogASADakHIAGooAAA2AgAgA0EEaiIDDQALIAAgAkEEakHIABCQAR\
ogAkHQAGokAAtYAQJ/IwBBsAFrIgIkACACQQA2AqwBQdh+IQMDQCACQQRqIANqQagBaiABIANqQagB\
aigAADYCACADQQRqIgMNAAsgACACQQRqQagBEJABGiACQbABaiQAC2YBAX9BAEEAKAKY1EAiAkEBaj\
YC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Zjb3JlOjpwdHI6OmRyb3BfaW5f\
cGxhY2U8YXJyYXl2ZWM6OmVycm9yczo6Q2FwYWNpdHlFcnJvcjxbdTg7IDMyXT4+OjpoNTNkNGJlZj\
cyZWQxN2IyYZQBPWNvcmU6OnB0cjo6ZHJvcF9pbl9wbGFjZTxjb3JlOjpmbXQ6OkVycm9yPjo6aGMz\
ZmY0OWFkMzQ0ODkyY2EAbwlwcm9kdWNlcnMCCGxhbmd1YWdlAQRSdXN0AAxwcm9jZXNzZWQtYnkDBX\
J1c3RjHTEuNzQuMCAoNzllOTcxNmM5IDIwMjMtMTEtMTMpBndhbHJ1cwYwLjIwLjMMd2FzbS1iaW5k\
Z2VuBjAuMi45MAAsD3RhcmdldF9mZWF0dXJlcwIrD211dGFibGUtZ2xvYmFscysIc2lnbi1leHQ=\
    ");
    const wasmModule = new WebAssembly.Module(wasmBytes);
    return new WebAssembly.Instance(wasmModule, imports);
}
function base64decode(b64) {
    const binString = atob(b64);
    const size = binString.length;
    const bytes = new Uint8Array(size);
    for(let i1 = 0; i1 < size; i1++){
        bytes[i1] = binString.charCodeAt(i1);
    }
    return bytes;
}
const digestAlgorithms = [
    "BLAKE2B-128",
    "BLAKE2B-160",
    "BLAKE2B-224",
    "BLAKE2B-256",
    "BLAKE2B-384",
    "BLAKE2B",
    "BLAKE2S",
    "BLAKE3",
    "KECCAK-224",
    "KECCAK-256",
    "KECCAK-384",
    "KECCAK-512",
    "SHA-384",
    "SHA3-224",
    "SHA3-256",
    "SHA3-384",
    "SHA3-512",
    "SHAKE128",
    "SHAKE256",
    "TIGER",
    "RIPEMD-160",
    "SHA-224",
    "SHA-256",
    "SHA-512",
    "MD4",
    "MD5",
    "SHA-1"
];
function swap32(val) {
    return (val & 0xff) << 24 | (val & 0xff00) << 8 | val >> 8 & 0xff00 | val >> 24 & 0xff;
}
function n16(n) {
    return n & 0xffff;
}
function n32(n) {
    return n >>> 0;
}
function add32WithCarry(a, b) {
    const added = n32(a) + n32(b);
    return [
        n32(added),
        added > 0xffffffff ? 1 : 0
    ];
}
function mul32WithCarry(a, b) {
    const al = n16(a);
    const ah = n16(a >>> 16);
    const bl = n16(b);
    const bh = n16(b >>> 16);
    const [t, tc] = add32WithCarry(al * bh, ah * bl);
    const [n, nc] = add32WithCarry(al * bl, n32(t << 16));
    const carry = nc + (tc << 16) + n16(t >>> 16) + ah * bh;
    return [
        n,
        carry
    ];
}
function mul32(a, b) {
    const al = n16(a);
    const ah = a - al;
    return n32(n32(ah * b) + al * b);
}
function mul64([ah, al], [bh, bl]) {
    const [n, c] = mul32WithCarry(al, bl);
    return [
        n32(mul32(al, bh) + mul32(ah, bl) + c),
        n
    ];
}
const prime32 = 16777619;
const fnv32 = (data)=>{
    let hash = 2166136261;
    data.forEach((c)=>{
        hash = mul32(hash, prime32);
        hash ^= c;
    });
    return Uint32Array.from([
        swap32(hash)
    ]).buffer;
};
const fnv32a = (data)=>{
    let hash = 2166136261;
    data.forEach((c)=>{
        hash ^= c;
        hash = mul32(hash, prime32);
    });
    return Uint32Array.from([
        swap32(hash)
    ]).buffer;
};
const prime64Lo = 435;
const prime64Hi = 256;
const fnv64 = (data)=>{
    let hashLo = 2216829733;
    let hashHi = 3421674724;
    data.forEach((c)=>{
        [hashHi, hashLo] = mul64([
            hashHi,
            hashLo
        ], [
            prime64Hi,
            prime64Lo
        ]);
        hashLo ^= c;
    });
    return new Uint32Array([
        swap32(hashHi >>> 0),
        swap32(hashLo >>> 0)
    ]).buffer;
};
const fnv64a = (data)=>{
    let hashLo = 2216829733;
    let hashHi = 3421674724;
    data.forEach((c)=>{
        hashLo ^= c;
        [hashHi, hashLo] = mul64([
            hashHi,
            hashLo
        ], [
            prime64Hi,
            prime64Lo
        ]);
    });
    return new Uint32Array([
        swap32(hashHi >>> 0),
        swap32(hashLo >>> 0)
    ]).buffer;
};
function fnv(name, buf) {
    if (!buf) {
        throw new TypeError("no data provided for hashing");
    }
    switch(name){
        case "FNV32":
            return fnv32(buf);
        case "FNV64":
            return fnv64(buf);
        case "FNV32A":
            return fnv32a(buf);
        case "FNV64A":
            return fnv64a(buf);
        default:
            throw new TypeError(`unsupported fnv digest: ${name}`);
    }
}
const webCrypto = ((crypto1)=>({
        getRandomValues: crypto1.getRandomValues?.bind(crypto1),
        randomUUID: crypto1.randomUUID?.bind(crypto1),
        subtle: {
            decrypt: crypto1.subtle?.decrypt?.bind(crypto1.subtle),
            deriveBits: crypto1.subtle?.deriveBits?.bind(crypto1.subtle),
            deriveKey: crypto1.subtle?.deriveKey?.bind(crypto1.subtle),
            digest: crypto1.subtle?.digest?.bind(crypto1.subtle),
            encrypt: crypto1.subtle?.encrypt?.bind(crypto1.subtle),
            exportKey: crypto1.subtle?.exportKey?.bind(crypto1.subtle),
            generateKey: crypto1.subtle?.generateKey?.bind(crypto1.subtle),
            importKey: crypto1.subtle?.importKey?.bind(crypto1.subtle),
            sign: crypto1.subtle?.sign?.bind(crypto1.subtle),
            unwrapKey: crypto1.subtle?.unwrapKey?.bind(crypto1.subtle),
            verify: crypto1.subtle?.verify?.bind(crypto1.subtle),
            wrapKey: crypto1.subtle?.wrapKey?.bind(crypto1.subtle)
        }
    }))(globalThis.crypto);
const bufferSourceBytes = (data)=>{
    let bytes;
    if (data instanceof Uint8Array) {
        bytes = data;
    } else if (ArrayBuffer.isView(data)) {
        bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
    } else if (data instanceof ArrayBuffer) {
        bytes = new Uint8Array(data);
    }
    return bytes;
};
const stdCrypto = ((x)=>x)({
    ...webCrypto,
    subtle: {
        ...webCrypto.subtle,
        async digest (algorithm, data) {
            const { name, length } = normalizeAlgorithm(algorithm);
            assertValidDigestLength(length);
            const bytes = bufferSourceBytes(data);
            if (FNV_ALGORITHMS.includes(name)) {
                return fnv(name, bytes);
            }
            if (webCryptoDigestAlgorithms.includes(name) && bytes) {
                return webCrypto.subtle.digest(algorithm, bytes);
            } else if (digestAlgorithms.includes(name)) {
                if (bytes) {
                    return stdCrypto.subtle.digestSync(algorithm, bytes);
                } else if (data[Symbol.iterator]) {
                    return stdCrypto.subtle.digestSync(algorithm, data);
                } else if (data[Symbol.asyncIterator]) {
                    const wasmCrypto = instantiate();
                    const context = new wasmCrypto.DigestContext(name);
                    for await (const chunk of data){
                        const chunkBytes = bufferSourceBytes(chunk);
                        if (!chunkBytes) {
                            throw new TypeError("data contained chunk of the wrong type");
                        }
                        context.update(chunkBytes);
                    }
                    return context.digestAndDrop(length).buffer;
                } else {
                    throw new TypeError("data must be a BufferSource or [Async]Iterable<BufferSource>");
                }
            } else if (webCrypto.subtle?.digest) {
                return webCrypto.subtle.digest(algorithm, data);
            } else {
                throw new TypeError(`unsupported digest algorithm: ${algorithm}`);
            }
        },
        digestSync (algorithm, data) {
            const { name, length } = normalizeAlgorithm(algorithm);
            assertValidDigestLength(length);
            const bytes = bufferSourceBytes(data);
            if (FNV_ALGORITHMS.includes(name)) {
                return fnv(name, bytes);
            }
            const wasmCrypto = instantiate();
            if (bytes) {
                return wasmCrypto.digest(name, bytes, length).buffer;
            } else if (data[Symbol.iterator]) {
                const context = new wasmCrypto.DigestContext(name);
                for (const chunk of data){
                    const chunkBytes = bufferSourceBytes(chunk);
                    if (!chunkBytes) {
                        throw new TypeError("data contained chunk of the wrong type");
                    }
                    context.update(chunkBytes);
                }
                return context.digestAndDrop(length).buffer;
            } else {
                throw new TypeError("data must be a BufferSource or Iterable<BufferSource>");
            }
        }
    }
});
const FNV_ALGORITHMS = [
    "FNV32",
    "FNV32A",
    "FNV64",
    "FNV64A"
];
const webCryptoDigestAlgorithms = [
    "SHA-384",
    "SHA-256",
    "SHA-512",
    "SHA-1"
];
function assertValidDigestLength(value) {
    if (value !== undefined && (value < 0 || value > 0x7FFF_FFFF || !Number.isInteger(value))) {
        throw new RangeError(`length must be an integer between 0 and ${0x7FFF_FFFF}, inclusive`);
    }
}
function normalizeAlgorithm(algorithm) {
    return typeof algorithm === "string" ? {
        name: algorithm.toUpperCase()
    } : {
        ...algorithm,
        name: algorithm.name.toUpperCase()
    };
}
function timingSafeEqual(a, b) {
    if (a.byteLength !== b.byteLength) {
        return false;
    }
    if (!(a instanceof DataView)) {
        a = ArrayBuffer.isView(a) ? new DataView(a.buffer, a.byteOffset, a.byteLength) : new DataView(a);
    }
    if (!(b instanceof DataView)) {
        b = ArrayBuffer.isView(b) ? new DataView(b.buffer, b.byteOffset, b.byteLength) : new DataView(b);
    }
    assert(a instanceof DataView);
    assert(b instanceof DataView);
    const length = a.byteLength;
    let out = 0;
    let i1 = -1;
    while(++i1 < length){
        out |= a.getUint8(i1) ^ b.getUint8(i1);
    }
    return out === 0;
}
function convertBase64ToBase64url(b64) {
    return b64.endsWith("=") ? b64.endsWith("==") ? b64.replace(/\+/g, "-").replace(/\//g, "_").slice(0, -2) : b64.replace(/\+/g, "-").replace(/\//g, "_").slice(0, -1) : b64.replace(/\+/g, "-").replace(/\//g, "_");
}
function encodeBase64Url(data) {
    return convertBase64ToBase64url(encodeBase64(data));
}
const encoder1 = new TextEncoder();
function importKey(key) {
    if (typeof key === "string") {
        key = encoder1.encode(key);
    } else if (Array.isArray(key)) {
        key = new Uint8Array(key);
    }
    return crypto.subtle.importKey("raw", key, {
        name: "HMAC",
        hash: {
            name: "SHA-256"
        }
    }, true, [
        "sign",
        "verify"
    ]);
}
function sign(data, key) {
    if (typeof data === "string") {
        data = encoder1.encode(data);
    } else if (Array.isArray(data)) {
        data = Uint8Array.from(data);
    }
    return crypto.subtle.sign("HMAC", key, data);
}
async function compare1(a, b) {
    const key = new Uint8Array(32);
    globalThis.crypto.getRandomValues(key);
    const cryptoKey = await importKey(key);
    const [ah, bh] = await Promise.all([
        sign(a, cryptoKey),
        sign(b, cryptoKey)
    ]);
    return timingSafeEqual(ah, bh);
}
class KeyStack {
    #cryptoKeys = new Map();
    #keys;
    async #toCryptoKey(key) {
        if (!this.#cryptoKeys.has(key)) {
            this.#cryptoKeys.set(key, await importKey(key));
        }
        return this.#cryptoKeys.get(key);
    }
    get length() {
        return this.#keys.length;
    }
    constructor(keys){
        const values = Array.isArray(keys) ? keys : [
            ...keys
        ];
        if (!values.length) {
            throw new TypeError("keys must contain at least one value");
        }
        this.#keys = values;
    }
    async sign(data) {
        const key = await this.#toCryptoKey(this.#keys[0]);
        return encodeBase64Url(await sign(data, key));
    }
    async verify(data, digest) {
        return await this.indexOf(data, digest) > -1;
    }
    async indexOf(data, digest) {
        for(let i1 = 0; i1 < this.#keys.length; i1++){
            const key = this.#keys[i1];
            const cryptoKey = await this.#toCryptoKey(key);
            if (await compare1(digest, encodeBase64Url(await sign(data, cryptoKey)))) {
                return i1;
            }
        }
        return -1;
    }
    [Symbol.for("Deno.customInspect")](inspect) {
        const { length } = this;
        return `${this.constructor.name} ${inspect({
            length
        })}`;
    }
    [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
        if (depth < 0) {
            return options.stylize(`[${this.constructor.name}]`, "special");
        }
        const newOptions = Object.assign({}, options, {
            depth: options.depth === null ? null : options.depth - 1
        });
        const { length } = this;
        return `${options.stylize(this.constructor.name, "special")} ${inspect({
            length
        }, newOptions)}`;
    }
}
var commonjsGlobal1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function createCommonjsModule3(fn, basedir, module1) {
    return module1 = {
        path: basedir,
        exports: {},
        require: function(path, base) {
            return commonjsRequire(path, base === void 0 || base === null ? module1.path : base);
        }
    }, fn(module1, module1.exports), module1.exports;
}
function commonjsRequire() {
    throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
var md5 = createCommonjsModule3(function(module1) {
    (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, len) {
            x[len >> 5] |= 128 << len % 32;
            x[(len + 64 >>> 9 << 4) + 14] = len;
            var i1;
            var olda;
            var oldb;
            var oldc;
            var oldd;
            var a = 1732584193;
            var b = -271733879;
            var c = -1732584194;
            var d = 271733878;
            for(i1 = 0; i1 < x.length; i1 += 16){
                olda = a;
                oldb = b;
                oldc = c;
                oldd = d;
                a = md5ff(a, b, c, d, x[i1], 7, -680876936);
                d = md5ff(d, a, b, c, x[i1 + 1], 12, -389564586);
                c = md5ff(c, d, a, b, x[i1 + 2], 17, 606105819);
                b = md5ff(b, c, d, a, x[i1 + 3], 22, -1044525330);
                a = md5ff(a, b, c, d, x[i1 + 4], 7, -176418897);
                d = md5ff(d, a, b, c, x[i1 + 5], 12, 1200080426);
                c = md5ff(c, d, a, b, x[i1 + 6], 17, -1473231341);
                b = md5ff(b, c, d, a, x[i1 + 7], 22, -45705983);
                a = md5ff(a, b, c, d, x[i1 + 8], 7, 1770035416);
                d = md5ff(d, a, b, c, x[i1 + 9], 12, -1958414417);
                c = md5ff(c, d, a, b, x[i1 + 10], 17, -42063);
                b = md5ff(b, c, d, a, x[i1 + 11], 22, -1990404162);
                a = md5ff(a, b, c, d, x[i1 + 12], 7, 1804603682);
                d = md5ff(d, a, b, c, x[i1 + 13], 12, -40341101);
                c = md5ff(c, d, a, b, x[i1 + 14], 17, -1502002290);
                b = md5ff(b, c, d, a, x[i1 + 15], 22, 1236535329);
                a = md5gg(a, b, c, d, x[i1 + 1], 5, -165796510);
                d = md5gg(d, a, b, c, x[i1 + 6], 9, -1069501632);
                c = md5gg(c, d, a, b, x[i1 + 11], 14, 643717713);
                b = md5gg(b, c, d, a, x[i1], 20, -373897302);
                a = md5gg(a, b, c, d, x[i1 + 5], 5, -701558691);
                d = md5gg(d, a, b, c, x[i1 + 10], 9, 38016083);
                c = md5gg(c, d, a, b, x[i1 + 15], 14, -660478335);
                b = md5gg(b, c, d, a, x[i1 + 4], 20, -405537848);
                a = md5gg(a, b, c, d, x[i1 + 9], 5, 568446438);
                d = md5gg(d, a, b, c, x[i1 + 14], 9, -1019803690);
                c = md5gg(c, d, a, b, x[i1 + 3], 14, -187363961);
                b = md5gg(b, c, d, a, x[i1 + 8], 20, 1163531501);
                a = md5gg(a, b, c, d, x[i1 + 13], 5, -1444681467);
                d = md5gg(d, a, b, c, x[i1 + 2], 9, -51403784);
                c = md5gg(c, d, a, b, x[i1 + 7], 14, 1735328473);
                b = md5gg(b, c, d, a, x[i1 + 12], 20, -1926607734);
                a = md5hh(a, b, c, d, x[i1 + 5], 4, -378558);
                d = md5hh(d, a, b, c, x[i1 + 8], 11, -2022574463);
                c = md5hh(c, d, a, b, x[i1 + 11], 16, 1839030562);
                b = md5hh(b, c, d, a, x[i1 + 14], 23, -35309556);
                a = md5hh(a, b, c, d, x[i1 + 1], 4, -1530992060);
                d = md5hh(d, a, b, c, x[i1 + 4], 11, 1272893353);
                c = md5hh(c, d, a, b, x[i1 + 7], 16, -155497632);
                b = md5hh(b, c, d, a, x[i1 + 10], 23, -1094730640);
                a = md5hh(a, b, c, d, x[i1 + 13], 4, 681279174);
                d = md5hh(d, a, b, c, x[i1], 11, -358537222);
                c = md5hh(c, d, a, b, x[i1 + 3], 16, -722521979);
                b = md5hh(b, c, d, a, x[i1 + 6], 23, 76029189);
                a = md5hh(a, b, c, d, x[i1 + 9], 4, -640364487);
                d = md5hh(d, a, b, c, x[i1 + 12], 11, -421815835);
                c = md5hh(c, d, a, b, x[i1 + 15], 16, 530742520);
                b = md5hh(b, c, d, a, x[i1 + 2], 23, -995338651);
                a = md5ii(a, b, c, d, x[i1], 6, -198630844);
                d = md5ii(d, a, b, c, x[i1 + 7], 10, 1126891415);
                c = md5ii(c, d, a, b, x[i1 + 14], 15, -1416354905);
                b = md5ii(b, c, d, a, x[i1 + 5], 21, -57434055);
                a = md5ii(a, b, c, d, x[i1 + 12], 6, 1700485571);
                d = md5ii(d, a, b, c, x[i1 + 3], 10, -1894986606);
                c = md5ii(c, d, a, b, x[i1 + 10], 15, -1051523);
                b = md5ii(b, c, d, a, x[i1 + 1], 21, -2054922799);
                a = md5ii(a, b, c, d, x[i1 + 8], 6, 1873313359);
                d = md5ii(d, a, b, c, x[i1 + 15], 10, -30611744);
                c = md5ii(c, d, a, b, x[i1 + 6], 15, -1560198380);
                b = md5ii(b, c, d, a, x[i1 + 13], 21, 1309151649);
                a = md5ii(a, b, c, d, x[i1 + 4], 6, -145523070);
                d = md5ii(d, a, b, c, x[i1 + 11], 10, -1120210379);
                c = md5ii(c, d, a, b, x[i1 + 2], 15, 718787259);
                b = md5ii(b, c, d, a, x[i1 + 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 i1;
            var output = "";
            var length32 = input.length * 32;
            for(i1 = 0; i1 < length32; i1 += 8){
                output += String.fromCharCode(input[i1 >> 5] >>> i1 % 32 & 255);
            }
            return output;
        }
        function rstr2binl(input) {
            var i1;
            var output = [];
            output[(input.length >> 2) - 1] = void 0;
            for(i1 = 0; i1 < output.length; i1 += 1){
                output[i1] = 0;
            }
            var length8 = input.length * 8;
            for(i1 = 0; i1 < length8; i1 += 8){
                output[i1 >> 5] |= (input.charCodeAt(i1 / 8) & 255) << i1 % 32;
            }
            return output;
        }
        function rstrMD5(s) {
            return binl2rstr(binlMD5(rstr2binl(s), s.length * 8));
        }
        function rstrHMACMD5(key, data) {
            var i1;
            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(i1 = 0; i1 < 16; i1 += 1){
                ipad[i1] = bkey[i1] ^ 909522486;
                opad[i1] = bkey[i1] ^ 1549556828;
            }
            hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
            return binl2rstr(binlMD5(opad.concat(hash), 512 + 128));
        }
        function rstr2hex(input) {
            var hexTab = "0123456789abcdef";
            var output = "";
            var x;
            var i1;
            for(i1 = 0; i1 < input.length; i1 += 1){
                x = input.charCodeAt(i1);
                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(string, key, raw) {
            if (!key) {
                if (!raw) {
                    return hexMD5(string);
                }
                return rawMD5(string);
            }
            if (!raw) {
                return hexHMACMD5(key, string);
            }
            return rawHMACMD5(key, string);
        }
        if (module1.exports) {
            module1.exports = md52;
        } else {
            $.md5 = md52;
        }
    })(commonjsGlobal1);
});
function md5Hash(content) {
    return md5(content);
}
function md5HashBytes(content) {
    const buffer = stdCrypto.subtle.digestSync("MD5", content);
    return Array.from(new Uint8Array(buffer)).map((b)=>b.toString(16).padStart(2, "0")).join("");
}
function insecureHash(content) {
    let hash = 0;
    for(let i1 = 0; i1 < content.length; i1++){
        const __char = content.charCodeAt(i1);
        hash = (hash << 5) - hash + __char;
        hash &= hash;
    }
    return new Uint32Array([
        hash
    ])[0].toString(36);
}
async function executeKernelOneshot(options) {
    await abortKernel(options);
    if (!options.quiet) {
        messageStartingKernel(options.kernelspec);
    }
    trace(options, "Executing notebook with oneshot kernel");
    const debug = !!options.format.execute[kExecuteDebug];
    const result1 = await execJupyter("execute", {
        ...options,
        debug
    }, options.kernelspec);
    if (!result1.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(options.kernelspec, 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, kernelspec) {
    try {
        const result1 = await execProcess({
            cmd: [
                ...await pythonExec(kernelspec),
                resourcePath("jupyter/jupyter.py")
            ],
            env: {
                "MPLBACKEND": "module://matplotlib_inline.backend_inline",
                "PYDEVD_DISABLE_FILE_VALIDATION": "1"
            },
            stdout: "piped"
        }, kernelCommand(command, "", options));
        if (!result1.success) {
            await printExecDiagnostics(kernelspec, result1.stderr);
        }
        return result1;
    } catch (e) {
        if (e?.message) {
            info("");
            error(e.message);
        }
        await printExecDiagnostics(kernelspec);
        return Promise.reject();
    }
}
async function printExecDiagnostics(kernelspec, stderr) {
    const caps = await jupyterCapabilities(kernelspec);
    if (caps && !caps.jupyter_core) {
        info("Python 3 installation:");
        info(await jupyterCapabilitiesMessage(caps, "  "));
        info("");
        info(jupyterInstallationMessage(caps));
        info("");
        maybePrintUnactivatedEnvMessage(caps);
    } else if (caps && !haveRequiredPython(caps)) {
        info(pythonVersionMessage());
        info(await jupyterCapabilitiesMessage(caps, "  "));
    } else if (!caps) {
        info(pythonInstallationMessage());
        info("");
    } else if (stderr && stderr.indexOf("ModuleNotFoundError") !== -1) {
        maybePrintUnactivatedEnvMessage(caps);
    }
}
function haveRequiredPython(caps) {
    return caps.versionMajor >= 3 && caps.versionMinor >= 6;
}
function pythonVersionMessage() {
    return `Quarto requires Python version 3.6 (or greater). Detected version is:`;
}
function maybePrintUnactivatedEnvMessage(caps) {
    const envMessage = jupyterUnactivatedEnvMessage(caps);
    if (envMessage) {
        info(envMessage);
        info("");
    }
}
async function writeKernelCommand(conn, command, secret, options) {
    let messageBytes = new TextEncoder().encode(kernelCommand(command, secret, options) + "\n");
    if (messageBytes.length > 1024) {
        const tempFile = Deno.makeTempFileSync();
        Deno.writeFileSync(tempFile, messageBytes);
        const msg = kernelCommand("file", secret, {
            file: tempFile
        }) + "\n";
        messageBytes = new TextEncoder().encode(msg);
    }
    const bytesWritten = await conn.write(messageBytes);
    if (bytesWritten !== messageBytes.length) {
        throw new Error("Internal Error");
    }
}
function kernelCommand(command, secret, options) {
    return JSON.stringify({
        command,
        secret,
        options: {
            ...options,
            log: kernelLogFile()
        }
    });
}
function kernelTransportFile(target) {
    let transportsDir;
    try {
        transportsDir = quartoRuntimeDir("jt");
    } catch (e) {
        console.error("Could create runtime directory for jupyter transport.");
        console.error("This is possibly a permission issue in the environment Quarto is running in.");
        console.error("Please consult the following documentation for more information:");
        console.error("https://github.com/quarto-dev/quarto-cli/issues/4594#issuecomment-1619177667");
        throw e;
    }
    const targetFile = normalizePath(target);
    const hash = md5Hash(targetFile).slice(0, 20);
    return join2(transportsDir, hash);
}
function kernelLogFile() {
    const logsDir = quartoDataDir("logs");
    const kernelLog = join2(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 debug = !!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  {
            if (existsSync(transportFile)) {
                Deno.removeSync(transportFile);
            }
        }
    }
    if (!startIfRequired) {
        return Promise.reject();
    }
    if (!options.quiet) {
        messageStartingKernel(options.kernelspec);
    }
    const keepAlive = options.format.execute[kExecuteDaemon];
    const timeout = keepAlive === true || keepAlive === null || keepAlive === undefined ? 300 : keepAlive === false ? 0 : keepAlive;
    const result1 = await execJupyter("start", {
        transport: transportFile,
        timeout,
        type,
        debug
    }, options.kernelspec);
    if (!result1.success) {
        return Promise.reject();
    }
    for(let i1 = 1; i1 < 20; i1++){
        await sleep(i1 * 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();
            }
        }
    }
    warn("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(kernelspec) {
    info(`\nStarting ${kernelspec.name} kernel...`, {
        newline: false
    });
}
function trace(options, msg) {
    if (options.format.execute[kExecuteDebug]) {
        info("- " + msg, {
            bold: true
        });
    }
}
const kRunHandlers = [];
function installRunHandler(handler) {
    kRunHandlers.push(handler);
}
function handlerForScript(script) {
    return kRunHandlers.find((handler)=>handler.canHandle(script));
}
function parseShellRunCommand(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"), " ");
    });
}
async function filteredNotebookFromCache(file, filters) {
    file = normalizeNotebookPath(file);
    const invalidation = await notebookInvalidation(file, filters);
    const notebook = getCachedNotebook(file);
    if (notebook?.invalidation === invalidation) {
        return Deno.readTextFileSync(notebook.fullPath);
    } else {
        return undefined;
    }
}
async function cacheFilteredNotebook(file, filters, json) {
    file = normalizeNotebookPath(file);
    const invalidation = await notebookInvalidation(file, filters);
    cacheNotebook(file, {
        invalidation,
        json
    });
}
function normalizeNotebookPath(file) {
    return isAbsolute2(file) ? file : join2(Deno.cwd(), file);
}
async function notebookInvalidation(file, filters) {
    return [
        file,
        ...await filterScriptPaths(file, filters || [])
    ].reduce((hash, file)=>{
        try {
            return hash + Deno.statSync(file).mtime?.toUTCString();
        } catch  {
            return hash;
        }
    }, "");
}
async function filterScriptPaths(file, filters) {
    const filterPaths = [];
    for (const filter of filters){
        const args = parseShellRunCommand(filter);
        const script = args[0];
        const scriptPath = join2(dirname2(file), script);
        if (existsSync(scriptPath)) {
            filterPaths.push(scriptPath);
        } else if (isAbsolute2(script) && existsSync(script)) {
            filterPaths.push(script);
        } else {
            const scriptPath = await which(script);
            if (scriptPath && existsSync(scriptPath)) {
                filterPaths.push(scriptPath);
            }
        }
    }
    return filterPaths;
}
function getCachedNotebook(file) {
    const contents = readNotebookIndex()[file];
    if (contents) {
        return {
            invalidation: contents.invalidation,
            fullPath: notebookCachePath(contents.path)
        };
    }
}
function cacheNotebook(file, contents) {
    const index = readNotebookIndex();
    const path = index[file]?.path || globalThis.crypto.randomUUID();
    Deno.writeTextFileSync(notebookCachePath(path), contents.json);
    index[file] = {
        invalidation: contents.invalidation,
        path
    };
    writeNotebookIndex(index);
}
function readNotebookIndex() {
    const index = notebookIndexFile();
    if (existsSync(index)) {
        return JSON.parse(Deno.readTextFileSync(index));
    }
    return {};
}
function writeNotebookIndex(index) {
    Deno.writeTextFileSync(notebookIndexFile(), JSON.stringify(index, undefined, 2));
}
const notebookIndexFile = ()=>notebookCachePath("INDEX");
function notebookCachePath(file) {
    const cacheDir = join2(quartoCacheDir(), "filtered-notebooks");
    ensureDirSync(cacheDir);
    return file ? join2(cacheDir, file) : cacheDir;
}
async function markdownFromNotebookFile(file, format) {
    const nbContents = await jupyterNotebookFiltered(file, format?.execute[kIpynbFilters]);
    const nb = JSON.parse(nbContents);
    return markdownFromNotebookJSON(nb);
}
function markdownFromNotebookJSON(nb) {
    nb = fixupFrontMatter(nb);
    const markdown = nb.cells.reduce((md, cell)=>{
        if ([
            "markdown",
            "raw"
        ].includes(cell.cell_type)) {
            return md + "\n" + jupyterCellSrcAsStr(cell) + "\n";
        } else {
            return md;
        }
    }, "");
    return markdown;
}
async function jupyterNotebookFiltered(file, filters) {
    let json = Deno.readTextFileSync(file);
    if (filters && filters.length > 0) {
        const cached = await filteredNotebookFromCache(file, filters);
        if (cached) {
            return cached;
        }
        for (const filter of filters){
            const args = parseShellRunCommand(filter);
            const script = args[0];
            const scriptPath = join2(dirname2(file), script);
            const handler = handlerForScript(scriptPath);
            const result1 = handler && existsSync(scriptPath) ? await handler.run(script, args.splice(1), json, {
                cwd: dirname2(file),
                env: {
                    PYTHONUNBUFFERED: "1"
                },
                stdout: "piped"
            }) : await execProcess({
                cmd: [
                    isAbsolute2(script) ? script : basename2(script),
                    ...args.slice(1)
                ],
                cwd: dirname2(file),
                env: {
                    PYTHONUNBUFFERED: "1"
                },
                stdout: "piped"
            }, json);
            if (!result1.success) {
                throw new Error();
            }
            json = result1.stdout || json;
        }
        await cacheFilteredNotebook(file, filters, json);
        return json;
    } else {
        return json;
    }
}
class InvalidShortcodeError extends Error {
    constructor(msg){
        super(msg);
    }
}
function isBlockShortcode(content, lenient) {
    const m = content.match(/^\s*{{< (?!\/\*)(.+?)(?<!\*\/) >}}\s*$/);
    if (m) {
        try {
            return parseShortcode(m[1]);
        } catch (_e) {
            if (lenient) {
                return false;
            }
            throw _e;
        }
    }
}
function parseShortcodeCapture(capture) {
    const nameMatch = capture.match(/^\/?[a-zA-Z0-9_]+/);
    if (!nameMatch) {
        return;
    }
    const params = [];
    const namedParams = {};
    const rawParams = [];
    const name = nameMatch[0];
    let paramStr = capture.slice(name.length).trim();
    while(paramStr.length){
        let paramMatch;
        paramMatch = paramStr.match(/^[a-zA-Z0-9_-]+="[^"]*"/);
        if (!paramMatch) {
            paramMatch = paramStr.match(/^[a-zA-Z0-9_-]+='[^']*'/);
        }
        if (!paramMatch) {
            paramMatch = paramStr.match(/^[a-zA-Z0-9_-]+=[^"'\s]+/);
        }
        if (paramMatch) {
            const [name, value] = paramMatch[0].split("=");
            namedParams[name] = value;
            rawParams.push({
                name,
                value
            });
            paramStr = paramStr.slice(paramMatch[0].length).trim();
            continue;
        }
        paramMatch = paramStr.match(/^[^"'\s]+/);
        if (paramMatch) {
            params.push(paramMatch[0]);
            rawParams.push({
                value: paramMatch[0]
            });
            paramStr = paramStr.slice(paramMatch[0].length).trim();
            continue;
        }
        paramMatch = paramStr.match(/^"[^"]*"/) || paramStr.match(/^'[^']*'/);
        if (paramMatch) {
            params.push(paramMatch[0].slice(1, -1));
            rawParams.push({
                value: paramMatch[0].slice(1, -1)
            });
            paramStr = paramStr.slice(paramMatch[0].length).trim();
            continue;
        }
        throw new InvalidShortcodeError("invalid shortcode: " + capture);
    }
    return {
        name,
        params,
        namedParams,
        rawParams
    };
}
function parseShortcode(shortCodeCapture) {
    const result1 = parseShortcodeCapture(shortCodeCapture);
    if (!result1) {
        throw new InvalidShortcodeError("invalid shortcode: " + shortCodeCapture);
    }
    return result1;
}
async function breakQuartoMd(src, validate = false, lenient = false) {
    if (typeof src === "string") {
        src = asMappedString(src);
    }
    const fileName = src.fileName;
    const nb = {
        cells: []
    };
    const yamlRegEx = /^---\s*$/;
    const startCodeCellRegEx = new RegExp("^\\s*(```+)\\s*\\{([=A-Za-z]+)( *[ ,].*)?\\}\\s*$");
    const startCodeRegEx = /^```/;
    const endCodeRegEx = /^\s*(```+)\s*$/;
    let language = "";
    let directiveParams = undefined;
    let cellStartLine = 0;
    let codeStartRange;
    let codeEndRange;
    const lineBuffer = [];
    const flushLineBuffer = async (cell_type, index)=>{
        if (lineBuffer.length || cell_type === "code") {
            const mappedChunks = [];
            for (const line of lineBuffer){
                mappedChunks.push(line.range);
            }
            const source = mappedString(src, mappedChunks, fileName);
            const makeCellType = ()=>{
                if (cell_type === "code") {
                    return {
                        language
                    };
                } else if (cell_type === "directive") {
                    return {
                        language: "_directive",
                        name: directiveParams.name,
                        shortcode: directiveParams
                    };
                } else {
                    return cell_type;
                }
            };
            const cell = {
                cell_type: makeCellType(),
                source,
                sourceOffset: 0,
                sourceStartLine: 0,
                sourceVerbatim: source,
                cellStartLine
            };
            cellStartLine = index + 1;
            if (cell_type === "code") {
                const { yaml, sourceStartLine } = await partitionCellOptionsMapped(language, cell.source, validate, "", lenient);
                const breaks = Array.from(lineOffsets(cell.source.value));
                let strUpToLastBreak = "";
                if (sourceStartLine > 0) {
                    cell.sourceWithYaml = cell.source;
                    cell.source = mappedSubstring(cell.source, breaks[sourceStartLine]);
                    if (breaks.length > 1) {
                        const lastBreak = breaks[Math.min(sourceStartLine - 1, breaks.length - 1)];
                        strUpToLastBreak = cell.source.value.substring(0, lastBreak);
                    } else {
                        strUpToLastBreak = cell.source.value;
                    }
                } else {
                    cell.sourceWithYaml = cell.source;
                }
                const prefix = "```{" + language + "}\n";
                cell.sourceOffset = strUpToLastBreak.length + prefix.length;
                cell.sourceVerbatim = mappedString(src, [
                    codeStartRange.range,
                    ...mappedChunks,
                    codeEndRange.range
                ], fileName);
                cell.options = yaml;
                cell.sourceStartLine = sourceStartLine;
            } else if (cell_type === "directive") {
                cell.source = mappedString(src, mappedChunks.slice(1, -1), fileName);
            }
            if (mdTrimEmptyLines(lines(cell.sourceVerbatim.value)).length > 0 || cell.options !== undefined) {
                nb.cells.push(cell);
            }
            lineBuffer.splice(0, lineBuffer.length);
        }
    };
    const tickCount = (s)=>Array.from(s.split(" ")[0] || "").filter((c)=>c === "`").length;
    let inYaml = false, inCodeCell = false, inCode = 0;
    const inPlainText = ()=>!inCodeCell && !inCode && !inYaml;
    const isYamlDelimiter = (line, index, skipHRs)=>{
        if (!yamlRegEx.test(line)) {
            return false;
        }
        if (skipHRs && index > 0 && srcLines[index - 1].substring.trim() === "" && index < srcLines.length - 1 && srcLines[index + 1].substring.trim() === "") {
            return false;
        }
        return true;
    };
    const srcLines = rangedLines(src.value, true);
    for(let i1 = 0; i1 < srcLines.length; ++i1){
        const line = srcLines[i1];
        const directiveMatch = isBlockShortcode(line.substring, true);
        if (isYamlDelimiter(line.substring, i1, !inYaml) && !inCodeCell && !inCode) {
            if (inYaml) {
                lineBuffer.push(line);
                await flushLineBuffer("raw", i1);
                inYaml = false;
            } else {
                await flushLineBuffer("markdown", i1);
                lineBuffer.push(line);
                inYaml = true;
            }
        } else if (inPlainText() && directiveMatch) {
            await flushLineBuffer("markdown", i1);
            directiveParams = directiveMatch;
            lineBuffer.push(line);
            await flushLineBuffer("directive", i1);
        } else if (startCodeCellRegEx.test(line.substring) && inPlainText()) {
            const m = line.substring.match(startCodeCellRegEx);
            language = m[2];
            await flushLineBuffer("markdown", i1);
            inCodeCell = true;
            inCode = m[1].length;
            codeStartRange = line;
        } else if (endCodeRegEx.test(line.substring) && inCode && line.substring.match(endCodeRegEx)[1].length === inCode) {
            if (inCodeCell) {
                codeEndRange = line;
                inCodeCell = false;
                inCode = 0;
                await flushLineBuffer("code", i1);
            } else {
                inCode = 0;
                lineBuffer.push(line);
            }
        } else if (startCodeRegEx.test(line.substring) && inCode === 0) {
            inCode = tickCount(line.substring);
            lineBuffer.push(line);
        } else {
            lineBuffer.push(line);
        }
    }
    await flushLineBuffer("markdown", srcLines.length);
    return nb;
}
function mdTrimEmptyLines(lines) {
    const firstNonEmpty = lines.findIndex((line)=>line.trim().length > 0);
    if (firstNonEmpty === -1) {
        return [];
    }
    lines = lines.slice(firstNonEmpty);
    let lastNonEmpty = -1;
    for(let i1 = lines.length - 1; i1 >= 0; i1--){
        if (lines[i1].trim().length > 0) {
            lastNonEmpty = i1;
            break;
        }
    }
    if (lastNonEmpty > -1) {
        lines = lines.slice(0, lastNonEmpty + 1);
    }
    return lines;
}
function isQmdFile(file) {
    const ext = extname2(file).toLowerCase();
    return kQmdExtensions.includes(ext);
}
const kJupyterPercentScriptExtensions = [
    ".py",
    ".jl",
    ".r"
];
function isJupyterPercentScript(file) {
    const ext = extname2(file).toLowerCase();
    if (kJupyterPercentScriptExtensions.includes(ext)) {
        const text = Deno.readTextFileSync(file);
        return !!text.match(/^\s*#\s*%%+\s+\[markdown|raw\]/);
    } else {
        return false;
    }
}
function markdownFromJupyterPercentScript(file) {
    const ext = extname2(file).toLowerCase();
    const language = ext === ".jl" ? "julia" : ext === ".r" ? "r" : "python";
    const cells = [];
    const activeCell = ()=>cells[cells.length - 1];
    for (const line of lines(Deno.readTextFileSync(file).trim())){
        const header = percentCellHeader(line);
        if (header) {
            cells.push({
                header,
                lines: []
            });
        } else {
            activeCell()?.lines.push(line);
        }
    }
    const isTripleQuote = (line)=>!!line.match(/^"{3,}\s*$/);
    const asCell = (lines)=>lines.join("\n") + "\n\n";
    const stripPrefix = (line)=>line.replace(/^#\s?/, "");
    const cellContent = (cellLines)=>{
        if (cellLines.length > 2 && isTripleQuote(cellLines[0]) && isTripleQuote(cellLines[cellLines.length - 1])) {
            return asCell(cellLines.slice(1, cellLines.length - 1));
        } else {
            return asCell(cellLines.map(stripPrefix));
        }
    };
    return cells.reduce((markdown, cell)=>{
        const cellLines = trimEmptyLines(cell.lines);
        if (cell.header.type === "code") {
            if (cell.header.metadata) {
                const yamlText = asYamlText(cell.header.metadata);
                cellLines.unshift(...lines(yamlText).map((line)=>`#| ${line}`));
            }
            markdown += asCell([
                "```{" + language + "}",
                ...cellLines,
                "```"
            ]);
        } else if (cell.header.type === "markdown") {
            markdown += cellContent(cellLines);
        } else if (cell.header.type == "raw") {
            let rawContent = cellContent(cellLines);
            const format = cell.header?.metadata?.["format"];
            const mimeType = cell.header.metadata?.[kCellRawMimeType];
            if (typeof mimeType === "string") {
                const rawBlock = mdRawOutput(mimeType, lines(rawContent));
                rawContent = rawBlock || rawContent;
            } else if (typeof format === "string") {
                rawContent = mdFormatOutput(format, lines(rawContent));
            }
            markdown += rawContent;
        }
        return markdown;
    }, "");
}
function percentCellHeader(line) {
    const match = line.match(/^\s*#\s*%%+\s*(?:\[(markdown|raw)\])?\s*(.*)?$/);
    if (match) {
        const type = match[1] || "code";
        const attribs = match[2] || "";
        if ([
            "code",
            "raw",
            "markdown"
        ].includes(type)) {
            return {
                type,
                metadata: parsePercentAttribs(attribs)
            };
        } else {
            throw new Error(`Invalid cell type: ${type}`);
        }
    }
}
function parsePercentAttribs(attribs) {
    const match = attribs.match(/[\w\-]+=.*$/);
    if (match) {
        const keyValue = pandocAttrKeyvalueFromText(match[0], " ");
        const metadata = {};
        keyValue.forEach((value)=>{
            metadata[value[0]] = value[1];
        });
        return metadata;
    }
}
function noPreviewServer() {
    return Promise.resolve({
        start: ()=>Promise.resolve(undefined),
        serve: ()=>{
            return new Promise(()=>{});
        },
        stop: ()=>{
            return Promise.resolve();
        }
    });
}
function runExternalPreviewServer(options) {
    const process = Deno.run({
        ...options,
        stdout: "piped",
        stderr: "piped"
    });
    const multiplexIterator = new MuxAsyncIterator();
    multiplexIterator.add(iterateReader1(process.stdout));
    multiplexIterator.add(iterateReader1(process.stderr));
    const decoder = new TextDecoder();
    return {
        start: async ()=>{
            for await (const chunk of multiplexIterator){
                const text = decoder.decode(chunk);
                if (options.readyPattern.test(text)) {
                    break;
                }
                Deno.stderr.writeSync(chunk);
            }
            return "";
        },
        serve: async ()=>{
            for await (const chunk of multiplexIterator){
                Deno.stderr.writeSync(chunk);
            }
            await process.status();
        },
        stop: ()=>{
            if (!isWindows3()) {
                Deno.kill(-process.pid, "SIGTERM");
            } else {
                process.kill();
            }
            process.close();
            return Promise.resolve();
        }
    };
}
const _types = [];
function registerProjectType(projectType) {
    _types.push(projectType);
}
function kTypes() {
    return _types.slice();
}
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 projectType = kTypes().find((pt)=>pt.type === type);
    if (projectType) {
        return projectType;
    } else {
        throw new Error(`Unsupported project type ${type}`);
    }
}
const kWebsite = "website";
const kSiteUrl = "site-url";
const kSitePath = "site-path";
const kSiteTitle = "title";
const kSiteFavicon = "favicon";
const kSiteRepoUrl = "repo-url";
const kSiteRepoSubdir = "repo-subdir";
const kSiteRepoBranch = "repo-branch";
const kSiteRepoLinkTarget = "repo-link-target";
const kSiteRepoLinkRel = "repo-link-rel";
const kSiteIssueUrl = "issue-url";
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 kBackToTopNavigation = "back-to-top-navigation";
const kBreadCrumbNavigation = "bread-crumbs";
const kMarginHeader = "margin-header";
const kMarginFooter = "margin-footer";
const kBodyHeader = "body-header";
const kBodyFooter = "body-footer";
const kDrafts = "drafts";
const kDraftMode = "draft-mode";
const kDraftModeVisible = "visible";
const kDraftModeGone = "gone";
const kAnnouncement = "announcement";
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 kImageAlt = "image-alt";
const kCreator = "creator";
const kTwitterSite = "site";
const kLocale = "locale";
const kSiteName = "site-name";
function existsSync1(s) {
    return existsSync(s);
}
async function appendTextFile(path, text) {
    const file = await Deno.open(path, {
        append: true
    });
    try {
        const encoder = new TextEncoder();
        file.writeSync(encoder.encode(text));
    } finally{
        file.close();
    }
}
async function touch(path) {
    if (Deno.build.os === "windows") {
        const contents = await Deno.readFileSync(path);
        await Deno.writeFileSync(path, contents);
    } else {
        await execProcess({
            cmd: [
                "touch",
                path
            ]
        });
    }
}
const kManuscriptType = "manuscript";
const kManuscriptUrl = "manuscript-url";
const kMecaBundle = "meca-bundle";
const kEnvironmentFiles = "environment";
const kDependencies = "dependencies";
const kSassBundles = "sass-bundles";
const kHtmlPostprocessors = "html-postprocessors";
const kHtmlFinalizers = "html-finalizers";
const kBodyEnvelope = "body-envelope";
const kTextHighlightingMode = "text-highlighting-mode";
const kQuartoCssVariables = "css-variables";
const kMarkdownAfterBody = "render-after-body";
function isPandocFilter(filter) {
    return filter.path !== undefined;
}
function isFilterEntryPoint(filter) {
    if (typeof filter === "string") {
        return false;
    }
    return filter.at !== undefined;
}
const basePandocNode = {
    emit: (_ls)=>{
        throw new Error("unimplemented");
    },
    mappedString () {
        const ls = [];
        this.emit(ls);
        return mappedConcat(ls);
    },
    push: ()=>{
        throw new Error("unimplemented");
    },
    unshift: ()=>{
        throw new Error("unimplemented");
    }
};
function pandocRawStr(content) {
    return {
        ...basePandocNode,
        emit: (ls)=>ls.push(content)
    };
}
function pandocHtmlBlock(elementName) {
    return function(opts) {
        let { id, classes, attrs, contents } = opts || {};
        if (classes === undefined) {
            classes = [];
        }
        if (attrs === undefined) {
            attrs = [];
        }
        contents = contents || [];
        function attrString() {
            const strs = [];
            if (id) {
                strs.push(`id="${id}"`);
            }
            if (classes && classes.length) {
                strs.push(`class="${classes.join(" ")}"`);
            }
            if (attrs) {
                strs.push(...attrs.map((attr)=>`data-${attr}`));
            }
            return strs.join(" ");
        }
        return {
            ...basePandocNode,
            push: function(s) {
                if (this !== s) {
                    contents.push(s);
                }
            },
            unshift: function(s) {
                if (this !== s) {
                    contents.unshift(s);
                }
            },
            emit: function(ls) {
                ls.push(`\n<${elementName} ${attrString()}>`);
                if (elementName !== "pre") {
                    ls.push("\n");
                }
                for (const entry of contents){
                    entry.emit(ls);
                }
                if (elementName !== "pre") {
                    ls.push("\n");
                }
                ls.push(`</${elementName}>\n`);
            }
        };
    };
}
function pandocList(opts) {
    let { contents, skipFirstLineBreak } = opts || {};
    contents = contents || [];
    return {
        ...basePandocNode,
        push: function(s) {
            if (this !== s) {
                contents.push(s);
            }
        },
        unshift: function(s) {
            if (this !== s) {
                contents.unshift(s);
            }
        },
        emit: function(ls) {
            const lb = skipFirstLineBreak ? "" : "\n";
            ls.push(`${lb}\n`);
            for (const entry of contents){
                entry.emit(ls);
            }
            if (!asMappedString(ls[ls.length - 1] || "\n").value.endsWith("\n")) {
                ls.push(`\n`);
            }
            ls.push(`\n`);
        }
    };
}
function pandocBlock(delimiterCharacter) {
    return function(opts) {
        let { id, classes, attrs, language, skipFirstLineBreak, contents } = opts || {};
        if (classes === undefined) {
            classes = [];
        }
        if (attrs === undefined) {
            attrs = [];
        }
        contents = contents || [];
        function attrString() {
            const strs = [];
            if (language) {
                strs.push(language);
            }
            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 {
            ...basePandocNode,
            push: function(s) {
                if (this !== s) {
                    contents.push(s);
                }
            },
            unshift: function(s) {
                if (this !== s) {
                    contents.unshift(s);
                }
            },
            emit: function(ls) {
                const innerLs = [];
                const lb = skipFirstLineBreak ? "" : "\n";
                for (const entry of contents){
                    entry.emit(innerLs);
                }
                if (!asMappedString(innerLs[innerLs.length - 1] || "\n").value.endsWith("\n")) {
                    innerLs.push(`\n`);
                }
                const longestStreak = Math.max(...innerLs.map((eitherS)=>{
                    const s = asMappedString(eitherS).value;
                    return s.match(new RegExp(`${delimiterCharacter}+`, "g"))?.[0]?.length || 0;
                }));
                const delimiter = delimiterCharacter.repeat(Math.max(3, longestStreak + 1));
                ls.push(`${lb}${delimiter}${attrString()}\n`);
                ls.push(...innerLs);
                ls.push(`${delimiter}\n`);
            }
        };
    };
}
function pandocNativeStr(content) {
    return {
        ...basePandocNode,
        emit: (ls)=>{
            const maxBackticks = content.match(/`+/g)?.[0].length || 0;
            const backticks = "`".repeat(maxBackticks + 1);
            const escapedContent = content.replaceAll('"', '\\"').replaceAll("\n", "\\n");
            ls.push(`${backticks}${'Str "'}${escapedContent}${'"'}${backticks}{=pandoc-native}`);
        }
    };
}
const pandocDiv = pandocBlock(":");
const pandocCode = pandocBlock("`");
pandocHtmlBlock("figure");
pandocHtmlBlock("figcaption");
class EventEmitter {
    events = new Map();
    maxListeners;
    #defaultMaxListeners = 10;
    get defaultMaxListeners() {
        return this.#defaultMaxListeners;
    }
    set defaultMaxListeners(n) {
        if (Number.isInteger(n) || n < 0) {
            const error = new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative integer. Received ' + n + '.');
            throw error;
        }
        this.#defaultMaxListeners = n;
    }
    addListener(eventName, listener) {
        return this.on(eventName, listener);
    }
    emit(eventName, ...args) {
        const listeners = this.events.get(eventName);
        if (listeners === undefined) {
            if (eventName === 'error') {
                const error = args[0];
                if (error instanceof Error) throw error;
                throw new Error('Unhandled error.');
            }
            return false;
        }
        const copyListeners = [
            ...listeners
        ];
        for (const listener of copyListeners){
            listener.apply(this, args);
        }
        return true;
    }
    setMaxListeners(n) {
        if (!Number.isInteger(n) || n < 0) {
            throw new RangeError('The value of "n" is out of range. It must be a non-negative integer. Received ' + n + '.');
        }
        this.maxListeners = n;
        return this;
    }
    getMaxListeners() {
        if (this.maxListeners === undefined) {
            return this.defaultMaxListeners;
        }
        return this.maxListeners;
    }
    listenerCount(eventName) {
        const events = this.events.get(eventName);
        return events === undefined ? 0 : events.length;
    }
    eventNames() {
        return Reflect.ownKeys(this.events);
    }
    listeners(eventName) {
        const listeners = this.events.get(eventName);
        return listeners === undefined ? [] : listeners;
    }
    off(eventName, listener) {
        return this.removeListener(eventName, listener);
    }
    on(eventName, listener, prepend) {
        if (this.events.has(eventName) === false) {
            this.events.set(eventName, []);
        }
        const events = this.events.get(eventName);
        if (prepend) {
            events.unshift(listener);
        } else {
            events.push(listener);
        }
        if (eventName !== "newListener" && this.events.has("newListener")) {
            this.emit('newListener', eventName, listener);
        }
        const maxListener = this.getMaxListeners();
        const eventLength = events.length;
        if (maxListener > 0 && eventLength > maxListener && !events.warned) {
            events.warned = true;
            const warning = new Error(`Possible EventEmitter memory leak detected.
         ${this.listenerCount(eventName)} ${eventName.toString()} listeners.
         Use emitter.setMaxListeners() to increase limit`);
            warning.name = "MaxListenersExceededWarning";
            console.warn(warning);
        }
        return this;
    }
    removeAllListeners(eventName) {
        const events = this.events;
        if (!events.has('removeListener')) {
            if (arguments.length === 0) {
                this.events = new Map();
            } else if (events.has(eventName)) {
                events.delete(eventName);
            }
            return this;
        }
        if (arguments.length === 0) {
            for (const key of events.keys()){
                if (key === 'removeListener') continue;
                this.removeAllListeners(key);
            }
            this.removeAllListeners('removeListener');
            this.events = new Map();
            return this;
        }
        const listeners = events.get(eventName);
        if (listeners !== undefined) {
            listeners.map((listener)=>{
                this.removeListener(eventName, listener);
            });
        }
        return this;
    }
    removeListener(eventName, listener) {
        const events = this.events;
        if (events.size === 0) return this;
        const list = events.get(eventName);
        if (list === undefined) return this;
        const index = list.findIndex((item)=>item === listener || item.listener === listener);
        if (index === -1) return this;
        list.splice(index, 1);
        if (list.length === 0) this.events.delete(eventName);
        if (events.has('removeListener')) {
            this.emit('removeListener', eventName, listener);
        }
        return this;
    }
    once(eventName, listener) {
        this.on(eventName, this.onceWrap(eventName, listener));
        return this;
    }
    onceWrap(eventName, listener) {
        const wrapper = function(...args) {
            this.context.removeListener(this.eventName, this.wrapedListener);
            this.listener.apply(this.context, args);
        };
        const wrapperContext = {
            eventName: eventName,
            listener: listener,
            wrapedListener: wrapper,
            context: this
        };
        const wrapped = wrapper.bind(wrapperContext);
        wrapperContext.wrapedListener = wrapped;
        wrapped.listener = listener;
        return wrapped;
    }
    prependListener(eventName, listener) {
        return this.on(eventName, listener, true);
    }
    prependOnceListener(eventName, listener) {
        this.prependListener(eventName, this.onceWrap(eventName, listener));
        return this;
    }
    rawListeners(eventName) {
        const events = this.events;
        if (events === undefined) return [];
        const listeners = events.get(eventName);
        if (listeners === undefined) return [];
        return [
            ...listeners
        ];
    }
}
const nextTick = (callback)=>{
    setTimeout(callback, 16);
};
function arrayToObject(parameters) {
    const keyValue = {};
    parameters.forEach((parameter)=>{
        const name = parameter.name;
        delete parameter.name;
        keyValue[name] = parameter;
    });
    return keyValue;
}
function decorate(to, category, object) {
    to.category = category;
    Object.keys(object).forEach((field)=>{
        if (field === "name") {
            return;
        }
        if (category === "type" && field === "properties" || field === "parameters") {
            to[field] = arrayToObject(object[field]);
        } else {
            to[field] = object[field];
        }
    });
}
function addCommand(chrome, domainName, command) {
    const commandName = `${domainName}.${command.name}`;
    const handler = (params, sessionId, callback)=>{
        return chrome.send(commandName, params, sessionId, callback);
    };
    decorate(handler, "command", command);
    chrome[commandName] = chrome[domainName][command.name] = handler;
}
function addEvent(chrome, domainName, event) {
    const eventName = `${domainName}.${event.name}`;
    const handler = (sessionId, handler)=>{
        if (typeof sessionId === "function") {
            handler = sessionId;
            sessionId = undefined;
        }
        const rawEventName = sessionId ? `${eventName}.${sessionId}` : eventName;
        if (typeof handler === "function") {
            chrome.on(rawEventName, handler);
            return ()=>chrome.removeListener(rawEventName, handler);
        } else {
            return new Promise((fulfill, _reject)=>{
                chrome.once(rawEventName, fulfill);
            });
        }
    };
    decorate(handler, "event", event);
    chrome[eventName] = chrome[domainName][event.name] = handler;
}
function addType(chrome, domainName, type) {
    const typeName = `${domainName}.${type.id}`;
    const help = {};
    decorate(help, "type", type);
    chrome[typeName] = chrome[domainName][type.id] = help;
}
function prepare(object, protocol) {
    object.protocol = protocol;
    protocol.domains.forEach((domain)=>{
        const domainName = domain.domain;
        object[domainName] = {};
        (domain.commands || []).forEach((command)=>{
            addCommand(object, domainName, command);
        });
        (domain.events || []).forEach((event)=>{
            addEvent(object, domainName, event);
        });
        (domain.types || []).forEach((type)=>{
            addType(object, domainName, type);
        });
        object[domainName].on = (eventName, handler)=>{
            return object[domainName][eventName](handler);
        };
    });
}
const HOST = "localhost";
const PORT = 9222;
async function externalRequest(options) {
    const url = `${options.protocol}:/${options.host}:${options.port}${options.path}`;
    const fetchOpts = {};
    if (options.method) {
        fetchOpts.method = options.method;
    }
    const response = await fetch(url, options);
    const text = await response.text();
    if (response.status !== 200) {
        throw new Error(text);
    }
    return text;
}
function devToolsInterface(options, callback) {
    options.host = options.host || HOST;
    options.port = options.port || PORT;
    options.secure = !!options.secure;
    options.useHostName = !!options.useHostName;
    options.alterPath = options.alterPath || ((path)=>path);
    const newOptions = {
        ...options
    };
    newOptions.path = options.alterPath(options.path);
    newOptions.protocol = options.secure ? "https" : "http";
    return externalRequest(newOptions, callback);
}
async function Protocol(options) {
    options.path = "/json/protocol";
    const result1 = await devToolsInterface(options);
    return JSON.parse(result1);
}
async function List(options) {
    options.path = "/json/list";
    const result1 = await devToolsInterface(options);
    return JSON.parse(result1);
}
async function New(options) {
    options.path = "/json/new";
    if (Object.prototype.hasOwnProperty.call(options, "url")) {
        options.path += `?${options.url}`;
    }
    options = {
        ...options,
        method: "PUT"
    };
    const result1 = await devToolsInterface(options);
    return JSON.parse(result1);
}
class ProtocolError extends Error {
    constructor(request, response){
        let { message } = response;
        if (response.data) {
            message += ` (${response.data})`;
        }
        super(message);
        this.request = request;
        this.response = response;
    }
}
async function tryUntilTimeout(cb, timeout = 3000) {
    const interval = 50;
    let soFar = 0;
    let lastE;
    do {
        try {
            const result1 = await cb();
            return result1;
        } catch (e) {
            lastE = e;
            soFar += interval;
            await new Promise((resolve)=>setTimeout(resolve, 50));
        }
    }while (soFar < timeout)
    throw lastE;
}
class Chrome extends EventEmitter {
    constructor(options, notifier){
        super();
        const defaultTarget = async (targets)=>{
            let target;
            if (!targets.length) {
                target = await New(options);
                if (!target.id) {
                    throw new Error("No inspectable targets and unable to create one");
                }
            } else {
                let backup;
                target = targets.find((target)=>{
                    if (target.webSocketDebuggerUrl) {
                        backup = backup || target;
                        return target.type === "page";
                    } else {
                        return false;
                    }
                });
                target = target || backup;
            }
            if (target) {
                return target;
            } else {
                throw new Error("No inspectable targets");
            }
        };
        options = options || {};
        this.host = options.host || HOST;
        this.port = options.port || PORT;
        this.secure = !!options.secure;
        this.useHostName = !!options.useHostName;
        this.alterPath = options.alterPath || ((path)=>path);
        this.protocol = options.protocol;
        this.local = !!options.local;
        this.target = options.target || defaultTarget;
        this._notifier = notifier;
        this._callbacks = {};
        this._nextCommandId = 1;
        this.webSocketUrl = undefined;
        this._start();
    }
    inspect(_depth, options) {
        options.customInspect = false;
        return Deno.inspect(this, options);
    }
    send(method, params, sessionId, callback) {
        const optionals = Array.from(arguments).slice(1);
        params = optionals.find((x)=>typeof x === "object");
        sessionId = optionals.find((x)=>typeof x === "string");
        callback = optionals.find((x)=>typeof x === "function");
        if (typeof callback === "function") {
            this._enqueueCommand(method, params, sessionId, callback);
            return undefined;
        } else {
            return new Promise((fulfill, reject)=>{
                this._enqueueCommand(method, params, sessionId, (error, response)=>{
                    if (error) {
                        const request = {
                            method,
                            params,
                            sessionId
                        };
                        reject(error instanceof Error ? error : new ProtocolError(request, response));
                    } else {
                        fulfill(response);
                    }
                });
            });
        }
    }
    close(callback) {
        const closeWebSocket = (callback)=>{
            if (this._ws.readyState === 3) {
                callback();
            } else {
                const onclose = this._ws.onclose;
                this._ws.onclose = ()=>{
                    callback();
                    this._ws.onclose = onclose;
                    this._ws.onclose && this._ws.onclose();
                };
                this._ws.close();
            }
        };
        if (typeof callback === "function") {
            closeWebSocket(callback);
            return undefined;
        } else {
            return new Promise((fulfill, _reject)=>{
                closeWebSocket(fulfill);
            });
        }
    }
    async _start() {
        const options = {
            host: this.host,
            port: this.port,
            secure: this.secure,
            useHostName: this.useHostName,
            alterPath: this.alterPath
        };
        try {
            const url = await this._fetchDebuggerURL(options);
            const urlObject = new URL(url);
            urlObject.pathname = options.alterPath(urlObject.pathname);
            this.webSocketUrl = urlObject.href;
            options.host = urlObject.hostname;
            options.port = urlObject.port || options.port;
            const protocol = await this._fetchProtocol(options);
            prepare(this, protocol);
            await this._connectToWebSocket();
            nextTick(()=>{
                this._notifier.emit("connect", this);
            });
        } catch (err) {
            this._notifier.emit("error", err);
        }
    }
    async _fetchDebuggerURL(options) {
        const userTarget = this.target;
        switch(typeof userTarget){
            case "string":
                {
                    let idOrUrl = userTarget;
                    if (idOrUrl.startsWith("/")) {
                        idOrUrl = `ws://${this.host}:${this.port}${idOrUrl}`;
                    }
                    if (idOrUrl.match(/^wss?:/i)) {
                        return idOrUrl;
                    } else {
                        const targets = await tryUntilTimeout(async ()=>{
                            return await List(options);
                        });
                        const object = targets.find((target)=>target.id === idOrUrl);
                        return object.webSocketDebuggerUrl;
                    }
                }
            case "object":
                {
                    const object = userTarget;
                    return object.webSocketDebuggerUrl;
                }
            case "function":
                {
                    const func = userTarget;
                    const targets = await List(options);
                    const result1 = await func(targets);
                    const object = typeof result1 === "number" ? targets[result1] : result1;
                    return object.webSocketDebuggerUrl;
                }
            default:
                throw new Error(`Invalid target argument "${this.target}"`);
        }
    }
    async _fetchProtocol(options) {
        if (this.protocol) {
            return this.protocol;
        } else {
            options.local = this.local;
            return await Protocol(options);
        }
    }
    _connectToWebSocket() {
        return new Promise((fulfill, reject)=>{
            try {
                if (this.secure) {
                    this.webSocketUrl = this.webSocketUrl.replace(/^ws:/i, "wss:");
                }
                this._ws = new WebSocket(this.webSocketUrl);
            } catch (err) {
                reject(err);
                return;
            }
            this._ws.onopen = ()=>{
                fulfill();
            };
            this._ws.onmessage = (data)=>{
                const message = JSON.parse(data.data);
                this._handleMessage(message);
            };
            this._ws.onclose = (_code)=>{
                this.emit("disconnect");
            };
            this._ws.onerror = (err)=>{
                reject(err);
            };
        });
    }
    _handleMessage(message) {
        if (message.id) {
            const callback = this._callbacks[message.id];
            if (!callback) {
                return;
            }
            if (message.error) {
                callback(true, message.error);
            } else {
                callback(false, message.result || {});
            }
            delete this._callbacks[message.id];
            if (Object.keys(this._callbacks).length === 0) {
                this.emit("ready");
            }
        } else if (message.method) {
            const { method, params, sessionId } = message;
            this.emit("event", message);
            this.emit(method, params, sessionId);
            this.emit(`${method}.${sessionId}`, params, sessionId);
        }
    }
    _enqueueCommand(method, params, sessionId, callback) {
        const id = this._nextCommandId++;
        const message = {
            id,
            method,
            sessionId,
            params: params || {}
        };
        this._ws.send(JSON.stringify(message));
        this._callbacks[id] = callback;
    }
}
function CDP(options, callback) {
    if (typeof options === "function") {
        callback = options;
        options = undefined;
    }
    const notifier = new EventEmitter();
    if (typeof callback === "function") {
        nextTick(()=>{
            new Chrome(options, notifier);
        });
        return notifier.once("connect", callback);
    } else {
        return new Promise((fulfill, reject)=>{
            notifier.once("connect", fulfill);
            notifier.once("error", reject);
            new Chrome(options, notifier);
        });
    }
}
async function readRegistryKey(registryPath, keyname) {
    const defaultKeyname = keyname === "(Default)";
    const args = [
        "query",
        registryPath
    ];
    if (defaultKeyname) {
        args.push("/ve");
    } else {
        args.push("/v");
        args.push(keyname);
    }
    const safeArgs = requireQuoting(args);
    const result1 = await safeWindowsExec("reg.exe", safeArgs.args, (cmd)=>{
        return execProcess({
            cmd,
            stdout: "piped",
            stderr: "piped"
        });
    });
    if (result1.success) {
        const output = result1.stdout;
        const regexStr = (defaultKeyname ? "" : ` *${keyname}`) + ` *(?:REG_SZ|REG_MULTI_SZ|REG_EXPAND_SZ|REG_DWORD|REG_BINARY|REG_NONE) *(.*)$`;
        const match = output?.match(RegExp(regexStr, "m"));
        if (match) {
            return match[1];
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
const tokenPath = join2(quartoCacheDir(), "codepage");
async function cacheCodePage() {
    if (!existsSync(tokenPath)) {
        const value = await registryReadString([
            kHKeyLocalMachine,
            kHKeyCurrentUser
        ], "SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage", "ACP");
        if (value) {
            Deno.writeTextFileSync(tokenPath, value);
        }
    }
}
function clearCodePageCache() {
    if (existsSync(tokenPath)) {
        Deno.removeSync(tokenPath);
    }
}
function readCodePageCache() {
    const codepage = Deno.readTextFileSync(tokenPath);
    if (codepage) {
        return codepage;
    } else {
        return undefined;
    }
}
function readCodePage() {
    const readCache = ()=>{
        const codepage = readCodePageCache();
        if (codepage) {
            return codepage;
        }
    };
    try {
        return readCache();
    } catch  {
        try {
            cacheCodePage();
            return readCache();
        } catch  {
            return undefined;
        }
    }
}
function requireQuoting(args) {
    let requireQuoting = false;
    if (Deno.build.os === "windows") {
        const shellCharReg = new RegExp("[ <>()|\\:&;#?*']");
        args = args.map((a)=>{
            if (shellCharReg.test(a)) {
                requireQuoting = true;
                return `"${a}"`;
            } else {
                return a;
            }
        });
    }
    return {
        status: requireQuoting,
        args: args
    };
}
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);
    }
}
let puppeteerImport = undefined;
let puppeteerUrl = "puppeteer/mod.ts";
async function getPuppeteer() {
    if (puppeteerImport !== undefined) {
        return puppeteerImport;
    }
    puppeteerImport = (await import(puppeteerUrl)).default;
    return puppeteerImport;
}
async function findChrome() {
    let path;
    if (Deno.build.os === "darwin") {
        path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
        if (!existsSync(path)) {
            return undefined;
        }
    } else if (Deno.build.os === "windows") {
        const programs = [
            "chrome.exe",
            "msedge.exe"
        ];
        for(let i1 = 0; i1 < programs.length; i1++){
            path = await readRegistryKey("HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\" + programs[i1], "(Default)");
            if (path && existsSync(path)) break;
        }
        if (!path) {
            const regKeys = [
                "ChromeHTML",
                "MSEdgeHTM"
            ];
            for(let i1 = 0; i1 < regKeys.length; i1++){
                path = await readRegistryKey(`HKCR\\${regKeys[i1]}\\shell\\open\\command`, "(Default)");
                path = path?.match(/"(.*)"/);
                path = path ? path[1] : undefined;
                if (path && existsSync(path)) break;
            }
        }
    } else {
        path = await which("google-chrome");
        if (!path) {
            path = await which("chromium-browser");
        }
    }
    return path;
}
async function getBrowserExecutablePath() {
    const browserFetcher = await fetcher();
    const availableRevisions = await browserFetcher.localRevisions();
    let executablePath = undefined;
    if (executablePath === undefined) {
        executablePath = await findChrome();
    }
    if (executablePath === undefined && availableRevisions.length > 0) {
        availableRevisions.sort((a, b)=>Number(b) - Number(a));
        const revision = availableRevisions[0];
        const revisionInfo = browserFetcher.revisionInfo(revision);
        executablePath = revisionInfo.executablePath;
    }
    if (executablePath === undefined) {
        error("Chrome not found");
        info("\nNo Chrome or Chromium installation was detected.\n\nPlease run 'quarto install chromium' to install Chromium.\n");
        throw new Error();
    }
    return executablePath;
}
async function fetcher() {
    const options = {
        path: chromiumInstallDir()
    };
    const fetcher = (await getPuppeteer()).createBrowserFetcher(options);
    return fetcher;
}
function chromiumInstallDir() {
    return quartoDataDir("chromium");
}
class Semaphore {
    value;
    tasks;
    constructor(value){
        this.value = value;
        this.tasks = [];
    }
    release() {
        this.value += 1;
        if (this.tasks.length) {
            const { resolve } = this.tasks.pop();
            resolve();
        }
    }
    async acquire() {
        if (this.value > 0) {
            this.value -= 1;
            return;
        }
        const result1 = new Promise((resolve, reject)=>{
            this.tasks.push({
                resolve,
                reject
            });
        });
        await result1;
        await this.acquire();
    }
    async runExclusive(fun) {
        await this.acquire();
        try {
            const result1 = await fun();
            this.release();
            return result1;
        } catch (e) {
            this.release();
            throw e;
        }
    }
}
function randomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(cryptoRandom() * (max - min) + min);
}
function randomHex(length) {
    const result1 = [];
    const hexRef = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "a",
        "b",
        "c",
        "d",
        "e",
        "f"
    ];
    for(let n = 0; n < length; n++){
        result1.push(hexRef[Math.floor(cryptoRandom() * 16)]);
    }
    return result1.join("");
}
function cryptoRandom() {
    const arr = new Uint32Array(2);
    crypto.getRandomValues(arr);
    const mantissa = arr[0] * Math.pow(2, 20) + (arr[1] >>> 12);
    const result1 = mantissa * Math.pow(2, -52);
    return result1;
}
function sleep1(ms) {
    return new Promise((resolve)=>setTimeout(resolve, ms));
}
const kLocalhost = "127.0.0.1";
const kMinPort = 3000;
const kMaxPort = 8000;
function isPortSafe(port) {
    return ![
        3659,
        4045,
        5060,
        5061,
        6000,
        6566,
        6665,
        6666,
        6667,
        6668,
        6669,
        6697
    ].includes(port);
}
function randomSafePort() {
    let result1;
    do {
        result1 = randomInt(kMinPort, kMaxPort);
    }while (!isPortSafe(result1))
    return result1;
}
function findOpenPort(defaultPort) {
    defaultPort = defaultPort || randomSafePort();
    if (isPortAvailableSync({
        port: defaultPort,
        hostname: kLocalhost
    })) {
        return defaultPort;
    } else {
        let ports = [];
        for(let i1 = 3000; i1 < 8000; ++i1){
            if (isPortSafe(i1)) {
                ports.push(i1);
            }
        }
        while(true){
            ports = shuffle1(ports);
            const port = getAvailablePortSync({
                port: ports,
                hostname: kLocalhost
            });
            if (port === undefined) {
                throw new Error("Unable to find open port");
            }
            if (isPortSafe(port)) {
                return port;
            }
        }
    }
}
async function waitForPort(options, timeout = 5000) {
    const kWaitInterval = 200;
    let waited = 0;
    while(waited <= timeout){
        if (isPortAvailableSync(options)) {
            return true;
        }
        await sleep1(200);
        waited += kWaitInterval;
    }
    return false;
}
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 (error) {
        if (error instanceof Deno.errors.AddrInUse) {
            return false;
        }
        throw error;
    }
}
function getAvailablePortSync(options = {
    transport: "tcp"
}) {
    if (options.port === undefined) {
        return getRandomPortSync(options);
    } else if (Array.isArray(options.port)) {
        const portList = options.port;
        for(let i1 = 0; i1 < portList.length; i1++){
            if (withinRange(portList[i1])) {
                const portAvailable = isPortAvailableSync({
                    port: portList[i1],
                    ...options.hostname ? {
                        hostname: options.hostname
                    } : {},
                    ...options.transport ? {
                        transport: options.transport
                    } : {}
                });
                if (portAvailable) {
                    return portList[i1];
                } 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);
    const restrictedPorts = [
        1719,
        1720,
        1723,
        2049,
        3659,
        4045,
        5060,
        5061,
        6000,
        6566,
        6665,
        6666,
        6667,
        6668,
        6669,
        6697,
        10080
    ];
    if (isPortAvailableSync({
        port: randomPort,
        ...options.hostname ? {
            hostname: options.hostname
        } : {},
        ...options.transport ? {
            transport: options.transport
        } : {}
    }) && !restrictedPorts.includes(randomPort)) {
        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;
}
const _globalLifetimes = {};
const _globalAwaitQueues = {};
function waitUntilNamedLifetime(name) {
    const lt = getNamedLifetime(name);
    if (lt === undefined) {
        return Promise.resolve(createNamedLifetime(name));
    }
    const promise = new Promise((resolve)=>{
        if (_globalAwaitQueues[name] === undefined) {
            _globalAwaitQueues[name] = [];
        }
        _globalAwaitQueues[name].push(resolve);
    });
    return promise;
}
function createNamedLifetime(name) {
    if (_globalLifetimes[name] !== undefined) {
        throw new InternalError(`Lifetime ${name} already exists.`);
    }
    const lifetime = new Lifetime();
    lifetime.attach({
        cleanup: ()=>{
            delete _globalLifetimes[name];
            if (_globalAwaitQueues[name] && _globalAwaitQueues[name].length) {
                const resolver = _globalAwaitQueues[name].shift();
                const newLifetime = createNamedLifetime(name);
                resolver(newLifetime);
            }
        }
    });
    _globalLifetimes[name] = lifetime;
    return lifetime;
}
function getNamedLifetime(name, createIfMissing = false) {
    if (_globalLifetimes[name] !== undefined) {
        return _globalLifetimes[name];
    }
    if (createIfMissing) {
        return createNamedLifetime(name);
    }
}
class Lifetime {
    _namedObjs;
    _unnamedObjs;
    constructor(){
        this._namedObjs = {};
        this._unnamedObjs = [];
    }
    attach(obj, key) {
        if (key === undefined) {
            this._unnamedObjs.push(obj);
        } else {
            this._namedObjs[key] = obj;
        }
    }
    get(key) {
        return this._namedObjs[key];
    }
    async cleanup() {
        await Promise.all(this._unnamedObjs.map((x)=>x.cleanup()));
        await Promise.all(Object.values(this._namedObjs).map((x)=>x.cleanup()));
        this._namedObjs = {};
        this._unnamedObjs = [];
    }
}
async function waitForServer(port, timeout = 3000) {
    const interval = 50;
    let soFar = 0;
    do {
        try {
            const response = await fetch(`http://localhost:${port}/json/list`);
            if (response.status !== 200) {
                throw new Error("");
            }
            return true;
        } catch (_e) {
            soFar += interval;
            await new Promise((resolve)=>setTimeout(resolve, 50));
        }
    }while (soFar < timeout)
    return false;
}
const criSemaphore = new Semaphore(1);
function withCriClient(fn, appPath, port) {
    if (port === undefined) {
        port = findOpenPort(9222);
    }
    return criSemaphore.runExclusive(async ()=>{
        const lifetime = getNamedLifetime(kRenderFileLifetime);
        if (lifetime === undefined) {
            throw new InternalError("named lifetime render-file not found");
        }
        let client;
        if (lifetime.get("cri-client") === undefined) {
            client = await criClient(appPath, port);
            lifetime.attach({
                client,
                async cleanup () {
                    await client.close();
                }
            }, "cri-client");
        } else {
            client = lifetime.get("cri-client").client;
        }
        return await fn(client);
    });
}
async function criClient(appPath, port) {
    if (port === undefined) {
        port = findOpenPort(9222);
    }
    const app = appPath || await getBrowserExecutablePath();
    const cmd = [
        app,
        "--headless",
        "--no-sandbox",
        "--disable-gpu",
        "--renderer-process-limit=1",
        `--remote-debugging-port=${port}`
    ];
    const browser = Deno.run({
        cmd,
        stdout: "piped",
        stderr: "piped"
    });
    if (!await waitForServer(port)) {
        let msg = "Couldn't find open server.";
        if (!(await browser.status()).success) {
            const rawError = await browser.stderrOutput();
            const errorString = new TextDecoder().decode(rawError);
            msg = msg + "\n" + `Chrome process error: ${errorString}`;
        }
        throw new Error(msg);
    }
    let client;
    const result1 = {
        close: async ()=>{
            await client.close();
            browser.close();
        },
        rawClient: ()=>client,
        open: async (url)=>{
            for(let i1 = 0; i1 < 5; ++i1){
                try {
                    client = await CDP({
                        port
                    });
                    break;
                } catch (e) {
                    if (i1 === 5 - 1) {
                        throw e;
                    }
                    await sleep(100);
                }
            }
            const { Network, Page } = client;
            await Network.enable();
            await Page.enable();
            await Page.navigate({
                url
            });
            return new Promise((fulfill, _reject)=>{
                Page.loadEventFired(()=>{
                    fulfill(null);
                });
            });
        },
        docQuerySelectorAll: async (cssSelector)=>{
            await client.DOM.enable();
            const doc = await client.DOM.getDocument();
            const nodeIds = await client.DOM.querySelectorAll({
                nodeId: doc.root.nodeId,
                selector: cssSelector
            });
            return nodeIds.nodeIds;
        },
        contents: async (cssSelector)=>{
            const nodeIds = await result1.docQuerySelectorAll(cssSelector);
            return Promise.all(nodeIds.map(async (nodeId)=>{
                return (await client.DOM.getOuterHTML({
                    nodeId
                })).outerHTML;
            }));
        },
        screenshots: async (cssSelector, scale = 4)=>{
            const nodeIds = await result1.docQuerySelectorAll(cssSelector);
            const lst = [];
            for (const nodeId of nodeIds){
                let quad;
                try {
                    quad = (await client.DOM.getContentQuads({
                        nodeId
                    })).quads[0];
                } catch (_e) {
                    continue;
                }
                const minX = Math.min(quad[0], quad[2], quad[4], quad[6]);
                const maxX = Math.max(quad[0], quad[2], quad[4], quad[6]);
                const minY = Math.min(quad[1], quad[3], quad[5], quad[7]);
                const maxY = Math.max(quad[1], quad[3], quad[5], quad[7]);
                try {
                    const screenshot = await client.Page.captureScreenshot({
                        clip: {
                            x: minX,
                            y: minY,
                            width: maxX - minX,
                            height: maxY - minY,
                            scale
                        },
                        fromSurface: true,
                        captureBeyondViewport: true
                    });
                    const buf = decodeBase64(screenshot.data);
                    lst.push({
                        nodeId,
                        data: buf
                    });
                } catch (_e) {
                    continue;
                }
            }
            return lst;
        }
    };
    return result1;
}
const standaloneInclude = async (handlerContext, filename)=>{
    const source = handlerContext.options.context.target.source;
    const retrievedFiles = [
        source
    ];
    const textFragments = [];
    if (!handlerContext.options.state) {
        handlerContext.options.state = {};
    }
    if (!handlerContext.options.state.include) {
        handlerContext.options.state.include = {
            includes: []
        };
    }
    const includeState = handlerContext.options.state.include;
    const retrieveInclude = async (filename)=>{
        const path = handlerContext.resolvePath(filename);
        if (retrievedFiles.indexOf(path) !== -1) {
            throw new Error(`Include directive found circular include of file ${filename}.`);
        }
        let includeSrc;
        try {
            includeSrc = asMappedString(Deno.readTextFileSync(path), path);
        } catch (_e) {
            const errMsg = [
                `Include directive failed.`
            ];
            errMsg.push(...retrievedFiles.map((s)=>`  in file ${s}, `));
            errMsg.push(`  could not find file ${path}.`);
            throw new Error(errMsg.join("\n"));
        }
        retrievedFiles.push(filename);
        let rangeStart = 0;
        for (const { substring, range } of rangedLines(includeSrc.value)){
            const m = isBlockShortcode(substring);
            if (m && m.name.toLocaleLowerCase() === "include") {
                textFragments.push(mappedString(includeSrc, [
                    {
                        start: rangeStart,
                        end: range.start
                    }
                ]));
                rangeStart = range.end;
                const params = m.params;
                if (params.length === 0) {
                    throw new Error("Include directive needs file parameter");
                }
                includeState.includes.push({
                    source: filename,
                    target: params[0]
                });
                await retrieveInclude(params[0]);
            }
        }
        if (rangeStart !== includeSrc.value.length) {
            textFragments.push(mappedString(includeSrc, [
                {
                    start: rangeStart,
                    end: includeSrc.value.length
                }
            ]));
        }
        textFragments.push(includeSrc.value.endsWith("\n") ? "\n" : "\n\n");
        retrievedFiles.pop();
    };
    await retrieveInclude(filename);
    return Promise.resolve(mappedConcat(textFragments));
};
class LocalizedError extends Error {
    constructor(name, message, source, position = 0, printName = true, printStack = true){
        const fileName = source.map(position)?.originalString?.fileName;
        if (fileName) {
            const { line, column } = mappedIndexToLineCol(source)(position);
            message = `In file ${fileName} (${line + 1}:${column + 1}):
${message}`;
        }
        super(message);
        this.name = name;
        this.printName = printName;
        this.printStack = printStack;
    }
    printName;
    printStack;
}
const handlers = {};
let globalFigureCounter = {};
function resetFigureCounter() {
    globalFigureCounter = {};
}
function makeHandlerContext(options) {
    if (options.state === undefined) {
        options.state = {};
    }
    const results = {
        resourceFiles: [],
        includes: {},
        extras: {},
        supporting: []
    };
    const tempContext = options.temp;
    const context = {
        options,
        getState () {
            if (options.state[options.name] === undefined) {
                options.state[options.name] = {};
            }
            return options.state[options.name];
        },
        async extractHtml (opts) {
            const { html: content, selector } = opts;
            const nonEmptyHtmlResources = opts.resources || [];
            const dirName = context.options.temp.createDir();
            for (const [name, content] of nonEmptyHtmlResources){
                Deno.writeTextFileSync(join2(dirName, name), content);
            }
            const fileName = join2(dirName, "index.html");
            Deno.writeTextFileSync(fileName, content);
            const url = `file://${fileName}`;
            return await withCriClient(async (client)=>{
                await client.open(url);
                return await client.contents(selector);
            });
        },
        async createPngsFromHtml (opts) {
            const { prefix, html: content, deviceScaleFactor, selector } = opts;
            const nonEmptyHtmlResources = opts.resources || [];
            const dirName = context.options.temp.createDir();
            for (const [name, content] of nonEmptyHtmlResources){
                Deno.writeTextFileSync(join2(dirName, name), content);
            }
            const fileName = join2(dirName, "index.html");
            Deno.writeTextFileSync(fileName, content);
            const url = `file://${fileName}`;
            const { elements, images } = await withCriClient(async (client)=>{
                await client.open(url);
                const elements = await client.contents(selector);
                const screenshots = await client.screenshots(selector, deviceScaleFactor);
                return {
                    elements,
                    images: screenshots.map((x)=>x.data)
                };
            });
            const sourceNames = [];
            for(let i1 = 0; i1 < images.length; ++i1){
                const { sourceName, fullName } = context.uniqueFigureName(prefix, ".png");
                sourceNames.push(sourceName);
                Deno.writeFileSync(fullName, images[i1]);
            }
            return {
                filenames: sourceNames,
                elements
            };
        },
        cellContent (cell) {
            if (typeof cell?.options?.file === "string") {
                try {
                    return mappedStringFromFile(context.resolvePath(cell?.options?.file));
                } catch (e) {
                    error(`Couldn't open file ${cell?.options?.file}`);
                    throw e;
                }
            } else {
                return cell.source;
            }
        },
        resolvePath (path) {
            const sourceDir = dirname2(options.context.target.source);
            const rootDir = options.context.project.isSingleFile ? sourceDir : options.context.project.dir;
            if (path.startsWith("/")) {
                return resolve2(rootDir, `.${path}`);
            } else {
                return resolve2(sourceDir, path);
            }
        },
        uniqueFigureName (prefix, extension) {
            prefix = prefix ?? "figure-";
            extension = extension ?? ".png";
            if (!globalFigureCounter[prefix]) {
                globalFigureCounter[prefix] = 1;
            } else {
                globalFigureCounter[prefix]++;
            }
            const pngName = `${prefix}${globalFigureCounter[prefix]}${extension}`;
            const tempName = join2(context.figuresDir(), pngName);
            const baseDir = dirname2(options.context.target.source);
            const mdName = relative2(baseDir, tempName);
            this.addSupporting(relative2(baseDir, context.figuresDir()));
            return {
                baseName: basename2(mdName),
                sourceName: mdName,
                fullName: tempName
            };
        },
        figuresDir () {
            const file = normalizePath(options.context.target.source);
            const filesDir = join2(dirname2(file), inputFilesDir(file));
            const result1 = join2(filesDir, figuresDir(context.options.format.pandoc.to));
            ensureDirSync(result1);
            return result1;
        },
        addHtmlDependency (dep) {
            if (results.extras.html === undefined) {
                results.extras.html = {
                    [kDependencies]: [
                        dep
                    ]
                };
            } else {
                results.extras.html[kDependencies].push(dep);
            }
        },
        addSupporting (dir) {
            if (results.supporting.indexOf(dir) === -1) {
                results.supporting.push(dir);
            }
        },
        addResource (fileName) {
            results.resourceFiles.push(fileName);
        },
        addInclude (content, where) {
            const fileName = tempContext.createFile();
            Deno.writeTextFileSync(fileName, content);
            if (results.includes[where] === undefined) {
                results.includes[where] = [
                    fileName
                ];
            } else {
                results.includes[where].push(fileName);
            }
        }
    };
    return {
        context,
        results
    };
}
function languages() {
    const cellLanguage = [];
    for (const [k, v] of Object.entries(handlers)){
        if (v.type === "cell") {
            cellLanguage.push(k);
        }
    }
    return cellLanguage;
}
async function languageSchema(language) {
    if (handlers[language] === undefined) {
        return undefined;
    }
    const call = handlers[language].schema;
    if (call === undefined) {
        return undefined;
    } else {
        return await call();
    }
}
function install(handler) {
    const language = handler.languageName;
    handlers[language] = handler;
    if (handler.comment !== undefined) {
        addLanguageComment(language, handler.comment);
    }
}
const processMarkdownIncludes = async (newCells, options, filename)=>{
    const includeHandler = makeHandlerContext(options);
    if (!includeHandler.context.options.state) {
        includeHandler.context.options.state = {};
    }
    if (!includeHandler.context.options.state.include) {
        includeHandler.context.options.state.include = {
            includes: []
        };
    }
    const includeState = includeHandler.context.options.state.include;
    for(let i1 = 0; i1 < newCells.length; ++i1){
        if (newCells[i1].value.search(/\s*```\s*{\s*shortcodes\s*=\s*false\s*}/) !== -1) {
            continue;
        }
        const lines = mappedLines(newCells[i1], true);
        let foundShortcodes = false;
        for(let j = 0; j < lines.length; ++j){
            try {
                const shortcode = isBlockShortcode(lines[j].value);
                if (shortcode && shortcode.name === "include") {
                    foundShortcodes = true;
                    const param = shortcode.params[0];
                    if (!param) {
                        throw new Error("Include directive needs filename as a parameter");
                    }
                    if (filename) {
                        includeState.includes.push({
                            source: filename,
                            target: param
                        });
                    }
                    lines[j] = await standaloneInclude(includeHandler.context, param);
                }
            } catch (e) {
                if (e instanceof InvalidShortcodeError) {
                    const mapResult = newCells[i1].map(newCells[i1].value.indexOf("{"));
                    throw new LocalizedError("Invalid Shortcode", e.message, mapResult.originalString, mapResult.index);
                } else {
                    throw e;
                }
            }
        }
        if (foundShortcodes) {
            newCells[i1] = mappedConcat(lines);
        }
    }
};
async function expandIncludes(markdown, options, filename) {
    const mdCells = (await breakQuartoMd(markdown, false)).cells;
    if (mdCells.length === 0) {
        return markdown;
    }
    const newCells = [];
    for(let i1 = 0; i1 < mdCells.length; ++i1){
        const cell = mdCells[i1];
        newCells.push(i1 === 0 ? cell.sourceVerbatim : mappedConcat([
            "\n",
            cell.sourceVerbatim
        ]));
    }
    await processMarkdownIncludes(newCells, options, filename);
    return join3(newCells, "");
}
async function handleLanguageCells(options) {
    const mdCells = (await breakQuartoMd(options.markdown, false)).cells;
    if (mdCells.length === 0) {
        return {
            markdown: options.markdown
        };
    }
    const newCells = [];
    const languageCellsPerLanguage = {};
    for(let i1 = 0; i1 < mdCells.length; ++i1){
        const cell = mdCells[i1];
        newCells.push(i1 === 0 ? cell.sourceVerbatim : mappedConcat([
            "\n",
            cell.sourceVerbatim
        ]));
        if (cell.cell_type === "raw" || cell.cell_type === "markdown") {
            continue;
        }
        const language = cell.cell_type.language;
        if (language !== "_directive" && handlers[language] === undefined) {
            continue;
        }
        if (handlers[language]?.stage && handlers[language].stage !== "any" && options.stage !== handlers[language].stage) {
            continue;
        }
        if (languageCellsPerLanguage[language] === undefined) {
            languageCellsPerLanguage[language] = [];
        }
        languageCellsPerLanguage[language].push({
            index: i1,
            source: cell
        });
    }
    let results = undefined;
    for (const [language, cells] of Object.entries(languageCellsPerLanguage)){
        if (language === "_directive") {
            for (const cell of cells){
                const directiveCellType = cell.source.cell_type;
                const innerLanguage = directiveCellType.name;
                const innerLanguageHandler = handlers[innerLanguage];
                if (innerLanguageHandler && innerLanguageHandler.stage !== "any" && innerLanguageHandler.stage !== options.stage) {
                    newCells[cell.index] = mappedConcat([
                        newCells[cell.index],
                        "\n"
                    ]);
                    continue;
                }
                if (innerLanguageHandler === undefined || innerLanguageHandler.type === "cell") {
                    newCells[cell.index] = mappedConcat([
                        newCells[cell.index],
                        "\n"
                    ]);
                    continue;
                }
                if (innerLanguageHandler.directive === undefined) {
                    throw new Error("Bad language handler: directive callback is undefined");
                }
                const innerHandler = makeHandlerContext({
                    ...options,
                    name: innerLanguage
                });
                newCells[cell.index] = asMappedString(await innerLanguageHandler.directive(innerHandler.context, directiveCellType));
                results = mergeConfigs(results, innerHandler.results);
            }
        } else {
            const handler = makeHandlerContext({
                ...options,
                name: language
            });
            const languageHandler = handlers[language];
            if (languageHandler !== undefined && languageHandler.type !== "directive") {
                const transformedCells = await languageHandler.document(handler.context, cells.map((x)=>x.source));
                for(let i1 = 0; i1 < transformedCells.length; ++i1){
                    newCells[cells[i1].index] = transformedCells[i1];
                }
                if (results === undefined) {
                    results = handler.results;
                } else {
                    results = mergeConfigs(results, handler.results);
                }
            }
        }
    }
    await processMarkdownIncludes(newCells, options);
    return {
        markdown: join3(newCells, ""),
        results
    };
}
const baseHandler = {
    type: "any",
    stage: "any",
    languageName: "<<<< baseHandler: languageName should have been overridden >>>>",
    defaultOptions: {
        echo: true
    },
    async document (handlerContext, cells) {
        this.documentStart(handlerContext);
        const mermaidExecute = handlerContext.options.format.mergeAdditionalFormats({
            execute: this.defaultOptions
        }).execute;
        const result1 = await Promise.all(cells.map((cell)=>{
            return this.cell(handlerContext, cell, mergeConfigs(mermaidExecute, cell.options ?? {}));
        }));
        this.documentEnd(handlerContext);
        return result1;
    },
    documentStart (_handlerContext) {},
    documentEnd (_handlerContext) {},
    cell (_handlerContext, cell, _options) {
        return Promise.resolve(cell.sourceVerbatim);
    },
    build (handlerContext, cell, content, options, extraCellOptions, skipOptions) {
        const contentLines = mappedLines(cell.sourceWithYaml, true);
        const frontMatterLines = [];
        const commentPattern = optionCommentPatternFromLanguage(this.languageName);
        let inputIndex = 0;
        for (const contentLine of contentLines){
            const commentMatch = contentLine.value.match(commentPattern);
            if (commentMatch) {
                if (contentLine.value.indexOf("echo: fenced") === -1) {
                    frontMatterLines.push(contentLine);
                }
                ++inputIndex;
            } else {
                break;
            }
        }
        const inputLines = contentLines.slice(inputIndex);
        const { classes, attrs } = getDivAttributes({
            ...{
                [kFigAlign]: handlerContext.options.format.render[kFigAlign]
            },
            ...extraCellOptions || {},
            ...cell.options
        }, skipOptions);
        const hasAttribute = (attrKey)=>attrs.some((attr)=>attr === attrKey || attr.startsWith(`${attrKey}=`));
        const hasLayoutAttributes = hasAttribute(kLayoutNrow) || hasAttribute(kLayoutNcol) || hasAttribute(kLayout);
        const isPowerpointOutput = handlerContext.options.format.pandoc.to?.startsWith("pptx");
        const unrolledOutput = isPowerpointOutput && !hasLayoutAttributes;
        const cellBlock = unrolledOutput ? pandocList({
            skipFirstLineBreak: true
        }) : pandocDiv({
            classes: [
                "cell",
                ...classes
            ],
            attrs
        });
        const languageClass = this.languageClass === undefined ? this.languageName : typeof this.languageClass === "string" ? this.languageClass : this.languageClass(handlerContext.options);
        const cellInputClasses = [
            languageClass,
            "cell-code",
            ...options["class-source"] ?? []
        ];
        const cellInputAttrs = [
            ...options["attr-source"] ?? []
        ];
        const cellOutputClasses = [
            "cell-output-display",
            ...options["class-output"] ?? []
        ];
        const cellOutputAttrs = [
            ...options["attr-output"] ?? []
        ];
        if (options[kCodeFold] !== undefined) {
            cellInputAttrs.push(`code-fold="${options[kCodeFold]}"`);
        }
        switch(options.echo){
            case true:
                {
                    const cellInput = pandocCode({
                        classes: cellInputClasses,
                        attrs: cellInputAttrs
                    });
                    cellInput.push(pandocRawStr(mappedTrim(mappedConcat(inputLines))));
                    cellBlock.push(cellInput);
                    break;
                }
            case "fenced":
                {
                    const cellInput = pandocCode({
                        classes: [
                            "markdown",
                            ...cellInputClasses.slice(1)
                        ],
                        attrs: cellInputAttrs
                    });
                    const cellFence = pandocCode({
                        language: this.languageName,
                        skipFirstLineBreak: true
                    });
                    const fencedInput = mappedConcat([
                        ...frontMatterLines,
                        ...inputLines
                    ]);
                    cellFence.push(pandocRawStr(mappedTrim(fencedInput)));
                    cellInput.push(cellFence);
                    cellBlock.push(cellInput);
                    break;
                }
        }
        const cellOutputDiv = unrolledOutput ? cellBlock : pandocDiv({
            attrs: cellOutputAttrs,
            classes: cellOutputClasses
        });
        cellBlock.push(cellOutputDiv);
        const figureLikeOptions = {};
        if (typeof cell.options?.label === "string") {
            figureLikeOptions.id = cell.options?.label;
        }
        const figureLike = unrolledOutput ? cellBlock : pandocDiv(figureLikeOptions);
        const cellOutput = unrolledOutput ? cellBlock : pandocDiv();
        figureLike.push(cellOutput);
        cellOutputDiv.push(figureLike);
        if (options.eval === true) {
            cellOutput.push(pandocRawStr(content));
        }
        if (cell.options?.[kCellFigCap]) {
            let capOpen = "", capClose = "";
            if (cell.options?.label === undefined) {
                capOpen = "`<figcaption>`{=html} ";
                capClose = "`</figcaption>`{=html} ";
            }
            figureLike.push(pandocRawStr(`\n\n${capOpen}${cell.options[kCellFigCap]}${capClose}`));
        }
        if (cell.options?.label === undefined) {
            figureLike.unshift(pandocRawStr("`<figure class=''>`{=html}\n"));
            figureLike.push(pandocRawStr("`</figure>`{=html}\n"));
        }
        return cellBlock.mappedString();
    }
};
function getDivAttributes(options, forceSkip) {
    const attrs = [];
    if (forceSkip) {
        options = {
            ...options
        };
        for (const skip of forceSkip){
            delete options[skip];
        }
    }
    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(options || {})){
        if (!keysToNotSerialize.has(key)) {
            const t = typeof value;
            if (t === "undefined") {
                continue;
            }
            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}, key ${key}`);
            }
        }
    }
    if (options?.[kCellLstCap]) {
        attrs.push(`lst-cap="${options?.[kCellLstCap]}"`);
    }
    const classStr = options?.classes || "";
    const classes = classStr === "" ? [] : classStr.trim().split(" ");
    if (typeof options?.[kFigAlign] === "string") {
        attrs.push(`layout-align="${options?.[kFigAlign]}"`);
    }
    if (typeof options?.panel === "string") {
        classes.push(`panel-${options?.panel}`);
    }
    if (typeof options?.column === "string") {
        classes.push(`column-${options?.column}`);
    }
    if (typeof options?.[kCapLoc] === "string") {
        classes.push(`caption-${options?.[kCapLoc]}`);
    }
    if (typeof options?.[kFigCapLoc] === "string") {
        classes.push(`fig-cap-location-${options?.[kFigCapLoc]}`);
    }
    if (typeof options?.[kTblCapLoc] === "string") {
        classes.push(`tbl-cap-location-${options?.[kTblCapLoc]}`);
    }
    if (typeof options?.[kCellFigColumn] === "string") {
        classes.push(`fig-caption-${options?.[kCellFigColumn]}`);
    }
    if (typeof options?.[kCellTblColumn] === "string") {
        classes.push(`fig-caption-${options?.[kCellTblColumn]}`);
    }
    return {
        attrs,
        classes
    };
}
function projectExcludeDirs(context) {
    const outputDir = projectOutputDir(context);
    if (outputDir) {
        return [
            outputDir
        ];
    } else {
        return [];
    }
}
function projectFormatOutputDir(format, context, type) {
    const projOutputDir = projectOutputDir(context);
    if (type.formatOutputDirectory) {
        const formatOutputDir = type.formatOutputDirectory(format);
        if (formatOutputDir) {
            return join2(projOutputDir, formatOutputDir);
        } else {
            return projOutputDir;
        }
    } else {
        return projOutputDir;
    }
}
function projectOutputDir(context) {
    let outputDir = context.config?.project[kProjectOutputDir];
    if (outputDir) {
        if (!isAbsolute2(outputDir)) {
            outputDir = join2(context.dir, outputDir);
        }
    } else {
        outputDir = context.dir;
    }
    if (existsSync(outputDir)) {
        return normalizePath(outputDir);
    } else {
        return outputDir;
    }
}
function hasProjectOutputDir(context) {
    return !!context.config?.project[kProjectOutputDir];
}
function isProjectInputFile(path, context) {
    if (existsSync(path)) {
        const renderPath = normalizePath(path);
        return context.files.input.map((file)=>normalizePath(file)).includes(renderPath);
    } else {
        return false;
    }
}
function projectConfigFile(dir) {
    return [
        "_quarto.yml",
        "_quarto.yaml"
    ].map((file)=>join2(dir, file)).find(existsSync1);
}
function projectVarsFile(dir) {
    return [
        "_variables.yml",
        "_variables.yaml"
    ].map((file)=>join2(dir, file)).find(existsSync1);
}
function projectOffset(context, input) {
    const projDir = normalizePath(context.dir);
    const inputDir = normalizePath(dirname2(input));
    const offset = relative2(inputDir, projDir) || ".";
    return pathWithForwardSlashes(offset);
}
function toInputRelativePaths(type, baseDir, inputDir, collection, ignoreResources) {
    const existsCache = new Map();
    const resourceIgnoreFields = ignoreResources || ignoreFieldsForProjectType(type) || [];
    const offset = relative2(inputDir, baseDir);
    const fixup = (value)=>{
        if (!existsCache.has(value)) {
            const projectPath = join2(baseDir, value);
            try {
                if (existsSync(projectPath)) {
                    existsCache.set(value, pathWithForwardSlashes(join2(offset, value)));
                } else {
                    existsCache.set(value, value);
                }
            } catch  {
                existsCache.set(value, value);
            }
        }
        return existsCache.get(value);
    };
    const inner = (collection, parentKey)=>{
        if (Array.isArray(collection)) {
            for(let index = 0; index < collection.length; ++index){
                const value = collection[index];
                if (Array.isArray(value) || value instanceof Object) {
                    inner(value);
                } else if (typeof value === "string") {
                    if (value.length > 0 && !isAbsolute2(value)) {
                        collection[index] = fixup(value);
                    }
                }
            }
        } else {
            for (const index of Object.keys(collection)){
                const value = collection[index];
                if (parentKey === kHtmlMathMethod && index === "method" || resourceIgnoreFields.includes(index)) {} else if (Array.isArray(value) || value instanceof Object) {
                    inner(value, index);
                } else if (typeof value === "string") {
                    if (value.length > 0 && !isAbsolute2(value)) {
                        collection[index] = fixup(value);
                    }
                }
            }
        }
    };
    inner(collection);
    return collection;
}
function ignoreFieldsForProjectType(type) {
    const resourceIgnoreFields = type ? [
        "project"
    ].concat(type.resourceIgnoreFields ? type.resourceIgnoreFields() : []) : [];
    return resourceIgnoreFields;
}
function projectIsWebsite(context) {
    if (context) {
        const projType = projectType(context.config?.project?.[kProjectType]);
        return projectTypeIsWebsite(projType);
    } else {
        return false;
    }
}
function projectIsManuscript(context) {
    if (context) {
        const projType = projectType(context.config?.project?.[kProjectType]);
        return projType.type === kManuscriptType;
    } else {
        return false;
    }
}
function projectPreviewServe(context) {
    return context?.config?.project?.preview?.serve;
}
function projectIsServeable(context) {
    return projectIsWebsite(context) || projectIsManuscript(context) || !!projectPreviewServe(context);
}
function projectTypeIsWebsite(projType) {
    return projType.type === kWebsite || projType.inheritsType === kWebsite;
}
function projectIsBook(context) {
    if (context) {
        const projType = projectType(context.config?.project?.[kProjectType]);
        return projType.type === "book";
    } else {
        return false;
    }
}
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 normalizeFormatYaml(yamlFormat) {
    if (yamlFormat) {
        if (typeof yamlFormat === "string") {
            yamlFormat = {
                [yamlFormat]: {}
            };
        } else if (typeof yamlFormat === "object") {
            const formats = Object.keys(yamlFormat);
            for (const format of formats){
                if (yamlFormat[format] === "default") {
                    yamlFormat[format] = {};
                }
            }
        }
    }
    return yamlFormat || {};
}
async function directoryMetadataForInputFile(project, inputDir) {
    const projectDir = project.dir;
    const metadataFile = (dir)=>{
        return [
            "_metadata.yml",
            "_metadata.yaml"
        ].map((file)=>join2(dir, file)).find(existsSync1);
    };
    const relativePath = relative2(projectDir, inputDir);
    const dirs = relativePath.split(SEPARATOR_PATTERN2);
    let config = {};
    let currentDir = projectDir;
    const frontMatterSchema = await getFrontMatterSchema();
    for(let i1 = 0; i1 < dirs.length; i1++){
        const dir = dirs[i1];
        currentDir = join2(currentDir, dir);
        const file = metadataFile(currentDir);
        if (file) {
            const errMsg = "Directory metadata validation failed for " + file + ".";
            const yaml = await readAndValidateYamlFromFile(file, frontMatterSchema, errMsg) || {};
            if (yaml.format) {
                yaml.format = normalizeFormatYaml(yaml.format);
            }
            config = mergeConfigs(config, toInputRelativePaths(projectType(project?.config?.project?.[kProjectType]), currentDir, inputDir, yaml));
        }
    }
    return config;
}
const mdForFile = async (project, engine, file)=>{
    if (engine) {
        return await engine.markdownForFile(file);
    } else {
        return Promise.resolve(mappedStringFromFile(file));
    }
};
async function projectResolveCodeCellsForFile(project, engine, file, markdown, force) {
    const cache = ensureFileInformationCache(project, file);
    if (!force && cache.codeCells) {
        return cache.codeCells || [];
    }
    if (!markdown) {
        markdown = await mdForFile(project, engine, file);
    }
    const result1 = [];
    const fileStack = [];
    const inner = async (file, cells)=>{
        if (fileStack.includes(file)) {
            throw new Error("Circular include detected:\n  " + fileStack.join(" ->\n  "));
        }
        fileStack.push(file);
        for (const cell of cells){
            if (typeof cell.cell_type === "string") {
                continue;
            }
            if (cell.cell_type.language === "_directive") {
                const directiveCell = cell.cell_type;
                if (directiveCell.name !== "include") {
                    continue;
                }
                const arg = directiveCell.shortcode.params[0];
                const paths = arg.startsWith("/") ? [
                    project.dir,
                    arg
                ] : [
                    project.dir,
                    relative2(project.dir, dirname2(file)),
                    arg
                ];
                const innerFile = join2(...paths);
                await inner(innerFile, (await breakQuartoMd(await mdForFile(project, engine, innerFile))).cells);
            }
            if (cell.cell_type.language !== "_directive") {
                const cellOptions = partitionCellOptionsText(cell.cell_type.language, cell.sourceWithYaml ?? cell.source);
                const metadata = cellOptions.yaml ? parse1(cellOptions.yaml.value, {
                    schema: QuartoJSONSchema1
                }) : {};
                const lineLocator = mappedIndexToLineCol(cell.sourceVerbatim);
                result1.push({
                    start: lineLocator(0).line,
                    end: lineLocator(cell.sourceVerbatim.value.length - 1).line,
                    file: file,
                    source: normalizeNewlines(cell.source.value),
                    language: cell.cell_type.language,
                    metadata
                });
            }
        }
        fileStack.pop();
    };
    await inner(file, (await breakQuartoMd(markdown)).cells);
    cache.codeCells = result1;
    return result1;
}
async function projectResolveFullMarkdownForFile(project, engine, file, markdown, force) {
    const cache = ensureFileInformationCache(project, file);
    if (!force && cache.fullMarkdown) {
        return cache.fullMarkdown;
    }
    const temp = createTempContext();
    if (!markdown) {
        markdown = await mdForFile(project, engine, file);
    }
    const options = {
        name: "",
        temp,
        stage: "pre-engine",
        format: undefined,
        markdown,
        context: {
            project,
            target: {
                source: file
            }
        },
        flags: {}
    };
    try {
        const result1 = await expandIncludes(markdown, options, file);
        cache.fullMarkdown = result1;
        cache.includeMap = options.state?.include.includes;
        return result1;
    } finally{
        temp.cleanup();
    }
}
const ensureFileInformationCache = (project, file)=>{
    if (!project.fileInformationCache) {
        project.fileInformationCache = new Map();
    }
    if (!project.fileInformationCache.has(file)) {
        project.fileInformationCache.set(file, {});
    }
    return project.fileInformationCache.get(file);
};
function assertExists(actual, msg) {
    if (actual === undefined || actual === null) {
        const msgSuffix = msg ? `: ${msg}` : ".";
        msg = `Expected actual: "${actual}" to not be null or undefined${msgSuffix}`;
        throw new AssertionError(msg);
    }
}
function assert2(expr, msg = "") {
    assert(expr, msg);
}
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,
            ...kJupyterPercentScriptExtensions,
            ...kQmdExtensions
        ],
    claimsFile: (file, ext)=>{
        return kJupyterNotebookExtensions.includes(ext.toLowerCase()) || isJupyterPercentScript(file);
    },
    claimsLanguage: (_language)=>{
        return false;
    },
    markdownForFile (file) {
        if (isJupyterNotebook(file)) {
            const nbJSON = Deno.readTextFileSync(file);
            const nb = JSON.parse(nbJSON);
            return Promise.resolve(asMappedString(markdownFromNotebookJSON(nb)));
        } else if (isJupyterPercentScript(file)) {
            return Promise.resolve(asMappedString(markdownFromJupyterPercentScript(file)));
        } else {
            return Promise.resolve(mappedStringFromFile(file));
        }
    },
    target: async (file, _quiet, markdown, project)=>{
        assert2(markdown);
        let nb;
        if (isJupyterNotebook(file)) {
            const nbJSON = Deno.readTextFileSync(file);
            nb = JSON.parse(nbJSON);
        }
        const isPercentScript = isJupyterPercentScript(file);
        const metadata = readYamlFromMarkdown(markdown.value);
        if (isQmdFile(file) || isPercentScript) {
            const [fileDir, fileStem] = dirAndStem(file);
            const notebook = join2(fileDir, fileStem + ".quarto_ipynb");
            const target = {
                source: file,
                input: notebook,
                markdown: markdown,
                metadata,
                data: {
                    transient: true,
                    kernelspec: {}
                }
            };
            nb = await createNotebookforTarget(target, project);
            target.data.kernelspec = nb.metadata.kernelspec;
            return target;
        } else if (isJupyterNotebook(file)) {
            return {
                source: file,
                input: file,
                markdown: markdown,
                metadata,
                data: {
                    transient: false,
                    kernelspec: nb?.metadata.kernelspec
                }
            };
        } else {
            return undefined;
        }
    },
    partitionedMarkdown: async (file, format)=>{
        if (isJupyterNotebook(file)) {
            return partitionMarkdown(await markdownFromNotebookFile(file, format));
        } else if (isJupyterPercentScript(file)) {
            return partitionMarkdown(markdownFromJupyterPercentScript(file));
        } else {
            return partitionMarkdown(Deno.readTextFileSync(file));
        }
    },
    filterFormat: (source, options, format)=>{
        if (isServerShinyPython(format, kJupyterEngine) && format.render[kKeepHidden] !== true) {
            format = cloneDeep1(format);
            format.render[kKeepHidden] = true;
            format.metadata[kRemoveHidden] = "all";
        }
        if (isJupyterNotebook(source)) {
            let executeEnabled;
            if (options.devServerReload) {
                executeEnabled = false;
            } else if (typeof format.execute[kExecuteIpynb] === "boolean") {
                executeEnabled = format.execute[kExecuteIpynb];
            } else if (typeof format.execute[kExecuteEnabled] == "boolean") {
                executeEnabled = format.execute[kExecuteEnabled];
            } else {
                executeEnabled = false;
            }
            if (executeEnabled !== undefined) {
                return {
                    ...format,
                    execute: {
                        ...format.execute,
                        [kExecuteEnabled]: executeEnabled
                    }
                };
            } else {
                return format;
            }
        } else {
            return format;
        }
    },
    execute: async (options)=>{
        if ((isQmdFile(options.target.source) || isJupyterPercentScript(options.target.source)) && !existsSync(options.target.input)) {
            await createNotebookforTarget(options.target);
        }
        let kernelspec = options.target.data.kernelspec;
        const execute = options.format.execute[kExecuteEnabled] !== false;
        if (execute) {
            if (isJupyterNotebook(options.target.source)) {
                kernelspec = await ensureYamlKernelspec(options.target, kernelspec) || kernelspec;
            }
            const execOptions = {
                ...options,
                target: {
                    ...options.target,
                    input: normalizePath(options.target.input)
                }
            };
            let executeDaemon = options.format.execute[kExecuteDaemon];
            if (executeDaemon === null || executeDaemon === undefined) {
                if (await disableDaemonForNotebook(options.target)) {
                    executeDaemon = false;
                } else {
                    executeDaemon = isInteractiveSession() && !runningInCI();
                }
            }
            const jupyterExecOptions = {
                kernelspec,
                python_cmd: await pythonExec(kernelspec),
                supervisor_pid: options.previewServer ? Deno.pid : undefined,
                ...execOptions
            };
            if (executeDaemon === false || executeDaemon === 0) {
                await executeKernelOneshot(jupyterExecOptions);
            } else {
                await executeKernelKeepalive(jupyterExecOptions);
            }
        }
        const nbContents = await jupyterNotebookFiltered(options.target.input, isJupyterNotebook(options.target.source) ? options.format.execute[kIpynbFilters] : []);
        const nb = jupyterFromJSON(nbContents);
        fixupShinyliveCodeCells(nb);
        const assets = jupyterAssets(options.target.input, options.format.pandoc.to);
        const preserveCellMetadata = options.format.render[kNotebookPreserveCells] === true || isHtmlDashboardOutput(options.format.identifier[kBaseFormat]) && !isQmdFile(options.target.source);
        const result1 = await jupyterToMarkdown(nb, {
            executeOptions: options,
            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),
            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],
            preserveCellMetadata,
            preserveCodeCellYaml: options.format.render[kIpynbProduceSourceNotebook] === true
        });
        let includes;
        let engineDependencies;
        if (options.dependencies) {
            includes = executeResultIncludes(options.tempDir, result1.dependencies);
        } else {
            const dependencies = executeResultEngineDependencies(result1.dependencies);
            if (dependencies) {
                engineDependencies = {
                    [kJupyterEngine]: dependencies
                };
            }
        }
        cleanupNotebook(options.target, options.format);
        const outputs = result1.cellOutputs.map((output)=>output.markdown);
        if (result1.notebookOutputs) {
            if (result1.notebookOutputs.prefix) {
                outputs.unshift(result1.notebookOutputs.prefix);
            }
            if (result1.notebookOutputs.suffix) {
                outputs.push(result1.notebookOutputs.suffix);
            }
        }
        const markdown = outputs.join("");
        return {
            engine: kJupyterEngine,
            markdown: markdown,
            supporting: [
                join2(assets.base_dir, assets.supporting_dir)
            ],
            filters: [],
            pandoc: result1.pandoc,
            includes,
            engineDependencies,
            preserve: result1.htmlPreserve,
            postProcess: result1.htmlPreserve && Object.keys(result1.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
        });
    },
    run: async (options)=>{
        const asSemVer = (version)=>{
            const v = version.split(".");
            if (v.length > 3) {
                return `${v[0]}.${v[1]}.${v[2]}`;
            } else {
                return version;
            }
        };
        const kShinyVersion = ">=0.6";
        let shinyError;
        const caps = await jupyterCapabilities();
        if (!caps?.shiny) {
            shinyError = "The shiny package is required for documents with server: shiny";
        } else if (!satisfies(asSemVer(caps.shiny), asSemVer(kShinyVersion))) {
            shinyError = `The shiny package version must be ${kShinyVersion} for documents with server: shiny`;
        }
        if (shinyError) {
            shinyError += "\n\nInstall the latest version of shiny with pip install --upgrade shiny\n";
            error(shinyError);
            throw new Error();
        }
        const [_dir] = dirAndStem(options.input);
        const appFile = "app.py";
        const cmd = [
            ...await pythonExec(),
            "-m",
            "shiny",
            "run",
            appFile,
            "--host",
            options.host,
            "--port",
            String(options.port)
        ];
        if (options.reload) {
            cmd.push("--reload");
            cmd.push(`--reload-includes`);
            cmd.push(`*.py`);
        }
        const readyPattern = /(http:\/\/(?:localhost|127\.0\.0\.1)\:\d+\/?[^\s]*)/;
        const server = runExternalPreviewServer({
            cmd,
            readyPattern,
            cwd: dirname2(options.input)
        });
        await server.start();
        onCleanup(async ()=>{
            await server.stop();
        });
        if (options.onReady) {
            options.onReady();
        }
        return server.serve();
    },
    postRender: async (file, _context)=>{
        if (isServerShiny(file.format)) {
            const [dir] = dirAndStem(file.input);
            const filesDir = join2(dir, inputFilesDir(file.input));
            const extraResources = file.resourceFiles.filter((resource)=>!resource.startsWith(filesDir)).map((resource)=>relative2(dir, resource));
            const appScriptDir = _context ? projectOutputDir(_context) : dir;
            const appScript = join2(appScriptDir, `app.py`);
            if (existsSync(appScript)) {
                const staticAssets = [
                    inputFilesDir(file.input),
                    ...extraResources
                ];
                const parentDirAssets = staticAssets.filter((asset)=>asset.startsWith(".."));
                if (parentDirAssets.length > 0) {
                    error(`References to files in parent directories found in document with server: shiny ` + `(${basename2(file.input)}): ${JSON.stringify(parentDirAssets)}. All resource files referenced ` + `by Shiny documents must exist in the same directory as the source file.`);
                    throw new Error();
                }
                let appContents = Deno.readTextFileSync(appScript);
                appContents = appContents.replace("##STATIC_ASSETS_PLACEHOLDER##", JSON.stringify(staticAssets));
                Deno.writeTextFileSync(appScript, appContents);
            }
        }
    },
    postprocess: (options)=>{
        postProcessRestorePreservedHtml(options);
        return Promise.resolve();
    },
    canFreeze: true,
    generatesFigures: true,
    ignoreDirs: ()=>{
        return [
            "venv",
            "env"
        ];
    },
    canKeepSource: (target)=>{
        return !isJupyterNotebook(target.source);
    },
    intermediateFiles: (input)=>{
        const files = [];
        const [fileDir, fileStem] = dirAndStem(input);
        if (!isJupyterNotebook(input)) {
            files.push(join2(fileDir, fileStem + ".ipynb"));
        } else if ([
            ...kQmdExtensions,
            ...kJupyterPercentScriptExtensions
        ].some((ext)=>{
            return existsSync(join2(fileDir, fileStem + ext));
        })) {
            files.push(input);
        }
        return files;
    }
};
async function ensureYamlKernelspec(target, kernelspec) {
    const markdown = target.markdown.value;
    const yamlJupyter = readYamlFromMarkdown(markdown)?.jupyter;
    if (yamlJupyter && typeof yamlJupyter !== "boolean") {
        const [yamlKernelspec, _] = await jupyterKernelspecFromMarkdown(markdown);
        if (yamlKernelspec.name !== kernelspec?.name) {
            const nb = jupyterFromJSON(Deno.readTextFileSync(target.source));
            nb.metadata.kernelspec = yamlKernelspec;
            Deno.writeTextFileSync(target.source, JSON.stringify(nb, null, 2));
            return yamlKernelspec;
        }
    }
}
function fixupShinyliveCodeCells(nb) {
    if (nb.metadata.kernelspec.language === "python") {
        nb.cells.forEach((cell)=>{
            if (cell.cell_type === "code" && cell.metadata.tags?.includes("shinylive")) {
                cell.cell_type = "markdown";
                cell.metadata = {};
                cell.source = [
                    "```{shinylive-python}\n",
                    ...cell.source,
                    "\n```"
                ];
                delete cell.execution_count;
                delete cell.outputs;
            }
        });
    }
}
async function createNotebookforTarget(target, project) {
    const nb = await quartoMdToJupyter(target.markdown.value, true, project);
    Deno.writeTextFileSync(target.input, JSON.stringify(nb, null, 2));
    return nb;
}
async function disableDaemonForNotebook(target) {
    const kShellMagics = [
        "cd",
        "cat",
        "cp",
        "env",
        "ls",
        "man",
        "mkdir",
        "more",
        "mv",
        "pwd",
        "rm",
        "rmdir"
    ];
    const nb = await breakQuartoMd(target.markdown);
    for (const cell of nb.cells){
        if (__VIRTUAL_FILE18(cell.cell_type)) {
            const language = cell.cell_type.language;
            if (language === "python") {
                if (cell.source.value.startsWith("!")) {
                    return true;
                }
                return kShellMagics.some((cmd)=>cell.source.value.includes("%" + cmd + " ") || cell.source.value.includes("!" + cmd + " ") || cell.source.value.startsWith(cmd + " "));
            }
        }
    }
    return false;
}
function cleanupNotebook(target, format) {
    const data = target.data;
    if (data.transient) {
        if (!format.execute[kKeepIpynb]) {
            removeIfExists(target.input);
        }
    }
}
function executeResultIncludes(tempDir, widgetDependencies) {
    if (widgetDependencies) {
        const includes = {};
        const includeFiles = includesForJupyterWidgetDependencies([
            widgetDependencies
        ], tempDir);
        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;
    }
}
const kMdExtensions = [
    ".md",
    ".markdown"
];
const markdownEngine = {
    name: kMarkdownEngine,
    defaultExt: ".qmd",
    defaultYaml: ()=>[],
    defaultContent: ()=>[],
    validExtensions: ()=>kQmdExtensions.concat(kMdExtensions),
    claimsFile: (_file, ext)=>{
        return kMdExtensions.includes(ext.toLowerCase());
    },
    claimsLanguage: (_language)=>{
        return false;
    },
    markdownForFile (file) {
        return Promise.resolve(mappedStringFromFile(file));
    },
    target: (file, _quiet, markdown)=>{
        if (markdown === undefined) {
            markdown = mappedStringFromFile(file);
        }
        const target = {
            source: file,
            input: file,
            markdown,
            metadata: readYamlFromMarkdown(markdown.value)
        };
        return Promise.resolve(target);
    },
    partitionedMarkdown: (file)=>{
        return Promise.resolve(partitionMarkdown(Deno.readTextFileSync(file)));
    },
    execute: (options)=>{
        const markdown = options.target.markdown.value;
        if (extname2(options.target.input).toLowerCase() === ".md") {
            const languages = languagesInMarkdown(markdown);
            if (languages.size > 0) {
                throw new Error("You must use the .qmd extension for documents with executable code.");
            }
        }
        return Promise.resolve({
            engine: kMarkdownEngine,
            markdown,
            supporting: [],
            filters: []
        });
    },
    dependencies: (_options)=>{
        return Promise.resolve({
            includes: {}
        });
    },
    postprocess: (_options)=>Promise.resolve(),
    canFreeze: false,
    generatesFigures: false
};
const kPandocExtensions = [
    "+abbreviations",
    "-abbreviations",
    "+alerts",
    "-alerts",
    "+all_symbols_escapable",
    "-all_symbols_escapable",
    "+amuse",
    "-amuse",
    "+angle_brackets_escapable",
    "-angle_brackets_escapable",
    "+ascii_identifiers",
    "-ascii_identifiers",
    "+attributes",
    "-attributes",
    "+auto_identifiers",
    "-auto_identifiers",
    "+autolink_bare_uris",
    "-autolink_bare_uris",
    "+backtick_code_blocks",
    "-backtick_code_blocks",
    "+blank_before_blockquote",
    "-blank_before_blockquote",
    "+blank_before_header",
    "-blank_before_header",
    "+bracketed_spans",
    "-bracketed_spans",
    "+citations",
    "-citations",
    "+compact_definition_lists",
    "-compact_definition_lists",
    "+definition_lists",
    "-definition_lists",
    "+east_asian_line_breaks",
    "-east_asian_line_breaks",
    "+element_citations",
    "-element_citations",
    "+emoji",
    "-emoji",
    "+empty_paragraphs",
    "-empty_paragraphs",
    "+epub_html_exts",
    "-epub_html_exts",
    "+escaped_line_breaks",
    "-escaped_line_breaks",
    "+example_lists",
    "-example_lists",
    "+fancy_lists",
    "-fancy_lists",
    "+fenced_code_attributes",
    "-fenced_code_attributes",
    "+fenced_code_blocks",
    "-fenced_code_blocks",
    "+fenced_divs",
    "-fenced_divs",
    "+footnotes",
    "-footnotes",
    "+four_space_rule",
    "-four_space_rule",
    "+gfm_auto_identifiers",
    "-gfm_auto_identifiers",
    "+grid_tables",
    "-grid_tables",
    "+gutenberg",
    "-gutenberg",
    "+hard_line_breaks",
    "-hard_line_breaks",
    "+header_attributes",
    "-header_attributes",
    "+ignore_line_breaks",
    "-ignore_line_breaks",
    "+implicit_figures",
    "-implicit_figures",
    "+implicit_header_references",
    "-implicit_header_references",
    "+inline_code_attributes",
    "-inline_code_attributes",
    "+inline_notes",
    "-inline_notes",
    "+intraword_underscores",
    "-intraword_underscores",
    "+latex_macros",
    "-latex_macros",
    "+line_blocks",
    "-line_blocks",
    "+link_attributes",
    "-link_attributes",
    "+lists_without_preceding_blankline",
    "-lists_without_preceding_blankline",
    "+literate_haskell",
    "-literate_haskell",
    "+mark",
    "-mark",
    "+markdown_attribute",
    "-markdown_attribute",
    "+markdown_in_html_blocks",
    "-markdown_in_html_blocks",
    "+mmd_header_identifiers",
    "-mmd_header_identifiers",
    "+mmd_link_attributes",
    "-mmd_link_attributes",
    "+mmd_title_block",
    "-mmd_title_block",
    "+multiline_tables",
    "-multiline_tables",
    "+native_divs",
    "-native_divs",
    "+native_numbering",
    "-native_numbering",
    "+native_spans",
    "-native_spans",
    "+ntb",
    "-ntb",
    "+old_dashes",
    "-old_dashes",
    "+pandoc_title_block",
    "-pandoc_title_block",
    "+pipe_tables",
    "-pipe_tables",
    "+raw_attribute",
    "-raw_attribute",
    "+raw_html",
    "-raw_html",
    "+raw_markdown",
    "-raw_markdown",
    "+raw_tex",
    "-raw_tex",
    "+rebase_relative_paths",
    "-rebase_relative_paths",
    "+short_subsuperscripts",
    "-short_subsuperscripts",
    "+shortcut_reference_links",
    "-shortcut_reference_links",
    "+simple_tables",
    "-simple_tables",
    "+smart",
    "-smart",
    "+sourcepos",
    "-sourcepos",
    "+space_in_atx_header",
    "-space_in_atx_header",
    "+spaced_reference_links",
    "-spaced_reference_links",
    "+startnum",
    "-startnum",
    "+strikeout",
    "-strikeout",
    "+styles",
    "-styles",
    "+subscript",
    "-subscript",
    "+superscript",
    "-superscript",
    "+table_captions",
    "-table_captions",
    "+tagging",
    "-tagging",
    "+task_lists",
    "-task_lists",
    "+tex_math_dollars",
    "-tex_math_dollars",
    "+tex_math_double_backslash",
    "-tex_math_double_backslash",
    "+tex_math_gfm",
    "-tex_math_gfm",
    "+tex_math_single_backslash",
    "-tex_math_single_backslash",
    "+wikilinks_title_after_pipe",
    "-wikilinks_title_after_pipe",
    "+wikilinks_title_before_pipe",
    "-wikilinks_title_before_pipe",
    "+xrefs_name",
    "-xrefs_name",
    "+xrefs_number",
    "-xrefs_number",
    "+yaml_metadata_block",
    "-yaml_metadata_block"
];
const kYamlMetadataBlock = "yaml_metadata_block";
async function pandocListFormats() {
    const result1 = await execProcess({
        cmd: [
            pandocBinaryPath(),
            "--list-output-formats"
        ],
        stdout: "piped"
    });
    if (result1.success) {
        return lines(result1.stdout).filter((line)=>line.length > 0);
    } else {
        return Promise.reject();
    }
}
function pandocFormat(format, extensions, disabled) {
    let newFormat = pandocFormatWith(format, "", extensions.map((ext)=>`+${ext}`).join("") + disabled.map((ext)=>`-${ext}`).join(""));
    extensions.forEach((ext)=>{
        newFormat = newFormat.replace("-" + ext, "");
    });
    return newFormat;
}
function pandocFormatWith(format, prepend, append) {
    const split = splitPandocFormatString(format);
    return `${split.format}${prepend}${split.options}${append}`;
}
function splitPandocFormatString(format) {
    let optionsPos = format.indexOf("-");
    if (optionsPos === -1) {
        optionsPos = format.indexOf("+");
    }
    const base = optionsPos === -1 ? format : format.substr(0, optionsPos);
    const options = optionsPos === -1 ? "" : format.substr(optionsPos);
    return {
        format: base,
        options
    };
}
const isValidFormat = (formatDesc, pandoc)=>{
    if (isBuiltInFormat(formatDesc.baseFormat)) {
        return true;
    } else if (pandoc.writer) {
        return true;
    } else {
        return false;
    }
};
const parseFormatString = (formatStr)=>{
    const formatDesc = breakFormatString(formatStr);
    if (formatDesc) {
        return formatDesc;
    } else {
        if (formatStr === "hugo") {
            formatStr = "hugo-md";
        }
        const splitFormat = formatStr.split(/-/);
        const lastEl = splitFormat.pop();
        if (lastEl) {
            const lastElFormatDesc = breakFormatString(lastEl, false);
            if (lastElFormatDesc) {
                lastElFormatDesc.extension = splitFormat.join("-");
                return lastElFormatDesc;
            } else {
                throw new Error("Invalid format string");
            }
        } else {
            throw new Error("Invalid format string");
        }
    }
};
class FormatAliases {
    static pandoc;
    static custom;
}
function ensureFormats() {
    if (!FormatAliases.pandoc) {
        const formatAliases = readYaml(resourcePath("schema/format-aliases.yml"));
        const pandocFormats = formatAliases["aliases"]["pandoc-all"];
        FormatAliases.pandoc = pandocFormats;
    }
    if (!FormatAliases.custom) {
        FormatAliases.custom = [
            "dashboard",
            "email"
        ];
    }
}
function pandocBuiltInFormats() {
    ensureFormats();
    return FormatAliases.pandoc;
}
function isBuiltInFormat(format) {
    ensureFormats();
    return FormatAliases.pandoc.includes(format) || FormatAliases.custom.includes(format) || extname2(format) === ".lua";
}
function breakFormatString(formatStr, strict = true) {
    const firstEl = formatStr.split(/[+-]/)[0];
    if (isBuiltInFormat(firstEl)) {
        const variantMatches = formatStr.matchAll(/[\+\-]\S*?(?=\-|\+|$)/g);
        const variantCommands = [];
        for (const match of variantMatches){
            variantCommands.push(match[0]);
        }
        const variants = [];
        const modifiers = [];
        variantCommands.forEach((cmd)=>{
            if (kPandocExtensions.includes(cmd)) {
                variants.push(cmd);
            } else {
                modifiers.push(cmd);
            }
        });
        return {
            baseFormat: firstEl,
            variants,
            modifiers,
            formatWithVariants: `${firstEl}${variants.join("")}`
        };
    } else {
        if (strict) {
            return undefined;
        } else {
            return {
                baseFormat: formatStr,
                variants: [],
                modifiers: [],
                formatWithVariants: formatStr
            };
        }
    }
}
const kQuartoScratch = ".quarto";
function projectScratchPath(dir, path = "") {
    const scratchDir = join2(dir, kQuartoScratch);
    ensureDirSync(scratchDir);
    if (path) {
        path = join2(scratchDir, path);
        ensureDirSync(dirname2(path));
        return path;
    } else {
        return normalizePath(scratchDir);
    }
}
const kQuartoIgnore = [
    `/${kQuartoScratch}/`
];
async function ensureGitignore(dir, forceEnv = false) {
    const gitignorePath = join2(dir, ".gitignore");
    if (existsSync(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);
            }
        }
        const kLocalEntry = `/_*.local`;
        if (!gitignore.includes(kLocalEntry)) {
            for (const walk of walkSync(dir, {
                maxDepth: 1
            })){
                if (walk.name.match(/^_.*?\.local$/)) {
                    requiredEntries.push(kLocalEntry);
                    break;
                }
            }
        }
        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 result1 = await execProcess({
            cmd: [
                "git",
                "rev-parse"
            ],
            cwd: dir,
            stdout: "piped",
            stderr: "piped"
        });
        if (result1.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(join2(dir, kEnv))) {
        return [
            "/" + kEnv
        ].concat(kQuartoIgnore);
    } else {
        return kQuartoIgnore;
    }
}
function writeGitignore(dir, lines) {
    const lineEnding = Deno.build.os === "windows" ? "\r\n" : "\n";
    Deno.writeTextFileSync(join2(dir, ".gitignore"), lines.join(lineEnding) + lineEnding);
}
const juliaEngine = {
    name: kJuliaEngine,
    defaultExt: ".qmd",
    defaultYaml: ()=>[],
    defaultContent: ()=>[
            "```{julia}",
            "1 + 1",
            "```"
        ],
    validExtensions: ()=>[],
    claimsFile: (file, ext)=>false,
    claimsLanguage: (language)=>{
        return false;
    },
    partitionedMarkdown: async (file)=>{
        return partitionMarkdown(Deno.readTextFileSync(file));
    },
    executeTargetSkipped: ()=>false,
    dependencies: (_options)=>{
        const includes = {};
        return Promise.resolve({
            includes
        });
    },
    postprocess: (_options)=>{
        return Promise.resolve();
    },
    canFreeze: true,
    generatesFigures: true,
    ignoreDirs: ()=>{
        return [];
    },
    canKeepSource: (_target)=>{
        return true;
    },
    markdownForFile (file) {
        return Promise.resolve(mappedStringFromFile(file));
    },
    execute: async (options)=>{
        options.target.source;
        let executeDaemon = options.format.execute[kExecuteDaemon];
        if (executeDaemon === null || executeDaemon === undefined) {
            executeDaemon = isInteractiveSession() && !runningInCI();
        }
        const execOptions = {
            ...options,
            target: {
                ...options.target,
                input: normalizePath(options.target.input)
            }
        };
        const juliaExecOptions = {
            julia_cmd: Deno.env.get("QUARTO_JULIA") ?? "julia",
            oneShot: !executeDaemon,
            supervisor_pid: options.previewServer ? Deno.pid : undefined,
            ...execOptions
        };
        const nb = await executeJulia(juliaExecOptions);
        if (!nb) {
            error("Execution of notebook returned undefined");
            return Promise.reject();
        }
        nb.metadata.kernelspec = {
            display_name: "Julia",
            name: "julia",
            language: "julia"
        };
        const assets = jupyterAssets(options.target.input, options.format.pandoc.to);
        const result1 = await jupyterToMarkdown(nb, {
            executeOptions: options,
            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),
            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],
            preserveCodeCellYaml: options.format.render[kIpynbProduceSourceNotebook] === true
        });
        let includes;
        let engineDependencies;
        if (options.dependencies) {
            includes = executeResultIncludes(options.tempDir, result1.dependencies);
        } else {
            const dependencies = executeResultEngineDependencies(result1.dependencies);
            if (dependencies) {
                engineDependencies = {
                    [kJuliaEngine]: dependencies
                };
            }
        }
        const outputs = result1.cellOutputs.map((output)=>output.markdown);
        if (result1.notebookOutputs) {
            if (result1.notebookOutputs.prefix) {
                outputs.unshift(result1.notebookOutputs.prefix);
            }
            if (result1.notebookOutputs.suffix) {
                outputs.push(result1.notebookOutputs.suffix);
            }
        }
        const markdown = outputs.join("");
        return {
            engine: kJuliaEngine,
            markdown: markdown,
            supporting: [
                join2(assets.base_dir, assets.supporting_dir)
            ],
            filters: [],
            pandoc: result1.pandoc,
            includes,
            engineDependencies,
            preserve: result1.htmlPreserve,
            postProcess: result1.htmlPreserve && Object.keys(result1.htmlPreserve).length > 0
        };
    },
    target: async (file, _quiet, markdown, _project)=>{
        if (markdown === undefined) {
            markdown = mappedStringFromFile(file);
        }
        const target = {
            source: file,
            input: file,
            markdown,
            metadata: readYamlFromMarkdown(markdown.value)
        };
        return Promise.resolve(target);
    }
};
async function startOrReuseJuliaServer(options) {
    const transportFile = juliaTransportFile();
    if (!existsSync(transportFile)) {
        trace1(options, `Transport file ${transportFile} doesn't exist`);
        info("Starting julia control server process. This might take a while...");
        let juliaProject = Deno.env.get("QUARTO_JULIA_PROJECT");
        if (juliaProject === undefined) {
            await ensureQuartoNotebookRunnerEnvironment(options);
            juliaProject = juliaRuntimeDir();
        } else {
            trace1(options, `Custom julia project set via QUARTO_JULIA_PROJECT="${juliaProject}". Checking if QuartoNotebookRunner can be loaded.`);
            const qnrTestCommand = new Deno.Command(options.julia_cmd, {
                args: [
                    "--startup-file=no",
                    `--project=${juliaProject}`,
                    "-e",
                    "using QuartoNotebookRunner"
                ],
                env: {
                    "JULIA_LOAD_PATH": Deno.build.os === "windows" ? "@;@stdlib" : "@:@stdlib"
                }
            });
            const qnrTestProc = qnrTestCommand.spawn();
            const result1 = await qnrTestProc.output();
            if (!result1.success) {
                throw Error(`Executing \`using QuartoNotebookRunner\` failed with QUARTO_JULIA_PROJECT="${juliaProject}". Ensure that this project exists, has QuartoNotebookRunner installed and is instantiated correctly.`);
            }
            trace1(options, `QuartoNotebookRunner could be loaded successfully.`);
        }
        if (Deno.build.os === "windows") {
            const command = new Deno.Command("PowerShell", {
                args: [
                    "-Command",
                    "Start-Process",
                    options.julia_cmd,
                    "-ArgumentList",
                    "--startup-file=no",
                    ",",
                    `--project=${juliaProject}`,
                    ",",
                    resourcePath("julia/quartonotebookrunner.jl"),
                    ",",
                    transportFile,
                    "-WindowStyle",
                    "Hidden"
                ],
                env: {
                    "JULIA_LOAD_PATH": "@;@stdlib"
                }
            });
            trace1(options, "Starting detached julia server through powershell, once transport file exists, server should be running.");
            const result1 = command.outputSync();
            if (!result1.success) {
                throw new Error(new TextDecoder().decode(result1.stderr));
            }
        } else {
            const command = new Deno.Command(options.julia_cmd, {
                args: [
                    "--startup-file=no",
                    resourcePath("julia/start_quartonotebookrunner_detached.jl"),
                    options.julia_cmd,
                    juliaProject,
                    resourcePath("julia/quartonotebookrunner.jl"),
                    transportFile
                ],
                env: {
                    "JULIA_LOAD_PATH": "@:@stdlib"
                }
            });
            trace1(options, "Starting detached julia server through julia, once transport file exists, server should be running.");
            const result1 = command.outputSync();
            if (!result1.success) {
                throw new Error(new TextDecoder().decode(result1.stderr));
            }
        }
    } else {
        trace1(options, `Transport file ${transportFile} exists, reusing server.`);
        return {
            reused: true
        };
    }
    return {
        reused: false
    };
}
async function ensureQuartoNotebookRunnerEnvironment(options) {
    const projectTomlTemplate = juliaResourcePath("Project.toml");
    const projectToml = join2(juliaRuntimeDir(), "Project.toml");
    Deno.copyFileSync(projectTomlTemplate, projectToml);
    const command = new Deno.Command(options.julia_cmd, {
        args: [
            "--startup-file=no",
            `--project=${juliaRuntimeDir()}`,
            juliaResourcePath("ensure_environment.jl")
        ]
    });
    const proc = command.spawn();
    const { success } = await proc.output();
    if (!success) {
        throw new Error("Ensuring an updated julia server environment failed");
    }
    return Promise.resolve();
}
function juliaResourcePath(...parts) {
    return join2(resourcePath("julia"), ...parts);
}
async function pollTransportFile(options) {
    const transportFile = juliaTransportFile();
    for(let i1 = 0; i1 < 20; i1++){
        if (existsSync(transportFile)) {
            const content = Deno.readTextFileSync(transportFile);
            trace1(options, "Transport file read successfully.");
            return JSON.parse(content);
        }
        trace1(options, "Transport file did not exist, yet.");
        await sleep(i1 * 100);
    }
    return Promise.reject();
}
async function getJuliaServerConnection(options) {
    const { reused } = await startOrReuseJuliaServer(options);
    const transportOptions = await pollTransportFile(options);
    if (!reused) {
        info("Julia server process started.");
    }
    trace1(options, `Connecting to server at port ${transportOptions.port}, pid ${transportOptions.pid}`);
    try {
        const conn = await Deno.connect({
            port: transportOptions.port
        });
        const isready = writeJuliaCommand(conn, "isready", transportOptions.key, options);
        const timeout = new Promise((accept, _)=>setTimeout(()=>{
                accept(`Timed out after getting no response for ${10000} milliseconds.`);
            }, 10000));
        const result1 = await Promise.race([
            isready,
            timeout
        ]);
        if (typeof result1 === "string") {
            throw new Error(result1);
        } else if (result1 !== true) {
            error(`Expected isready command to return true, returned ${isready} instead. Closing connection.`);
            conn.close();
            return Promise.reject();
        }
        return conn;
    } catch (e) {
        if (reused) {
            trace1(options, "Connecting to server failed, a transport file was reused so it might be stale. Delete transport file and retry.");
            Deno.removeSync(juliaTransportFile());
            return await getJuliaServerConnection(options);
        } else {
            error("Connecting to server failed. A transport file was successfully created by the server process, so something in the server process might be broken.");
            throw e;
        }
    }
}
function firstSignificantLine(str, n) {
    const lines = str.split("\n");
    for (const line of lines){
        const trimmedLine = line.trim();
        if (!trimmedLine.startsWith("#|") && trimmedLine !== "") {
            if (trimmedLine.length <= n) {
                return trimmedLine;
            } else {
                return trimmedLine.substring(0, n - 1) + "…";
            }
        }
    }
    return "";
}
function getConsoleColumns() {
    try {
        return Deno.consoleSize().columns ?? null;
    } catch (_error) {
        return null;
    }
}
async function executeJulia(options) {
    const conn = await getJuliaServerConnection(options);
    const transportOptions = await pollTransportFile(options);
    if (options.oneShot || options.format.execute[kExecuteDaemonRestart]) {
        const isopen = await writeJuliaCommand(conn, "isopen", transportOptions.key, options);
        if (isopen) {
            await writeJuliaCommand(conn, "close", transportOptions.key, options);
        }
    }
    const response = await writeJuliaCommand(conn, "run", transportOptions.key, options, (update)=>{
        const n = update.nChunks.toString();
        const i1 = update.chunkIndex.toString();
        const i_padded = `${" ".repeat(n.length - i1.length)}${i1}`;
        const ncols = getConsoleColumns() ?? 80;
        const firstPart = `Running [${i_padded}/${n}] at line ${update.line}:  `;
        const firstPartLength = firstPart.length;
        const sigLine = firstSignificantLine(update.source, Math.max(0, ncols - firstPartLength));
        info(`${firstPart}${sigLine}`);
    });
    if (options.oneShot) {
        await writeJuliaCommand(conn, "close", transportOptions.key, options);
    }
    if (response.error !== undefined) {
        throw new Error("Running notebook failed:\n" + response.juliaError);
    }
    return response.notebook;
}
async function writeJuliaCommand(conn, command, secret, options, onProgressUpdate) {
    const content = command === "run" ? {
        file: options.target.input,
        options
    } : command === "stop" || command === "isready" ? {} : options.target.input;
    const commandData = {
        type: command,
        content
    };
    const payload = JSON.stringify(commandData);
    const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
        name: "HMAC",
        hash: "SHA-256"
    }, true, [
        "sign"
    ]);
    const canonicalRequestBytes = new TextEncoder().encode(JSON.stringify(commandData));
    const signatureArrayBuffer = await crypto.subtle.sign("HMAC", key, canonicalRequestBytes);
    const signatureBytes = new Uint8Array(signatureArrayBuffer);
    const hmac = encodeBase64(signatureBytes);
    const message = JSON.stringify({
        hmac,
        payload
    }) + "\n";
    const messageBytes = new TextEncoder().encode(message);
    trace1(options, `write command "${command}" to socket server`);
    const bytesWritten = await conn.write(messageBytes);
    if (bytesWritten !== messageBytes.length) {
        throw new Error("Internal Error");
    }
    let restOfPreviousResponse = new Uint8Array(512);
    let restLength = 0;
    while(true){
        const respArray = [];
        let respLength = 0;
        let response = "";
        const newlineAt = restOfPreviousResponse.indexOf(10);
        if (newlineAt !== -1 && newlineAt < restLength) {
            response = new TextDecoder().decode(restOfPreviousResponse.slice(0, newlineAt));
            restOfPreviousResponse.set(restOfPreviousResponse.slice(newlineAt + 1, restLength));
            restLength -= newlineAt + 1;
        } else {
            respArray.push(restOfPreviousResponse.slice(0, restLength));
            respLength += restLength;
            while(true){
                const buffer = new Uint8Array(512);
                const bytesRead = await conn.read(buffer);
                if (bytesRead === null) {
                    break;
                }
                if (bytesRead > 0) {
                    const bufferNewlineAt = buffer.indexOf(10);
                    if (bufferNewlineAt === -1 || bufferNewlineAt >= bytesRead) {
                        respArray.push(buffer.slice(0, bytesRead));
                        restLength = 0;
                        respLength += bytesRead;
                    } else {
                        respArray.push(buffer.slice(0, bufferNewlineAt));
                        respLength += bufferNewlineAt;
                        restOfPreviousResponse.set(buffer.slice(bufferNewlineAt + 1, bytesRead));
                        restLength = bytesRead - bufferNewlineAt - 1;
                        let respBuffer = new Uint8Array(respLength);
                        let offset = 0;
                        respArray.forEach((item)=>{
                            respBuffer.set(item, offset);
                            offset += item.length;
                        });
                        response = new TextDecoder().decode(respBuffer);
                        break;
                    }
                }
            }
        }
        trace1(options, "received server response");
        const json = response.split("\n")[0];
        const data = JSON.parse(json);
        if (data.type === "progress_update") {
            trace1(options, "received progress update response, listening for further responses");
            if (onProgressUpdate !== undefined) {
                onProgressUpdate(data);
            }
            continue;
        }
        const err = data.error;
        if (err !== undefined) {
            const juliaError = data.juliaError ?? "No julia error message available.";
            error(`Julia server returned error after receiving "${command}" command:\n` + err);
            error(juliaError);
            throw new Error("Internal julia server error");
        }
        return data;
    }
}
function juliaRuntimeDir() {
    try {
        return quartoRuntimeDir("julia");
    } catch (e) {
        error("Could not create julia runtime directory.");
        error("This is possibly a permission issue in the environment Quarto is running in.");
        error("Please consult the following documentation for more information:");
        error("https://github.com/quarto-dev/quarto-cli/issues/4594#issuecomment-1619177667");
        throw e;
    }
}
function juliaTransportFile() {
    return join2(juliaRuntimeDir(), "julia_transport.txt");
}
function trace1(options, msg) {
    if (options.format.execute[kExecuteDebug]) {
        info("- " + msg, {
            bold: true
        });
    }
}
const kEngines = new Map();
function executionEngines() {
    return [
        ...kEngines.values()
    ];
}
function executionEngine(name) {
    return kEngines.get(name);
}
for (const engine of [
    knitrEngine,
    jupyterEngine,
    markdownEngine,
    juliaEngine
]){
    registerExecutionEngine(engine);
}
function registerExecutionEngine(engine) {
    if (kEngines.has(engine.name)) {
        throw new Error(`Execution engine ${engine.name} already registered`);
    }
    kEngines.set(engine.name, engine);
}
function executionEngineKeepMd(context) {
    const { input } = context.target;
    const baseFormat = context.format.identifier[kBaseFormat] || "html";
    const keepSuffix = `.${baseFormat}.md`;
    if (!input.endsWith(keepSuffix)) {
        const [dir, stem] = dirAndStem(input);
        return join2(dir, stem + keepSuffix);
    }
}
function executionEngineIntermediateFiles(engine, input) {
    const files = [];
    const [dir, stem] = dirAndStem(input);
    files.push(...pandocBuiltInFormats().flatMap((format)=>[
            `-${format}.md`,
            `.${format}.md`
        ]).map((suffix)=>join2(dir, stem + suffix)));
    const engineKeepFiles = engine.intermediateFiles ? engine.intermediateFiles(input) : undefined;
    if (engineKeepFiles) {
        return files.concat(engineKeepFiles);
    } else {
        return files;
    }
}
function engineValidExtensions() {
    return __VIRTUAL_FILE181(executionEngines().flatMap((engine)=>engine.validExtensions()));
}
function markdownExecutionEngine(markdown, flags) {
    const result1 = partitionYamlFrontMatter(markdown);
    if (result1) {
        let yaml = readYamlFromMarkdown(result1.yaml);
        if (yaml) {
            yaml = mergeConfigs(yaml, flags?.metadata);
            for (const [_, engine] of kEngines){
                if (yaml[engine.name]) {
                    return engine;
                }
                const format = metadataAsFormat(yaml);
                if (format.execute?.[kEngine] === engine.name) {
                    return engine;
                }
            }
        }
    }
    const languages1 = languagesInMarkdown(markdown);
    for (const language of languages1){
        for (const [_, engine] of kEngines){
            if (engine.claimsLanguage(language)) {
                return engine;
            }
        }
    }
    const handlerLanguagesVal = languages();
    for (const language of languages1){
        if (language !== "ojs" && !handlerLanguagesVal.includes(language)) {
            return jupyterEngine;
        }
    }
    return markdownEngine;
}
async function fileExecutionEngine(file, flags, project) {
    const ext = extname2(file).toLowerCase();
    if (!executionEngines().some((engine)=>engine.validExtensions().includes(ext))) {
        return undefined;
    }
    for (const [_, engine] of kEngines){
        if (engine.claimsFile(file, ext)) {
            return engine;
        }
    }
    if (kMdExtensions.includes(ext) || kQmdExtensions.includes(ext)) {
        const markdown = await project.resolveFullMarkdownForFile(undefined, file);
        try {
            return markdownExecutionEngine(markdown ? markdown.value : Deno.readTextFileSync(file), flags);
        } catch (error) {
            if (error.name === "YAMLError") {
                error.message = `${file}:\n${error.message}`;
            }
            throw error;
        }
    } else {
        return undefined;
    }
}
async function fileExecutionEngineAndTarget(file, flags, project) {
    const cached = project.engineAndTargetCache?.get(file);
    if (cached) {
        return cached;
    }
    const engine = await fileExecutionEngine(file, flags, project);
    if (!engine) {
        throw new Error("Can't determine execution engine for " + file);
    }
    const markdown = await project.resolveFullMarkdownForFile(engine, file);
    const target = await engine.target(file, flags?.quiet, markdown, project);
    if (!target) {
        throw new Error("Can't determine execution target for " + file);
    }
    const result1 = {
        engine,
        target
    };
    if (!project.engineAndTargetCache) {
        project.engineAndTargetCache = new Map();
    }
    project.engineAndTargetCache.set(file, result1);
    return result1;
}
function engineIgnoreDirs() {
    const ignoreDirs = [
        "node_modules"
    ];
    executionEngines().forEach((engine)=>{
        if (engine && engine.ignoreDirs) {
            const ignores = engine.ignoreDirs();
            if (ignores) {
                ignoreDirs.push(...ignores);
            }
        }
    });
    return ignoreDirs;
}
function engineIgnoreGlobs() {
    return engineIgnoreDirs().map((ignore)=>`**/${ignore}/**`);
}
function projectIgnoreGlobs(dir) {
    return engineIgnoreGlobs().concat(gitignoreEntries(dir).map((ignore)=>`**/${ignore}**`));
}
const kCrossrefIndexFile = "crossref-index-file";
const kCrossrefInputType = "crossref-input-type";
const kCrossrefResolveRefs = "crossref-resolve-refs";
const kCrossrefIndexDir = "xref";
function crossrefIndexForOutputFile(projectDir, input, output) {
    if (isAbsolute2(input)) {
        input = relative2(projectDir, input);
    }
    input = pathWithForwardSlashes(input);
    const crossrefDir = projectScratchPath(projectDir, kCrossrefIndexDir);
    ensureDirSync(crossrefDir);
    const mainIndexFile = join2(crossrefDir, "INDEX");
    const mainIndex = existsSync(mainIndexFile) ? JSON.parse(Deno.readTextFileSync(mainIndexFile)) : {};
    const outputBaseFile = basename2(output);
    if (mainIndex[input]?.[outputBaseFile] === undefined) {
        if (mainIndex[input] === undefined) {
            mainIndex[input] = {};
        }
        mainIndex[input][outputBaseFile] = shortUuid();
        Deno.writeTextFileSync(mainIndexFile, JSON.stringify(mainIndex, undefined, 2));
    }
    return join2(crossrefDir, mainIndex[input]?.[outputBaseFile]);
}
function deleteCrossrefMetadata(metadata) {
    const crossref = metadata[kCrossref];
    if (crossref) {
        delete crossref[kCrossrefChaptersAppendix];
        delete crossref[kCrossrefChaptersAlpha];
        delete crossref[kCrossrefChapterId];
        if (Object.keys(crossref).length === 0) {
            delete metadata[kCrossref];
        }
    }
}
function copyTo(src, dest, options = {
    overwrite: true
}) {
    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) {
        copySymlinkSync1(src, dest, options);
    } else if (srcStat.isDirectory) {
        copyDirSync1(src, dest, options);
    } else if (srcStat.isFile) {
        copyFileSync1(src, dest, options);
    }
}
function copyMinimal(srcDir, destDir, skip, filter) {
    skip = [
        ...skip || [],
        /\.DS_Store/
    ];
    const srcFiles = [];
    for (const walk of walkSync(srcDir, {
        includeDirs: false,
        followSymlinks: false,
        skip
    })){
        const srcFile = walk.path;
        if (filter && !filter(srcFile)) {
            continue;
        }
        srcFiles.push(srcFile);
    }
    for (const srcFile of srcFiles){
        if (!existsSync(srcFile)) {
            continue;
        }
        const destFile = join2(destDir, relative2(srcDir, srcFile));
        copyFileIfNewer(srcFile, destFile);
    }
}
function copyFileIfNewer(srcFile, destFile) {
    const doCopy = ()=>{
        copyTo(srcFile, destFile, {
            overwrite: true,
            preserveTimestamps: true
        });
    };
    ensureDirSync(dirname2(destFile));
    try {
        if (existsSync(destFile)) {
            const srcInfo = Deno.statSync(srcFile);
            const destInfo = Deno.statSync(destFile);
            if (!srcInfo.mtime || !destInfo.mtime || destInfo.mtime < srcInfo.mtime) {
                doCopy();
            }
        } else {
            doCopy();
        }
    } catch  {
        doCopy();
    }
}
function copyFileSync1(src, dest, options) {
    ensureValidCopySync1(src, dest, options);
    if (existsSync(dest)) {
        Deno.removeSync(dest);
    }
    Deno.copyFileSync(src, dest);
    if (options.preserveTimestamps) {
        const statInfo = Deno.statSync(src);
        if (statInfo.atime && statInfo.mtime) {
            Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
        }
    }
}
function copyDirSync1(src, dest, options) {
    const destStat = ensureValidCopySync1(src, dest, {
        ...options,
        isFolder: true
    });
    if (!destStat) {
        ensureDirSync(dest);
    }
    if (options.preserveTimestamps) {
        const srcStatInfo = Deno.statSync(src);
        if (srcStatInfo.atime && srcStatInfo.mtime) {
            Deno.utimeSync(dest, srcStatInfo.atime, srcStatInfo.mtime);
        }
    }
    for (const entry of Deno.readDirSync(src)){
        const srcPath = join2(src, entry.name);
        const destPath = join2(dest, basename2(srcPath));
        if (entry.isSymlink) {
            copySymlinkSync1(srcPath, destPath, options);
        } else if (entry.isDirectory) {
            copyDirSync1(srcPath, destPath, options);
        } else if (entry.isFile) {
            copyFileSync1(srcPath, destPath, options);
        }
    }
}
function copySymlinkSync1(src, dest, options) {
    ensureValidCopySync1(src, dest, options);
    if (existsSync(dest)) {
        Deno.removeSync(dest);
    }
    const originSrcFilePath = Deno.readLinkSync(src);
    const type = getFileInfoType(Deno.lstatSync(src));
    if (isWindows3()) {
        Deno.symlinkSync(originSrcFilePath, dest, {
            type: type === "dir" ? "dir" : "file"
        });
    } else {
        Deno.symlinkSync(originSrcFilePath, dest);
    }
    if (options.preserveTimestamps) {
        const statInfo = Deno.lstatSync(src);
        if (statInfo.atime && statInfo.mtime) {
            Deno.utimeSync(dest, statInfo.atime, statInfo.mtime);
        }
    }
}
function ensureValidCopySync1(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;
}
const kPatchedTemplateExt = ".patched";
const kTemplatePartials = "template-partials";
function readPartials(metadata, inputDir) {
    if (typeof metadata?.[kTemplatePartials] === "string") {
        metadata[kTemplatePartials] = [
            metadata[kTemplatePartials]
        ];
    }
    const result1 = metadata?.[kTemplatePartials] || [];
    inputDir = inputDir ? normalizePath(inputDir) : undefined;
    const resolvePath = (path)=>{
        if (!inputDir || isAbsolute2(path)) {
            return path;
        } else {
            return join2(inputDir, path);
        }
    };
    return result1.flatMap((path)=>{
        const result1 = [];
        for (const walk of expandGlobSync(resolvePath(path))){
            result1.push(walk.path);
        }
        if (!isGlob1(path) && result1.length === 0) {
            throw new Error(`Template partial ${path} was not found. Please confirm that the path to the file is correct.`);
        }
        return result1;
    });
}
function resolveTemplatePartialPaths(metadata, inputDir, project) {
    if (typeof metadata?.[kTemplatePartials] === "string") {
        metadata[kTemplatePartials] = [
            metadata[kTemplatePartials]
        ];
    }
    const result1 = metadata?.[kTemplatePartials] || [];
    metadata[kTemplatePartials] = result1.map((path)=>{
        if (project && (path.startsWith("/") || path.startsWith("\\"))) {
            return join2(project.dir, path.slice(1));
        } else if (!inputDir || isAbsolute2(path)) {
            return path;
        } else {
            if (isAbsolute2(inputDir)) {
                return join2(inputDir, path);
            } else {
                return join2(Deno.cwd(), inputDir, path);
            }
        }
    });
}
async function stageTemplate(options, extras, userContext) {
    const stagingDir = options.services.temp.createDir();
    const template = "template.patched";
    const stageContext = (dir, template, context)=>{
        if (context) {
            if (context.template) {
                const targetFile = join2(dir, template);
                copyTo(context.template, targetFile);
                if (Deno.build.os !== "windows") {
                    Deno.chmodSync(targetFile, 0o666);
                }
            }
            if (context.partials) {
                for (const partial of context.partials){
                    copyTo(partial, join2(stagingDir, basename2(partial)));
                }
            }
            return true;
        } else {
            return false;
        }
    };
    const formatStaged = stageContext(stagingDir, template, extras.templateContext);
    const userStaged = await stageContext(stagingDir, template, userContext);
    if (formatStaged || userStaged) {
        const stagedTemplatePath = join2(stagingDir, template);
        applyTemplatePatches(stagedTemplatePath, options.format, options.flags);
        return stagedTemplatePath;
    } else {
        return undefined;
    }
}
function cleanTemplatePartialMetadata(metadata, builtIns) {
    const partials = metadata[kTemplatePartials];
    if (partials) {
        const cleansed = partials.filter((part)=>builtIns.includes(part));
        if (cleansed.length === 0) {
            delete metadata[kTemplatePartials];
        } else {
            metadata[kTemplatePartials] = cleansed;
        }
    }
}
function applyTemplatePatches(template, format, flags) {
    const patches = [];
    if (isHtmlDocOutput(format.pandoc) || isRevealjsOutput(format.pandoc)) {
        if ((flags && flags[kSelfContained] || format.pandoc[kSelfContained] || flags && flags[kEmbedResources] || format.pandoc[kEmbedResources]) && !format.render[kSelfContainedMath]) {
            const math = mathConfig(format, flags);
            if (math) {
                const mathTemplate = math.method === "mathjax" ? mathjaxScript(math.url) : math.method == "katex" ? katexScript(math.url) : "";
                if (mathTemplate) {
                    patches.push({
                        searchValue: /\$math\$/,
                        contents: mathTemplate
                    });
                }
            }
        }
    }
    if (patches.length) {
        let templateContents = Deno.readTextFileSync(template);
        patches.forEach((patch)=>{
            templateContents = templateContents.replace(patch.searchValue, patch.contents);
        });
        Deno.writeTextFileSync(template, templateContents);
    }
}
function mathConfig(format, flags) {
    if (flags?.mathjax || flags?.katex || flags?.webtex || flags?.gladtex || flags?.mathml) {
        return undefined;
    }
    const math = format.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>
  `;
}
function bibEngine(defaults, flags) {
    return flags?.natbib ? "natbib" : flags?.biblatex ? "biblatex" : defaults[kCiteMethod] === "natbib" ? "natbib" : defaults[kCiteMethod] == "biblatex" ? "biblatex" : undefined;
}
function pdfEngine(defaults, render, flags) {
    const pdfEngine = 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 = render[kLatexMakeIndex];
    const indexEngineOpts = render[kLatexMakeIndexOpts] || [];
    if (flags?.makeIndexOpts) {
        indexEngineOpts?.push(...flags?.makeIndexOpts);
    }
    const tlmgrOpts = render[kLatexTlmgrOpts] || [];
    if (flags?.tlmgrOpts) {
        tlmgrOpts?.push(...flags?.tlmgrOpts);
    }
    return {
        pdfEngine,
        pdfEngineOpts,
        bibEngine: bibEngine(defaults, flags),
        indexEngine,
        indexEngineOpts,
        tlmgrOpts
    };
}
function isLatexPdfEngine(engine) {
    return [
        "pdflatex",
        "xelatex",
        "lualatex",
        "latexmk"
    ].includes(engine.pdfEngine);
}
function filesDirLibDir(input) {
    return join2(inputFilesDir(input), "libs");
}
function filesDirMediabagDir(input) {
    return join2(inputFilesDir(input), "mediabag");
}
function pandocMetadataPath(path) {
    return pathWithForwardSlashes(path);
}
const kBookChapters = "chapters";
const kBookAppendix = "appendices";
const kBookReferences = "references";
const kBookRender = "render";
const kBookOutputFile = "output-file";
const kBookDownloads = "downloads";
const kBookTools = "tools";
const kBookSearch = "search";
const kBookItemChapter = "chapter";
const kBookItemAppendix = "appendix";
const kBookItemPart = "part";
function texSafeFilename(file) {
    return file.replaceAll(/[ <>()|\:&;#?*'\\\/]/g, "-");
}
const kBook = "book";
const kBookCoverImage = "cover-image";
const kBookCoverImageAlt = "cover-image-alt";
function bookConfig(name, project) {
    const book = project?.[kBook];
    if (book) {
        return book[name];
    } else {
        return undefined;
    }
}
function setBookConfig(name, value, project) {
    const book = project?.[kBook];
    if (book) {
        book[name] = value;
    }
}
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(format) {
    const extension = format.extensions?.book;
    if (extension) {
        return !!extension.multiFile;
    } else {
        return false;
    }
}
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 bookOutputStem(projectDir, config) {
    const outputFile = bookConfig(kBookOutputFile, config) || bookConfig(kTitle, config) || basename2(projectDir);
    return texSafeFilename(config !== undefined ? resolveVariables(outputFile, config) : outputFile);
}
function crossrefFilterActive(options) {
    return options.format.metadata.crossref !== false;
}
function crossrefFilterParams(options, defaults) {
    const flags = options.flags;
    const metadata = options.format.metadata;
    const kCrossrefFilterParams = [
        kListings,
        kNumberSections,
        kNumberOffset
    ];
    const params = {};
    kCrossrefFilterParams.forEach((option)=>{
        let value = crossrefOption(option, flags, defaults);
        if (value) {
            if (option === kNumberOffset) {
                if (typeof value === "number") {
                    value = [
                        value
                    ];
                }
                if (!Array.isArray(value) || value.some((num)=>!Number.isInteger(num))) {
                    throw new Error("Invalid value for number-offset (should be an array of numbers)");
                }
                if (defaults?.[kNumberSections] === undefined) {
                    params[kNumberSections] = true;
                }
            }
            params[option] = value;
        }
    });
    params[kNumberDepth] = metadata?.[kNumberDepth];
    if (!options.project?.isSingleFile) {
        if (!projectIsBook(options.project) || isMultiFileBookFormat(options.format)) {
            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);
        }
    }
    const crossrefInputType = Deno.env.get("QUARTO_CROSSREF_INPUT_TYPE");
    if (crossrefInputType) {
        params[kCrossrefInputType] = crossrefInputType;
    }
    return params;
}
function crossrefOption(name, flags, defaults) {
    if (flags && Object.keys(flags).includes(name)) {
        return flags[name];
    } else if (Object.keys(defaults || {}).includes(name)) {
        return defaults[name];
    } else {
        return undefined;
    }
}
const kMarkdownBlockSeparator = "\n\n<!-- -->\n\n";
const kDefaultHighlightStyle = "arrow";
const kHtmlEmptyPostProcessResult = {
    resources: [],
    supporting: []
};
const kQuartoRenderCommand = "90B3C9E8-0DBC-4BC0-B164-AA2D5C031B28";
const kDarkSuffix1 = "dark";
const kLightSuffix1 = "light";
function textHighlightThemePath1(inputDir, theme, style) {
    let resolvedTheme;
    if (typeof theme === "object") {
        if (style && theme[style]) {
            resolvedTheme = theme[style];
        } else {
            resolvedTheme = theme[Object.keys(theme)[0]];
        }
    } else {
        resolvedTheme = theme;
    }
    const names = [
        `${theme}-${style === "dark" ? kDarkSuffix1 : kLightSuffix1}`,
        theme
    ];
    const themePath = names.map((name)=>{
        return resourcePath(join2("pandoc", "highlight-styles", `${name}.theme`));
    }).find((path)=>existsSync(path));
    if (themePath) {
        return themePath;
    } else {
        const userThemePath = join2(inputDir, resolvedTheme);
        if (existsSync(userThemePath)) {
            return normalizePath(userThemePath);
        }
    }
    return undefined;
}
function readHighlightingTheme(inputDir, pandoc, style) {
    const theme = pandoc[kHighlightStyle] || kDefaultHighlightStyle;
    if (theme) {
        const themeRaw = readTheme(inputDir, theme, style);
        if (themeRaw) {
            return {
                json: JSON.parse(themeRaw),
                isAdaptive: isAdaptiveTheme(theme)
            };
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function hasAdaptiveTheme(pandoc) {
    const theme = pandoc[kHighlightStyle] || kDefaultHighlightStyle;
    return theme && isAdaptiveTheme(theme);
}
function hasTextHighlighting(pandoc) {
    const theme = pandoc[kHighlightStyle];
    return theme !== null;
}
function isAdaptiveTheme(theme) {
    if (typeof theme === "string") {
        return [
            "a11y",
            "arrow",
            "atom-one",
            "ayu",
            "breeze",
            "github",
            "gruvbox",
            "monochrome"
        ].includes(theme);
    } else {
        const keys = Object.keys(theme);
        return keys.includes("dark") && keys.includes("light");
    }
}
function readTheme(inputDir, theme, style) {
    const themeFile = textHighlightThemePath1(inputDir, theme, style === "default" ? undefined : style);
    if (!themeFile) {
        return undefined;
    }
    if (!existsSync(themeFile)) {
        warnOnce(`The text highlighting theme ${themeFile} does not exist.`);
        return undefined;
    }
    if (Deno.statSync(themeFile).isDirectory) {
        throw new Error(`The text highlighting theme ${themeFile} is a directory. Please provide a valid theme name or path to a .theme file.`);
    }
    return Deno.readTextFileSync(themeFile);
}
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": ""
};
const kAdaptiveTextHighlighting = "adaptive-text-highlighting";
const kTextHighlighting = "text-highlighting";
function layoutFilterParams(format, defaults) {
    const params = {};
    const pageWidth = format.render[kPageWidth];
    if (pageWidth) {
        params[kPageWidth] = pageWidth;
    }
    if (defaults) {
        if (hasAdaptiveTheme(defaults)) {
            params[kAdaptiveTextHighlighting] = true;
        }
        if (hasTextHighlighting(defaults)) {
            params[kTextHighlighting] = true;
        }
    }
    return params;
}
function overflowXPostprocessor(doc) {
    const outputs = doc.querySelectorAll(".cell-output-display");
    for(let i1 = 0; i1 < outputs.length; i1++){
        const output = outputs[i1];
        const noOverflowX = !!output.querySelector("select") || !!output.querySelector(".shiny-html-output") || !!output.querySelector(".rglWebGL");
        if (noOverflowX) {
            output.classList.add("no-overflow-x");
        }
    }
    return Promise.resolve(kHtmlEmptyPostProcessResult);
}
function formatHasBootstrap(format) {
    if (format && (isHtmlOutput(format.pandoc, true) || isHtmlDashboardOutput(format.identifier["base-format"]))) {
        return hasBootstrapTheme(format.metadata);
    } else {
        return false;
    }
}
function hasBootstrapTheme(metadata) {
    const theme = metadata[kTheme];
    return theme !== "none" && theme !== "pandoc";
}
function formatDarkMode(format) {
    const isBootstrap = formatHasBootstrap(format);
    if (isBootstrap) {
        return darkModeDefault(format.metadata);
    }
    return undefined;
}
function darkModeDefault(metadata) {
    if (metadata !== undefined) {
        const theme = metadata[kTheme];
        if (theme && typeof theme === "object") {
            const keys = Object.keys(theme);
            if (keys.includes("dark")) {
                if (keys[0] === "dark") {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }
    return undefined;
}
function expandGlobSync1(glob, options) {
    if (options === undefined) {
        return expandGlobSync(glob, {
            globstar: true
        });
    } else {
        return expandGlobSync(glob, {
            ...options,
            globstar: options.globstar ?? true
        });
    }
}
const kBuiltInExtOrg = "quarto";
const kCommon = "common";
const kExtensionDir = "_extensions";
const kTitle1 = "title";
const kAuthor1 = "author";
const kVersion = "version";
const kQuartoRequired1 = "quarto-required";
const kRevealJSPlugins = "revealjs-plugins";
const kBuiltInExtNames = [
    "lightbox"
];
function extensionIdString(extensionId) {
    if (extensionId.organization) {
        return `${extensionId.organization}/${extensionId.name}`;
    } else {
        return extensionId.name;
    }
}
const getProjectConfigFieldsSchema = defineCached(async ()=>{
    return {
        schema: objectSchemaFromFieldsObject(getYamlIntelligenceResource("schema/project.yml")),
        errorHandlers: []
    };
}, "project-config-fields");
const getExtensionConfigFieldsSchema = defineCached(async ()=>{
    return {
        schema: objectSchemaFromFieldsObject(getYamlIntelligenceResource("schema/extension.yml")),
        errorHandlers: []
    };
}, "extension-config-fields");
function disallowTopLevelType(error, parse, _schema) {
    if (!(error.instancePath.length === 1 && error.instancePath[0] === "type")) {
        return error;
    }
    const violatingObject = locateAnnotation(parse, error.instancePath, "key");
    const localizedError = createLocalizedError({
        ...error,
        message: "top-level key 'type' is not allowed in project configuration.",
        violatingObject,
        source: mappedSubstring(parse.source, violatingObject.start, violatingObject.end + 1)
    });
    localizedError.niceError.info["top-level-type-not-allowed"] = "Did you mean to use 'project: type: ...' instead?";
    return localizedError;
}
const getProjectConfigSchema = defineCached(async ()=>{
    const projectConfigFields = await getProjectConfigFieldsSchema();
    const execute = await getFormatExecuteOptionsSchema();
    const format = await getFrontMatterFormatSchema();
    const profile = refSchema("project-profile", "Specify a default profile and profile groups");
    const result1 = allOfSchema(objectSchema({
        properties: {
            execute,
            format,
            profile
        },
        description: "be a Quarto YAML front matter object"
    }), execute, await getFrontMatterSchema(), projectConfigFields);
    return {
        schema: describeSchema(result1, "a project configuration object"),
        errorHandlers: [
            disallowTopLevelType
        ]
    };
}, "project-config");
const getExtensionConfigSchema = defineCached(async ()=>{
    const extensionConfig = await getExtensionConfigFieldsSchema();
    return {
        schema: describeSchema(extensionConfig, "an extension configuration object"),
        errorHandlers: []
    };
}, "extension-config");
function asArray(x) {
    return x ? Array.isArray(x) ? x : [
        x
    ] : [];
}
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 projectResourceFiles = resolvePathGlobs(dir, resourceGlobs, exclude);
        resourceFiles.push(...__VIRTUAL_FILE137(projectResourceFiles.include, projectResourceFiles.exclude));
        resourceFiles.push(...[
            "robots.txt",
            ".nojekyll",
            "CNAME",
            "_redirects",
            kProject404File
        ].map((file)=>join2(dir, file)).filter(existsSync1));
    }
    return __VIRTUAL_FILE181(resourceFiles);
}
function copyResourceFile(rootDir, srcFile, destFile) {
    if (!normalizePath(srcFile).startsWith(normalizePath(rootDir))) {
        return;
    }
    ensureDirSync(dirname2(destFile));
    copyFileIfNewer(srcFile, destFile);
    if (extname2(srcFile).toLowerCase() === ".css") {
        handleCssReferences(rootDir, srcFile, destFile);
    }
}
function fixupCssReferences1(css, offset, onRef) {
    let destCss = css.replaceAll(kCssUrlRegex, (_match, p1, p2)=>{
        const ref = p2.startsWith("/") ? `${offset}${p2.slice(1)}` : p2;
        return `url(${p1 || ""}${onRef(ref)}${p1 || ""})`;
    });
    destCss = destCss.replaceAll(kCssImportRegex, (_match, p1, p2)=>{
        const ref = p2.startsWith("/") ? `${offset}${p2.slice(1)}` : p2;
        return `@import ${p1 || ""}${onRef(ref)}${p1 || ""}`;
    });
    return destCss;
}
function handleCssReferences(rootDir, srcFile, destFile) {
    const css = Deno.readTextFileSync(destFile);
    const offset = relative2(dirname2(srcFile), rootDir);
    const copyRef = (ref)=>{
        const refPath = join2(dirname2(srcFile), ref);
        if (safeExistsSync(refPath)) {
            const refDestPath = join2(dirname2(destFile), ref);
            copyResourceFile(rootDir, refPath, refDestPath);
        }
        return ref;
    };
    const destCss = fixupCssReferences1(css, offset, copyRef);
    if (destCss !== css) {
        Deno.writeTextFileSync(destFile, destCss);
    }
}
const kQuartoExtOrganization = "quarto-ext";
const kQuartoExtBuiltIn = [
    "code-filename",
    "grouped-tabsets"
];
function createExtensionContext() {
    const extensionCache = {};
    const extensions = async (input, config, projectDir, options)=>{
        const extensions = await loadExtensions(extensionCache, input, projectDir);
        const results = Object.values(extensions).filter((ext)=>options?.builtIn !== false || ext.id.organization !== kBuiltInExtOrg);
        return results.map((extension)=>{
            if (input) {
                return resolveExtensionPaths(extension, input, config);
            } else {
                return extension;
            }
        });
    };
    const extension = async (name, input, config, projectDir)=>{
        const unresolved = await loadExtension(name, input, projectDir);
        return resolveExtensionPaths(unresolved, input, config);
    };
    const find = async (name, input, contributes, config, projectDir, options)=>{
        const extId = toExtensionId(name);
        return findExtensions(await extensions(input, config, projectDir, options), extId, contributes);
    };
    return {
        extension,
        extensions,
        find
    };
}
function projectExtensionPathResolver(libDir, projectDir) {
    return (href, projectOffset)=>{
        const projectRelativeHref = relative2(projectOffset, href);
        if (projectRelativeHref.startsWith("_extensions/")) {
            const projectTargetHref = projectRelativeHref.replace(/^_extensions\//, `${libDir}/quarto-contrib/quarto-project/`);
            copyResourceFile(projectDir, join2(projectDir, projectRelativeHref), join2(projectDir, projectTargetHref));
            return join2(projectOffset, projectTargetHref);
        }
        return href;
    };
}
function filterBuiltInExtensions(extensions) {
    const quartoExts = extensions.filter((ext)=>{
        return ext.id.organization === kBuiltInExtOrg;
    });
    const nowBuiltInExtensions = extensions?.filter((ext)=>{
        return ext.id.organization === "quarto-ext" && quartoExts.map((ext)=>ext.id.name).includes(ext.id.name);
    });
    if (nowBuiltInExtensions.length > 0) {
        extensions = filterExtensionAndWarn(extensions, nowBuiltInExtensions);
    }
    return extensions;
}
function filterExtensionAndWarn(extensions, filterOutExtensions) {
    warnToRemoveExtensions(filterOutExtensions);
    return extensions.filter((ext)=>{
        return !filterOutExtensions.map((ext)=>ext.id.name).includes(ext.id.name);
    });
}
function warnToRemoveExtensions(extensions) {
    const removeCommands = extensions.map((ext)=>{
        return `quarto remove extension ${extensionIdString(ext.id)}`;
    });
    warnOnce(`One or more extensions have been built in to Quarto. Please use the following command to remove the unneeded extension:\n  ${removeCommands.join("\n  ")}`);
}
function filterExtensions(extensions, extensionId, type) {
    if (extensions && extensions.length > 0) {
        extensions = filterBuiltInExtensions(extensions);
        const ownedExtensions = extensions.filter((ext)=>{
            return ext.id.organization !== undefined;
        }).map((ext)=>{
            return extensionIdString(ext.id);
        });
        if (ownedExtensions.length > 1) {
            warnOnce(`The ${type} '${extensionId}' matched more than one extension. Please use a full name to disambiguate:\n  ${ownedExtensions.join("\n  ")}`);
        }
        const oldBuiltInExt = extensions?.filter((ext)=>{
            return ext.id.organization === kQuartoExtOrganization && (kQuartoExtBuiltIn.includes(ext.id.name) || kBuiltInExtNames.includes(ext.id.name));
        });
        if (oldBuiltInExt.length > 0) {
            return filterExtensionAndWarn(extensions, oldBuiltInExt);
        } else {
            return extensions;
        }
    } else {
        return extensions;
    }
}
const loadExtensions = async (cache, input, projectDir)=>{
    const extensionPath = inputExtensionDirs(input, projectDir);
    const allExtensions = {};
    for (const extensionDir of extensionPath){
        if (cache[extensionDir]) {
            cache[extensionDir].forEach((ext)=>{
                allExtensions[extensionIdString(ext.id)] = cloneDeep1(ext);
            });
        } else {
            const extensions = await readExtensions(extensionDir);
            extensions.forEach((extension)=>{
                allExtensions[extensionIdString(extension.id)] = cloneDeep1(extension);
            });
            cache[extensionDir] = extensions;
        }
    }
    return allExtensions;
};
const loadExtension = async (extension, input, projectDir)=>{
    const extensionId = toExtensionId(extension);
    const extensionPath = discoverExtensionPath(input, extensionId, projectDir);
    if (extensionPath) {
        const file = extensionFile(extensionPath);
        if (file) {
            const extension = await readExtension(extensionId, file);
            validateExtension(extension);
            return extension;
        } else {
            throw new Error(`The extension '${extension}' is missing the expected '_extension.yml' file.`);
        }
    } else {
        throw new Error(`Unable to read the extension '${extension}'.\nPlease ensure that you provided the correct id and that the extension is installed.`);
    }
};
function findExtensions(extensions, extensionId, contributes) {
    const exts = extensions.filter((ext)=>{
        if (contributes === "shortcodes" && ext.contributes.shortcodes) {
            return true;
        } else if (contributes === "filters" && ext.contributes.filters) {
            return true;
        } else if (contributes === "formats" && ext.contributes.formats) {
            return true;
        } else if (contributes === "project" && ext.contributes.project) {
            return true;
        } else if (contributes === "metadata" && ext.contributes.metadata) {
            return true;
        } else if (contributes === kRevealJSPlugins && ext.contributes[kRevealJSPlugins]) {
            return true;
        } else {
            return contributes === undefined;
        }
    });
    if (extensionId.organization) {
        const exact = exts.filter((ext)=>{
            return ext.id.name === extensionId.name && ext.id.organization === extensionId.organization;
        });
        if (exact.length > 0) {
            return exact;
        }
    }
    const nameMatches = exts.filter((ext)=>{
        return extensionId.name === ext.id.name;
    });
    const sortedMatches = nameMatches.sort((ext1, _ext2)=>{
        return ext1.id.organization === undefined ? -1 : 1;
    });
    return sortedMatches;
}
function extensionProjectType(extension, config) {
    if (extension.contributes.project) {
        const projType = extension.contributes.project?.type || "default";
        return projectType(projType);
    } else {
        return projectType(config?.project?.[kProjectType]);
    }
}
function resolveExtensionPaths(extension, input, config) {
    const inputDir = Deno.statSync(input).isDirectory ? input : dirname2(input);
    return toInputRelativePaths(extensionProjectType(extension, config), extension.path, inputDir, extension, kExtensionIgnoreFields);
}
const kExtensionIgnoreFields = [
    "biblio-style",
    "revealjs-plugins"
];
async function readExtensions(extensionsDirectory, organization) {
    const extensions = [];
    const extensionDirs = safeExistsSync(extensionsDirectory) && Deno.statSync(extensionsDirectory).isDirectory ? Deno.readDirSync(extensionsDirectory) : [];
    for (const extensionDir of extensionDirs){
        if (extensionDir.isDirectory) {
            const extFile = extensionFile(join2(extensionsDirectory, extensionDir.name));
            if (extFile) {
                const extensionId = {
                    name: extensionDir.name,
                    organization
                };
                const extension = await readExtension(extensionId, extFile);
                extensions.push(extension);
            } else if (!organization) {
                const ownedExtensions = await readExtensions(join2(extensionsDirectory, extensionDir.name), extensionDir.name);
                if (ownedExtensions) {
                    extensions.push(...ownedExtensions);
                }
            }
        }
    }
    return extensions;
}
function projectExtensionDirs(project) {
    const extensionDirs = [];
    for (const walk of expandGlobSync1(join2(project.dir, "**/_extensions"), {
        exclude: [
            ...projectIgnoreGlobs(project.dir),
            "**/.*",
            "**/.*/**"
        ]
    })){
        extensionDirs.push(walk.path);
    }
    return extensionDirs;
}
function extensionFilesFromDirs(dirs) {
    const files = [];
    for (const dir of dirs){
        for (const walk of walkSync(dir, {
            includeDirs: false,
            followSymlinks: false,
            skip: [
                kSkipHidden
            ]
        })){
            files.push(walk.path);
        }
    }
    return files;
}
function inputExtensionDirs(input, projectDir) {
    const extensionsDirPath = (path)=>{
        const extPath = join2(path, kExtensionDir);
        try {
            if (Deno.statSync(extPath).isDirectory) {
                return extPath;
            } else {
                return undefined;
            }
        } catch  {
            return undefined;
        }
    };
    const inputDirName = (inputOrDir)=>{
        if (Deno.statSync(inputOrDir).isDirectory) {
            return inputOrDir;
        } else {
            return dirname2(inputOrDir);
        }
    };
    const extensionDirectories = [
        builtinExtensions()
    ];
    if (projectDir && input) {
        let currentDir = normalizePath(inputDirName(input));
        do {
            const extensionPath = extensionsDirPath(currentDir);
            if (extensionPath) {
                extensionDirectories.push(extensionPath);
            }
            currentDir = dirname2(currentDir);
        }while (isSubdir(projectDir, currentDir) || projectDir === currentDir)
        return extensionDirectories;
    } else if (input) {
        const dir = extensionsDirPath(inputDirName(input));
        if (dir) {
            extensionDirectories.push(dir);
        }
    } else if (projectDir) {
        const dir = extensionsDirPath(projectDir);
        if (dir) {
            extensionDirectories.push(dir);
        }
    }
    return extensionDirectories;
}
function discoverExtensionPath(input, extensionId, projectDir) {
    const extensionDirGlobs = [];
    if (extensionId.organization) {
        extensionDirGlobs.push(`${extensionId.organization}/${extensionId.name}/`);
    } else {
        extensionDirGlobs.push(`${extensionId.name}/`);
        extensionDirGlobs.push(`*/${extensionId.name}/`);
    }
    const findExtensionDir = (extDir, globs)=>{
        const paths = resolvePathGlobs(extDir, globs, [], {
            mode: "strict"
        }).include.filter((path)=>{
            return extensionFile(path);
        });
        if (paths.length > 0) {
            if (paths.length > 1) {
                warn(`More than one extension is available for ${extensionId.name} in the directory ${extDir}.\nExtensions that match:\n${paths.join("\n")}`);
            }
            return relative2(Deno.cwd(), paths[0]);
        } else {
            return undefined;
        }
    };
    const builtinExtensionDir = findExtensionDir(builtinExtensions(), extensionDirGlobs);
    if (builtinExtensionDir) {
        return builtinExtensionDir;
    }
    const sourceDir = Deno.statSync(input).isDirectory ? input : dirname2(input);
    const sourceDirAbs = normalizePath(sourceDir);
    if (projectDir && isSubdir(projectDir, sourceDirAbs)) {
        let extensionDir;
        let currentDir = normalize2(sourceDirAbs);
        const projDir = normalize2(projectDir);
        while(!extensionDir){
            extensionDir = findExtensionDir(join2(currentDir, kExtensionDir), extensionDirGlobs);
            if (currentDir == projDir) {
                break;
            }
            currentDir = dirname2(currentDir);
        }
        return extensionDir;
    } else {
        return findExtensionDir(join2(sourceDirAbs, kExtensionDir), extensionDirGlobs);
    }
}
function builtinExtensions() {
    return resourcePath("extensions");
}
function validateExtension(extension) {
    let contribCount = 0;
    const contribs = [
        extension.contributes.filters,
        extension.contributes.shortcodes,
        extension.contributes.formats,
        extension.contributes.project,
        extension.contributes[kRevealJSPlugins],
        extension.contributes.metadata
    ];
    contribs.forEach((contrib)=>{
        if (contrib) {
            if (Array.isArray(contrib)) {
                contribCount = contribCount + contrib.length;
            } else if (typeof contrib === "object") {
                contribCount = contribCount + Object.keys(contrib).length;
            }
        }
    });
    if (contribCount === 0) {
        throw new Error(`The extension ${extension.title || extension.id.name} is not valid- it does not contribute anything.`);
    }
    if (extension.quartoVersion && !satisfies(quartoConfig.version(), extension.quartoVersion)) {
        throw new Error(`The extension ${extension.title || extension.id.name} is incompatible with this quarto version.

Extension requires: ${extension.quartoVersion.raw}
Quarto version: ${quartoConfig.version()}`);
    }
}
async function readExtension(extensionId, extensionFile) {
    const extensionSchema = await getExtensionConfigSchema();
    const yaml = await readAndValidateYamlFromFile(extensionFile, extensionSchema, "YAML Validation Failed");
    const readVersionRange = (str)=>{
        return new Range(str);
    };
    const contributes = yaml.contributes;
    const title = yaml[kTitle1];
    const author = yaml[kAuthor1];
    const versionRaw = yaml[kVersion];
    const quartoVersionRaw = yaml[kQuartoRequired1];
    const versionParsed = versionRaw ? coerce(versionRaw) : undefined;
    const quartoVersion = quartoVersionRaw ? readVersionRange(quartoVersionRaw) : undefined;
    const version = versionParsed ? versionParsed : undefined;
    const extensionDirRaw = dirname2(extensionFile);
    const extensionDir = isAbsolute2(extensionDirRaw) ? extensionDirRaw : join2(Deno.cwd(), extensionDirRaw);
    const formats = contributes?.formats || contributes?.format || {};
    const embeddedExtensions = await readExtensions(join2(extensionDir, kExtensionDir));
    Object.keys(formats).forEach((key)=>{
        if (formats[key] === "default") {
            formats[key] = {};
        }
    });
    Object.keys(formats).filter((key)=>{
        return key !== kCommon;
    }).forEach((key)=>{
        formats[key] = mergeConfigs(formats[kCommon] || {}, formats[key]);
        const formatMeta = formats[key];
        if (formatMeta[kFormatResources]) {
            const resolved = resolvePathGlobs(extensionDir, formatMeta[kFormatResources], [], {
                mode: "strict"
            });
            if (resolved.include.length > 0) {
                formatMeta[kFormatResources] = resolved.include.map((include)=>{
                    return relative2(extensionDir, include);
                });
            }
        }
        if (key.endsWith(".lua")) {
            const fullPath = join2(extensionDir, key);
            if (existsSync(fullPath)) {
                formatMeta.writer = fullPath;
            }
        }
        formatMeta.shortcodes = (formatMeta.shortcodes || []).flatMap((shortcode)=>{
            return resolveShortcode(embeddedExtensions, extensionDir, shortcode);
        });
        formatMeta.filters = (formatMeta.filters || []).flatMap((filter)=>{
            return resolveFilter(embeddedExtensions, extensionDir, filter);
        });
        formatMeta[kRevealJSPlugins] = (formatMeta?.[kRevealJSPlugins] || []).flatMap((plugin)=>{
            return resolveRevealJSPlugin(embeddedExtensions, extensionDir, plugin);
        });
    });
    delete formats[kCommon];
    const shortcodes = (contributes?.shortcodes || []).map((shortcode)=>{
        return resolveShortcodePath(extensionDir, shortcode);
    });
    const filters = (contributes?.filters || []).map((filter)=>{
        return resolveFilterPath(extensionDir, filter);
    });
    const project = contributes?.project;
    const metadata = contributes?.metadata;
    for (const key of [
        "pre-render",
        "post-render"
    ]){
        for (const object of [
            metadata,
            project
        ]){
            if (!object?.project || typeof object.project !== "object") {
                continue;
            }
            const t = object.project[key];
            if (t) {
                const value = Array.isArray(t) ? t : [
                    t
                ];
                const resolved = resolvePathGlobs(extensionDir, value, []);
                if (resolved.include.length > 0) {
                    object.project[key] = resolved.include;
                }
            }
        }
    }
    const revealJSPlugins = (contributes?.[kRevealJSPlugins] || []).map((plugin)=>{
        return resolveRevealPlugin(extensionDir, plugin);
    });
    const result1 = {
        title,
        author,
        version,
        quartoVersion,
        id: extensionId,
        path: extensionDir,
        contributes: {
            metadata,
            shortcodes,
            filters,
            formats,
            project: project ?? {},
            [kRevealJSPlugins]: revealJSPlugins
        }
    };
    validateExtension(result1);
    return result1;
}
function resolveRevealJSPlugin(embeddedExtensions, dir, plugin) {
    if (typeof plugin === "string") {
        const extensionId = toExtensionId(plugin);
        const extensions = findExtensions(embeddedExtensions, extensionId, "revealjs-plugins");
        if (extensions.length > 0) {
            const plugins = [];
            for (const plugin of extensions[0].contributes[kRevealJSPlugins] || []){
                plugins.push(plugin);
            }
            return plugins;
        } else {
            validateExtensionPath("revealjs-plugin", dir, plugin);
            return resolveRevealPlugin(dir, plugin);
        }
    } else {
        return plugin;
    }
}
function isPluginRaw(plugin) {
    return plugin.plugin === undefined;
}
function resolveRevealPlugin(extensionDir, plugin) {
    if (typeof plugin === "string") {
        return join2(extensionDir, plugin);
    } else if (isPluginRaw(plugin)) {
        return resolveRevealPluginInline(plugin, extensionDir);
    } else {
        plugin.plugin = join2(extensionDir, plugin.plugin);
        return plugin;
    }
}
function resolveRevealPluginInline(plugin, extensionDir) {
    if (!plugin.name) {
        throw new Error(`Invalid revealjs-plugin in ${extensionDir} - 'name' property is required.`);
    }
    const resolvedPlugin = {
        name: plugin.name,
        path: extensionDir,
        register: plugin.register,
        config: plugin.config
    };
    if (plugin.script) {
        const pluginArr = Array.isArray(plugin.script) ? plugin.script : [
            plugin.script
        ];
        resolvedPlugin.script = pluginArr.map((plug)=>{
            if (typeof plug === "string") {
                return {
                    path: plug
                };
            } else {
                return plug;
            }
        });
    }
    if (plugin.stylesheet) {
        resolvedPlugin.stylesheet = Array.isArray(plugin.stylesheet) ? plugin.stylesheet : [
            plugin.stylesheet
        ];
    }
    return resolvedPlugin;
}
function resolveShortcode(embeddedExtensions, dir, shortcode) {
    const extensionId = toExtensionId(shortcode);
    const extensions = findExtensions(embeddedExtensions, extensionId, "shortcodes");
    if (extensions.length > 0) {
        const shortcodes = [];
        for (const shortcode of extensions[0].contributes.shortcodes || []){
            shortcodes.push(resolveShortcodePath(extensions[0].path, shortcode));
        }
        return shortcodes;
    } else {
        validateExtensionPath("shortcode", dir, shortcode);
        return resolveShortcodePath(dir, shortcode);
    }
}
function resolveShortcodePath(extensionDir, shortcode) {
    if (isAbsolute2(shortcode)) {
        return shortcode;
    } else {
        return join2(extensionDir, shortcode);
    }
}
function resolveFilter(embeddedExtensions, dir, filter) {
    if (typeof filter === "string") {
        if (filter === "quarto") {
            return filter;
        }
        const extensionId = toExtensionId(filter);
        const extensions = findExtensions(embeddedExtensions, extensionId, "filters");
        if (extensions.length > 0) {
            const filters = [];
            for (const filter of extensions[0].contributes.filters || []){
                filters.push(resolveFilterPath(extensions[0].path, filter));
            }
            return filters;
        } else {
            validateExtensionPath("filter", dir, filter);
            return resolveFilterPath(dir, filter);
        }
    } else {
        validateExtensionPath("filter", dir, filter.path);
        return resolveFilterPath(dir, filter);
    }
}
function resolveFilterPath(extensionDir, filter) {
    if (typeof filter === "string") {
        if (isAbsolute2(filter)) {
            return filter;
        } else {
            return join2(extensionDir, filter);
        }
    } else {
        const filterAt = filter.at;
        const result1 = {
            type: filter.type,
            path: isAbsolute2(filter.path) ? filter.path : join2(extensionDir, filter.path)
        };
        if (filterAt === undefined) {
            return result1;
        } else {
            return {
                ...result1,
                at: filterAt
            };
        }
    }
}
function validateExtensionPath(type, dir, path) {
    const resolves = existsSync(join2(dir, path));
    if (!resolves) {
        throw Error(`Failed to resolve referenced ${type} ${path} - path does not exist.\nIf you are attempting to use another extension within this extension, please install the extension using the 'quarto install --embedded' command.`);
    }
    return resolves;
}
function toExtensionId(extension) {
    if (extension.indexOf("/") > -1) {
        const extParts = extension.split("/");
        if (extParts.length === 2) {
            return {
                name: extParts[1],
                organization: extParts[0]
            };
        } else {
            return {
                name: extension
            };
        }
    } else {
        return {
            name: extension
        };
    }
}
const extensionFile = (dir)=>{
    return [
        "_extension.yml",
        "_extension.yaml"
    ].map((file)=>join2(dir, file)).find(existsSync1);
};
const kMetaNormalizationActive = "metadata-normalization";
function metadataNormalizationFilterActive(options) {
    return options.format.metadata[kMetaNormalizationActive] !== false;
}
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",
        "--quiet"
    ];
    if (loadPaths) {
        loadPaths.forEach((loadPath)=>{
            args.push(`--load-path=${loadPath}`);
        });
    }
    await dartCommand(args);
    return outputFilePath;
}
async function dartCommand(args) {
    const resolvePath = ()=>{
        const dartOverrideCmd = Deno.env.get("QUARTO_DART_SASS");
        if (dartOverrideCmd) {
            if (!existsSync(dartOverrideCmd)) {
                warnOnce(`Specified QUARTO_DART_SASS does not exist, using built in dart sass.`);
            } else {
                return dartOverrideCmd;
            }
        }
        const command = Deno.build.os === "windows" ? "sass.bat" : "sass";
        return architectureToolsPath(join2("dart-sass", command));
    };
    const sass = resolvePath();
    const cmd = [
        sass,
        ...args
    ];
    const result1 = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "piped"
    });
    if (result1.success) {
        if (result1.stderr) {
            info(result1.stderr);
        }
        return result1.stdout;
    } else {
        debug(`[DART path]   : ${sass}`);
        debug(`[DART args]   : ${args.join(" ")}`);
        debug(`[DART stdout] : ${result1.stdout}`);
        debug(`[DART stderr] : ${result1.stderr}`);
        const errLines = lines(result1.stderr || "");
        const errMsg = errLines.slice(0, errLines.length - 2).join("\n");
        throw new Error("Theme file compilation failed:\n\n" + errMsg);
    }
}
function sassVariable(name, value, formatter) {
    return {
        name: name,
        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 quartoUses = bundles.map((bundle)=>bundle.quarto?.uses || "");
    const quartoFunctions = bundles.map((bundle)=>bundle.quarto?.functions || "");
    const quartoDefaults = bundles.map((bundle)=>bundle.quarto?.defaults || "");
    const quartoRules = 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,
        ...quartoUses,
        ...userUses,
        ...frameworkFunctions,
        ...quartoFunctions,
        ...userFunctions,
        ...userDefaults.reverse(),
        ...quartoDefaults.reverse(),
        ...frameworkDefaults.reverse(),
        ...frameworkMixins,
        ...quartoMixins,
        ...userMixins,
        ...frameworkRules,
        ...quartoRules,
        ...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(path) {
    if (Deno.statSync(path).isFile) {
        return sassLayerFile(path);
    } else {
        return sassLayerDir(path, {
            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 = (path)=>{
        if (path) {
            path = join2(dir, path);
            if (existsSync(path)) {
                return Deno.readTextFileSync(path);
            } 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 useSessionCache = input.match(/@import/);
        const cacheDir = useSessionCache ? join2(temp.baseDir, "sass") : quartoCacheDir("sass");
        const cacheIdxPath = join2(cacheDir, "index.json");
        const outputFile = `${identifierHash}.css`;
        const outputFilePath = join2(cacheDir, outputFile);
        let cacheIndex = {};
        let writeCache = true;
        if (existsSync(outputFilePath)) {
            try {
                cacheIndex = JSON.parse(Deno.readTextFileSync(cacheIdxPath));
                const existingEntry = cacheIndex[identifierHash];
                writeCache = !existingEntry || existingEntry.hash !== inputHash;
            } catch  {
                debug(`The scss cache index file ${cacheIdxPath} can't be read.`);
            }
        }
        if (writeCache) {
            try {
                await dartCompile(input, outputFilePath, temp, loadPaths, compressed);
            } catch (error) {
                try {
                    if (safeExistsSync(outputFilePath)) {
                        Deno.removeSync(outputFilePath);
                    }
                } finally{}
                throw error;
            }
            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 kTabsets = "tabsets";
const kCodeCopy = "code-copy";
const kAnchorSections = "anchor-sections";
const kCitationsHover = "citations-hover";
const kFootnotesHover = "footnotes-hover";
const kXrefsHover = "crossrefs-hover";
const kSmoothScroll = "smooth-scroll";
const kCodeAnnotations = "code-annotations";
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 kAppendixCiteAs = "appendix-cite-as";
const kLicense = "license";
const kCopyright = "copyright";
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", join2("clipboard", "clipboard.min.js"))
    });
    return dependency;
};
const bootstrapFunctions = ()=>{
    return Deno.readTextFileSync(join2(bootstrapResourceDir(), "_functions.scss"));
};
const bootstrapMixins = ()=>{
    return Deno.readTextFileSync(join2(bootstrapResourceDir(), "_mixins.scss"));
};
const bootstrapVariables = ()=>{
    return Deno.readTextFileSync(join2(bootstrapResourceDir(), "_variables.scss"));
};
const bootstrapRules = ()=>{
    return Deno.readTextFileSync(join2(bootstrapResourceDir(), "bootstrap.scss"));
};
const bslibComponentMixins = ()=>{
    const bootstrapDistDir = formatResourcePath("html", "bslib");
    const mixinsDir = join2(bootstrapDistDir, "components", "scss", "mixins");
    return Deno.readTextFileSync(join2(mixinsDir, "_mixins.scss"));
};
const bslibComponentRules = ()=>{
    const bslibDistDir = formatResourcePath("html", join2("bslib"));
    const bslibDirs = [
        join2(bslibDistDir, "bslib-scss"),
        join2(bslibDistDir, "components", "scss")
    ];
    const scss = [];
    for (const bsLibDir of bslibDirs){
        for (const walk of Deno.readDirSync(bsLibDir)){
            if (walk.isFile) {
                const contents = Deno.readTextFileSync(join2(bsLibDir, walk.name));
                scss.push(contents);
            }
        }
    }
    return scss.join("\n");
};
const htmlToolsRules = ()=>{
    const htmlToolsDir = formatResourcePath("html", join2("htmltools"));
    const fillCss = Deno.readTextFileSync(join2(htmlToolsDir, "fill.css"));
    return fillCss;
};
const bootstrapResourceDir = ()=>{
    return formatResourcePath("html", join2("bootstrap", "dist", "scss"));
};
const bslibResourceDir = ()=>{
    return formatResourcePath("html", join2("bslib", "bslib-scss"));
};
const sassUtilFunctions = (name)=>{
    const bootstrapDistDir = formatResourcePath("html", join2("bootstrap", "dist"));
    const path = join2(bootstrapDistDir, "sass-utils", name);
    return Deno.readTextFileSync(path);
};
const quartoRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules.scss"));
const quartoCopyCodeDefaults = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-variables-copy-code.scss"));
const quartoCopyCodeRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules-copy-code.scss"));
const quartoLinkExternalRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules-link-external.scss"));
const quartoCodeFilenameRules = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-rules-code-filename.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 path = formatResourcePath("html", join2("bootstrap", "_bootstrap-customize.scss"));
    return sassLayer(path);
};
const quartoBootstrapRules = ()=>Deno.readTextFileSync(formatResourcePath("html", join2("bootstrap", "_bootstrap-rules.scss")));
const quartoBootstrapMixins = ()=>Deno.readTextFileSync(formatResourcePath("html", join2("bootstrap", "_bootstrap-mixins.scss")));
const quartoBootstrapFunctions = ()=>Deno.readTextFileSync(formatResourcePath("html", join2("bootstrap", "_bootstrap-functions.scss")));
const quartoBaseLayer = (format, codeCopy = false, tabby = false, figResponsive = false, codeFilename = false)=>{
    const rules = [
        quartoRules()
    ];
    const defaults = [
        quartoDefaults(format),
        quartoVariables()
    ];
    if (codeCopy) {
        rules.push(quartoCopyCodeRules());
        defaults.push(quartoCopyCodeDefaults());
    }
    if (tabby) {
        rules.push(quartoTabbyRules());
    }
    if (figResponsive) {
        rules.push(quartoFigResponsiveRules());
    }
    if (codeFilename) {
        rules.push(quartoCodeFilenameRules());
    }
    if (format.render[kLinkExternalIcon]) {
        rules.push(quartoLinkExternalRules());
    }
    return {
        uses: quartoUses(),
        defaults: defaults.join("\n"),
        functions: quartoFunctions(),
        mixins: "",
        rules: rules.join("\n")
    };
};
const quartoVariables = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-variables.scss"));
const quartoUses = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-uses.scss"));
const quartoFunctions = ()=>Deno.readTextFileSync(formatResourcePath("html", "_quarto-functions.scss"));
const quartoDefaults = (format)=>{
    const defaults = [];
    defaults.push(outputVariable(sassVariable("code-copy-selector", format.metadata[kCodeCopy] === undefined || format.metadata[kCodeCopy] === "hover" ? '"pre.sourceCode:hover > "' : '""')));
    defaults.push(outputVariable(sassVariable("code-white-space", format.render[kCodeOverflow] === "wrap" ? "pre-wrap" : "pre")));
    defaults.push(outputVariable(sassVariable(kTblCapLoc, format.metadata[kTblCapLoc] || format.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, title, level = 2, headingClasses = []) {
    prependHeading(doc, el, title, level, headingClasses);
}
function prependHeading(doc, el, title, level, classes) {
    const heading = doc.createElement("h" + level);
    if (typeof title == "string" && title !== "none") {
        heading.innerHTML = title;
    }
    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-title-banner .quarto-title",
        ".quarto-title-block .quarto-title-meta-author",
        ".quarto-title-block .quarto-title-meta",
        "div[class^='quarto-about-']",
        "div[class*=' quarto-about-']"
    ];
    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(format, flags) {
    return format.pandoc[kReferenceLocation] === "margin" || flags[kReferenceLocation] === "margin";
}
function hasMarginCites(format) {
    return format.metadata[kCitationLocation] === "margin";
}
function hasMarginFigCaps(format) {
    return format.metadata[kFigCapLoc] === "margin";
}
function createCodeCopyButton(doc, format) {
    const copyButton = doc.createElement("button");
    const title = format.language[kCopyButtonTooltip];
    copyButton.setAttribute("title", title);
    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(name, content, doc) {
    const m = doc.createElement("META");
    if (name.startsWith("og:")) {
        m.setAttribute("property", name);
    } else {
        m.setAttribute("name", name);
    }
    m.setAttribute("content", content);
    const nl = doc.createTextNode("\n");
    doc.querySelector("head")?.appendChild(m);
    doc.querySelector("head")?.appendChild(nl);
}
function writeLinkTag(rel, href, doc) {
    const l1 = doc.createElement("LINK");
    l1.setAttribute("rel", rel);
    l1.setAttribute("href", href);
    const nl = doc.createTextNode("\n");
    doc.querySelector("head")?.appendChild(l1);
    doc.querySelector("head")?.appendChild(nl);
}
function formatPageLayout(format) {
    return format.metadata[kPageLayout] || kPageLayoutArticle;
}
function formatHasFullLayout(format) {
    return format.metadata[kPageLayout] === kPageLayoutFull;
}
function formatHasArticleLayout(format) {
    return format.metadata[kPageLayout] === undefined || format.metadata[kPageLayout] === kPageLayoutArticle || format.metadata[kPageLayout] === kPageLayoutFull;
}
const kCitesIndexFile = "cites-index-file";
const kCiteIndexDir = "cites";
function citeIndexFilterParams(options, _defaults) {
    if (options.project && projectIsBook(options.project)) {
        return {
            [kCitesIndexFile]: citeIndexFile(options.project.dir)
        };
    } else {
        return {};
    }
}
function citeIndex(projectDir) {
    const mainIndexFile = citeIndexFile(projectDir);
    const mainIndex = existsSync(mainIndexFile) ? JSON.parse(Deno.readTextFileSync(mainIndexFile)) : {};
    return mainIndex;
}
function citeIndexFile(projectDir) {
    const citesDir = projectScratchPath(projectDir, kCiteIndexDir);
    ensureDirSync(citesDir);
    return join2(citesDir, "index.json");
}
const kJatsSubarticle = "jats-subarticle";
const kLintXml = "_lint-jats-xml-output";
const kSubArticles = "subarticles";
function jatsTagset(to) {
    return kTagSets[to];
}
function jatsDtd(tagset) {
    return kDJatsDtds[tagset];
}
function xmlPlaceholder(token, input) {
    return `<!-- (F2ED4C6E)[${token}]:${input} -->`;
}
const kTagSets = {
    "jats": "archiving",
    "jats_archiving": "archiving",
    "jats_publishing": "publishing",
    "jats_articleauthoring": "authoring"
};
const kDJatsDtds = {
    "archiving": {
        name: "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.2 20190208//EN",
        location: "JATS-archivearticle1.dtd"
    },
    "publishing": {
        name: "-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN",
        location: "JATS-publishing1.dtd"
    },
    "authoring": {
        name: "-//NLM//DTD JATS (Z39.96) Article Authoring DTD v1.2 20190208//EN",
        location: "JATS-articleauthoring1.dtd"
    }
};
const kQuartoParams = "quarto-params";
const kProjectOffset = "project-offset";
const kFilterProjectOutputDir = "project-output-dir";
const kMediabagDir = "mediabag-dir";
const kResultsFile = "results-file";
const kTimingFile = "timings-file";
const kHasBootstrap = "has-bootstrap";
const kActiveFilters = "active-filters";
const kQuartoVersion1 = "quarto-version";
const kQuartoCliPath = "quarto-cli-path";
const kQuartoSource = "quarto-source";
const kHasResourcePath = "has-resource-path";
const kQuartoCustomFormat = "quarto-custom-format";
const kIsShinyPython = "is-shiny-python";
const kShinyPythonExec = "shiny-python-exec";
const kExecutionEngine = "execution-engine";
async function filterParamsJson(args, options, defaults, filterParams, resultsFile, dependenciesFile, timingFile) {
    const includes = options.format.render[kMergeIncludes] !== false ? extractIncludeParams(args, options.format.metadata, defaults || {}) : {};
    const filterSpec = extractFilterSpecParams(options.format.metadata);
    const quartoColumnParams = extractColumnParams(args, options.format.metadata, defaults);
    const customFormatParams = extractCustomFormatParams(options.format.metadata);
    const isShinyPython = isServerShinyPython(options.format, options.executionEngine);
    const typstFilterParams = extractTypstFilterParams(options.format);
    const params = {
        ...includes,
        ...initFilterParams(dependenciesFile),
        ...ipynbFilterParams(options),
        ...await projectFilterParams(options),
        ...quartoColumnParams,
        ...await quartoFilterParams(options, defaults),
        ...crossrefFilterParams(options, defaults),
        ...citeIndexFilterParams(options, defaults),
        ...layoutFilterParams(options.format, defaults),
        ...languageFilterParams(options.format),
        ...jatsFilterParams(options),
        ...notebookContextFilterParams(options),
        ...filterParams,
        ...customFormatParams,
        ...typstFilterParams,
        [kResultsFile]: pandocMetadataPath(resultsFile),
        [kTimingFile]: pandocMetadataPath(timingFile),
        [kQuartoFilters]: filterSpec,
        [kActiveFilters]: {
            normalization: metadataNormalizationFilterActive(options),
            crossref: crossrefFilterActive(options),
            jats_subarticle: options.format.metadata[kJatsSubarticle]
        },
        [kFormatIdentifier]: options.format.identifier,
        [kIsShinyPython]: isShinyPython,
        [kShinyPythonExec]: isShinyPython ? await pythonExec() : undefined,
        [kExecutionEngine]: options.executionEngine
    };
    return JSON.stringify(params);
}
function removeFilterParams(metadata) {
    delete metadata[kQuartoParams];
}
function quartoMainFilter() {
    return resourcePath("filters/main.lua");
}
function extractCustomFormatParams(metadata) {
    const customFormatParams = metadata[kQuartoCustomFormat];
    if (customFormatParams) {
        delete metadata[kQuartoCustomFormat];
        return {
            [kQuartoCustomFormat]: customFormatParams
        };
    } else {
        return {};
    }
}
function extractFilterSpecParams(metadata) {
    const filterSpec = metadata[kQuartoFilters];
    delete metadata[kQuartoFilters];
    return filterSpec;
}
function extractIncludeParams(args, metadata, defaults) {
    const includes = mergeConfigs(extractSmartIncludeText(metadata), extractSmartIncludeText(defaults || {}), extractSmartIncludeText(defaults.variables || {}), extractIncludeVariables(metadata), extractIncludeVariables(defaults.variables || {}));
    if (defaults.variables && Object.keys(defaults.variables).length === 0) {
        delete defaults.variables;
    }
    const inHeaderFiles = [];
    const beforeBodyFiles = [];
    const afterBodyFiles = [];
    const smartMetadataFiles = extractSmartIncludeFile(metadata);
    const smartDefaultsFiles = extractSmartIncludeFile(defaults || {});
    const smartDefaultsVariablesFiles = extractSmartIncludeFile(defaults.variables || {});
    inHeaderFiles.push(...defaults[kIncludeInHeader] || []);
    beforeBodyFiles.push(...defaults[kIncludeBeforeBody] || []);
    afterBodyFiles.push(...defaults[kIncludeAfterBody] || []);
    inHeaderFiles.push(...smartMetadataFiles[kIncludeInHeader]);
    beforeBodyFiles.push(...smartMetadataFiles[kIncludeBeforeBody]);
    afterBodyFiles.push(...smartMetadataFiles[kIncludeAfterBody]);
    inHeaderFiles.push(...smartDefaultsFiles[kIncludeInHeader]);
    beforeBodyFiles.push(...smartDefaultsFiles[kIncludeBeforeBody]);
    afterBodyFiles.push(...smartDefaultsFiles[kIncludeAfterBody]);
    inHeaderFiles.push(...smartDefaultsVariablesFiles[kIncludeInHeader]);
    beforeBodyFiles.push(...smartDefaultsVariablesFiles[kIncludeBeforeBody]);
    afterBodyFiles.push(...smartDefaultsVariablesFiles[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);
    const result1 = {
        ...includes,
        [kIncludeInHeader]: inHeaderFiles.map(pandocMetadataPath),
        [kIncludeBeforeBody]: beforeBodyFiles.map(pandocMetadataPath),
        [kIncludeAfterBody]: afterBodyFiles.map(pandocMetadataPath)
    };
    return result1;
}
function extractSmartIncludeText(obj) {
    return extractSmartIncludeInternal(obj, "text");
}
function extractSmartIncludeFile(obj) {
    const inner = extractSmartIncludeInternal(obj, "file");
    return {
        [kIncludeInHeader]: inner[kHeaderIncludes],
        [kIncludeBeforeBody]: inner[kIncludeBefore],
        [kIncludeAfterBody]: inner[kIncludeAfter]
    };
}
function extractSmartIncludeInternal(obj, key) {
    const isContent = (v)=>{
        if (typeof v !== "object") {
            return false;
        }
        return typeof v[key] === "string";
    };
    const extractVariable = (name)=>{
        const value = obj[name];
        if (value === undefined) {
            return [];
        }
        if (Array.isArray(value)) {
            const contents = value.filter(isContent);
            const nonContents = value.filter((v)=>!isContent(v));
            obj[name] = nonContents;
            return contents.map((v)=>v[key]);
        } else if (isContent(value)) {
            delete obj[name];
            return [
                value[key]
            ];
        } else {
            return [];
        }
    };
    return {
        [kHeaderIncludes]: extractVariable(kIncludeInHeader),
        [kIncludeBefore]: extractVariable(kIncludeBeforeBody),
        [kIncludeAfter]: extractVariable(kIncludeAfterBody)
    };
}
function extractIncludeVariables(obj) {
    const extractVariable = (name)=>{
        const value = obj[name];
        delete obj[name];
        if (!value) {
            return [];
        } else if (Array.isArray(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 (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(format) {
    const language = format.language;
    const params = {
        [kCodeSummary]: format.metadata[kCodeSummary] || language[kCodeSummary],
        [kTocTitleDocument]: language[kTocTitleDocument]
    };
    Object.keys(language).forEach((key)=>{
        if (key.startsWith("callout-") || key.startsWith("crossref-") || key.startsWith("environment-")) {
            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;
}
async function projectFilterParams(options) {
    const projType = projectType(options.project?.config?.project?.[kProjectType]);
    const params = (projType.filterParams ? await projType.filterParams(options) : undefined) || {};
    const additionalParams = {};
    if (options.project) {
        const absProjectOutputDir = projectOutputDir(options.project);
        const outputDir = relative2(options.project.dir, absProjectOutputDir);
        if (outputDir) {
            additionalParams[kFilterProjectOutputDir] = outputDir;
        }
    }
    if (options.offset) {
        additionalParams[kProjectOffset] = options.offset;
    }
    return {
        ...additionalParams,
        ...params
    };
}
function ipynbFilterParams(options) {
    const params = {
        [kIPynbTitleBlockTemplate]: options.format.metadata[kIPynbTitleBlockTemplate]
    };
    if (options.format.render[kIpynbProduceSourceNotebook]) {
        params[kEnableCrossRef] = false;
        params[kIpynbProduceSourceNotebook] = true;
    }
    return params;
}
function jatsFilterParams(options) {
    if (options.format.metadata[kJatsSubarticle]) {
        return {
            [kJatsSubarticleId]: options.format.metadata[kJatsSubarticleId] || shortUuid()
        };
    } else {
        return {};
    }
}
function notebookContextFilterParams(options) {
    const nbContext = options.services.notebook;
    const notebooks = nbContext.all();
    if (notebooks.length > 0) {
        return {
            "notebook-context": notebooks
        };
    }
}
async function quartoFilterParams(options, defaults) {
    const format = options.format;
    const params = {
        [kOutputDivs]: format.render[kOutputDivs]
    };
    params[kMediabagDir] = options.mediabagDir;
    const figAlign = format.render[kFigAlign];
    if (figAlign) {
        params[kFigAlign] = figAlign;
    }
    const figPos = format.render[kFigPos];
    if (figPos) {
        params[kFigPos] = figPos;
    }
    const figEnv = format.render[kFigEnv];
    if (figEnv) {
        params[kFigEnv] = figEnv;
    }
    const foldCode = format.render[kCodeFold];
    if (foldCode) {
        params[kCodeFold] = foldCode;
    }
    const htmlTableProcessing = format.render[kHtmlTableProcessing];
    if (htmlTableProcessing) {
        params[kHtmlTableProcessing] = htmlTableProcessing;
    }
    const useRsvgConvert = format.render[kUseRsvgConvert];
    if (useRsvgConvert !== undefined) {
        params[kUseRsvgConvert] = useRsvgConvert;
    }
    const tblColwidths = format.render[kTblColwidths];
    if (tblColwidths !== undefined) {
        params[kTblColwidths] = tblColwidths;
    }
    const shortcodes = format.render[kShortcodes];
    if (shortcodes !== undefined) {
        params[kShortcodes] = shortcodes;
    }
    const extShortcodes = await extensionShortcodes(options);
    if (extShortcodes) {
        params[kShortcodes] = params[kShortcodes] || [];
        params[kShortcodes].push(...extShortcodes);
    }
    params[kHtmlMathMethod] = defaults?.[kHtmlMathMethod];
    const figResponsive = format.metadata[kFigResponsive] === true;
    if (figResponsive) {
        params[kFigResponsive] = figResponsive;
    }
    const outputLocation = format.metadata[kOutputLocation];
    if (outputLocation) {
        params[kOutputLocation] = outputLocation;
    }
    const lineNumbers = format.render[kCodeLineNumbers];
    if (lineNumbers) {
        params[kCodeLineNumbers] = lineNumbers;
    }
    const keepHidden = format.render[kKeepHidden];
    if (keepHidden) {
        params[kKeepHidden] = kKeepHidden;
    }
    const removeHidden = format.metadata[kRemoveHidden];
    if (removeHidden) {
        params[kRemoveHidden] = removeHidden;
    }
    const clearHiddenClasses = format.metadata[kClearHiddenClasses];
    if (clearHiddenClasses) {
        params[kClearHiddenClasses] = clearHiddenClasses;
    }
    const unrollMarkdownCells = format.metadata[kUnrollMarkdownCells];
    if (unrollMarkdownCells) {
        params[kUnrollMarkdownCells] = unrollMarkdownCells;
    }
    const clearCellOptions = format.render[kClearCellOptions];
    if (clearCellOptions) {
        params[kClearCellOptions] = clearCellOptions;
    }
    params[kCiteMethod] = citeMethod(options);
    params[kPdfEngine] = pdfEngine1(options);
    params[kHasBootstrap] = formatHasBootstrap(options.format);
    const hasResourcePath = options.format.pandoc[kResourcePath] !== undefined || options.args.includes("--resource-path");
    params[kHasResourcePath] = hasResourcePath;
    params[kQuartoSource] = options.source;
    params[kQuartoProfile.toLowerCase()] = activeProfiles();
    params[kQuartoVersion1] = quartoConfig.version();
    params[kQuartoCliPath] = quartoConfig.cliPath();
    params[kCodeAnnotations] = format.metadata[kCodeAnnotations];
    return params;
}
async function extensionShortcodes(options) {
    const extensionShortcodes = [];
    if (options.services.extension) {
        const allExtensions = await options.services.extension?.extensions(options.source, options.project?.config, options.project?.dir);
        const shortCodeExtensions = filterBuiltInExtensions(allExtensions.filter((ext)=>{
            return !!ext.contributes.shortcodes;
        }));
        shortCodeExtensions.forEach((extension)=>{
            const shortcodes = extension.contributes.shortcodes || [];
            extensionShortcodes.push(...shortcodes);
        });
    }
    return extensionShortcodes;
}
function initFilterParams(dependenciesFile) {
    const params = {};
    if (Deno.build.os === "windows") {
        const value = readCodePage();
        if (value) {
            debug("Windows: Using code page " + value);
            Deno.env.set("QUARTO_WIN_CODEPAGE", value);
        }
    }
    Deno.env.set("QUARTO_FILTER_DEPENDENCY_FILE", dependenciesFile);
    return params;
}
const kQuartoFilterMarker = "quarto";
const kQuartoCiteProcMarker = "citeproc";
async function resolveFilters(filters, options, pandoc) {
    const quartoFilters = [];
    quartoFilters.push(quartoMainFilter());
    filters = await resolveFilterExtension(options, filters);
    let quartoLoc = filters.findIndex((filter)=>filter === kQuartoFilterMarker);
    if (quartoLoc === -1) {
        quartoLoc = Infinity;
    }
    const entryPoints = filters.filter((f)=>f !== "quarto").map((filter, i1)=>{
        if (isFilterEntryPoint(filter)) {
            return filter;
        }
        const at = quartoLoc > i1 ? kQuartoPre : kQuartoPost;
        const result1 = typeof filter === "string" ? {
            "at": at,
            "type": filter.endsWith(".lua") ? "lua" : "json",
            "path": filter
        } : {
            "at": at,
            ...filter
        };
        return result1;
    });
    filters = filters.filter((filter)=>filter !== kQuartoCiteProcMarker);
    const citeproc = citeMethod(options) === kQuartoCiteProcMarker;
    if (citeproc) {
        if (pandoc.citeproc === true) {
            delete pandoc.citeproc;
        }
        quartoFilters.push(kQuartoCiteProcMarker);
    }
    if ([
        quartoFilters
    ].some((x)=>x.length)) {
        return {
            quartoFilters,
            beforeQuartoFilters: [],
            afterQuartoFilters: [],
            entryPoints
        };
    } else {
        return undefined;
    }
}
function citeMethod(options) {
    const pandoc = options.format.pandoc;
    const metadata = options.format.metadata;
    const engine = bibEngine(options.format.pandoc, options.flags);
    if (pandoc.citeproc) {
        if (engine) {
            throw new Error(`The bibliography engine '${engine}' was set when 'citeproc' was also explicitly requested.`);
        }
        return "citeproc";
    }
    if (!metadata[kBibliography] && !metadata[kReferences]) {
        return null;
    }
    if (engine) {
        return engine;
    }
    if (pandoc.citeproc !== false) {
        return "citeproc";
    } else {
        return null;
    }
}
function pdfEngine1(options) {
    const pdfEngine = options.flags?.pdfEngine || options.metadata?.[kPdfEngine] || "pdflatex";
    return pdfEngine;
}
async function resolveFilterExtension(options, filters) {
    const results = [];
    const getFilter = async (filter)=>{
        if (filter !== kQuartoFilterMarker && filter !== kQuartoCiteProcMarker && typeof filter === "string") {
            if (existsSync(filter) && !Deno.statSync(filter).isDirectory) {
                return filter;
            }
            const extensions = await options.services.extension?.find(filter, options.source, "filters", options.project?.config, options.project?.dir) || [];
            const filteredExtensions = filterExtensions(extensions || [], filter, "filter");
            if (filteredExtensions.length > 0) {
                const filters = extensions[0].contributes.filters;
                if (filters) {
                    return filters;
                } else {
                    return filter;
                }
            } else if (extensions.length > 0) {
                return [];
            } else {
                return filter;
            }
        } else {
            return filter;
        }
    };
    for (const filter of filters){
        const r = await getFilter(filter);
        results.push(r);
    }
    return results.flat();
}
const extractTypstFilterParams = (format)=>{
    return {
        [kTocIndent]: format.metadata[kTocIndent],
        [kCssPropertyProcessing]: format.metadata[kCssPropertyProcessing],
        [kHtmlPreTagProcessing]: format.metadata[kHtmlPreTagProcessing]
    };
};
async function generateDefaults(options) {
    let allDefaults;
    if (options.format.pandoc) {
        allDefaults = options.format.pandoc ? cloneDeep1(options.format.pandoc) : {};
        const resolvedFilters = await resolveFilters([
            ...allDefaults[kFilters] || []
        ], options, allDefaults);
        if (resolvedFilters) {
            allDefaults[kFilters] = resolvedFilters.quartoFilters;
            options.format.metadata[kQuartoFilters] = resolvedFilters;
        }
        if (isLatexOutput(options.format.pandoc)) {
            if (options.format.metadata[kNumberDepth] !== undefined) {
                allDefaults.variables = allDefaults.variables || {};
                allDefaults.variables["secnumdepth"] = options.format.metadata[kNumberDepth];
            }
        }
        return allDefaults;
    } else {
        return undefined;
    }
}
async function writeDefaultsFile(defaults, temp) {
    const defaultsStr = "---\n" + stringify(defaults, {
        indent: 2,
        lineWidth: -1,
        sortKeys: false,
        skipInvalid: true
    });
    const defaultsFile = temp.createFile({
        prefix: "quarto-defaults",
        suffix: ".yml"
    });
    await Deno.writeTextFile(defaultsFile, defaultsStr);
    return defaultsFile;
}
function pandocDefaultsMessage(pandoc, sysFilters, debug) {
    const kDebugOnly = [
        kIncludeInHeader,
        kIncludeBeforeBody,
        kIncludeAfterBody
    ];
    const kOrder = [
        kTo,
        kFrom,
        kOutputFile,
        kTemplate,
        kStandalone,
        kEmbedResources,
        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) && (debug || !kDebugOnly.includes(key))) {
            defaults[key] = pandoc[key];
        }
    });
    const filtersContains = (filters, filter)=>{
        return filters.find((sysFilter)=>{
            const sysPath = typeof sysFilter === "string" ? sysFilter : sysFilter.path;
            const filterPath = typeof filter === "string" ? filter : filter.path;
            return sysPath === filterPath;
        });
    };
    if (defaults.filters?.length) {
        defaults.filters = defaults.filters.filter((filter)=>{
            return filter !== quartoMainFilter() && filtersContains(sysFilters, filter);
        });
        if (defaults.filters?.length === 0) {
            delete defaults.filters;
        }
    }
    if (defaults.template && extname2(defaults.template) === kPatchedTemplateExt) {
        delete defaults.template;
    }
    if (defaults.writer) {
        if (defaults.writer.match(/(?:^|[\\/])_extensions[\\/]/) || defaults.writer.match(/(?:^|[\\/])extensions[\\/]quarto[\\/]/)) {
            delete defaults.writer;
        }
    }
    return stringify(defaults);
}
function executionEngineCanKeepSource(engine, target) {
    return !engine.canKeepSource || engine.canKeepSource(target);
}
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(format) {
    const codeTools = format.render?.[kCodeTools];
    return !!codeTools && isHtmlOutput(format.pandoc, true) && formatHasBootstrap(format);
}
function resolveKeepSource(format, engine, target) {
    const codeTools = format.render?.[kCodeTools];
    if (codeTools === true || typeof codeTools === "object" && (codeTools?.source === undefined || codeTools?.source === true)) {
        format.render[kKeepSource] = true;
    }
    format.render[kKeepSource] = format.render[kKeepSource] && isHtmlOutput(format.pandoc, true) && formatHasBootstrap(format) && executionEngineCanKeepSource(engine, target);
}
function keepSourceBlock(format, source) {
    if (format.render[kKeepSource]) {
        let code = Deno.readTextFileSync(source).trimLeft();
        if (!code.endsWith("\n")) {
            code = code + "\n";
        }
        code = code.replaceAll(/\n```{(\w+)}\s*\n/g, "\n" + kKeepSourceSentinel + "\n\n```$1\n");
        const kKeepSourceBackticks = "```````````````````";
        return `${kMarkdownBlockSeparator}::: {.${kEmbeddedSourceClass}}\n${kKeepSourceBackticks}` + `{.markdown shortcodes="false"}\n${code}` + `${kKeepSourceBackticks}\n:::\n`;
    } else {
        return "";
    }
}
function codeToolsPostprocessor(format) {
    return (doc)=>{
        return withTiming("codeToolsPostprocessor", ()=>{
            if (format.render[kKeepSource]) {
                const lines = doc.querySelectorAll(`.${kEmbeddedSourceClass} > div.sourceCode > pre > code > span`);
                if (lines.length > 0) {
                    const newLines = [];
                    for(let i1 = 0; i1 < lines.length; i1++){
                        const line = lines[i1];
                        if (line.innerText === kKeepSourceSentinel) {
                            i1 += 2;
                            const codeBlockLine = lines[i1];
                            const anchor = codeBlockLine.querySelector("a");
                            const text = codeBlockLine.innerText;
                            codeBlockLine.textContent = "";
                            codeBlockLine.appendChild(anchor);
                            const newSpan = doc.createElement("span");
                            newSpan.classList.add("in");
                            newSpan.innerText = text.replace(/```(\w+)/, "```{$1}");
                            codeBlockLine.appendChild(newSpan);
                            newLines.push(codeBlockLine);
                        } else {
                            newLines.push(line);
                        }
                    }
                    if (newLines.length !== lines.length) {
                        const parent = lines[0].parentElement;
                        parent.innerHTML = "";
                        newLines.forEach((line)=>{
                            parent.appendChild(line);
                            parent.appendChild(doc.createTextNode("\n"));
                        });
                    }
                }
            }
            if (formatHasCodeTools(format)) {
                const codeTools = resolveCodeTools(format, doc);
                if (codeTools.source || codeTools.toggle) {
                    const title = doc.querySelector("#title-block-header h1");
                    const header = title !== null ? title.parentElement : doc.querySelector("main.content");
                    if (header) {
                        const titleDiv = doc.createElement("div");
                        titleDiv.classList.add("quarto-title-block");
                        const layoutDiv = doc.createElement("div");
                        titleDiv.appendChild(layoutDiv);
                        if (title) {
                            header?.replaceChild(titleDiv, title);
                            layoutDiv.appendChild(title);
                        } else {
                            const h1El = doc.createElement("h1");
                            layoutDiv.appendChild(h1El);
                            layoutDiv.classList.add("quarto-title-tools-only");
                        }
                        const button = doc.createElement("button");
                        button.setAttribute("type", "button");
                        button.classList.add("btn");
                        button.classList.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);
                        if (title) {
                            header.appendChild(titleDiv);
                        } else {
                            header.prepend(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");
                            ul.classList.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, format.language[kCodeToolsShowAllCode]);
                            addListItem(kHideAllCodeLinkId, format.language[kCodeToolsHideAllCode]);
                            if (codeTools.source) {
                                addDivider();
                                const vsLi = addListItem(kViewSourceLinkId, format.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");
                            modalDiv.classList.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");
                            modalDialogDiv.classList.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(format.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);
                            const mainEl = doc.querySelector("main.content");
                            if (mainEl) {
                                const mainParentEl = mainEl.parentElement;
                                mainParentEl?.insertBefore(modalDiv, mainParentEl.lastChild);
                            } else {
                                embeddedCode.parentElement?.insertBefore(modalDiv, embeddedCode);
                            }
                            modalBody.appendChild(embeddedCode);
                            embeddedCode.classList.remove(kEmbeddedSourceClass);
                        }
                    }
                    for (const el of Array.from(doc.querySelectorAll("details div pre.hidden"))){
                        const det = el.parentElement.parentElement;
                        det.classList.add("hidden");
                    }
                }
            }
            return Promise.resolve(kHtmlEmptyPostProcessResult);
        });
    };
}
function resolveCodeTools(format, doc) {
    const kCodeCaption = format.language[kCodeToolsMenuCaption];
    const codeTools = format?.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 === true) {
        codeToolsResolved.source = !!format.render[kKeepSource];
    }
    if (codeToolsResolved.toggle) {
        const codeDetails = doc.querySelector(".cell > details > .sourceCode");
        const codeHidden = doc.querySelector(".cell .sourceCode.hidden:not(div pre.js)");
        codeToolsResolved.toggle = !!codeDetails || !!codeHidden;
    }
    return codeToolsResolved;
}
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 types = new Map();
function populateMaps(extensions, types) {
    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;
        }
        extensions.set(type, exts);
        for (const ext of exts){
            const current = types.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;
                }
            }
            types.set(ext, type);
        }
    }
}
populateMaps(extensions, types);
function lookup1(path) {
    const extension = extname2("x." + path).toLowerCase().substr(1);
    return types.get(extension);
}
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(code, set) {
    var pos = 65536;
    for(var i1 = 0; i1 < set.length; i1 += 2){
        pos += set[i1];
        if (pos > code) {
            return false;
        }
        pos += set[i1 + 1];
        if (pos >= code) {
            return true;
        }
    }
}
function isIdentifierStart(code, astral) {
    if (code < 65) {
        return code === 36;
    }
    if (code < 91) {
        return true;
    }
    if (code < 97) {
        return code === 95;
    }
    if (code < 123) {
        return true;
    }
    if (code <= 65535) {
        return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
    }
    if (astral === false) {
        return false;
    }
    return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code, astral) {
    if (code < 48) {
        return code === 36;
    }
    if (code < 58) {
        return true;
    }
    if (code < 65) {
        return false;
    }
    if (code < 91) {
        return true;
    }
    if (code < 97) {
        return code === 95;
    }
    if (code < 123) {
        return true;
    }
    if (code <= 65535) {
        return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
    }
    if (astral === false) {
        return false;
    }
    return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, 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(name, prec) {
    return new TokenType(name, {
        beforeExpr: true,
        binop: prec
    });
}
var beforeExpr = {
    beforeExpr: true
}, startsExpr = {
    startsExpr: true
};
var keywords$1 = {};
function kw(name, options) {
    if (options === void 0) options = {};
    options.keyword = name;
    return keywords$1[name] = new TokenType(name, options);
}
var types1 = {
    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(code, ecma2019String) {
    return code === 10 || code === 13 || !ecma2019String && (code === 8232 || code === 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(n) {
    return new Position(this.line, this.column + n);
};
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 = types1.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 = [], len = arguments.length;
    while(len--)plugins[len] = arguments[len];
    var cls = this;
    for(var i1 = 0; i1 < plugins.length; i1++){
        cls = plugins[i1](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(name) {
    return this.type === types1.name && this.value === name && !this.containsEsc;
};
pp.eatContextual = function(name) {
    if (!this.isContextual(name)) {
        return false;
    }
    this.next();
    return true;
};
pp.expectContextual = function(name) {
    if (!this.eatContextual(name)) {
        this.unexpected();
    }
};
pp.canInsertSemicolon = function() {
    return this.type === types1.eof || this.type === types1.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(types1.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 !== types1.eof){
        var stmt = this.parseStatement(null, true, exports);
        node.body.push(stmt);
    }
    if (this.inModule) {
        for(var i1 = 0, list = Object.keys(this.undefinedExports); i1 < list.length; i1 += 1){
            var name = list[i1];
            this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' 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 = types1._var;
        kind = "let";
    }
    switch(starttype){
        case types1._break:
        case types1._continue:
            return this.parseBreakContinueStatement(node, starttype.keyword);
        case types1._debugger:
            return this.parseDebuggerStatement(node);
        case types1._do:
            return this.parseDoStatement(node);
        case types1._for:
            return this.parseForStatement(node);
        case types1._function:
            if (context && (this.strict || context !== "if" && context !== "label") && this.options.ecmaVersion >= 6) {
                this.unexpected();
            }
            return this.parseFunctionStatement(node, false, !context);
        case types1._class:
            if (context) {
                this.unexpected();
            }
            return this.parseClass(node, true);
        case types1._if:
            return this.parseIfStatement(node);
        case types1._return:
            return this.parseReturnStatement(node);
        case types1._switch:
            return this.parseSwitchStatement(node);
        case types1._throw:
            return this.parseThrowStatement(node);
        case types1._try:
            return this.parseTryStatement(node);
        case types1._const:
        case types1._var:
            kind = kind || this.value;
            if (context && kind !== "var") {
                this.unexpected();
            }
            return this.parseVarStatement(node, kind);
        case types1._while:
            return this.parseWhileStatement(node);
        case types1._with:
            return this.parseWithStatement(node);
        case types1.braceL:
            return this.parseBlock(true, node);
        case types1.semi:
            return this.parseEmptyStatement(node);
        case types1._export:
        case types1._import:
            if (this.options.ecmaVersion > 10 && starttype === types1._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 === types1._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 === types1.name && expr.type === "Identifier" && this.eat(types1.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(types1.semi) || this.insertSemicolon()) {
        node.label = null;
    } else if (this.type !== types1.name) {
        this.unexpected();
    } else {
        node.label = this.parseIdent();
        this.semicolon();
    }
    var i1 = 0;
    for(; i1 < this.labels.length; ++i1){
        var lab = this.labels[i1];
        if (node.label == null || lab.name === node.label.name) {
            if (lab.kind != null && (isBreak || lab.kind === "loop")) {
                break;
            }
            if (node.label && isBreak) {
                break;
            }
        }
    }
    if (i1 === 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(types1._while);
    node.test = this.parseParenExpression();
    if (this.options.ecmaVersion >= 6) {
        this.eat(types1.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(types1.parenL);
    if (this.type === types1.semi) {
        if (awaitAt > -1) {
            this.unexpected(awaitAt);
        }
        return this.parseFor(node, null);
    }
    var isLet = this.isLet();
    if (this.type === types1._var || this.type === types1._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 === types1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && init$1.declarations.length === 1) {
            if (this.options.ecmaVersion >= 9) {
                if (this.type === types1._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 init = this.parseExpression(true, refDestructuringErrors);
    if (this.type === types1._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
        if (this.options.ecmaVersion >= 9) {
            if (this.type === types1._in) {
                if (awaitAt > -1) {
                    this.unexpected(awaitAt);
                }
            } else {
                node.await = awaitAt > -1;
            }
        }
        this.toAssignable(init, false, refDestructuringErrors);
        this.checkLVal(init);
        return this.parseForIn(node, init);
    } else {
        this.checkExpressionErrors(refDestructuringErrors, true);
    }
    if (awaitAt > -1) {
        this.unexpected(awaitAt);
    }
    return this.parseFor(node, init);
};
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(types1._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(types1.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(types1.braceL);
    this.labels.push(switchLabel);
    this.enterScope(0);
    var cur;
    for(var sawDefault = false; this.type !== types1.braceR;){
        if (this.type === types1._case || this.type === types1._default) {
            var isCase = this.type === types1._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(types1.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 === types1._catch) {
        var clause = this.startNode();
        this.next();
        if (this.eat(types1.parenL)) {
            clause.param = this.parseBindingAtom();
            var simple = clause.param.type === "Identifier";
            this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
            this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
            this.expect(types1.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(types1._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 === types1._switch ? "switch" : null;
    for(var i1 = this.labels.length - 1; i1 >= 0; i1--){
        var label$1 = this.labels[i1];
        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(types1.braceL);
    if (createNewLexicalScope) {
        this.enterScope(0);
    }
    while(this.type !== types1.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, init) {
    node.init = init;
    this.expect(types1.semi);
    node.test = this.type === types1.semi ? null : this.parseExpression();
    this.expect(types1.semi);
    node.update = this.type === types1.parenR ? null : this.parseExpression();
    this.expect(types1.parenR);
    node.body = this.parseStatement("for");
    this.exitScope();
    this.labels.pop();
    return this.finishNode(node, "ForStatement");
};
pp$1.parseForIn = function(node, init) {
    var isForIn = this.type === types1._in;
    this.next();
    if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
        this.raise(init.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
    } else if (init.type === "AssignmentPattern") {
        this.raise(init.start, "Invalid left-hand side in for-loop");
    }
    node.left = init;
    node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
    this.expect(types1.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(types1.eq)) {
            decl.init = this.parseMaybeAssign(isFor);
        } else if (kind === "const" && !(this.type === types1._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
            this.unexpected();
        } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types1._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(types1.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 === types1.star && statement & FUNC_HANGING_STATEMENT) {
            this.unexpected();
        }
        node.generator = this.eat(types1.star);
    }
    if (this.options.ecmaVersion >= 8) {
        node.async = !!isAsync;
    }
    if (statement & FUNC_STATEMENT) {
        node.id = statement & FUNC_NULLABLE_ID && this.type !== types1.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 === types1.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(types1.parenL);
    node.params = this.parseBindingList(types1.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(types1.braceL);
    while(this.type !== types1.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(types1.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 !== types1.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(types1.star);
    var isAsync = false;
    if (!isGenerator) {
        if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
            isAsync = true;
            isGenerator = this.options.ecmaVersion >= 9 && this.eat(types1.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 === types1.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(types1._extends) ? this.parseExprSubscripts() : null;
};
pp$1.parseExport = function(node, exports) {
    this.next();
    if (this.eat(types1.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 !== types1.string) {
            this.unexpected();
        }
        node.source = this.parseExprAtom();
        this.semicolon();
        return this.finishNode(node, "ExportAllDeclaration");
    }
    if (this.eat(types1._default)) {
        this.checkExport(exports, "default", this.lastTokStart);
        var isAsync;
        if (this.type === types1._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 === types1._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 !== types1.string) {
                this.unexpected();
            }
            node.source = this.parseExprAtom();
        } else {
            for(var i1 = 0, list = node.specifiers; i1 < list.length; i1 += 1){
                var spec = list[i1];
                this.checkUnreserved(spec.local);
                this.checkLocalExport(spec.local);
            }
            node.source = null;
        }
        this.semicolon();
    }
    return this.finishNode(node, "ExportNamedDeclaration");
};
pp$1.checkExport = function(exports, name, pos) {
    if (!exports) {
        return;
    }
    if (has(exports, name)) {
        this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
    }
    exports[name] = 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 i1 = 0, list = pat.properties; i1 < list.length; i1 += 1){
            var prop = list[i1];
            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 i1 = 0, list = decls; i1 < list.length; i1 += 1){
        var decl = list[i1];
        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(types1.braceL);
    while(!this.eat(types1.braceR)){
        if (!first) {
            this.expect(types1.comma);
            if (this.afterTrailingComma(types1.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 === types1.string) {
        node.specifiers = empty;
        node.source = this.parseExprAtom();
    } else {
        node.specifiers = this.parseImportSpecifiers();
        this.expectContextual("from");
        node.source = this.type === types1.string ? this.parseExprAtom() : this.unexpected();
    }
    this.semicolon();
    return this.finishNode(node, "ImportDeclaration");
};
pp$1.parseImportSpecifiers = function() {
    var nodes = [], first = true;
    if (this.type === types1.name) {
        var node = this.startNode();
        node.local = this.parseIdent();
        this.checkLVal(node.local, BIND_LEXICAL);
        nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
        if (!this.eat(types1.comma)) {
            return nodes;
        }
    }
    if (this.type === types1.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(types1.braceL);
    while(!this.eat(types1.braceR)){
        if (!first) {
            this.expect(types1.comma);
            if (this.afterTrailingComma(types1.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 i1 = 0; i1 < statements.length && this.isDirectiveCandidate(statements[i1]); ++i1){
        statements[i1].directive = statements[i1].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 i1 = 0, list = node.properties; i1 < list.length; i1 += 1){
                    var prop = list[i1];
                    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 i1 = 0; i1 < end; i1++){
        var elt = exprList[i1];
        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 !== types1.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 types1.bracketL:
                var node = this.startNode();
                this.next();
                node.elements = this.parseBindingList(types1.bracketR, true, true);
                return this.finishNode(node, "ArrayPattern");
            case types1.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(types1.comma);
        }
        if (allowEmpty && this.type === types1.comma) {
            elts.push(null);
        } else if (allowTrailingComma && this.afterTrailingComma(close)) {
            break;
        } else if (this.type === types1.ellipsis) {
            var rest = this.parseRestBinding();
            this.parseBindingListItem(rest);
            elts.push(rest);
            if (this.type === types1.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(types1.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 i1 = 0, list = expr.properties; i1 < list.length; i1 += 1){
                var prop = list[i1];
                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 name;
    switch(key.type){
        case "Identifier":
            name = key.name;
            break;
        case "Literal":
            name = String(key.value);
            break;
        default:
            return;
    }
    var kind = prop.kind;
    if (this.options.ecmaVersion >= 6) {
        if (name === "__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;
    }
    name = "$" + name;
    var other = propHash[name];
    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[name] = {
            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 === types1.comma) {
        var node = this.startNodeAt(startPos, startLoc);
        node.expressions = [
            expr
        ];
        while(this.eat(types1.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 === types1.parenL || this.type === types1.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 === types1.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(types1.question)) {
        var node = this.startNodeAt(startPos, startLoc);
        node.test = expr;
        node.consequent = this.parseMaybeAssign();
        this.expect(types1.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 !== types1._in)) {
        if (prec > minPrec) {
            var logical = this.type === types1.logicalOR || this.type === types1.logicalAND;
            var coalesce = this.type === types1.coalesce;
            if (coalesce) {
                prec = types1.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 === types1.coalesce || coalesce && (this.type === types1.logicalOR || this.type === types1.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 === types1.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(types1.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 result1 = this.parseSubscripts(expr, startPos, startLoc);
    if (refDestructuringErrors && result1.type === "MemberExpression") {
        if (refDestructuringErrors.parenthesizedAssign >= result1.start) {
            refDestructuringErrors.parenthesizedAssign = -1;
        }
        if (refDestructuringErrors.parenthesizedBind >= result1.start) {
            refDestructuringErrors.parenthesizedBind = -1;
        }
    }
    return result1;
};
pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
    var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start;
    var optionalChained = false;
    while(true){
        var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
        if (element.optional) {
            optionalChained = true;
        }
        if (element === base || element.type === "ArrowFunctionExpression") {
            if (optionalChained) {
                var chainNode = this.startNodeAt(startPos, startLoc);
                chainNode.expression = element;
                element = this.finishNode(chainNode, "ChainExpression");
            }
            return element;
        }
        base = element;
    }
};
pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
    var optionalSupported = this.options.ecmaVersion >= 11;
    var optional = optionalSupported && this.eat(types1.questionDot);
    if (noCalls && optional) {
        this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions");
    }
    var computed = this.eat(types1.bracketL);
    if (computed || optional && this.type !== types1.parenL && this.type !== types1.backQuote || this.eat(types1.dot)) {
        var node = this.startNodeAt(startPos, startLoc);
        node.object = base;
        node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
        node.computed = !!computed;
        if (computed) {
            this.expect(types1.bracketR);
        }
        if (optionalSupported) {
            node.optional = optional;
        }
        base = this.finishNode(node, "MemberExpression");
    } else if (!noCalls && this.eat(types1.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(types1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
        if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types1.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 = base;
        node$1.arguments = exprList;
        if (optionalSupported) {
            node$1.optional = optional;
        }
        base = this.finishNode(node$1, "CallExpression");
    } else if (this.type === types1.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 = base;
        node$2.quasi = this.parseTemplate({
            isTagged: true
        });
        base = this.finishNode(node$2, "TaggedTemplateExpression");
    }
    return base;
};
pp$3.parseExprAtom = function(refDestructuringErrors) {
    if (this.type === types1.slash) {
        this.readRegexp();
    }
    var node, canBeArrow = this.potentialArrowAt === this.start;
    switch(this.type){
        case types1._super:
            if (!this.allowSuper) {
                this.raise(this.start, "'super' keyword outside a method");
            }
            node = this.startNode();
            this.next();
            if (this.type === types1.parenL && !this.allowDirectSuper) {
                this.raise(node.start, "super() call outside constructor of a subclass");
            }
            if (this.type !== types1.dot && this.type !== types1.bracketL && this.type !== types1.parenL) {
                this.unexpected();
            }
            return this.finishNode(node, "Super");
        case types1._this:
            node = this.startNode();
            this.next();
            return this.finishNode(node, "ThisExpression");
        case types1.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(types1._function)) {
                return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true);
            }
            if (canBeArrow && !this.canInsertSemicolon()) {
                if (this.eat(types1.arrow)) {
                    return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [
                        id
                    ], false);
                }
                if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types1.name && !containsEsc) {
                    id = this.parseIdent(false);
                    if (this.canInsertSemicolon() || !this.eat(types1.arrow)) {
                        this.unexpected();
                    }
                    return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [
                        id
                    ], true);
                }
            }
            return id;
        case types1.regexp:
            var value = this.value;
            node = this.parseLiteral(value.value);
            node.regex = {
                pattern: value.pattern,
                flags: value.flags
            };
            return node;
        case types1.num:
        case types1.string:
            return this.parseLiteral(this.value);
        case types1._null:
        case types1._true:
        case types1._false:
            node = this.startNode();
            node.value = this.type === types1._null ? null : this.type === types1._true;
            node.raw = this.type.keyword;
            this.next();
            return this.finishNode(node, "Literal");
        case types1.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 types1.bracketL:
            node = this.startNode();
            this.next();
            node.elements = this.parseExprList(types1.bracketR, true, true, refDestructuringErrors);
            return this.finishNode(node, "ArrayExpression");
        case types1.braceL:
            return this.parseObj(false, refDestructuringErrors);
        case types1._function:
            node = this.startNode();
            this.next();
            return this.parseFunction(node, 0);
        case types1._class:
            return this.parseClass(this.startNode(), false);
        case types1._new:
            return this.parseNew();
        case types1.backQuote:
            return this.parseTemplate();
        case types1._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 types1.parenL:
            return this.parseDynamicImport(node);
        case types1.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(types1.parenR)) {
        var errorPos = this.start;
        if (this.eat(types1.comma) && this.eat(types1.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(types1.parenL);
    var val = this.parseExpression();
    this.expect(types1.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 !== types1.parenR){
            first ? first = false : this.expect(types1.comma);
            if (allowTrailingComma && this.afterTrailingComma(types1.parenR, true)) {
                lastIsComma = true;
                break;
            } else if (this.type === types1.ellipsis) {
                spreadStart = this.start;
                exprList.push(this.parseParenItem(this.parseRestBinding()));
                if (this.type === types1.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(types1.parenR);
        if (canBeArrow && !this.canInsertSemicolon() && this.eat(types1.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(types1.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 === types1._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(types1.parenL)) {
        node.arguments = this.parseExprList(types1.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 === types1.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 === types1.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 === types1.eof) {
            this.raise(this.pos, "Unterminated template literal");
        }
        this.expect(types1.dollarBraceL);
        node.expressions.push(this.parseExpression());
        this.expect(types1.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 === types1.name || this.type === types1.num || this.type === types1.string || this.type === types1.bracketL || this.type.keyword || this.options.ecmaVersion >= 9 && this.type === types1.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(types1.braceR)){
        if (!first) {
            this.expect(types1.comma);
            if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types1.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(types1.ellipsis)) {
        if (isPattern) {
            prop.argument = this.parseIdent(false);
            if (this.type === types1.comma) {
                this.raise(this.start, "Comma is not permitted after the rest element");
            }
            return this.finishNode(prop, "RestElement");
        }
        if (this.type === types1.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 === types1.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(types1.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(types1.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 === types1.colon) {
        this.unexpected();
    }
    if (this.eat(types1.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 === types1.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 !== types1.comma && this.type !== types1.braceR && this.type !== types1.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 === types1.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(types1.bracketL)) {
            prop.computed = true;
            prop.key = this.parseMaybeAssign();
            this.expect(types1.bracketR);
            return prop.key;
        } else {
            prop.computed = false;
        }
    }
    return prop.key = this.type === types1.num || this.type === types1.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(types1.parenL);
    node.params = this.parseBindingList(types1.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 !== types1.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 i1 = 0, list = params; i1 < list.length; i1 += 1){
        var param = list[i1];
        if (param.type !== "Identifier") {
            return false;
        }
    }
    return true;
};
pp$3.checkParams = function(node, allowDuplicates) {
    var nameHash = {};
    for(var i1 = 0, list = node.params; i1 < list.length; i1 += 1){
        var param = list[i1];
        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(types1.comma);
            if (allowTrailingComma && this.afterTrailingComma(close)) {
                break;
            }
        } else {
            first = false;
        }
        var elt = void 0;
        if (allowEmpty && this.type === types1.comma) {
            elt = null;
        } else if (this.type === types1.ellipsis) {
            elt = this.parseSpread(refDestructuringErrors);
            if (refDestructuringErrors && this.type === types1.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 name = ref2.name;
    if (this.inGenerator && name === "yield") {
        this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
    }
    if (this.inAsync && name === "await") {
        this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
    }
    if (this.keywords.test(name)) {
        this.raise(start, "Unexpected keyword '" + name + "'");
    }
    if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
        return;
    }
    var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
    if (re.test(name)) {
        if (!this.inAsync && name === "await") {
            this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
        }
        this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
    }
};
pp$3.parseIdent = function(liberal, isBinding) {
    var node = this.startNode();
    if (this.type === types1.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 === types1.semi || this.canInsertSemicolon() || this.type !== types1.star && !this.type.startsExpr) {
        node.delegate = false;
        node.argument = null;
    } else {
        node.delegate = this.eat(types1.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(name, bindingType, pos) {
    var redeclared = false;
    if (bindingType === BIND_LEXICAL) {
        var scope = this.currentScope();
        redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
        scope.lexical.push(name);
        if (this.inModule && scope.flags & SCOPE_TOP) {
            delete this.undefinedExports[name];
        }
    } else if (bindingType === BIND_SIMPLE_CATCH) {
        var scope$1 = this.currentScope();
        scope$1.lexical.push(name);
    } else if (bindingType === BIND_FUNCTION) {
        var scope$2 = this.currentScope();
        if (this.treatFunctionsAsVar) {
            redeclared = scope$2.lexical.indexOf(name) > -1;
        } else {
            redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
        }
        scope$2.functions.push(name);
    } else {
        for(var i1 = this.scopeStack.length - 1; i1 >= 0; --i1){
            var scope$3 = this.scopeStack[i1];
            if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
                redeclared = true;
                break;
            }
            scope$3.var.push(name);
            if (this.inModule && scope$3.flags & SCOPE_TOP) {
                delete this.undefinedExports[name];
            }
            if (scope$3.flags & SCOPE_VAR) {
                break;
            }
        }
    }
    if (redeclared) {
        this.raiseRecoverable(pos, "Identifier '" + name + "' 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 i1 = this.scopeStack.length - 1;; i1--){
        var scope = this.scopeStack[i1];
        if (scope.flags & SCOPE_VAR) {
            return scope;
        }
    }
};
pp$5.currentThisScope = function() {
    for(var i1 = this.scopeStack.length - 1;; i1--){
        var scope = this.scopeStack[i1];
        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 === types1.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) {
        return !parent.isExpr;
    }
    if (prevType === types1._return || prevType === types1.name && this.exprAllowed) {
        return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
    }
    if (prevType === types1._else || prevType === types1.semi || prevType === types1.eof || prevType === types1.parenR || prevType === types1.arrow) {
        return true;
    }
    if (prevType === types1.braceL) {
        return parent === types$1.b_stat;
    }
    if (prevType === types1._var || prevType === types1._const || prevType === types1.name) {
        return false;
    }
    return !this.exprAllowed;
};
pp$7.inGeneratorContext = function() {
    for(var i1 = this.context.length - 1; i1 >= 1; i1--){
        var context = this.context[i1];
        if (context.token === "function") {
            return context.generator;
        }
    }
    return false;
};
pp$7.updateContext = function(prevType) {
    var update, type = this.type;
    if (type.keyword && prevType === types1.dot) {
        this.exprAllowed = false;
    } else if (update = type.updateContext) {
        update.call(this, prevType);
    } else {
        this.exprAllowed = type.beforeExpr;
    }
};
types1.parenR.updateContext = types1.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;
};
types1.braceL.updateContext = function(prevType) {
    this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
    this.exprAllowed = true;
};
types1.dollarBraceL.updateContext = function() {
    this.context.push(types$1.b_tmpl);
    this.exprAllowed = true;
};
types1.parenL.updateContext = function(prevType) {
    var statementParens = prevType === types1._if || prevType === types1._for || prevType === types1._with || prevType === types1._while;
    this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
    this.exprAllowed = true;
};
types1.incDec.updateContext = function() {};
types1._function.updateContext = types1._class.updateContext = function(prevType) {
    if (prevType.beforeExpr && prevType !== types1.semi && prevType !== types1._else && !(prevType === types1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types1.colon || prevType === types1.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;
};
types1.backQuote.updateContext = function() {
    if (this.curContext() === types$1.q_tmpl) {
        this.context.pop();
    } else {
        this.context.push(types$1.q_tmpl);
    }
    this.exprAllowed = false;
};
types1.star.updateContext = function(prevType) {
    if (prevType === types1._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;
};
types1.name.updateContext = function(prevType) {
    var allowed = false;
    if (this.options.ecmaVersion >= 6 && prevType !== types1.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(i1, forceU) {
    if (forceU === void 0) forceU = false;
    var s = this.source;
    var l1 = s.length;
    if (i1 >= l1) {
        return -1;
    }
    var c = s.charCodeAt(i1);
    if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i1 + 1 >= l1) {
        return c;
    }
    var next = s.charCodeAt(i1 + 1);
    return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;
};
RegExpValidationState.prototype.nextIndex = function nextIndex(i1, forceU) {
    if (forceU === void 0) forceU = false;
    var s = this.source;
    var l1 = s.length;
    if (i1 >= l1) {
        return l1;
    }
    var c = s.charCodeAt(i1), next;
    if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i1 + 1 >= l1 || (next = s.charCodeAt(i1 + 1)) < 56320 || next > 57343) {
        return i1 + 1;
    }
    return i1 + 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(state) {
    var validFlags = state.validFlags;
    var flags = state.flags;
    for(var i1 = 0; i1 < flags.length; i1++){
        var flag = flags.charAt(i1);
        if (validFlags.indexOf(flag) === -1) {
            this.raise(state.start, "Invalid regular expression flag");
        }
        if (flags.indexOf(flag, i1 + 1) > -1) {
            this.raise(state.start, "Duplicate regular expression flag");
        }
    }
};
pp$8.validateRegExpPattern = function(state) {
    this.regexp_pattern(state);
    if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
        state.switchN = true;
        this.regexp_pattern(state);
    }
};
pp$8.regexp_pattern = function(state) {
    state.pos = 0;
    state.lastIntValue = 0;
    state.lastStringValue = "";
    state.lastAssertionIsQuantifiable = false;
    state.numCapturingParens = 0;
    state.maxBackReference = 0;
    state.groupNames.length = 0;
    state.backReferenceNames.length = 0;
    this.regexp_disjunction(state);
    if (state.pos !== state.source.length) {
        if (state.eat(41)) {
            state.raise("Unmatched ')'");
        }
        if (state.eat(93) || state.eat(125)) {
            state.raise("Lone quantifier brackets");
        }
    }
    if (state.maxBackReference > state.numCapturingParens) {
        state.raise("Invalid escape");
    }
    for(var i1 = 0, list = state.backReferenceNames; i1 < list.length; i1 += 1){
        var name = list[i1];
        if (state.groupNames.indexOf(name) === -1) {
            state.raise("Invalid named capture referenced");
        }
    }
};
pp$8.regexp_disjunction = function(state) {
    this.regexp_alternative(state);
    while(state.eat(124)){
        this.regexp_alternative(state);
    }
    if (this.regexp_eatQuantifier(state, true)) {
        state.raise("Nothing to repeat");
    }
    if (state.eat(123)) {
        state.raise("Lone quantifier brackets");
    }
};
pp$8.regexp_alternative = function(state) {
    while(state.pos < state.source.length && this.regexp_eatTerm(state)){}
};
pp$8.regexp_eatTerm = function(state) {
    if (this.regexp_eatAssertion(state)) {
        if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
            if (state.switchU) {
                state.raise("Invalid quantifier");
            }
        }
        return true;
    }
    if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
        this.regexp_eatQuantifier(state);
        return true;
    }
    return false;
};
pp$8.regexp_eatAssertion = function(state) {
    var start = state.pos;
    state.lastAssertionIsQuantifiable = false;
    if (state.eat(94) || state.eat(36)) {
        return true;
    }
    if (state.eat(92)) {
        if (state.eat(66) || state.eat(98)) {
            return true;
        }
        state.pos = start;
    }
    if (state.eat(40) && state.eat(63)) {
        var lookbehind = false;
        if (this.options.ecmaVersion >= 9) {
            lookbehind = state.eat(60);
        }
        if (state.eat(61) || state.eat(33)) {
            this.regexp_disjunction(state);
            if (!state.eat(41)) {
                state.raise("Unterminated group");
            }
            state.lastAssertionIsQuantifiable = !lookbehind;
            return true;
        }
    }
    state.pos = start;
    return false;
};
pp$8.regexp_eatQuantifier = function(state, noError) {
    if (noError === void 0) noError = false;
    if (this.regexp_eatQuantifierPrefix(state, noError)) {
        state.eat(63);
        return true;
    }
    return false;
};
pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
    return state.eat(42) || state.eat(43) || state.eat(63) || this.regexp_eatBracedQuantifier(state, noError);
};
pp$8.regexp_eatBracedQuantifier = function(state, noError) {
    var start = state.pos;
    if (state.eat(123)) {
        var min = 0, max = -1;
        if (this.regexp_eatDecimalDigits(state)) {
            min = state.lastIntValue;
            if (state.eat(44) && this.regexp_eatDecimalDigits(state)) {
                max = state.lastIntValue;
            }
            if (state.eat(125)) {
                if (max !== -1 && max < min && !noError) {
                    state.raise("numbers out of order in {} quantifier");
                }
                return true;
            }
        }
        if (state.switchU && !noError) {
            state.raise("Incomplete quantifier");
        }
        state.pos = start;
    }
    return false;
};
pp$8.regexp_eatAtom = function(state) {
    return this.regexp_eatPatternCharacters(state) || state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
};
pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
    var start = state.pos;
    if (state.eat(92)) {
        if (this.regexp_eatAtomEscape(state)) {
            return true;
        }
        state.pos = start;
    }
    return false;
};
pp$8.regexp_eatUncapturingGroup = function(state) {
    var start = state.pos;
    if (state.eat(40)) {
        if (state.eat(63) && state.eat(58)) {
            this.regexp_disjunction(state);
            if (state.eat(41)) {
                return true;
            }
            state.raise("Unterminated group");
        }
        state.pos = start;
    }
    return false;
};
pp$8.regexp_eatCapturingGroup = function(state) {
    if (state.eat(40)) {
        if (this.options.ecmaVersion >= 9) {
            this.regexp_groupSpecifier(state);
        } else if (state.current() === 63) {
            state.raise("Invalid group");
        }
        this.regexp_disjunction(state);
        if (state.eat(41)) {
            state.numCapturingParens += 1;
            return true;
        }
        state.raise("Unterminated group");
    }
    return false;
};
pp$8.regexp_eatExtendedAtom = function(state) {
    return state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
};
pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
    if (this.regexp_eatBracedQuantifier(state, true)) {
        state.raise("Nothing to repeat");
    }
    return false;
};
pp$8.regexp_eatSyntaxCharacter = function(state) {
    var ch = state.current();
    if (isSyntaxCharacter(ch)) {
        state.lastIntValue = ch;
        state.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(state) {
    var start = state.pos;
    var ch = 0;
    while((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)){
        state.advance();
    }
    return state.pos !== start;
};
pp$8.regexp_eatExtendedPatternCharacter = function(state) {
    var ch = state.current();
    if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
        state.advance();
        return true;
    }
    return false;
};
pp$8.regexp_groupSpecifier = function(state) {
    if (state.eat(63)) {
        if (this.regexp_eatGroupName(state)) {
            if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
                state.raise("Duplicate capture group name");
            }
            state.groupNames.push(state.lastStringValue);
            return;
        }
        state.raise("Invalid group");
    }
};
pp$8.regexp_eatGroupName = function(state) {
    state.lastStringValue = "";
    if (state.eat(60)) {
        if (this.regexp_eatRegExpIdentifierName(state) && state.eat(62)) {
            return true;
        }
        state.raise("Invalid capture group name");
    }
    return false;
};
pp$8.regexp_eatRegExpIdentifierName = function(state) {
    state.lastStringValue = "";
    if (this.regexp_eatRegExpIdentifierStart(state)) {
        state.lastStringValue += codePointToString(state.lastIntValue);
        while(this.regexp_eatRegExpIdentifierPart(state)){
            state.lastStringValue += codePointToString(state.lastIntValue);
        }
        return true;
    }
    return false;
};
pp$8.regexp_eatRegExpIdentifierStart = function(state) {
    var start = state.pos;
    var forceU = this.options.ecmaVersion >= 11;
    var ch = state.current(forceU);
    state.advance(forceU);
    if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
        ch = state.lastIntValue;
    }
    if (isRegExpIdentifierStart(ch)) {
        state.lastIntValue = ch;
        return true;
    }
    state.pos = start;
    return false;
};
function isRegExpIdentifierStart(ch) {
    return isIdentifierStart(ch, true) || ch === 36 || ch === 95;
}
pp$8.regexp_eatRegExpIdentifierPart = function(state) {
    var start = state.pos;
    var forceU = this.options.ecmaVersion >= 11;
    var ch = state.current(forceU);
    state.advance(forceU);
    if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
        ch = state.lastIntValue;
    }
    if (isRegExpIdentifierPart(ch)) {
        state.lastIntValue = ch;
        return true;
    }
    state.pos = start;
    return false;
};
function isRegExpIdentifierPart(ch) {
    return isIdentifierChar(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$8.regexp_eatAtomEscape = function(state) {
    if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {
        return true;
    }
    if (state.switchU) {
        if (state.current() === 99) {
            state.raise("Invalid unicode escape");
        }
        state.raise("Invalid escape");
    }
    return false;
};
pp$8.regexp_eatBackReference = function(state) {
    var start = state.pos;
    if (this.regexp_eatDecimalEscape(state)) {
        var n = state.lastIntValue;
        if (state.switchU) {
            if (n > state.maxBackReference) {
                state.maxBackReference = n;
            }
            return true;
        }
        if (n <= state.numCapturingParens) {
            return true;
        }
        state.pos = start;
    }
    return false;
};
pp$8.regexp_eatKGroupName = function(state) {
    if (state.eat(107)) {
        if (this.regexp_eatGroupName(state)) {
            state.backReferenceNames.push(state.lastStringValue);
            return true;
        }
        state.raise("Invalid named reference");
    }
    return false;
};
pp$8.regexp_eatCharacterEscape = function(state) {
    return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
};
pp$8.regexp_eatCControlLetter = function(state) {
    var start = state.pos;
    if (state.eat(99)) {
        if (this.regexp_eatControlLetter(state)) {
            return true;
        }
        state.pos = start;
    }
    return false;
};
pp$8.regexp_eatZero = function(state) {
    if (state.current() === 48 && !isDecimalDigit(state.lookahead())) {
        state.lastIntValue = 0;
        state.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatControlEscape = function(state) {
    var ch = state.current();
    if (ch === 116) {
        state.lastIntValue = 9;
        state.advance();
        return true;
    }
    if (ch === 110) {
        state.lastIntValue = 10;
        state.advance();
        return true;
    }
    if (ch === 118) {
        state.lastIntValue = 11;
        state.advance();
        return true;
    }
    if (ch === 102) {
        state.lastIntValue = 12;
        state.advance();
        return true;
    }
    if (ch === 114) {
        state.lastIntValue = 13;
        state.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatControlLetter = function(state) {
    var ch = state.current();
    if (isControlLetter(ch)) {
        state.lastIntValue = ch % 32;
        state.advance();
        return true;
    }
    return false;
};
function isControlLetter(ch) {
    return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
    if (forceU === void 0) forceU = false;
    var start = state.pos;
    var switchU = forceU || state.switchU;
    if (state.eat(117)) {
        if (this.regexp_eatFixedHexDigits(state, 4)) {
            var lead = state.lastIntValue;
            if (switchU && lead >= 55296 && lead <= 56319) {
                var leadSurrogateEnd = state.pos;
                if (state.eat(92) && state.eat(117) && this.regexp_eatFixedHexDigits(state, 4)) {
                    var trail = state.lastIntValue;
                    if (trail >= 56320 && trail <= 57343) {
                        state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
                        return true;
                    }
                }
                state.pos = leadSurrogateEnd;
                state.lastIntValue = lead;
            }
            return true;
        }
        if (switchU && state.eat(123) && this.regexp_eatHexDigits(state) && state.eat(125) && isValidUnicode(state.lastIntValue)) {
            return true;
        }
        if (switchU) {
            state.raise("Invalid unicode escape");
        }
        state.pos = start;
    }
    return false;
};
function isValidUnicode(ch) {
    return ch >= 0 && ch <= 1114111;
}
pp$8.regexp_eatIdentityEscape = function(state) {
    if (state.switchU) {
        if (this.regexp_eatSyntaxCharacter(state)) {
            return true;
        }
        if (state.eat(47)) {
            state.lastIntValue = 47;
            return true;
        }
        return false;
    }
    var ch = state.current();
    if (ch !== 99 && (!state.switchN || ch !== 107)) {
        state.lastIntValue = ch;
        state.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatDecimalEscape = function(state) {
    state.lastIntValue = 0;
    var ch = state.current();
    if (ch >= 49 && ch <= 57) {
        do {
            state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
            state.advance();
        }while ((ch = state.current()) >= 48 && ch <= 57)
        return true;
    }
    return false;
};
pp$8.regexp_eatCharacterClassEscape = function(state) {
    var ch = state.current();
    if (isCharacterClassEscape(ch)) {
        state.lastIntValue = -1;
        state.advance();
        return true;
    }
    if (state.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) {
        state.lastIntValue = -1;
        state.advance();
        if (state.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(125)) {
            return true;
        }
        state.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(state) {
    var start = state.pos;
    if (this.regexp_eatUnicodePropertyName(state) && state.eat(61)) {
        var name = state.lastStringValue;
        if (this.regexp_eatUnicodePropertyValue(state)) {
            var value = state.lastStringValue;
            this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
            return true;
        }
    }
    state.pos = start;
    if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
        var nameOrValue = state.lastStringValue;
        this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
        return true;
    }
    return false;
};
pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
    if (!has(state.unicodeProperties.nonBinary, name)) {
        state.raise("Invalid property name");
    }
    if (!state.unicodeProperties.nonBinary[name].test(value)) {
        state.raise("Invalid property value");
    }
};
pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
    if (!state.unicodeProperties.binary.test(nameOrValue)) {
        state.raise("Invalid property name");
    }
};
pp$8.regexp_eatUnicodePropertyName = function(state) {
    var ch = 0;
    state.lastStringValue = "";
    while(isUnicodePropertyNameCharacter(ch = state.current())){
        state.lastStringValue += codePointToString(ch);
        state.advance();
    }
    return state.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter(ch) {
    return isControlLetter(ch) || ch === 95;
}
pp$8.regexp_eatUnicodePropertyValue = function(state) {
    var ch = 0;
    state.lastStringValue = "";
    while(isUnicodePropertyValueCharacter(ch = state.current())){
        state.lastStringValue += codePointToString(ch);
        state.advance();
    }
    return state.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter(ch) {
    return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch);
}
pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
    return this.regexp_eatUnicodePropertyValue(state);
};
pp$8.regexp_eatCharacterClass = function(state) {
    if (state.eat(91)) {
        state.eat(94);
        this.regexp_classRanges(state);
        if (state.eat(93)) {
            return true;
        }
        state.raise("Unterminated character class");
    }
    return false;
};
pp$8.regexp_classRanges = function(state) {
    while(this.regexp_eatClassAtom(state)){
        var left = state.lastIntValue;
        if (state.eat(45) && this.regexp_eatClassAtom(state)) {
            var right = state.lastIntValue;
            if (state.switchU && (left === -1 || right === -1)) {
                state.raise("Invalid character class");
            }
            if (left !== -1 && right !== -1 && left > right) {
                state.raise("Range out of order in character class");
            }
        }
    }
};
pp$8.regexp_eatClassAtom = function(state) {
    var start = state.pos;
    if (state.eat(92)) {
        if (this.regexp_eatClassEscape(state)) {
            return true;
        }
        if (state.switchU) {
            var ch$1 = state.current();
            if (ch$1 === 99 || isOctalDigit(ch$1)) {
                state.raise("Invalid class escape");
            }
            state.raise("Invalid escape");
        }
        state.pos = start;
    }
    var ch = state.current();
    if (ch !== 93) {
        state.lastIntValue = ch;
        state.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatClassEscape = function(state) {
    var start = state.pos;
    if (state.eat(98)) {
        state.lastIntValue = 8;
        return true;
    }
    if (state.switchU && state.eat(45)) {
        state.lastIntValue = 45;
        return true;
    }
    if (!state.switchU && state.eat(99)) {
        if (this.regexp_eatClassControlLetter(state)) {
            return true;
        }
        state.pos = start;
    }
    return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
};
pp$8.regexp_eatClassControlLetter = function(state) {
    var ch = state.current();
    if (isDecimalDigit(ch) || ch === 95) {
        state.lastIntValue = ch % 32;
        state.advance();
        return true;
    }
    return false;
};
pp$8.regexp_eatHexEscapeSequence = function(state) {
    var start = state.pos;
    if (state.eat(120)) {
        if (this.regexp_eatFixedHexDigits(state, 2)) {
            return true;
        }
        if (state.switchU) {
            state.raise("Invalid escape");
        }
        state.pos = start;
    }
    return false;
};
pp$8.regexp_eatDecimalDigits = function(state) {
    var start = state.pos;
    var ch = 0;
    state.lastIntValue = 0;
    while(isDecimalDigit(ch = state.current())){
        state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
        state.advance();
    }
    return state.pos !== start;
};
function isDecimalDigit(ch) {
    return ch >= 48 && ch <= 57;
}
pp$8.regexp_eatHexDigits = function(state) {
    var start = state.pos;
    var ch = 0;
    state.lastIntValue = 0;
    while(isHexDigit(ch = state.current())){
        state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
        state.advance();
    }
    return state.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(state) {
    if (this.regexp_eatOctalDigit(state)) {
        var n1 = state.lastIntValue;
        if (this.regexp_eatOctalDigit(state)) {
            var n2 = state.lastIntValue;
            if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
                state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
            } else {
                state.lastIntValue = n1 * 8 + n2;
            }
        } else {
            state.lastIntValue = n1;
        }
        return true;
    }
    return false;
};
pp$8.regexp_eatOctalDigit = function(state) {
    var ch = state.current();
    if (isOctalDigit(ch)) {
        state.lastIntValue = ch - 48;
        state.advance();
        return true;
    }
    state.lastIntValue = 0;
    return false;
};
function isOctalDigit(ch) {
    return ch >= 48 && ch <= 55;
}
pp$8.regexp_eatFixedHexDigits = function(state, length) {
    var start = state.pos;
    state.lastIntValue = 0;
    for(var i1 = 0; i1 < length; ++i1){
        var ch = state.current();
        if (!isHexDigit(ch)) {
            state.pos = start;
            return false;
        }
        state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
        state.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 === types1.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(types1.eof);
    }
    if (curContext.override) {
        return curContext.override(this);
    } else {
        this.readToken(this.fullCharCodeAtPos());
    }
};
pp$9.readToken = function(code) {
    if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92) {
        return this.readWord();
    }
    return this.getTokenFromCode(code);
};
pp$9.fullCharCodeAtPos = function() {
    var code = this.input.charCodeAt(this.pos);
    if (code <= 55295 || code >= 57344) {
        return code;
    }
    var next = this.input.charCodeAt(this.pos + 1);
    return (code << 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(types1.ellipsis);
    } else {
        ++this.pos;
        return this.finishToken(types1.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(types1.assign, 2);
    }
    return this.finishOp(types1.slash, 1);
};
pp$9.readToken_mult_modulo_exp = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    var size = 1;
    var tokentype = code === 42 ? types1.star : types1.modulo;
    if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
        ++size;
        tokentype = types1.starstar;
        next = this.input.charCodeAt(this.pos + 2);
    }
    if (next === 61) {
        return this.finishOp(types1.assign, size + 1);
    }
    return this.finishOp(tokentype, size);
};
pp$9.readToken_pipe_amp = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === code) {
        if (this.options.ecmaVersion >= 12) {
            var next2 = this.input.charCodeAt(this.pos + 2);
            if (next2 === 61) {
                return this.finishOp(types1.assign, 3);
            }
        }
        return this.finishOp(code === 124 ? types1.logicalOR : types1.logicalAND, 2);
    }
    if (next === 61) {
        return this.finishOp(types1.assign, 2);
    }
    return this.finishOp(code === 124 ? types1.bitwiseOR : types1.bitwiseAND, 1);
};
pp$9.readToken_caret = function() {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 61) {
        return this.finishOp(types1.assign, 2);
    }
    return this.finishOp(types1.bitwiseXOR, 1);
};
pp$9.readToken_plus_min = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === code) {
        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(types1.incDec, 2);
    }
    if (next === 61) {
        return this.finishOp(types1.assign, 2);
    }
    return this.finishOp(types1.plusMin, 1);
};
pp$9.readToken_lt_gt = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    var size = 1;
    if (next === code) {
        size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
        if (this.input.charCodeAt(this.pos + size) === 61) {
            return this.finishOp(types1.assign, size + 1);
        }
        return this.finishOp(types1.bitShift, size);
    }
    if (next === 33 && code === 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(types1.relational, size);
};
pp$9.readToken_eq_excl = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === 61) {
        return this.finishOp(types1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
    }
    if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
        this.pos += 2;
        return this.finishToken(types1.arrow);
    }
    return this.finishOp(code === 61 ? types1.eq : types1.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(types1.questionDot, 2);
            }
        }
        if (next === 63) {
            if (ecmaVersion >= 12) {
                var next2$1 = this.input.charCodeAt(this.pos + 2);
                if (next2$1 === 61) {
                    return this.finishOp(types1.assign, 3);
                }
            }
            return this.finishOp(types1.coalesce, 2);
        }
    }
    return this.finishOp(types1.question, 1);
};
pp$9.getTokenFromCode = function(code) {
    switch(code){
        case 46:
            return this.readToken_dot();
        case 40:
            ++this.pos;
            return this.finishToken(types1.parenL);
        case 41:
            ++this.pos;
            return this.finishToken(types1.parenR);
        case 59:
            ++this.pos;
            return this.finishToken(types1.semi);
        case 44:
            ++this.pos;
            return this.finishToken(types1.comma);
        case 91:
            ++this.pos;
            return this.finishToken(types1.bracketL);
        case 93:
            ++this.pos;
            return this.finishToken(types1.bracketR);
        case 123:
            ++this.pos;
            return this.finishToken(types1.braceL);
        case 125:
            ++this.pos;
            return this.finishToken(types1.braceR);
        case 58:
            ++this.pos;
            return this.finishToken(types1.colon);
        case 96:
            if (this.options.ecmaVersion < 6) {
                break;
            }
            ++this.pos;
            return this.finishToken(types1.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(code);
        case 47:
            return this.readToken_slash();
        case 37:
        case 42:
            return this.readToken_mult_modulo_exp(code);
        case 124:
        case 38:
            return this.readToken_pipe_amp(code);
        case 94:
            return this.readToken_caret();
        case 43:
        case 45:
            return this.readToken_plus_min(code);
        case 60:
        case 62:
            return this.readToken_lt_gt(code);
        case 61:
        case 33:
            return this.readToken_eq_excl(code);
        case 63:
            return this.readToken_question();
        case 126:
            return this.finishOp(types1.prefix, 1);
    }
    this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
};
pp$9.finishOp = function(type, size) {
    var str = this.input.slice(this.pos, this.pos + size);
    this.pos += size;
    return this.finishToken(type, str);
};
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 state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
    state.reset(start, pattern, flags);
    this.validateRegExpFlags(state);
    this.validateRegExpPattern(state);
    var value = null;
    try {
        value = new RegExp(pattern, flags);
    } catch (e) {}
    return this.finishToken(types1.regexp, {
        pattern,
        flags,
        value
    });
};
pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
    var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
    var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
    var start = this.pos, total = 0, lastCode = 0;
    for(var i1 = 0, e = len == null ? Infinity : len; i1 < e; ++i1, ++this.pos){
        var code = this.input.charCodeAt(this.pos), val = void 0;
        if (allowSeparators && code === 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 (i1 === 0) {
                this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
            }
            lastCode = code;
            continue;
        }
        if (code >= 97) {
            val = code - 97 + 10;
        } else if (code >= 65) {
            val = code - 65 + 10;
        } else if (code >= 48 && code <= 57) {
            val = code - 48;
        } else {
            val = Infinity;
        }
        if (val >= radix) {
            break;
        }
        lastCode = code;
        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 || len != null && this.pos - start !== len) {
        return null;
    }
    return total;
};
function stringToNumber(str, isLegacyOctalNumericLiteral) {
    if (isLegacyOctalNumericLiteral) {
        return parseInt(str, 8);
    }
    return parseFloat(str.replace(/_/g, ""));
}
function stringToBigInt(str) {
    if (typeof BigInt !== "function") {
        return null;
    }
    return BigInt(str.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(types1.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(types1.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(types1.num, val);
};
pp$9.readCodePoint = function() {
    var ch = this.input.charCodeAt(this.pos), code;
    if (ch === 123) {
        if (this.options.ecmaVersion < 6) {
            this.unexpected();
        }
        var codePos = ++this.pos;
        code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
        ++this.pos;
        if (code > 1114111) {
            this.invalidStringToken(codePos, "Code point out of bounds");
        }
    } else {
        code = this.readHexChar(4);
    }
    return code;
};
function codePointToString$1(code) {
    if (code <= 65535) {
        return String.fromCharCode(code);
    }
    code -= 65536;
    return String.fromCharCode((code >> 10) + 55296, (code & 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(types1.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 === types1.template || this.type === types1.invalidTemplate)) {
                if (ch === 36) {
                    this.pos += 2;
                    return this.finishToken(types1.dollarBraceL);
                } else {
                    ++this.pos;
                    return this.finishToken(types1.backQuote);
                }
            }
            out += this.input.slice(chunkStart, this.pos);
            return this.finishToken(types1.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(types1.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(len) {
    var codePos = this.pos;
    var n = this.readInt(16, len);
    if (n === null) {
        this.invalidStringToken(codePos, "Bad character escape sequence");
    }
    return n;
};
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 = types1.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: types1,
    keywordTypes: keywords$1,
    TokContext,
    tokContexts: types$1,
    isIdentifierChar,
    isIdentifierStart,
    Token,
    isNewLine,
    lineBreak,
    lineBreakG,
    nonASCIIwhitespace
};
function simple(node, visitors, baseVisitor, state, 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, state, override);
}
function ancestor(node, visitors, baseVisitor, state, 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, state, override);
}
var create = Object.create || function(proto) {
    function Ctor() {}
    Ctor.prototype = proto;
    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 i1 = 0, list = node.body; i1 < list.length; i1 += 1){
        var stmt = list[i1];
        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 i1 = 0, list = cs.consequent; i1 < list.length; i1 += 1){
            var cons = list[i1];
            c(cons, st, "Statement");
        }
    }
};
base.SwitchCase = function(node, st, c) {
    if (node.test) {
        c(node.test, st, "Expression");
    }
    for(var i1 = 0, list = node.consequent; i1 < list.length; i1 += 1){
        var cons = list[i1];
        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 i1 = 0, list = node.declarations; i1 < list.length; i1 += 1){
        var decl = list[i1];
        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 i1 = 0, list = node.params; i1 < list.length; i1 += 1){
        var param = list[i1];
        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 i1 = 0, list = node.elements; i1 < list.length; i1 += 1){
        var elt = list[i1];
        if (elt) {
            c(elt, st, "Pattern");
        }
    }
};
base.ObjectPattern = function(node, st, c) {
    for(var i1 = 0, list = node.properties; i1 < list.length; i1 += 1){
        var prop = list[i1];
        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 i1 = 0, list = node.elements; i1 < list.length; i1 += 1){
        var elt = list[i1];
        if (elt) {
            c(elt, st, "Expression");
        }
    }
};
base.ObjectExpression = function(node, st, c) {
    for(var i1 = 0, list = node.properties; i1 < list.length; i1 += 1){
        var prop = list[i1];
        c(prop, st);
    }
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function(node, st, c) {
    for(var i1 = 0, list = node.expressions; i1 < list.length; i1 += 1){
        var expr = list[i1];
        c(expr, st, "Expression");
    }
};
base.TemplateLiteral = function(node, st, c) {
    for(var i1 = 0, list = node.quasis; i1 < list.length; i1 += 1){
        var quasi = list[i1];
        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 i1 = 0, list = node.arguments; i1 < list.length; i1 += 1){
            var arg = list[i1];
            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 i1 = 0, list = node.specifiers; i1 < list.length; i1 += 1){
        var spec = list[i1];
        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 i1 = 0, list = node.body; i1 < list.length; i1 += 1){
        var elt = list[i1];
        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, name) {
        const l1 = locals.get(node);
        return l1 ? l1.has(name) : false;
    }
    function declareLocal(node, id) {
        const l1 = locals.get(node);
        if (l1) l1.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 i1 = parents.length - 1; i1 >= 0 && parent === null; --i1){
                if (node.kind === "var" ? isScope(parents[i1]) : isBlockScope(parents[i1])) {
                    parent = parents[i1];
                }
            }
            node.declarations.forEach((declaration)=>declarePattern(declaration.id, parent));
        },
        FunctionDeclaration: (node, parents)=>{
            let parent = null;
            for(let i1 = parents.length - 2; i1 >= 0 && parent === null; --i1){
                if (isScope(parents[i1])) {
                    parent = parents[i1];
                }
            }
            declareLocal(parent, node.id);
            declareFunction(node);
        },
        Function: declareFunction,
        ClassDeclaration: (node, parents)=>{
            let parent = null;
            for(let i1 = parents.length - 2; i1 >= 0 && parent === null; i1--){
                if (isScope(parents[i1])) {
                    parent = parents[i1];
                }
            }
            declareLocal(parent, node.id);
        },
        Class: declareClass,
        CatchClause: declareCatchClause,
        ImportDefaultSpecifier: declareModuleSpecifier,
        ImportSpecifier: declareModuleSpecifier,
        ImportNamespaceSpecifier: declareModuleSpecifier
    }, walk);
    function identifier(node, parents) {
        let name = node.name;
        if (name === "undefined") return;
        for(let i1 = parents.length - 2; i1 >= 0; --i1){
            if (name === "arguments") {
                if (declaresArguments(parents[i1])) {
                    return;
                }
            }
            if (hasLocal(parents[i1], name)) {
                return;
            }
            if (parents[i1].type === "ViewExpression") {
                node = parents[i1];
                name = `viewof ${node.id.name}`;
            }
            if (parents[i1].type === "MutableExpression") {
                node = parents[i1];
                name = `mutable ${node.id.name}`;
            }
        }
        if (!globalSet.has(name)) {
            if (name === "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 property of node.properties){
                        checkConst(property, 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 name = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked;
            const location = {
                start: arg.start,
                end: arg.end
            };
            if (features.has(name)) features.get(name).push(location);
            else features.set(name, [
                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, init) {
        if (this.O_function === 1 && node.await) this.O_async = true;
        return super.parseForIn(node, init);
    }
    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 === types1._with) {
            this.next();
            node.injections = this.parseImportSpecifiers();
        }
        this.expectContextual("from");
        node.source = this.type === types1.string ? this.parseExprAtom() : this.unexpected();
        return this.finishNode(node, "ImportDeclaration");
    }
    parseImportSpecifiers() {
        const nodes = [];
        const identifiers = new Set();
        let first = true;
        this.expect(types1.braceL);
        while(!this.eat(types1.braceR)){
            if (first) {
                first = false;
            } else {
                this.expect(types1.comma);
                if (this.afterTrailingComma(types1.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 === types1._import && lookahead.getToken().type !== types1.parenL) {
            body = this.parseImport(this.startNode());
        } else if (token.type !== types1.eof && token.type !== types1.semi) {
            if (token.type === types1.name) {
                if (token.value === "viewof" || token.value === "mutable") {
                    token = lookahead.getToken();
                    if (token.type !== types1.name) {
                        lookahead.unexpected();
                    }
                }
                token = lookahead.getToken();
                if (token.type === types1.eq) {
                    id = this.parseMaybeKeywordExpression("viewof", "ViewExpression") || this.parseMaybeKeywordExpression("mutable", "MutableExpression") || this.parseIdent();
                    token = lookahead.getToken();
                    this.expect(types1.eq);
                }
            }
            if (token.type === types1.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(types1.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 === types1.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 === types1.invalidTemplate) {
                            this.pos += 2;
                            return this.finishToken(types1.dollarBraceL);
                        }
                        break out;
                    }
                    break;
                }
        }
    }
    return this.finishToken(types1.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 !== types1.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((i1)=>i1.imported) : [];
    } else {
        try {
            cell.references = findReferences(cell, globals);
        } catch (error) {
            if (error.node) {
                const loc = getLineInfo(input, error.node.start);
                error.message += ` (${loc.line}:${loc.column})`;
                error.pos = error.node.start;
                error.loc = loc;
                delete error.node;
            }
            throw error;
        }
    }
    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 (error) {
            if (error.node) {
                const loc = getLineInfo(input, error.node.start);
                error.message += ` (${loc.line}:${loc.column})`;
                error.pos = error.node.start;
                error.loc = loc;
                delete error.node;
            }
            throw error;
        }
    } else {
        cell.fileAttachments = new Map();
        cell.databaseClients = new Map();
        cell.secrets = new Map();
    }
    return cell;
}
var reservedWords1 = {
    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 ecma5AndLessKeywords1 = "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 keywords1 = {
    5: ecma5AndLessKeywords1,
    "5module": ecma5AndLessKeywords1 + " export import",
    6: ecma5AndLessKeywords1 + " const class extends export import super"
};
var keywordRelationalOperator1 = /^in(stanceof)?$/;
var nonASCIIidentifierStartChars1 = "\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-\u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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 nonASCIIidentifierChars1 = "\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 nonASCIIidentifierStart1 = new RegExp("[" + nonASCIIidentifierStartChars1 + "]");
var nonASCIIidentifier1 = new RegExp("[" + nonASCIIidentifierStartChars1 + nonASCIIidentifierChars1 + "]");
nonASCIIidentifierStartChars1 = nonASCIIidentifierChars1 = null;
var astralIdentifierStartCodes1 = [
    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 astralIdentifierCodes1 = [
    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 isInAstralSet1(code, set) {
    var pos = 65536;
    for(var i1 = 0; i1 < set.length; i1 += 2){
        pos += set[i1];
        if (pos > code) {
            return false;
        }
        pos += set[i1 + 1];
        if (pos >= code) {
            return true;
        }
    }
}
function isIdentifierStart1(code, astral) {
    if (code < 65) {
        return code === 36;
    }
    if (code < 91) {
        return true;
    }
    if (code < 97) {
        return code === 95;
    }
    if (code < 123) {
        return true;
    }
    if (code <= 65535) {
        return code >= 170 && nonASCIIidentifierStart1.test(String.fromCharCode(code));
    }
    if (astral === false) {
        return false;
    }
    return isInAstralSet1(code, astralIdentifierStartCodes1);
}
function isIdentifierChar1(code, astral) {
    if (code < 48) {
        return code === 36;
    }
    if (code < 58) {
        return true;
    }
    if (code < 65) {
        return false;
    }
    if (code < 91) {
        return true;
    }
    if (code < 97) {
        return code === 95;
    }
    if (code < 123) {
        return true;
    }
    if (code <= 65535) {
        return code >= 170 && nonASCIIidentifier1.test(String.fromCharCode(code));
    }
    if (astral === false) {
        return false;
    }
    return isInAstralSet1(code, astralIdentifierStartCodes1) || isInAstralSet1(code, astralIdentifierCodes1);
}
var TokenType1 = 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 binop1(name, prec) {
    return new TokenType1(name, {
        beforeExpr: true,
        binop: prec
    });
}
var beforeExpr1 = {
    beforeExpr: true
}, startsExpr1 = {
    startsExpr: true
};
var keywords$11 = {};
function kw1(name, options) {
    if (options === void 0) options = {};
    options.keyword = name;
    return keywords$11[name] = new TokenType1(name, options);
}
var types2 = {
    num: new TokenType1("num", startsExpr1),
    regexp: new TokenType1("regexp", startsExpr1),
    string: new TokenType1("string", startsExpr1),
    name: new TokenType1("name", startsExpr1),
    privateId: new TokenType1("privateId", startsExpr1),
    eof: new TokenType1("eof"),
    bracketL: new TokenType1("[", {
        beforeExpr: true,
        startsExpr: true
    }),
    bracketR: new TokenType1("]"),
    braceL: new TokenType1("{", {
        beforeExpr: true,
        startsExpr: true
    }),
    braceR: new TokenType1("}"),
    parenL: new TokenType1("(", {
        beforeExpr: true,
        startsExpr: true
    }),
    parenR: new TokenType1(")"),
    comma: new TokenType1(",", beforeExpr1),
    semi: new TokenType1(";", beforeExpr1),
    colon: new TokenType1(":", beforeExpr1),
    dot: new TokenType1("."),
    question: new TokenType1("?", beforeExpr1),
    questionDot: new TokenType1("?."),
    arrow: new TokenType1("=>", beforeExpr1),
    template: new TokenType1("template"),
    invalidTemplate: new TokenType1("invalidTemplate"),
    ellipsis: new TokenType1("...", beforeExpr1),
    backQuote: new TokenType1("`", startsExpr1),
    dollarBraceL: new TokenType1("${", {
        beforeExpr: true,
        startsExpr: true
    }),
    eq: new TokenType1("=", {
        beforeExpr: true,
        isAssign: true
    }),
    assign: new TokenType1("_=", {
        beforeExpr: true,
        isAssign: true
    }),
    incDec: new TokenType1("++/--", {
        prefix: true,
        postfix: true,
        startsExpr: true
    }),
    prefix: new TokenType1("!/~", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    }),
    logicalOR: binop1("||", 1),
    logicalAND: binop1("&&", 2),
    bitwiseOR: binop1("|", 3),
    bitwiseXOR: binop1("^", 4),
    bitwiseAND: binop1("&", 5),
    equality: binop1("==/!=/===/!==", 6),
    relational: binop1("</>/<=/>=", 7),
    bitShift: binop1("<</>>/>>>", 8),
    plusMin: new TokenType1("+/-", {
        beforeExpr: true,
        binop: 9,
        prefix: true,
        startsExpr: true
    }),
    modulo: binop1("%", 10),
    star: binop1("*", 10),
    slash: binop1("/", 10),
    starstar: new TokenType1("**", {
        beforeExpr: true
    }),
    coalesce: binop1("??", 1),
    _break: kw1("break"),
    _case: kw1("case", beforeExpr1),
    _catch: kw1("catch"),
    _continue: kw1("continue"),
    _debugger: kw1("debugger"),
    _default: kw1("default", beforeExpr1),
    _do: kw1("do", {
        isLoop: true,
        beforeExpr: true
    }),
    _else: kw1("else", beforeExpr1),
    _finally: kw1("finally"),
    _for: kw1("for", {
        isLoop: true
    }),
    _function: kw1("function", startsExpr1),
    _if: kw1("if"),
    _return: kw1("return", beforeExpr1),
    _switch: kw1("switch"),
    _throw: kw1("throw", beforeExpr1),
    _try: kw1("try"),
    _var: kw1("var"),
    _const: kw1("const"),
    _while: kw1("while", {
        isLoop: true
    }),
    _with: kw1("with"),
    _new: kw1("new", {
        beforeExpr: true,
        startsExpr: true
    }),
    _this: kw1("this", startsExpr1),
    _super: kw1("super", startsExpr1),
    _class: kw1("class", startsExpr1),
    _extends: kw1("extends", beforeExpr1),
    _export: kw1("export"),
    _import: kw1("import", startsExpr1),
    _null: kw1("null", startsExpr1),
    _true: kw1("true", startsExpr1),
    _false: kw1("false", startsExpr1),
    _in: kw1("in", {
        beforeExpr: true,
        binop: 7
    }),
    _instanceof: kw1("instanceof", {
        beforeExpr: true,
        binop: 7
    }),
    _typeof: kw1("typeof", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    }),
    _void: kw1("void", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    }),
    _delete: kw1("delete", {
        beforeExpr: true,
        prefix: true,
        startsExpr: true
    })
};
var lineBreak1 = /\r\n?|\n|\u2028|\u2029/;
var lineBreakG1 = new RegExp(lineBreak1.source, "g");
function isNewLine1(code, ecma2019String) {
    return code === 10 || code === 13 || !ecma2019String && (code === 8232 || code === 8233);
}
var nonASCIIwhitespace1 = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
var skipWhiteSpace1 = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
var ref1 = Object.prototype;
var hasOwnProperty16 = ref1.hasOwnProperty;
var toString3 = ref1.toString;
function has1(obj, propName) {
    return hasOwnProperty16.call(obj, propName);
}
var isArray2 = Array.isArray || function(obj) {
    return toString3.call(obj) === "[object Array]";
};
function wordsRegexp1(words) {
    return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$");
}
var Position1 = function Position2(line, col) {
    this.line = line;
    this.column = col;
};
Position1.prototype.offset = function offset(n) {
    return new Position1(this.line, this.column + n);
};
var SourceLocation1 = function SourceLocation2(p, start, end) {
    this.start = start;
    this.end = end;
    if (p.sourceFile !== null) {
        this.source = p.sourceFile;
    }
};
function getLineInfo1(input, offset2) {
    for(var line = 1, cur = 0;;){
        lineBreakG1.lastIndex = cur;
        var match = lineBreakG1.exec(input);
        if (match && match.index < offset2) {
            ++line;
            cur = match.index + match[0].length;
        } else {
            return new Position1(line, offset2 - cur);
        }
    }
}
var defaultOptions1 = {
    ecmaVersion: null,
    sourceType: "script",
    onInsertedSemicolon: null,
    onTrailingComma: null,
    allowReserved: null,
    allowReturnOutsideFunction: false,
    allowImportExportEverywhere: false,
    allowAwaitOutsideFunction: null,
    allowSuperOutsideMethod: null,
    allowHashBang: false,
    locations: false,
    onToken: null,
    onComment: null,
    ranges: false,
    program: null,
    sourceFile: null,
    directSourceFile: null,
    preserveParens: false
};
var warnedAboutEcmaVersion = false;
function getOptions1(opts) {
    var options = {};
    for(var opt in defaultOptions1){
        options[opt] = opts && has1(opts, opt) ? opts[opt] : defaultOptions1[opt];
    }
    if (options.ecmaVersion === "latest") {
        options.ecmaVersion = 1e8;
    } else if (options.ecmaVersion == null) {
        if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
            warnedAboutEcmaVersion = true;
            console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
        }
        options.ecmaVersion = 11;
    } else if (options.ecmaVersion >= 2015) {
        options.ecmaVersion -= 2009;
    }
    if (options.allowReserved == null) {
        options.allowReserved = options.ecmaVersion < 5;
    }
    if (options.allowAwaitOutsideFunction == null) {
        options.allowAwaitOutsideFunction = options.ecmaVersion >= 13;
    }
    if (isArray2(options.onToken)) {
        var tokens = options.onToken;
        options.onToken = function(token) {
            return tokens.push(token);
        };
    }
    if (isArray2(options.onComment)) {
        options.onComment = pushComment1(options, options.onComment);
    }
    return options;
}
function pushComment1(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 SourceLocation1(this, startLoc, endLoc);
        }
        if (options.ranges) {
            comment.range = [
                start,
                end
            ];
        }
        array.push(comment);
    };
}
var SCOPE_TOP1 = 1, SCOPE_FUNCTION1 = 2, SCOPE_VAR1 = SCOPE_TOP1 | SCOPE_FUNCTION1, SCOPE_ASYNC1 = 4, SCOPE_GENERATOR1 = 8, SCOPE_ARROW1 = 16, SCOPE_SIMPLE_CATCH1 = 32, SCOPE_SUPER1 = 64, SCOPE_DIRECT_SUPER1 = 128;
function functionFlags1(async, generator) {
    return SCOPE_FUNCTION1 | (async ? SCOPE_ASYNC1 : 0) | (generator ? SCOPE_GENERATOR1 : 0);
}
var BIND_NONE1 = 0, BIND_VAR1 = 1, BIND_LEXICAL1 = 2, BIND_FUNCTION1 = 3, BIND_SIMPLE_CATCH1 = 4, BIND_OUTSIDE1 = 5;
var Parser1 = function Parser2(options, input, startPos) {
    this.options = options = getOptions1(options);
    this.sourceFile = options.sourceFile;
    this.keywords = wordsRegexp1(keywords1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
    var reserved = "";
    if (options.allowReserved !== true) {
        reserved = reservedWords1[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
        if (options.sourceType === "module") {
            reserved += " await";
        }
    }
    this.reservedWords = wordsRegexp1(reserved);
    var reservedStrict = (reserved ? reserved + " " : "") + reservedWords1.strict;
    this.reservedWordsStrict = wordsRegexp1(reservedStrict);
    this.reservedWordsStrictBind = wordsRegexp1(reservedStrict + " " + reservedWords1.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(lineBreak1).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.potentialArrowInForAwait = false;
    this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
    this.labels = [];
    this.undefinedExports = Object.create(null);
    if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") {
        this.skipLineComment(2);
    }
    this.scopeStack = [];
    this.enterScope(SCOPE_TOP1);
    this.regexpState = null;
    this.privateNameStack = [];
};
var prototypeAccessors1 = {
    inFunction: {
        configurable: true
    },
    inGenerator: {
        configurable: true
    },
    inAsync: {
        configurable: true
    },
    allowSuper: {
        configurable: true
    },
    allowDirectSuper: {
        configurable: true
    },
    treatFunctionsAsVar: {
        configurable: true
    },
    inNonArrowFunction: {
        configurable: true
    }
};
Parser1.prototype.parse = function parse() {
    var node = this.options.program || this.startNode();
    this.nextToken();
    return this.parseTopLevel(node);
};
prototypeAccessors1.inFunction.get = function() {
    return (this.currentVarScope().flags & SCOPE_FUNCTION1) > 0;
};
prototypeAccessors1.inGenerator.get = function() {
    return (this.currentVarScope().flags & SCOPE_GENERATOR1) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors1.inAsync.get = function() {
    return (this.currentVarScope().flags & SCOPE_ASYNC1) > 0 && !this.currentVarScope().inClassFieldInit;
};
prototypeAccessors1.allowSuper.get = function() {
    var ref2 = this.currentThisScope();
    var flags = ref2.flags;
    var inClassFieldInit = ref2.inClassFieldInit;
    return (flags & SCOPE_SUPER1) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod;
};
prototypeAccessors1.allowDirectSuper.get = function() {
    return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER1) > 0;
};
prototypeAccessors1.treatFunctionsAsVar.get = function() {
    return this.treatFunctionsAsVarInScope(this.currentScope());
};
prototypeAccessors1.inNonArrowFunction.get = function() {
    var ref2 = this.currentThisScope();
    var flags = ref2.flags;
    var inClassFieldInit = ref2.inClassFieldInit;
    return (flags & SCOPE_FUNCTION1) > 0 || inClassFieldInit;
};
Parser1.extend = function extend() {
    var plugins = [], len = arguments.length;
    while(len--)plugins[len] = arguments[len];
    var cls = this;
    for(var i1 = 0; i1 < plugins.length; i1++){
        cls = plugins[i1](cls);
    }
    return cls;
};
Parser1.parse = function parse2(input, options) {
    return new this(options, input).parse();
};
Parser1.parseExpressionAt = function parseExpressionAt(input, pos, options) {
    var parser = new this(options, input, pos);
    parser.nextToken();
    return parser.parseExpression();
};
Parser1.tokenizer = function tokenizer(input, options) {
    return new this(options, input);
};
Object.defineProperties(Parser1.prototype, prototypeAccessors1);
var pp1 = Parser1.prototype;
var literal1 = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
pp1.strictDirective = function(start) {
    for(;;){
        skipWhiteSpace1.lastIndex = start;
        start += skipWhiteSpace1.exec(this.input)[0].length;
        var match = literal1.exec(this.input.slice(start));
        if (!match) {
            return false;
        }
        if ((match[1] || match[2]) === "use strict") {
            skipWhiteSpace1.lastIndex = start + match[0].length;
            var spaceAfter = skipWhiteSpace1.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
            var next = this.input.charAt(end);
            return next === ";" || next === "}" || lineBreak1.test(spaceAfter[0]) && !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=");
        }
        start += match[0].length;
        skipWhiteSpace1.lastIndex = start;
        start += skipWhiteSpace1.exec(this.input)[0].length;
        if (this.input[start] === ";") {
            start++;
        }
    }
};
pp1.eat = function(type) {
    if (this.type === type) {
        this.next();
        return true;
    } else {
        return false;
    }
};
pp1.isContextual = function(name) {
    return this.type === types2.name && this.value === name && !this.containsEsc;
};
pp1.eatContextual = function(name) {
    if (!this.isContextual(name)) {
        return false;
    }
    this.next();
    return true;
};
pp1.expectContextual = function(name) {
    if (!this.eatContextual(name)) {
        this.unexpected();
    }
};
pp1.canInsertSemicolon = function() {
    return this.type === types2.eof || this.type === types2.braceR || lineBreak1.test(this.input.slice(this.lastTokEnd, this.start));
};
pp1.insertSemicolon = function() {
    if (this.canInsertSemicolon()) {
        if (this.options.onInsertedSemicolon) {
            this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
        }
        return true;
    }
};
pp1.semicolon = function() {
    if (!this.eat(types2.semi) && !this.insertSemicolon()) {
        this.unexpected();
    }
};
pp1.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;
    }
};
pp1.expect = function(type) {
    this.eat(type) || this.unexpected();
};
pp1.unexpected = function(pos) {
    this.raise(pos != null ? pos : this.start, "Unexpected token");
};
function DestructuringErrors1() {
    this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1;
}
pp1.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");
    }
};
pp1.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");
    }
};
pp1.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");
    }
};
pp1.isSimpleAssignTarget = function(expr) {
    if (expr.type === "ParenthesizedExpression") {
        return this.isSimpleAssignTarget(expr.expression);
    }
    return expr.type === "Identifier" || expr.type === "MemberExpression";
};
var pp$11 = Parser1.prototype;
pp$11.parseTopLevel = function(node) {
    var exports = Object.create(null);
    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 i1 = 0, list = Object.keys(this.undefinedExports); i1 < list.length; i1 += 1){
            var name = list[i1];
            this.raiseRecoverable(this.undefinedExports[name].start, "Export '" + name + "' is not defined");
        }
    }
    this.adaptDirectivePrologue(node.body);
    this.next();
    node.sourceType = this.options.sourceType;
    return this.finishNode(node, "Program");
};
var loopLabel1 = {
    kind: "loop"
}, switchLabel1 = {
    kind: "switch"
};
pp$11.isLet = function(context) {
    if (this.options.ecmaVersion < 6 || !this.isContextual("let")) {
        return false;
    }
    skipWhiteSpace1.lastIndex = this.pos;
    var skip = skipWhiteSpace1.exec(this.input);
    var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
    if (nextCh === 91 || nextCh === 92 || nextCh > 55295 && nextCh < 56320) {
        return true;
    }
    if (context) {
        return false;
    }
    if (nextCh === 123) {
        return true;
    }
    if (isIdentifierStart1(nextCh, true)) {
        var pos = next + 1;
        while(isIdentifierChar1(nextCh = this.input.charCodeAt(pos), true)){
            ++pos;
        }
        if (nextCh === 92 || nextCh > 55295 && nextCh < 56320) {
            return true;
        }
        var ident = this.input.slice(next, pos);
        if (!keywordRelationalOperator1.test(ident)) {
            return true;
        }
    }
    return false;
};
pp$11.isAsyncFunction = function() {
    if (this.options.ecmaVersion < 8 || !this.isContextual("async")) {
        return false;
    }
    skipWhiteSpace1.lastIndex = this.pos;
    var skip = skipWhiteSpace1.exec(this.input);
    var next = this.pos + skip[0].length, after;
    return !lineBreak1.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !(isIdentifierChar1(after = this.input.charCodeAt(next + 8)) || after > 55295 && after < 56320));
};
pp$11.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) {
                skipWhiteSpace1.lastIndex = this.pos;
                var skip = skipWhiteSpace1.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$11.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 i1 = 0;
    for(; i1 < this.labels.length; ++i1){
        var lab = this.labels[i1];
        if (node.label == null || lab.name === node.label.name) {
            if (lab.kind != null && (isBreak || lab.kind === "loop")) {
                break;
            }
            if (node.label && isBreak) {
                break;
            }
        }
    }
    if (i1 === this.labels.length) {
        this.raise(node.start, "Unsyntactic " + keyword);
    }
    return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
};
pp$11.parseDebuggerStatement = function(node) {
    this.next();
    this.semicolon();
    return this.finishNode(node, "DebuggerStatement");
};
pp$11.parseDoStatement = function(node) {
    this.next();
    this.labels.push(loopLabel1);
    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$11.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(loopLabel1);
    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 DestructuringErrors1();
    var init = this.parseExpression(awaitAt > -1 ? "await" : 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(init, false, refDestructuringErrors);
        this.checkLValPattern(init);
        return this.parseForIn(node, init);
    } else {
        this.checkExpressionErrors(refDestructuringErrors, true);
    }
    if (awaitAt > -1) {
        this.unexpected(awaitAt);
    }
    return this.parseFor(node, init);
};
pp$11.parseFunctionStatement = function(node, isAsync, declarationPosition) {
    this.next();
    return this.parseFunction(node, FUNC_STATEMENT1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT1), false, isAsync);
};
pp$11.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$11.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$11.parseSwitchStatement = function(node) {
    this.next();
    node.discriminant = this.parseParenExpression();
    node.cases = [];
    this.expect(types2.braceL);
    this.labels.push(switchLabel1);
    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$11.parseThrowStatement = function(node) {
    this.next();
    if (lineBreak1.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 empty1 = [];
pp$11.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 simple = clause.param.type === "Identifier";
            this.enterScope(simple ? SCOPE_SIMPLE_CATCH1 : 0);
            this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH1 : BIND_LEXICAL1);
            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$11.parseVarStatement = function(node, kind) {
    this.next();
    this.parseVar(node, false, kind);
    this.semicolon();
    return this.finishNode(node, "VariableDeclaration");
};
pp$11.parseWhileStatement = function(node) {
    this.next();
    node.test = this.parseParenExpression();
    this.labels.push(loopLabel1);
    node.body = this.parseStatement("while");
    this.labels.pop();
    return this.finishNode(node, "WhileStatement");
};
pp$11.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$11.parseEmptyStatement = function(node) {
    this.next();
    return this.finishNode(node, "EmptyStatement");
};
pp$11.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 i1 = this.labels.length - 1; i1 >= 0; i1--){
        var label$1 = this.labels[i1];
        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$11.parseExpressionStatement = function(node, expr) {
    node.expression = expr;
    this.semicolon();
    return this.finishNode(node, "ExpressionStatement");
};
pp$11.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$11.parseFor = function(node, init) {
    node.init = init;
    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$11.parseForIn = function(node, init) {
    var isForIn = this.type === types2._in;
    this.next();
    if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.options.ecmaVersion < 8 || this.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
        this.raise(init.start, (isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer");
    }
    node.left = init;
    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$11.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$11.parseVarId = function(decl, kind) {
    decl.id = this.parseBindingAtom();
    this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR1 : BIND_LEXICAL1, false);
};
var FUNC_STATEMENT1 = 1, FUNC_HANGING_STATEMENT1 = 2, FUNC_NULLABLE_ID1 = 4;
pp$11.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_STATEMENT1) {
            this.unexpected();
        }
        node.generator = this.eat(types2.star);
    }
    if (this.options.ecmaVersion >= 8) {
        node.async = !!isAsync;
    }
    if (statement & FUNC_STATEMENT1) {
        node.id = statement & FUNC_NULLABLE_ID1 && this.type !== types2.name ? null : this.parseIdent();
        if (node.id && !(statement & FUNC_HANGING_STATEMENT1)) {
            this.checkLValSimple(node.id, this.strict || node.generator || node.async ? this.treatFunctionsAsVar ? BIND_VAR1 : BIND_LEXICAL1 : BIND_FUNCTION1);
        }
    }
    var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.yieldPos = 0;
    this.awaitPos = 0;
    this.awaitIdentPos = 0;
    this.enterScope(functionFlags1(node.async, node.generator));
    if (!(statement & FUNC_STATEMENT1)) {
        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_STATEMENT1 ? "FunctionDeclaration" : "FunctionExpression");
};
pp$11.parseFunctionParams = function(node) {
    this.expect(types2.parenL);
    node.params = this.parseBindingList(types2.parenR, false, this.options.ecmaVersion >= 8);
    this.checkYieldAwaitInDefaultParams();
};
pp$11.parseClass = function(node, isStatement) {
    this.next();
    var oldStrict = this.strict;
    this.strict = true;
    this.parseClassId(node, isStatement);
    this.parseClassSuper(node);
    var privateNameMap = this.enterClassBody();
    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;
            } else if (element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
                this.raiseRecoverable(element.key.start, "Identifier '#" + element.key.name + "' has already been declared");
            }
        }
    }
    this.strict = oldStrict;
    this.next();
    node.body = this.finishNode(classBody, "ClassBody");
    this.exitClassBody();
    return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
};
pp$11.parseClassElement = function(constructorAllowsSuper) {
    if (this.eat(types2.semi)) {
        return null;
    }
    var ecmaVersion = this.options.ecmaVersion;
    var node = this.startNode();
    var keyName = "";
    var isGenerator = false;
    var isAsync = false;
    var kind = "method";
    node.static = false;
    if (this.eatContextual("static")) {
        if (this.isClassElementNameStart() || this.type === types2.star) {
            node.static = true;
        } else {
            keyName = "static";
        }
    }
    if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
        if ((this.isClassElementNameStart() || this.type === types2.star) && !this.canInsertSemicolon()) {
            isAsync = true;
        } else {
            keyName = "async";
        }
    }
    if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types2.star)) {
        isGenerator = true;
    }
    if (!keyName && !isAsync && !isGenerator) {
        var lastValue = this.value;
        if (this.eatContextual("get") || this.eatContextual("set")) {
            if (this.isClassElementNameStart()) {
                kind = lastValue;
            } else {
                keyName = lastValue;
            }
        }
    }
    if (keyName) {
        node.computed = false;
        node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
        node.key.name = keyName;
        this.finishNode(node.key, "Identifier");
    } else {
        this.parseClassElementName(node);
    }
    if (ecmaVersion < 13 || this.type === types2.parenL || kind !== "method" || isGenerator || isAsync) {
        var isConstructor = !node.static && checkKeyName(node, "constructor");
        var allowsDirectSuper = isConstructor && constructorAllowsSuper;
        if (isConstructor && kind !== "method") {
            this.raise(node.key.start, "Constructor can't have get/set modifier");
        }
        node.kind = isConstructor ? "constructor" : kind;
        this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
    } else {
        this.parseClassField(node);
    }
    return node;
};
pp$11.isClassElementNameStart = function() {
    return this.type === types2.name || this.type === types2.privateId || this.type === types2.num || this.type === types2.string || this.type === types2.bracketL || this.type.keyword;
};
pp$11.parseClassElementName = function(element) {
    if (this.type === types2.privateId) {
        if (this.value === "constructor") {
            this.raise(this.start, "Classes can't have an element named '#constructor'");
        }
        element.computed = false;
        element.key = this.parsePrivateIdent();
    } else {
        this.parsePropertyName(element);
    }
};
pp$11.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
    var key = method.key;
    if (method.kind === "constructor") {
        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");
        }
    } else if (method.static && checkKeyName(method, "prototype")) {
        this.raise(key.start, "Classes may not have a static property named prototype");
    }
    var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
    if (method.kind === "get" && value.params.length !== 0) {
        this.raiseRecoverable(value.start, "getter should have no params");
    }
    if (method.kind === "set" && value.params.length !== 1) {
        this.raiseRecoverable(value.start, "setter should have exactly one param");
    }
    if (method.kind === "set" && value.params[0].type === "RestElement") {
        this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params");
    }
    return this.finishNode(method, "MethodDefinition");
};
pp$11.parseClassField = function(field) {
    if (checkKeyName(field, "constructor")) {
        this.raise(field.key.start, "Classes can't have a field named 'constructor'");
    } else if (field.static && checkKeyName(field, "prototype")) {
        this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
    }
    if (this.eat(types2.eq)) {
        var scope = this.currentThisScope();
        var inClassFieldInit = scope.inClassFieldInit;
        scope.inClassFieldInit = true;
        field.value = this.parseMaybeAssign();
        scope.inClassFieldInit = inClassFieldInit;
    } else {
        field.value = null;
    }
    this.semicolon();
    return this.finishNode(field, "PropertyDefinition");
};
pp$11.parseClassId = function(node, isStatement) {
    if (this.type === types2.name) {
        node.id = this.parseIdent();
        if (isStatement) {
            this.checkLValSimple(node.id, BIND_LEXICAL1, false);
        }
    } else {
        if (isStatement === true) {
            this.unexpected();
        }
        node.id = null;
    }
};
pp$11.parseClassSuper = function(node) {
    node.superClass = this.eat(types2._extends) ? this.parseExprSubscripts() : null;
};
pp$11.enterClassBody = function() {
    var element = {
        declared: Object.create(null),
        used: []
    };
    this.privateNameStack.push(element);
    return element.declared;
};
pp$11.exitClassBody = function() {
    var ref2 = this.privateNameStack.pop();
    var declared = ref2.declared;
    var used = ref2.used;
    var len = this.privateNameStack.length;
    var parent = len === 0 ? null : this.privateNameStack[len - 1];
    for(var i1 = 0; i1 < used.length; ++i1){
        var id = used[i1];
        if (!has1(declared, id.name)) {
            if (parent) {
                parent.used.push(id);
            } else {
                this.raiseRecoverable(id.start, "Private field '#" + id.name + "' must be declared in an enclosing class");
            }
        }
    }
};
function isPrivateNameConflicted(privateNameMap, element) {
    var name = element.key.name;
    var curr = privateNameMap[name];
    var next = "true";
    if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
        next = (element.static ? "s" : "i") + element.kind;
    }
    if (curr === "iget" && next === "iset" || curr === "iset" && next === "iget" || curr === "sget" && next === "sset" || curr === "sset" && next === "sget") {
        privateNameMap[name] = "true";
        return false;
    } else if (!curr) {
        privateNameMap[name] = next;
        return false;
    } else {
        return true;
    }
}
function checkKeyName(node, name) {
    var computed = node.computed;
    var key = node.key;
    return !computed && (key.type === "Identifier" && key.name === name || key.type === "Literal" && key.value === name);
}
pp$11.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_STATEMENT1 | FUNC_NULLABLE_ID1, 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 i1 = 0, list = node.specifiers; i1 < list.length; i1 += 1){
                var spec = list[i1];
                this.checkUnreserved(spec.local);
                this.checkLocalExport(spec.local);
            }
            node.source = null;
        }
        this.semicolon();
    }
    return this.finishNode(node, "ExportNamedDeclaration");
};
pp$11.checkExport = function(exports, name, pos) {
    if (!exports) {
        return;
    }
    if (has1(exports, name)) {
        this.raiseRecoverable(pos, "Duplicate export '" + name + "'");
    }
    exports[name] = true;
};
pp$11.checkPatternExport = function(exports, pat) {
    var type = pat.type;
    if (type === "Identifier") {
        this.checkExport(exports, pat.name, pat.start);
    } else if (type === "ObjectPattern") {
        for(var i1 = 0, list = pat.properties; i1 < list.length; i1 += 1){
            var prop = list[i1];
            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$11.checkVariableExport = function(exports, decls) {
    if (!exports) {
        return;
    }
    for(var i1 = 0, list = decls; i1 < list.length; i1 += 1){
        var decl = list[i1];
        this.checkPatternExport(exports, decl.id);
    }
};
pp$11.shouldParseExportStatement = function() {
    return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction();
};
pp$11.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$11.parseImport = function(node) {
    this.next();
    if (this.type === types2.string) {
        node.specifiers = empty1;
        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$11.parseImportSpecifiers = function() {
    var nodes = [], first = true;
    if (this.type === types2.name) {
        var node = this.startNode();
        node.local = this.parseIdent();
        this.checkLValSimple(node.local, BIND_LEXICAL1);
        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.checkLValSimple(node$1.local, BIND_LEXICAL1);
        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.checkLValSimple(node$2.local, BIND_LEXICAL1);
        nodes.push(this.finishNode(node$2, "ImportSpecifier"));
    }
    return nodes;
};
pp$11.adaptDirectivePrologue = function(statements) {
    for(var i1 = 0; i1 < statements.length && this.isDirectiveCandidate(statements[i1]); ++i1){
        statements[i1].directive = statements[i1].expression.raw.slice(1, -1);
    }
};
pp$11.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$21 = Parser1.prototype;
pp$21.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 "AssignmentPattern":
            case "RestElement":
                break;
            case "ObjectExpression":
                node.type = "ObjectPattern";
                if (refDestructuringErrors) {
                    this.checkPatternErrors(refDestructuringErrors, true);
                }
                for(var i1 = 0, list = node.properties; i1 < list.length; i1 += 1){
                    var prop = list[i1];
                    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);
                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$21.toAssignableList = function(exprList, isBinding) {
    var end = exprList.length;
    for(var i1 = 0; i1 < end; i1++){
        var elt = exprList[i1];
        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$21.parseSpread = function(refDestructuringErrors) {
    var node = this.startNode();
    this.next();
    node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
    return this.finishNode(node, "SpreadElement");
};
pp$21.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$21.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$21.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$21.parseBindingListItem = function(param) {
    return param;
};
pp$21.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$21.checkLValSimple = function(expr, bindingType, checkClashes) {
    if (bindingType === void 0) bindingType = BIND_NONE1;
    var isBind = bindingType !== BIND_NONE1;
    switch(expr.type){
        case "Identifier":
            if (this.strict && this.reservedWordsStrictBind.test(expr.name)) {
                this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
            }
            if (isBind) {
                if (bindingType === BIND_LEXICAL1 && expr.name === "let") {
                    this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name");
                }
                if (checkClashes) {
                    if (has1(checkClashes, expr.name)) {
                        this.raiseRecoverable(expr.start, "Argument name clash");
                    }
                    checkClashes[expr.name] = true;
                }
                if (bindingType !== BIND_OUTSIDE1) {
                    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 (isBind) {
                this.raiseRecoverable(expr.start, "Binding member expression");
            }
            break;
        case "ParenthesizedExpression":
            if (isBind) {
                this.raiseRecoverable(expr.start, "Binding parenthesized expression");
            }
            return this.checkLValSimple(expr.expression, bindingType, checkClashes);
        default:
            this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
    }
};
pp$21.checkLValPattern = function(expr, bindingType, checkClashes) {
    if (bindingType === void 0) bindingType = BIND_NONE1;
    switch(expr.type){
        case "ObjectPattern":
            for(var i1 = 0, list = expr.properties; i1 < list.length; i1 += 1){
                var prop = list[i1];
                this.checkLValInnerPattern(prop, 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.checkLValInnerPattern(elem, bindingType, checkClashes);
                }
            }
            break;
        default:
            this.checkLValSimple(expr, bindingType, checkClashes);
    }
};
pp$21.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
    if (bindingType === void 0) bindingType = BIND_NONE1;
    switch(expr.type){
        case "Property":
            this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
            break;
        case "AssignmentPattern":
            this.checkLValPattern(expr.left, bindingType, checkClashes);
            break;
        case "RestElement":
            this.checkLValPattern(expr.argument, bindingType, checkClashes);
            break;
        default:
            this.checkLValPattern(expr, bindingType, checkClashes);
    }
};
var pp$31 = Parser1.prototype;
pp$31.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 name;
    switch(key.type){
        case "Identifier":
            name = key.name;
            break;
        case "Literal":
            name = String(key.value);
            break;
        default:
            return;
    }
    var kind = prop.kind;
    if (this.options.ecmaVersion >= 6) {
        if (name === "__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;
    }
    name = "$" + name;
    var other = propHash[name];
    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[name] = {
            init: false,
            get: false,
            set: false
        };
    }
    other[kind] = true;
};
pp$31.parseExpression = function(forInit, refDestructuringErrors) {
    var startPos = this.start, startLoc = this.startLoc;
    var expr = this.parseMaybeAssign(forInit, 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(forInit, refDestructuringErrors));
        }
        return this.finishNode(node, "SequenceExpression");
    }
    return expr;
};
pp$31.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
    if (this.isContextual("yield")) {
        if (this.inGenerator) {
            return this.parseYield(forInit);
        } 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 DestructuringErrors1();
        ownDestructuringErrors = true;
    }
    var startPos = this.start, startLoc = this.startLoc;
    if (this.type === types2.parenL || this.type === types2.name) {
        this.potentialArrowAt = this.start;
        this.potentialArrowInForAwait = forInit === "await";
    }
    var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
    if (afterLeftParse) {
        left = afterLeftParse.call(this, left, startPos, startLoc);
    }
    if (this.type.isAssign) {
        var node = this.startNodeAt(startPos, startLoc);
        node.operator = this.value;
        if (this.type === types2.eq) {
            left = this.toAssignable(left, false, refDestructuringErrors);
        }
        if (!ownDestructuringErrors) {
            refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
        }
        if (refDestructuringErrors.shorthandAssign >= left.start) {
            refDestructuringErrors.shorthandAssign = -1;
        }
        if (this.type === types2.eq) {
            this.checkLValPattern(left);
        } else {
            this.checkLValSimple(left);
        }
        node.left = left;
        this.next();
        node.right = this.parseMaybeAssign(forInit);
        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$31.parseMaybeConditional = function(forInit, refDestructuringErrors) {
    var startPos = this.start, startLoc = this.startLoc;
    var expr = this.parseExprOps(forInit, 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(forInit);
        return this.finishNode(node, "ConditionalExpression");
    }
    return expr;
};
pp$31.parseExprOps = function(forInit, 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, forInit);
};
pp$31.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
    var prec = this.type.binop;
    if (prec != null && (!forInit || 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, forInit);
            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, forInit);
        }
    }
    return left;
};
pp$31.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$31.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec) {
    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, update);
        this.checkExpressionErrors(refDestructuringErrors, true);
        if (update) {
            this.checkLValSimple(node.argument);
        } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") {
            this.raiseRecoverable(node.start, "Deleting local variable in strict mode");
        } else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) {
            this.raiseRecoverable(node.start, "Private fields can not be deleted");
        } 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.checkLValSimple(expr);
            this.next();
            expr = this.finishNode(node$1, "UpdateExpression");
        }
    }
    if (!incDec && this.eat(types2.starstar)) {
        if (sawUnary) {
            this.unexpected(this.lastTokStart);
        } else {
            return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false);
        }
    } else {
        return expr;
    }
};
function isPrivateFieldAccess(node) {
    return node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || node.type === "ChainExpression" && isPrivateFieldAccess(node.expression);
}
pp$31.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 result1 = this.parseSubscripts(expr, startPos, startLoc);
    if (refDestructuringErrors && result1.type === "MemberExpression") {
        if (refDestructuringErrors.parenthesizedAssign >= result1.start) {
            refDestructuringErrors.parenthesizedAssign = -1;
        }
        if (refDestructuringErrors.parenthesizedBind >= result1.start) {
            refDestructuringErrors.parenthesizedBind = -1;
        }
        if (refDestructuringErrors.trailingComma >= result1.start) {
            refDestructuringErrors.trailingComma = -1;
        }
    }
    return result1;
};
pp$31.parseSubscripts = function(base, startPos, startLoc, noCalls) {
    var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && this.potentialArrowAt === base.start;
    var optionalChained = false;
    while(true){
        var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
        if (element.optional) {
            optionalChained = true;
        }
        if (element === base || element.type === "ArrowFunctionExpression") {
            if (optionalChained) {
                var chainNode = this.startNodeAt(startPos, startLoc);
                chainNode.expression = element;
                element = this.finishNode(chainNode, "ChainExpression");
            }
            return element;
        }
        base = element;
    }
};
pp$31.parseSubscript = function(base, 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 = base;
        if (computed) {
            node.property = this.parseExpression();
            this.expect(types2.bracketR);
        } else if (this.type === types2.privateId && base.type !== "Super") {
            node.property = this.parsePrivateIdent();
        } else {
            node.property = this.parseIdent(this.options.allowReserved !== "never");
        }
        node.computed = !!computed;
        if (optionalSupported) {
            node.optional = optional;
        }
        base = this.finishNode(node, "MemberExpression");
    } else if (!noCalls && this.eat(types2.parenL)) {
        var refDestructuringErrors = new DestructuringErrors1(), 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 = base;
        node$1.arguments = exprList;
        if (optionalSupported) {
            node$1.optional = optional;
        }
        base = 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 = base;
        node$2.quasi = this.parseTemplate({
            isTagged: true
        });
        base = this.finishNode(node$2, "TaggedTemplateExpression");
    }
    return base;
};
pp$31.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 && (!this.potentialArrowInForAwait || this.value !== "of" || this.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$31.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$31.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$31.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.options.allowImportExportEverywhere) {
        this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module");
    }
    return this.finishNode(node, "MetaProperty");
};
pp$31.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$31.parseParenExpression = function() {
    this.expect(types2.parenL);
    var val = this.parseExpression();
    this.expect(types2.parenR);
    return val;
};
pp$31.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 DestructuringErrors1(), 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$31.parseParenItem = function(item) {
    return item;
};
pp$31.parseParenArrowList = function(startPos, startLoc, exprList) {
    return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
};
var empty$11 = [];
pp$31.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$11;
    }
    return this.finishNode(node, "NewExpression");
};
pp$31.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$31.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$31.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) && !lineBreak1.test(this.input.slice(this.lastTokEnd, this.start));
};
pp$31.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$31.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$31.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, this.copyNode(prop.key));
        } else if (this.type === types2.eq && refDestructuringErrors) {
            if (refDestructuringErrors.shorthandAssign < 0) {
                refDestructuringErrors.shorthandAssign = this.start;
            }
            prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
        } else {
            prop.value = this.copyNode(prop.key);
        }
        prop.shorthand = true;
    } else {
        this.unexpected();
    }
};
pp$31.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$31.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$31.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(functionFlags1(isAsync, node.generator) | SCOPE_SUPER1 | (allowDirectSuper ? SCOPE_DIRECT_SUPER1 : 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$31.parseArrowExpression = function(node, params, isAsync) {
    var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
    this.enterScope(functionFlags1(isAsync, false) | SCOPE_ARROW1);
    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$31.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.checkLValSimple(node.id, BIND_OUTSIDE1);
        }
        node.body = this.parseBlock(false, void 0, useStrict && !oldStrict);
        node.expression = false;
        this.adaptDirectivePrologue(node.body.body);
        this.labels = oldLabels;
    }
    this.exitScope();
};
pp$31.isSimpleParamList = function(params) {
    for(var i1 = 0, list = params; i1 < list.length; i1 += 1){
        var param = list[i1];
        if (param.type !== "Identifier") {
            return false;
        }
    }
    return true;
};
pp$31.checkParams = function(node, allowDuplicates) {
    var nameHash = Object.create(null);
    for(var i1 = 0, list = node.params; i1 < list.length; i1 += 1){
        var param = list[i1];
        this.checkLValInnerPattern(param, BIND_VAR1, allowDuplicates ? null : nameHash);
    }
};
pp$31.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$31.checkUnreserved = function(ref2) {
    var start = ref2.start;
    var end = ref2.end;
    var name = ref2.name;
    if (this.inGenerator && name === "yield") {
        this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator");
    }
    if (this.inAsync && name === "await") {
        this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function");
    }
    if (this.currentThisScope().inClassFieldInit && name === "arguments") {
        this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer");
    }
    if (this.keywords.test(name)) {
        this.raise(start, "Unexpected keyword '" + name + "'");
    }
    if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) {
        return;
    }
    var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
    if (re.test(name)) {
        if (!this.inAsync && name === "await") {
            this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function");
        }
        this.raiseRecoverable(start, "The keyword '" + name + "' is reserved");
    }
};
pp$31.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$31.parsePrivateIdent = function() {
    var node = this.startNode();
    if (this.type === types2.privateId) {
        node.name = this.value;
    } else {
        this.unexpected();
    }
    this.next();
    this.finishNode(node, "PrivateIdentifier");
    if (this.privateNameStack.length === 0) {
        this.raise(node.start, "Private field '#" + node.name + "' must be declared in an enclosing class");
    } else {
        this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
    }
    return node;
};
pp$31.parseYield = function(forInit) {
    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(forInit);
    }
    return this.finishNode(node, "YieldExpression");
};
pp$31.parseAwait = function() {
    if (!this.awaitPos) {
        this.awaitPos = this.start;
    }
    var node = this.startNode();
    this.next();
    node.argument = this.parseMaybeUnary(null, true);
    return this.finishNode(node, "AwaitExpression");
};
var pp$41 = Parser1.prototype;
pp$41.raise = function(pos, message) {
    var loc = getLineInfo1(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$41.raiseRecoverable = pp$41.raise;
pp$41.curPosition = function() {
    if (this.options.locations) {
        return new Position1(this.curLine, this.pos - this.lineStart);
    }
};
var pp$51 = Parser1.prototype;
var Scope1 = function Scope2(flags) {
    this.flags = flags;
    this.var = [];
    this.lexical = [];
    this.functions = [];
    this.inClassFieldInit = false;
};
pp$51.enterScope = function(flags) {
    this.scopeStack.push(new Scope1(flags));
};
pp$51.exitScope = function() {
    this.scopeStack.pop();
};
pp$51.treatFunctionsAsVarInScope = function(scope) {
    return scope.flags & SCOPE_FUNCTION1 || !this.inModule && scope.flags & SCOPE_TOP1;
};
pp$51.declareName = function(name, bindingType, pos) {
    var redeclared = false;
    if (bindingType === BIND_LEXICAL1) {
        var scope = this.currentScope();
        redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
        scope.lexical.push(name);
        if (this.inModule && scope.flags & SCOPE_TOP1) {
            delete this.undefinedExports[name];
        }
    } else if (bindingType === BIND_SIMPLE_CATCH1) {
        var scope$1 = this.currentScope();
        scope$1.lexical.push(name);
    } else if (bindingType === BIND_FUNCTION1) {
        var scope$2 = this.currentScope();
        if (this.treatFunctionsAsVar) {
            redeclared = scope$2.lexical.indexOf(name) > -1;
        } else {
            redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1;
        }
        scope$2.functions.push(name);
    } else {
        for(var i1 = this.scopeStack.length - 1; i1 >= 0; --i1){
            var scope$3 = this.scopeStack[i1];
            if (scope$3.lexical.indexOf(name) > -1 && !(scope$3.flags & SCOPE_SIMPLE_CATCH1 && scope$3.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
                redeclared = true;
                break;
            }
            scope$3.var.push(name);
            if (this.inModule && scope$3.flags & SCOPE_TOP1) {
                delete this.undefinedExports[name];
            }
            if (scope$3.flags & SCOPE_VAR1) {
                break;
            }
        }
    }
    if (redeclared) {
        this.raiseRecoverable(pos, "Identifier '" + name + "' has already been declared");
    }
};
pp$51.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$51.currentScope = function() {
    return this.scopeStack[this.scopeStack.length - 1];
};
pp$51.currentVarScope = function() {
    for(var i1 = this.scopeStack.length - 1;; i1--){
        var scope = this.scopeStack[i1];
        if (scope.flags & SCOPE_VAR1) {
            return scope;
        }
    }
};
pp$51.currentThisScope = function() {
    for(var i1 = this.scopeStack.length - 1;; i1--){
        var scope = this.scopeStack[i1];
        if (scope.flags & SCOPE_VAR1 && !(scope.flags & SCOPE_ARROW1)) {
            return scope;
        }
    }
};
var Node2 = function Node2(parser, pos, loc) {
    this.type = "";
    this.start = pos;
    this.end = 0;
    if (parser.options.locations) {
        this.loc = new SourceLocation1(parser, loc);
    }
    if (parser.options.directSourceFile) {
        this.sourceFile = parser.options.directSourceFile;
    }
    if (parser.options.ranges) {
        this.range = [
            pos,
            0
        ];
    }
};
var pp$61 = Parser1.prototype;
pp$61.startNode = function() {
    return new Node2(this, this.start, this.startLoc);
};
pp$61.startNodeAt = function(pos, loc) {
    return new Node2(this, pos, loc);
};
function finishNodeAt1(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$61.finishNode = function(node, type) {
    return finishNodeAt1.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
};
pp$61.finishNodeAt = function(node, type, pos, loc) {
    return finishNodeAt1.call(this, node, type, pos, loc);
};
pp$61.copyNode = function(node) {
    var newNode = new Node2(this, node.start, this.startLoc);
    for(var prop in node){
        newNode[prop] = node[prop];
    }
    return newNode;
};
var TokContext1 = function TokContext2(token, isExpr, preserveSpace, override, generator) {
    this.token = token;
    this.isExpr = !!isExpr;
    this.preserveSpace = !!preserveSpace;
    this.override = override;
    this.generator = !!generator;
};
var types$11 = {
    b_stat: new TokContext1("{", false),
    b_expr: new TokContext1("{", true),
    b_tmpl: new TokContext1("${", false),
    p_stat: new TokContext1("(", false),
    p_expr: new TokContext1("(", true),
    q_tmpl: new TokContext1("`", true, true, function(p) {
        return p.tryReadTemplateToken();
    }),
    f_stat: new TokContext1("function", false),
    f_expr: new TokContext1("function", true),
    f_expr_gen: new TokContext1("function", true, false, null, true),
    f_gen: new TokContext1("function", false, false, null, true)
};
var pp$71 = Parser1.prototype;
pp$71.initialContext = function() {
    return [
        types$11.b_stat
    ];
};
pp$71.braceIsBlock = function(prevType) {
    var parent = this.curContext();
    if (parent === types$11.f_expr || parent === types$11.f_stat) {
        return true;
    }
    if (prevType === types2.colon && (parent === types$11.b_stat || parent === types$11.b_expr)) {
        return !parent.isExpr;
    }
    if (prevType === types2._return || prevType === types2.name && this.exprAllowed) {
        return lineBreak1.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$11.b_stat;
    }
    if (prevType === types2._var || prevType === types2._const || prevType === types2.name) {
        return false;
    }
    return !this.exprAllowed;
};
pp$71.inGeneratorContext = function() {
    for(var i1 = this.context.length - 1; i1 >= 1; i1--){
        var context = this.context[i1];
        if (context.token === "function") {
            return context.generator;
        }
    }
    return false;
};
pp$71.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$11.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$11.b_stat : types$11.b_expr);
    this.exprAllowed = true;
};
types2.dollarBraceL.updateContext = function() {
    this.context.push(types$11.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$11.p_stat : types$11.p_expr);
    this.exprAllowed = true;
};
types2.incDec.updateContext = function() {};
types2._function.updateContext = types2._class.updateContext = function(prevType) {
    if (prevType.beforeExpr && prevType !== types2._else && !(prevType === types2.semi && this.curContext() !== types$11.p_stat) && !(prevType === types2._return && lineBreak1.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types2.colon || prevType === types2.braceL) && this.curContext() === types$11.b_stat)) {
        this.context.push(types$11.f_expr);
    } else {
        this.context.push(types$11.f_stat);
    }
    this.exprAllowed = false;
};
types2.backQuote.updateContext = function() {
    if (this.curContext() === types$11.q_tmpl) {
        this.context.pop();
    } else {
        this.context.push(types$11.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$11.f_expr) {
            this.context[index] = types$11.f_expr_gen;
        } else {
            this.context[index] = types$11.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 ecma9BinaryProperties1 = "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 ecma10BinaryProperties1 = ecma9BinaryProperties1 + " Extended_Pictographic";
var ecma11BinaryProperties1 = ecma10BinaryProperties1;
var ecma12BinaryProperties = ecma11BinaryProperties1 + " EBase EComp EMod EPres ExtPict";
var unicodeBinaryProperties1 = {
    9: ecma9BinaryProperties1,
    10: ecma10BinaryProperties1,
    11: ecma11BinaryProperties1,
    12: ecma12BinaryProperties
};
var unicodeGeneralCategoryValues1 = "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 ecma9ScriptValues1 = "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 ecma10ScriptValues1 = ecma9ScriptValues1 + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
var ecma11ScriptValues1 = ecma10ScriptValues1 + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
var ecma12ScriptValues = ecma11ScriptValues1 + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
var unicodeScriptValues1 = {
    9: ecma9ScriptValues1,
    10: ecma10ScriptValues1,
    11: ecma11ScriptValues1,
    12: ecma12ScriptValues
};
var data1 = {};
function buildUnicodeData1(ecmaVersion) {
    var d = data1[ecmaVersion] = {
        binary: wordsRegexp1(unicodeBinaryProperties1[ecmaVersion] + " " + unicodeGeneralCategoryValues1),
        nonBinary: {
            General_Category: wordsRegexp1(unicodeGeneralCategoryValues1),
            Script: wordsRegexp1(unicodeScriptValues1[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;
}
buildUnicodeData1(9);
buildUnicodeData1(10);
buildUnicodeData1(11);
buildUnicodeData1(12);
var pp$81 = Parser1.prototype;
var RegExpValidationState1 = function RegExpValidationState2(parser) {
    this.parser = parser;
    this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "");
    this.unicodeProperties = data1[parser.options.ecmaVersion >= 12 ? 12 : 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 = [];
};
RegExpValidationState1.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;
};
RegExpValidationState1.prototype.raise = function raise(message) {
    this.parser.raiseRecoverable(this.start, "Invalid regular expression: /" + this.source + "/: " + message);
};
RegExpValidationState1.prototype.at = function at(i1, forceU) {
    if (forceU === void 0) forceU = false;
    var s = this.source;
    var l1 = s.length;
    if (i1 >= l1) {
        return -1;
    }
    var c = s.charCodeAt(i1);
    if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i1 + 1 >= l1) {
        return c;
    }
    var next = s.charCodeAt(i1 + 1);
    return next >= 56320 && next <= 57343 ? (c << 10) + next - 56613888 : c;
};
RegExpValidationState1.prototype.nextIndex = function nextIndex(i1, forceU) {
    if (forceU === void 0) forceU = false;
    var s = this.source;
    var l1 = s.length;
    if (i1 >= l1) {
        return l1;
    }
    var c = s.charCodeAt(i1), next;
    if (!(forceU || this.switchU) || c <= 55295 || c >= 57344 || i1 + 1 >= l1 || (next = s.charCodeAt(i1 + 1)) < 56320 || next > 57343) {
        return i1 + 1;
    }
    return i1 + 2;
};
RegExpValidationState1.prototype.current = function current(forceU) {
    if (forceU === void 0) forceU = false;
    return this.at(this.pos, forceU);
};
RegExpValidationState1.prototype.lookahead = function lookahead(forceU) {
    if (forceU === void 0) forceU = false;
    return this.at(this.nextIndex(this.pos, forceU), forceU);
};
RegExpValidationState1.prototype.advance = function advance(forceU) {
    if (forceU === void 0) forceU = false;
    this.pos = this.nextIndex(this.pos, forceU);
};
RegExpValidationState1.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 codePointToString1(ch) {
    if (ch <= 65535) {
        return String.fromCharCode(ch);
    }
    ch -= 65536;
    return String.fromCharCode((ch >> 10) + 55296, (ch & 1023) + 56320);
}
pp$81.validateRegExpFlags = function(state) {
    var validFlags = state.validFlags;
    var flags = state.flags;
    for(var i1 = 0; i1 < flags.length; i1++){
        var flag = flags.charAt(i1);
        if (validFlags.indexOf(flag) === -1) {
            this.raise(state.start, "Invalid regular expression flag");
        }
        if (flags.indexOf(flag, i1 + 1) > -1) {
            this.raise(state.start, "Duplicate regular expression flag");
        }
    }
};
pp$81.validateRegExpPattern = function(state) {
    this.regexp_pattern(state);
    if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
        state.switchN = true;
        this.regexp_pattern(state);
    }
};
pp$81.regexp_pattern = function(state) {
    state.pos = 0;
    state.lastIntValue = 0;
    state.lastStringValue = "";
    state.lastAssertionIsQuantifiable = false;
    state.numCapturingParens = 0;
    state.maxBackReference = 0;
    state.groupNames.length = 0;
    state.backReferenceNames.length = 0;
    this.regexp_disjunction(state);
    if (state.pos !== state.source.length) {
        if (state.eat(41)) {
            state.raise("Unmatched ')'");
        }
        if (state.eat(93) || state.eat(125)) {
            state.raise("Lone quantifier brackets");
        }
    }
    if (state.maxBackReference > state.numCapturingParens) {
        state.raise("Invalid escape");
    }
    for(var i1 = 0, list = state.backReferenceNames; i1 < list.length; i1 += 1){
        var name = list[i1];
        if (state.groupNames.indexOf(name) === -1) {
            state.raise("Invalid named capture referenced");
        }
    }
};
pp$81.regexp_disjunction = function(state) {
    this.regexp_alternative(state);
    while(state.eat(124)){
        this.regexp_alternative(state);
    }
    if (this.regexp_eatQuantifier(state, true)) {
        state.raise("Nothing to repeat");
    }
    if (state.eat(123)) {
        state.raise("Lone quantifier brackets");
    }
};
pp$81.regexp_alternative = function(state) {
    while(state.pos < state.source.length && this.regexp_eatTerm(state)){}
};
pp$81.regexp_eatTerm = function(state) {
    if (this.regexp_eatAssertion(state)) {
        if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
            if (state.switchU) {
                state.raise("Invalid quantifier");
            }
        }
        return true;
    }
    if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
        this.regexp_eatQuantifier(state);
        return true;
    }
    return false;
};
pp$81.regexp_eatAssertion = function(state) {
    var start = state.pos;
    state.lastAssertionIsQuantifiable = false;
    if (state.eat(94) || state.eat(36)) {
        return true;
    }
    if (state.eat(92)) {
        if (state.eat(66) || state.eat(98)) {
            return true;
        }
        state.pos = start;
    }
    if (state.eat(40) && state.eat(63)) {
        var lookbehind = false;
        if (this.options.ecmaVersion >= 9) {
            lookbehind = state.eat(60);
        }
        if (state.eat(61) || state.eat(33)) {
            this.regexp_disjunction(state);
            if (!state.eat(41)) {
                state.raise("Unterminated group");
            }
            state.lastAssertionIsQuantifiable = !lookbehind;
            return true;
        }
    }
    state.pos = start;
    return false;
};
pp$81.regexp_eatQuantifier = function(state, noError) {
    if (noError === void 0) noError = false;
    if (this.regexp_eatQuantifierPrefix(state, noError)) {
        state.eat(63);
        return true;
    }
    return false;
};
pp$81.regexp_eatQuantifierPrefix = function(state, noError) {
    return state.eat(42) || state.eat(43) || state.eat(63) || this.regexp_eatBracedQuantifier(state, noError);
};
pp$81.regexp_eatBracedQuantifier = function(state, noError) {
    var start = state.pos;
    if (state.eat(123)) {
        var min = 0, max = -1;
        if (this.regexp_eatDecimalDigits(state)) {
            min = state.lastIntValue;
            if (state.eat(44) && this.regexp_eatDecimalDigits(state)) {
                max = state.lastIntValue;
            }
            if (state.eat(125)) {
                if (max !== -1 && max < min && !noError) {
                    state.raise("numbers out of order in {} quantifier");
                }
                return true;
            }
        }
        if (state.switchU && !noError) {
            state.raise("Incomplete quantifier");
        }
        state.pos = start;
    }
    return false;
};
pp$81.regexp_eatAtom = function(state) {
    return this.regexp_eatPatternCharacters(state) || state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state);
};
pp$81.regexp_eatReverseSolidusAtomEscape = function(state) {
    var start = state.pos;
    if (state.eat(92)) {
        if (this.regexp_eatAtomEscape(state)) {
            return true;
        }
        state.pos = start;
    }
    return false;
};
pp$81.regexp_eatUncapturingGroup = function(state) {
    var start = state.pos;
    if (state.eat(40)) {
        if (state.eat(63) && state.eat(58)) {
            this.regexp_disjunction(state);
            if (state.eat(41)) {
                return true;
            }
            state.raise("Unterminated group");
        }
        state.pos = start;
    }
    return false;
};
pp$81.regexp_eatCapturingGroup = function(state) {
    if (state.eat(40)) {
        if (this.options.ecmaVersion >= 9) {
            this.regexp_groupSpecifier(state);
        } else if (state.current() === 63) {
            state.raise("Invalid group");
        }
        this.regexp_disjunction(state);
        if (state.eat(41)) {
            state.numCapturingParens += 1;
            return true;
        }
        state.raise("Unterminated group");
    }
    return false;
};
pp$81.regexp_eatExtendedAtom = function(state) {
    return state.eat(46) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state);
};
pp$81.regexp_eatInvalidBracedQuantifier = function(state) {
    if (this.regexp_eatBracedQuantifier(state, true)) {
        state.raise("Nothing to repeat");
    }
    return false;
};
pp$81.regexp_eatSyntaxCharacter = function(state) {
    var ch = state.current();
    if (isSyntaxCharacter1(ch)) {
        state.lastIntValue = ch;
        state.advance();
        return true;
    }
    return false;
};
function isSyntaxCharacter1(ch) {
    return ch === 36 || ch >= 40 && ch <= 43 || ch === 46 || ch === 63 || ch >= 91 && ch <= 94 || ch >= 123 && ch <= 125;
}
pp$81.regexp_eatPatternCharacters = function(state) {
    var start = state.pos;
    var ch = 0;
    while((ch = state.current()) !== -1 && !isSyntaxCharacter1(ch)){
        state.advance();
    }
    return state.pos !== start;
};
pp$81.regexp_eatExtendedPatternCharacter = function(state) {
    var ch = state.current();
    if (ch !== -1 && ch !== 36 && !(ch >= 40 && ch <= 43) && ch !== 46 && ch !== 63 && ch !== 91 && ch !== 94 && ch !== 124) {
        state.advance();
        return true;
    }
    return false;
};
pp$81.regexp_groupSpecifier = function(state) {
    if (state.eat(63)) {
        if (this.regexp_eatGroupName(state)) {
            if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
                state.raise("Duplicate capture group name");
            }
            state.groupNames.push(state.lastStringValue);
            return;
        }
        state.raise("Invalid group");
    }
};
pp$81.regexp_eatGroupName = function(state) {
    state.lastStringValue = "";
    if (state.eat(60)) {
        if (this.regexp_eatRegExpIdentifierName(state) && state.eat(62)) {
            return true;
        }
        state.raise("Invalid capture group name");
    }
    return false;
};
pp$81.regexp_eatRegExpIdentifierName = function(state) {
    state.lastStringValue = "";
    if (this.regexp_eatRegExpIdentifierStart(state)) {
        state.lastStringValue += codePointToString1(state.lastIntValue);
        while(this.regexp_eatRegExpIdentifierPart(state)){
            state.lastStringValue += codePointToString1(state.lastIntValue);
        }
        return true;
    }
    return false;
};
pp$81.regexp_eatRegExpIdentifierStart = function(state) {
    var start = state.pos;
    var forceU = this.options.ecmaVersion >= 11;
    var ch = state.current(forceU);
    state.advance(forceU);
    if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
        ch = state.lastIntValue;
    }
    if (isRegExpIdentifierStart1(ch)) {
        state.lastIntValue = ch;
        return true;
    }
    state.pos = start;
    return false;
};
function isRegExpIdentifierStart1(ch) {
    return isIdentifierStart1(ch, true) || ch === 36 || ch === 95;
}
pp$81.regexp_eatRegExpIdentifierPart = function(state) {
    var start = state.pos;
    var forceU = this.options.ecmaVersion >= 11;
    var ch = state.current(forceU);
    state.advance(forceU);
    if (ch === 92 && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
        ch = state.lastIntValue;
    }
    if (isRegExpIdentifierPart1(ch)) {
        state.lastIntValue = ch;
        return true;
    }
    state.pos = start;
    return false;
};
function isRegExpIdentifierPart1(ch) {
    return isIdentifierChar1(ch, true) || ch === 36 || ch === 95 || ch === 8204 || ch === 8205;
}
pp$81.regexp_eatAtomEscape = function(state) {
    if (this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || state.switchN && this.regexp_eatKGroupName(state)) {
        return true;
    }
    if (state.switchU) {
        if (state.current() === 99) {
            state.raise("Invalid unicode escape");
        }
        state.raise("Invalid escape");
    }
    return false;
};
pp$81.regexp_eatBackReference = function(state) {
    var start = state.pos;
    if (this.regexp_eatDecimalEscape(state)) {
        var n = state.lastIntValue;
        if (state.switchU) {
            if (n > state.maxBackReference) {
                state.maxBackReference = n;
            }
            return true;
        }
        if (n <= state.numCapturingParens) {
            return true;
        }
        state.pos = start;
    }
    return false;
};
pp$81.regexp_eatKGroupName = function(state) {
    if (state.eat(107)) {
        if (this.regexp_eatGroupName(state)) {
            state.backReferenceNames.push(state.lastStringValue);
            return true;
        }
        state.raise("Invalid named reference");
    }
    return false;
};
pp$81.regexp_eatCharacterEscape = function(state) {
    return this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || !state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state) || this.regexp_eatIdentityEscape(state);
};
pp$81.regexp_eatCControlLetter = function(state) {
    var start = state.pos;
    if (state.eat(99)) {
        if (this.regexp_eatControlLetter(state)) {
            return true;
        }
        state.pos = start;
    }
    return false;
};
pp$81.regexp_eatZero = function(state) {
    if (state.current() === 48 && !isDecimalDigit1(state.lookahead())) {
        state.lastIntValue = 0;
        state.advance();
        return true;
    }
    return false;
};
pp$81.regexp_eatControlEscape = function(state) {
    var ch = state.current();
    if (ch === 116) {
        state.lastIntValue = 9;
        state.advance();
        return true;
    }
    if (ch === 110) {
        state.lastIntValue = 10;
        state.advance();
        return true;
    }
    if (ch === 118) {
        state.lastIntValue = 11;
        state.advance();
        return true;
    }
    if (ch === 102) {
        state.lastIntValue = 12;
        state.advance();
        return true;
    }
    if (ch === 114) {
        state.lastIntValue = 13;
        state.advance();
        return true;
    }
    return false;
};
pp$81.regexp_eatControlLetter = function(state) {
    var ch = state.current();
    if (isControlLetter1(ch)) {
        state.lastIntValue = ch % 32;
        state.advance();
        return true;
    }
    return false;
};
function isControlLetter1(ch) {
    return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122;
}
pp$81.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
    if (forceU === void 0) forceU = false;
    var start = state.pos;
    var switchU = forceU || state.switchU;
    if (state.eat(117)) {
        if (this.regexp_eatFixedHexDigits(state, 4)) {
            var lead = state.lastIntValue;
            if (switchU && lead >= 55296 && lead <= 56319) {
                var leadSurrogateEnd = state.pos;
                if (state.eat(92) && state.eat(117) && this.regexp_eatFixedHexDigits(state, 4)) {
                    var trail = state.lastIntValue;
                    if (trail >= 56320 && trail <= 57343) {
                        state.lastIntValue = (lead - 55296) * 1024 + (trail - 56320) + 65536;
                        return true;
                    }
                }
                state.pos = leadSurrogateEnd;
                state.lastIntValue = lead;
            }
            return true;
        }
        if (switchU && state.eat(123) && this.regexp_eatHexDigits(state) && state.eat(125) && isValidUnicode1(state.lastIntValue)) {
            return true;
        }
        if (switchU) {
            state.raise("Invalid unicode escape");
        }
        state.pos = start;
    }
    return false;
};
function isValidUnicode1(ch) {
    return ch >= 0 && ch <= 1114111;
}
pp$81.regexp_eatIdentityEscape = function(state) {
    if (state.switchU) {
        if (this.regexp_eatSyntaxCharacter(state)) {
            return true;
        }
        if (state.eat(47)) {
            state.lastIntValue = 47;
            return true;
        }
        return false;
    }
    var ch = state.current();
    if (ch !== 99 && (!state.switchN || ch !== 107)) {
        state.lastIntValue = ch;
        state.advance();
        return true;
    }
    return false;
};
pp$81.regexp_eatDecimalEscape = function(state) {
    state.lastIntValue = 0;
    var ch = state.current();
    if (ch >= 49 && ch <= 57) {
        do {
            state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
            state.advance();
        }while ((ch = state.current()) >= 48 && ch <= 57)
        return true;
    }
    return false;
};
pp$81.regexp_eatCharacterClassEscape = function(state) {
    var ch = state.current();
    if (isCharacterClassEscape1(ch)) {
        state.lastIntValue = -1;
        state.advance();
        return true;
    }
    if (state.switchU && this.options.ecmaVersion >= 9 && (ch === 80 || ch === 112)) {
        state.lastIntValue = -1;
        state.advance();
        if (state.eat(123) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(125)) {
            return true;
        }
        state.raise("Invalid property name");
    }
    return false;
};
function isCharacterClassEscape1(ch) {
    return ch === 100 || ch === 68 || ch === 115 || ch === 83 || ch === 119 || ch === 87;
}
pp$81.regexp_eatUnicodePropertyValueExpression = function(state) {
    var start = state.pos;
    if (this.regexp_eatUnicodePropertyName(state) && state.eat(61)) {
        var name = state.lastStringValue;
        if (this.regexp_eatUnicodePropertyValue(state)) {
            var value = state.lastStringValue;
            this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
            return true;
        }
    }
    state.pos = start;
    if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
        var nameOrValue = state.lastStringValue;
        this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
        return true;
    }
    return false;
};
pp$81.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
    if (!has1(state.unicodeProperties.nonBinary, name)) {
        state.raise("Invalid property name");
    }
    if (!state.unicodeProperties.nonBinary[name].test(value)) {
        state.raise("Invalid property value");
    }
};
pp$81.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
    if (!state.unicodeProperties.binary.test(nameOrValue)) {
        state.raise("Invalid property name");
    }
};
pp$81.regexp_eatUnicodePropertyName = function(state) {
    var ch = 0;
    state.lastStringValue = "";
    while(isUnicodePropertyNameCharacter1(ch = state.current())){
        state.lastStringValue += codePointToString1(ch);
        state.advance();
    }
    return state.lastStringValue !== "";
};
function isUnicodePropertyNameCharacter1(ch) {
    return isControlLetter1(ch) || ch === 95;
}
pp$81.regexp_eatUnicodePropertyValue = function(state) {
    var ch = 0;
    state.lastStringValue = "";
    while(isUnicodePropertyValueCharacter1(ch = state.current())){
        state.lastStringValue += codePointToString1(ch);
        state.advance();
    }
    return state.lastStringValue !== "";
};
function isUnicodePropertyValueCharacter1(ch) {
    return isUnicodePropertyNameCharacter1(ch) || isDecimalDigit1(ch);
}
pp$81.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
    return this.regexp_eatUnicodePropertyValue(state);
};
pp$81.regexp_eatCharacterClass = function(state) {
    if (state.eat(91)) {
        state.eat(94);
        this.regexp_classRanges(state);
        if (state.eat(93)) {
            return true;
        }
        state.raise("Unterminated character class");
    }
    return false;
};
pp$81.regexp_classRanges = function(state) {
    while(this.regexp_eatClassAtom(state)){
        var left = state.lastIntValue;
        if (state.eat(45) && this.regexp_eatClassAtom(state)) {
            var right = state.lastIntValue;
            if (state.switchU && (left === -1 || right === -1)) {
                state.raise("Invalid character class");
            }
            if (left !== -1 && right !== -1 && left > right) {
                state.raise("Range out of order in character class");
            }
        }
    }
};
pp$81.regexp_eatClassAtom = function(state) {
    var start = state.pos;
    if (state.eat(92)) {
        if (this.regexp_eatClassEscape(state)) {
            return true;
        }
        if (state.switchU) {
            var ch$1 = state.current();
            if (ch$1 === 99 || isOctalDigit1(ch$1)) {
                state.raise("Invalid class escape");
            }
            state.raise("Invalid escape");
        }
        state.pos = start;
    }
    var ch = state.current();
    if (ch !== 93) {
        state.lastIntValue = ch;
        state.advance();
        return true;
    }
    return false;
};
pp$81.regexp_eatClassEscape = function(state) {
    var start = state.pos;
    if (state.eat(98)) {
        state.lastIntValue = 8;
        return true;
    }
    if (state.switchU && state.eat(45)) {
        state.lastIntValue = 45;
        return true;
    }
    if (!state.switchU && state.eat(99)) {
        if (this.regexp_eatClassControlLetter(state)) {
            return true;
        }
        state.pos = start;
    }
    return this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state);
};
pp$81.regexp_eatClassControlLetter = function(state) {
    var ch = state.current();
    if (isDecimalDigit1(ch) || ch === 95) {
        state.lastIntValue = ch % 32;
        state.advance();
        return true;
    }
    return false;
};
pp$81.regexp_eatHexEscapeSequence = function(state) {
    var start = state.pos;
    if (state.eat(120)) {
        if (this.regexp_eatFixedHexDigits(state, 2)) {
            return true;
        }
        if (state.switchU) {
            state.raise("Invalid escape");
        }
        state.pos = start;
    }
    return false;
};
pp$81.regexp_eatDecimalDigits = function(state) {
    var start = state.pos;
    var ch = 0;
    state.lastIntValue = 0;
    while(isDecimalDigit1(ch = state.current())){
        state.lastIntValue = 10 * state.lastIntValue + (ch - 48);
        state.advance();
    }
    return state.pos !== start;
};
function isDecimalDigit1(ch) {
    return ch >= 48 && ch <= 57;
}
pp$81.regexp_eatHexDigits = function(state) {
    var start = state.pos;
    var ch = 0;
    state.lastIntValue = 0;
    while(isHexDigit1(ch = state.current())){
        state.lastIntValue = 16 * state.lastIntValue + hexToInt1(ch);
        state.advance();
    }
    return state.pos !== start;
};
function isHexDigit1(ch) {
    return ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102;
}
function hexToInt1(ch) {
    if (ch >= 65 && ch <= 70) {
        return 10 + (ch - 65);
    }
    if (ch >= 97 && ch <= 102) {
        return 10 + (ch - 97);
    }
    return ch - 48;
}
pp$81.regexp_eatLegacyOctalEscapeSequence = function(state) {
    if (this.regexp_eatOctalDigit(state)) {
        var n1 = state.lastIntValue;
        if (this.regexp_eatOctalDigit(state)) {
            var n2 = state.lastIntValue;
            if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
                state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
            } else {
                state.lastIntValue = n1 * 8 + n2;
            }
        } else {
            state.lastIntValue = n1;
        }
        return true;
    }
    return false;
};
pp$81.regexp_eatOctalDigit = function(state) {
    var ch = state.current();
    if (isOctalDigit1(ch)) {
        state.lastIntValue = ch - 48;
        state.advance();
        return true;
    }
    state.lastIntValue = 0;
    return false;
};
function isOctalDigit1(ch) {
    return ch >= 48 && ch <= 55;
}
pp$81.regexp_eatFixedHexDigits = function(state, length) {
    var start = state.pos;
    state.lastIntValue = 0;
    for(var i1 = 0; i1 < length; ++i1){
        var ch = state.current();
        if (!isHexDigit1(ch)) {
            state.pos = start;
            return false;
        }
        state.lastIntValue = 16 * state.lastIntValue + hexToInt1(ch);
        state.advance();
    }
    return true;
};
var Token1 = 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 SourceLocation1(p, p.startLoc, p.endLoc);
    }
    if (p.options.ranges) {
        this.range = [
            p.start,
            p.end
        ];
    }
};
var pp$91 = Parser1.prototype;
pp$91.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 Token1(this));
    }
    this.lastTokEnd = this.end;
    this.lastTokStart = this.start;
    this.lastTokEndLoc = this.endLoc;
    this.lastTokStartLoc = this.startLoc;
    this.nextToken();
};
pp$91.getToken = function() {
    this.next();
    return new Token1(this);
};
if (typeof Symbol !== "undefined") {
    pp$91[Symbol.iterator] = function() {
        var this$1 = this;
        return {
            next: function() {
                var token = this$1.getToken();
                return {
                    done: token.type === types2.eof,
                    value: token
                };
            }
        };
    };
}
pp$91.curContext = function() {
    return this.context[this.context.length - 1];
};
pp$91.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$91.readToken = function(code) {
    if (isIdentifierStart1(code, this.options.ecmaVersion >= 6) || code === 92) {
        return this.readWord();
    }
    return this.getTokenFromCode(code);
};
pp$91.fullCharCodeAtPos = function() {
    var code = this.input.charCodeAt(this.pos);
    if (code <= 55295 || code >= 56320) {
        return code;
    }
    var next = this.input.charCodeAt(this.pos + 1);
    return next <= 56319 || next >= 57344 ? code : (code << 10) + next - 56613888;
};
pp$91.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) {
        lineBreakG1.lastIndex = start;
        var match;
        while((match = lineBreakG1.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$91.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 && !isNewLine1(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$91.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 && nonASCIIwhitespace1.test(String.fromCharCode(ch))) {
                    ++this.pos;
                } else {
                    break loop;
                }
        }
    }
};
pp$91.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$91.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$91.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$91.readToken_mult_modulo_exp = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    var size = 1;
    var tokentype = code === 42 ? types2.star : types2.modulo;
    if (this.options.ecmaVersion >= 7 && code === 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$91.readToken_pipe_amp = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === code) {
        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(code === 124 ? types2.logicalOR : types2.logicalAND, 2);
    }
    if (next === 61) {
        return this.finishOp(types2.assign, 2);
    }
    return this.finishOp(code === 124 ? types2.bitwiseOR : types2.bitwiseAND, 1);
};
pp$91.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$91.readToken_plus_min = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    if (next === code) {
        if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak1.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$91.readToken_lt_gt = function(code) {
    var next = this.input.charCodeAt(this.pos + 1);
    var size = 1;
    if (next === code) {
        size = code === 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 && code === 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$91.readToken_eq_excl = function(code) {
    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 (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
        this.pos += 2;
        return this.finishToken(types2.arrow);
    }
    return this.finishOp(code === 61 ? types2.eq : types2.prefix, 1);
};
pp$91.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$91.readToken_numberSign = function() {
    var ecmaVersion = this.options.ecmaVersion;
    var code = 35;
    if (ecmaVersion >= 13) {
        ++this.pos;
        code = this.fullCharCodeAtPos();
        if (isIdentifierStart1(code, true) || code === 92) {
            return this.finishToken(types2.privateId, this.readWord1());
        }
    }
    this.raise(this.pos, "Unexpected character '" + codePointToString$11(code) + "'");
};
pp$91.getTokenFromCode = function(code) {
    switch(code){
        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(code);
        case 47:
            return this.readToken_slash();
        case 37:
        case 42:
            return this.readToken_mult_modulo_exp(code);
        case 124:
        case 38:
            return this.readToken_pipe_amp(code);
        case 94:
            return this.readToken_caret();
        case 43:
        case 45:
            return this.readToken_plus_min(code);
        case 60:
        case 62:
            return this.readToken_lt_gt(code);
        case 61:
        case 33:
            return this.readToken_eq_excl(code);
        case 63:
            return this.readToken_question();
        case 126:
            return this.finishOp(types2.prefix, 1);
        case 35:
            return this.readToken_numberSign();
    }
    this.raise(this.pos, "Unexpected character '" + codePointToString$11(code) + "'");
};
pp$91.finishOp = function(type, size) {
    var str = this.input.slice(this.pos, this.pos + size);
    this.pos += size;
    return this.finishToken(type, str);
};
pp$91.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 (lineBreak1.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 state = this.regexpState || (this.regexpState = new RegExpValidationState1(this));
    state.reset(start, pattern, flags);
    this.validateRegExpFlags(state);
    this.validateRegExpPattern(state);
    var value = null;
    try {
        value = new RegExp(pattern, flags);
    } catch (e) {}
    return this.finishToken(types2.regexp, {
        pattern,
        flags,
        value
    });
};
pp$91.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
    var allowSeparators = this.options.ecmaVersion >= 12 && len === void 0;
    var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
    var start = this.pos, total = 0, lastCode = 0;
    for(var i1 = 0, e = len == null ? Infinity : len; i1 < e; ++i1, ++this.pos){
        var code = this.input.charCodeAt(this.pos), val = void 0;
        if (allowSeparators && code === 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 (i1 === 0) {
                this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits");
            }
            lastCode = code;
            continue;
        }
        if (code >= 97) {
            val = code - 97 + 10;
        } else if (code >= 65) {
            val = code - 65 + 10;
        } else if (code >= 48 && code <= 57) {
            val = code - 48;
        } else {
            val = Infinity;
        }
        if (val >= radix) {
            break;
        }
        lastCode = code;
        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 || len != null && this.pos - start !== len) {
        return null;
    }
    return total;
};
function stringToNumber1(str, isLegacyOctalNumericLiteral) {
    if (isLegacyOctalNumericLiteral) {
        return parseInt(str, 8);
    }
    return parseFloat(str.replace(/_/g, ""));
}
function stringToBigInt1(str) {
    if (typeof BigInt !== "function") {
        return null;
    }
    return BigInt(str.replace(/_/g, ""));
}
pp$91.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 = stringToBigInt1(this.input.slice(start, this.pos));
        ++this.pos;
    } else if (isIdentifierStart1(this.fullCharCodeAtPos())) {
        this.raise(this.pos, "Identifier directly after number");
    }
    return this.finishToken(types2.num, val);
};
pp$91.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 = stringToBigInt1(this.input.slice(start, this.pos));
        ++this.pos;
        if (isIdentifierStart1(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 (isIdentifierStart1(this.fullCharCodeAtPos())) {
        this.raise(this.pos, "Identifier directly after number");
    }
    var val = stringToNumber1(this.input.slice(start, this.pos), octal);
    return this.finishToken(types2.num, val);
};
pp$91.readCodePoint = function() {
    var ch = this.input.charCodeAt(this.pos), code;
    if (ch === 123) {
        if (this.options.ecmaVersion < 6) {
            this.unexpected();
        }
        var codePos = ++this.pos;
        code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
        ++this.pos;
        if (code > 1114111) {
            this.invalidStringToken(codePos, "Code point out of bounds");
        }
    } else {
        code = this.readHexChar(4);
    }
    return code;
};
function codePointToString$11(code) {
    if (code <= 65535) {
        return String.fromCharCode(code);
    }
    code -= 65536;
    return String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
}
pp$91.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 (isNewLine1(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_ERROR1 = {};
pp$91.tryReadTemplateToken = function() {
    this.inTemplateElement = true;
    try {
        this.readTmplToken();
    } catch (err) {
        if (err === INVALID_TEMPLATE_ESCAPE_ERROR1) {
            this.readInvalidTemplateToken();
        } else {
            throw err;
        }
    }
    this.inTemplateElement = false;
};
pp$91.invalidStringToken = function(position, message) {
    if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
        throw INVALID_TEMPLATE_ESCAPE_ERROR1;
    } else {
        this.raise(position, message);
    }
};
pp$91.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 (isNewLine1(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$91.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$91.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$11(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 (this.strict) {
                this.invalidStringToken(this.pos - 1, "Invalid escape sequence");
            }
            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 (isNewLine1(ch)) {
                return "";
            }
            return String.fromCharCode(ch);
    }
};
pp$91.readHexChar = function(len) {
    var codePos = this.pos;
    var n = this.readInt(16, len);
    if (n === null) {
        this.invalidStringToken(codePos, "Bad character escape sequence");
    }
    return n;
};
pp$91.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 (isIdentifierChar1(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 ? isIdentifierStart1 : isIdentifierChar1)(esc, astral)) {
                this.invalidStringToken(escStart, "Invalid Unicode escape");
            }
            word += codePointToString$11(esc);
            chunkStart = this.pos;
        } else {
            break;
        }
        first = false;
    }
    return word + this.input.slice(chunkStart, this.pos);
};
pp$91.readWord = function() {
    var word = this.readWord1();
    var type = types2.name;
    if (this.keywords.test(word)) {
        type = keywords$11[word];
    }
    return this.finishToken(type, word);
};
var version1 = "8.4.0";
Parser1.acorn = {
    Parser: Parser1,
    version: version1,
    defaultOptions: defaultOptions1,
    Position: Position1,
    SourceLocation: SourceLocation1,
    getLineInfo: getLineInfo1,
    Node: Node2,
    TokenType: TokenType1,
    tokTypes: types2,
    keywordTypes: keywords$11,
    TokContext: TokContext1,
    tokContexts: types$11,
    isIdentifierChar: isIdentifierChar1,
    isIdentifierStart: isIdentifierStart1,
    Token: Token1,
    isNewLine: isNewLine1,
    lineBreak: lineBreak1,
    lineBreakG: lineBreakG1,
    nonASCIIwhitespace: nonASCIIwhitespace1
};
function parse31(input, options) {
    return Parser1.parse(input, options);
}
function parseExpressionAt2(input, pos, options) {
    return Parser1.parseExpressionAt(input, pos, options);
}
function tokenizer2(input, options) {
    return Parser1.tokenizer(input, options);
}
const mod2 = function() {
    return {
        Node: Node2,
        Parser: Parser1,
        Position: Position1,
        SourceLocation: SourceLocation1,
        TokContext: TokContext1,
        Token: Token1,
        TokenType: TokenType1,
        defaultOptions: defaultOptions1,
        getLineInfo: getLineInfo1,
        isIdentifierChar: isIdentifierChar1,
        isIdentifierStart: isIdentifierStart1,
        isNewLine: isNewLine1,
        keywordTypes: keywords$11,
        lineBreak: lineBreak1,
        lineBreakG: lineBreakG1,
        nonASCIIwhitespace: nonASCIIwhitespace1,
        parse: parse31,
        parseExpressionAt: parseExpressionAt2,
        tokContexts: types$11,
        tokTypes: types2,
        tokenizer: tokenizer2,
        version: version1,
        default: null
    };
}();
async function esbuildCompile(input, workingDir, args, format) {
    format = format ?? "esm";
    const fullArgs = [
        "--bundle",
        `--format=${format}`,
        ...args || []
    ];
    return await esbuildCommand(fullArgs, input, workingDir);
}
async function esbuildCommand(args, input, workingDir) {
    const cmd = [
        Deno.env.get("QUARTO_ESBUILD") || architectureToolsPath("esbuild"),
        ...args
    ];
    const result1 = await execProcess({
        cmd,
        cwd: workingDir,
        stdout: "piped"
    }, input);
    if (result1.success) {
        return result1.stdout;
    } else {
        throw new Error("esbuild command failed");
    }
}
function simple1(node, visitors, baseVisitor, state, override) {
    if (!baseVisitor) {
        baseVisitor = base1;
    }
    (function c(node2, st, override2) {
        var type = override2 || node2.type, found = visitors[type];
        baseVisitor[type](node2, st, c);
        if (found) {
            found(node2, st);
        }
    })(node, state, override);
}
function make1(funcs, baseVisitor) {
    var visitor = Object.create(baseVisitor || base1);
    for(var type in funcs){
        visitor[type] = funcs[type];
    }
    return visitor;
}
function skipThrough1(node, st, c) {
    c(node, st);
}
function ignore1(_node, _st, _c) {}
var base1 = {};
base1.Program = base1.BlockStatement = base1.StaticBlock = function(node, st, c) {
    for(var i1 = 0, list = node.body; i1 < list.length; i1 += 1){
        var stmt = list[i1];
        c(stmt, st, "Statement");
    }
};
base1.Statement = skipThrough1;
base1.EmptyStatement = ignore1;
base1.ExpressionStatement = base1.ParenthesizedExpression = base1.ChainExpression = function(node, st, c) {
    return c(node.expression, st, "Expression");
};
base1.IfStatement = function(node, st, c) {
    c(node.test, st, "Expression");
    c(node.consequent, st, "Statement");
    if (node.alternate) {
        c(node.alternate, st, "Statement");
    }
};
base1.LabeledStatement = function(node, st, c) {
    return c(node.body, st, "Statement");
};
base1.BreakStatement = base1.ContinueStatement = ignore1;
base1.WithStatement = function(node, st, c) {
    c(node.object, st, "Expression");
    c(node.body, st, "Statement");
};
base1.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 i1 = 0, list = cs.consequent; i1 < list.length; i1 += 1){
            var cons = list[i1];
            c(cons, st, "Statement");
        }
    }
};
base1.SwitchCase = function(node, st, c) {
    if (node.test) {
        c(node.test, st, "Expression");
    }
    for(var i1 = 0, list = node.consequent; i1 < list.length; i1 += 1){
        var cons = list[i1];
        c(cons, st, "Statement");
    }
};
base1.ReturnStatement = base1.YieldExpression = base1.AwaitExpression = function(node, st, c) {
    if (node.argument) {
        c(node.argument, st, "Expression");
    }
};
base1.ThrowStatement = base1.SpreadElement = function(node, st, c) {
    return c(node.argument, st, "Expression");
};
base1.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");
    }
};
base1.CatchClause = function(node, st, c) {
    if (node.param) {
        c(node.param, st, "Pattern");
    }
    c(node.body, st, "Statement");
};
base1.WhileStatement = base1.DoWhileStatement = function(node, st, c) {
    c(node.test, st, "Expression");
    c(node.body, st, "Statement");
};
base1.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");
};
base1.ForInStatement = base1.ForOfStatement = function(node, st, c) {
    c(node.left, st, "ForInit");
    c(node.right, st, "Expression");
    c(node.body, st, "Statement");
};
base1.ForInit = function(node, st, c) {
    if (node.type === "VariableDeclaration") {
        c(node, st);
    } else {
        c(node, st, "Expression");
    }
};
base1.DebuggerStatement = ignore1;
base1.FunctionDeclaration = function(node, st, c) {
    return c(node, st, "Function");
};
base1.VariableDeclaration = function(node, st, c) {
    for(var i1 = 0, list = node.declarations; i1 < list.length; i1 += 1){
        var decl = list[i1];
        c(decl, st);
    }
};
base1.VariableDeclarator = function(node, st, c) {
    c(node.id, st, "Pattern");
    if (node.init) {
        c(node.init, st, "Expression");
    }
};
base1.Function = function(node, st, c) {
    if (node.id) {
        c(node.id, st, "Pattern");
    }
    for(var i1 = 0, list = node.params; i1 < list.length; i1 += 1){
        var param = list[i1];
        c(param, st, "Pattern");
    }
    c(node.body, st, node.expression ? "Expression" : "Statement");
};
base1.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);
    }
};
base1.VariablePattern = ignore1;
base1.MemberPattern = skipThrough1;
base1.RestElement = function(node, st, c) {
    return c(node.argument, st, "Pattern");
};
base1.ArrayPattern = function(node, st, c) {
    for(var i1 = 0, list = node.elements; i1 < list.length; i1 += 1){
        var elt = list[i1];
        if (elt) {
            c(elt, st, "Pattern");
        }
    }
};
base1.ObjectPattern = function(node, st, c) {
    for(var i1 = 0, list = node.properties; i1 < list.length; i1 += 1){
        var prop = list[i1];
        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");
        }
    }
};
base1.Expression = skipThrough1;
base1.ThisExpression = base1.Super = base1.MetaProperty = ignore1;
base1.ArrayExpression = function(node, st, c) {
    for(var i1 = 0, list = node.elements; i1 < list.length; i1 += 1){
        var elt = list[i1];
        if (elt) {
            c(elt, st, "Expression");
        }
    }
};
base1.ObjectExpression = function(node, st, c) {
    for(var i1 = 0, list = node.properties; i1 < list.length; i1 += 1){
        var prop = list[i1];
        c(prop, st);
    }
};
base1.FunctionExpression = base1.ArrowFunctionExpression = base1.FunctionDeclaration;
base1.SequenceExpression = function(node, st, c) {
    for(var i1 = 0, list = node.expressions; i1 < list.length; i1 += 1){
        var expr = list[i1];
        c(expr, st, "Expression");
    }
};
base1.TemplateLiteral = function(node, st, c) {
    for(var i1 = 0, list = node.quasis; i1 < list.length; i1 += 1){
        var quasi = list[i1];
        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");
    }
};
base1.TemplateElement = ignore1;
base1.UnaryExpression = base1.UpdateExpression = function(node, st, c) {
    c(node.argument, st, "Expression");
};
base1.BinaryExpression = base1.LogicalExpression = function(node, st, c) {
    c(node.left, st, "Expression");
    c(node.right, st, "Expression");
};
base1.AssignmentExpression = base1.AssignmentPattern = function(node, st, c) {
    c(node.left, st, "Pattern");
    c(node.right, st, "Expression");
};
base1.ConditionalExpression = function(node, st, c) {
    c(node.test, st, "Expression");
    c(node.consequent, st, "Expression");
    c(node.alternate, st, "Expression");
};
base1.NewExpression = base1.CallExpression = function(node, st, c) {
    c(node.callee, st, "Expression");
    if (node.arguments) {
        for(var i1 = 0, list = node.arguments; i1 < list.length; i1 += 1){
            var arg = list[i1];
            c(arg, st, "Expression");
        }
    }
};
base1.MemberExpression = function(node, st, c) {
    c(node.object, st, "Expression");
    if (node.computed) {
        c(node.property, st, "Expression");
    }
};
base1.ExportNamedDeclaration = base1.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");
    }
};
base1.ExportAllDeclaration = function(node, st, c) {
    if (node.exported) {
        c(node.exported, st);
    }
    c(node.source, st, "Expression");
};
base1.ImportDeclaration = function(node, st, c) {
    for(var i1 = 0, list = node.specifiers; i1 < list.length; i1 += 1){
        var spec = list[i1];
        c(spec, st);
    }
    c(node.source, st, "Expression");
};
base1.ImportExpression = function(node, st, c) {
    c(node.source, st, "Expression");
};
base1.ImportSpecifier = base1.ImportDefaultSpecifier = base1.ImportNamespaceSpecifier = base1.Identifier = base1.PrivateIdentifier = base1.Literal = ignore1;
base1.TaggedTemplateExpression = function(node, st, c) {
    c(node.tag, st, "Expression");
    c(node.quasi, st, "Expression");
};
base1.ClassDeclaration = base1.ClassExpression = function(node, st, c) {
    return c(node, st, "Class");
};
base1.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);
};
base1.ClassBody = function(node, st, c) {
    for(var i1 = 0, list = node.body; i1 < list.length; i1 += 1){
        var elt = list[i1];
        c(elt, st);
    }
};
base1.MethodDefinition = base1.PropertyDefinition = base1.Property = function(node, st, c) {
    if (node.computed) {
        c(node.key, st, "Expression");
    }
    if (node.value) {
        c(node.value, st, "Expression");
    }
};
const walkerBase = make1({
    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 i1 = 0, list = node.body; i1 < list.length; i1 += 1){
                const stmt = list[i1];
                c(stmt, st, "Statement");
            }
        } else if (node.cells) {
            for(let i1 = 0, list = node.cells; i1 < list.length; i1 += 1){
                const stmt = list[i1];
                c(stmt, st);
            }
        } else {
            error("I don't know how to walk this node", node);
            throw new InternalError(`OJS traversal: I don't know how to walk this node: ${node}`);
        }
    }
});
function ojsSimpleWalker(parse, visitor) {
    simple1(parse, visitor, walkerBase);
}
function resolveResourceFilename(resource, rootDir) {
    if (resource.pathType == "relative") {
        const result1 = resolve2(rootDir, dirname2(resource.referent), resource.filename);
        return result1;
    } else if (resource.pathType === "root-relative") {
        const result1 = resolve2(rootDir, dirname2(resource.referent), `.${resource.filename}`);
        return result1;
    } else {
        throw new Error(`Unrecognized pathType ${resource.pathType}`);
    }
}
function uniqueResources(resourceList) {
    const result1 = [];
    const uniqResources = new Map();
    for (const resource of resourceList){
        if (!uniqResources.has(resource.filename)) {
            result1.push(resource);
            uniqResources.set(resource.filename, resource);
        }
    }
    return result1;
}
const resolveES6Path = (path, originDir, projectRoot)=>{
    if (path.startsWith("/")) {
        if (projectRoot === undefined) {
            return {
                pathType: "root-relative",
                resolvedImportPath: resolve2(originDir, `.${path}`)
            };
        } else {
            return {
                pathType: "root-relative",
                resolvedImportPath: resolve2(projectRoot, `.${path}`)
            };
        }
    } else {
        return {
            pathType: "relative",
            resolvedImportPath: resolve2(originDir, path)
        };
    }
};
const localImports = (parse)=>{
    const result1 = [];
    ojsSimpleWalker(parse, {
        ExportNamedDeclaration (node) {
            if (node.source?.value) {
                const source = node.source?.value;
                if (source.startsWith("/") || source.startsWith(".")) {
                    result1.push(source);
                }
            }
        },
        ImportDeclaration (node) {
            const source = node.source?.value;
            if (source.startsWith("/") || source.startsWith(".")) {
                result1.push(source);
            }
        }
    });
    return result1;
};
async function directDependencies(source, fileDir, language, projectRoot) {
    let ast;
    if (language === "js") {
        try {
            ast = parse31(source.value, {
                ecmaVersion: "2020",
                sourceType: "module"
            });
        } catch (e) {
            if (!(e instanceof SyntaxError)) {
                throw e;
            }
            return [];
        }
    } else if (language === "ojs") {
        try {
            ast = parseModule(source.value);
        } catch (e) {
            if (!(e instanceof SyntaxError)) throw e;
            return [];
        }
    } else {
        const ojsCellsSrc = (await breakQuartoMd(source)).cells.filter((cell)=>cell.cell_type !== "markdown" && cell.cell_type !== "raw" && cell.cell_type?.language === "ojs").flatMap((v)=>v.source);
        return await directDependencies(mappedConcat(ojsCellsSrc), fileDir, "ojs", projectRoot);
    }
    return localImports(ast).map((importPath)=>{
        const { resolvedImportPath, pathType } = resolveES6Path(importPath, fileDir, projectRoot);
        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?.language === "ojs") {
            pageResources.push(...await extractResourceDescriptionsFromOJSChunk(cell.source, mdDir, projectRoot));
        }
    }
    const result1 = new Set();
    for (const resource of uniqueResources(pageResources)){
        result1.add(resolveResourceFilename(resource, Deno.cwd()));
    }
    return Array.from(result1);
}
const literalFileAttachments = (parse)=>{
    const result1 = [];
    ojsSimpleWalker(parse, {
        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;
            }
            result1.push(args[0]?.value);
        }
    });
    return result1;
};
async function resolveImport(file, referent, projectRoot, mdDir, visited) {
    visited = visited ?? new Set();
    let source;
    const createdResources = [];
    if (!file.endsWith(".ts") && !file.endsWith(".tsx")) {
        try {
            source = Deno.readTextFileSync(file);
        } catch (_e) {
            error(`OJS dependency ${file} (from ${referent}) not found.`);
            throw new Error();
        }
        return {
            source,
            createdResources
        };
    }
    projectRoot = projectRoot ?? dirname2(referent);
    const deno = Deno.execPath();
    const p = Deno.run({
        cmd: [
            deno,
            "check",
            file,
            "-c",
            resourcePath("conf/deno-ts-compile.jsonc"),
            `--importmap=${resourcePath("conf/jsx-import-map.json")}`
        ],
        stderr: "piped"
    });
    const [status, stderr] = await Promise.all([
        p.status(),
        p.stderrOutput()
    ]);
    if (!status.success) {
        error("Compilation of typescript dependencies in ojs cell failed.");
        let errStr = new TextDecoder().decode(stderr);
        const errorLines = lines(stripColor2(errStr));
        const denoBugErrorLines = errorLines.map((l1, i1)=>({
                text: l1,
                line: i1
            })).filter((x)=>x.text.trim().indexOf("TS7026 [ERROR]: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists.") !== -1);
        console.log(errorLines);
        const errorCountRe = /^Found (\d+) errors.$/;
        const errorCount = Number((errorLines.filter((x)=>x.trim().match(errorCountRe))[0] ?? "Found 1 errors.").match(errorCountRe)[1]);
        if (denoBugErrorLines.length > 0) {
            const m = errorLines[denoBugErrorLines[0].line + 3].trim().match(/^.*(file:.+):\d+:\d+$/);
            if (m === null) {
                console.log(errStr);
                throw new InternalError("Internal error in deno ojs cell compilation.");
            }
            const badFile = fromFileUrl2(m[1]);
            const badContents = Deno.readTextFileSync(badFile);
            if (!badContents.startsWith("/** @jsxImportSource quarto-tsx */")) {
                console.log(`
File ${red(badFile)} must start with

${yellow("/** @jsxImportSource quarto-tsx */")}

We apologize for the inconvenience; this is a temporary workaround for an upstream bug.
`);
            }
            if (denoBugErrorLines.length !== errorCount) {
                console.log(`Other compilation errors follow below.\n`);
                let colorErrorLines = lines(errStr);
                for(let i1 = denoBugErrorLines.length - 1; i1 >= 0; i1--){
                    colorErrorLines.splice(denoBugErrorLines[i1].line, 5);
                }
                colorErrorLines = colorErrorLines.map((line)=>{
                    if (line.match(errorCountRe)) {
                        return `Found ${errorCount - denoBugErrorLines.length} errors.`;
                    }
                    return line;
                });
                errStr = colorErrorLines.slice(1).join("\n");
            }
            throw new Error();
        }
        console.log(errStr);
        throw new Error();
    }
    const localFile = file.replace(/[.]ts$/, ".js").replace(/[.]tsx$/, ".js");
    const fileDir = dirname2(localFile);
    if (!fileDir.startsWith(resolve2(projectRoot))) {
        error(`ERROR: File ${file} has typescript import dependency ${localFile},
outside of main folder ${resolve2(projectRoot)}. 
quarto will only generate javascript files in ${resolve2(projectRoot)} or subfolders.`);
        throw new Error();
    }
    const jsSource = await esbuildCommand([
        file,
        "--format=esm",
        "--sourcemap=inline",
        "--jsx-factory=window._ojs.jsx.createElement"
    ], "", fileDir);
    if (typeof jsSource === "undefined") {
        throw new InternalError(`esbuild compilation of file ${file} failed`);
    }
    let fixedSource = jsSource;
    const ast = parse31(jsSource, {
        ecmaVersion: "2020",
        sourceType: "module"
    });
    const recursionList = [];
    const patchDeclaration = (node)=>{
        if (node.source?.value.endsWith(".ts") || node.source?.value.endsWith(".tsx")) {
            recursionList.push(node.source.value);
            const rawReplacement = JSON.stringify(node.source.value.replace(/[.]ts$/, ".js").replace(/[.]tsx$/, ".js"));
            fixedSource = fixedSource.substring(0, node.source.start) + rawReplacement + fixedSource.slice(node.source.end);
        }
    };
    ojsSimpleWalker(ast, {
        ExportNamedDeclaration: patchDeclaration,
        ImportDeclaration: patchDeclaration
    });
    for (const tsImport of recursionList){
        if (!visited.has(tsImport)) {
            visited.add(tsImport);
            const { createdResources: recursionCreatedResources } = await resolveImport(resolve2(dirname2(file), tsImport), file, projectRoot, mdDir, visited);
            createdResources.push(...recursionCreatedResources);
        }
    }
    const transformedSource = fixedSource;
    Deno.writeTextFileSync(localFile, transformedSource);
    createdResources.push({
        pathType: "relative",
        resourceType: "import",
        referent,
        filename: resolve2(dirname2(referent), localFile),
        importPath: `./${relative2(resolve2(mdDir), localFile)}`
    });
    source = Deno.readTextFileSync(localFile);
    return {
        source,
        createdResources
    };
}
async function extractResourceDescriptionsFromOJSChunk(ojsSource, mdDir, projectRoot) {
    let result1 = [];
    const handled = new Set();
    const imports = new Map();
    const rootReferent = `${mdDir}/<<root>>.qmd`;
    for (const { resolvedImportPath, pathType, importPath } of (await directDependencies(ojsSource, mdDir, "ojs", projectRoot))){
        if (!imports.has(resolvedImportPath)) {
            const v = {
                filename: resolvedImportPath,
                referent: rootReferent,
                pathType,
                importPath,
                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);
        const resolvedImport = await resolveImport(thisResolvedImportPath, importResource.referent, projectRoot, mdDir);
        if (resolvedImport === undefined) {
            console.error(`WARNING: While following dependencies, could not resolve reference:`);
            console.error(`  Reference: ${importResource.importPath}`);
            console.error(`  In file: ${importResource.referent}`);
            continue;
        }
        const source = resolvedImport.source;
        result1.push(...resolvedImport.createdResources);
        if (projectRoot) {
            getNamedLifetime(kRenderServicesLifetime, true).attach({
                cleanup () {
                    for (const res of resolvedImport.createdResources){
                        try {
                            Deno.removeSync(res.filename);
                        } catch (e) {
                            if (e.name !== "NotFound") {
                                throw e;
                            }
                        }
                    }
                    return;
                }
            });
        }
        let language;
        if (thisResolvedImportPath.endsWith(".js") || thisResolvedImportPath.endsWith(".ts") || thisResolvedImportPath.endsWith(".tsx")) {
            language = "js";
        } else if (thisResolvedImportPath.endsWith(".ojs")) {
            language = "ojs";
        } else if (thisResolvedImportPath.endsWith(".qmd")) {
            language = "qmd";
        } else {
            throw new Error(`Unknown 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") && !description.filename.endsWith(".ts") && !description.filename.endsWith(".tsx"));
    result1 = result1.map((description)=>{
        const { referent, resourceType, importPath, pathType } = description;
        let relName = relative2(mdDir, description.filename);
        if (!relName.startsWith(".")) {
            relName = `./${relName}`;
        }
        return {
            filename: relName,
            referent,
            importPath,
            pathType,
            resourceType
        };
    });
    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 = encodeBase64(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 result1 = [
        ...jsModuleResolves,
        ...ojsFiles.map((f)=>[
                f.importPath,
                asDataURL(Deno.readTextFileSync(f.filename), "application/ojs-javascript")
            ]),
        ...attachments.map((f)=>{
            const resolvedFileName = resolveResourceFilename(f, Deno.cwd());
            const mimeType = lookup1(resolvedFileName) || "application/octet-stream";
            return [
                f.filename,
                asDataURL(Deno.readFileSync(resolvedFileName).buffer, mimeType)
            ];
        })
    ];
    return result1;
}
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, excludeDirs, markdown, globs, skipOjsDiscovery) {
    const ignore = engineIgnoreGlobs().concat(kQuartoScratch + "/").concat([
        "**/.*",
        "**/.*/**"
    ]).concat(...excludeDirs);
    const resources = resolvePathGlobs(fileDir, globs, ignore, {
        mode: "always",
        explicitSubfolderSearch: true
    });
    if (markdown.length > 0 && !skipOjsDiscovery) {
        resources.include.push(...await extractResolvedResourceFilenamesFromQmd(asMappedString(markdown), fileDir, rootDir));
    }
    return resources;
}
function resourceFilesFromRenderedFile(baseDir, excludeDirs, renderedFile, partitioned) {
    return resourceFilesFromFile(baseDir, excludeDirs, renderedFile.file, renderedFile.resourceFiles, renderedFile.selfContained, renderedFile.supporting, partitioned, true);
}
async function resourceFilesFromFile(baseDir, excludeDirs, file, resources, selfContained, supporting, partitioned, skipOjsDiscovery) {
    const resourceDir = join2(baseDir, dirname2(file));
    const markdown = partitioned ? partitioned.markdown : "";
    const globs = resources.globs;
    const fileResourceFiles = await resolveFileResources(baseDir, resourceDir, excludeDirs, markdown, globs, skipOjsDiscovery);
    if (!selfContained) {
        const resultFiles = resources.files.map((file)=>join2(resourceDir, file)).filter(safeExistsSync).map(normalizePath);
        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(join2(baseDir, support)))) {
            return false;
        } else {
            return true;
        }
    });
    return __VIRTUAL_FILE181(resourceFiles);
}
const kQuartoHtmlDependency = "quarto-html";
const kNotebookViewStyleNotebook = "notebook";
function generateCssKeyValues(textValues) {
    const lines = [];
    Object.keys(textValues).forEach((textAttr)=>{
        switch(textAttr){
            case "text-color":
                lines.push(`color: ${textValues[textAttr]};`);
                break;
            case "background-color":
                lines.push(`background-color: ${textValues[textAttr]};`);
                break;
            case "bold":
                if (textValues[textAttr]) {
                    lines.push("font-weight: bold;");
                }
                break;
            case "italic":
                if (textValues[textAttr]) {
                    lines.push("font-style: italic;");
                } else {
                    lines.push("font-style: inherit;");
                }
                break;
            case "underline":
                if (textValues[textAttr]) {
                    lines.push("text-decoration: underline;");
                }
                break;
        }
    });
    return lines;
}
function cssHasDarkModeSentinel(css) {
    return !!css.match(/\/\*! dark \*\//g);
}
async function resolveSassBundles(inputDir, extras, format, 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);
            const cssResult = processCssIntoExtras(cssPath, extras, temp);
            cssPath = cssResult.path;
            for (const bundle of target.bundles){
                if (bundle.attribs) {
                    for (const key of Object.keys(bundle.attribs)){
                        if (target.attribs[key] === undefined) {
                            target.attribs[key] = bundle.attribs[key];
                        }
                    }
                }
            }
            target.attribs["data-mode"] = cssResult.dark ? "dark" : "light";
            const css = Deno.readTextFileSync(cssPath);
            const toDependencies = (paths)=>{
                return paths.map((path)=>{
                    return {
                        name: path,
                        path: project ? join2(project.dir, path) : path,
                        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(inputDir, extras, format, temp, hasDarkStyles ? "light" : "default", defaultStyle);
    if (hasDarkStyles) {
        extras = await resolveQuartoSyntaxHighlighting(inputDir, extras, format, temp, "dark", defaultStyle);
    }
    if (isHtmlOutput(format.pandoc, true)) {
        setTextHighlightStyle("none", extras);
    }
    return extras;
}
async function resolveQuartoSyntaxHighlighting(inputDir, extras, format, temp, style, defaultStyle) {
    const minimal = format.metadata[kMinimal] === true;
    if (minimal) {
        return extras;
    }
    extras = cloneDeep1(extras);
    const mediaAttr = attribForThemeStyle(style, defaultStyle);
    if (style === "default") {
        if (extras.html?.[kTextHighlightingMode] === "dark") {
            style = "dark";
        }
    }
    mediaAttr.id = "quarto-text-highlighting-styles";
    const cssFileName = `quarto-syntax-highlighting${style === "dark" ? "-dark" : ""}.css`;
    const themeDescriptor = readHighlightingTheme(inputDir, format.pandoc, style);
    if (themeDescriptor) {
        const extraVariables = extras.html?.[kQuartoCssVariables] || [];
        const highlightCss = generateThemeCssVars(themeDescriptor.json);
        if (highlightCss) {
            const rules = [
                highlightCss,
                "",
                "/* other quarto variables */",
                ...extraVariables
            ];
            const textHighlightCssRules = generateThemeCssClasses(themeDescriptor.json);
            if (textHighlightCssRules) {
                rules.push(...textHighlightCssRules);
            }
            rules.push(".prevent-inlining { content: '</' }");
            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 quartoDependency = extraDeps.find((extraDep)=>extraDep.name === kQuartoHtmlDependency);
                const existingDependency = quartoDependency;
                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 lines = [];
        lines.push("/* quarto syntax highlight colors */");
        lines.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":
                            lines.push(`  --quarto-hl-${abbr}-color: ${textValues[textAttr] || "inherit"};`);
                            break;
                    }
                });
            }
        });
        lines.push("}");
        return lines.join("\n");
    }
    return undefined;
}
function generateThemeCssClasses(themeJson) {
    const textStyles = themeJson["text-styles"];
    if (textStyles) {
        const lines = [];
        Object.keys(textStyles).forEach((styleName)=>{
            const abbr = kAbbrevs[styleName];
            if (abbr !== undefined) {
                const textValues = textStyles[styleName];
                const cssValues = generateCssKeyValues(textValues);
                if (abbr !== "") {
                    lines.push(`\ncode span.${abbr} {`);
                    lines.push(...cssValues);
                    lines.push("}\n");
                } else {
                    [
                        "pre > code.sourceCode > span",
                        "code span",
                        "code.sourceCode > span",
                        "div.sourceCode,\ndiv.sourceCode pre.sourceCode"
                    ].forEach((selector)=>{
                        lines.push(`\n${selector} {`);
                        lines.push(...cssValues);
                        lines.push("}\n");
                    });
                }
            }
        });
        return lines;
    }
    return undefined;
}
function processCssIntoExtras(cssPath, extras, temp) {
    extras.html = extras.html || {};
    const css = Deno.readTextFileSync(cssPath).replaceAll(kSourceMappingRegexes[0], "").replaceAll(kSourceMappingRegexes[1], "");
    const hasDarkSentinel = cssHasDarkModeSentinel(css);
    if (!extras.html[kTextHighlightingMode] && hasDarkSentinel) {
        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"
            });
            let mode;
            if (Deno.build.os !== "windows") {
                const stat = Deno.statSync(cssPath);
                if (stat.mode !== null) {
                    mode = stat.mode;
                }
            }
            if (mode !== undefined) {
                Deno.writeTextFileSync(newCssPath, cleanedCss, {
                    mode
                });
            } else {
                Deno.writeTextFileSync(newCssPath, cleanedCss);
            }
            return {
                dark: hasDarkSentinel,
                path: newCssPath
            };
        }
    }
    return {
        dark: hasDarkSentinel,
        path: cssPath
    };
}
const kVariablesRegex = /\/\*\! quarto-variables-start \*\/([\S\s]*)\/\*\! quarto-variables-end \*\//g;
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;
}
const kName = "name";
const kGiven = "given";
const kFamily = "family";
const kDropping = "dropping-particle";
const kNonDropping = "non-dropping-particle";
const kAffiliation = "affiliation";
const kAfilliationUrl = "affiliation-url";
const kOrcid = "orcid";
const kUrl = "url";
function cslNameToString(cslName) {
    if (typeof cslName === "string") {
        return cslName;
    } else {
        if (cslName.literal) {
            return cslName.literal;
        } else {
            const parts = [];
            if (cslName.given) {
                parts.push(cslName.given);
            }
            if (cslName["dropping-particle"]) {
                parts.push(cslName["dropping-particle"]);
            }
            if (cslName["non-dropping-particle"]) {
                parts.push(cslName["non-dropping-particle"]);
            }
            if (cslName.family) {
                parts.push(cslName.family);
            }
            return parts.join(" ");
        }
    }
}
function parseAuthor(authorRaw, strict) {
    if (authorRaw) {
        const parsed = [];
        const authors = Array.isArray(authorRaw) ? authorRaw : [
            authorRaw
        ];
        let unrecognized = 0;
        authors.forEach((author)=>{
            if (typeof author === "string") {
                parsed.push({
                    name: author
                });
            } else if (typeof author === "object") {
                const name = author[kName];
                if (name) {
                    const auth = {
                        name
                    };
                    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);
                } else if (author[kFamily]) {
                    const given = author[kGiven];
                    const family = author[kFamily];
                    const dropping = author[kDropping];
                    const nonDropping = author[kNonDropping];
                    parsed.push({
                        name: {
                            [kGiven]: given,
                            [kFamily]: family,
                            [kDropping]: dropping,
                            [kNonDropping]: nonDropping
                        }
                    });
                } else {
                    unrecognized = unrecognized + 1;
                }
            }
        });
        if (strict && unrecognized > 0) {
            return undefined;
        } else {
            return parsed;
        }
    } else {
        return undefined;
    }
}
class Token2 {
    constructor(value, type){
        this._value = value;
        this._type = type;
        this._format = "";
    }
    get value() {
        return this._value;
    }
    set value(value) {
        this._value = value;
    }
    get type() {
        return this._type;
    }
    set type(type) {
        this._type = type;
    }
    get format() {
        return this._format;
    }
    set format(format) {
        this._format = format;
    }
}
class Parser2 {
    constructor(name, pattern){
        this.name = name;
        this.pattern = pattern;
    }
    parse(date) {
        const match = this.pattern.exec(date);
        if (!match || !match.groups) {
            return;
        }
        let tokens = [];
        for (const [key, val] of Object.entries(match.groups)){
            if (val) {
                tokens.push(new Token2(val, /delim\d+/.test(key) ? "delimiter" : key));
            }
        }
        return {
            tokens,
            index: match.index,
            parser: this.name
        };
    }
}
const abbreviatedTimezones = "UT|CAT|CET|CVT|EAT|EET|GMT|MUT|RET|SAST|SCT|WAST|WAT|WEST|WET|WST|WT|ADT|AFT|ALMT|AMST|AMT|ANAST|ANAT|AQTT|AST|AZST|AZT|BNT|BST|BTT|CHOST|CHOT|CST|EEST|EET|GET|GST|HKT|HOVST|HOVT|ICT|IDT|IRDT|IRKST|IRKT|IST|JST|KGT|KRAST|KRAT|KST|MAGST|MAGT|MMT|MSK|MVT|NOVST|NOVT|NPT|OMSST|OMST|ORAT|PETST|PETT|PHT|PKT|PYT|QYZT|SAKT|SGT|SRET|TJT|TLT|TMT|TRT|ULAST|ULAT|UZT|VLAST|VLAT|WIB|WIT|YAKST|YAKT|YEKST|YEKT|ART|CAST|CEST|CLST|CLT|DAVT|DDUT|GMT|MAWT|NZDT|NZST|ROTT|SYOT|VOST|ADT|AST|AT|AZOST|AZOT|ACDT|ACST|ACT|ACWST|AEDT|AEST|AET|AWDT|AWST|CXT|LHDT|LHST|NFDT|NFT|AST|AT|CDT|CIDST|CIST|CST|EDT|EST|ET|CST|CT|EST|ET|BST|CEST|CET|EEST|EET|FET|GET|GMT|IST|KUYT|MSD|MSK|SAMT|TRT|WEST|WET|CCT|EAT|IOT|TFT|ADT|AKDT|AKST|AST|AT|CDT|CST|CT|EDT|EGST|EGT|ET|GMT|HDT|HST|MDT|MST|MT|NDT|NST|PDT|PMDT|PMST|PST|PT|WGST|WGT|AoE|BST|CHADT|CHAST|CHUT|CKT|ChST|EASST|EAST|FJST|FJT|GALT|GAMT|GILT|HST|KOST|LINT|MART|MHT|NCT|NRT|NUT|NZDT|NZST|PGT|PHOT|PONT|PST|PWT|SBT|SST|TAHT|TKT|TOST|TOT|TVT|VUT|WAKT|WFT|WST|YAPT|ACT|AMST|AMT|ART|BOT|BRST|BRT|CLST|CLT|COT|ECT|FKST|FKT|FNT|GFT|GST|GYT|PET|PYST|PYT|SRT|UYST|UYT|VET|WARST";
const dayOfMonthAndMonthNameDateFormatParser = new Parser2("DayOfMonthAndMonthNameDateFormatParser", new RegExp(`^(?<dayOfWeek>(?:Sun?|Mon?|Tu(?:es)?|We(?:dnes)?|Th(?:urs)?|Fri?|Sa(?:tur)?)(?:day)?)?(?<delim1>,)?(?<delim2>\\s)?(?<dayOfMonth>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:st|nd|rd|th)?)(?<delim3>\\s)(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?<delim4>,)?(?<delim5>\\s)?(?<year>\\d{4}|\\d{2})?(?:(?<delim6>,)?(?<delim7>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim8>[:.])(?<minute>[0-5]\\d))?(?:(?<delim9>[:.])(?<second>[0-5]\\d))?(?:(?<delim10>.)(?<millisecond>\\d{3}))?(?<delim11>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim12>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?$`));
const iSO8601BasicDateTimeFormatParser = new Parser2("ISO8601BasicDateTimeFormatParser", new RegExp("^(?<year>[+-]\\d{6}|\\d{4})(?:(?<month>\\d{2})(?:(?<dayOfMonth>\\d{2}))?|(?<escapeText>W)(?<isoWeekOfYear>\\d{2})(?:(?<isoDayOfWeek>\\d))?|(?<dayOfYear>\\d{3}))?(?:(?<delim1>T| )(?:(?<twentyFourHour>\\d{2})(?:(?<minute>\\d{2})(?:(?<second>\\d{2})(?:(?<delim2>[.,])(?<millisecond>\\d{1,9}))?)?)?)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z)?)?$"));
const iSO8601ExtendedDateTimeFormatParser = new Parser2("ISO8601ExtendedDateTimeFormatParser", new RegExp("^(?<year>[+-]\\d{6}|\\d{4})(?<delim1>\\-)(?:(?<month>\\d{2})(?:(?<delim2>\\-)(?<dayOfMonth>\\d{2}))?|(?<escapeText>W)(?<isoWeekOfYear>\\d{2})(?:(?<delim3>\\-)(?<isoDayOfWeek>\\d))?|(?<dayOfYear>\\d{3}))(?:(?<delim4>T| )(?:(?<twentyFourHour>\\d{2})(?:(?<delim5>:)(?<minute>\\d{2})(?:(?<delim6>:)(?<second>\\d{2})(?:(?<delim7>[.,])(?<millisecond>\\d{1,9}))?)?)?)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z)?)?$"));
const monthNameAndDayOfMonthDateFormatParser = new Parser2("MonthNameAndDayOfMonthDateFormatParser", new RegExp(`^(?<dayOfWeek>(?:Sun?|Mon?|Tu(?:es)?|We(?:dnes)?|Th(?:urs)?|Fri?|Sa(?:tur)?)(?:day)?)?(?<delim1>,)?(?<delim2>\\s)?(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?<delim3>\\s)(?<dayOfMonth>(?:3[0-1]|[1-2]\\d|0?[1-9])(?:st|nd|rd|th)?)(?<delim4>,)?(?<delim5>\\s)?(?<year>\\d{4}|\\d{2})?(?:(?:(?<delim6>,)?(?<delim7>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim8>[:.])(?<minute>[0-5]\\d))?(?:(?<delim9>[:.])(?<second>[0-5]\\d))?(?:(?<delim10>.)(?<millisecond>\\d{3}))?(?<delim11>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim12>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
const rFC2822DateTimeFormatParser = new Parser2("RFC2822DateTimeFormatParser", new RegExp("^(?:(?<dayOfWeek>Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?<delim1>,)?(?<delim2>\\s))?(?<dayOfMonth>\\d{1,2})(?<delim3>\\s)(?<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(?<delim4>\\s)(?<year>\\d{2,4})(?<delim5>\\s)(?<twentyFourHour>\\d{2})(?<delim6>:)(?<minute>\\d{2})(?:(?<delim7>:)(?<second>\\d{2}))?(?<delim8>\\s)(?<timezone>(?:(?:UT|GMT|[ECMP][SD]T)|[Zz]|[+-]\\d{4}))$"));
const slashDelimitedDateTimeFormatParser = new Parser2("SlashDelimitedDateFormatParser", new RegExp(`^(?<year>\\d{4}|\\d{2})(?<delim1>[/.-])(?<month>0?[1-9]|1[0-2])(?:(?<delim2>[/.-])(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1]))?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
const twelveHourTimeFormatParser = new Parser2("TwelveHourTimeFormatParser", new RegExp(`^(?<twelveHour>0?[1-9]|1[0-2])(?:(?<delim1>[:.])(?<minute>[0-5]\\d))?(?:(?<delim2>[:.])(?<second>[0-5]\\d))?(?:(?<delim3>.)(?<millisecond>\\d{3}))?(?<delim4>\\s)?(?<meridiem>am|pm|AM|PM)(?:(?<delim5>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?$`));
const twentyFourHourTimeFormatParser = new Parser2("TwentyFourHourTimeFormatParser", new RegExp(`^(?<twentyFourHour>2[0-3]|0?\\d|1\\d)(?<delim1>[:.])(?<minute>[0-5]\\d)(?:(?<delim2>[:.])(?<second>[0-5]\\d))?(?:(?<delim3>.)(?<millisecond>\\d{3}))?(?:(?<delim4>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?$`));
const uKStyleSlashDelimitedDateTimeFormatParser = new Parser2("UKStyleSlashDelimitedDateFormatParser", new RegExp(`^(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])(?<delim1>[/.-])(?<month>0?[1-9]|1[0-2])(?:(?<delim2>[/.-])(?<year>\\d{4}|\\d{2}))?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
const uSStyleSlashDelimitedDateTimeFormatParser = new Parser2("USStyleSlashDelimitedDateFormatParser", new RegExp(`^(?<month>0?[1-9]|1[0-2])(?<delim1>[/.-])(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])(?:(?<delim2>[/.-])(?<year>\\d{4}|\\d{2}))?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
const dashDelimitedWithMonthNameDateTimeFormatParser = new Parser2("DashDelimitedWithMonthNameDateTimeFormatParser", new RegExp(`^(?<dayOfMonth>0?[1-9]|[1-2]\\d|3[0-1])(?<delim1>-)(?<month>Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)(?<delim2>-)?(?<year>\\d{4}|\\d{2})?(?:(?:(?<delim3>,)?(?<delim4>\\s)(?:(?<twentyFourHour>2[0-3]|0?\\d|1\\d)|(?<twelveHour>0?[1-9]|1[0-2]))(?:(?<delim5>[:.])(?<minute>[0-5]\\d))?(?:(?<delim6>[:.])(?<second>[0-5]\\d))?(?:(?<delim7>.)(?<millisecond>\\d{3}))?(?<delim8>\\s)?(?<meridiem>am|pm|AM|PM)?(?:(?<delim9>\\s)(?<timezone>[+-]\\d{2}(?::?\\d{2})?|Z|${abbreviatedTimezones}))?)?)?$`));
const parsers = [
    iSO8601ExtendedDateTimeFormatParser,
    iSO8601BasicDateTimeFormatParser,
    rFC2822DateTimeFormatParser,
    slashDelimitedDateTimeFormatParser,
    uKStyleSlashDelimitedDateTimeFormatParser,
    uSStyleSlashDelimitedDateTimeFormatParser,
    monthNameAndDayOfMonthDateFormatParser,
    dayOfMonthAndMonthNameDateFormatParser,
    twentyFourHourTimeFormatParser,
    twelveHourTimeFormatParser,
    dashDelimitedWithMonthNameDateTimeFormatParser
];
class StandardFormatParsersRefiner {
    constructor(name){
        this.name = name;
    }
    refine(parsedResults) {
        const res = parsedResults.filter((r)=>{
            return r.parser === "ISO8601ExtendedDateTimeFormatParser" || r.parser === "ISO8601BasicDateTimeFormatParser" || r.parser === "RFC2822DateTimeFormatParser";
        });
        if (res.length === 0) {
            return parsedResults;
        }
        return res;
    }
}
class TimeFormatRefiner {
    constructor(name){
        this.name = name;
    }
    refine(parsedResults) {
        parsedResults.forEach((r)=>{
            let meridiemExists = false;
            r.tokens.forEach((t)=>{
                if (t.type === "meridiem") {
                    meridiemExists = true;
                }
            });
            if (meridiemExists) {
                r.tokens.forEach((t)=>{
                    if (t.type === "twentyFourHour") {
                        t.type = "twelveHour";
                    }
                });
            }
        });
        return parsedResults;
    }
}
const timeFormatRefiner = new TimeFormatRefiner("TimeFormatRefiner");
const standardFormatParsersRefiner = new StandardFormatParsersRefiner("StandardFormatParsersRefiner");
const refiners = [
    standardFormatParsersRefiner,
    timeFormatRefiner
];
class YearFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{2}/, "YY");
            this._map.set(/\d{4}/, "YYYY");
            this._map.set(/[+-]\d{6}/, "YYYYYY");
        } else {
            this._map.set(/\d{2}/, "%y");
            this._map.set(/\d{4}/, "%Y");
            this._map.set(/[+-]\d{6}/, "NA");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class MonthFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{1,2}/, "M");
            this._map.set(/\d{2}/, "MM");
            this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "Mo");
            this._map.set(/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/, "MMM");
            this._map.set(/^(January|February|March|April|May|June|July|August|September|October|November|December)$/, "MMMM");
        } else {
            this._map.set(/\d{1,2}/, "NA");
            this._map.set(/\d{2}/, "%m");
            this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "NA");
            this._map.set(/^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/, "%b");
            this._map.set(/^(January|February|March|April|May|June|July|August|September|October|November|December)$/, "%B");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class DayOfMonthFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{1,2}/, "D");
            this._map.set(/\d{2}/, "DD");
            this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "Do");
        } else {
            this._map.set(/\d{1,2}/, "%-e");
            this._map.set(/\d{2}/, "%d");
            this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "%o");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class DelimiterFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.format = format;
        this.type = type;
    }
    assign(token) {}
}
class MinuteFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{1,2}/, "m");
            this._map.set(/\d{2}/, "mm");
        } else {
            this._map.set(/\d{1,2}/, "NA");
            this._map.set(/\d{2}/, "%M");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class SecondFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{1,2}/, "s");
            this._map.set(/\d{2}/, "ss");
        } else {
            this._map.set(/\d{1,2}/, "NA");
            this._map.set(/\d{2}/, "%S");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class MillisecondFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d/, "S");
            this._map.set(/\d{2}/, "SS");
            this._map.set(/\d{3}/, "SSS");
        } else {
            this._map.set(/\d/, "NA");
            this._map.set(/\d{2}/, "NA");
            this._map.set(/\d{3}/, "%L");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class TimezoneFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        const abbreviatedTimezoneRegex = new RegExp("UT|CAT|CET|CVT|EAT|EET|GMT|MUT|RET|SAST|SCT|WAST|WAT|WEST|WET|WST|WT|ADT|AFT|ALMT|AMST|AMT|ANAST|ANAT|AQTT|AST|AZST|AZT|BNT|BST|BTT|CHOST|CHOT|CST|EEST|EET|GET|GST|HKT|HOVST|HOVT|ICT|IDT|IRDT|IRKST|IRKT|IST|JST|KGT|KRAST|KRAT|KST|MAGST|MAGT|MMT|MSK|MVT|NOVST|NOVT|NPT|OMSST|OMST|ORAT|PETST|PETT|PHT|PKT|PYT|QYZT|SAKT|SGT|SRET|TJT|TLT|TMT|TRT|ULAST|ULAT|UZT|VLAST|VLAT|WIB|WIT|YAKST|YAKT|YEKST|YEKT|ART|CAST|CEST|CLST|CLT|DAVT|DDUT|GMT|MAWT|NZDT|NZST|ROTT|SYOT|VOST|ADT|AST|AT|AZOST|AZOT|ACDT|ACST|ACT|ACWST|AEDT|AEST|AET|AWDT|AWST|CXT|LHDT|LHST|NFDT|NFT|AST|AT|CDT|CIDST|CIST|CST|EDT|EST|ET|CST|CT|EST|ET|BST|CEST|CET|EEST|EET|FET|GET|GMT|IST|KUYT|MSD|MSK|SAMT|TRT|WEST|WET|CCT|EAT|IOT|TFT|ADT|AKDT|AKST|AST|AT|CDT|CST|CT|EDT|EGST|EGT|ET|GMT|HDT|HST|MDT|MST|MT|NDT|NST|PDT|PMDT|PMST|PST|PT|WGST|WGT|AoE|BST|CHADT|CHAST|CHUT|CKT|ChST|EASST|EAST|FJST|FJT|GALT|GAMT|GILT|HST|KOST|LINT|MART|MHT|NCT|NRT|NUT|NZDT|NZST|PGT|PHOT|PONT|PST|PWT|SBT|SST|TAHT|TKT|TOST|TOT|TVT|VUT|WAKT|WFT|WST|YAPT|ACT|AMST|AMT|ART|BOT|BRST|BRT|CLST|CLT|COT|ECT|FKST|FKT|FNT|GFT|GST|GYT|PET|PYST|PYT|SRT|UYST|UYT|VET|WARST");
        if (!format || format === "default") {
            this._map.set(/[+-]\d{2}(?::\d{2})?/, "Z");
            this._map.set(/[+-]\d{4}/, "ZZ");
            this._map.set(/Z/, "[Z]");
            this._map.set(/z/, "[z]");
            this._map.set(abbreviatedTimezoneRegex, "z");
        } else {
            this._map.set(/[+-]\d{2}(?::\d{2})?/, "%:z");
            this._map.set(/[+-]\d{4}/, "%z");
            this._map.set(/Z/, "Z");
            this._map.set(/z/, "z");
            this._map.set(abbreviatedTimezoneRegex, "%Z");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class DayOfYearFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{1,3}/, "DDD");
            this._map.set(/\d{3}/, "DDDD");
            this._map.set(/\d{1,3}(?:st|nd|rd|th)/, "DDDo");
        } else {
            this._map.set(/\d{1,3}/, "NA");
            this._map.set(/\d{3}/, "%j");
            this._map.set(/\d{1,3}(?:st|nd|rd|th)/, "NA");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class EscapeTextFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        if (this._testTokenType(token)) {
            token.format = !this.format || this.format === "default" ? `[${token.value}]` : token.value;
        }
    }
}
class ISODayOfWeekFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/[1-7]/, "E");
        } else {
            this._map.set(/[1-7]/, "%u");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class ISOWeekOfYearFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/\d{1,2}/, "W");
            this._map.set(/\d{2}/, "WW");
            this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "Wo");
        } else {
            this._map.set(/\d{1,2}/, "NA");
            this._map.set(/\d{2}/, "%U");
            this._map.set(/\d{1,2}(?:st|nd|rd|th)/, "NA");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class TwentyFourHourFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/^(\d|1\d|2[0-3])$/, "H");
            this._map.set(/^([0-1]\d|2[0-3])$/, "HH");
        } else {
            this._map.set(/^(\d|1\d|2[0-3])$/, "%-k");
            this._map.set(/^([0-1]\d|2[0-3])$/, "%H");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class TwelveHourFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/^([1-9]|1[0-2])$/, "h");
            this._map.set(/^(0\d|1[0-2])$/, "hh");
        } else {
            this._map.set(/^([1-9]|1[0-2])$/, "%-l");
            this._map.set(/^(0\d|1[0-2])$/, "%I");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class DayOfWeekFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/[0-6]/, "d");
            this._map.set(/[0-6](?:st|nd|rd|th)/, "do");
            this._map.set(/(?:Su|Mo|Tu|We|Th|Fr|Sa)/, "dd");
            this._map.set(/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)/, "ddd");
            this._map.set(/(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)/, "dddd");
        } else {
            this._map.set(/[0-6]/, "%w");
            this._map.set(/[0-6](?:st|nd|rd|th)/, "NA");
            this._map.set(/(?:Su|Mo|Tu|We|Th|Fr|Sa)/, "NA");
            this._map.set(/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)/, "%a");
            this._map.set(/(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)/, "%A");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
class MeridiemFormatTokenAssigner {
    constructor(name, type, format){
        this.name = name;
        this.type = type;
        this.format = format;
        this._map = new Map();
        if (!format || format === "default") {
            this._map.set(/am|pm/, "a");
            this._map.set(/AM|PM/, "A");
        } else {
            this._map.set(/am|pm/, "%P");
            this._map.set(/AM|PM/, "%p");
        }
    }
    _testTokenType(token) {
        return token.type === this.type;
    }
    assign(token) {
        this._map.forEach((formatToken, pattern)=>{
            if (this._testTokenType(token) && pattern.test(token.value)) {
                token.format = formatToken;
            }
        });
    }
}
const dayOfMonthFormatTokenAssigner = new DayOfMonthFormatTokenAssigner("DelimiterFormatTokenAssigner", "dayOfMonth");
const dayOfWeekFormatTokenAssigner = new DayOfWeekFormatTokenAssigner("DayOfWeekFormatTokenAssigner", "dayOfWeek");
const dayOfYearFormatTokenAssigner = new DayOfYearFormatTokenAssigner("DayOfYearFormatTokenAssigner", "dayOfYear");
const delimiterFormatTokenAssigner = new DelimiterFormatTokenAssigner("DelimiterFormatTokenAssigner", "delimiter");
const escapeTextFormatTokenAssigner = new EscapeTextFormatTokenAssigner("EscapeTextFormatTokenAssigner", "escapeText");
const iSODayOfWeekFormatTokenAssigner = new ISODayOfWeekFormatTokenAssigner("ISODayOfWeekFormatTokenAssigner", "isoDayOfWeek");
const iSOWeekOfYearFormatTokenAssigner = new ISOWeekOfYearFormatTokenAssigner("ISOWeekOfYearFormatTokenAssigner", "isoWeekOfYear");
const meridiemFormatTokenAssigner = new MeridiemFormatTokenAssigner("MeridiemFormatTokenAssigner", "meridiem");
const millisecondFormatTokenAssigner = new MillisecondFormatTokenAssigner("MillisecondFormatTokenAssigner", "millisecond");
const minuteFormatTokenAssigner = new MinuteFormatTokenAssigner("MinuteFormatTokenAssigner", "minute");
const monthFormatTokenAssigner = new MonthFormatTokenAssigner("MonthFormatTokenAssigner", "month");
const secondFormatTokenAssigner = new SecondFormatTokenAssigner("SecondFormatTokenAssigner", "second");
const timezoneFormatTokenAssigner = new TimezoneFormatTokenAssigner("TimezoneFormatTokenAssigner", "timezone");
const twelveHourFormatTokenAssigner = new TwelveHourFormatTokenAssigner("TwelveHourFormatTokenAssigner", "twelveHour");
const twentyFourHourFormatTokenAssigner = new TwentyFourHourFormatTokenAssigner("TwentyFourHourFormatTokenAssigner", "twentyFourHour");
const yearFormatTokenAssigner = new YearFormatTokenAssigner("YearFormatTokenAssigner", "year");
const strftimeDayOfMonthFormatTokenAssigner = new DayOfMonthFormatTokenAssigner("DelimiterFormatTokenAssigner", "dayOfMonth", "strftime");
const strftimeDayOfWeekFormatTokenAssigner = new DayOfWeekFormatTokenAssigner("DayOfWeekFormatTokenAssigner", "dayOfWeek", "strftime");
const strftimeDayOfYearFormatTokenAssigner = new DayOfYearFormatTokenAssigner("DayOfYearFormatTokenAssigner", "dayOfYear", "strftime");
const strftimeDelimiterFormatTokenAssigner = new DelimiterFormatTokenAssigner("DelimiterFormatTokenAssigner", "delimiter", "strftime");
const strftimeEscapeTextFormatTokenAssigner = new EscapeTextFormatTokenAssigner("EscapeTextFormatTokenAssigner", "escapeText", "strftime");
const strftimeISODayOfWeekFormatTokenAssigner = new ISODayOfWeekFormatTokenAssigner("ISODayOfWeekFormatTokenAssigner", "isoDayOfWeek", "strftime");
const strftimeISOWeekOfYearFormatTokenAssigner = new ISOWeekOfYearFormatTokenAssigner("ISOWeekOfYearFormatTokenAssigner", "isoWeekOfYear", "strftime");
const strftimeMeridiemFormatTokenAssigner = new MeridiemFormatTokenAssigner("MeridiemFormatTokenAssigner", "meridiem", "strftime");
const strftimeMillisecondFormatTokenAssigner = new MillisecondFormatTokenAssigner("MillisecondFormatTokenAssigner", "millisecond", "strftime");
const strftimeMinuteFormatTokenAssigner = new MinuteFormatTokenAssigner("MinuteFormatTokenAssigner", "minute", "strftime");
const strftimeMonthFormatTokenAssigner = new MonthFormatTokenAssigner("MonthFormatTokenAssigner", "month", "strftime");
const strftimeSecondFormatTokenAssigner = new SecondFormatTokenAssigner("SecondFormatTokenAssigner", "second", "strftime");
const strftimeTimezoneFormatTokenAssigner = new TimezoneFormatTokenAssigner("TimezoneFormatTokenAssigner", "timezone", "strftime");
const strftimeTwelveHourFormatTokenAssigner = new TwelveHourFormatTokenAssigner("TwelveHourFormatTokenAssigner", "twelveHour", "strftime");
const strftimeTwentyFourHourFormatTokenAssigner = new TwentyFourHourFormatTokenAssigner("TwentyFourHourFormatTokenAssigner", "twentyFourHour", "strftime");
const strftimeYearFormatTokenAssigner = new YearFormatTokenAssigner("YearFormatTokenAssigner", "year", "strftime");
const defaultAssigners = [
    yearFormatTokenAssigner,
    monthFormatTokenAssigner,
    dayOfMonthFormatTokenAssigner,
    delimiterFormatTokenAssigner,
    minuteFormatTokenAssigner,
    secondFormatTokenAssigner,
    millisecondFormatTokenAssigner,
    timezoneFormatTokenAssigner,
    dayOfYearFormatTokenAssigner,
    escapeTextFormatTokenAssigner,
    iSODayOfWeekFormatTokenAssigner,
    iSOWeekOfYearFormatTokenAssigner,
    twentyFourHourFormatTokenAssigner,
    twelveHourFormatTokenAssigner,
    dayOfWeekFormatTokenAssigner,
    meridiemFormatTokenAssigner
];
const strftimeAssigners = [
    strftimeDayOfMonthFormatTokenAssigner,
    strftimeDayOfWeekFormatTokenAssigner,
    strftimeDayOfYearFormatTokenAssigner,
    strftimeDelimiterFormatTokenAssigner,
    strftimeEscapeTextFormatTokenAssigner,
    strftimeISODayOfWeekFormatTokenAssigner,
    strftimeISOWeekOfYearFormatTokenAssigner,
    strftimeMeridiemFormatTokenAssigner,
    strftimeMillisecondFormatTokenAssigner,
    strftimeMinuteFormatTokenAssigner,
    strftimeMonthFormatTokenAssigner,
    strftimeSecondFormatTokenAssigner,
    strftimeTimezoneFormatTokenAssigner,
    strftimeTwelveHourFormatTokenAssigner,
    strftimeTwentyFourHourFormatTokenAssigner,
    strftimeYearFormatTokenAssigner
];
class Guesser {
    constructor(){}
    static parse(date) {
        const parsedResults = [];
        parsers.forEach((parser)=>{
            const parsedResult = parser.parse(date);
            if (parsedResult) {
                parsedResults.push(Object.assign({}, parsedResult));
            }
        });
        return parsedResults;
    }
    static refine(parsedResults) {
        let refinedParsedResults = [
            ...parsedResults
        ];
        refiners.forEach((refiner)=>{
            refinedParsedResults = [
                ...refiner.refine(refinedParsedResults)
            ];
        });
        return refinedParsedResults;
    }
    static assign(tokens, format) {
        let assigners = !format || format === "default" ? defaultAssigners : strftimeAssigners;
        assigners.forEach((assigner)=>{
            tokens.forEach((token)=>{
                assigner.assign(token);
            });
        });
    }
    static getFormatString(tokens) {
        let formatString = "";
        tokens.forEach((token)=>{
            if (token.format === "NA") {
                throw Error(`Couldn't find strftime modifier for "${token.value}"`);
            }
            formatString += token.format ? token.format : token.value;
        });
        return formatString;
    }
}
function guessFormat(date, format) {
    const parsedResults = Guesser.parse(date);
    const refinedParsedResults = Guesser.refine(parsedResults);
    if (refinedParsedResults.length === 0) {
        throw Error("Couldn't parse date");
    }
    refinedParsedResults.forEach((r)=>Guesser.assign(r.tokens, format));
    let matchedFormats = [];
    refinedParsedResults.forEach((r)=>matchedFormats.push(Guesser.getFormatString(r.tokens)));
    return matchedFormats.length === 1 ? matchedFormats[0] : matchedFormats;
}
class Tokenizer {
    rules;
    constructor(rules = []){
        this.rules = rules;
    }
    addRule(test, fn) {
        this.rules.push({
            test,
            fn
        });
        return this;
    }
    tokenize(string, receiver = (token)=>token) {
        function* generator(rules) {
            let index = 0;
            for (const rule of rules){
                const result1 = rule.test(string);
                if (result1) {
                    const { value, length } = result1;
                    index += length;
                    string = string.slice(length);
                    const token = {
                        ...rule.fn(value),
                        index
                    };
                    yield receiver(token);
                    yield* generator(rules);
                }
            }
        }
        const tokenGenerator = generator(this.rules);
        const tokens = [];
        for (const token of tokenGenerator){
            tokens.push(token);
        }
        if (string.length) {
            throw new Error(`parser error: string not fully parsed! ${string.slice(0, 25)}`);
        }
        return tokens;
    }
}
function digits(value, count = 2) {
    return String(value).padStart(count, "0");
}
function createLiteralTestFunction(value) {
    return (string)=>{
        return string.startsWith(value) ? {
            value,
            length: value.length
        } : undefined;
    };
}
function createMatchTestFunction(match) {
    return (string)=>{
        const result1 = match.exec(string);
        if (result1) return {
            value: result1,
            length: result1[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 result1 = {
                type,
                value
            };
            if (hour12) result1.hour12 = hour12;
            return result1;
        });
    }
    format(date, options = {}) {
        let string = "";
        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":
                                {
                                    string += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string += 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":
                                {
                                    string += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string += 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":
                                {
                                    string += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "hour":
                    {
                        let value = utc ? date.getUTCHours() : date.getHours();
                        if (token.hour12) {
                            if (value === 0) value = 12;
                            else if (value > 12) value -= 12;
                        }
                        switch(token.value){
                            case "numeric":
                                {
                                    string += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string += 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":
                                {
                                    string += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string += 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":
                                {
                                    string += value;
                                    break;
                                }
                            case "2-digit":
                                {
                                    string += digits(value, 2);
                                    break;
                                }
                            default:
                                throw Error(`FormatterError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "fractionalSecond":
                    {
                        const value = utc ? date.getUTCMilliseconds() : date.getMilliseconds();
                        string += digits(value, Number(token.value));
                        break;
                    }
                case "timeZoneName":
                    {
                        break;
                    }
                case "dayPeriod":
                    {
                        string += token.value ? date.getHours() >= 12 ? "PM" : "AM" : "";
                        break;
                    }
                case "literal":
                    {
                        string += token.value;
                        break;
                    }
                default:
                    throw Error(`FormatterError: { ${token.type} ${token.value} }`);
            }
        }
        return string;
    }
    parseToParts(string) {
        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(string)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{1,2}/.exec(string)?.[0];
                                    break;
                                }
                        }
                        break;
                    }
                case "month":
                    {
                        switch(token.value){
                            case "numeric":
                                {
                                    value = /^\d{1,2}/.exec(string)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string)?.[0];
                                    break;
                                }
                            case "narrow":
                                {
                                    value = /^[a-zA-Z]+/.exec(string)?.[0];
                                    break;
                                }
                            case "short":
                                {
                                    value = /^[a-zA-Z]+/.exec(string)?.[0];
                                    break;
                                }
                            case "long":
                                {
                                    value = /^[a-zA-Z]+/.exec(string)?.[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(string)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string)?.[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(string)?.[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(string)?.[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(string)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string)?.[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(string)?.[0];
                                    break;
                                }
                            case "2-digit":
                                {
                                    value = /^\d{2}/.exec(string)?.[0];
                                    break;
                                }
                            default:
                                throw Error(`ParserError: value "${token.value}" is not supported`);
                        }
                        break;
                    }
                case "fractionalSecond":
                    {
                        value = new RegExp(`^\\d{${token.value}}`).exec(string)?.[0];
                        break;
                    }
                case "timeZoneName":
                    {
                        value = token.value;
                        break;
                    }
                case "dayPeriod":
                    {
                        value = /^(A|P)M/.exec(string)?.[0];
                        break;
                    }
                case "literal":
                    {
                        if (!string.startsWith(token.value)) {
                            throw Error(`Literal "${token.value}" not found "${string.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} } ${string.slice(0, 25)}`);
            }
            parts.push({
                type,
                value
            });
            string = string.slice(value.length);
        }
        if (string.length) {
            throw Error(`datetime string was not fully parsed! ${string.slice(0, 25)}`);
        }
        return parts;
    }
    sortDateTimeFormatPart(parts) {
        let result1 = [];
        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) {
                result1 = result1.concat(parts.splice(current, 1));
            }
        }
        result1 = result1.concat(parts);
        return result1;
    }
    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 part of parts){
            switch(part.type){
                case "year":
                    {
                        const value = Number(part.value.padStart(4, "20"));
                        utc ? date.setUTCFullYear(value) : date.setFullYear(value);
                        break;
                    }
                case "month":
                    {
                        const value = Number(part.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(part.value);
                        utc ? date.setUTCDate(value) : date.setDate(value);
                        break;
                    }
                case "hour":
                    {
                        let value = Number(part.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(part.value);
                        utc ? date.setUTCMinutes(value) : date.setMinutes(value);
                        break;
                    }
                case "second":
                    {
                        const value = Number(part.value);
                        utc ? date.setUTCSeconds(value) : date.setSeconds(value);
                        break;
                    }
                case "fractionalSecond":
                    {
                        const value = Number(part.value);
                        utc ? date.setUTCMilliseconds(value) : date.setMilliseconds(value);
                        break;
                    }
            }
        }
        return date;
    }
    parse(string) {
        const parts = this.parseToParts(string);
        const sortParts = this.sortDateTimeFormatPart(parts);
        return this.partsToDate(sortParts);
    }
}
function parse6(dateString, formatString) {
    const formatter = new DateTimeFormatter(formatString);
    const parts = formatter.parseToParts(dateString);
    const sortParts = formatter.sortDateTimeFormatPart(parts);
    return formatter.partsToDate(sortParts);
}
var commonjsGlobal2 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function createCommonjsModule4(fn, basedir, module1) {
    return module1 = {
        path: basedir,
        exports: {},
        require: function(path, base) {
            return commonjsRequire1(path, base === void 0 || base === null ? module1.path : base);
        }
    }, fn(module1, module1.exports), module1.exports;
}
function commonjsRequire1() {
    throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs");
}
var dayjs_min = createCommonjsModule4(function(module1, exports) {
    !function(t, n) {
        module1.exports = n();
    }(commonjsGlobal2, function() {
        var t = "millisecond", n = "second", e = "minute", r = "hour", i1 = "day", s = "week", u = "month", o = "quarter", a = "year", h = /^(\d{4})-?(\d{1,2})-?(\d{0,2})[^0-9]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?.?(\d{1,3})?$/, f = /\[([^\]]+)]|Y{2,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, c = function(t2, n2, e2) {
            var r2 = String(t2);
            return !r2 || r2.length >= n2 ? t2 : "" + Array(n2 + 1 - r2.length).join(e2) + t2;
        }, d = {
            s: c,
            z: function(t2) {
                var n2 = -t2.utcOffset(), e2 = Math.abs(n2), r2 = Math.floor(e2 / 60), i2 = e2 % 60;
                return (n2 <= 0 ? "+" : "-") + c(r2, 2, "0") + ":" + c(i2, 2, "0");
            },
            m: function(t2, n2) {
                var e2 = 12 * (n2.year() - t2.year()) + (n2.month() - t2.month()), r2 = t2.clone().add(e2, u), i2 = n2 - r2 < 0, s2 = t2.clone().add(e2 + (i2 ? -1 : 1), u);
                return Number(-(e2 + (n2 - r2) / (i2 ? r2 - s2 : s2 - r2)) || 0);
            },
            a: function(t2) {
                return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
            },
            p: function(h2) {
                return ({
                    M: u,
                    y: a,
                    w: s,
                    d: i1,
                    D: "date",
                    h: r,
                    m: e,
                    s: n,
                    ms: t,
                    Q: o
                })[h2] || String(h2 || "").toLowerCase().replace(/s$/, "");
            },
            u: function(t2) {
                return t2 === void 0;
            }
        }, $ = {
            name: "en",
            weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
            months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_")
        }, l1 = "en", m = {};
        m[l1] = $;
        var y = function(t2) {
            return t2 instanceof v;
        }, M = function(t2, n2, e2) {
            var r2;
            if (!t2) return l1;
            if (typeof t2 == "string") m[t2] && (r2 = t2), n2 && (m[t2] = n2, r2 = t2);
            else {
                var i2 = t2.name;
                m[i2] = t2, r2 = i2;
            }
            return e2 || (l1 = r2), r2;
        }, g = function(t2, n2, e2) {
            if (y(t2)) return t2.clone();
            var r2 = n2 ? typeof n2 == "string" ? {
                format: n2,
                pl: e2
            } : n2 : {};
            return r2.date = t2, new v(r2);
        }, D = d;
        D.l = M, D.i = y, D.w = function(t2, n2) {
            return g(t2, {
                locale: n2.$L,
                utc: n2.$u,
                $offset: n2.$offset
            });
        };
        var v = function() {
            function c2(t2) {
                this.$L = this.$L || M(t2.locale, null, true), this.parse(t2);
            }
            var d2 = c2.prototype;
            return d2.parse = function(t2) {
                this.$d = function(t3) {
                    var n2 = t3.date, e2 = t3.utc;
                    if (n2 === null) return new Date(NaN);
                    if (D.u(n2)) return new Date();
                    if (n2 instanceof Date) return new Date(n2);
                    if (typeof n2 == "string" && !/Z$/i.test(n2)) {
                        var r2 = n2.match(h);
                        if (r2) return e2 ? new Date(Date.UTC(r2[1], r2[2] - 1, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, r2[7] || 0)) : new Date(r2[1], r2[2] - 1, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, r2[7] || 0);
                    }
                    return new Date(n2);
                }(t2), this.init();
            }, d2.init = function() {
                var t2 = this.$d;
                this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
            }, d2.$utils = function() {
                return D;
            }, d2.isValid = function() {
                return !(this.$d.toString() === "Invalid Date");
            }, d2.isSame = function(t2, n2) {
                var e2 = g(t2);
                return this.startOf(n2) <= e2 && e2 <= this.endOf(n2);
            }, d2.isAfter = function(t2, n2) {
                return g(t2) < this.startOf(n2);
            }, d2.isBefore = function(t2, n2) {
                return this.endOf(n2) < g(t2);
            }, d2.$g = function(t2, n2, e2) {
                return D.u(t2) ? this[n2] : this.set(e2, t2);
            }, d2.year = function(t2) {
                return this.$g(t2, "$y", a);
            }, d2.month = function(t2) {
                return this.$g(t2, "$M", u);
            }, d2.day = function(t2) {
                return this.$g(t2, "$W", i1);
            }, d2.date = function(t2) {
                return this.$g(t2, "$D", "date");
            }, d2.hour = function(t2) {
                return this.$g(t2, "$H", r);
            }, d2.minute = function(t2) {
                return this.$g(t2, "$m", e);
            }, d2.second = function(t2) {
                return this.$g(t2, "$s", n);
            }, d2.millisecond = function(n2) {
                return this.$g(n2, "$ms", t);
            }, d2.unix = function() {
                return Math.floor(this.valueOf() / 1e3);
            }, d2.valueOf = function() {
                return this.$d.getTime();
            }, d2.startOf = function(t2, o2) {
                var h2 = this, f2 = !!D.u(o2) || o2, c3 = D.p(t2), d3 = function(t3, n2) {
                    var e2 = D.w(h2.$u ? Date.UTC(h2.$y, n2, t3) : new Date(h2.$y, n2, t3), h2);
                    return f2 ? e2 : e2.endOf(i1);
                }, $2 = function(t3, n2) {
                    return D.w(h2.toDate()[t3].apply(h2.toDate(), (f2 ? [
                        0,
                        0,
                        0,
                        0
                    ] : [
                        23,
                        59,
                        59,
                        999
                    ]).slice(n2)), h2);
                }, l2 = this.$W, m2 = this.$M, y2 = this.$D, M2 = "set" + (this.$u ? "UTC" : "");
                switch(c3){
                    case a:
                        return f2 ? d3(1, 0) : d3(31, 11);
                    case u:
                        return f2 ? d3(1, m2) : d3(0, m2 + 1);
                    case s:
                        var g2 = this.$locale().weekStart || 0, v2 = (l2 < g2 ? l2 + 7 : l2) - g2;
                        return d3(f2 ? y2 - v2 : y2 + (6 - v2), m2);
                    case i1:
                    case "date":
                        return $2(M2 + "Hours", 0);
                    case r:
                        return $2(M2 + "Minutes", 1);
                    case e:
                        return $2(M2 + "Seconds", 2);
                    case n:
                        return $2(M2 + "Milliseconds", 3);
                    default:
                        return this.clone();
                }
            }, d2.endOf = function(t2) {
                return this.startOf(t2, false);
            }, d2.$set = function(s2, o2) {
                var h2, f2 = D.p(s2), c3 = "set" + (this.$u ? "UTC" : ""), d3 = (h2 = {}, h2[i1] = c3 + "Date", h2.date = c3 + "Date", h2[u] = c3 + "Month", h2[a] = c3 + "FullYear", h2[r] = c3 + "Hours", h2[e] = c3 + "Minutes", h2[n] = c3 + "Seconds", h2[t] = c3 + "Milliseconds", h2)[f2], $2 = f2 === i1 ? this.$D + (o2 - this.$W) : o2;
                if (f2 === u || f2 === a) {
                    var l2 = this.clone().set("date", 1);
                    l2.$d[d3]($2), l2.init(), this.$d = l2.set("date", Math.min(this.$D, l2.daysInMonth())).toDate();
                } else d3 && this.$d[d3]($2);
                return this.init(), this;
            }, d2.set = function(t2, n2) {
                return this.clone().$set(t2, n2);
            }, d2.get = function(t2) {
                return this[D.p(t2)]();
            }, d2.add = function(t2, o2) {
                var h2, f2 = this;
                t2 = Number(t2);
                var c3 = D.p(o2), d3 = function(n2) {
                    var e2 = g(f2);
                    return D.w(e2.date(e2.date() + Math.round(n2 * t2)), f2);
                };
                if (c3 === u) return this.set(u, this.$M + t2);
                if (c3 === a) return this.set(a, this.$y + t2);
                if (c3 === i1) return d3(1);
                if (c3 === s) return d3(7);
                var $2 = (h2 = {}, h2[e] = 6e4, h2[r] = 36e5, h2[n] = 1e3, h2)[c3] || 1, l2 = this.$d.getTime() + t2 * $2;
                return D.w(l2, this);
            }, d2.subtract = function(t2, n2) {
                return this.add(-1 * t2, n2);
            }, d2.format = function(t2) {
                var n2 = this;
                if (!this.isValid()) return "Invalid Date";
                var e2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", r2 = D.z(this), i2 = this.$locale(), s2 = this.$H, u2 = this.$m, o2 = this.$M, a2 = i2.weekdays, h2 = i2.months, c3 = function(t3, r3, i3, s3) {
                    return t3 && (t3[r3] || t3(n2, e2)) || i3[r3].substr(0, s3);
                }, d3 = function(t3) {
                    return D.s(s2 % 12 || 12, t3, "0");
                }, $2 = i2.meridiem || function(t3, n3, e3) {
                    var r3 = t3 < 12 ? "AM" : "PM";
                    return e3 ? r3.toLowerCase() : r3;
                }, l2 = {
                    YY: String(this.$y).slice(-2),
                    YYYY: this.$y,
                    M: o2 + 1,
                    MM: D.s(o2 + 1, 2, "0"),
                    MMM: c3(i2.monthsShort, o2, h2, 3),
                    MMMM: h2[o2] || h2(this, e2),
                    D: this.$D,
                    DD: D.s(this.$D, 2, "0"),
                    d: String(this.$W),
                    dd: c3(i2.weekdaysMin, this.$W, a2, 2),
                    ddd: c3(i2.weekdaysShort, this.$W, a2, 3),
                    dddd: a2[this.$W],
                    H: String(s2),
                    HH: D.s(s2, 2, "0"),
                    h: d3(1),
                    hh: d3(2),
                    a: $2(s2, u2, true),
                    A: $2(s2, u2, false),
                    m: String(u2),
                    mm: D.s(u2, 2, "0"),
                    s: String(this.$s),
                    ss: D.s(this.$s, 2, "0"),
                    SSS: D.s(this.$ms, 3, "0"),
                    Z: r2
                };
                return e2.replace(f, function(t3, n3) {
                    return n3 || l2[t3] || r2.replace(":", "");
                });
            }, d2.utcOffset = function() {
                return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
            }, d2.diff = function(t2, h2, f2) {
                var c3, d3 = D.p(h2), $2 = g(t2), l2 = 6e4 * ($2.utcOffset() - this.utcOffset()), m2 = this - $2, y2 = D.m(this, $2);
                return y2 = (c3 = {}, c3[a] = y2 / 12, c3[u] = y2, c3[o] = y2 / 3, c3[s] = (m2 - l2) / 6048e5, c3[i1] = (m2 - l2) / 864e5, c3[r] = m2 / 36e5, c3[e] = m2 / 6e4, c3[n] = m2 / 1e3, c3)[d3] || m2, f2 ? y2 : D.a(y2);
            }, d2.daysInMonth = function() {
                return this.endOf(u).$D;
            }, d2.$locale = function() {
                return m[this.$L];
            }, d2.locale = function(t2, n2) {
                if (!t2) return this.$L;
                var e2 = this.clone(), r2 = M(t2, n2, true);
                return r2 && (e2.$L = r2), e2;
            }, d2.clone = function() {
                return D.w(this.$d, this);
            }, d2.toDate = function() {
                return new Date(this.valueOf());
            }, d2.toJSON = function() {
                return this.isValid() ? this.toISOString() : null;
            }, d2.toISOString = function() {
                return this.$d.toISOString();
            }, d2.toString = function() {
                return this.$d.toUTCString();
            }, c2;
        }();
        return g.prototype = v.prototype, g.extend = function(t2, n2) {
            return t2(n2, v, g), g;
        }, g.locale = M, g.isDayjs = y, g.unix = function(t2) {
            return g(1e3 * t2);
        }, g.en = m[l1], g.Ls = m, g;
    });
});
dayjs_min.Ls;
dayjs_min.en;
dayjs_min.extend;
dayjs_min.isDayjs;
dayjs_min.locale;
dayjs_min.unix;
const MILLISECONDS_A_MINUTE = 60 * 1e3;
const MS = "millisecond";
const MIN = "minute";
const D = "day";
const W = "week";
const Y = "year";
const FORMAT_DEFAULT = "YYYY-MM-DDTHH:mm:ssZ";
const __default4 = (o, c, d)=>{
    const proto = c.prototype;
    const oldFormat = proto.format;
    d.en.ordinal = (number)=>{
        const s = [
            "th",
            "st",
            "nd",
            "rd"
        ];
        const v = number % 100;
        return `[${number}${s[(v - 20) % 10] || s[v] || s[0]}]`;
    };
    proto.format = function(formatStr) {
        const locale = this.$locale();
        if (!this.isValid()) {
            return oldFormat.bind(this)(formatStr);
        }
        const utils = this.$utils();
        const str = formatStr || FORMAT_DEFAULT;
        const result1 = str.replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g, (match)=>{
            switch(match){
                case "Q":
                    return Math.ceil((this.$M + 1) / 3);
                case "Do":
                    return locale.ordinal(this.$D);
                case "gggg":
                    return this.weekYear();
                case "GGGG":
                    return this.isoWeekYear();
                case "wo":
                    return locale.ordinal(this.week(), "W");
                case "w":
                case "ww":
                    return utils.s(this.week(), match === "w" ? 1 : 2, "0");
                case "W":
                case "WW":
                    return utils.s(this.isoWeek(), match === "W" ? 1 : 2, "0");
                case "k":
                case "kk":
                    return utils.s(String(this.$H === 0 ? 24 : this.$H), match === "k" ? 1 : 2, "0");
                case "X":
                    return Math.floor(this.$d.getTime() / 1000);
                case "x":
                    return this.$d.getTime();
                case "z":
                    return `[${this.offsetName()}]`;
                case "zzz":
                    return `[${this.offsetName("long")}]`;
                default:
                    return match;
            }
        });
        return oldFormat.bind(this)(result1);
    };
};
const typeToPos = {
    year: 0,
    month: 1,
    day: 2,
    hour: 3,
    minute: 4,
    second: 5
};
const dtfCache = {};
const getDateTimeFormat = (timezone, options = {})=>{
    const timeZoneName = options.timeZoneName || "short";
    const key = `${timezone}|${timeZoneName}`;
    let dtf = dtfCache[key];
    if (!dtf) {
        dtf = new Intl.DateTimeFormat("en-US", {
            hour12: false,
            timeZone: timezone,
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
            second: "2-digit",
            timeZoneName
        });
        dtfCache[key] = dtf;
    }
    return dtf;
};
const __default5 = (o, c, d)=>{
    let defaultTimezone;
    const makeFormatParts = (timestamp, timezone, options = {})=>{
        const date = new Date(timestamp);
        const dtf = getDateTimeFormat(timezone, options);
        return dtf.formatToParts(date);
    };
    const tzOffset = (timestamp, timezone)=>{
        const formatResult = makeFormatParts(timestamp, timezone);
        const filled = [];
        for(let i1 = 0; i1 < formatResult.length; i1 += 1){
            const { type, value } = formatResult[i1];
            const pos = typeToPos[type];
            if (pos >= 0) {
                filled[pos] = parseInt(value, 10);
            }
        }
        const hour = filled[3];
        const fixedHour = hour === 24 ? 0 : hour;
        const utcString = `${filled[0]}-${filled[1]}-${filled[2]} ${fixedHour}:${filled[4]}:${filled[5]}:000`;
        const utcTs = d.utc(utcString).valueOf();
        let asTS = +timestamp;
        const over = asTS % 1000;
        asTS -= over;
        return (utcTs - asTS) / (60 * 1000);
    };
    const fixOffset = (localTS, o0, tz)=>{
        let utcGuess = localTS - o0 * 60 * 1000;
        const o2 = tzOffset(utcGuess, tz);
        if (o0 === o2) {
            return [
                utcGuess,
                o0
            ];
        }
        utcGuess -= (o2 - o0) * 60 * 1000;
        const o3 = tzOffset(utcGuess, tz);
        if (o2 === o3) {
            return [
                utcGuess,
                o2
            ];
        }
        return [
            localTS - Math.min(o2, o3) * 60 * 1000,
            Math.max(o2, o3)
        ];
    };
    const proto = c.prototype;
    proto.tz = function(timezone = defaultTimezone, keepLocalTime) {
        const oldOffset = this.utcOffset();
        const date = this.toDate();
        const target = date.toLocaleString("en-US", {
            timeZone: timezone
        });
        const diff = Math.round((date - new Date(target)) / 1000 / 60);
        let ins = d(target).$set(MS, this.$ms).utcOffset(-Math.round(date.getTimezoneOffset() / 15) * 15 - diff, true);
        if (keepLocalTime) {
            const newOffset = ins.utcOffset();
            ins = ins.add(oldOffset - newOffset, MIN);
        }
        ins.$x.$timezone = timezone;
        return ins;
    };
    proto.offsetName = function(type) {
        const zone = this.$x?.$timezone || d.tz.guess();
        const result1 = makeFormatParts(this.valueOf(), zone, {
            timeZoneName: type
        }).find((m)=>m.type.toLowerCase() === "timezonename");
        return result1 && result1.value;
    };
    const oldStartOf = proto.startOf;
    proto.startOf = function(units, startOf) {
        if (!this.$x || !this.$x.$timezone) {
            return oldStartOf.call(this, units, startOf);
        }
        const withoutTz = d(this.format("YYYY-MM-DD HH:mm:ss:SSS"));
        const startOfWithoutTz = oldStartOf.call(withoutTz, units, startOf);
        return startOfWithoutTz.tz(this.$x.$timezone, true);
    };
    d.tz = function(input, arg1, arg2) {
        const parseFormat = arg2 && arg1;
        const timezone = arg2 || arg1 || defaultTimezone;
        const previousOffset = tzOffset(+d(), timezone);
        if (typeof input !== "string") {
            return d(input).tz(timezone);
        }
        const localTs = d.utc(input, parseFormat).valueOf();
        const [targetTs, targetOffset] = fixOffset(localTs, previousOffset, timezone);
        const ins = d(targetTs).utcOffset(targetOffset);
        ins.$x.$timezone = timezone;
        return ins;
    };
    d.tz.guess = function() {
        return Intl.DateTimeFormat().resolvedOptions().timeZone;
    };
    d.tz.setDefault = function(timezone) {
        defaultTimezone = timezone;
    };
};
const REGEX_VALID_OFFSET_FORMAT = /[+-]\d\d(?::?\d\d)?/g;
const REGEX_OFFSET_HOURS_MINUTES_FORMAT = /([+-]|\d\d)/g;
function offsetFromString(value = "") {
    const offset = value.match(REGEX_VALID_OFFSET_FORMAT);
    if (!offset) {
        return null;
    }
    const [indicator, hoursOffset, minutesOffset] = `${offset[0]}`.match(REGEX_OFFSET_HOURS_MINUTES_FORMAT) || [
        "-",
        0,
        0
    ];
    const totalOffsetInMinutes = +hoursOffset * 60 + +minutesOffset;
    if (totalOffsetInMinutes === 0) {
        return 0;
    }
    return indicator === "+" ? totalOffsetInMinutes : -totalOffsetInMinutes;
}
const __default6 = (option, Dayjs, dayjs)=>{
    const proto = Dayjs.prototype;
    dayjs.utc = function(date) {
        const cfg = {
            date,
            utc: true,
            args: arguments
        };
        return new Dayjs(cfg);
    };
    proto.utc = function(keepLocalTime) {
        const ins = dayjs(this.toDate(), {
            locale: this.$L,
            utc: true
        });
        if (keepLocalTime) {
            return ins.add(this.utcOffset(), MIN);
        }
        return ins;
    };
    proto.local = function() {
        return dayjs(this.toDate(), {
            locale: this.$L,
            utc: false
        });
    };
    const oldParse = proto.parse;
    proto.parse = function(cfg) {
        if (cfg.utc) {
            this.$u = true;
        }
        if (!this.$utils().u(cfg.$offset)) {
            this.$offset = cfg.$offset;
        }
        oldParse.call(this, cfg);
    };
    const oldInit = proto.init;
    proto.init = function() {
        if (this.$u) {
            const { $d } = this;
            this.$y = $d.getUTCFullYear();
            this.$M = $d.getUTCMonth();
            this.$D = $d.getUTCDate();
            this.$W = $d.getUTCDay();
            this.$H = $d.getUTCHours();
            this.$m = $d.getUTCMinutes();
            this.$s = $d.getUTCSeconds();
            this.$ms = $d.getUTCMilliseconds();
        } else {
            oldInit.call(this);
        }
    };
    const oldUtcOffset = proto.utcOffset;
    proto.utcOffset = function(input, keepLocalTime) {
        const { u } = this.$utils();
        if (u(input)) {
            if (this.$u) {
                return 0;
            }
            if (!u(this.$offset)) {
                return this.$offset;
            }
            return oldUtcOffset.call(this);
        }
        if (typeof input === "string") {
            input = offsetFromString(input);
            if (input === null) {
                return this;
            }
        }
        const offset = Math.abs(input) <= 16 ? input * 60 : input;
        let ins = this;
        if (keepLocalTime) {
            ins.$offset = offset;
            ins.$u = input === 0;
            return ins;
        }
        if (input !== 0) {
            const localTimezoneOffset = this.$u ? this.toDate().getTimezoneOffset() : -1 * this.utcOffset();
            ins = this.local().add(offset + localTimezoneOffset, MIN);
            ins.$offset = offset;
            ins.$x.$localOffset = localTimezoneOffset;
        } else {
            ins = this.utc();
        }
        return ins;
    };
    const oldFormat = proto.format;
    const UTC_FORMAT_DEFAULT = "YYYY-MM-DDTHH:mm:ss[Z]";
    proto.format = function(formatStr) {
        const str = formatStr || (this.$u ? UTC_FORMAT_DEFAULT : "");
        return oldFormat.call(this, str);
    };
    proto.valueOf = function() {
        const addedOffset = !this.$utils().u(this.$offset) ? this.$offset + (this.$x.$localOffset || this.$d.getTimezoneOffset()) : 0;
        return this.$d.valueOf() - addedOffset * MILLISECONDS_A_MINUTE;
    };
    proto.isUTC = function() {
        return !!this.$u;
    };
    proto.toISOString = function() {
        return this.toDate().toISOString();
    };
    proto.toString = function() {
        return this.toDate().toUTCString();
    };
    const oldToDate = proto.toDate;
    proto.toDate = function(type) {
        if (type === "s" && this.$offset) {
            return dayjs(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate();
        }
        return oldToDate.call(this);
    };
    const oldDiff = proto.diff;
    proto.diff = function(input, units, __float) {
        if (input && this.$u === input.$u) {
            return oldDiff.call(this, input, units, __float);
        }
        const localThis = this.local();
        const localInput = dayjs(input).local();
        return oldDiff.call(localThis, localInput, units, __float);
    };
};
const isoWeekPrettyUnit = "isoweek";
const __default7 = (o, c, d)=>{
    const getYearFirstThursday = (year, isUtc)=>{
        const yearFirstDay = (isUtc ? d.utc : d)().year(year).startOf(Y);
        let addDiffDays = 4 - yearFirstDay.isoWeekday();
        if (yearFirstDay.isoWeekday() > 4) {
            addDiffDays += 7;
        }
        return yearFirstDay.add(addDiffDays, D);
    };
    const getCurrentWeekThursday = (ins)=>ins.add(4 - ins.isoWeekday(), D);
    const proto = c.prototype;
    proto.isoWeekYear = function() {
        const nowWeekThursday = getCurrentWeekThursday(this);
        return nowWeekThursday.year();
    };
    proto.isoWeek = function(week) {
        if (!this.$utils().u(week)) {
            return this.add((week - this.isoWeek()) * 7, D);
        }
        const nowWeekThursday = getCurrentWeekThursday(this);
        const diffWeekThursday = getYearFirstThursday(this.isoWeekYear(), this.$u);
        return nowWeekThursday.diff(diffWeekThursday, W) + 1;
    };
    proto.isoWeekday = function(week) {
        if (!this.$utils().u(week)) {
            return this.day(this.day() % 7 ? week : week - 7);
        }
        return this.day() || 7;
    };
    const oldStartOf = proto.startOf;
    proto.startOf = function(units, startOf) {
        const utils = this.$utils();
        const isStartOf = !utils.u(startOf) ? startOf : true;
        const unit = utils.p(units);
        if (unit === isoWeekPrettyUnit) {
            return isStartOf ? this.date(this.date() - (this.isoWeekday() - 1)).startOf("day") : this.date(this.date() - 1 - (this.isoWeekday() - 1) + 7).endOf("day");
        }
        return oldStartOf.bind(this)(units, startOf);
    };
};
const __default8 = (o, c, d)=>{
    const proto = c.prototype;
    proto.week = function(week = null) {
        if (week !== null) {
            return this.add((week - this.week()) * 7, D);
        }
        const yearStart = this.$locale().yearStart || 1;
        if (this.month() === 11 && this.date() > 25) {
            const nextYearStartDay = d(this).startOf(Y).add(1, Y).date(yearStart);
            const thisEndOfWeek = d(this).endOf(W);
            if (nextYearStartDay.isBefore(thisEndOfWeek)) {
                return 1;
            }
        }
        const yearStartDay = d(this).startOf(Y).date(yearStart);
        const yearStartWeek = yearStartDay.startOf(W).subtract(1, MS);
        const diffInWeek = this.diff(yearStartWeek, W, true);
        if (diffInWeek < 0) {
            return d(this).startOf("week").week();
        }
        return Math.ceil(diffInWeek);
    };
    proto.weeks = function(week = null) {
        return this.week(week);
    };
};
const __default9 = (o, c)=>{
    const proto = c.prototype;
    proto.weekYear = function() {
        const month = this.month();
        const weekOfYear = this.week();
        const year = this.year();
        if (weekOfYear === 1 && month === 11) {
            return year + 1;
        }
        if (month === 0 && weekOfYear >= 52) {
            return year - 1;
        }
        return year;
    };
};
const kLastModified = "last-modified";
const kToday = "today";
const kNow = "now";
function today() {
    const today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);
    return today;
}
function resolveAndFormatDate(input, date, format) {
    const resolveDate = (date)=>{
        if (date) {
            if (typeof date === "string") {
                return {
                    value: date,
                    format: format || "iso"
                };
            } else if (typeof date === "object") {
                const schemaDate = date;
                return {
                    value: schemaDate.value,
                    format: schemaDate.format || format || "iso"
                };
            }
        } else {
            return undefined;
        }
    };
    const resolvedDate = resolveDate(date);
    if (resolvedDate) {
        if (isSpecialDate(resolvedDate.value)) {
            resolvedDate.value = parseSpecialDate(input, resolvedDate.value);
        }
        const parsed = parsePandocDate(resolvedDate.value);
        return formatDate(parsed, resolvedDate.format);
    }
}
function resolveDate(input, val) {
    if (isSpecialDate(val)) {
        return parseSpecialDate(input, val);
    } else {
        return val;
    }
}
function isSpecialDate(val) {
    return val === kLastModified || val === kToday || val === kNow;
}
function parseSpecialDate(input, val) {
    if (val === kLastModified) {
        if (!Array.isArray(input)) {
            input = [
                input
            ];
        }
        let lastModifiedTs = 0;
        for (const inp of input){
            const stat = Deno.statSync(inp);
            if (stat.mtime) {
                lastModifiedTs = Math.max(lastModifiedTs, stat.mtime.getTime());
            }
        }
        return formatDate(new Date(lastModifiedTs), "YYYY-MM-DDTHH:mm:ssZ");
    } else if (val === kToday) {
        return formatDate(today(), "YYYY-MM-DDTHH:mm:ssZ");
    } else if (val === kNow) {
        return formatDate(new Date(), "YYYY-MM-DDTHH:mm:ssZ");
    } else {
        return val;
    }
}
function initDayJsPlugins() {
    dayjs_min.extend(__default6);
    dayjs_min.extend(__default5);
    dayjs_min.extend(__default7);
    dayjs_min.extend(__default9);
    dayjs_min.extend(__default8);
    dayjs_min.extend(__default4);
}
async function setDateLocale(localeStr) {
    localeStr = localeStr.toLowerCase();
    if (localeStr !== dayjs_min.locale()) {
        const findLocale = ()=>{
            const locales = [
                localeStr
            ];
            if (localeStr.includes("-")) {
                locales.push(localeStr.split("-")[0]);
            }
            for (const locale of locales){
                const path = resourcePath(`library/dayjs/locale/${locale}.js`);
                if (existsSync(path)) {
                    return {
                        locale,
                        path
                    };
                }
            }
            return undefined;
        };
        const locale = findLocale();
        if (locale) {
            const localeUrl = toFileUrl2(locale.path).href;
            const localeModule = await import(localeUrl);
            dayjs_min.locale(localeModule.default, null, true);
            dayjs_min.locale(locale.locale);
        }
    }
}
const formatDate = (date, dateStyle, timeStyle)=>{
    if (dateStyle === "full" || dateStyle === "long" || dateStyle === "medium" || dateStyle === "short") {
        const options = {
            dateStyle
        };
        if (timeStyle) {
            options.timeStyle = timeStyle;
        }
        return date.toLocaleString(dayjs_min.locale(), options);
    } else {
        if (dateStyle === "iso") dateStyle = "YYYY-MM-DD";
        return dayjs_min(date).format(dateStyle);
    }
};
const parsePandocDate = (dateRaw)=>{
    const formats = [
        "MM/dd/yyyy",
        "MM-dd-yyyy",
        "MM/dd/yy",
        "MM-dd-yy",
        "yyyy-MM-dd",
        "dd MM yyyy",
        "MM dd, yyyy"
    ];
    const parseFormat = (dateStr)=>{
        for (const format of formats){
            try {
                const date = parse6(dateStr, format);
                return date;
            } catch  {}
        }
        try {
            const formats = guessFormat(dateRaw);
            if (formats) {
                try {
                    const format = Array.isArray(formats) ? formats[0] : formats;
                    const date = dayjs_min(dateStr, format);
                    return date.toDate();
                } catch  {}
            }
        } catch  {}
        try {
            return new Date(dateStr);
        } catch  {
            return undefined;
        }
    };
    return parseFormat(dateRaw);
};
function katexPostProcessor() {
    return (doc)=>{
        const katexScript = doc.querySelector(`script[src$="katex.min.js"]`);
        const katexCss = doc.querySelector(`link[href$="katex.min.css"]`);
        if (katexScript && katexCss) {
            katexScript.removeAttribute("defer");
            const katexBefore = doc.createElement("script");
            katexBefore.innerText = "window.backupDefine = window.define; window.define = undefined;";
            katexScript.parentNode?.insertBefore(katexBefore, katexScript);
            const katexAfter = doc.createElement("script");
            katexAfter.innerText = "window.define = window.backupDefine; window.backupDefine = undefined;";
            katexCss?.parentNode?.insertBefore(katexAfter, katexCss);
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
async function appendDependencies(dependenciesFile, dependencies) {
    const dependencyLines = [];
    for (const dependency of dependencies){
        dependencyLines.push(JSON.stringify(dependency));
    }
    if (dependencyLines.length > 0) {
        await appendTextFile(dependenciesFile, `${dependencyLines.join("\n")}\n`);
    }
}
async function writeDependencies(dependenciesFile, extras) {
    if (extras.html?.[kDependencies]) {
        const dependencies = extras.html[kDependencies].map((dep)=>{
            return {
                type: "html",
                content: dep
            };
        });
        await appendDependencies(dependenciesFile, dependencies);
    }
}
function readAndInjectDependencies(dependenciesFile, inputDir, libDir, doc, project) {
    const dependencyJsonStream = Deno.readTextFileSync(dependenciesFile);
    const htmlDependencies = [];
    const htmlAttachments = [];
    lines(dependencyJsonStream).forEach((json)=>{
        if (json) {
            const dependency = JSON.parse(json);
            if (dependency.type === "html") {
                htmlDependencies.push(dependency.content);
            } else if (dependency.type === "html-attachment") {
                htmlAttachments.push(dependency);
            }
        }
    });
    const injectedDependencies = [];
    if (htmlDependencies.length > 0) {
        const injector = domDependencyInjector(doc);
        const injected = processHtmlDependencies(htmlDependencies, inputDir, libDir, injector, project);
        injectedDependencies.push(...injected);
        injector.finalizeInjection();
    }
    if (htmlAttachments.length > 0) {
        for (const attachment of htmlAttachments){
            const parentDependency = injectedDependencies.find((dep)=>{
                return dep.name === attachment.content.name;
            });
            if (parentDependency) {
                const directoryInfo = targetDirectoryInfo(inputDir, libDir, parentDependency);
                copyDependencyFile(attachment.content.file, directoryInfo.absolute, !!parentDependency.external);
            }
        }
    }
    const relocateScripts = doc.querySelectorAll("script[data-relocate-top]");
    if (relocateScripts.length > 0) {
        const nextSiblingEl = doc.querySelector("head script:first-of-type");
        if (nextSiblingEl) {
            for (const relocateScript of relocateScripts){
                relocateScript.removeAttribute("data-relocate-top");
                nextSiblingEl.parentElement?.insertBefore(relocateScript, nextSiblingEl);
            }
        }
    }
    return Promise.resolve({
        resources: [],
        supporting: []
    });
}
function resolveDependencies(extras, inputDir, libDir, temp, project) {
    extras = cloneDeep1(extras);
    const lines = [];
    const afterBodyLines = [];
    if (extras.html?.[kDependencies]) {
        const injector = lineDependencyInjector(lines, afterBodyLines);
        processHtmlDependencies(extras.html[kDependencies], inputDir, libDir, injector, project);
        injector.finalizeInjection();
        delete extras.html?.[kDependencies];
        const dependenciesHead = temp.createFile({
            prefix: "dependencies",
            suffix: ".html"
        });
        Deno.writeTextFileSync(dependenciesHead, lines.join("\n"));
        extras[kIncludeInHeader] = [
            dependenciesHead
        ].concat(extras[kIncludeInHeader] || []);
        if (afterBodyLines.length > 0) {
            const dependenciesAfter = temp.createFile({
                prefix: "dependencies-after",
                suffix: ".html"
            });
            Deno.writeTextFileSync(dependenciesAfter, afterBodyLines.join("\n"));
            extras[kIncludeAfterBody] = [
                dependenciesAfter
            ].concat(extras[kIncludeAfterBody] || []);
        }
    }
    return extras;
}
function processHtmlDependencies(dependencies, inputDir, libDir, injector, project) {
    const copiedDependencies = [];
    for (const dependency of dependencies){
        if (copiedDependencies.find((copiedDep)=>{
            return copiedDep.name === dependency.name;
        })) {
            continue;
        }
        const directoryInfo = targetDirectoryInfo(inputDir, libDir, dependency);
        const copyFile = (file, attribs, afterBody, inject)=>{
            copyDependencyFile(file, directoryInfo.absolute, dependency.external || false);
            if (inject) {
                const href = join2(directoryInfo.relative, file.name);
                inject(href, attribs, afterBody);
            }
        };
        if (dependency.scripts) {
            dependency.scripts.forEach((script)=>copyFile(script, script.attribs, script.afterBody, injector.injectScript));
        }
        if (dependency.stylesheets) {
            dependency.stylesheets.forEach((stylesheet)=>{
                copyFile(stylesheet, stylesheet.attribs, stylesheet.afterBody, injector.injectStyle);
            });
        }
        if (dependency.serviceworkers) {
            dependency.serviceworkers.forEach((serviceWorker)=>{
                const resolveDestination = (worker, inputDir, project)=>{
                    if (!worker.destination) {
                        if (project) {
                            worker.destination = `/${basename2(worker.source)}`;
                        } else {
                            worker.destination = `${basename2(worker.source)}`;
                        }
                    }
                    if (worker.destination.startsWith("/")) {
                        if (project) {
                            const projectDir = projectOutputDir(project);
                            return join2(projectDir, worker.destination.slice(1));
                        } else {
                            throw new Error("A service worker is being provided with a project relative destination path but no valid Quarto project was found.");
                        }
                    } else {
                        return join2(inputDir, worker.destination);
                    }
                };
                const destinationFile = resolveDestination(serviceWorker, inputDir, project);
                const destinationDir = dirname2(destinationFile);
                ensureDirSync(destinationDir);
                copyFileIfNewer(serviceWorker.source, destinationFile);
            });
        }
        if (dependency.head) {
            injector.injectHtml(dependency.head);
        }
        if (dependency.links) {
            dependency.links.forEach((link)=>{
                injector.injectLink(link.href, link.rel, link.type);
            });
        }
        if (dependency.meta) {
            injector.injectMeta(dependency.meta);
        }
        if (dependency.resources) {
            dependency.resources.forEach((resource)=>copyFile(resource));
        }
        copiedDependencies.push(dependency);
    }
    return copiedDependencies;
}
function copyDependencyFile(file, targetDir, external) {
    const targetPath = join2(targetDir, file.name);
    ensureDirSync(dirname2(targetPath));
    copyFileIfNewer(file.path, targetPath);
    if (external && isCssFile(file.path)) {
        processCssFile(dirname2(file.path), targetPath);
    }
}
function targetDirectoryInfo(inputDir, libDir, dependency) {
    const targetLibDir = dependency.external ? join2(libDir, "quarto-contrib") : libDir;
    const dir = dependency.version ? `${dependency.name}-${dependency.version}` : dependency.name;
    const relativeTargetDir = join2(targetLibDir, dir);
    const absoluteTargetDir = join2(inputDir, relativeTargetDir);
    return {
        absolute: absoluteTargetDir,
        relative: relativeTargetDir
    };
}
function processCssFile(srcDir, file) {
    const css = Deno.readTextFileSync(file);
    const destCss = fixupCssReferences(css, (ref)=>{
        const refPath = join2(srcDir, ref);
        if (safeExistsSync(refPath)) {
            const refDir = dirname2(ref);
            const targetRef = refDir && refDir !== "." && refDir.includes("..") ? join2(insecureHash(dirname2(ref)), basename2(ref)) : ref;
            const refDestPath = join2(dirname2(file), targetRef);
            copyFileIfNewer(refPath, refDestPath);
            return pathWithForwardSlashes(targetRef);
        } else {
            return ref;
        }
    });
    if (destCss !== css) {
        Deno.writeTextFileSync(file, destCss);
    }
}
const kDependencyTarget = "htmldependencies:E3FAD763";
function domDependencyInjector(doc) {
    const findTargetComment = ()=>{
        for (const node of doc.head.childNodes){
            if (node.nodeType === NodeType.COMMENT_NODE) {
                if (node.textContent && node.textContent.trim() === kDependencyTarget) {
                    return node;
                }
            }
        }
        return doc.head.firstChild;
    };
    const targetComment = findTargetComment();
    const injectEl = (el, attribs, afterBody)=>{
        if (attribs) {
            for (const key of Object.keys(attribs)){
                el.setAttribute(key, attribs[key]);
            }
        }
        if (!afterBody) {
            doc.head.insertBefore(doc.createTextNode("\n"), targetComment);
            doc.head.insertBefore(el, targetComment);
        } else {
            doc.body.appendChild(el);
            doc.body.appendChild(doc.createTextNode("\n"));
        }
    };
    const injectScript = (href, attribs, afterBody)=>{
        const scriptEl = doc.createElement("script");
        scriptEl.setAttribute("src", pathWithForwardSlashes(href));
        injectEl(scriptEl, attribs, afterBody);
    };
    const injectStyle = (href, attribs, afterBody)=>{
        const linkEl = doc.createElement("link");
        linkEl.setAttribute("href", pathWithForwardSlashes(href));
        linkEl.setAttribute("rel", "stylesheet");
        injectEl(linkEl, attribs, afterBody);
    };
    const injectLink = (href, rel, type)=>{
        const linkEl = doc.createElement("link");
        linkEl.setAttribute("href", pathWithForwardSlashes(href));
        linkEl.setAttribute("rel", rel);
        if (type) {
            linkEl.setAttribute("type", type);
        }
        injectEl(linkEl);
    };
    const injectHtml = (html)=>{
        const container = doc.createElement("div");
        container.innerHTML = html;
        for (const childEl of container.children){
            injectEl(childEl);
        }
    };
    const injectMeta = (meta)=>{
        Object.keys(meta).forEach((key)=>{
            const metaEl = doc.createElement("meta");
            metaEl.setAttribute("name", key);
            metaEl.setAttribute("content", meta[key]);
            injectEl(metaEl);
        });
    };
    const finalizeInjection = ()=>{
        if (targetComment) {
            targetComment._remove();
        }
    };
    return {
        injectScript,
        injectStyle,
        injectLink,
        injectMeta,
        injectHtml,
        finalizeInjection
    };
}
function lineDependencyInjector(lines, afterBodyLines) {
    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 inject = (content, afterBody)=>{
        if (afterBody) {
            afterBodyLines.push(content);
        } else {
            lines.push(content);
        }
    };
    const formatAttribs = (attribs)=>{
        return attribs ? Object.entries(attribs).map((entry)=>{
            const attrib = `${entry[0]}="${entry[1]}"`;
            return attrib;
        }).join(" ") : "";
    };
    const injectScript = (href, attribs, afterBody)=>{
        inject(scriptTemplate({
            href: pathWithForwardSlashes(href),
            attribs: formatAttribs(attribs)
        }, afterBody));
    };
    const injectStyle = (href, attribs, afterBody)=>{
        inject(stylesheetTempate({
            href: pathWithForwardSlashes(href),
            attribs: formatAttribs(attribs)
        }, afterBody));
    };
    const injectLink = (href, rel, type)=>{
        if (!type) {
            type = "";
        }
        lines.push(rawLinkTemplate({
            href: pathWithForwardSlashes(href),
            type,
            rel
        }));
    };
    const injectHtml = (html)=>{
        lines.push(html + "\n");
    };
    const injectMeta = (meta)=>{
        Object.keys(meta).forEach((name)=>{
            lines.push(metaTemplate({
                name,
                value: meta[name]
            }));
        });
    };
    const finalizeInjection = ()=>{};
    return {
        injectScript,
        injectStyle,
        injectLink,
        injectMeta,
        injectHtml,
        finalizeInjection
    };
}
async function writeFormatResources(inputDir, dependenciesFile, formatResources) {
    if (formatResources) {
        const files = Array.isArray(formatResources) ? formatResources : [
            formatResources
        ];
        const dependencies = files.map((file)=>{
            const absPath = join2(inputDir, file);
            if (!existsSync(absPath)) {
                throw new Error(`The referenced format resource '${file}' does not exist.`);
            }
            return {
                type: kFormatResources,
                content: {
                    file: absPath
                }
            };
        });
        await appendDependencies(dependenciesFile, dependencies);
    }
}
async function processFormatResources(inputDir, dependenciesFile) {
    const resources = [];
    const supporting = [];
    const dependencyJsonStream = await Deno.readTextFile(dependenciesFile);
    for (const jsonBlob of lines(dependencyJsonStream)){
        if (jsonBlob) {
            const dependency = JSON.parse(jsonBlob);
            if (dependency.type === kFormatResources) {
                const formatResource = dependency.content;
                const targetPath = join2(inputDir, basename2(formatResource.file));
                copyTo(formatResource.file, targetPath, {
                    overwrite: true,
                    preserveTimestamps: true
                });
            } else if (dependency.type === kResources) {
                const resource = dependency.content;
                resources.push(isAbsolute2(resource.file) ? relative2(inputDir, resource.file) : resource.file);
            } else if (dependency.type === kSupporting) {
                const supportingResource = dependency.content;
                supporting.push(supportingResource.file);
            }
        }
    }
    return {
        supporting,
        resources
    };
}
function createFormat(displayName, ext, ...formats) {
    return mergeConfigs(defaultFormat(displayName), ...formats, {
        render: {
            [kOutputExt]: ext
        }
    });
}
function createHtmlFormat(displayName, figwidth, figheight) {
    return createFormat(displayName, "html", {
        metadata: {
            [kLang]: "en",
            [kFigResponsive]: true,
            [kQuartoVersion]: quartoConfig.version()
        },
        execute: {
            [kFigFormat]: "retina",
            [kFigWidth]: figwidth,
            [kFigHeight]: figheight
        },
        render: {
            [kTblColwidths]: "auto"
        },
        pandoc: {
            [kStandalone]: true,
            [kWrap]: "none",
            [kDefaultImageExtension]: "png"
        }
    });
}
function createHtmlPresentationFormat(displayName, figwidth, figheight) {
    return mergeConfigs(createHtmlFormat(displayName, figwidth, figheight), {
        metadata: {
            [kFigResponsive]: false
        },
        execute: {
            [kEcho]: false,
            [kWarning]: false
        }
    });
}
function createEbookFormat(displayName, ext) {
    return createFormat(displayName, 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(displayName, ext) {
    return createFormat(displayName, ext, {
        render: {
            [kPageWidth]: 6.5
        },
        execute: {
            [kFigWidth]: 5,
            [kFigHeight]: 4
        },
        pandoc: {
            [kDefaultImageExtension]: "png"
        }
    });
}
function plaintextFormat(displayName, ext) {
    return createFormat(displayName, ext, {
        pandoc: {
            standalone: true,
            [kDefaultImageExtension]: "png"
        }
    });
}
function defaultFormat(displayName) {
    return {
        identifier: {
            [kDisplayName]: displayName
        },
        execute: {
            [kFigWidth]: 7,
            [kFigHeight]: 5,
            [kFigFormat]: "png",
            [kFigDpi]: 96,
            [kFigAsp]: undefined,
            [kMermaidFormat]: undefined,
            [kDfPrint]: "default",
            [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,
            [kIpynbFilters]: [],
            [kIpynbShellInteractivity]: null,
            [kPlotlyConnected]: true
        },
        render: {
            [kKeepTex]: false,
            [kKeepTyp]: 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,
            [kInlineIncludes]: false,
            [kPreserveYaml]: false,
            [kLatexAutoMk]: true,
            [kLatexAutoInstall]: true,
            [kLatexClean]: true,
            [kLatexMinRuns]: 1,
            [kLatexMaxRuns]: 10,
            [kLatexMakeIndex]: "makeindex",
            [kLatexMakeIndexOpts]: [],
            [kLatexTlmgrOpts]: [],
            [kLatexInputPaths]: [],
            [kLatexOutputDir]: null,
            [kLinkExternalIcon]: false,
            [kLinkExternalNewwindow]: false,
            [kSelfContainedMath]: false,
            [kFormatResources]: [],
            [kVariant]: ""
        },
        pandoc: {},
        language: {},
        metadata: {}
    };
}
function requiresShortcodeUnescapePostprocessor(markdown) {
    return markdown.includes("{{{<");
}
const kDisplayNameGFM = "Github (GFM)";
const kDisplayNameCommonMark = "CommonMark";
const kDisplayNameMarkdown = "Markdown";
function shortcodeUnescapePostprocessor(output) {
    Deno.writeTextFileSync(output, Deno.readTextFileSync(output).replaceAll("{{\\<", "{{<").replaceAll("\\>}}", ">}}"));
    return Promise.resolve();
}
function gfmFormat() {
    return createFormat(kDisplayNameGFM, "md", markdownFormat(kDisplayNameGFM), {
        pandoc: {
            to: "commonmark"
        },
        render: {
            [kVariant]: kGfmCommonmarkVariant
        },
        resolveFormat: (format)=>{
            if (format.pandoc[kToc] === true) {
                format.pandoc[kFrom] = pandocFormat(format.pandoc[kFrom] || "markdown", [
                    "gfm_auto_identifiers"
                ], []);
            }
        }
    });
}
function markdownWithCommonmarkExtensionsFormat() {
    return createFormat(kDisplayNameCommonMark, "md", markdownFormat(kDisplayNameCommonMark), {
        pandoc: {
            to: [
                "markdown_strict",
                "+raw_html",
                "+all_symbols_escapable",
                "+backtick_code_blocks",
                "+fenced_code_blocks",
                "+space_in_atx_header",
                "+intraword_underscores",
                "+lists_without_preceding_blankline",
                "+shortcut_reference_links"
            ].join("")
        }
    });
}
function commonmarkFormat(to) {
    return createFormat(kDisplayNameCommonMark, "md", markdownFormat(kDisplayNameCommonMark), {
        pandoc: {
            to
        }
    });
}
function pandocMarkdownFormat() {
    return createFormat(kDisplayNameMarkdown, "md", plaintextFormat(kDisplayNameMarkdown, "md"), {});
}
function markdownFormat(displayName) {
    return createFormat(displayName, "md", plaintextFormat(displayName, "md"), {
        render: {
            [kOutputDivs]: false
        }
    });
}
const kPdfUrl = "pdf-url";
const kAbstractUrl = "abstract-url";
const kEIssn = "eissn";
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.replaceAll(/\s+/g, "_").toLowerCase()}${datePart}`;
    if (suggestedId.length === 0) {
        suggestedId = "untitled";
    }
    return suggestedId;
}
function cslDateToEDTFDate(date) {
    if (date["date-parts"] && date["date-parts"].length > 0) {
        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 cslNames = [];
    const authorList = Array.isArray(authors) ? authors : [
        authors
    ];
    authorList.forEach((auth)=>{
        if (auth) {
            const name = authorToCslName(auth);
            if (name) {
                cslNames.push(name);
            }
        }
    });
    return cslNames;
}
const isCslDate = (dateRaw)=>{
    if (typeof dateRaw === "object") {
        return dateRaw["date-parts"] !== undefined && dateRaw["iso-8601"] !== undefined;
    } else {
        return false;
    }
};
function cslDate(dateRaw) {
    const toDateArray = (dateArr)=>{
        if (dateArr.length === 0) {
            return undefined;
        } else if (dateArr.length === 1) {
            return {
                "date-parts": [
                    [
                        dateArr[0]
                    ]
                ],
                "iso-8601": `${dateArr[0]}`
            };
        } else if (dateArr.length === 2) {
            return {
                "date-parts": [
                    [
                        dateArr[0],
                        dateArr[1]
                    ]
                ],
                "iso-8601": `${dateArr[0]}-${dateArr[1]}`
            };
        } else if (dateArr.length >= 3) {
            return {
                "date-parts": [
                    [
                        dateArr[0],
                        dateArr[1],
                        dateArr[2]
                    ]
                ],
                "iso-8601": `${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 dateStr = String(dateRaw);
        const dateArr = parseNumeric(dateStr);
        if (dateArr) {
            return toDateArray(dateArr);
        }
    } else if (typeof dateRaw === "string") {
        const match = dateRaw.match(/^(\d\d\d\d)[-/](\d\d)$/);
        if (match) {
            return {
                "date-parts": [
                    [
                        parseInt(match[1]),
                        parseInt(match[2])
                    ]
                ],
                "iso-8601": `${match[1]}-${match[2]}`
            };
        } else {
            const date = parsePandocDate(dateRaw);
            if (date) {
                const formatted = formatDate(date, "YYYY-MM-DD");
                return {
                    "date-parts": [
                        [
                            date.getFullYear(),
                            date.getMonth() + 1,
                            date.getDate()
                        ]
                    ],
                    literal: formatDate(date, "YYYY-MM-DD"),
                    raw: dateRaw,
                    "iso-8601": formatted
                };
            }
        }
        return undefined;
    } else if (isCslDate(dateRaw)) {
        return dateRaw;
    } else if (dateRaw !== null && typeof dateRaw === "object") {
        const dateParts = [];
        if ("year" in dateRaw) {
            dateParts.push(dateRaw["year"]);
            if ("month" in dateRaw) {
                dateParts.push(dateRaw["month"]);
                if ("day" in dateRaw) {
                    dateParts.push(dateRaw["day"]);
                }
            }
            return {
                "date-parts": [
                    dateParts
                ],
                "iso-8601": dateParts.join("-")
            };
        } else {
            return undefined;
        }
    }
}
function authorToCslName(author) {
    if (typeof author === "string") {
        const parts = author.split(" ");
        if (parts.length > 0) {
            const given = parts.shift() || "";
            const family = parts.length > 0 ? parts.join(" ") : "";
            return {
                family,
                given
            };
        }
    } else {
        return author;
    }
}
function cslType(type) {
    if (types3.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 types3 = [
    "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 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);
        },
        readMarkdown (doc) {
            return readEnvelope(doc, envelopeId);
        },
        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 .quarto-markdown-envelope-contents render-id="${id}"}`;
    };
    const hiddenDiv = (id, contents)=>{
        return `\n:::{.hidden .quarto-markdown-envelope-contents 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;
};
function getEnv(name, defaultValue) {
    const value = Deno.env.get(name);
    if (!value) {
        if (defaultValue === undefined) {
            throw new Error("Missing environment variable: " + name);
        } else {
            return defaultValue;
        }
    } else {
        return value;
    }
}
let traceCount = 0;
async function runPandoc(options, sysFilters) {
    const beforePandocHooks = [];
    const afterPandocHooks = [];
    const pandocEnv = {};
    const setupPandocEnv = ()=>{
        pandocEnv["QUARTO_FILTER_PARAMS"] = encodeBase64(paramsJson);
        const traceFilters = pandocMetadata?.["_quarto"]?.["trace-filters"] || Deno.env.get("QUARTO_TRACE_FILTERS");
        if (traceFilters) {
            let traceCountSuffix = "";
            if (traceCount > 0) {
                traceCountSuffix = `-${traceCount}`;
            }
            ++traceCount;
            if (traceFilters === true) {
                pandocEnv["QUARTO_TRACE_FILTERS"] = "quarto-filter-trace.json" + traceCountSuffix;
            } else {
                pandocEnv["QUARTO_TRACE_FILTERS"] = traceFilters + traceCountSuffix;
            }
        }
        if (Deno.env.get("QUARTO_LUA_CPATH") !== undefined) {
            pandocEnv["LUA_CPATH"] = getEnv("QUARTO_LUA_CPATH");
        } else {
            pandocEnv["LUA_CPATH"] = "";
        }
    };
    const cwd = dirname2(options.source);
    const cmd = [
        pandocBinaryPath(),
        "+RTS",
        "-K512m",
        "-RTS"
    ];
    const args = [
        ...options.args
    ];
    if (logLevel() === "DEBUG") {
        args.push("--verbose");
        args.push("--trace");
    }
    if (options.flags?.quiet || logLevel() === "ERROR") {
        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[kQuartoInternal];
        delete metadata[kQuartoVarsKey];
        delete metadata[kQuartoVersion];
        delete metadata[kFigResponsive];
        delete metadata[kQuartoTemplateParams];
        delete metadata[kRevealJsScripts];
        deleteProjectMetadata(metadata);
        deleteCrossrefMetadata(metadata);
        if (metadata[kRevealJSPlugins] && metadata[kRevealJSPlugins].length === 0) {
            delete metadata[kRevealJSPlugins];
        }
    };
    cleanMetadataForPrinting(printMetadata);
    kQuartoForwardedMetadataFields.forEach((field)=>{
        if (options.flags?.pandocMetadata?.[field]) {
            options.format.metadata[field] = options.flags.pandocMetadata[field];
        }
    });
    let allDefaults = await generateDefaults(options) || {};
    let printAllDefaults = __VIRTUAL_FILE107(allDefaults);
    const formatFilterParams = {};
    const forceMath = options.format.metadata[kMath];
    delete options.format.metadata[kMath];
    const kOJSFilter = "ojs";
    if (sysFilters.includes(kOJSFilter)) {
        formatFilterParams[kOJSFilter] = true;
        sysFilters = sysFilters.filter((filter)=>filter !== kOJSFilter);
    }
    formatFilterParams["language"] = options.format.language;
    if (!options.format.metadata[kTocTitle] && !isAstOutput(options.format.pandoc)) {
        options.format.metadata[kTocTitle] = options.format.language[projectIsWebsite(options.project) && !projectIsBook(options.project) && isHtmlOutput(options.format.pandoc, true) ? kTocTitleWebsite : kTocTitleDocument];
    }
    if (options.format.metadata[kTocLocation] && options.format.pandoc.toc === undefined) {
        options.format.pandoc.toc = true;
    }
    if (options.format.metadata[kAbstract] && (isHtmlDocOutput(options.format.pandoc) || isEpubOutput(options.format.pandoc))) {
        options.format.metadata[kAbstractTitle] = options.format.metadata[kAbstractTitle] || options.format.language[kSectionTitleAbstract];
    }
    const postprocessors = [];
    const htmlPostprocessors = [];
    const htmlFinalizers = [];
    const htmlRenderAfterBody = [];
    const dependenciesFile = options.services.temp.createFile();
    if (sysFilters.length > 0 || options.format.formatExtras || options.project?.formatExtras) {
        const projectExtras = options.project?.formatExtras ? await options.project.formatExtras(options.source, options.flags || {}, options.format, options.services) : {};
        const formatExtras = options.format.formatExtras ? await options.format.formatExtras(options.source, options.markdown, options.flags || {}, options.format, options.libDir, options.services, options.offset, options.project, options.quiet) : {};
        const extras = await resolveExtras(projectExtras, formatExtras, options.format, cwd, options.libDir, options.services.temp, dependenciesFile, 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(overflowXPostprocessor);
            if (options.flags?.katex || options.format.pandoc[kHtmlMathMethod] === "katex") {
                htmlPostprocessors.push(katexPostProcessor());
            }
            if (!projectIsWebsite(options.project)) {
                htmlPostprocessors.push(discoverResourceRefs);
                htmlPostprocessors.push(fixEmptyHrefs);
            }
            if (forceMath) {
                const htmlMarkdownHandlers = [];
                htmlMarkdownHandlers.push({
                    getUnrendered: ()=>{
                        return {
                            inlines: {
                                "quarto-enable-math-inline": "$e = mC^2$"
                            }
                        };
                    },
                    processRendered: (_rendered, _doc)=>{}
                });
                const htmlMarkdownPipeline = createMarkdownPipeline("quarto-book-math", htmlMarkdownHandlers);
                const htmlPipelinePostProcessor = (doc)=>{
                    htmlMarkdownPipeline.processRenderedMarkdown(doc);
                    return Promise.resolve({
                        resources: [],
                        supporting: []
                    });
                };
                htmlRenderAfterBody.push(htmlMarkdownPipeline.markdownAfterBody());
                htmlPostprocessors.push(htmlPipelinePostProcessor);
            }
        }
        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((filter)=>resourcePath(join2("filters", filter))));
        }
        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] === null) {
                delete printAllDefaults[kHighlightStyle];
                allDefaults[kHighlightStyle] = null;
            } else if (extras.pandoc[kHighlightStyle]) {
                delete printAllDefaults[kHighlightStyle];
                allDefaults[kHighlightStyle] = extras.pandoc[kHighlightStyle];
            } else {
                delete printAllDefaults[kHighlightStyle];
                delete allDefaults[kHighlightStyle];
            }
        }
        if (extras.metadata || extras.metadataOverride) {
            resolveTemplatePartialPaths(options.format.metadata, cwd, options.project);
            options.format.metadata = {
                ...mergeConfigs(extras.metadata || {}, options.format.metadata),
                ...extras.metadataOverride || {}
            };
            printMetadata = mergeConfigs(extras.metadata, printMetadata);
            cleanMetadataForPrinting(printMetadata);
        }
        if (extras[kNotebooks]) {
            const documentNotebooks = options.format.render[kNotebookView];
            if (documentNotebooks !== false) {
                const userNotebooks = documentNotebooks === true ? [] : Array.isArray(documentNotebooks) ? documentNotebooks : documentNotebooks !== undefined ? [
                    documentNotebooks
                ] : [];
                const uniqExtraNotebooks = extras[kNotebooks].filter((nb)=>{
                    return !userNotebooks.find((userNb)=>{
                        return userNb.notebook === nb.notebook;
                    });
                });
                options.format.render[kNotebookView] = [
                    ...userNotebooks,
                    ...uniqExtraNotebooks
                ];
            }
        }
        if (isTypstOutput(options.format.pandoc)) {
            delete allDefaults[kColumns];
            delete printAllDefaults[kColumns];
        }
        const userTemplate = getPandocArg(args, "--template") || allDefaults[kTemplate];
        const userPartials = readPartials(options.format.metadata, cwd);
        const inputDir = normalizePath(cwd);
        const resolvePath = (path)=>{
            if (isAbsolute2(path)) {
                return path;
            } else {
                return join2(inputDir, path);
            }
        };
        const templateContext = extras.templateContext;
        if (templateContext) {
            cleanTemplatePartialMetadata(printMetadata, templateContext.partials || []);
            const template = userTemplate ? resolvePath(userTemplate) : templateContext.template;
            if (!userTemplate && userPartials.length > 0) {
                const templateNames = templateContext.partials?.map((temp)=>basename2(temp));
                if (templateNames) {
                    const userPartialNames = userPartials.map((userPartial)=>basename2(userPartial));
                    const hasAtLeastOnePartial = userPartialNames.find((userPartial)=>{
                        return templateNames.includes(userPartial);
                    });
                    if (!hasAtLeastOnePartial) {
                        const errorMsg = `The format '${allDefaults.to}' only supports the following partials:\n${templateNames.join("\n")}\n\nPlease provide one or more of these partials.`;
                        throw new Error(errorMsg);
                    }
                } else {
                    throw new Error(`The format ${allDefaults.to} does not support providing any template partials.`);
                }
            }
            const partials = templateContext.partials || [];
            partials.push(...userPartials);
            const stagedTemplate = await stageTemplate(options, extras, {
                template,
                partials
            });
            delete options.format.metadata[kTemplatePartials];
            allDefaults[kTemplate] = stagedTemplate;
        } else {
            if (userPartials.length > 0 && !isIpynbOutput(options.format.pandoc)) {
                throw new Error(`The format ${allDefaults.to} does not support providing any template partials.`);
            } else if (userTemplate) {
                allDefaults[kTemplate] = userTemplate;
            }
        }
        options.format.metadata = cleanupPandocMetadata(options.format.metadata);
        printMetadata = cleanupPandocMetadata(printMetadata);
        if (extras[kIncludeInHeader]) {
            if (allDefaults[kIncludeInHeader] !== undefined && !__VIRTUAL_FILE53(allDefaults[kIncludeInHeader])) {
                allDefaults[kIncludeInHeader] = [
                    allDefaults[kIncludeInHeader]
                ];
            }
            allDefaults = {
                ...allDefaults,
                [kIncludeInHeader]: [
                    ...extras[kIncludeInHeader] || [],
                    ...allDefaults[kIncludeInHeader] || []
                ]
            };
        }
        if (extras[kIncludeBeforeBody]) {
            if (allDefaults[kIncludeBeforeBody] !== undefined && !__VIRTUAL_FILE53(allDefaults[kIncludeBeforeBody])) {
                allDefaults[kIncludeBeforeBody] = [
                    allDefaults[kIncludeBeforeBody]
                ];
            }
            allDefaults = {
                ...allDefaults,
                [kIncludeBeforeBody]: [
                    ...extras[kIncludeBeforeBody] || [],
                    ...allDefaults[kIncludeBeforeBody] || []
                ]
            };
        }
        if (extras[kIncludeAfterBody]) {
            if (allDefaults[kIncludeAfterBody] !== undefined && !__VIRTUAL_FILE53(allDefaults[kIncludeAfterBody])) {
                allDefaults[kIncludeAfterBody] = [
                    allDefaults[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.services.temp);
        allDefaults.filters = [
            ...extras.filters?.pre || [],
            ...allDefaults.filters || [],
            ...extras.filters?.post || []
        ];
        allDefaults.filters = allDefaults.filters.map((filter)=>{
            if (typeof filter === "string") {
                return pandocMetadataPath(filter);
            } else {
                return {
                    type: filter.type,
                    path: pandocMetadataPath(filter.path)
                };
            }
        });
        const filterParams = extras[kFilterParams];
        if (filterParams) {
            Object.keys(filterParams).forEach((key)=>{
                formatFilterParams[key] = filterParams[key];
            });
        }
    }
    if (isMarkdownOutput(options.format) && requiresShortcodeUnescapePostprocessor(options.markdown)) {
        postprocessors.push(shortcodeUnescapePostprocessor);
    }
    const title = allDefaults?.[kVariables]?.[kTitle] || options.format.metadata[kTitle];
    const pageTitle = allDefaults?.[kVariables]?.[kPageTitle] || options.format.metadata[kPageTitle];
    const titlePrefix = allDefaults?.[kTitlePrefix];
    if (!title && !pageTitle && isHtmlFileOutput(options.format.pandoc)) {
        const [_dir, stem] = dirAndStem(options.source);
        args.push("--metadata", `pagetitle:${pandocAutoIdentifier(stem, false)}`);
    }
    if (pageTitle !== undefined && pageTitle === titlePrefix || pageTitle === undefined && title === titlePrefix) {
        delete allDefaults[kTitlePrefix];
    }
    if (options.keepYaml && allDefaults.to) {
        allDefaults.to = allDefaults.to.replaceAll(`+${kYamlMetadataBlock}`, "");
    }
    if (Deno.build.os === "windows") {
        await cacheCodePage();
    }
    const filterResultsFile = options.services.temp.createFile();
    const timingResultsFile = options.services.temp.createFile();
    const writerKeys = [
        "to",
        "writer"
    ];
    for (const key of writerKeys){
        if (allDefaults[key]?.match(/[.]lua$/)) {
            formatFilterParams["custom-writer"] = allDefaults[key];
            allDefaults[key] = resourcePath("filters/customwriter/customwriter.lua");
        }
    }
    if (allDefaults.from) {
        formatFilterParams["user-defined-from"] = allDefaults.from;
    }
    allDefaults.from = resourcePath("filters/qmd-reader.lua");
    let pandocArgs = args;
    const paramsJson = await filterParamsJson(pandocArgs, options, allDefaults, formatFilterParams, filterResultsFile, dependenciesFile, timingResultsFile);
    if (!isLatexOutput(options.format.pandoc) && !isTypstOutput(options.format.pandoc) && !isMarkdownOutput(options.format) && 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);
    }
    if (typeof allDefaults[kNumberOffset] === "number") {
        allDefaults[kNumberOffset] = [
            allDefaults[kNumberOffset]
        ];
    }
    const dataDirArgs = new Map();
    dataDirArgs.set("--data-dir", true);
    pandocArgs = removePandocArgs(pandocArgs, dataDirArgs);
    pandocArgs.push("--data-dir", resourcePath("pandoc/datadir"));
    allDefaults[kSyntaxDefinitions] = allDefaults[kSyntaxDefinitions] || [];
    const syntaxDefinitions = expandGlobSync(join2(resourcePath(join2("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[kTemplate] && !havePandocArg(args, "--template") && !options.keepYaml && allDefaults.to) {
        const formatDesc = parseFormatString(allDefaults.to);
        const lookupTo = formatDesc.baseFormat;
        if ([
            "gfm",
            "commonmark",
            "commonmark_x",
            "markdown_strict",
            "markdown_phpextra",
            "markdown_github",
            "markua"
        ].includes(lookupTo)) {
            allDefaults[kTemplate] = resourcePath(join2("pandoc", "templates", "default.markdown"));
        }
    }
    if (isHtmlFileOutput(options.format.pandoc)) {
        pandocArgs = pandocArgs.filter((arg)=>arg !== "--self-contained" && arg !== "--embed-resources");
        delete allDefaults[kSelfContained];
        delete allDefaults[kEmbedResources];
    }
    if (allDefaults) {
        const defaultsFile = await writeDefaultsFile(allDefaults, options.services.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 key of Object.keys(engineMetadata)){
        const isChapterTitle = key === kTitle && projectIsBook(options.project);
        if (!isQuartoMetadata(key) && !isChapterTitle && !isIncludeMetadata(key)) {
            const formats = engineMetadata[kMetadataFormat];
            if (__VIRTUAL_FILE18(formats) && metadataGetDeep(formats, key).length > 0) {
                continue;
            }
            if (key === kTheme && isRevealjsOutput(options.format.pandoc)) {
                continue;
            }
            pandocMetadata[key] = engineMetadata[key];
        }
    }
    const dateRaw = pandocMetadata[kDate];
    const dateFields = [
        kDate,
        kDateModified
    ];
    dateFields.forEach((dateField)=>{
        const date = pandocMetadata[dateField];
        const format = pandocMetadata[kDateFormat];
        pandocMetadata[dateField] = resolveAndFormatDate(options.source, date, format);
    });
    if (typeof pandocMetadata[kCitation] === "boolean" && pandocMetadata[kCitation] === true) {
        pandocMetadata[kCitation] = {};
    }
    const citationMetadata = pandocMetadata[kCitation];
    if (citationMetadata) {
        const docCSLDate = dateRaw ? cslDate(resolveDate(options.source, dateRaw)) : undefined;
        const fields = [
            "issued",
            "available-date"
        ];
        fields.forEach((field)=>{
            if (citationMetadata[field]) {
                citationMetadata[field] = cslDate(citationMetadata[field]);
            } else if (docCSLDate) {
                citationMetadata[field] = docCSLDate;
            }
        });
    }
    const authorsRaw = pandocMetadata[kAuthors] || pandocMetadata[kAuthor];
    if (authorsRaw) {
        const authors = parseAuthor(pandocMetadata[kAuthor], true);
        if (authors) {
            pandocMetadata[kAuthor] = authors.map((author)=>cslNameToString(author.name));
            pandocMetadata[kAuthors] = Array.isArray(authorsRaw) ? authorsRaw : [
                authorsRaw
            ];
        }
    }
    const instituteRaw = pandocMetadata[kInstitute];
    if (instituteRaw) {
        pandocMetadata[kInstitutes] = Array.isArray(instituteRaw) ? instituteRaw : [
            instituteRaw
        ];
    }
    if (pandocMetadata.lang === "zh") {
        pandocMetadata.lang = "zh-Hans";
    }
    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.services.temp.createFile({
        prefix: "quarto-input",
        suffix: ".md"
    });
    Deno.writeTextFileSync(inputTemp, input);
    cmd.push(inputTemp);
    const metadataTemp = options.services.temp.createFile({
        prefix: "quarto-metadata",
        suffix: ".yml"
    });
    const pandocPassedMetadata = __VIRTUAL_FILE107(pandocMetadata);
    delete pandocPassedMetadata.format;
    delete pandocPassedMetadata.project;
    delete pandocPassedMetadata.website;
    delete pandocPassedMetadata.about;
    if (pandocPassedMetadata._quarto) {
        delete pandocPassedMetadata._quarto.tests;
    }
    Deno.writeTextFileSync(metadataTemp, stringify(pandocPassedMetadata, {
        indent: 2,
        lineWidth: -1,
        sortKeys: false,
        skipInvalid: true
    }));
    cmd.push("--metadata-file", metadataTemp);
    cmd.push(...pandocArgs);
    if (!options.quiet && !options.flags?.quiet) {
        runPandocMessage(printArgs, printAllDefaults, sysFilters, printMetadata);
    }
    const luaEpoch = await getLuaTiming();
    setupPandocEnv();
    for (const hook of beforePandocHooks){
        await hook();
    }
    const result1 = await execProcess({
        cmd,
        cwd,
        env: pandocEnv
    });
    for (const hook of afterPandocHooks){
        await hook();
    }
    const resources = resourcesFromMetadata(options.format.metadata[kResources]);
    let inputTraits = {};
    if (existsSync(filterResultsFile)) {
        const filterResultsJSON = Deno.readTextFileSync(filterResultsFile);
        if (filterResultsJSON.trim().length > 0) {
            const filterResults = JSON.parse(filterResultsJSON);
            inputTraits = filterResults.inputTraits;
            const resourceFiles = filterResults.resourceFiles || [];
            resources.push(...resourceFiles);
        }
    }
    if (existsSync(timingResultsFile)) {
        const timingResultsJSON = Deno.readTextFileSync(timingResultsFile);
        if (timingResultsJSON.length > 0 && Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
            const luaNow = await getLuaTiming();
            const entries = JSON.parse(timingResultsJSON);
            insertExplicitTimingEntries(luaEpoch, luaNow, entries, "pandoc");
        }
    }
    if (result1.success) {
        return {
            inputMetadata: pandocMetadata,
            inputTraits,
            resources,
            postprocessors,
            htmlPostprocessors: isHtmlOutput(options.format.pandoc) ? htmlPostprocessors : [],
            htmlFinalizers: isHtmlDocOutput(options.format.pandoc) ? htmlFinalizers : []
        };
    } else {
        if (Deno.build.os === "windows") {
            clearCodePageCache();
        }
        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, format, inputDir, libDir, temp, dependenciesFile, project) {
    let extras = mergeConfigs(projectExtras, formatExtras);
    if (projectExtras.metadata?.[kDocumentClass]) {
        extras.metadata = extras.metadata || {};
        extras.metadata[kDocumentClass] = projectExtras.metadata?.[kDocumentClass];
    }
    await writeFormatResources(inputDir, dependenciesFile, format.render[kFormatResources]);
    if (isHtmlOutput(format.pandoc)) {
        extras = await resolveSassBundles(inputDir, extras, format, temp, formatExtras.html?.[kSassBundles], projectExtras.html?.[kSassBundles], project);
        await writeDependencies(dependenciesFile, extras);
        const htmlDependenciesPostProcesor = (doc, _inputMedata)=>{
            return withTiming("pandocDependenciesPostProcessor", async ()=>await readAndInjectDependencies(dependenciesFile, inputDir, libDir, doc, project));
        };
        extras.html = extras.html || {};
        extras.html[kHtmlPostprocessors] = extras.html?.[kHtmlPostprocessors] || [];
        if (isHtmlFileOutput(format.pandoc)) {
            extras.html[kHtmlPostprocessors].unshift(htmlDependenciesPostProcesor);
        }
        delete extras.html?.[kDependencies];
    } else {
        delete extras.html;
    }
    if (format.render[kLatexAutoMk] === false) {
        await processFormatResources(inputDir, dependenciesFile);
    } else {
        const resourceDependenciesPostProcessor = async (_output)=>{
            return await processFormatResources(inputDir, dependenciesFile);
        };
        extras.postprocessors = extras.postprocessors || [];
        extras.postprocessors.push(resourceDependenciesPostProcessor);
    }
    extras = resolveTextHighlightStyle(inputDir, extras, format.pandoc);
    return extras;
}
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 runPandocMessage(args, pandoc, sysFilters, metadata, debug) {
    info(`pandoc ${args.join(" ")}`, {
        bold: true
    });
    if (pandoc) {
        info(pandocDefaultsMessage(pandoc, sysFilters, debug), {
            indent: 2
        });
    }
    const keys = Object.keys(metadata);
    if (keys.length > 0) {
        const printMetadata = __VIRTUAL_FILE107(metadata);
        delete printMetadata.format;
        removeFilterParams(printMetadata);
        if (Object.keys(printMetadata).length > 0) {
            info("metadata", {
                bold: true
            });
            info(stringify(printMetadata, {
                indent: 2,
                lineWidth: -1,
                sortKeys: false,
                skipInvalid: true
            }), {
                indent: 2
            });
        }
    }
}
function resolveTextHighlightStyle(inputDir, extras, pandoc) {
    extras = cloneDeep1(extras);
    const highlightTheme = pandoc[kHighlightStyle] || kDefaultHighlightStyle;
    const textHighlightingMode = extras.html?.[kTextHighlightingMode];
    if (highlightTheme === "none") {
        extras.pandoc = extras.pandoc || {};
        extras.pandoc[kHighlightStyle] = null;
        return extras;
    }
    switch(textHighlightingMode){
        case "light":
        case "dark":
            extras.pandoc = extras.pandoc || {};
            extras.pandoc[kHighlightStyle] = textHighlightThemePath1(inputDir, highlightTheme, textHighlightingMode) || highlightTheme;
            break;
        case "none":
            if (extras.pandoc) {
                extras.pandoc = extras.pandoc || {};
                extras.pandoc[kHighlightStyle] = textHighlightThemePath1(inputDir, "none");
            }
            break;
        case undefined:
        default:
            extras.pandoc = extras.pandoc || {};
            extras.pandoc[kHighlightStyle] = textHighlightThemePath1(inputDir, highlightTheme, "light") || highlightTheme;
            break;
    }
    return extras;
}
function renderCleanup(input, output, format, supporting, keepMd) {
    const figureFormat = isLatexOutput(format.pandoc) ? extname2(output).slice(1) : format.pandoc.to;
    if (!isAbsolute2(output)) {
        output = join2(dirname2(input), output);
    }
    if (keepMd && !format.execute[kKeepMd] && keepMd !== output) {
        removeIfExists(keepMd);
    }
    if (!format.execute[kKeepMd] && !format.render[kKeepTex] && !format.render[kKeepTyp] && supporting) {
        if (isHtmlFileOutput(format.pandoc)) {
            const libDir = join2(dirname2(input), filesDirLibDir(input));
            if (existsSync(libDir)) {
                supporting.push(normalizePath(libDir));
            }
        } else {
            let filesDir = join2(dirname2(input), inputFilesDir(input));
            if (existsSync(filesDir)) {
                filesDir = normalizePath(filesDir);
            }
            supporting = supporting.map((supportingDir)=>{
                if (filesDir === supportingDir) {
                    return join2(filesDir, figuresDir(figureFormat));
                } else {
                    return supportingDir;
                }
            });
        }
        const mediabagDir = join2(dirname2(input), filesDirMediabagDir(input));
        if (existsSync(mediabagDir)) {
            supporting.push(mediabagDir);
        }
        __VIRTUAL_FILE181(supporting).forEach((path)=>{
            if (existsSync(path)) {
                safeRemoveSync(path, {
                    recursive: true
                });
            }
        });
    }
    const filesDir = join2(dirname2(input), inputFilesDir(input));
    const figsDir = join2(filesDir, figuresDir(figureFormat));
    const libDir = join2(dirname2(input), filesDirLibDir(input));
    const mediabagDir = join2(dirname2(input), filesDirMediabagDir(input));
    removeIfEmptyDir(figsDir);
    removeIfEmptyDir(libDir);
    removeIfEmptyDir(mediabagDir);
    removeIfEmptyDir(filesDir);
}
function isSelfContained(flags, format) {
    return !!(flags[kSelfContained] || format.pandoc[kSelfContained] || flags[kEmbedResources] || format.pandoc[kEmbedResources]);
}
const kStandaloneExtensionNames = [
    "pdf",
    "epub",
    "fb2",
    "docx",
    "rtf",
    "pptx",
    "odt",
    "ipynb"
];
const kStandaloneExtensions = kStandaloneExtensionNames.map((name)=>`.${name}`);
function isSelfContainedOutput(flags, format, finalOutput) {
    return isSelfContained(flags, format) || kStandaloneExtensions.includes(extname2(finalOutput));
}
function renderProgress(message) {
    logProgress(message);
}
function ipynbTitleTemplatePath() {
    return formatResourcePath("ipynb", join2("templates", "title-block.md"));
}
function ipynbFormat() {
    return createFormat("Jupyter", "ipynb", {
        pandoc: {
            standalone: true,
            [kDefaultImageExtension]: "png"
        },
        formatExtras: (input, _markdown, _flags, format)=>{
            const resolveTemplate = ()=>{
                const titleTemplate = ipynbTitleTemplatePath();
                const partials = readPartials(format.metadata, dirname2(input));
                if (partials.length > 0) {
                    const userTitleTemplate = partials.find((part)=>{
                        return basename2(part) === "title-block.md";
                    });
                    if (userTitleTemplate) {
                        return userTitleTemplate;
                    } else {
                        return titleTemplate;
                    }
                } else {
                    return titleTemplate;
                }
            };
            return {
                metadata: {
                    [kIPynbTitleBlockTemplate]: resolveTemplate()
                },
                postprocessors: [
                    (output)=>{
                        const nb = jupyterFromFile(output);
                        const widgets = nb.metadata.widgets;
                        if (widgets && typeof widgets === "string") {
                            nb.metadata.widgets = JSON.parse(new TextDecoder().decode(decodeBase64(widgets)));
                        }
                        nb.cells = nb.cells.map((cell)=>{
                            if (cell.cell_type == "raw") {
                                if (cell.metadata[kCellFormat]) {
                                    const format = cell.metadata[kCellFormat];
                                    delete cell.metadata[kCellFormat];
                                    if (format === kTextHtml) {
                                        cell.metadata[kCellRawMimeType] = format;
                                    } else if (format === "tex") {
                                        cell.metadata[kCellRawMimeType] = kTextLatex;
                                    } else if (format === "rst") {
                                        cell.metadata[kCellRawMimeType] = kRestructuredText;
                                    } else if (format === "rtf") {
                                        cell.metadata[kCellRawMimeType] = kApplicationRtf;
                                    } else {
                                        cell.metadata[kCellFormat] = format;
                                    }
                                }
                            }
                            cell.outputs?.forEach((output)=>{
                                const cellOutput = output;
                                if (cellOutput.output_type === "display_data") {
                                    const cellDisplayOutput = cellOutput;
                                    if (cellDisplayOutput.data["application/json"]) {
                                        const jsonData = cellDisplayOutput.data["application/json"];
                                        if (jsonData[kQuartoMimeType]) {
                                            const realMimetype = jsonData[kQuartoMimeType];
                                            delete jsonData[kQuartoMimeType];
                                            cellDisplayOutput.data[realMimetype] = jsonData;
                                            delete cellDisplayOutput.data["application/json"];
                                        }
                                    }
                                }
                            });
                            return cell;
                        });
                        Deno.writeTextFileSync(output, JSON.stringify(nb, null, 2));
                        return Promise.resolve();
                    }
                ]
            };
        }
    });
}
const kHtmlPreview = "html-preview";
const kJatsSubarticle1 = "jats-subarticle";
const kRenderedIPynb = "rendered-ipynb";
const kQmdIPynb = "qmd-ipynb";
const kEcho1 = "echo";
const kWarning1 = "warning";
const kOutput1 = "output";
const kHashRegex = /(.*?)#(.*)/;
const kIndexRegex = /(.*)\[([0-9,-]*)\]/;
const placeholderRegex = ()=>{
    return /<!-- 12A0366C\|(.*)\|:(.*?) \| (.*?) \| (.*?) -->/g;
};
const kNotebookCache = "notebook-cache";
function parseNotebookAddress(path) {
    const hashResult = path.match(kHashRegex);
    if (hashResult) {
        const path = hashResult[1];
        if (isEmbeddable(path)) {
            return {
                path,
                ids: resolveCellIds(hashResult[2])
            };
        } else {
            unsupportedEmbed(path);
        }
    }
    const indexResult = path.match(kIndexRegex);
    if (indexResult) {
        const path = indexResult[1];
        if (isEmbeddable(path)) {
            return {
                path,
                indexes: resolveRange(indexResult[2])
            };
        } else {
            unsupportedEmbed(path);
        }
    }
    if (isEmbeddable(path)) {
        return {
            path
        };
    } else {
        unsupportedEmbed(path);
    }
}
function unsupportedEmbed(path) {
    if (extname2(path) === "") {
        throw new Error(`Unable to embed content from ${path} - there is no extension on the file path.`);
    } else {
        throw new Error(`Unable to embed content from ${path} - embedding content is not supported for this file type.`);
    }
}
async function ensureNotebookContext(markdown, services, context) {
    const regex = placeholderRegex();
    let match = regex.exec(markdown);
    const nbsToRender = [];
    while(match){
        const inputPath = match[1];
        const nbAddr = match[2];
        const nbAddress = parseNotebookAddress(nbAddr);
        if (!nbAddress) {
            throw new InternalError("Unexpected - there must be a notebook address since we matched.");
        }
        const nbAbsPath = resolveNbPath(inputPath, nbAddress.path, context);
        if (!isNotebook(nbAbsPath)) {
            if (!services.notebook.get(nbAbsPath, context)?.[kQmdIPynb]) {
                nbsToRender.push({
                    path: nbAbsPath,
                    name: nbAddress.path
                });
            }
        }
        match = regex.exec(markdown);
    }
    const uniqueRenders = __VIRTUAL_FILE210(nbsToRender, (nb)=>nb.path);
    if (uniqueRenders.length) {
        logProgress("Rendering qmd embeds");
    }
    let count = 0;
    for (const nb of uniqueRenders){
        logProgress(`[${++count}/${uniqueRenders.length}] ${nb.name}`);
        const partitioned = partitionMarkdown(Deno.readTextFileSync(nb.path));
        let notebookMeta;
        const filename = basename2(nb.path);
        if (partitioned.yaml && partitioned.yaml.title) {
            notebookMeta = {
                title: partitioned.yaml.title,
                filename
            };
        } else {
            notebookMeta = {
                title: filename,
                filename: filename
            };
        }
        await services.notebook.render(nb.path, ipynbFormat(), kQmdIPynb, services, notebookMeta, context);
    }
}
function notebookMarkdownPlaceholder(input, nbPath, options, outputs) {
    return `<!-- 12A0366C|${input}|:${nbPath} | ${outputs || ""} | ${optionsToPlaceholder(options)} -->\n`;
}
async function replaceNotebookPlaceholders(to, context, flags, markdown, services) {
    const assetCache = {};
    const regex = placeholderRegex();
    let match = regex.exec(markdown);
    let includes;
    const notebooks = [];
    while(match){
        const inputPath = match[1];
        const nbAddressStr = match[2];
        const nbAddress = parseNotebookAddress(nbAddressStr);
        if (!nbAddress) {
            throw new InternalError("Expected to find a valid notebook address string for an embed.");
        }
        const nbAbsPath = resolveNbPath(inputPath, nbAddress.path, context.project);
        let assets = assetCache[inputPath];
        if (!assets) {
            assets = jupyterAssets(inputPath, to);
            assetCache[inputPath] = assets;
        }
        if (nbAddress) {
            const outputsStr = match[3];
            const nbOutputs = outputsStr ? resolveRange(outputsStr) : undefined;
            const placeholderStr = match[4];
            const nbOptions = placeholderStr ? placeholderToOptions(placeholderStr) : {};
            const notebookIncludes = ()=>{
                if (safeExistsSync(nbAbsPath)) {
                    const notebook = jupyterFromNotebookOrQmd(nbAbsPath, services, context.project);
                    const dependencies = isHtmlOutput(context.format.pandoc) ? extractJupyterWidgetDependencies(notebook) : undefined;
                    if (dependencies) {
                        const tempDir = globalTempContext().createDir();
                        return includesForJupyterWidgetDependencies([
                            dependencies
                        ], tempDir);
                    } else {
                        return undefined;
                    }
                } else {
                    throw new Error(`Unable to embed content from notebook '${nbAddress.path}'\nThe file ${nbAbsPath} doesn't exist or cannot be read.`);
                }
            };
            includes = notebookIncludes();
            const nbMarkdown = await notebookMarkdown(inputPath, nbAddress, nbAbsPath, assets, context, flags, nbOptions, nbOutputs);
            if (nbMarkdown && !notebooks.includes(nbAddress.path)) {
                notebooks.push(nbAddress.path);
            }
            markdown = markdown.replaceAll(match[0], nbMarkdown || "");
        }
        match = regex.exec(markdown);
    }
    regex.lastIndex = 0;
    const supporting = Object.values(assetCache).map((assets)=>{
        return join2(assets.base_dir, assets.supporting_dir);
    });
    return {
        notebooks,
        includes,
        markdown,
        supporting
    };
}
function resolveNbPath(input, path, context) {
    if (!context.isSingleFile) {
        const projectMatch = path.match(/^[\\/](.*)/);
        if (projectMatch) {
            return join2(context.dir, projectMatch[1]);
        }
    }
    if (isAbsolute2(path)) {
        return path;
    } else {
        if (isAbsolute2(input)) {
            return join2(dirname2(input), path);
        } else {
            const baseDir = context.isSingleFile ? Deno.cwd() : context.dir;
            const result1 = join2(baseDir, dirname2(input), path);
            return result1;
        }
    }
}
async function notebookMarkdown(inputPath, nbAddress, nbAbsPath, assets, context, flags, options, outputs) {
    const notebookInfo = await getCachedNotebookInfo(inputPath, nbAddress, assets, context, flags, options, outputs);
    if (notebookInfo.outputs.length === 0) {
        return undefined;
    }
    const notebookMarkdown = (nbAbsPath, cells, title)=>{
        const cellId = cells.length > 0 ? cells[0].id || "" : "";
        const markdown = [
            "",
            `:::{.quarto-embed-nb-cell notebook="${nbAbsPath}" ${title ? `notebook-title="${title}"` : ""} notebook-cellId="${cellId}"}`
        ];
        const cellOutput = cells.map((cell)=>cell.markdown).join("");
        markdown.push("");
        markdown.push(cellOutput);
        markdown.push("");
        markdown.push(":::");
        return markdown.join("\n");
    };
    if (nbAddress.ids) {
        const theCells = nbAddress.ids.map((id)=>{
            const cell = cellForId(id, notebookInfo.outputs);
            if (cell === undefined) {
                throw new Error(`The cell ${id} does not exist in notebook`);
            } else if (cell.markdown.trim() === "") {
                throw new Error(`The notebook ${nbAddress.path} doesn't contain output to embed with the cell id, tag, or label '${id}'. Please be sure to have executed any cells that you are embedding.`);
            } else {
                return cell;
            }
        });
        return notebookMarkdown(nbAbsPath, theCells, notebookInfo.title);
    } else if (nbAddress.indexes) {
        const theCells = nbAddress.indexes.map((idx)=>{
            if (idx < 1 || idx > notebookInfo.outputs.length) {
                throw new Error(`The cell index ${idx} isn't within the range of cells`);
            } else {
                const cell = notebookInfo.outputs[idx - 1];
                if (cell.markdown.trim() === "") {
                    throw new Error(`The notebook ${nbAddress.path} doesn't contain output to embed for the cell in position ${idx}. Please be sure to have executed any cells that you are embedding.`);
                }
                return cell;
            }
        });
        return notebookMarkdown(nbAbsPath, theCells, notebookInfo.title);
    } else {
        const notebookMd = notebookMarkdown(nbAbsPath, notebookInfo.outputs, notebookInfo.title);
        if (notebookMd.trim() === "") {
            throw new Error(`The notebook ${nbAddress.path} doesn't contain output to embed. Please be sure to have executed any cells that you are embedding.`);
        } else {
            return notebookMd;
        }
    }
}
const isNotebook = (path)=>{
    return extname2(path) === ".ipynb";
};
const isEmbeddable = (path)=>{
    return isNotebook(path) || extname2(path) === ".qmd";
};
async function getCachedNotebookInfo(inputPath, nbAddress, assets, context, flags, options, outputs) {
    const lifetime = getNamedLifetime(kRenderFileLifetime);
    if (lifetime === undefined) {
        throw new InternalError(`named lifetime ${kRenderFileLifetime} not found`);
    }
    const nbCache = lifetime.get(kNotebookCache) || {
        cache: {},
        cleanup: ()=>{}
    };
    const cacheKey = notebookCacheKey(inputPath, nbAddress, assets, options, outputs);
    if (!nbCache.cache[cacheKey]) {
        const nbAbsPath = resolveNbPath(inputPath, nbAddress.path, context.project);
        const notebook = jupyterFromNotebookOrQmd(nbAbsPath, context.options.services, context.project);
        if (options) {
            notebook.cells = notebook.cells.map((cell)=>{
                if (options.echo !== undefined) {
                    cell.metadata[kEcho1] = options.echo;
                }
                if (options.warning !== undefined) {
                    cell.metadata[kWarning1] = options.warning;
                }
                if (options.asis !== undefined) {
                    cell.metadata[kOutput1] = options.asis ? true : false;
                }
                if (outputs && cell.outputs) {
                    cell.outputs = cell.outputs.map((output, index)=>{
                        const oneBasedIdx = index + 1;
                        output.metadata = output.metadata || {};
                        if (!outputs.includes(oneBasedIdx)) {
                            output.metadata[kQuartoOutputDisplay] = false;
                        } else {
                            const explicitOrder = outputs.indexOf(oneBasedIdx);
                            if (explicitOrder > -1) {
                                output.metadata[kQuartoOutputOrder] = explicitOrder;
                            }
                        }
                        return output;
                    });
                }
                return cell;
            });
        }
        if (options?.filter) {
            notebook.cells = notebook.cells.filter((cell)=>{
                if (options?.filter) {
                    return options?.filter(cell);
                } else {
                    return true;
                }
            });
        }
        const format = context.format;
        const executeOptions = {
            target: context.target,
            resourceDir: resourcePath(),
            tempDir: context.options.services.temp.createDir(),
            dependencies: true,
            libDir: context.libDir,
            format: context.format,
            projectDir: context.project?.dir,
            cwd: flags.executeDir || dirname2(normalizePath(context.target.source)),
            params: resolveParams(flags.params, flags.paramsFile),
            quiet: flags.quiet,
            previewServer: context.options.previewServer,
            handledLanguages: languages()
        };
        const [dir, stem] = dirAndStem(nbAddress.path);
        const outputPrefix = texSafeFilename(`${dir !== "." ? dir + "-" : ""}${stem}`);
        const result1 = await jupyterToMarkdown(notebook, {
            executeOptions,
            language: notebook.metadata.kernelspec.language.toLowerCase(),
            assets,
            execute: format.execute,
            keepHidden: format.render[kKeepHidden],
            preserveCellMetadata: options?.preserveCellMetadata,
            toHtml: isHtmlCompatible(format),
            toLatex: isLatexOutput(format.pandoc),
            toMarkdown: isMarkdownOutput(format),
            toIpynb: isIpynbOutput(format.pandoc),
            toPresentation: isPresentationOutput(format.pandoc),
            figFormat: format.execute[kFigFormat],
            figDpi: format.execute[kFigDpi],
            figPos: format.render[kFigPos],
            fixups: "minimal",
            outputPrefix
        });
        const title = findTitle(result1.cellOutputs);
        nbCache.cache[cacheKey] = {
            outputs: result1.cellOutputs,
            title
        };
        lifetime.attach(nbCache, kNotebookCache);
    }
    return nbCache.cache[cacheKey];
}
function findTitle(cells) {
    for (const cell of cells){
        const partitioned = partitionMarkdown(cell.markdown);
        if (partitioned.yaml?.title) {
            return partitioned.yaml.title;
        } else if (partitioned.headingText) {
            return partitioned.headingText;
        }
    }
    return undefined;
}
function notebookCacheKey(inputPath, nbAddress, assets, nbOptions, nbOutputs) {
    const optionsKey = nbOptions ? Object.keys(nbOptions).reduce((current, key)=>{
        if (nbOptions[key] !== undefined && typeof (nbOptions[key] === "boolean")) {
            return current + `${key}:${String(nbOptions[key])}`;
        } else {
            return current;
        }
    }, "") : "";
    const coreKey = optionsKey ? `${inputPath}-${nbAddress.path}-${optionsKey}` : `${inputPath}-${nbAddress.path}`;
    const outputsKey = nbOutputs ? nbOutputs.join(",") : "";
    return `${coreKey}:${outputsKey}:${assets.supporting_dir}`;
}
function optionsToPlaceholder(options) {
    return Object.keys(options).map((key)=>{
        return `${key}:${String(options[key])}`;
    }).join(",");
}
function placeholderToOptions(placeholder) {
    const parts = placeholder.split(",");
    const options = {};
    for (const part of parts){
        const kv = part.split(":");
        if (kv.length > 1) {
            const key = part.split(":")[0];
            const value = part.split(":").slice(1).join(":");
            options[key] = value.toLowerCase() === "true";
        } else {
            throw new Error("Unexpected placeholder for notebook option: " + part);
        }
    }
    return options;
}
function cellForId(id, cells) {
    for (const cell of cells){
        const hasId = cell.id ? id === cell.id : false;
        if (hasId) {
            return cell;
        }
        const hasLabel = cell.options && cell.options[kCellLabel] ? id === cell.options[kCellLabel] : false;
        if (hasLabel) {
            return cell;
        }
        const hasTag = cell.metadata && cell.metadata.tags ? cell.metadata.tags.find((tag)=>id === tag) !== undefined : false;
        if (hasTag) {
            return cell;
        }
        if (cell.markdown && cell.markdown.includes(id)) {
            if (cell.markdown.match(new RegExp(`.*{#${id}(\\s+[^}]*)*}$`, "gm"))) {
                return cell;
            }
        }
    }
}
function resolveCellIds(hash) {
    if (hash && hash.indexOf(",") > 0) {
        return hash.split(",");
    } else if (hash) {
        return [
            hash
        ];
    } else {
        return undefined;
    }
}
function resolveRange(rangeRaw) {
    if (rangeRaw) {
        const result1 = [];
        const ranges = rangeRaw.split(",");
        ranges.forEach((range)=>{
            if (range.indexOf("-") > -1) {
                const parts = range.split("-");
                const start = parseInt(parts[0]);
                const end = parseInt(parts[1]);
                const step = start > end ? -1 : 1;
                for(let i1 = start; step > 0 ? i1 <= end : i1 >= end; i1 = i1 + step){
                    result1.push(i1);
                }
            } else {
                result1.push(parseInt(range));
            }
        });
        return result1;
    } else {
        return undefined;
    }
}
function jupyterFromNotebookOrQmd(nbAbsPath, services, project) {
    let jupyterNotebookPath = nbAbsPath;
    if (!isNotebook(jupyterNotebookPath)) {
        const notebook = services.notebook.get(nbAbsPath, project);
        if (notebook?.[kQmdIPynb] && notebook[kQmdIPynb]) {
            jupyterNotebookPath = notebook[kQmdIPynb].path;
        } else {
            throw new InternalError(`Expected an 'ipynb' file to be present for the 'qmd' file ${nbAbsPath}`);
        }
    }
    return jupyterFromFile(jupyterNotebookPath);
}
const pandocIngestSelfContainedContent = async (file, resourcePath)=>{
    const filename = basename2(file);
    const workingDir = dirname2(file);
    const template = formatResourcePath("html", "pandoc-selfcontained/selfcontained.html");
    const contents = Deno.readTextFileSync(file);
    const input = [];
    input.push("````````{=html}");
    input.push(contents);
    input.push("````````");
    const cmd = [
        pandocBinaryPath()
    ];
    cmd.push("--to", "html");
    cmd.push("--from", "markdown");
    cmd.push("--template", template);
    cmd.push("--output", filename);
    cmd.push("--metadata", "title=placeholder");
    cmd.push("--embed-resources");
    if (resourcePath && resourcePath.length) {
        cmd.push("--resource-path", resourcePath.join(":"));
    }
    const result1 = await execProcess({
        cmd,
        stdout: "piped",
        cwd: workingDir
    }, input.join("\n"));
    if (result1.success) {
        return result1.stdout;
    } else {
        throw new Error();
    }
};
async function renderPandoc(file, quiet) {
    const { context, recipe, executeResult, resourceFiles } = file;
    const format = recipe.format;
    if (executeResult.includes) {
        format.pandoc = mergePandocIncludes(format.pandoc || {}, executeResult.includes);
    }
    if (executeResult.pandoc) {
        format.pandoc = mergeConfigs(format.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,
                output: recipe.output,
                resourceDir: resourcePath(),
                tempDir: context.options.services.temp.createDir(),
                projectDir: context.project?.dir,
                libDir: context.libDir,
                dependencies: executeResult.engineDependencies[engineName],
                quiet: context.options.flags?.quiet
            });
            format.pandoc = mergePandocIncludes(format.pandoc, dependenciesResult.includes);
        }
    }
    const mediabagDir = filesDirMediabagDir(context.target.source);
    ensureDirSync(join2(dirname2(context.target.source), mediabagDir));
    const notebookResult = await replaceNotebookPlaceholders(format.pandoc.to || "html", context, context.options.flags || {}, executeResult.markdown, context.options.services);
    const embedSupporting = [];
    if (notebookResult.supporting.length) {
        embedSupporting.push(...notebookResult.supporting);
    }
    const pandocIncludes = {
        [kIncludeAfterBody]: notebookResult.includes?.afterBody ? [
            notebookResult.includes?.afterBody
        ] : undefined,
        [kIncludeInHeader]: notebookResult.includes?.inHeader ? [
            notebookResult.includes?.inHeader
        ] : undefined
    };
    format.pandoc = mergePandocIncludes(format.pandoc, pandocIncludes);
    let markdownInput = notebookResult.markdown ? notebookResult.markdown : executeResult.markdown;
    if (format.render[kInlineIncludes]) {
        const collectIncludes = (location)=>{
            const includes = format.pandoc[location];
            if (includes) {
                const append = location === "include-after-body";
                for (const include of includes){
                    const includeMd = Deno.readTextFileSync(include);
                    if (append) {
                        markdownInput = `${markdownInput}\n\n${includeMd}`;
                    } else {
                        markdownInput = `${includeMd}\n\n${markdownInput}`;
                    }
                }
                delete format.pandoc[location];
            }
        };
        collectIncludes(kIncludeInHeader);
        collectIncludes(kIncludeBeforeBody);
        collectIncludes(kIncludeAfterBody);
    }
    const pandocOptions = {
        markdown: markdownInput,
        source: context.target.source,
        output: recipe.output,
        keepYaml: recipe.keepYaml,
        mediabagDir,
        libDir: context.libDir,
        format,
        executionEngine: executeResult.engine,
        project: context.project,
        args: recipe.args,
        services: context.options.services,
        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();
    }
    return {
        complete: async (renderedFormats, cleanup)=>{
            push("render-postprocessor");
            if (executeResult.postProcess) {
                await withTimingAsync("engine-postprocess", async ()=>{
                    return await context.engine.postprocess({
                        engine: context.engine,
                        target: context.target,
                        format,
                        output: recipe.output,
                        tempDir: context.options.services.temp.createDir(),
                        projectDir: context.project?.dir,
                        preserve: executeResult.preserve,
                        quiet: context.options.flags?.quiet
                    });
                });
            }
            const canHtmlPostProcess = isHtmlFileOutput(format.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(pandocResult.inputMetadata, pandocResult.inputTraits, pandocOptions, htmlPostProcessors, htmlFinalizers, renderedFormats, quiet);
            const outputFile = isAbsolute2(pandocOptions.output) ? pandocOptions.output : join2(dirname2(pandocOptions.source), pandocOptions.output);
            const postProcessSupporting = [];
            const postProcessResources = [];
            if (pandocResult.postprocessors) {
                for (const postprocessor of pandocResult.postprocessors){
                    const result1 = await postprocessor(outputFile);
                    if (result1 && result1.supporting) {
                        postProcessSupporting.push(...result1.supporting);
                    }
                    if (result1 && result1.resources) {
                        postProcessResources.push(...result1.resources);
                    }
                }
            }
            let finalOutput;
            let selfContained;
            await withTimingAsync("postprocess-selfcontained", async ()=>{
                const flags = context.options.flags || {};
                finalOutput = await recipe.complete(pandocOptions) || recipe.output;
                selfContained = isSelfContainedOutput(flags, format, finalOutput);
                if (selfContained && isHtmlFileOutput(format.pandoc)) {
                    await pandocIngestSelfContainedContent(outputFile, format.pandoc[kResourcePath]);
                }
            });
            let filesDir = inputFilesDir(context.target.source);
            filesDir = existsSync(join2(dirname2(context.target.source), filesDir)) ? filesDir : undefined;
            let supporting = filesDir ? executeResult.supporting : undefined;
            if (filesDir && isHtmlFileOutput(format.pandoc)) {
                const filesDirAbsolute = join2(dirname2(context.target.source), filesDir);
                if (existsSync(filesDirAbsolute) && (!supporting || !supporting.includes(filesDirAbsolute))) {
                    const filesLibs = join2(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);
            }
            if (embedSupporting && embedSupporting.length > 0) {
                supporting = supporting || [];
                supporting.push(...embedSupporting);
            }
            if (postProcessSupporting && postProcessSupporting.length > 0) {
                supporting = supporting || [];
                supporting.push(...postProcessSupporting);
            }
            let cleanupSelfContained = undefined;
            if (selfContained && supporting) {
                cleanupSelfContained = [
                    ...supporting
                ];
                if (context.project) {
                    const libDir = context.project?.config?.project["lib-dir"];
                    if (libDir) {
                        const absLibDir = join2(context.project.dir, libDir);
                        cleanupSelfContained = cleanupSelfContained.filter((file)=>!file.startsWith(absLibDir));
                    }
                }
            }
            if (cleanup !== false) {
                withTiming("render-cleanup", ()=>renderCleanup(context.target.input, finalOutput, format, cleanupSelfContained, executionEngineKeepMd(context)));
            }
            const projectPath = (path)=>{
                if (context.project) {
                    if (isAbsolute2(path)) {
                        return relative2(normalizePath(context.project.dir), normalizePath(path));
                    } else {
                        return relative2(normalizePath(context.project.dir), normalizePath(join2(dirname2(context.target.source), path)));
                    }
                } else {
                    return path;
                }
            };
            pop();
            const files = resourceFiles.concat(htmlPostProcessResult.resources).concat(postProcessResources);
            const result1 = {
                isTransient: recipe.isOutputTransient,
                input: projectPath(context.target.source),
                markdown: executeResult.markdown,
                format,
                supporting: supporting ? supporting.filter(existsSync1).map((file)=>context.project ? relative2(context.project.dir, file) : file) : undefined,
                file: recipe.isOutputTransient ? finalOutput : projectPath(finalOutput),
                resourceFiles: {
                    globs: pandocResult.resources,
                    files
                },
                selfContained: selfContained
            };
            return result1;
        }
    };
}
function renderResultFinalOutput(renderResults, relativeToInputDir) {
    let result1 = renderResults.files.find((file)=>{
        return !file.supplemental;
    });
    if (!result1) {
        return undefined;
    }
    for (const fileResult of renderResults.files){
        if (fileResult.file === "index.html" && !fileResult.supplemental) {
            result1 = fileResult;
            break;
        }
    }
    if (renderResults.context) {
        const projType = projectType(renderResults.context.config?.project.type);
        if (projType && projType.renderResultFinalOutput) {
            const projectResult = projType.renderResultFinalOutput(renderResults, relativeToInputDir);
            if (projectResult) {
                result1 = projectResult;
            }
        }
    }
    let finalInput = result1.input;
    let finalOutput = result1.file;
    if (renderResults.baseDir) {
        finalInput = join2(renderResults.baseDir, finalInput);
        if (renderResults.outputDir) {
            finalOutput = join2(renderResults.baseDir, renderResults.outputDir, finalOutput);
        } else {
            finalOutput = join2(renderResults.baseDir, finalOutput);
        }
    } else {
        finalOutput = join2(dirname2(finalInput), finalOutput);
    }
    if (!safeExistsSync(finalOutput)) {
        return undefined;
    }
    if (relativeToInputDir) {
        const inputRealPath = normalizePath(relativeToInputDir);
        const outputRealPath = normalizePath(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(join2(renderResult.baseDir, renderResult.outputDir), finalOutput));
            return targetPath;
        }
    }
    return undefined;
}
function mergePandocIncludes(format, pandocIncludes) {
    return mergeConfigs(format, pandocIncludes);
}
async function runHtmlPostprocessors(inputMetadata, inputTraits, options, htmlPostprocessors, htmlFinalizers, renderedFormats, quiet) {
    const postProcessResult = {
        resources: [],
        supporting: []
    };
    if (htmlPostprocessors.length > 0 || htmlFinalizers.length > 0) {
        await withTimingAsync("htmlPostprocessors", async ()=>{
            const outputFile = isAbsolute2(options.output) ? options.output : join2(dirname2(options.source), options.output);
            const htmlInput = Deno.readTextFileSync(outputFile);
            const doctypeMatch = htmlInput.match(/^<!DOCTYPE.*?>/);
            const doc = await parseHtml(htmlInput);
            for(let i1 = 0; i1 < htmlPostprocessors.length; i1++){
                const postprocessor = htmlPostprocessors[i1];
                const result1 = await postprocessor(doc, {
                    inputMetadata,
                    inputTraits,
                    renderedFormats,
                    quiet
                });
                postProcessResult.resources.push(...result1.resources);
                postProcessResult.supporting.push(...result1.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 cacheMap(f) {
    const map = new Map();
    return async (key)=>{
        if (!map.has(key)) {
            map.set(key, await f(key));
        }
        return map.get(key);
    };
}
const translationCache = cacheMap(async (file)=>{
    if (existsSync(file)) {
        const errMsg = "Validation of format language object failed.";
        const formatLanguageSchema = getSchemaDefinition("format-language");
        const result1 = await readAndValidateYamlFromFile(file, formatLanguageSchema, errMsg);
        return {
            file: normalizePath(file),
            language: result1
        };
    } else {
        return {
            language: {}
        };
    }
});
function escapeRegExp1(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
async function readLanguageTranslations(translationFile, lang) {
    const files = [];
    const { file, language } = await translationCache(translationFile);
    if (file) {
        files.push(file);
    }
    const ext = extname2(translationFile);
    let [dir, stem] = dirAndStem(translationFile);
    stem = escapeRegExp1(stem);
    const variations = [];
    if (lang) {
        const subtags = lang.split("-");
        for(let i1 = 0; i1 < subtags.length; i1++){
            variations.push(subtags.slice(0, i1 + 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 { file: variationFile, language: translations } = await translationCache(join2(dir, stem + "-" + variation + ext));
        if (variationFile) {
            files.push(variationFile);
        }
        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(join2("language", "_language.yml")), lang);
}
async function resolveLanguageMetadata(metadata, dir) {
    if (typeof metadata[kLanguageDefaults] === "string") {
        const translationsFile = join2(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 i1 = 0; i1 < subtags.length; i1++){
        const variation = subtags.slice(0, i1 + 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 buildConfluenceFiles = ()=>{
    const file = [
        {
            name: "index",
            content: `This project provides provides a simple scaffold for creating a Quarto Confluence Project. You'll almost certainly want to remove the sample files, they are just here as examples. When you add you own documents (including ones in subfolders) they will be automatically added to the site navigation sidebar.`,
            title: "Example"
        },
        {
            name: "project-roadmap",
            content: `## Overview

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla id accumsan justo. Nulla ut lectus efficitur, aliquet tellus elementum, hendrerit mi. Aenean risus purus, finibus eu consectetur sit amet, maximus ut tortor. Vivamus congue mollis ante in interdum. In at semper turpis, sed faucibus arcu. Nullam ultrices, neque nec mattis dictum, risus ante mattis diam, sit amet sagittis arcu ante ut urna.

Quisque cursus eros dictum justo varius condimentum a ac risus. Vestibulum sodales, quam quis dignissim scelerisque, tellus turpis mollis sapien, tempor lacinia quam elit at urna. Etiam pharetra sapien at tristique tincidunt. Duis vitae lectus nisl. Proin pharetra, ante a iaculis interdum, lectus massa tempor leo, eu luctus lorem sapien vel sem. Morbi vitae tincidunt libero, eget tincidunt quam.

## Key Milestones

Donec elementum a neque a rutrum. Nulla a quam in eros ornare fringilla at eget mi. Sed dui dolor, porta mollis auctor in, finibus vel tellus. Nunc quis ipsum sit amet magna vulputate tincidunt. Vivamus eget ornare dolor, eget rhoncus purus.

Praesent ac mauris quis magna placerat hendrerit. Fusce viverra nulla nec urna pulvinar semper.

Nunc sit amet libero ut ligula venenatis volutpat. Integer scelerisque iaculis lacus, et ornare velit placerat nec.

Phasellus nisi ante, dignissim quis metus nec, consequat bibendum lacus.`,
            title: "Project Roadmap"
        },
        {
            name: "2022-01",
            subdirectory: "reports",
            title: "January 2022",
            content: "## Project Status\n" + "Fusce tristique, elit vel tincidunt vehicula, est tortor laoreet sem, nec sagittis ipsum nisl eget ipsum. Ut fringilla facilisis tincidunt:\n" + "\n" + "1. Cras fermentum sagittis tincidunt. Vestibulum nunc nisi, consequat sed nunc vitae, mollis sodales urna.\n" + "2. Curabitur venenatis, sem sed sodales fermentum, ante mauris posuere nisl, eu pretium velit magna a ex. Duis malesuada vitae nisl sit amet aliquam.\n" + "3. Nullam scelerisque condimentum leo in convallis. Phasellus eu mauris enim.\n" + "\n" + "Sed volutpat orci eu ligula gravida, et congue lacus efficitur. Vivamus eget mi nisl. Nam tristique eros nec elit commodo, at vehicula purus venenatis. Donec imperdiet interdum erat at dignissim. Nullam odio ante, pellentesque id commodo et, sodales eget diam.\n" + "\n" + "## Challenges and Opportunities\n" + "In scelerisque non dolor at congue. Donec neque lorem, consectetur sed consectetur ut, pulvinar sit amet justo. Donec at mi erat. Maecenas luctus sem orci, eu ullamcorper arcu porta sed. Nam dapibus risus ligula, non tempor leo convallis vel. Mauris pretium, arcu ut bibendum egestas, nisi tellus cursus tortor, vel interdum turpis ipsum in nisi.\n" + "\n" + "Aliquam ac egestas mi. Nulla ut porttitor justo. Proin id fermentum nunc:\n" + "\n" + "1. In odio justo, scelerisque at augue at, blandit rhoncus nibh.\n" + "2. Mauris ut tristique elit. Suspendisse pretium tempor mauris non luctus.\n" + "3. Mauris posuere nulla purus, quis dapibus urna suscipit ac.\n" + "\n" + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam at risus blandit, aliquet leo sed, pretium lectus. Vivamus in tortor in velit consequat sodales. Integer eleifend dictum vestibulum. Nullam ac augue ultrices, consectetur velit pretium, tincidunt elit. Aliquam mollis nulla erat, vitae scelerisque ante ultrices eu. Fusce maximus libero eget viverra ornare. Proin eu augue placerat, sodales nibh et, laoreet ex."
        },
        {
            name: "2022-03",
            subdirectory: "reports",
            title: "March 2023",
            content: "## Project Status\n" + "Sed at auctor lacus, ut porta tellus. Curabitur luctus sem nec ipsum elementum, non congue erat ultrices. Vivamus fringilla nulla lacus, sit amet tincidunt quam cursus vel. Nunc ligula lacus, sollicitudin vitae imperdiet vel, aliquet nec elit.\n" + "\n" + "Quisque non magna sodales, pellentesque neque quis, varius orci. Aliquam pharetra velit accumsan libero mattis, vitae aliquet justo facilisis. Fusce feugiat tincidunt ante vel lacinia. Curabitur imperdiet cursus iaculis. Nulla posuere neque ac sem euismod pharetra. Morbi massa augue, consectetur sed luctus sagittis, sagittis ac sapien. Sed tempor nisl urna, a sollicitudin tellus rutrum a.\n" + "\n" + "Challenges and Opportunities\n" + "Aenean imperdiet tellus non neque placerat pellentesque. Morbi ac pulvinar arcu. In eget eleifend justo. Pellentesque porttitor consectetur consectetur:\n" + "\n" + "1. Sed et velit erat.\n" + "2. Nunc ullamcorper hendrerit convallis.\n" + "3. Curabitur sagittis ex purus.\n" + "4. Nulla porta sem sem, vel rutrum tortor.\n" + "\n" + "Fusce semper est sit amet finibus dictum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Praesent vehicula, augue eu posuere imperdiet, magna ipsum tristique nisl, ut mollis ipsum ligula sed orci. Sed vitae auctor urna. Fusce pellentesque odio vel enim posuere, sollicitudin viverra quam dictum. Ut eget laoreet eros. Integer vitae imperdiet velit, a cursus lorem.\n" + "\n" + "Phasellus varius, libero et viverra eleifend, sem orci condimentum turpis, in condimentum sapien est vitae urna. Sed auctor condimentum tortor in egestas. Pellentesque turpis urna, commodo ut ipsum nec, fermentum venenatis risus. Quisque at dictum tortor. Curabitur gravida suscipit nisl, rutrum sagittis mauris ultricies sed.\n" + "\n" + "Phasellus commodo id nisl sit amet dignissim. Mauris facilisis nunc ut nibh faucibus sagittis. Integer at molestie odio, nec fermentum lectus. Donec quis purus id nisi viverra dapibus vitae eget turpis. Maecenas ut lorem malesuada nunc commodo vulputate. Nunc vulputate quam sapien, eget finibus nunc lobortis vitae. Ut gravida hendrerit lorem vitae consectetur. Quisque eget massa risus. Maecenas fringilla augue congue, lobortis neque sed, consectetur neque. Vivamus auctor nisl et placerat feugiat."
        }
    ];
    return file;
};
const kDefaultProjectFileContents = "{ project: { type: 'default' } }";
const kConfluence = "confluence";
const defaultProjectType = {
    type: "default",
    templates: [
        kConfluence
    ],
    formatLibDirs: ()=>[
            "bootstrap",
            "quarto-html",
            "quarto-ojs",
            "quarto-diagram",
            "quarto-contrib"
        ],
    create: (title, template)=>{
        let resourceDirectory = "default";
        if (template === kConfluence) {
            resourceDirectory = "confluence";
        }
        const resourceDir = resourcePath(join2("projects", resourceDirectory));
        return {
            configTemplate: join2(resourceDir, "templates", "_quarto.ejs.yml"),
            resourceDir,
            scaffold: (engine, kernel, packages)=>{
                if (template === kConfluence) {
                    return buildConfluenceFiles();
                }
                const file = [
                    {
                        name: title,
                        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
                    }
                ];
                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 MIN_BUF_SIZE = 16;
const CR = "\r".charCodeAt(0);
const LF1 = "\n".charCodeAt(0);
class BufferFullError extends Error {
    partial;
    name;
    constructor(partial){
        super("Buffer full");
        this.partial = partial;
        this.name = "BufferFullError";
    }
}
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 i1 = 100; i1 > 0; i1--){
            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);
                }
                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(LF1);
        } catch (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] === LF1) {
            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 slice;
        while(true){
            let i1 = this.#buf.subarray(this.#r + s, this.#w).indexOf(delim);
            if (i1 >= 0) {
                i1 += s;
                slice = this.#buf.subarray(this.#r, this.#r + i1 + 1);
                this.#r += i1 + 1;
                break;
            }
            if (this.#eof) {
                if (this.#r === this.#w) {
                    return null;
                }
                slice = 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 = slice;
                }
                throw err;
            }
        }
        return slice;
    }
    async peek(n) {
        if (n < 0) {
            throw Error("negative count");
        }
        let avail = this.#w - this.#r;
        while(avail < n && 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);
                }
                throw err;
            }
            avail = this.#w - this.#r;
        }
        if (avail === 0 && this.#eof) {
            return null;
        } else if (avail < n && this.#eof) {
            return this.#buf.subarray(this.#r, this.#r + avail);
        } else if (avail < n) {
            throw new BufferFullError(this.#buf.subarray(this.#r, this.#w));
        }
        return this.#buf.subarray(this.#r, this.#r + n);
    }
}
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 = [];
        }
    }
}
function pdfFormat() {
    return mergeConfigs(createPdfFormat("PDF"), {
        extensions: {
            book: pdfBookExtension
        }
    });
}
function beamerFormat() {
    return createFormat("Beamer", "pdf", createPdfFormat("Beamer", false, false), {
        execute: {
            [kFigWidth]: 10,
            [kFigHeight]: 7,
            [kEcho]: false,
            [kWarning]: false
        },
        classoption: [
            "notheorems"
        ]
    });
}
function latexFormat(displayName) {
    return createFormat(displayName, "tex", mergeConfigs(createPdfFormat(displayName), {
        extensions: {
            book: {
                onSingleFilePreRender: (format, _config)=>{
                    format.render[kKeepTex] = true;
                    return format;
                },
                formatOutputDirectory: ()=>{
                    return "book-latex";
                }
            }
        }
    }));
}
function createPdfFormat(displayName, autoShiftHeadings = true, koma = true) {
    return createFormat(displayName, "pdf", {
        execute: {
            [kFigWidth]: 5.5,
            [kFigHeight]: 3.5,
            [kFigFormat]: "pdf",
            [kFigDpi]: 300
        },
        pandoc: {
            [kPdfEngine]: "xelatex",
            standalone: true,
            variables: {
                graphics: true,
                tables: true
            },
            [kDefaultImageExtension]: "pdf"
        },
        metadata: {
            ["block-headings"]: true
        },
        formatExtras: (_input, markdown, flags, format, _libDir, services)=>{
            const extras = {};
            const engine = pdfEngine(format.pandoc, format.render, flags);
            if (!isLatexPdfEngine(engine)) {
                return extras;
            }
            extras.postprocessors = [
                pdfLatexPostProcessor(flags, format, services.temp)
            ];
            const documentclass = format.metadata[kDocumentClass];
            const usingCustomTemplates = format.pandoc.template !== undefined || format.metadata[kTemplatePartials] !== undefined;
            if (usingCustomTemplates || documentclass && ![
                "srcbook",
                "scrreprt",
                "scrreport",
                "scrartcl",
                "scrarticle"
            ].includes(documentclass)) {
                koma = false;
            }
            if (koma) {
                const captionOptions = [];
                const tblCaploc = tblCapLocation(format);
                captionOptions.push(tblCaploc === kCapTop ? "tableheading" : "tablesignature");
                if (figCapLocation(format) === kCapTop) {
                    captionOptions.push("figureheading");
                }
                const defaultClassOptions = [
                    "DIV=11"
                ];
                if (format.metadata[kLang] !== "de") {
                    defaultClassOptions.push("numbers=noendperiod");
                }
                const userClassOptions = format.metadata[kClassOption];
                const classOptions = defaultClassOptions.filter((option)=>{
                    if (Array.isArray(userClassOptions)) {
                        const name = option.split("=")[0];
                        return !userClassOptions.some((userOption)=>String(userOption).startsWith(name + "="));
                    } else {
                        return true;
                    }
                });
                const headerIncludes = [];
                headerIncludes.push("\\KOMAoption{captions}{" + captionOptions.join(",") + "}");
                extras.metadata = {
                    [kDocumentClass]: "scrartcl",
                    [kClassOption]: classOptions,
                    [kPaperSize]: "letter",
                    [kHeaderIncludes]: headerIncludes
                };
            }
            const partialNames = [
                "before-bib",
                "biblio",
                "citations",
                "doc-class",
                "graphics",
                "after-body",
                "before-body",
                "pandoc",
                "tables",
                "tightlist",
                "before-title",
                "title",
                "toc"
            ];
            extras.templateContext = {
                template: formatResourcePath("pdf", "pandoc/template.tex"),
                partials: partialNames.map((name)=>{
                    return formatResourcePath("pdf", `pandoc/${name}.tex`);
                })
            };
            const hasLevelOneHeadings = !!markdown.match(/\n^#\s.*$/gm);
            if (!hasLevelOneHeadings && autoShiftHeadings && (flags?.[kNumberSections] === true || format.pandoc[kNumberSections] === true) && flags?.[kTopLevelDivision] === undefined && format.pandoc?.[kTopLevelDivision] === undefined && flags?.[kShiftHeadingLevelBy] === undefined && format.pandoc?.[kShiftHeadingLevelBy] === undefined) {
                extras.pandoc = {
                    [kShiftHeadingLevelBy]: -1
                };
            }
            extras.pandoc = extras.pandoc || {};
            if (documentclass === "scrbook" && format.pandoc[kNumberSections] !== false && flags[kNumberSections] !== false) {
                extras.pandoc[kNumberSections] = true;
            }
            return extras;
        }
    });
}
const pdfBookExtension = {
    selfContainedOutput: true,
    onSingleFilePostRender: (project, renderedFile)=>{
        if (renderedFile.format.render[kKeepTex]) {
            const finalOutputFile = renderedFile.file;
            const texOutputFile = texSafeFilename(basename2(finalOutputFile, extname2(finalOutputFile))) + ".tex";
            Deno.renameSync(join2(project.dir, "index.tex"), join2(project.dir, texOutputFile));
        }
    }
};
function pdfLatexPostProcessor(flags, format, temp) {
    return async (output)=>{
        const lineProcessors = [
            sidecaptionLineProcessor(),
            calloutFloatHoldLineProcessor(),
            tableColumnMarginLineProcessor(),
            guidsProcessor()
        ];
        if (format.pandoc[kCiteMethod] === "biblatex") {
            lineProcessors.push(bibLatexBibligraphyRefsDivProcessor());
        } else if (format.pandoc[kCiteMethod] === "natbib") {
            lineProcessors.push(natbibBibligraphyRefsDivProcessor(format.metadata[kBibliography]));
        }
        const marginCites = format.metadata[kCitationLocation] === "margin";
        const renderedCites = {};
        if (marginCites) {
            if (format.pandoc[kCiteMethod] === "biblatex") {
                lineProcessors.push(suppressBibLatexBibliographyLineProcessor());
                lineProcessors.push(bibLatexCiteLineProcessor());
            } else if (format.pandoc[kCiteMethod] === "natbib") {
                lineProcessors.push(suppressNatbibBibliographyLineProcessor());
                lineProcessors.push(natbibCiteLineProcessor());
            } else {
                lineProcessors.push(indexAndSuppressPandocBibliography(renderedCites), cleanReferencesChapter());
            }
        }
        if (tblCapLocation(format) === kCapBottom) {
            lineProcessors.push(longtableBottomCaptionProcessor());
        }
        if (marginRefs(flags, format)) {
            lineProcessors.push(sideNoteLineProcessor());
        }
        lineProcessors.push(captionFootnoteLineProcessor());
        if (format.metadata[kCodeAnnotations] !== false && format.metadata[kCodeAnnotations] !== "none") {
            lineProcessors.push(codeAnnotationPostProcessor());
            lineProcessors.push(codeListAnnotationPostProcessor());
        }
        lineProcessors.push(tableSidenoteProcessor());
        await processLines(output, lineProcessors, temp);
        const pass2Processors = [
            longTableSidenoteProcessor()
        ];
        if (Object.keys(renderedCites).length > 0) {
            pass2Processors.push(placePandocBibliographyEntries(renderedCites));
        }
        await processLines(output, pass2Processors, temp);
    };
}
function tblCapLocation(format) {
    return format.metadata[kTblCapLoc] || format.metadata[kCapLoc] || kCapTop;
}
function figCapLocation(format) {
    return format.metadata[kFigCapLoc] || format.metadata[kCapLoc] || kCapBottom;
}
function marginRefs(flags, format) {
    return format.pandoc[kReferenceLocation] === "margin" || flags[kReferenceLocation] === "margin";
}
async function processLines(inputFile, lineProcessors, temp) {
    const outputFile = temp.createFile({
        suffix: ".tex"
    });
    const file = await Deno.open(inputFile);
    let mode;
    if (Deno.build.os !== "windows") {
        const stat = Deno.statSync(inputFile);
        if (stat.mode !== null) {
            mode = stat.mode;
        }
    }
    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,
                    mode
                });
            }
        }
    } finally{
        file.close();
        copyTo(outputFile, inputFile);
    }
}
const kBeginScanRegex = /^%quartopost-sidecaption-206BE349/;
const kEndScanRegex = /^%\/quartopost-sidecaption-206BE349/;
const sidecaptionLineProcessor = ()=>{
    let state = "scanning";
    return (line)=>{
        switch(state){
            case "scanning":
                if (line.match(kBeginScanRegex)) {
                    state = "replacing";
                    return kbeginLongTablesideCap;
                } else {
                    return line;
                }
            case "replacing":
                if (line.match(kEndScanRegex)) {
                    state = "scanning";
                    return kEndLongTableSideCap;
                } else {
                    return line;
                }
        }
    };
};
const readBalancedCommand = (latex)=>{
    let braceCount = 0;
    let entered = false;
    const chars = [];
    for(let i1 = 0; i1 < latex.length; i1++){
        const __char = latex.charAt(i1);
        if (__char === "{") {
            braceCount++;
            entered = true;
        } else if (__char === "}") {
            braceCount--;
        }
        chars.push(__char);
        if (entered && braceCount === 0) {
            break;
        }
    }
    return chars.join("");
};
const processElementCaptionFootnotes = (latexFigure)=>{
    const footnoteMark = "\\footnote{";
    const captionMark = "\\caption{";
    const contents = [];
    const captionIndex = latexFigure.indexOf(captionMark);
    if (captionIndex > -1) {
        contents.push(latexFigure.substring(0, captionIndex));
        const captionStartStr = latexFigure.slice(captionIndex);
        const captionLatex = readBalancedCommand(captionStartStr);
        const figureSuffix = captionStartStr.slice(captionLatex.length);
        let captionContents = captionLatex.slice(captionMark.length, captionLatex.length - 1);
        let footNoteIndex = captionContents.indexOf(footnoteMark);
        if (footNoteIndex > -1) {
            const captionText = [];
            const captionWithNote = [];
            const footNotes = [];
            while(footNoteIndex > -1){
                const prefix = captionContents.substring(0, footNoteIndex);
                captionContents = captionContents.slice(footNoteIndex);
                captionText.push(prefix);
                captionWithNote.push(prefix);
                const footnoteLatex = readBalancedCommand(captionContents);
                captionContents = captionContents.slice(footnoteLatex.length);
                footNoteIndex = captionContents.indexOf(footnoteMark);
                captionWithNote.push("\\footnotemark{}");
                footNotes.push(footnoteLatex.slice(footnoteMark.length, footnoteLatex.length - 1));
            }
            captionText.push(captionContents);
            captionWithNote.push(captionContents);
            contents.push(`\\caption[${captionText.join("")}]{${captionWithNote.join("")}}`);
            contents.push(figureSuffix);
            contents.push("\n");
            if (footNotes.length > 1) {
                contents.push(`\\addtocounter{footnote}{-${footNotes.length - 1}}`);
            }
            for(let i1 = 0; i1 < footNotes.length; i1++){
                contents.push(`\\footnotetext{${footNotes[i1]}}`);
                if (footNotes.length > 1 && i1 < footNotes.length - 1) {
                    contents.push(`\\addtocounter{footnote}{1}`);
                }
            }
            return contents.join("");
        } else {
            return latexFigure;
        }
    } else {
        return latexFigure;
    }
};
const kMatchLongTableSize = /^(.*)p{\(\\columnwidth - (\d+\\tabcolsep\).*$)/;
const kStartLongTable = /^\\begin{longtable}/;
const kEndLongTable = /^\\end{longtable}/;
const guidsProcessor = ()=>{
    let state = "looking-for-definition-start";
    const guidDefinitions = [];
    let guidBeingProcessed;
    let guidContents = [];
    return (line)=>{
        switch(state){
            case "looking-for-definition-start":
                {
                    if (line.startsWith("%quarto-define-uuid: ")) {
                        state = "looking-for-definition-end";
                        line = line.replace(/^%quarto-define-uuid:\s*/, "");
                        guidBeingProcessed = line.trim();
                        return undefined;
                    }
                    for (const [key, value] of guidDefinitions){
                        line = line.replaceAll(key, value);
                    }
                    return line;
                }
            case "looking-for-definition-end":
                {
                    if (line === "%quarto-end-define-uuid") {
                        state = "looking-for-definition-start";
                        if (guidBeingProcessed === undefined) {
                            throw new Error("guidBeingProcessed is undefined");
                        }
                        guidDefinitions.push([
                            guidBeingProcessed,
                            guidContents.join("").trim()
                        ]);
                        guidContents = [];
                        guidBeingProcessed = undefined;
                        return undefined;
                    } else {
                        guidContents.push(line);
                        return undefined;
                    }
                }
        }
    };
};
const tableColumnMarginLineProcessor = ()=>{
    let state = "looking-for-boundaries";
    return (line)=>{
        switch(state){
            case "looking-for-boundaries":
                {
                    if (line === "% quarto-tables-in-margin-AB1927C9:begin") {
                        state = "looking-for-tables";
                        return undefined;
                    }
                    return line;
                }
            case "looking-for-tables":
                {
                    if (line.match(kStartLongTable)) {
                        state = "processing";
                        return line;
                    } else if (line === "% quarto-tables-in-margin-AB1927C9:end") {
                        state = "looking-for-boundaries";
                        return undefined;
                    }
                    return line;
                }
            case "processing":
                {
                    if (line.match(kEndLongTable)) {
                        state = "looking-for-tables";
                        return line;
                    } else {
                        const match = line.match(kMatchLongTableSize);
                        if (match) {
                            return `${match[1]}p{(\\marginparwidth + \\marginparsep + \\columnwidth - ${match[2]}`;
                        } else {
                            return line;
                        }
                    }
                }
            default:
                {
                    return line;
                }
        }
    };
};
const captionFootnoteLineProcessor = ()=>{
    let state = "scanning";
    let capturedLines = [];
    return (line)=>{
        switch(state){
            case "scanning":
                if (line.match(/^\\begin{figure}.*$/)) {
                    state = "capturing";
                    capturedLines = [
                        line
                    ];
                    return undefined;
                } else {
                    return line;
                }
            case "capturing":
                capturedLines.push(line);
                if (line.match(/^\\end{figure}%*$/)) {
                    state = "scanning";
                    const lines = capturedLines.join("\n");
                    capturedLines = [];
                    return processElementCaptionFootnotes(lines);
                } else {
                    return undefined;
                }
        }
    };
};
const processSideNotes = (endMarker)=>{
    return (latexLongTable)=>{
        const sideNoteMarker = "\\sidenote{\\footnotesize ";
        let strProcessing = latexLongTable;
        const strOutput = [];
        const sidenotes = [];
        let sidenotePos = strProcessing.indexOf(sideNoteMarker);
        while(sidenotePos > -1){
            strOutput.push(strProcessing.substring(0, sidenotePos));
            const remainingStr = strProcessing.substring(sidenotePos + sideNoteMarker.length);
            let escaped = false;
            let sideNoteEnd = -1;
            for(let i1 = 0; i1 < remainingStr.length; i1++){
                const ch = remainingStr[i1];
                if (ch === "\\") {
                    escaped = true;
                } else {
                    if (!escaped && ch === "}") {
                        sideNoteEnd = i1;
                        break;
                    } else {
                        escaped = false;
                    }
                }
            }
            if (sideNoteEnd > -1) {
                strOutput.push("\\sidenotemark{}");
                const contents = remainingStr.substring(0, sideNoteEnd);
                sidenotes.push(contents);
                strProcessing = remainingStr.substring(sideNoteEnd + 1);
                sidenotePos = strProcessing.indexOf(sideNoteMarker);
            } else {
                strOutput.push(remainingStr);
            }
        }
        const endTable = endMarker;
        const endPos = strProcessing.indexOf(endTable);
        const prefix = strProcessing.substring(0, endPos + endTable.length);
        const suffix = strProcessing.substring(endPos + endTable.length, strProcessing.length);
        strOutput.push(prefix);
        for (const note of sidenotes){
            strOutput.push(`\\sidenotetext{${note}}\n`);
        }
        if (suffix) {
            strOutput.push(suffix);
        }
        return strOutput.join("");
    };
};
const processLongTableSidenotes = processSideNotes("\\end{longtable}");
const processTableSidenotes = processSideNotes("\\end{table}");
const sideNoteProcessor = (beginRegex, endRegex, callback)=>{
    return ()=>{
        let state = "scanning";
        let capturedLines = [];
        return (line)=>{
            switch(state){
                case "scanning":
                    if (line.match(beginRegex)) {
                        state = "capturing";
                        capturedLines = [
                            line
                        ];
                        return undefined;
                    } else {
                        return line;
                    }
                case "capturing":
                    capturedLines.push(line);
                    if (line.match(endRegex)) {
                        state = "scanning";
                        const lines = capturedLines.join("\n");
                        capturedLines = [];
                        return callback(lines);
                    } else {
                        return undefined;
                    }
            }
        };
    };
};
const longTableSidenoteProcessor = sideNoteProcessor(/^\\begin{longtable}.*$/, /^\\end{longtable}%*$/, processLongTableSidenotes);
const tableSidenoteProcessor = sideNoteProcessor(/^\\begin{table}.*$/, /^\\end{table}%*$/, processTableSidenotes);
const calloutFloatHoldLineProcessor = ()=>{
    let state = "scanning";
    return (line)=>{
        switch(state){
            case "scanning":
                if (line.match(/^\\begin{tcolorbox}/)) {
                    state = "replacing";
                    return line;
                } else {
                    return line;
                }
            case "replacing":
                if (line.match(/^\\end{tcolorbox}/)) {
                    state = "scanning";
                    return line;
                } else if (line.match(/^\\begin{figure}$/)) {
                    return "\\begin{figure}[H]";
                } else if (line.match(/^\\begin{codelisting}$/)) {
                    return "\\begin{codelisting}[H]";
                } else {
                    return line;
                }
        }
    };
};
const kQuartoBibPlaceholderRegex = "%bib-loc-124C8010";
const bibLatexBibligraphyRefsDivProcessor = ()=>{
    let hasRefsDiv = false;
    return (line)=>{
        if (line === kQuartoBibPlaceholderRegex) {
            if (!hasRefsDiv) {
                hasRefsDiv = true;
                return "\\printbibliography[heading=none]";
            } else {
                return undefined;
            }
        } else if (hasRefsDiv && line.match(/^\\printbibliography$/)) {
            return undefined;
        } else {
            return line;
        }
    };
};
const natbibBibligraphyRefsDivProcessor = (bibs)=>{
    let hasRefsDiv = false;
    return (line)=>{
        if (line === kQuartoBibPlaceholderRegex) {
            if (bibs && !hasRefsDiv) {
                hasRefsDiv = true;
                return `\\renewcommand{\\bibsection}{}\n\\bibliography{${bibs.join(",")}}`;
            } else {
                return undefined;
            }
        } else if (hasRefsDiv && line.match(/^\s*\\bibliography{.*}$/)) {
            return undefined;
        } 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 capturing = false;
    let caption;
    return (line)=>{
        const isEndOfDocument = !!line.match(/^\\end{document}/);
        if (isEndOfDocument && caption) {
            return `${caption}\n${line}`;
        } else if (scanning) {
            if (capturing) {
                caption = `${caption}\n${line}`;
                capturing = !line.match(/\\tabularnewline$/);
                return undefined;
            } else {
                if (line.match(/^\\caption.*?\\tabularnewline$/) || line.match(/^\\caption{.*}\\\\$/)) {
                    caption = line;
                    return undefined;
                } else if (line.match(/^\\caption.*?/)) {
                    caption = line;
                    capturing = true;
                    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 kChapterRefNameRegex = /^\\chapter\*?{(.*?)}\\label{references.*?}$/;
const cleanReferencesChapter = ()=>{
    let refChapterName;
    let refChapterContentsRegex;
    let refChapterMarkRegex;
    return (line)=>{
        const chapterRefMatch = line.match(kChapterRefNameRegex);
        if (chapterRefMatch) {
            refChapterName = chapterRefMatch[1];
            refChapterContentsRegex = new RegExp(`\\\\addcontentsline{toc}{chapter}{${refChapterName}}`);
            refChapterMarkRegex = new RegExp(`\\\\markboth{${refChapterName}}{${refChapterName}}`);
            return undefined;
        } else if (refChapterContentsRegex && line.match(refChapterContentsRegex)) {
            return undefined;
        } else if (refChapterMarkRegex && line.match(refChapterMarkRegex)) {
            return undefined;
        }
        return line;
    };
};
const indexAndSuppressPandocBibliography = (renderedCites)=>{
    let readingBibliography = false;
    let currentCiteKey = undefined;
    return (line)=>{
        if (!readingBibliography && line.match(/^\\phantomsection\\label{refs}$/)) {
            readingBibliography = true;
            return undefined;
        } else if (readingBibliography && line.match(/^\\end{CSLReferences}$/)) {
            readingBibliography = false;
            return undefined;
        } else if (readingBibliography) {
            const matches = line.match(/\\bibitem\[\\citeproctext\]{ref\-(.*?)}/);
            if (matches && matches[1]) {
                currentCiteKey = matches[1];
                renderedCites[currentCiteKey] = [
                    line
                ];
            } else if (line.length === 0) {
                currentCiteKey = undefined;
            } else if (currentCiteKey) {
                renderedCites[currentCiteKey].push(line);
            }
        }
        if (readingBibliography) {
            return undefined;
        } else {
            return line;
        }
    };
};
const kInSideCaptionRegex = /^\\sidecaption{/;
const kBeginFigureRegex = /^\\begin{figure}\[.*?\]$/;
const kEndFigureRegex = /^\\end{figure}\%?$/;
const placePandocBibliographyEntries = (renderedCites)=>{
    let biblioEntryState = "scanning";
    let pendingCiteKeys = [];
    return (line)=>{
        switch(biblioEntryState){
            case "scanning":
                {
                    if (line.match(kBeginFigureRegex)) {
                        biblioEntryState = "in-figure";
                    }
                    break;
                }
            case "in-figure":
                {
                    if (line.match(kInSideCaptionRegex)) {
                        biblioEntryState = "in-sidecaption";
                    } else {
                        if (line.match(kEndFigureRegex)) {
                            biblioEntryState = "scanning";
                        }
                    }
                    break;
                }
            case "in-sidecaption":
                {
                    if (line.match(kEndFigureRegex)) {
                        biblioEntryState = "scanning";
                    }
                    break;
                }
            default:
                break;
        }
        if (biblioEntryState === "scanning" && pendingCiteKeys.length > 0) {
            const result1 = [
                line,
                "\n\\begin{CSLReferences}{2}{0}",
                ...pendingCiteKeys,
                "\\end{CSLReferences}\n"
            ].join("\n");
            pendingCiteKeys = [];
            return result1;
        }
        return line.replaceAll(kQuartoCiteRegex, (_match, citeKey)=>{
            const citeLines = renderedCites[citeKey];
            if (citeLines) {
                if (biblioEntryState === "in-sidecaption" && citeLines.length > 0) {
                    pendingCiteKeys.push(citeLines[0]);
                    return [
                        "",
                        ...citeLines.slice(1)
                    ].join("\n");
                } else {
                    return [
                        "\n\\begin{CSLReferences}{2}{0}",
                        ...citeLines,
                        "\\end{CSLReferences}\n"
                    ].join("\n");
                }
            } else {
                return citeKey;
            }
        });
    };
};
const kCodeAnnotationRegex = /(.*)\\CommentTok\{(.*?)[^\s]+? +\\textless\{\}(\d+)\\textgreater\{\}.*\}$/gm;
const kCodePlainAnnotationRegex = /(.*)% \((\d+)\)$/g;
const codeAnnotationPostProcessor = ()=>{
    let lastAnnotation;
    return (line)=>{
        if (line === "\\begin{Shaded}") {
            lastAnnotation = undefined;
        }
        line = line.replaceAll(kCodeAnnotationRegex, (_match, prefix, comment, annotationNumber)=>{
            if (annotationNumber !== lastAnnotation) {
                lastAnnotation = annotationNumber;
                if (comment.length > 0) {
                    prefix = `${prefix}\\CommentTok\{${comment}\}`;
                }
                return `${prefix}\\hspace*{\\fill}\\NormalTok{\\circled{${annotationNumber}}}`;
            } else {
                return `${prefix}`;
            }
        });
        line = line.replaceAll(kCodePlainAnnotationRegex, (_match, prefix, annotationNumber)=>{
            if (annotationNumber !== lastAnnotation) {
                lastAnnotation = annotationNumber;
                const replaceValue = `(${annotationNumber})`;
                const paddingNumber = Math.max(0, 75 - prefix.length - replaceValue.length);
                const padding = " ".repeat(paddingNumber);
                return `${prefix}${padding}${replaceValue}`;
            } else {
                return `${prefix}`;
            }
        });
        return line;
    };
};
const kListAnnotationRegex = /(.*)5CB6E08D-list-annote-(\d+)(.*)/g;
const codeListAnnotationPostProcessor = ()=>{
    return (line)=>{
        return line.replaceAll(kListAnnotationRegex, (_match, prefix, annotationNumber, suffix)=>{
            return `${prefix}\\circled{${annotationNumber}}${suffix}`;
        });
    };
};
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(to) {
    return mergeConfigs(createEbookFormat("ePub", "epub"), {
        pandoc: {
            [kHtmlMathMethod]: to === "epub2" ? "webtex" : "mathml"
        },
        extensions: {
            book: epubBookExtension
        }
    });
}
const epubBookExtension = {
    selfContainedOutput: true,
    onSingleFilePreRender: (format, config)=>{
        if (!format.pandoc[kEPubCoverImage] && !format.metadata[kBookCoverImage]) {
            const coverImage = bookConfig(kBookCoverImage, config);
            if (coverImage) {
                format.metadata[kBookCoverImage] = coverImage;
            }
        }
        return format;
    }
};
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("MS Word", "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: {
                selfContainedOutput: true
            }
        }
    });
}
function iconPath(icon) {
    return formatResourcePath("docx", icon);
}
const kXmlLint = "xmllint";
async function reformat(xmlFile) {
    if (Deno.build.os !== "windows") {
        const xmlLint = await which(kXmlLint);
        if (xmlLint) {
            const result1 = await execProcess({
                cmd: [
                    kXmlLint,
                    xmlFile,
                    "--format",
                    "-o",
                    xmlFile
                ]
            });
            if (!result1.success) {
                warn("Unable to reformat the XML file " + xmlFile);
            }
        }
    }
}
async function copy2(src, dst, options) {
    let n = 0;
    const bufSize = options?.bufSize ?? DEFAULT_BUFFER_SIZE;
    const b = new Uint8Array(bufSize);
    let gotEOF = false;
    while(gotEOF === false){
        const result1 = await src.read(b);
        if (result1 === null) {
            gotEOF = true;
        } else {
            let nwritten = 0;
            while(nwritten < result1){
                nwritten += await dst.write(b.subarray(nwritten, result1));
            }
            n += nwritten;
        }
    }
    return n;
}
class MultiReader {
    #readers;
    #currentIndex = 0;
    constructor(readers){
        this.#readers = [
            ...readers
        ];
    }
    async read(p) {
        const r = this.#readers[this.#currentIndex];
        if (!r) return null;
        const result1 = await r.read(p);
        if (result1 === null) {
            this.#currentIndex++;
            return 0;
        }
        return result1;
    }
}
async function readAll(reader) {
    const chunks = [];
    while(true){
        let chunk = new Uint8Array(16_640);
        const n = await reader.read(chunk);
        if (n === null) {
            break;
        }
        if (n < 16_640) {
            chunk = chunk.subarray(0, n);
        }
        chunks.push(chunk);
    }
    return concat(chunks);
}
function readAllSync(reader) {
    const chunks = [];
    while(true){
        const chunk = new Uint8Array(16_640);
        const n = reader.readSync(chunk);
        if (n === null) {
            break;
        }
        if (n < 16_640) {
            chunks.push(chunk.subarray(0, n));
            break;
        }
        chunks.push(chunk);
    }
    return concat(chunks);
}
BigInt(Number.MAX_SAFE_INTEGER);
new TextDecoder();
const reformatXmlPostProcessor = async (output)=>{
    await reformat(output);
};
const renderSubarticlePostProcessor = (input, format, subArticles, services, project, quiet)=>{
    return async (output)=>{
        const subArticlesToRender = subArticles.filter((subArticle)=>{
            return services.notebook.get(subArticle.input, project) === undefined;
        });
        const total = subArticlesToRender.length;
        if (subArticlesToRender.length > 0 && !quiet) {
            logProgress("Rendering JATS sub-articles");
        }
        let count = 0;
        for (const subArticle of subArticlesToRender){
            const subArticlePath = subArticle.input;
            const nbRelPath = relative2(dirname2(input), subArticlePath);
            if (!quiet) {
                logProgress(`[${++count}/${total}] ${nbRelPath}`);
            }
            await services.notebook.render(subArticlePath, format, kJatsSubarticle1, services, undefined, project);
        }
        const supportingOut = [];
        for (const subArticle of subArticles){
            const nb = services.notebook.get(subArticle.input, project);
            if (nb && nb[kJatsSubarticle1]) {
                let outputContents = Deno.readTextFileSync(output);
                const notebook = nb[kJatsSubarticle1];
                const jatsSubarticlePath = notebook.path;
                const placeholder = xmlPlaceholder(subArticle.token, subArticle.input);
                const subArtReader = await Deno.open(jatsSubarticlePath);
                const subArtLines = [];
                for await (let line of readLines(subArtReader)){
                    line = line.replaceAll(kIdRegex, `$1id="$2-${subArticle.token}"`);
                    line = line.replaceAll(kRidRegex, `$1rid="$2-${subArticle.token}"`);
                    subArtLines.push(line);
                }
                outputContents = outputContents.replaceAll(placeholder, subArtLines.join("\n"));
                for (const support of notebook.supporting){
                    const basePath = project ? project.dir : dirname2(notebook.path);
                    const fromPath = join2(basePath, support);
                    const toPath = join2(dirname2(output), relative2(dirname2(notebook.path), fromPath));
                    if (fromPath !== toPath) {
                        copySync(fromPath, toPath, {
                            overwrite: true
                        });
                    }
                    supportingOut.push(toPath);
                }
                Deno.writeTextFileSync(output, outputContents);
            }
        }
        for (const subArticle of subArticles){
            services.notebook.removeRendering(subArticle.input, kJatsSubarticle1, supportingOut);
        }
        return {
            supporting: supportingOut
        };
    };
};
const kIdRegex = /(\s+)id="([^"]*)"/g;
const kRidRegex = /(\s+)rid="([^"]*)"/g;
const kJatsExtended = "jats-extended";
const kJatsDtd = "jats-dtd";
const kElementsVariant = "+element_citations";
function jatsFormat(displayName, ext) {
    return createFormat(displayName, ext, {
        pandoc: {
            standalone: true,
            [kDefaultImageExtension]: "png"
        },
        render: {
            [kVariant]: kElementsVariant
        },
        formatExtras: (input, _markdown, _flags, format, _libDir, services, _offset, project, quiet)=>{
            const templateDir = formatResourcePath("jats", "pandoc");
            const partials = [
                "front.xml",
                "authors.xml",
                "institution.xml",
                "affiliation.xml",
                "name.xml"
            ];
            const templateContext = {
                template: join2(templateDir, "template.xml"),
                partials: partials.map((partial)=>join2(templateDir, partial))
            };
            const tagset = jatsTagset(format.identifier["base-format"] || "jats");
            const metadataOverride = {
                [kLinkCitations]: true
            };
            if (format.metadata[kLinkCitations] === false) {
                warn("JATS formats require that `link-citations` is enabled to emit well formed JATS. Explicitly set value is being ignored.");
            }
            const postprocessors = [];
            const internalMetadata = format.metadata[kQuartoInternal];
            const afterBody = [];
            const subArticleResources = [];
            if (internalMetadata && !format.metadata[kJatsSubarticle]) {
                const subArticles = internalMetadata[kSubArticles];
                if (subArticles && format.render[kNotebookSubarticles] !== false) {
                    const placeholderFile = services.temp.createFile({
                        suffix: ".placeholder.xml"
                    });
                    const placeholders = [];
                    subArticles.forEach((subArticle)=>{
                        const placeholder = xmlPlaceholder(subArticle.token, subArticle.input);
                        placeholders.push(placeholder);
                    });
                    Deno.writeTextFileSync(placeholderFile, placeholders.join("\n"));
                    afterBody.push(placeholderFile);
                    if (subArticles.length > 0 && !format.metadata[kJatsSubarticle]) {
                        postprocessors.push(renderSubarticlePostProcessor(input, format, subArticles, services, project, quiet));
                    }
                }
            }
            if (format.metadata[kLintXml] !== false) {
                postprocessors.push(reformatXmlPostProcessor);
            }
            return {
                [kIncludeAfterBody]: afterBody,
                metadata: {
                    [kQuartoInternal]: {
                        [kJatsExtended]: tagset === "archiving" || tagset === "publishing",
                        [kJatsDtd]: jatsDtd(tagset)
                    },
                    [kResources]: subArticleResources
                },
                templateContext,
                metadataOverride,
                postprocessors
            };
        }
    });
}
function typstFormat() {
    return createFormat("Typst", "pdf", {
        execute: {
            [kFigWidth]: 5.5,
            [kFigHeight]: 3.5,
            [kFigFormat]: "svg"
        },
        pandoc: {
            standalone: true,
            [kDefaultImageExtension]: "svg",
            [kWrap]: "none",
            [kCiteproc]: false
        },
        resolveFormat: typstResolveFormat,
        formatExtras: (_input, markdown, flags, format, _libDir, _services)=>{
            const pandoc = {};
            const metadata = {};
            if (flags?.[kNumberSections] === true || format.pandoc[kNumberSections] === true) {
                if (!format.metadata?.[kSectionNumbering]) {
                    metadata[kSectionNumbering] = "1.1.a";
                }
            }
            const hasLevelOneHeadings = !!markdown.match(/\n^#\s.*$/gm);
            if (!hasLevelOneHeadings && flags?.[kShiftHeadingLevelBy] === undefined && format.pandoc?.[kShiftHeadingLevelBy] === undefined) {
                pandoc[kShiftHeadingLevelBy] = -1;
            }
            const columns = format.pandoc[kColumns];
            if (columns) {
                pandoc[kColumns] = undefined;
                metadata[kColumns] = columns;
            }
            const templateDir = formatResourcePath("typst", join2("pandoc", "quarto"));
            const templateContext = {
                template: join2(templateDir, "template.typ"),
                partials: [
                    "definitions.typ",
                    "typst-template.typ",
                    "typst-show.typ",
                    "notes.typ",
                    "biblio.typ"
                ].map((partial)=>join2(templateDir, partial))
            };
            return {
                pandoc,
                metadata,
                templateContext
            };
        }
    });
}
function typstResolveFormat(format) {
    if (format.pandoc?.[kCiteproc] === true && !format.pandoc.to?.includes("-citations") && !format.render[kVariant]?.includes("-citations")) {
        format.render[kVariant] = [
            format.render?.[kVariant],
            "-citations"
        ].join("");
    }
}
const writerFormatHandlers = [];
function registerWriterFormatHandler(handler) {
    writerFormatHandlers.push(handler);
}
function defaultWriterFormat(to) {
    const formatDescriptor = parseFormatString(to);
    let lookupTo = formatDescriptor.baseFormat;
    let pandocTo = lookupTo;
    let writerFormat;
    let handled = false;
    for (const handler of writerFormatHandlers){
        const result1 = handler(lookupTo);
        if (result1) {
            handled = true;
            if (result1.pandocTo) {
                pandocTo = result1.pandocTo;
            }
            writerFormat = result1.format;
            break;
        }
    }
    if (!handled) {
        switch(lookupTo){
            case "pdf":
                writerFormat = pdfFormat();
                break;
            case "beamer":
                writerFormat = beamerFormat();
                break;
            case "latex":
                writerFormat = latexFormat("LaTeX");
                break;
            case "context":
                writerFormat = latexFormat("ConTeXt");
                break;
            case "s5":
                writerFormat = createHtmlPresentationFormat("S5", 9.5, 6.5);
                break;
            case "dzslides":
                writerFormat = createHtmlPresentationFormat("DZSlides", 9.5, 6.5);
                break;
            case "slidy":
                writerFormat = createHtmlPresentationFormat("Slidy", 9.5, 6.5);
                break;
            case "slideous":
                writerFormat = createHtmlPresentationFormat("Slideous", 9.5, 6.5);
                break;
            case "markdown":
                writerFormat = pandocMarkdownFormat();
                pandocTo = to;
                break;
            case "markdown_phpextra":
            case "markdown_github":
            case "markdown_mmd":
            case "markdown_strict":
                writerFormat = markdownFormat("Markdown");
                pandocTo = to;
                break;
            case "markua":
                writerFormat = markdownFormat("Markua");
                pandocTo = to;
                break;
            case "md":
                writerFormat = markdownWithCommonmarkExtensionsFormat();
                lookupTo = "commonmark";
                pandocTo = "markdown_strict";
                break;
            case "commonmark":
            case "commonmark_x":
                writerFormat = commonmarkFormat(to);
                pandocTo = to;
                break;
            case "gfm":
                writerFormat = gfmFormat();
                pandocTo = to;
                break;
            case "docbook":
            case "docbook4":
            case "docbook5":
                writerFormat = plaintextFormat("DocBook", "xml");
                break;
            case "docx":
                writerFormat = docxFormat();
                break;
            case "pptx":
                writerFormat = powerpointFormat();
                break;
            case "odt":
                writerFormat = createWordprocessorFormat("OpenOffice", "odt");
                break;
            case "opendocument":
                writerFormat = createWordprocessorFormat("OpenDocument", "xml");
                break;
            case "rtf":
                writerFormat = rtfFormat();
                break;
            case "plain":
                writerFormat = plaintextFormat("Text", "txt");
                break;
            case "epub":
            case "epub2":
            case "epub3":
                writerFormat = epubFormat(lookupTo);
                break;
            case "fb2":
                writerFormat = createEbookFormat("FictionBook", "fb2");
                break;
            case "zimwiki":
                writerFormat = plaintextFormat("Zim Wiki", "zim");
                break;
            case "jats":
                writerFormat = jatsFormat("JATS", "xml");
                break;
            case "jats_archiving":
                writerFormat = jatsFormat("JATS Archiving", "xml");
                break;
            case "jats_articleauthoring":
                writerFormat = jatsFormat("JATS Authoring", "xml");
                break;
            case "jats_publishing":
                writerFormat = jatsFormat("JATS Publising", "xml");
                break;
            case "ipynb":
                writerFormat = ipynbFormat();
                break;
            case "biblatex":
                writerFormat = bibliographyFormat("BibLaTeX", "bib");
                break;
            case "bibtex":
                writerFormat = bibliographyFormat("BibTeX", "bib");
                break;
            case "csljson":
                writerFormat = bibliographyFormat("CSL-JSON", "csl");
                break;
            case "typst":
                writerFormat = typstFormat();
                break;
            case "texttile":
                writerFormat = plaintextFormat("Textile", to);
                break;
            case "texinfo":
                writerFormat = plaintextFormat("GNU TexInfo", to);
                break;
            case "tei":
                writerFormat = plaintextFormat("TEI Simple", to);
                break;
            case "rst":
                writerFormat = plaintextFormat("reST", to);
                break;
            case "org":
                writerFormat = plaintextFormat("Org-Mode", to);
                break;
            case "opml":
                writerFormat = plaintextFormat("OPML", to);
                break;
            case "muse":
                writerFormat = plaintextFormat("Muse", to);
                break;
            case "ms":
                writerFormat = plaintextFormat("Groff Manuscript", to);
                break;
            case "native":
                writerFormat = plaintextFormat("Native", to);
                break;
            case "man":
                writerFormat = plaintextFormat("Groff Man Page", to);
                break;
            case "dokuwiki":
                writerFormat = plaintextFormat("DocuWiki", to);
                break;
            case "haddock":
                writerFormat = plaintextFormat("Haddock markup", to);
                break;
            case "json":
                writerFormat = plaintextFormat("JSON", to);
                break;
            case "icml":
                writerFormat = plaintextFormat("InDesign", to);
                break;
            case "jira":
                writerFormat = plaintextFormat("Jira Wiki", to);
                break;
            case "mediawiki":
                writerFormat = plaintextFormat("MediaWiki", to);
                break;
            case "xwiki":
                writerFormat = plaintextFormat("XWiki", to);
                break;
            default:
                writerFormat = unknownFormat("txt");
        }
    }
    if (writerFormat === undefined) {
        throw new Error("Should never get here, but TypeScript's analysis doesn't know.");
    }
    writerFormat.pandoc = writerFormat.pandoc || {};
    if (!writerFormat.pandoc.to) {
        writerFormat.pandoc.to = pandocTo;
    }
    writerFormat.identifier[kTargetFormat] = to;
    writerFormat.identifier[kBaseFormat] = lookupTo;
    writerFormat.render[kVariant] = mergePandocVariant(writerFormat.render[kVariant], formatDescriptor.variants.join(""));
    return writerFormat;
}
function powerpointFormat() {
    return createFormat("Powerpoint", "pptx", {
        render: {
            [kPageWidth]: 10,
            [kOutputDivs]: false
        },
        execute: {
            [kFigWidth]: 11,
            [kFigHeight]: 5.5,
            [kEcho]: false,
            [kWarning]: false
        },
        pandoc: {
            [kDefaultImageExtension]: "png"
        }
    });
}
function rtfFormat() {
    return createFormat("RTF", "rtf", createWordprocessorFormat("RTF", "rtf"), {
        pandoc: {
            standalone: true
        }
    });
}
function unknownFormat(ext) {
    return createFormat("Unknown", ext);
}
function bibliographyFormat(displayName, ext) {
    return createFormat(displayName, ext);
}
async function resolveFormatsFromMetadata(metadata, input, formats, flags) {
    const includeDir = dirname2(input);
    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 (formats === undefined) {
        formats = formatKeys(allMetadata);
    }
    if (formats.length === 0) {
        formats.push(baseFormat.pandoc.to || baseFormat.pandoc.writer || "html");
    }
    const renderFormats = [];
    if (flags?.to === undefined) {
        renderFormats.push(...formats);
    } else if (flags?.to === "default") {
        renderFormats.push(formats[0]);
    } else {
        const toFormats = flags.to.split(",").flatMap((to)=>{
            if (to === "all") {
                return formats;
            } else {
                return [
                    to
                ];
            }
        });
        renderFormats.push(...toFormats);
    }
    formats = uniq1(formats.concat(renderFormats));
    const resolved = {};
    formats.forEach((to)=>{
        const format = formatFromMetadata(baseFormat, to, flags?.debug);
        const config = mergeFormatMetadata(baseFormat, format);
        const defaultFormat = defaultWriterFormat(to);
        const resolveFormat = defaultFormat.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] = {
            format: config,
            active: renderFormats.includes(to)
        };
    });
    return resolved;
}
async function renderContexts(file, options, forExecute, notebookContext, project, cloneOptions = true, enforceProjectFormats = true) {
    if (cloneOptions) {
        options = cloneDeep1(options);
    }
    const { engine, target } = await fileExecutionEngineAndTarget(file.path, options.flags, project);
    const formats = await resolveFormats(file, target, engine, options, notebookContext, project, enforceProjectFormats);
    options = removePandocTo(options);
    let libDir = project?.config?.project[kProjectLibDir];
    if (project && libDir) {
        libDir = relative2(dirname2(file.path), join2(project.dir, libDir));
    } else {
        libDir = filesDirLibDir(file.path);
    }
    const contexts = {};
    for (const formatKey of Object.keys(formats)){
        formats[formatKey].format.language = await formatLanguage(formats[formatKey].format.metadata, formats[formatKey].format.language, options.flags);
        const context = {
            target,
            options,
            engine,
            format: formats[formatKey].format,
            active: formats[formatKey].active,
            project,
            libDir: libDir
        };
        contexts[formatKey] = context;
        if (!isJupyterNotebook(context.target.source)) {
            const preEngineCellHandlerOptions = {
                name: "",
                temp: options.services.temp,
                format: context.format,
                markdown: context.target.markdown,
                context,
                flags: options.flags || {},
                stage: "pre-engine"
            };
            const { markdown, results } = await handleLanguageCells(preEngineCellHandlerOptions);
            context.target.markdown = markdown;
            if (results) {
                context.target.preEngineExecuteResults = results;
            }
        }
        if (!forExecute && engine.executeTargetSkipped) {
            engine.executeTargetSkipped(target, formats[formatKey].format);
        }
    }
    return contexts;
}
async function renderFormats(file, services, to = "all", project) {
    const contexts = await renderContexts({
        path: file
    }, {
        services,
        flags: {
            to
        }
    }, false, services.notebook, project);
    const formats = {};
    Object.keys(contexts).forEach((formatName)=>{
        const context = contexts[formatName];
        const format = context.format;
        delete format.metadata.format;
        deleteProjectMetadata(format.metadata);
        if (!format.pandoc[kOutputFile]) {
            const [_dir, stem] = dirAndStem(file);
            format.pandoc[kOutputFile] = `${stem}.${format.render[kOutputExt]}`;
        }
        format.execute[kEngine] = context.engine.name;
        formats[formatName] = format;
    });
    return formats;
}
function mergeQuartoConfigs(config, ...configs) {
    config = cloneDeep1(config);
    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 format = config[kMetadataFormat];
        if (typeof format === "string") {
            config.format = {
                [format]: {}
            };
        } else if (format instanceof Object) {
            Object.keys(format).forEach((key)=>{
                if (typeof Reflect.get(format, key) !== "object") {
                    Reflect.set(format, key, {});
                }
                fixupMergeableScalars(Reflect.get(format, key));
            });
        }
        fixupMergeableScalars(config);
        return config;
    };
    return mergeConfigs(fixupFormat(config), ...configs.map((c)=>fixupFormat(c)));
}
async function resolveFormats(file, target, engine, options, _notebookContext, project, enforceProjectFormats = true) {
    const inputMetadata = target.metadata;
    const directoryMetadata = project?.dir ? await directoryMetadataForInputFile(project, dirname2(target.input)) : {};
    const projMetadata = project === undefined ? {} : await projectMetadataForInputFile(target.input, project);
    let formats = [];
    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) {
        formats = projFormatKeys;
    } else if (inputFormatKeys.length > 0) {
        formats = inputFormatKeys;
    } else {
        formats = projFormatKeys;
    }
    if (file.formats) {
        formats = formats.filter((format)=>{
            return file.formats?.includes(format);
        });
        options = cloneDeep1(options);
        delete options.flags?.to;
    }
    const projFormats = await resolveFormatsFromMetadata(projMetadata, target.input, formats, options.flags);
    const directoryFormats = await resolveFormatsFromMetadata(directoryMetadata, target.input, formats, options.flags);
    const inputFormats = await resolveFormatsFromMetadata(inputMetadata, target.input, formats, options.flags);
    const activeKeys = (formats)=>{
        return Object.keys(formats).filter((key)=>{
            return formats[key].active;
        });
    };
    const activeFormatKeys = __VIRTUAL_FILE181(activeKeys(projFormats).concat(activeKeys(directoryFormats)).concat(activeKeys(inputFormats)));
    const allFormatKeys = __VIRTUAL_FILE181(Object.keys(projFormats).concat(Object.keys(directoryFormats)).concat(Object.keys(inputFormats)));
    const mergedFormats = {};
    for (const format of allFormatKeys){
        const projFormat = projFormats[format].format;
        const directoryFormat = directoryFormats[format].format;
        const inputFormat = inputFormats[format].format;
        if (project && (isHtmlOutput(format, true) || isHtmlDashboardOutput(format)) && formatHasBootstrap(projFormat) && projectTypeIsWebsite(projType)) {
            if (formatHasBootstrap(inputFormat)) {
                if (inputFormat.metadata[kTheme] !== undefined && !__VIRTUAL_FILE211(inputFormat.metadata[kTheme], projFormat.metadata[kTheme])) {
                    warnOnce(`The file ${file.path} contains a theme property which is being ignored. Website projects do not support per document themes since all pages within a website share the website's theme.`);
                }
                delete inputFormat.metadata[kTheme];
            }
            if (formatHasBootstrap(directoryFormat)) {
                if (directoryFormat.metadata[kTheme] !== undefined && !__VIRTUAL_FILE211(directoryFormat.metadata[kTheme], projFormat.metadata[kTheme])) {
                    warnOnce(`The file ${file.path} contains a theme provided by a metadata file. This theme metadata is being ignored. Website projects do not support per directory themes since all pages within a website share the website's theme.`);
                }
                delete directoryFormat.metadata[kTheme];
            }
        }
        const userFormat = mergeFormatMetadata(projFormat || {}, directoryFormat || {}, inputFormat || {});
        if (userFormat.metadata[kServer] !== undefined) {
            if (userFormat.execute[kEcho] === undefined) {
                userFormat.execute[kEcho] = false;
            }
            if (userFormat.execute[kIpynbShellInteractivity] === undefined) {
                userFormat.execute[kIpynbShellInteractivity] = "all";
            }
        }
        if (options.echo) {
            userFormat.execute[kEcho] = true;
        }
        if (options.warning) {
            userFormat.execute[kWarning] = true;
        }
        const formatDesc = parseFormatString(format);
        const extensionMetadata = await readExtensionFormat(target.source, formatDesc, options.services.extension, project);
        mergedFormats[format] = mergeFormatMetadata(defaultWriterFormat(formatDesc.formatWithVariants), extensionMetadata[formatDesc.baseFormat] ? extensionMetadata[formatDesc.baseFormat].format : {}, userFormat);
        mergedFormats[format].identifier[kTargetFormat] = format;
        mergedFormats[format].mergeAdditionalFormats = (...configs)=>{
            return mergeFormatMetadata(defaultWriterFormat(formatDesc.formatWithVariants), extensionMetadata[formatDesc.baseFormat] ? extensionMetadata[formatDesc.baseFormat].format : {}, ...configs, userFormat);
        };
        const formatIsValid = isValidFormat(formatDesc, mergedFormats[format].pandoc);
        if (!formatIsValid) {
            throw new Error(`Unknown format ${format}`);
        }
    }
    if (enforceProjectFormats) {
        for (const formatName of Object.keys(mergedFormats)){
            const format = mergedFormats[formatName];
            if (projType.isSupportedFormat) {
                if (!projType.isSupportedFormat(format)) {
                    delete mergedFormats[formatName];
                    warnOnce(`The ${formatName} format is not supported by ${projType.type} projects`);
                }
            }
        }
    }
    for (const formatName of Object.keys(mergedFormats)){
        let format = mergedFormats[formatName];
        if (hasIpynbFilters(format.execute)) {
            const markdown = await engine.partitionedMarkdown(target.source, format);
            if (markdown.yaml) {
                const nbFormats = await resolveFormatsFromMetadata(markdown.yaml, target.source, [
                    formatName
                ], {
                    ...options.flags,
                    to: undefined
                });
                format = mergeConfigs(format, nbFormats[formatName]);
            }
        }
        if (engine.filterFormat) {
            format = engine.filterFormat(target.source, options, format);
        }
        if (projType.filterFormat) {
            format = projType.filterFormat(target.source, format, project);
        }
        mergedFormats[formatName] = format;
    }
    const finalFormats = {};
    for (const key of Object.keys(mergedFormats)){
        const active = activeFormatKeys.includes(key);
        finalFormats[key] = {
            format: mergedFormats[key],
            active
        };
    }
    return finalFormats;
}
const readExtensionFormat = async (file, formatDesc, extensionContext, project)=>{
    if (formatDesc.extension) {
        const extension = await extensionContext.extension(formatDesc.extension, file, project?.config, project?.dir);
        const extensionFormat = extension?.contributes.formats;
        if (extensionFormat) {
            const fmtTarget = formatDesc.modifiers ? `${formatDesc.baseFormat}${formatDesc.modifiers.join("")}` : formatDesc.baseFormat;
            const extensionMetadata = extensionFormat[fmtTarget] || extensionFormat[formatDesc.baseFormat] || {};
            extensionMetadata[kExtensionName] = extensionMetadata[kExtensionName] || formatDesc.extension;
            const formats = await resolveFormatsFromMetadata(extensionMetadata, extension.path, [
                formatDesc.baseFormat
            ]);
            return formats;
        } else {
            throw new Error(`No valid format ${formatDesc.baseFormat} is provided by the extension ${formatDesc.extension}`);
        }
    } else {
        return {};
    }
};
function hasIpynbFilters(execute) {
    return execute[kIpynbFilters] && execute[kIpynbFilters]?.length;
}
async function projectMetadataForInputFile(input, project) {
    project = cloneDeep1(project);
    if (project.dir && project.config) {
        return toInputRelativePaths(projectType(project.config?.project?.[kProjectType]), project.dir, dirname2(input), project.config);
    } else {
        return project.config || {};
    }
}
function isHttpUrl(url) {
    return /^https?:/i.test(url);
}
function joinUrl(baseUrl, path) {
    const baseHasSlash = baseUrl.endsWith("/");
    path = pathWithForwardSlashes(path);
    const pathHasSlash = path.startsWith("/");
    if (baseHasSlash && pathHasSlash) {
        return `${baseUrl}${path.slice(1)}`;
    } else if (!baseHasSlash && !pathHasSlash) {
        return `${baseUrl}/${path}`;
    } else {
        return `${baseUrl}${path}`;
    }
}
function ensureProtocolAndTrailingSlash(url) {
    if (!url.startsWith("http")) {
        url = `https://${url}`;
    }
    url = ensureTrailingSlash(url);
    return url;
}
async function gitCmds(dir, cmds) {
    for (const cmd of cmds){
        if (!(await execProcess({
            cmd: [
                "git",
                ...cmd
            ],
            cwd: dir
        })).success) {
            throw new Error();
        }
    }
}
async function gitVersion() {
    const result1 = await execProcess({
        cmd: [
            "git",
            "--version"
        ],
        stdout: "piped"
    });
    if (!result1.success) {
        throw new Error("Unable to determine git version. Please check that git is installed and available on your PATH.");
    }
    const match = result1.stdout?.match(/git version (\d+\.\d+\.\d+)/);
    if (match) {
        return new SemVer(match[1]);
    } else {
        throw new Error(`Unable to determine git version from string ${result1.stdout}`);
    }
}
async function lsFiles(cwd, args) {
    if (await which("git")) {
        const result1 = await execProcess({
            cmd: [
                "git",
                "ls-files",
                ...args || []
            ],
            cwd,
            stdout: "piped",
            stderr: "piped"
        });
        if (result1.success) {
            return result1.stdout?.split("\n").filter((file)=>{
                return file.length > 0;
            });
        }
    }
    return Promise.resolve(undefined);
}
async function gitBranchExists(branch, cwd) {
    if (await which("git")) {
        const result1 = await execProcess({
            cmd: [
                "git",
                "show-ref",
                "--verify",
                "--quiet",
                `refs/heads/${branch}`
            ],
            cwd,
            stdout: "piped",
            stderr: "piped"
        });
        return result1.code === 0;
    }
    return Promise.resolve(undefined);
}
async function gitHubContext(dir) {
    const context = {
        git: false,
        repo: false
    };
    context.git = !!await which("git");
    if (context.git) {
        context.repo = (await execProcess({
            cmd: [
                "git",
                "rev-parse"
            ],
            cwd: dir,
            stdout: "piped",
            stderr: "piped"
        })).success;
        if (context.repo) {
            const result1 = await execProcess({
                cmd: [
                    "git",
                    "config",
                    "--get",
                    "remote.origin.url"
                ],
                cwd: dir,
                stdout: "piped",
                stderr: "piped"
            });
            if (result1.success) {
                context.originUrl = result1.stdout?.trim();
                const ghPagesRemote = await execProcess({
                    cmd: [
                        "git",
                        "ls-remote",
                        "--quiet",
                        "--exit-code",
                        "origin",
                        "gh-pages"
                    ],
                    stdout: "piped",
                    stderr: "piped"
                });
                context.ghPagesRemote = ghPagesRemote.success;
                if (!ghPagesRemote.success) {
                    if (ghPagesRemote.code === 2) {
                        context.ghPagesLocal = await gitBranchExists("gh-pages");
                    } else {
                        throw new Error(`There is an error while retrieving information from remote 'origin'.\n Git error: ${ghPagesRemote.stderr}. \n Git status code: ${ghPagesRemote.code}.`);
                    }
                }
                context.siteUrl = siteUrl(dir, context.originUrl);
                const repo = repoInfo(context.originUrl);
                if (repo) {
                    context.repoUrl = repo.repoUrl;
                    context.organization = repo.organization;
                    context.repository = repo.repository;
                }
            }
        }
    }
    return context;
}
const kGithubCom = "github.com";
const kGithubIo = "github.io";
const kGithubGitPattern = /^git@([^:]+):([^\/]+)\/(.+?)(?:\.git)?$/;
const kGithubHttpsPattern = /^https:\/\/([^\/]+)\/([^\/]+)\/(.+?)(?:\.git)?$/;
function repoInfo(originUrl) {
    const match = originUrl?.match(kGithubGitPattern) || originUrl?.match(kGithubHttpsPattern);
    if (match && match.includes(kGithubCom)) {
        return {
            repoUrl: `https://${match[1]}/${match[2]}/${match[3]}/`,
            organization: match[2],
            repository: match[3]
        };
    }
}
function siteUrl(dir, originUrl) {
    const cname = join2(dir, "CNAME");
    if (existsSync(cname)) {
        const url = Deno.readTextFileSync(cname).trim();
        if (isHttpUrl(url)) {
            return url;
        } else {
            return `https://${url}`;
        }
    } else {
        const match = originUrl?.match(kGithubGitPattern) || originUrl?.match(kGithubHttpsPattern);
        if (match && match.includes(kGithubCom)) {
            const server = match[1].replace(kGithubCom, kGithubIo);
            const domain = `${match[2]}.${server}`;
            if (domain === match[3]) {
                return `https://${domain}/`;
            } else {
                return `https://${domain}/${match[3]}/`;
            }
        }
    }
}
function renderServices(notebook) {
    const temp = createTempContext();
    const extension = createExtensionContext();
    if (getNamedLifetime(kRenderServicesLifetime)) {
        return {
            temp,
            extension,
            notebook,
            lifetime: getNamedLifetime(kRenderServicesLifetime),
            cleanup: ()=>{}
        };
    } else {
        const lifetime = createNamedLifetime(kRenderServicesLifetime);
        lifetime.attach(temp);
        lifetime.attach(notebook);
        return {
            temp,
            extension,
            notebook,
            lifetime,
            cleanup: ()=>{
                lifetime.cleanup();
            }
        };
    }
}
function withRenderServices(notebook, fn) {
    const services = renderServices(notebook);
    return fn(services).finally(()=>{
        services.cleanup();
    });
}
const kDefaultContainerTitle = "Default Container";
const makeProjectEnvironmentMemoizer = (notebookContext)=>{
    let cachedEnv = undefined;
    return async (project)=>{
        if (cachedEnv) {
            return Promise.resolve(cachedEnv);
        } else {
            cachedEnv = await computeProjectEnvironment(notebookContext, project);
            return cachedEnv;
        }
    };
};
const computeProjectEnvironment = async (notebookContext, context)=>{
    const version = quartoConfig.version();
    const quarto = version === kLocalDevelopment ? "prerelease" : new SemVer(version);
    const github = await gitHubContext(context.dir);
    const containerCtx = {
        title: kDefaultContainerTitle,
        engines: context.engines,
        tools: [],
        codeEnvironment: "vscode",
        quarto,
        environments: [],
        openFiles: [],
        envVars: {},
        github
    };
    const editorContext = projectEditor(context);
    containerCtx.codeEnvironment = editorContext.editor;
    containerCtx.openFiles.push(...editorContext.openFiles);
    const title = context.config?.project.title;
    if (title) {
        containerCtx.title = title;
    }
    const tools = await projectTools(notebookContext, context);
    containerCtx.tools.push(...tools);
    const envFiles = Object.keys(environmentCommands);
    for (const envFile of envFiles){
        if (existsSync(envFile)) {
            containerCtx.environments.push(envFile);
        }
    }
    return containerCtx;
};
const environmentCommands = {
    "renv.lock": {
        restore: `Rscript -e 'renv::restore();'`
    },
    "requirements.txt": {
        restore: `python3 -m pip install -r requirements.txt`
    },
    "DESCRIPTION": {
        restore: `Rscript -e 'devtools::install_local(getwd())'`
    },
    "install.R": {
        restore: `Rscript install.R`
    },
    "environment.yml": {
        restore: "conda env create -f environment.yml",
        features: {
            "ghcr.io/devcontainers/features/conda:1": {
                addCondaForge: true
            }
        }
    },
    "PipFile": {},
    "PipFile.lock": {},
    "setup.py": {},
    "Project.toml": {},
    "REQUIRE": {}
};
const kChromiumHint = /````*{mermaid}|{dot}/gm;
const projectTools = async (notebookContext, context)=>{
    let tinytex = false;
    let chromium = false;
    for (const input of context.files.input){
        if (!tinytex) {
            const formats = await withRenderServices(notebookContext, (services)=>context.renderFormats(input, services, "all", context));
            const hasPdf = Object.values(formats).some((format)=>{
                return isPdfOutput(format.pandoc);
            });
            tinytex = hasPdf;
        }
        if (!chromium) {
            const contents = Deno.readTextFileSync(input);
            if (contents.match(kChromiumHint)) {
                chromium = true;
            }
        }
        if (tinytex && chromium) {
            break;
        }
    }
    const tools = [];
    if (tinytex) {
        tools.push("tinytex");
    }
    if (chromium) {
        tools.push("chromium");
    }
    return tools;
};
const projectEditor = (context)=>{
    const qmdCodeTool = context.engines.includes("knitr") ? "rstudio" : "vscode";
    const ipynbCodeTool = "jupyterlab";
    const openFiles = [];
    let editor = qmdCodeTool;
    if (projectType(context.config?.project.type).type === kManuscriptType) {
        const manuscriptConfig = context.config?.[kManuscriptType];
        if (extname2(manuscriptConfig.article) === ".qmd") {
            editor = qmdCodeTool;
        } else {
            editor = ipynbCodeTool;
        }
        openFiles.push(manuscriptConfig.article);
    } else {
        const exts = {};
        const inputs = context.files.input;
        for (const input of inputs){
            const ext = extname2(input);
            exts[ext] = (exts[ext] || 0) + 1;
        }
        const qmdCount = exts[".qmd"] || 0;
        const ipynbCount = exts[".ipynb"] || 0;
        if (qmdCount >= ipynbCount) {
            editor = qmdCodeTool;
        } else {
            editor = ipynbCodeTool;
        }
    }
    return {
        editor,
        openFiles
    };
};
async function projectContext(path, notebookContext, renderOptions, force = false) {
    const flags = renderOptions?.flags;
    let dir = normalizePath(Deno.statSync(path).isDirectory ? path : dirname2(path));
    const originalDir = dir;
    const extensionContext = renderOptions?.services.extension || createExtensionContext();
    const configSchema = await getProjectConfigSchema();
    const configResolvers = [
        quartoYamlProjectConfigResolver(configSchema),
        await projectExtensionsConfigResolver(extensionContext, dir)
    ];
    let cachedEnv = undefined;
    const environment = async (project)=>{
        if (cachedEnv) {
            return Promise.resolve(cachedEnv);
        } else {
            cachedEnv = await computeProjectEnvironment(notebookContext, project);
            return cachedEnv;
        }
    };
    while(true){
        const resolver = configResolvers[0];
        const resolved = await resolver(dir);
        if (resolved) {
            let projectConfig = resolved.config;
            const configFiles = resolved.files;
            projectConfig = migrateProjectConfig(projectConfig);
            const projType = projectConfig.project[kProjectType];
            if (projType && !projectTypes().includes(projType)) {
                projectConfig = await resolveProjectExtension(extensionContext, projType, projectConfig, dir);
                const configSchema = await getProjectConfigSchema();
                const includedMeta = await includedMetadata(dir, projectConfig, configSchema);
                const metadata = includedMeta.metadata;
                projectConfig = mergeProjectMetadata(projectConfig, metadata);
            }
            const result1 = await initializeProfileConfig(dir, projectConfig, configSchema);
            projectConfig = result1.config;
            configFiles.push(...result1.files);
            const dotenvFiles = await dotenvSetVariables(dir);
            configFiles.push(...dotenvFiles);
            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 formats = {
                    [flags?.to]: toFormat
                };
                Object.keys(projectFormats).forEach((format)=>{
                    formats[format] = projectFormats[format];
                });
                projectConfig[kMetadataFormat] = formats;
            }
            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];
                }
                const projOutputDir = projectConfig.project[kProjectOutputDir];
                if (projOutputDir && isAbsolute2(projOutputDir)) {
                    projectConfig.project[kProjectOutputDir] = relative2(dir, projOutputDir);
                }
                const result1 = {
                    resolveFullMarkdownForFile: (engine, file, markdown, force)=>{
                        return projectResolveFullMarkdownForFile(result1, engine, file, markdown, force);
                    },
                    dir,
                    engines: [],
                    fileInformationCache: new Map(),
                    files: {
                        input: []
                    },
                    config: projectConfig,
                    renderFormats,
                    environment: ()=>environment(result1),
                    notebookContext,
                    fileExecutionEngineAndTarget: (file)=>{
                        return fileExecutionEngineAndTarget(file, flags, result1);
                    },
                    isSingleFile: false
                };
                if (type.config) {
                    result1.config = await type.config(result1, projectConfig, flags);
                }
                const { files, engines } = await projectInputFiles(result1, projectConfig);
                const fullPath = normalizePath(path);
                if (Deno.statSync(fullPath).isFile && !files.includes(fullPath)) {
                    return undefined;
                }
                debug(`projectContext: Found Quarto project in ${dir}`);
                if (type.formatExtras) {
                    result1.formatExtras = async (source, flags, format, services)=>type.formatExtras(result1, source, flags, format, services);
                }
                result1.engines = engines;
                result1.files = {
                    input: files,
                    resources: projectResourceFiles(dir, projectConfig),
                    config: configFiles,
                    configResources: projectConfigResources(dir, projectConfig, type)
                };
                return result1;
            } else {
                debug(`projectContext: Found Quarto project in ${dir}`);
                const result1 = {
                    resolveFullMarkdownForFile: (engine, file, markdown, force)=>{
                        return projectResolveFullMarkdownForFile(result1, engine, file, markdown, force);
                    },
                    dir,
                    config: projectConfig,
                    engines: [],
                    fileInformationCache: new Map(),
                    files: {
                        input: []
                    },
                    renderFormats,
                    environment: ()=>environment(result1),
                    fileExecutionEngineAndTarget: (file)=>{
                        return fileExecutionEngineAndTarget(file, flags, result1);
                    },
                    notebookContext,
                    isSingleFile: false
                };
                const { files, engines } = await projectInputFiles(result1, projectConfig);
                result1.engines = engines;
                result1.files = {
                    input: files,
                    resources: projectResourceFiles(dir, projectConfig),
                    config: configFiles,
                    configResources: projectConfigResources(dir, projectConfig)
                };
                return result1;
            }
        } else {
            const nextDir = dirname2(dir);
            if (nextDir === dir) {
                if (configResolvers.length > 1) {
                    dir = originalDir;
                    configResolvers.shift();
                } else if (force) {
                    const context = {
                        resolveFullMarkdownForFile: (engine, file, markdown, force)=>{
                            return projectResolveFullMarkdownForFile(context, engine, file, markdown, force);
                        },
                        dir: originalDir,
                        engines: [],
                        config: {
                            project: {
                                [kProjectOutputDir]: flags?.outputDir
                            }
                        },
                        fileInformationCache: new Map(),
                        files: {
                            input: []
                        },
                        renderFormats,
                        environment: ()=>environment(context),
                        notebookContext,
                        fileExecutionEngineAndTarget: (file)=>{
                            return fileExecutionEngineAndTarget(file, flags, context);
                        },
                        isSingleFile: false
                    };
                    if (Deno.statSync(path).isDirectory) {
                        const { files, engines } = await projectInputFiles(context);
                        context.engines = engines;
                        context.files.input = files;
                    } else {
                        const input = normalizePath(path);
                        const engine = await fileExecutionEngine(input, undefined, context);
                        context.engines = [
                            engine?.name ?? kMarkdownEngine
                        ];
                        context.files.input = [
                            input
                        ];
                    }
                    debug(`projectContext: Found Quarto project in ${originalDir}`);
                    return context;
                } else {
                    return undefined;
                }
            } else {
                dir = nextDir;
            }
        }
    }
}
function quartoYamlProjectConfigResolver(configSchema) {
    return async (dir)=>{
        let configFile = undefined;
        try {
            configFile = projectConfigFile(dir);
        } catch (e) {
            if (e instanceof Deno.errors.PermissionDenied) {} else {
                throw e;
            }
        }
        if (configFile) {
            const files = [
                configFile
            ];
            const errMsg = "Project _quarto.yml validation failed.";
            let config = await readAndValidateYamlFromFile(configFile, configSchema, errMsg, kDefaultProjectFileContents);
            config.project = config.project || {};
            const includedMeta = await includedMetadata(dir, config, configSchema);
            const metadata = includedMeta.metadata;
            files.push(...includedMeta.files);
            config = mergeProjectMetadata(config, metadata);
            delete config[kMetadataFile];
            delete config[kMetadataFiles];
            return {
                config,
                files
            };
        } else {
            return undefined;
        }
    };
}
async function projectExtensionsConfigResolver(context, dir) {
    const projectTypeDetectors = (await context.extensions(dir)).reduce((projectTypeDetectors, extension)=>{
        if (extension.contributes.project) {
            const project = extension.contributes.project;
            if (project?.project?.detect) {
                const detect = asArray(project?.project.detect);
                projectTypeDetectors.push({
                    type: extension.id.name,
                    detect
                });
            }
        }
        return projectTypeDetectors;
    }, []);
    return (dir)=>{
        for (const detector of projectTypeDetectors){
            if (detector.detect.some((files)=>files.every((file)=>safeExistsSync(join2(dir, file))))) {
                return Promise.resolve({
                    config: {
                        project: {
                            type: detector.type
                        }
                    },
                    files: []
                });
            }
        }
        return Promise.resolve(undefined);
    };
}
async function resolveProjectExtension(context, projectType, projectConfig, dir) {
    const extensions = await context.find(projectType, dir, "project", projectConfig, dir);
    const filtered = filterExtensions(extensions, projectType, "project");
    if (filtered.length > 0) {
        const extension = filtered[0];
        const projectExt = extension.contributes.project;
        if (projectExt) {
            const projectExtConfig = __VIRTUAL_FILE107(projectExt);
            delete projectExtConfig.project.detect;
            if (projectConfig.project.render) {
                delete projectExtConfig.project.render;
            }
            const extProjType = ()=>{
                const projectMeta = projectExt.project;
                if (projectMeta && typeof projectMeta === "object") {
                    const extType = projectMeta.type;
                    if (typeof extType === "string") {
                        return extType;
                    } else {
                        return "default";
                    }
                } else {
                    return "default";
                }
            };
            projectConfig.project[kProjectType] = extProjType();
            projectConfig = mergeProjectMetadata(projectExtConfig, projectConfig);
        }
    }
    return projectConfig;
}
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(join2(dir, "_language.yml"));
    projectConfig[kLanguageDefaults] = mergeConfigs(translations.language, projectConfig[kLanguageDefaults]);
    files.push(...translations.files);
    return files;
}
function projectContextForDirectory(path, notebookContext, renderOptions) {
    return projectContext(path, notebookContext, renderOptions, true);
}
function projectHiddenIgnoreGlob(dir) {
    return projectIgnoreGlobs(dir).concat([
        "**/_*",
        "**/_*/**"
    ]).concat([
        "**/.*",
        "**/.*/**"
    ]).concat([
        "**/README.?([Rrq])md"
    ]);
}
async function projectInputFiles(project, metadata) {
    const { dir } = project;
    const files = [];
    const engines = [];
    const intermediateFiles = [];
    const outputDir = metadata?.project[kProjectOutputDir];
    const projIgnoreGlobs = projectHiddenIgnoreGlob(dir);
    const projectIgnores = projIgnoreGlobs.map((glob)=>globToRegExp2(glob, {
            extended: true,
            globstar: true
        }));
    const addFile = async (file)=>{
        if (!outputDir || !ensureTrailingSlash(dirname2(file)).startsWith(ensureTrailingSlash(join2(dir, outputDir))) || !ensureTrailingSlash(join2(dir, outputDir)).startsWith(ensureTrailingSlash(dir))) {
            const engine = await fileExecutionEngine(file, undefined, project);
            if (engine) {
                if (!engines.includes(engine.name)) {
                    engines.push(engine.name);
                }
                files.push(file);
                const engineIntermediates = executionEngineIntermediateFiles(engine, file);
                if (engineIntermediates) {
                    intermediateFiles.push(...engineIntermediates);
                }
            }
        }
    };
    const addDir = async (dir)=>{
        for (const walk of walkSync(dir, {
            includeDirs: false,
            followSymlinks: false,
            skip: [
                kSkipHidden
            ].concat(engineIgnoreDirs().map((ignore)=>globToRegExp2(join2(dir, ignore) + SEPARATOR2)))
        })){
            const pathRelative = pathWithForwardSlashes(relative2(dir, walk.path));
            if (!projectIgnores.some((regex)=>regex.test(pathRelative))) {
                await addFile(walk.path);
            }
        }
    };
    const renderFiles = metadata?.project[kProjectRender];
    if (renderFiles) {
        const exclude = projIgnoreGlobs.concat(outputDir ? [
            outputDir
        ] : []);
        const resolved = resolvePathGlobs(dir, renderFiles, exclude, {
            mode: "auto"
        });
        await Promise.all(__VIRTUAL_FILE137(resolved.include, resolved.exclude).map((file)=>{
            if (Deno.statSync(file).isDirectory) {
                return addDir(file);
            } else {
                return addFile(file);
            }
        }));
    } else {
        await addDir(dir);
    }
    const inputFiles = __VIRTUAL_FILE137(__VIRTUAL_FILE181(files), __VIRTUAL_FILE181(intermediateFiles));
    return {
        files: inputFiles,
        engines
    };
}
function projectConfigResources(dir, metadata, type) {
    const resourceIgnoreFields = ignoreFieldsForProjectType(type);
    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 path = isAbsolute2(value) ? value : join2(dir, value);
                try {
                    if (existsSync(path) && !Deno.statSync(path).isDirectory) {
                        resources.push(normalizePath(path));
                    }
                } catch  {}
            }
        });
    };
    findResources(metadata);
    return resources;
}
function websiteConfigBoolean(name, defaultValue, project) {
    const config = websiteConfig(name, project);
    if (typeof config === "string") {
        return !!config;
    } else if (typeof config == "boolean") {
        return config;
    } else {
        return defaultValue;
    }
}
function websiteConfigString(name, project) {
    const config = websiteConfig(name, project);
    if (typeof config === "string") {
        return config;
    } else {
        return undefined;
    }
}
function websiteConfigMetadata(name, project) {
    const config = websiteConfig(name, project);
    if (typeof config === "object" && !Array.isArray(config)) {
        return config;
    } else {
        return undefined;
    }
}
function websiteConfigArray(name, project) {
    const config = websiteConfig(name, project);
    if (Array.isArray(config)) {
        return config;
    } else {
        return undefined;
    }
}
function websiteConfig(name, project) {
    const site = project?.[kWebsite];
    if (site) {
        return site[name];
    } else {
        return undefined;
    }
}
function websiteConfigUnknown(name, project) {
    const site = project?.[kWebsite];
    if (site) {
        return site[name];
    } 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 path = websiteConfigString(kSitePath, project);
    if (path) {
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        return path;
    } else {
        const baseUrl = websiteBaseurl(project);
        if (baseUrl) {
            try {
                const url = new URL(baseUrl);
                let path = url.pathname;
                if (!path.endsWith("/")) {
                    path = path + "/";
                }
                return path;
            } catch  {
                return "/";
            }
        } else {
            return "/";
        }
    }
}
function websiteRepoInfo(format, project) {
    let repoUrl = websiteConfigString(kSiteRepoUrl, project);
    if (format.metadata[kSiteRepoUrl] !== undefined) {
        repoUrl = format.metadata[kSiteRepoUrl];
    }
    if (repoUrl) {
        repoUrl = ensureTrailingSlash(repoUrl);
        const repoSubdir = websiteConfigString(kSiteRepoSubdir, project);
        if (repoSubdir) {
            return {
                baseUrl: repoUrl,
                path: ensureTrailingSlash(repoSubdir)
            };
        } else {
            return {
                baseUrl: repoUrl,
                path: ""
            };
        }
    } else {
        return undefined;
    }
}
function websiteRepoBranch(project) {
    return websiteConfigString(kSiteRepoBranch, project) || "main";
}
function websiteMetadataFields() {
    return [
        kWebsite,
        "site"
    ];
}
function repoUrlIcon(url) {
    if (url.indexOf("github.com") !== -1) {
        return "github";
    } else {
        return "git";
    }
}
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 websiteFormatPreferHtml(format) {
    if (format !== undefined) {
        if (typeof format === "string") {
            return {
                [format]: "default"
            };
        } else {
            const formats = Object.keys(format);
            const orderedFormats = {};
            const htmlFormatPos = formats.findIndex((format)=>isHtmlOutput(format, true));
            if (htmlFormatPos !== -1) {
                const htmlFormatName = formats.splice(htmlFormatPos, 1)[0];
                orderedFormats[htmlFormatName] = format[htmlFormatName];
            }
            for (const formatName of formats){
                orderedFormats[formatName] = format[formatName];
            }
            return orderedFormats;
        }
    } else {
        return {
            html: "default"
        };
    }
}
function formatsPreferHtml(formats) {
    const orderedFormats = {};
    const formatNames = Object.keys(formats);
    const htmlFormatPos = formatNames.findIndex((format)=>isHtmlOutput(format, true));
    if (htmlFormatPos !== -1) {
        const htmlFormatName = formatNames.splice(htmlFormatPos, 1)[0];
        orderedFormats[htmlFormatName] = formats[htmlFormatName];
    }
    for (const formatName of formatNames){
        orderedFormats[formatName] = formats[formatName];
    }
    return orderedFormats;
}
function websiteProjectConfig(project, config, flags) {
    const projectDir = project.dir;
    config = cloneDeep1(config);
    const format = config[kMetadataFormat];
    config[kMetadataFormat] = websiteFormatPreferHtml(format);
    const ensureArray = (val)=>{
        if (Array.isArray(val)) {
            return val;
        } else if (typeof val === "string") {
            return [
                val
            ];
        }
    };
    const siteMeta = config[kWebsite] || {};
    siteMeta[kSiteTitle] = siteMeta[kSiteTitle] || config.project[kProjectTitle];
    if (flags?.siteUrl) {
        siteMeta[kSiteUrl] = flags.siteUrl;
    }
    if (siteMeta[kBodyHeader]) {
        siteMeta[kBodyHeader] = ensureArray(siteMeta[kBodyHeader]);
    }
    if (siteMeta[kBodyFooter]) {
        siteMeta[kBodyFooter] = ensureArray(siteMeta[kBodyFooter]);
    }
    const resolveProjectPaths = (maybePath)=>{
        if (existsSync(maybePath)) {
            return join2(projectDir, maybePath);
        } else {
            return maybePath;
        }
    };
    if (siteMeta[kMarginHeader]) {
        siteMeta[kMarginHeader] = ensureArray(siteMeta[kMarginHeader])?.map(resolveProjectPaths);
    }
    if (siteMeta[kMarginFooter]) {
        siteMeta[kMarginFooter] = ensureArray(siteMeta[kMarginFooter])?.map(resolveProjectPaths);
    }
    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);
    }
    if (websiteConfigUnknown(kOtherLinks, config) && config[kOtherLinks] === undefined) {
        config[kOtherLinks] = websiteConfigUnknown(kOtherLinks, config);
    }
    if (websiteConfigUnknown(kCodeLinks, config) && config[kCodeLinks] === undefined) {
        config[kCodeLinks] = websiteConfigUnknown(kCodeLinks, config);
    }
    const draftMode = websiteConfigString(kDraftMode, config);
    if (draftMode) {
        config[kDraftMode] = draftMode;
    }
    const drafts = websiteConfigArray(kDrafts, config);
    if (drafts) {
        config[kDrafts] = drafts;
    }
    return Promise.resolve(config);
}
function websiteHtmlFormat(project) {
    const projConfig = project.config || {};
    const baseFormat = metadataAsFormat(projConfig);
    const format = formatFromMetadata(baseFormat, formatKeys(projConfig)[0]);
    return mergeConfigs(baseFormat, format);
}
async function inputTargetIndex(project, input) {
    const inputFile = join2(project.dir, input);
    if (!safeExistsSync(inputFile) || Deno.statSync(inputFile).isDirectory) {
        return Promise.resolve(undefined);
    }
    if (!project.files.input.includes(normalizePath(inputFile))) {
        return Promise.resolve(undefined);
    }
    const { index: targetIndex } = readInputTargetIndex(project.dir, input);
    if (targetIndex) {
        return targetIndex;
    }
    const index = await readBaseInputIndex(inputFile, project);
    if (index) {
        const indexFile = inputTargetIndexFile(project.dir, input);
        Deno.writeTextFileSync(indexFile, JSON.stringify(index));
    }
    return index;
}
async function readBaseInputIndex(inputFile, project) {
    const engine = await fileExecutionEngine(inputFile, undefined, project);
    if (engine === undefined) {
        return Promise.resolve(undefined);
    }
    const formats = await withRenderServices(project.notebookContext, (services)=>project.renderFormats(inputFile, services, "all", project));
    const firstFormat = Object.values(formats)[0];
    const markdown = await engine.partitionedMarkdown(inputFile, firstFormat);
    const index = {
        title: firstFormat?.metadata?.[kTitle] || markdown.yaml?.[kTitle] || markdown.headingText,
        markdown,
        formats,
        draft: firstFormat?.metadata?.[kDraft] || markdown.yaml?.[kDraft]
    };
    if (index.title) {
        if (typeof index.title !== "string") {
            throw new Error(`${relative2(project.dir, inputFile)}: Title must be a string, but is instead of type ${typeof index.title}`);
        }
        const parsedTitle = parsePandocTitle(index.title);
        index.title = parsedTitle.heading;
    } else {
        index.title = index.markdown.headingText;
    }
    if (project.config) {
        index.projectFormats = formatKeys(project.config);
    }
    return index;
}
function readInputTargetIndex(projectDir, input) {
    const index = readInputTargetIndexIfStillCurrent(projectDir, input);
    if (!index) {
        return {
            missingReason: "stale"
        };
    }
    if (Object.keys(index.formats).includes("html")) {
        index.formats = websiteFormatPreferHtml(index.formats);
    }
    const formats = index.projectFormats ?? Object.keys(index.formats);
    const projConfigFile = projectConfigFile(projectDir);
    if (!projConfigFile) {
        return {
            index
        };
    }
    let contents = Deno.readTextFileSync(projConfigFile);
    if (contents.trim().length === 0) {
        contents = kDefaultProjectFileContents;
    }
    const config = readYamlFromString(contents);
    const projFormats = formatKeys(config);
    if (__VIRTUAL_FILE211(formats, projFormats)) {
        return {
            index
        };
    } else {
        return {
            missingReason: "formats"
        };
    }
}
function inputTargetIsEmpty(index) {
    if (index.markdown.markdown.trim().length > 0) {
        return false;
    }
    if (index.markdown.yaml && Object.keys(index.markdown.yaml).find((key)=>key !== kTitle)) {
        return false;
    }
    return true;
}
const inputTargetIndexCache = new Map();
const inputTargetIndexCacheMetrics = {
    hits: 0,
    misses: 0,
    invalidations: 0
};
function readInputTargetIndexIfStillCurrent(projectDir, input) {
    const inputFile = join2(projectDir, input);
    const indexFile = inputTargetIndexFile(projectDir, input);
    try {
        const inputMod = Deno.statSync(inputFile).mtime;
        const indexMod = Deno.statSync(indexFile).mtime;
        if (inputMod && indexMod) {
            if (inputMod > indexMod) {
                inputTargetIndexCacheMetrics.invalidations++;
                inputTargetIndexCache.delete(indexFile);
                return undefined;
            }
            if (inputTargetIndexCache.has(indexFile)) {
                inputTargetIndexCacheMetrics.hits++;
                return inputTargetIndexCache.get(indexFile);
            } else {
                inputTargetIndexCacheMetrics.misses++;
                try {
                    const result1 = JSON.parse(Deno.readTextFileSync(indexFile));
                    inputTargetIndexCache.set(indexFile, result1);
                    return result1;
                } catch  {
                    return undefined;
                }
            }
        }
    } catch (e) {
        if (e instanceof Deno.errors.NotFound) {
            return undefined;
        } else {
            throw e;
        }
    }
}
async function resolveInputTarget(project, href, absolute = true) {
    const index = await inputTargetIndex(project, href);
    if (index) {
        const formats = formatsPreferHtml(index.formats);
        const format = Object.values(formats)[0];
        const projType = projectType(project.config?.project?.[kProjectType]);
        const projOutputFile = projType.outputFile ? projType.outputFile(href, format, project) : undefined;
        const [hrefDir, hrefStem] = dirAndStem(href);
        const outputFile = projOutputFile || formatOutputFile(format) || `${hrefStem}.html`;
        const outputHref = pathWithForwardSlashes((absolute ? "/" : "") + join2(hrefDir, outputFile));
        const inputTarget = {
            input: href,
            title: index.title,
            outputHref,
            draft: index.draft === true
        };
        if (projType.filterInputTarget) {
            return projType.filterInputTarget(inputTarget, project);
        } else {
            return inputTarget;
        }
    } else {
        return undefined;
    }
}
async function inputFileForOutputFile(project, output) {
    const outputDir = projectOutputDir(project);
    output = isAbsolute2(output) ? output : join2(outputDir, output);
    if (project.outputNameIndex !== undefined) {
        return project.outputNameIndex.get(output);
    }
    project.outputNameIndex = new Map();
    for (const file of project.files.input){
        const inputRelative = relative2(project.dir, file);
        const index = await inputTargetIndex(project, relative2(project.dir, file));
        if (index) {
            Object.keys(index.formats).forEach((key)=>{
                const format = index.formats[key];
                const outputFile = formatOutputFile(format);
                if (outputFile) {
                    const formatOutputPath = join2(outputDir, dirname2(inputRelative), outputFile);
                    project.outputNameIndex.set(formatOutputPath, {
                        file,
                        format
                    });
                }
            });
        }
    }
    return project.outputNameIndex.get(output);
}
async function inputTargetIndexForOutputFile(project, outputRelative) {
    const input = await inputFileForOutputFile(project, outputRelative);
    if (!input) {
        return undefined;
    }
    return await inputTargetIndex(project, relative2(project.dir, input.file));
}
async function resolveInputTargetForOutputFile(project, outputRelative) {
    const input = await inputFileForOutputFile(project, outputRelative);
    if (!input) {
        return undefined;
    }
    return await resolveInputTarget(project, pathWithForwardSlashes(relative2(project.dir, input.file)));
}
function clearProjectIndex(projectDir) {
    const indexPath = projectScratchPath(projectDir, "idx");
    removeIfExists(indexPath);
}
function inputTargetIndexFile(projectDir, input) {
    return indexPath(projectDir, `${input}.json`);
}
function indexPath(projectDir, path) {
    return projectScratchPath(projectDir, join2("idx", path));
}
const sidebarContext = ()=>{
    return {
        counter: 0
    };
};
function normalizeSidebarItem(projectDir, item, context) {
    item = cloneDeep1(item);
    if (typeof item === "string") {
        if (safeExistsSync(join2(projectDir, item))) {
            item = {
                href: item
            };
        } else {
            item = {
                text: item
            };
        }
    } else {
        resolveHrefAttribute(item);
        const section = item.section;
        if (section) {
            context.counter = context.counter + 1;
            const sectionPath = join2(projectDir, section);
            if (safeExistsSync(sectionPath) && Deno.statSync(sectionPath).isFile) {
                item.href = section;
            } else {
                item.text = section;
            }
            item.sectionId = `${kQuartoSidebarPrefix}${context.counter}`;
            delete item.section;
            item.contents = item.contents || [];
        }
        if (item.contents) {
            for(let i1 = 0; i1 < item.contents.length; i1++){
                item.contents[i1] = normalizeSidebarItem(projectDir, item.contents[i1], context);
            }
        }
    }
    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(project, input) {
    const { index } = readInputTargetIndex(project.dir, input);
    if (index) {
        return index.markdown;
    } else {
        const inputPath = join2(project.dir, input);
        const engine = await fileExecutionEngine(inputPath, undefined, project);
        if (engine) {
            return await engine.partitionedMarkdown(inputPath);
        } else {
            return undefined;
        }
    }
}
function inInches(size) {
    if (size.endsWith("in")) {
        return Number(size.slice(0, -2));
    }
    if (size.endsWith("pt") || size.endsWith("px")) {
        return Number(size.slice(0, -2)) / 96;
    }
    return Number(size);
}
async function resolveSize(svg, options) {
    const dom = (await getDomParser()).parseFromString(svg, "text/html");
    const svgEl = dom?.querySelector("svg");
    if (!svgEl) {
        throw new InternalError("Couldn't find an svg element in svg string");
    }
    let width = svgEl.getAttribute("width");
    let height = svgEl.getAttribute("height");
    const getViewBox = ()=>{
        const m = svg.match(/viewbox/i);
        if (!m) return undefined;
        const vb = denoDomWorkaroundNamedItemAccessor(svg, svgEl, "viewbox")?.value;
        if (!vb) return undefined;
        const lst = vb.trim().split(" ").map(Number);
        if (lst.length !== 4) return undefined;
        if (lst.some(isNaN)) return undefined;
        return lst;
    };
    if (!width || !height) {
        const viewBox = getViewBox();
        if (viewBox !== undefined) {
            const [_mx, _my, vbWidth, vbHeight] = viewBox;
            width = `${vbWidth}px`;
            height = `${vbHeight}px`;
        } else {
            throw new Error("Mermaid generated an SVG without a viewbox attribute. Without knowing the diagram dimensions, quarto cannot convert it to a PNG");
        }
    }
    let svgWidthInInches, svgHeightInInches;
    if (width.slice(0, -2) === "pt" && height.slice(0, -2) === "pt" || width.slice(0, -2) === "px" && height.slice(0, -2) === "px" || !isNaN(Number(width)) && !isNaN(Number(height))) {
        svgWidthInInches = Number(width.slice(0, -2)) / 96;
        svgHeightInInches = Number(height.slice(0, -2)) / 96;
    }
    const viewBox = getViewBox();
    if (viewBox !== undefined) {
        const [_mx, _my, vbWidth, vbHeight] = viewBox;
        svgWidthInInches = vbWidth / 96;
        svgHeightInInches = vbHeight / 96;
    } else {
        throw new InternalError("Couldn't resolve width and height of SVG");
    }
    const svgWidthOverHeight = svgWidthInInches / svgHeightInInches;
    let widthInInches, heightInInches;
    if (options?.[kFigWidth] && options?.[kFigHeight]) {
        widthInInches = inInches(String(options?.[kFigWidth]));
        heightInInches = inInches(String(options?.[kFigHeight]));
    } else if (options?.[kFigWidth]) {
        widthInInches = inInches(String(options?.[kFigWidth]));
        heightInInches = widthInInches / svgWidthOverHeight;
    } else if (options?.[kFigHeight]) {
        heightInInches = inInches(String(options?.[kFigHeight]));
        widthInInches = heightInInches * svgWidthOverHeight;
    } else {
        heightInInches = svgHeightInInches;
        widthInInches = svgWidthInInches;
    }
    return {
        widthInInches,
        heightInInches,
        widthInPoints: Math.round(widthInInches * 96),
        heightInPoints: Math.round(heightInInches * 96),
        explicitWidth: options?.[kFigWidth] !== undefined,
        explicitHeight: options?.[kFigHeight] !== undefined
    };
}
const fixupAlignment = (svg, align)=>{
    let style = svg.getAttribute("style") ?? "";
    switch(align){
        case "left":
            style = `${style}; display: block; margin: auto auto auto 0`;
            break;
        case "right":
            style = `${style}; display: block; margin: auto 0 auto auto`;
            break;
        case "center":
            style = `${style}; display: block; margin: auto auto auto auto`;
            break;
    }
    svg.setAttribute("style", style);
};
const denoDomWorkaroundNamedItemAccessor = (_str, el, key)=>{
    key = key.toLocaleLowerCase();
    for(let i1 = 0; i1 < el.attributes.length; ++i1){
        const attr = el.attributes.item(i1);
        if (attr?.name.toLowerCase() === key) {
            return attr;
        }
    }
    return null;
};
async function setSvgSize(svgSrc, options, extra) {
    const mappedSvgSrc = asMappedString(svgSrc);
    const { widthInPoints, heightInPoints, explicitHeight, explicitWidth } = await resolveSize(mappedSvgSrc.value, options);
    const dom = (await getDomParser()).parseFromString(mappedSvgSrc.value, "text/html");
    const svg = dom.querySelector("svg");
    if (explicitWidth && explicitHeight) {
        svg.setAttribute("width", widthInPoints);
        svg.setAttribute("height", heightInPoints);
        svg.setAttribute("style", (denoDomWorkaroundNamedItemAccessor(mappedSvgSrc.value, svg, "style")?.value || "") + "; max-width: none; max-height: none");
    } else {
        let style = denoDomWorkaroundNamedItemAccessor(mappedSvgSrc.value, svg, "style")?.value || "";
        if (explicitWidth) {
            style = `${style}; max-width: ${widthInPoints}px`;
        }
        if (explicitHeight) {
            style = `${style}; max-height: ${heightInPoints}px`;
        }
        if (explicitWidth || explicitHeight) {
            svg.setAttribute("style", style);
        }
    }
    if (extra) {
        extra(svg);
    }
    return mappedDiff(mappedSvgSrc, svg.outerHTML);
}
async function makeResponsive(svgSrc, extras) {
    const mappedSvgSrc = asMappedString(svgSrc);
    const dom = (await getDomParser()).parseFromString(mappedSvgSrc.value, "text/html");
    if (dom === null) {
        throw new Error("Couldn't parse element");
    }
    const svg = dom.querySelector("svg");
    if (svg === null) {
        throw new Error("Couldn't find SVG element");
    }
    const width = svg.getAttribute("width");
    if (width === null) {
        throw new Error("Couldn't find SVG width");
    }
    const numWidth = Number(width.slice(0, -2));
    let changed = false;
    if (numWidth > 650) {
        changed = true;
        svg.setAttribute("width", "100%");
        svg.removeAttribute("height");
    }
    if (extras) {
        changed = true;
        extras(svg);
    }
    if (changed) {
        return mappedDiff(mappedSvgSrc, svg.outerHTML);
    } else {
        return mappedSvgSrc;
    }
}
const mermaidHandler = {
    ...baseHandler,
    schema () {
        return Promise.resolve(convertFromYaml(readYamlFromString(`
object:
  properties:
    mermaid-format:
      enum: [png, svg, js]
    theme:
      anyOf:
        - null
        - string
`)));
    },
    type: "cell",
    stage: "post-engine",
    languageName: "mermaid",
    languageClass: (options)=>{
        if (isMarkdownOutput(options.format, [
            "gfm"
        ])) {
            return "mermaid-source";
        } else {
            return "default";
        }
    },
    defaultOptions: {
        echo: false,
        eval: true,
        include: true
    },
    comment: "%%",
    async cell (handlerContext, cell, options) {
        const mermaidOpts = {};
        if (typeof handlerContext.options.format.metadata.mermaid === "object" && handlerContext.options.format.metadata.mermaid) {
            const { mermaid } = handlerContext.options.format.metadata;
            if (mermaid.theme) {
                mermaidOpts.theme = mermaid.theme;
            } else {
                mermaidOpts.theme = "neutral";
            }
        }
        const cellContent = handlerContext.cellContent(cell);
        const content = `<html>
<head>
<script src="./mermaid.min.js"></script>
</head>
<body>
<pre class="mermaid">\n${__VIRTUAL_FILE172(cellContent.value)}\n</pre> 
<script>
mermaid.initialize(${JSON.stringify(mermaidOpts)});
</script>
</html>`;
        const selector = "pre.mermaid svg";
        const resources = [
            [
                "mermaid.min.js",
                Deno.readTextFileSync(formatResourcePath("html", join2("mermaid", "mermaid.min.js")))
            ]
        ];
        const setupMermaidSvgJsRuntime = ()=>{
            if (handlerContext.getState().hasSetupMermaidSvgJsRuntime) {
                return;
            }
            handlerContext.getState().hasSetupMermaidSvgJsRuntime = true;
            const dep = {
                name: "quarto-diagram",
                scripts: [
                    {
                        name: "mermaid-postprocess-shim.js",
                        path: formatResourcePath("html", join2("mermaid", "mermaid-postprocess-shim.js")),
                        afterBody: true
                    }
                ]
            };
            handlerContext.addHtmlDependency(dep);
        };
        const setupMermaidJsRuntime = ()=>{
            if (handlerContext.getState().hasSetupMermaidJsRuntime) {
                return;
            }
            handlerContext.getState().hasSetupMermaidJsRuntime = true;
            const jsName = handlerContext.options.context.format.metadata?.["mermaid-debug"] ? "mermaid.js" : "mermaid.min.js";
            if (mermaidOpts.theme) {
                const mermaidMeta = {};
                mermaidMeta["mermaid-theme"] = mermaidOpts.theme;
                handlerContext.addHtmlDependency({
                    name: "quarto-mermaid-conf",
                    meta: mermaidMeta
                });
            }
            const dep = {
                name: "quarto-diagram",
                scripts: [
                    {
                        name: jsName,
                        path: formatResourcePath("html", join2("mermaid", jsName))
                    },
                    {
                        name: "mermaid-init.js",
                        path: formatResourcePath("html", join2("mermaid", "mermaid-init.js")),
                        afterBody: true
                    }
                ],
                stylesheets: [
                    {
                        name: "mermaid.css",
                        path: formatResourcePath("html", join2("mermaid", "mermaid.css"))
                    }
                ]
            };
            handlerContext.addHtmlDependency(dep);
        };
        const makeFigLink = (sourceName, width, height, includeCaption)=>{
            const figEnvSpecifier = isLatexOutput(handlerContext.options.format.pandoc) ? ` fig-env='${cell.options?.["fig-env"] || "figure"}'` : "";
            let posSpecifier = "";
            if (isLatexOutput(handlerContext.options.format.pandoc) && cell.options?.["fig-pos"] !== false) {
                const v = Array.isArray(cell.options?.["fig-pos"]) ? cell.options?.["fig-pos"].join("") : cell.options?.["fig-pos"];
                posSpecifier = ` fig-pos='${v || "H"}'`;
            }
            const idSpecifier = cell.options?.label && includeCaption ? ` #${cell.options?.label}` : "";
            const widthSpecifier = width ? `width="${Math.round(width * 100) / 100}in"` : "";
            const heightSpecifier = height ? ` height="${Math.round(height * 100) / 100}in"` : "";
            const captionSpecifier = includeCaption ? cell.options?.["fig-cap"] || "" : "";
            return `\n![${captionSpecifier}](${sourceName}){${widthSpecifier}${heightSpecifier}${posSpecifier}${figEnvSpecifier}${idSpecifier}}\n`;
        };
        const responsive = handlerContext.options.context.format.metadata?.[kFigResponsive];
        const makeSvg = async ()=>{
            setupMermaidSvgJsRuntime();
            let svg = asMappedString((await handlerContext.extractHtml({
                html: content,
                selector,
                resources
            }))[0]);
            const fixupRevealAlignment = (svg)=>{
                if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
                    const align = options?.[kFigAlign] ?? "center";
                    fixupAlignment(svg, align);
                }
            };
            let newId = undefined;
            const idsToPatch = [];
            const fixupMermaidSvg = (svg)=>{
                const { baseName: newMermaidId } = handlerContext.uniqueFigureName("mermaid-figure-", "");
                newId = newMermaidId;
                fixupRevealAlignment(svg);
                const oldId = svg.getAttribute("id");
                svg.setAttribute("id", newMermaidId);
                const style = svg.querySelector("style");
                style.innerHTML = style.innerHTML.replaceAll(oldId, newMermaidId);
                for (const defNode of svg.querySelectorAll("defs")){
                    const defEl = defNode;
                    const m = defEl.innerHTML.match(/id="([^\"]+)"/);
                    if (m) {
                        const id = m[1];
                        idsToPatch.push(id);
                    }
                }
            };
            if (responsive && options[kFigWidth] === undefined && options[kFigHeight] === undefined) {
                svg = await makeResponsive(svg, fixupMermaidSvg);
            } else {
                svg = await setSvgSize(svg, options, (svg)=>{
                    svg.removeAttribute("style");
                    fixupMermaidSvg(svg);
                });
            }
            if (idsToPatch.length) {
                let oldSvgSrc = svg.value;
                for (const idToPatch of idsToPatch){
                    const to = `${newId}-${idToPatch}`;
                    oldSvgSrc = oldSvgSrc.replaceAll(`"${idToPatch}"`, `"${to}"`);
                    oldSvgSrc = oldSvgSrc.replaceAll(`#${idToPatch}`, `#${to}`);
                }
                svg = mappedDiff(svg, oldSvgSrc);
            }
            if (isMarkdownOutput(handlerContext.options.format, [
                "gfm"
            ])) {
                const { sourceName, fullName } = handlerContext.uniqueFigureName("mermaid-figure-", ".svg");
                Deno.writeTextFileSync(fullName, svg.value);
                const { widthInInches, heightInInches } = await resolveSize(svg.value, cell.options ?? {});
                return asMappedString(makeFigLink(sourceName, widthInInches, heightInInches, true));
            } else {
                return this.build(handlerContext, cell, svg, options, undefined, new Set([
                    "fig-width",
                    "fig-height",
                    "mermaid-format"
                ]));
            }
        };
        const makePng = async ()=>{
            const { filenames: [sourceName], elements: [svgText] } = await handlerContext.createPngsFromHtml({
                prefix: "mermaid-figure-",
                selector,
                count: 1,
                deviceScaleFactor: Number(options.deviceScaleFactor) || 4,
                html: content,
                resources
            });
            const { widthInInches, heightInInches } = await resolveSize(svgText, cell.options ?? {});
            if (isMarkdownOutput(handlerContext.options.format, [
                "gfm"
            ])) {
                return asMappedString(makeFigLink(sourceName, widthInInches, heightInInches, true));
            } else {
                return this.build(handlerContext, cell, asMappedString(makeFigLink(sourceName, widthInInches, heightInInches)), options, undefined, new Set([
                    "fig-width",
                    "fig-height",
                    "mermaid-format"
                ]));
            }
        };
        const makeJs = async ()=>{
            setupMermaidJsRuntime();
            const preAttrs = [];
            if (options.label) {
                preAttrs.push(`label="${options.label}"`);
            }
            const preEl = pandocHtmlBlock("pre")({
                classes: [
                    "mermaid",
                    "mermaid-js"
                ],
                attrs: preAttrs
            });
            const content = handlerContext.cellContent(cell);
            preEl.push(pandocRawStr(__VIRTUAL_FILE172(content.value)));
            const attrs = {};
            if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
                attrs.reveal = true;
            }
            return this.build(handlerContext, cell, mappedConcat([
                preEl.mappedString()
            ]), options, attrs, new Set([
                "mermaid-format"
            ]));
        };
        const makeDefault = async ()=>{
            if (isIpynbOutput(handlerContext.options.format.pandoc)) {
                return await makePng();
            } else if (isJavascriptCompatible(handlerContext.options.format)) {
                return await makeJs();
            } else if (isMarkdownOutput(handlerContext.options.format, [
                "gfm"
            ])) {
                return mappedConcat([
                    "\n``` mermaid\n",
                    cellContent,
                    "\n```\n"
                ]);
            } else {
                return await makePng();
            }
        };
        const format = options[kMermaidFormat] || handlerContext.options.format.execute[kMermaidFormat];
        if (format === "svg") {
            return await makeSvg();
        } else if (format === "png") {
            return await makePng();
        } else if (format === "js") {
            if (!isJavascriptCompatible(handlerContext.options.format)) {
                const error = new LocalizedError("IncompatibleOutput", `\`mermaid-format: js\` not supported in format ${handlerContext.options.format.pandoc.to ?? ""}`, cell.sourceVerbatim, 0);
                warn(error.message);
                console.log("");
                return await makeDefault();
            } else {
                if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
                    const error = new LocalizedError("NotRecommended", `\`mermaid-format: js\` not recommended in format ${handlerContext.options.format.pandoc.to ?? ""}`, cell.sourceVerbatim, 0);
                    warn(error.message);
                    console.log("");
                }
                return await makeJs();
            }
        } else {
            return await makeDefault();
        }
    }
};
install(mermaidHandler);
const includeHandler = {
    ...baseHandler,
    languageName: "include",
    type: "directive",
    stage: "pre-engine",
    async directive (handlerContext, directive) {
        const param = directive.shortcode.params[0];
        if (!param) {
            throw new Error("Include directive needs filename as a parameter");
        }
        return await standaloneInclude(handlerContext, param);
    }
};
install(includeHandler);
const dotHandler = {
    ...baseHandler,
    type: "cell",
    stage: "post-engine",
    languageName: "dot",
    defaultOptions: {
        echo: false,
        eval: true,
        include: true,
        "graph-layout": "dot"
    },
    comment: "//",
    async cell (handlerContext, cell, options) {
        const cellContent = handlerContext.cellContent(cell);
        const graphvizModule = await import(toFileUrl2(resourcePath(join2("js", "graphviz-wasm.js"))).href);
        let svg;
        const oldConsoleLog = console.log;
        const oldConsoleWarn = console.warn;
        console.log = ()=>{};
        console.warn = ()=>{};
        try {
            svg = await graphvizModule.graphviz().layout(cellContent.value, "svg", options["graph-layout"]);
            console.log = oldConsoleLog;
            console.warn = oldConsoleWarn;
        } catch (e) {
            console.log = oldConsoleLog;
            console.warn = oldConsoleWarn;
            const m = e.message.match(/(.*)syntax error in line (\d+)(.*)/);
            if (m) {
                const number = Number(m[2]) - 1;
                const locF = mappedIndexToLineCol(cellContent);
                const offsets = Array.from(lineOffsets(cellContent.value));
                const offset = offsets[number];
                const mapResult = cellContent.map(offset, true);
                const { line } = locF(offset);
                e.message = e.message.replace(m[0], `${m[1]}syntax error in file ${mapResult.originalString.fileName}, line ${line + 1}${m[3]}`);
                throw e;
            } else {
                throw e;
            }
        }
        const makeFigLink = (sourceName, width, height, includeCaption)=>{
            const figEnvSpecifier = isLatexOutput(handlerContext.options.format.pandoc) ? ` fig-env='${cell.options?.["fig-env"] || "figure"}'` : "";
            const heightOffset = isTypstOutput(handlerContext.options.format.pandoc) ? 0.1 : 0.0;
            let posSpecifier = "";
            if (isLatexOutput(handlerContext.options.format.pandoc) && cell.options?.["fig-pos"] !== false) {
                const v = Array.isArray(cell.options?.["fig-pos"]) ? cell.options?.["fig-pos"].join("") : cell.options?.["fig-pos"];
                posSpecifier = ` fig-pos='${v || "H"}'`;
            }
            const idSpecifier = cell.options?.label && includeCaption ? ` #${cell.options?.label}` : "";
            const widthSpecifier = width ? `width="${Math.round(width * 100) / 100}in"` : "";
            const heightSpecifier = height ? ` height="${Math.round(height * 100) / 100 + heightOffset}in"` : "";
            const captionSpecifier = includeCaption ? cell.options?.["fig-cap"] || "" : "";
            return `\n![${captionSpecifier}](${sourceName}){${widthSpecifier}${heightSpecifier}${posSpecifier}${figEnvSpecifier}${idSpecifier}}\n`;
        };
        const fixupRevealAlignment = (svg)=>{
            if (isRevealjsOutput(handlerContext.options.context.format.pandoc)) {
                const align = options?.[kFigAlign] ?? "center";
                fixupAlignment(svg, align);
            }
        };
        if (isJavascriptCompatible(handlerContext.options.format) && !isIpynbOutput(handlerContext.options.format.pandoc)) {
            const responsive = options?.[kFigResponsive] ?? handlerContext.options.context.format.metadata?.[kFigResponsive];
            svg = (await parseHtml(svg)).querySelector("svg").outerHTML;
            if (responsive && options[kFigWidth] === undefined && options[kFigHeight] === undefined) {
                svg = await makeResponsive(svg, fixupRevealAlignment);
            } else {
                svg = await setSvgSize(svg, options, fixupRevealAlignment);
            }
            svg = mappedConcat([
                "```{=html}\n",
                svg,
                "\n```\n"
            ]);
            return this.build(handlerContext, cell, svg, options);
        } else {
            const { filenames: [sourceName] } = await handlerContext.createPngsFromHtml({
                prefix: "dot-figure-",
                selector: "svg",
                count: 1,
                deviceScaleFactor: Number(options.deviceScaleFactor) || 4,
                html: `<!DOCTYPE html><html><body>${svg}</body></html>`
            });
            const { widthInInches, heightInInches } = await resolveSize(svg, options);
            const isIpynbSourceOutput = isIpynbOutput(handlerContext.options.context.format.pandoc) && handlerContext.options.context.format.render[kIpynbProduceSourceNotebook];
            if (isIpynbSourceOutput) {
                const figLink = makeFigLink(sourceName, widthInInches, heightInInches, true);
                return mappedConcat([
                    "\n:::{.cell .markdown}",
                    figLink,
                    ":::\n"
                ]);
            } else {
                return this.build(handlerContext, cell, mappedConcat([
                    makeFigLink(sourceName, widthInInches, heightInInches)
                ]), options);
            }
        }
    }
};
install(dotHandler);
const kHandlers = [
    {
        name: "Jupyter Notebook Embed",
        handle (filename, params, handlerContext) {
            const markdownFragments = [];
            const notebookAddress = parseNotebookAddress(filename);
            if (notebookAddress) {
                const outputs = params.outputs;
                const placeHolder = notebookMarkdownPlaceholder(handlerContext.options.context.target.input, filename, {
                    echo: params.echo !== undefined ? params.echo : false,
                    warning: false,
                    asis: true,
                    eval: false
                }, outputs);
                markdownFragments.push(placeHolder);
                return Promise.resolve({
                    handled: true,
                    markdownFragments,
                    resources: [
                        notebookAddress.path
                    ]
                });
            } else {
                return Promise.resolve({
                    handled: false,
                    markdownFragments: []
                });
            }
        }
    }
];
const embedHandler = {
    ...baseHandler,
    languageName: "embed",
    type: "directive",
    stage: "post-engine",
    async directive (handlerContext, directive) {
        const textFragments = [];
        const filename = directive.shortcode.params[0];
        if (!filename) {
            throw new Error("Embed directive requires a filename as a parameter");
        }
        for (const handler of kHandlers){
            const result1 = await handler.handle(filename, directive.shortcode.namedParams, handlerContext);
            if (result1.handled) {
                textFragments.push(...result1.markdownFragments);
                if (result1.resources) {
                    result1.resources.forEach((res)=>{
                        handlerContext.addResource(res);
                    });
                }
                break;
            }
        }
        return mappedConcat(textFragments);
    }
};
install(embedHandler);
async function validateDocumentFromSource(src, engine, errorFn) {
    const result1 = [];
    const reportSet = new Set();
    const nb = await breakQuartoMd(src);
    if (nb.cells.length < 1) {
        return [];
    }
    const firstCell = nb.cells[0];
    let firstContentCellIndex;
    if (firstCell.source.value.startsWith("---")) {
        firstContentCellIndex = 1;
        if (!firstCell.source.value.trimEnd().endsWith("---")) {
            throw new Error("Expected YAML front matter to end with '---'");
        }
        const lineRanges = rangedLines(firstCell.source.value.trimEnd());
        if (lineRanges.length < 2) {
            if (src.map(0)?.originalString?.fileName) {
                throw new Error(`${src.map(0)?.originalString?.fileName}: Expected YAML front matter to contain at least 2 lines`);
            } else {
                throw new Error("Expected front matter to have at least 2 lines");
            }
        }
        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) {
                    result1.push(...fmValidation.errors);
                }
            });
        }
    } else {
        firstContentCellIndex = 0;
    }
    for (const cell of nb.cells.slice(firstContentCellIndex)){
        if (cell.cell_type === "markdown" || cell.cell_type === "raw") {
            continue;
        }
        const lang = cell.cell_type.language;
        try {
            const fullCell = mappedString(cell.sourceVerbatim, [
                {
                    start: lang.length + 6,
                    end: cell.sourceVerbatim.value.length - 3
                }
            ]);
            await partitionCellOptionsMapped(lang, fullCell, true, engine);
        } catch (e) {
            if (e instanceof ValidationError2) {
                error("Validation of YAML cell metadata failed.");
                for (const err of e.validationErrors){
                    console.log(tidyverseFormatError(err.niceError));
                }
                result1.push(...e.validationErrors);
            } else {
                throw e;
            }
        }
    }
    return result1;
}
async function validateDocument(context) {
    if (context.target.markdown.value === "") {
        return [];
    }
    return validateDocumentFromSource(context.target.markdown, context.engine.name, error);
}
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: []
        };
    }
}
function ojsParseError(acornError, ojsSource) {
    const acornMsg = String(acornError).split("\n")[0].trim().replace(/ *\(\d+:\d+\)$/, "");
    const { line, column } = mappedIndexToLineCol(ojsSource)(acornError.pos);
    const errLines = [];
    const ourError = (msg)=>{
        if (msg.length) {
            errLines.push(msg);
        }
    };
    const errMsg = `OJS parsing failed on line ${line + 1}, column ${column + 1}`;
    ourError(errMsg);
    ourError(acornMsg);
    if (acornMsg.endsWith("Unexpected character '#'") && ojsSource.value.slice(acornError.pos, acornError.pos + 2) === "#|") {
        ourError("\n(Did you mean to use '//|' instead?)\n");
    }
    ourError("----- OJS Source:");
    const ojsSourceSplit = ojsSource.value.split("\n");
    for(let i1 = 0; i1 < ojsSourceSplit.length; ++i1){
        ourError(ojsSourceSplit[i1]);
        if (i1 + 1 === acornError.loc.line) {
            ourError(" ".repeat(acornError.loc.column) + "^");
        }
    }
    ourError("-----");
    if (errLines.length) {
        error(errLines.join("\n"));
    }
}
const ojsHasOutputs = (parse)=>{
    let hasOutputs = false;
    ojsSimpleWalker(parse, {
        Cell (node) {
            if (node.id === null) {
                hasOutputs = true;
            }
        }
    });
    return hasOutputs;
};
async function ojsCompile(options) {
    const { markdown, project, ojsBlockLineNumbers } = options;
    const output = await breakQuartoMd(markdown, true);
    const hasOjsDefines = markdown.value.indexOf("ojs_define") !== -1;
    if (!isJavascriptCompatible(options.format) || options.format.metadata?.["ojs-engine"] === false) {
        return {
            markdown: markdown
        };
    }
    const languages = languagesInMarkdown(markdown.value);
    if (options.format.metadata?.["ojs-engine"] !== true && !languages.has("ojs") && !hasOjsDefines) {
        return {
            markdown: markdown
        };
    }
    const projDir = project.isSingleFile ? undefined : project.dir;
    const selfContained = options.format.pandoc?.[kSelfContained] ?? options.format.pandoc?.[kEmbedResources] ?? false;
    const isHtmlMarkdown = isMarkdownOutput(options.format, [
        "gfm",
        "commonmark"
    ]);
    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 = pathWithForwardSlashes(relative2(ojsRuntimeDir, docDir));
    const runtimeToRoot = pathWithForwardSlashes(relative2(ojsRuntimeDir, rootDir));
    const docToRoot = pathWithForwardSlashes(relative2(docDir, rootDir));
    scriptContents.push(`if (window.location.protocol === "file:") { alert("The OJS runtime does not work with file:// URLs. Please use a web server to view this document."); }`);
    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 cell of output.cells){
        const errorVal = cell.options?.[kError] ?? options.format.execute?.[kError] ?? false;
        const handleOJSCell = async (cell, mdClassList)=>{
            const cellSrcStr = cell.source;
            const bumpOjsCellIdString = ()=>{
                ojsCellID += 1;
                return `ojs-cell-${ojsCellID}`;
            };
            const ojsId = bumpOjsCellIdString();
            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 if (cell.options?.[kCellFigCap] || cell.options?.[kCellFigSubCap] || cell.options?.[kCellLstCap]) {
                    return chooseId(`fig-${ojsId}`);
                } else {
                    return undefined;
                }
            };
            const userId = userCellId();
            const attrs = [];
            const hasFigureSubCaptions = ()=>{
                return cell.options?.[kCellFigSubCap];
            };
            const cellStartingLoc = ojsBlockLineNumbers[ojsBlockIndex++] || 0;
            if (cellStartingLoc === 0) {
                warn("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 = pandocCode({
                    classes: [
                        "numberLines",
                        "java"
                    ],
                    attrs: [
                        `startFrom="${cellStartingLoc - 1}"`,
                        `syntax-error-position="${err.pos}"`,
                        `source-offset="${cell.sourceOffset}"`
                    ]
                });
                preDiv.push(pandocRawStr(cell.sourceVerbatim.value.trim()));
                div.push(preDiv);
                const errMsgDiv = pandocDiv({
                    classes: [
                        "cell-output",
                        "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 = [];
            let hasOutputs = true;
            try {
                const parse = parseModule(cellSrcStr.value);
                hasOutputs = ojsHasOutputs(parse);
                let info = [];
                const flushSeqSrc = ()=>{
                    parsedCells.push({
                        info
                    });
                    for(let i1 = 1; i1 < info.length; ++i1){
                        parsedCells.push({
                            info: []
                        });
                    }
                    info = [];
                };
                ojsSimpleWalker(parse, {
                    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") {
                            info.push({
                                start: node.start,
                                end: node.end,
                                cellType: "expression"
                            });
                            flushSeqSrc();
                        } else {
                            info.push({
                                start: node.start,
                                end: node.end,
                                cellType: "declaration"
                            });
                        }
                    }
                });
                nCells = parse.cells.length;
                if (info.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";
                }
            };
            let outputVal = cell.options?.[kOutput] ?? options.format.execute[kOutput];
            outputVal = outputVal ?? true;
            if (outputVal === "all" || outputVal === "asis") {
                attrs.push(`output="${outputVal}"`);
            }
            const { classes, attrs: otherAttrs } = getDivAttributes(cell.options || {});
            attrs.push(...otherAttrs);
            const evalVal = cell.options?.[kEval] ?? options.format.execute[kEval] ?? true;
            const echoVal = cell.options?.[kEcho] ?? options.format.execute[kEcho] ?? true;
            const ojsCellClasses = [
                "cell"
            ];
            if (!outputVal) {
                ojsCellClasses.push("hidden");
            }
            const div = pandocDiv({
                id: idPlacement() === "outer" ? userId : undefined,
                classes: [
                    ...ojsCellClasses,
                    ...classes
                ],
                attrs
            });
            const includeVal = cell.options?.[kInclude] ?? options.format.execute[kInclude] ?? true;
            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?.[kCodeSummary]) {
                srcAttrs.push(`${kCodeSummary}="${__VIRTUAL_FILE172(cell.options?.[kCodeSummary])}"`);
            }
            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",
                "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 = pandocCode({
                    classes: ourClasses,
                    attrs: ourAttrs
                });
                srcDiv.push(pandocRawStr(cell.sourceVerbatim.value.trim()));
                div.push(srcDiv);
            }
            const shouldEmitSource = echoVal !== "fenced" && !(echoVal === false && isHtmlMarkdown);
            const makeSubFigures = (specs)=>{
                let subfigIx = 1;
                const cellInfo = [].concat(...parsedCells.map((n)=>n.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).trim()));
                        div.push(srcDiv);
                    }
                    subfigIx++;
                    outputDiv.push(outputInnerDiv);
                    outputInnerDiv.push(ojsDiv);
                    if (spec.caption) {
                        outputInnerDiv.push(pandocRawStr(spec.caption));
                    }
                    div.push(outputDiv);
                }
            };
            if (!hasFigureSubCaptions() && hasManyRowsCols()) {
                const cellCount = Math.max(nRow() * nCol(), nCells, 1);
                const specs = [];
                for(let i1 = 0; i1 < cellCount; ++i1){
                    specs.push({
                        caption: ""
                    });
                }
                makeSubFigures(specs);
                if (cell.options?.[kCellFigCap]) {
                    div.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]) {
                    div.push(pandocRawStr(cell.options[kCellFigCap]));
                }
            } else {
                if (parsedCells.length === 0) {
                    throw new Error(`Fatal: OJS cell starting on line ${cellStartingLoc} is empty. OJS cells require at least one declaration.`);
                }
                const innerInfo = parsedCells[0].info;
                if (innerInfo.length > 0 && srcConfig !== undefined) {
                    const ourAttrs = srcConfig.attrs.slice();
                    ourAttrs.push(`startFrom="${cellStartingLoc + cell.sourceStartLine - 1}"`);
                    ourAttrs.push(`source-offset="0"`);
                    if (shouldEmitSource) {
                        const srcDiv = pandocCode({
                            attrs: ourAttrs,
                            classes: srcConfig.classes
                        });
                        srcDiv.push(pandocRawStr(mappedTrim(cellSrcStr)));
                        div.push(srcDiv);
                    }
                }
                const outputDiv = pandocDiv({
                    id: idPlacement() === "inner" ? userId : undefined,
                    classes: outputCellClasses
                });
                div.push(outputDiv);
                outputDiv.push(pandocDiv({
                    id: ojsId,
                    attrs: [
                        `nodetype="${innerInfo[0].cellType}"`
                    ]
                }));
                if (cell.options?.[kCellFigCap]) {
                    outputDiv.push(pandocRawStr(cell.options[kCellFigCap]));
                }
            }
            div.emit(ls);
        };
        if (cell.cell_type === "raw") {
            ls.push(cell.sourceVerbatim);
        } else if (cell.cell_type === "markdown") {
            const markdown = executeInlineCodeHandlerMapped("ojs", (exec)=>"${" + exec + "}")(cell.sourceVerbatim);
            ls.push(markdown);
        } else if (cell.cell_type?.language === "ojs") {
            await handleOJSCell(cell);
        } else {
            ls.push(cell.sourceVerbatim);
        }
    }
    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, def)=>{
        if (!serverMetadata || serverMetadata["type"] !== "shiny" || !serverMetadata[key]) {
            return def;
        }
        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 el of ojsIdentifiers){
            resultSet.add(el);
        }
    }
    if (importAllViews) {
        for (const el of ojsViews){
            resultSet.add(el);
        }
    }
    for (const el of shinyInputs){
        resultSet.add(el);
    }
    for (const el of shinyInputExcludes){
        resultSet.delete(el);
    }
    for (const el of resultSet){
        moduleContents.push({
            methodName: "interpretQuiet",
            source: `shinyInput('${el}')`
        });
    }
    for (const el of shinyOutputMetadata){
        moduleContents.push({
            methodName: "interpretQuiet",
            source: `${el} = shinyOutput('${el}')`
        });
    }
    scriptContents.push("window._ojs.runtime.interpretFromScriptTags();");
    const afterBody = [
        `<script type="ojs-module-contents">`,
        encodeBase64(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, project);
    const ojsBundleTempFiles = [];
    if (selfContained) {
        const ojsBundleFilename = join2(quartoConfig.sharePath(), "formats/html/ojs/quarto-ojs-runtime.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: join3(ls, ""),
        filters: [
            "ojs"
        ],
        includes: {
            [kIncludeInHeader]: includeInHeader,
            [kIncludeAfterBody]: [
                includeAfterBodyFile
            ]
        },
        resourceFiles
    };
}
async function ojsExecuteResult(context, executeResult, ojsBlockLineNumbers) {
    executeResult = cloneDeep1(executeResult);
    const { markdown, includes, filters, resourceFiles } = await ojsCompile({
        source: context.target.source,
        format: context.format,
        markdown: executeResult.markdown,
        libDir: context.libDir,
        project: context.project,
        temp: context.options.services.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 || []
    };
}
function asUndefined(value, test) {
    if (value === test) {
        return undefined;
    }
    return value;
}
function ojsFormatDependency(selfContained) {
    const ojsResource = (resource)=>formatResourcePath("html", join2("ojs", resource));
    const ojsDependency = (resource, attribs)=>({
            name: resource,
            path: ojsResource(resource),
            attribs
        });
    const scripts = selfContained ? [] : [
        ojsDependency("quarto-ojs-runtime.js", {
            type: "module"
        })
    ];
    return {
        name: "quarto-ojs",
        stylesheets: [
            ojsDependency("quarto-ojs.css")
        ],
        scripts
    };
}
const base64abc1 = [
    "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(data) {
    const uint8 = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
    let result1 = "", i1;
    const l1 = uint8.length;
    for(i1 = 2; i1 < l1; i1 += 3){
        result1 += base64abc1[uint8[i1 - 2] >> 2];
        result1 += base64abc1[(uint8[i1 - 2] & 0x03) << 4 | uint8[i1 - 1] >> 4];
        result1 += base64abc1[(uint8[i1 - 1] & 0x0f) << 2 | uint8[i1] >> 6];
        result1 += base64abc1[uint8[i1] & 0x3f];
    }
    if (i1 === l1 + 1) {
        result1 += base64abc1[uint8[i1 - 2] >> 2];
        result1 += base64abc1[(uint8[i1 - 2] & 0x03) << 4];
        result1 += "==";
    }
    if (i1 === l1) {
        result1 += base64abc1[uint8[i1 - 2] >> 2];
        result1 += base64abc1[(uint8[i1 - 2] & 0x03) << 4 | uint8[i1 - 1] >> 4];
        result1 += base64abc1[(uint8[i1 - 1] & 0x0f) << 2];
        result1 += "=";
    }
    return result1;
}
const ESC = "\x1B";
const CSI = `${ESC}[`;
const OSC = `${ESC}]`;
const SEP = ";";
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 i1 = 0; i1 < count; i1++){
        clear += eraseLine + (i1 < 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",
        SEP,
        SEP,
        url,
        bel,
        text,
        OSC,
        "8",
        SEP,
        SEP,
        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();
const encoder2 = new TextEncoder();
function factory() {
    let result1 = [];
    let stack = [];
    const ansi = function(...args) {
        if (this) {
            if (args.length) {
                update(args);
                return this;
            }
            return this.toString();
        }
        return factory();
    };
    ansi.text = function(text) {
        stack.push([
            text,
            []
        ]);
        return this;
    };
    ansi.toArray = function() {
        update();
        const ret = result1;
        result1 = [];
        return ret;
    };
    ansi.toString = function() {
        return this.toArray().join("");
    };
    ansi.bytes = function() {
        return encoder2.encode(this.toString());
    };
    const methodList = Object.entries(mod3);
    for (const [name, method] of methodList){
        Object.defineProperty(ansi, name, {
            get () {
                stack.push([
                    method,
                    []
                ]);
                return this;
            }
        });
    }
    return ansi;
    function update(args) {
        if (!stack.length) {
            return;
        }
        if (args) {
            stack[stack.length - 1][1] = args;
        }
        result1.push(...stack.map(([prop, args])=>typeof prop === "string" ? prop : prop.call(ansi, ...args)));
        stack = [];
    }
}
const proto = Object.create(null);
const methodNames = Object.keys(mod1);
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 colors = function(str, ...args) {
        if (typeof str !== "undefined") {
            const lastIndex = stack.length - 1;
            return stack.reduce((str, name, index)=>index === lastIndex ? mod1[name](str, ...args) : mod1[name](str), str);
        }
        const tmp = stack.slice();
        stack = [];
        return factory1(tmp);
    };
    Object.setPrototypeOf(colors, proto);
    colors._stack = stack;
    return colors;
}
const encoder3 = new TextEncoder();
const decoder = new TextDecoder();
function getCursorPosition({ reader = Deno.stdin, writer = Deno.stdout } = {}) {
    const data = new Uint8Array(8);
    reader.setRaw(true);
    writer.writeSync(encoder3.encode(cursorPosition));
    reader.readSync(data);
    reader.setRaw(false);
    const [y, x] = decoder.decode(data).match(/\[(\d+);(\d+)R/)?.slice(1, 3).map(Number) ?? [
        0,
        0
    ];
    return {
        x,
        y
    };
}
const tty = factory2();
const encoder4 = new TextEncoder();
function factory2(options) {
    let result1 = "";
    let stack = [];
    const writer = options?.writer ?? Deno.stdout;
    const reader = options?.reader ?? Deno.stdin;
    const tty = function(...args) {
        if (this) {
            update(args);
            writer.writeSync(encoder4.encode(result1));
            return this;
        }
        return factory2(args[0] ?? options);
    };
    tty.text = function(text) {
        stack.push([
            text,
            []
        ]);
        update();
        writer.writeSync(encoder4.encode(result1));
        return this;
    };
    tty.getCursorPosition = ()=>getCursorPosition({
            writer,
            reader
        });
    const methodList = Object.entries(mod3);
    for (const [name, method] of methodList){
        if (name === "cursorPosition") {
            continue;
        }
        Object.defineProperty(tty, name, {
            get () {
                stack.push([
                    method,
                    []
                ]);
                return this;
            }
        });
    }
    return tty;
    function update(args) {
        if (!stack.length) {
            return;
        }
        if (args) {
            stack[stack.length - 1][1] = args;
        }
        result1 = stack.reduce((prev, [cur, args])=>prev + (typeof cur === "string" ? cur : cur.call(tty, ...args)), "");
        stack = [];
    }
}
const kSpinnerChars = [
    "|",
    "/",
    "-",
    "\\"
];
const kSpinerContainerChars = [
    "(",
    ")"
];
const kSpinerCompleteContainerChars = [
    "[",
    "]"
];
const kSpinnerCompleteChar = Deno.build.os !== "windows" ? "✓" : ">";
const kProgressIncrementChar = "#";
const kProgressContainerChars = [
    "[",
    "]"
];
function progressBar(total, prefixMessage) {
    const isCi = runningInCI();
    if (isCi && prefixMessage) {
        info(prefixMessage);
    }
    const updateProgress = (progress, status)=>{
        if (!isCi) {
            const progressBar = `${asciiProgressBar(progress / total * 100, 35)}`;
            const progressText = `\r${prefixMessage ? prefixMessage + " " : ""}${progressBar}${status ? " " + status : ""}`;
            clearLine();
            info(progressText, {
                newline: false
            });
        }
    };
    return {
        update: updateProgress,
        complete: (finalMsg)=>{
            if (!isCi) {
                clearLine();
            }
            if (typeof finalMsg === "string") {
                if (isCi) {
                    info(finalMsg);
                } else {
                    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 {
        return await op();
    } finally{
        cancel(options.doneMessage);
    }
}
function spinner(status, timeInterval = 100) {
    let spin = 0;
    const statusFn = typeof status === "string" ? ()=>{
        return status;
    } : ()=>{
        if (!runningInCI()) {
            clearLine();
        }
        return status();
    };
    const id = setInterval(()=>{
        const __char = kSpinnerChars[spin % kSpinnerChars.length];
        const msg = `${spinContainer(__char)} ${statusFn()}`;
        if (!runningInCI() || spin === 0) {
            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(statusFn());
            }
        }
    };
}
function spinContainer(body) {
    return `${kSpinerContainerChars[0]}${body}${kSpinerContainerChars[1]}`;
}
function completeMessage(msg) {
    info(`\r${kSpinerCompleteContainerChars[0]}${kSpinnerCompleteChar}${kSpinerCompleteContainerChars[1]} ${msg}`, {
        newline: true
    });
}
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 progressBar = kProgressContainerChars[0];
    for(let i1 = 0; i1 < width; i1++){
        progressBar = progressBar + (i1 < segsComplete ? kProgressIncrementChar : " ");
    }
    progressBar = progressBar + kProgressContainerChars[1];
    return progressBar;
}
function hasTinyTex() {
    const installDir = tinyTexInstallDir();
    if (installDir && existsSync(installDir)) {
        return true;
    } else {
        return false;
    }
}
function tinyTexInstallDir() {
    switch(Deno.build.os){
        case "windows":
            let appDir = getenv("APPDATA", undefined);
            if (!appDir || !appDir.match(/^[!-~]+$/)) {
                appDir = getenv("ProgramData", undefined);
            }
            return expandPath(join2(appDir, "TinyTeX"));
        case "linux":
            return expandPath("~/.TinyTeX");
        case "darwin":
            return expandPath("~/Library/TinyTeX");
        default:
            return undefined;
    }
}
function tinyTexBinDir() {
    const basePath = tinyTexInstallDir();
    if (basePath) {
        switch(Deno.build.os){
            case "windows":
                {
                    const winPath = join2(basePath, "bin\\win32\\");
                    if (safeExistsSync(winPath)) return winPath;
                    return join2(basePath, "bin\\windows\\");
                }
            case "linux":
                return join2(basePath, `bin/${Deno.build.arch}-linux`);
            case "darwin":
                return join2(basePath, "bin/universal-darwin");
            default:
                return undefined;
        }
    } else {
        return undefined;
    }
}
async function texLiveContext(preferTinyTex) {
    const hasTiny = hasTinyTex();
    const hasTex = await hasTexLive();
    const binDir = tinyTexBinDir();
    const usingGlobal = await texLiveInPath() && !hasTiny;
    return {
        preferTinyTex,
        hasTinyTex: hasTiny,
        hasTexLive: hasTex,
        usingGlobal,
        binDir
    };
}
function systemTexLiveContext() {
    return {
        preferTinyTex: false,
        hasTinyTex: false,
        hasTexLive: false,
        usingGlobal: true
    };
}
async function hasTexLive() {
    if (hasTinyTex()) {
        return true;
    } else {
        if (await texLiveInPath()) {
            return true;
        } else {
            return false;
        }
    }
}
async function texLiveInPath() {
    try {
        const systemContext = systemTexLiveContext();
        const result1 = await tlmgrCommand("--version", [], systemContext);
        return result1.code === 0;
    } catch  {
        return false;
    }
}
async function findPackages(searchTerms, context, opts, quiet) {
    const results = [];
    const args = [
        "--file",
        "--global"
    ];
    for (const searchTerm of searchTerms){
        if (!quiet) {
            logProgress(`finding package for ${searchTerm}`);
        }
        if (searchTerm === "fandol") {
            results.push("fandol");
        } else {
            const result1 = await tlmgrCommand("search", [
                ...args,
                ...opts || [],
                searchTerm
            ], context, true);
            if (result1.code === 0 && result1.stdout) {
                const text = result1.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;
                            }
                        }
                    }
                });
            } else {
                const errorMessage = tlMgrError(result1.stderr);
                if (errorMessage) {
                    throw new Error(errorMessage);
                }
            }
        }
    }
    return __VIRTUAL_FILE181(results);
}
function updatePackages(all, self1, context, opts, quiet) {
    const args = [];
    if (opts) {
        args.push(...opts);
    }
    if (all) {
        args.push("--all");
    }
    if (self1) {
        args.push("--self");
    }
    return tlmgrCommand("update", args || [], context, quiet);
}
async function installPackages(pkgs, context, opts, quiet) {
    if (!quiet) {
        logProgress(`> ${pkgs.length} ${pkgs.length === 1 ? "package" : "packages"} to install`);
    }
    let count = 1;
    for (const pkg of pkgs){
        if (!quiet) {
            logProgress(`> installing ${pkg} (${count} of ${pkgs.length})`);
        }
        await installPackage(pkg, context, opts, quiet);
        count = count + 1;
    }
    if (context.usingGlobal) {
        await addPath(context);
    }
}
function addPath(context, opts) {
    return tlmgrCommand("path", [
        "add",
        ...opts || []
    ], context, true);
}
function removePath(context, opts, quiet) {
    return tlmgrCommand("path", [
        "remove",
        ...opts || []
    ], context, quiet);
}
async function installPackage(pkg, context, opts, quiet) {
    let isInstalled = await verifyPackageInstalled(pkg, context);
    if (isInstalled) {
        const updateResult = await updatePackages(true, true, context, opts, quiet);
        if (updateResult.code !== 0) {
            return Promise.reject();
        }
        const fmtutilResult = await fmtutilCommand(context);
        if (fmtutilResult.code !== 0) {
            return Promise.reject();
        }
    }
    let installResult = await tlmgrCommand("install", [
        ...opts || [],
        pkg
    ], context, quiet);
    if (installResult.code !== 0 && installResult.code !== 255) {
        return Promise.reject(`tlmgr returned a non zero status code\n${installResult.stderr}`);
    }
    isInstalled = await verifyPackageInstalled(pkg, context);
    if (!isInstalled) {
        const updateResult = await updatePackages(false, true, context, opts, quiet);
        if (updateResult.code !== 0) {
            return Promise.reject();
        }
        const fmtutilResult = await fmtutilCommand(context);
        if (fmtutilResult.code !== 0) {
            return Promise.reject();
        }
        installResult = await tlmgrCommand("install", [
            ...opts || [],
            pkg
        ], context, quiet);
    }
    return installResult;
}
async function tlVersion(context) {
    try {
        const result1 = await tlmgrCommand("--version", [
            "--machine-readable"
        ], context, true);
        if (result1.success) {
            const versionStr = result1.stdout;
            const match = versionStr && versionStr.match(/tlversion (\d*)/);
            if (match) {
                return match[1];
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    } catch  {
        return undefined;
    }
}
function texLiveCmd(cmd, context) {
    if (context.preferTinyTex && context.hasTinyTex) {
        if (context.binDir) {
            return {
                cmd,
                fullPath: join2(context.binDir, cmd)
            };
        } else {
            return {
                cmd,
                fullPath: cmd
            };
        }
    } else {
        return {
            cmd,
            fullPath: cmd
        };
    }
}
function tlMgrError(msg) {
    if (msg && msg.indexOf("is older than remote repository") > -1) {
        const message = `Your TexLive version is not updated enough to connect to the remote repository and download packages. Please update your installation of TexLive or TinyTex.\n\nUnderlying message:`;
        return `${message} ${msg.replace("\ntlmgr: ", "")}`;
    } else {
        return undefined;
    }
}
async function verifyPackageInstalled(pkg, context, opts) {
    const result1 = await tlmgrCommand("info", [
        "--list",
        "--only-installed",
        "--data",
        "name",
        ...opts || [],
        pkg
    ], context);
    return result1.stdout?.trim() === pkg;
}
function tlmgrCommand(tlmgrCmd, args, context, _quiet) {
    const execTlmgr = (tlmgrCmd)=>{
        return execProcess({
            cmd: tlmgrCmd,
            stdout: "piped",
            stderr: "piped"
        });
    };
    const tlmgr = texLiveCmd("tlmgr", context);
    if (Deno.build.os === "windows") {
        const quoted = requireQuoting(args);
        return safeWindowsExec(tlmgr.fullPath, [
            tlmgrCmd,
            ...quoted.args
        ], execTlmgr);
    } else {
        return execTlmgr([
            tlmgr.fullPath,
            tlmgrCmd,
            ...args
        ]);
    }
}
function fmtutilCommand(context) {
    const fmtutil = texLiveCmd("fmtutil-sys", context);
    return execProcess({
        cmd: [
            fmtutil.fullPath,
            "--all"
        ],
        stdout: "piped",
        stderr: "piped"
    });
}
const kLatexBodyMessageOptions = {
    indent: 2
};
async function hasLatexDistribution() {
    try {
        const result1 = await execProcess({
            cmd: [
                "pdftex",
                "--version"
            ],
            stdout: "piped",
            stderr: "piped"
        });
        return result1.code === 0;
    } catch  {
        return false;
    }
}
const kLatexMkEngineFlags = [
    "-pdf",
    "-pdfdvi",
    "-pdfps",
    "-pdflua",
    "-pdfxe",
    "-pdf-"
];
async function runPdfEngine(input, engine, texLive, outputDir, texInputDirs, pkgMgr, quiet) {
    const [cwd, stem] = dirAndStem(input);
    const targetDir = outputDir ? join2(cwd, outputDir) : cwd;
    const output = join2(targetDir, `${stem}.pdf`);
    const log = join2(targetDir, `${stem}.log`);
    [
        log,
        output
    ].forEach((file)=>{
        if (existsSync(file)) {
            Deno.removeSync(file);
        }
    });
    const computeEngineArgs = ()=>{
        if (engine.pdfEngine === "latexmk") {
            const engineArgs = [
                "-interaction=batchmode",
                "-halt-on-error"
            ];
            if (!engine.pdfEngineOpts || engine.pdfEngineOpts.find((opt)=>{
                return kLatexMkEngineFlags.includes(opt);
            }) === undefined) {
                engineArgs.push("-pdf");
            }
            engineArgs.push("-quiet");
            return engineArgs;
        } else {
            return [
                "-interaction=batchmode",
                "-halt-on-error"
            ];
        }
    };
    const args = computeEngineArgs();
    if (outputDir !== undefined) {
        args.push(`-output-directory=${outputDir}`);
    }
    if (engine.pdfEngineOpts) {
        args.push(...engine.pdfEngineOpts);
    }
    args.push(basename2(input));
    const result1 = await runLatexCommand(engine.pdfEngine, args, {
        pkgMgr,
        cwd,
        texInputDirs,
        texLive
    }, quiet);
    return {
        result: result1,
        output,
        log
    };
}
async function runIndexEngine(input, texLive, engine, args, pkgMgr, quiet) {
    const [cwd, stem] = dirAndStem(input);
    const log = join2(cwd, `${stem}.ilg`);
    if (existsSync(log)) {
        Deno.removeSync(log);
    }
    const result1 = await runLatexCommand(engine || "makeindex", [
        ...args || [],
        basename2(input)
    ], {
        cwd,
        pkgMgr,
        texLive
    }, quiet);
    return {
        result: result1,
        log
    };
}
async function runBibEngine(engine, input, cwd, texLive, pkgMgr, texInputDirs, quiet) {
    const [dir, stem] = dirAndStem(input);
    const log = join2(dir, `${stem}.blg`);
    if (existsSync(log)) {
        Deno.removeSync(log);
    }
    const result1 = await runLatexCommand(engine, [
        input
    ], {
        pkgMgr,
        cwd,
        texInputDirs,
        texLive
    }, quiet);
    return {
        result: result1,
        log
    };
}
async function runLatexCommand(latexCmd, args, context, quiet) {
    const fullLatexCmd = texLiveCmd(latexCmd, context.texLive);
    const runOptions = {
        cmd: [
            fullLatexCmd.fullPath,
            ...args
        ],
        stdout: "piped",
        stderr: "piped"
    };
    if (context.texLive.binDir) {
        runOptions.env = runOptions.env || {};
        runOptions.env["PATH"] = withPath({
            prepend: [
                context.texLive.binDir
            ]
        });
    }
    if (context.cwd) {
        runOptions.cwd = context.cwd;
    }
    if (context.texInputDirs && context.texInputDirs.length > 0) {
        runOptions.env = runOptions.env || {};
        runOptions.env["TEXINPUTS"] = `${context.texInputDirs.join(";")};`;
        runOptions.env["BSTINPUTS"] = `${context.texInputDirs.join(";")};`;
    }
    const runCmd = async ()=>{
        const result1 = await execProcess(runOptions, undefined, "stdout>stderr");
        if (!quiet && result1.stderr) {
            info(result1.stderr, kLatexBodyMessageOptions);
        }
        return result1;
    };
    try {
        return await runCmd();
    } catch (_e) {
        const tex = await hasTexLive() || await hasLatexDistribution();
        if (!tex) {
            info("\nNo TeX installation was detected.\n\nPlease run 'quarto install tinytex' to install TinyTex.\nIf you prefer, you may install TexLive or another TeX distribution.\n");
            return Promise.reject();
        } else if (context.pkgMgr && context.pkgMgr.autoInstall) {
            if (!quiet) {
                logProgress(`command ${latexCmd} not found, attempting install`);
            }
            const packageForCommand = await context.pkgMgr.searchPackages([
                latexCmd
            ]);
            if (packageForCommand) {
                await context.pkgMgr.installPackages(packagesForCommand(latexCmd));
            }
            return await runCmd();
        } else {
            error(`Error executing ${latexCmd}`);
            return Promise.reject();
        }
    }
}
function packagesForCommand(cmd) {
    if (cmd === "texindy") {
        return [
            "xindy"
        ];
    } else {
        return [
            cmd
        ];
    }
}
function packageManager(mkOptions, texLive) {
    let lastPkgs = [];
    return {
        autoInstall: mkOptions.autoInstall === undefined ? true : mkOptions.autoInstall,
        installPackages: async (pkgs)=>{
            const difference = __VIRTUAL_FILE137(pkgs, lastPkgs);
            if (difference.length > 0) {
                await installPackages(pkgs, texLive, mkOptions.engine.tlmgrOpts, mkOptions.quiet);
                lastPkgs = pkgs;
                return true;
            } else {
                return false;
            }
        },
        updatePackages: (all, self1)=>{
            return updatePackages(all, self1, texLive, mkOptions.engine.tlmgrOpts, mkOptions.quiet);
        },
        searchPackages: (searchTerms)=>{
            return findPackages(searchTerms, texLive, 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 unresolvedMatches = 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 !!unresolvedMatches;
        }
    }
    return false;
}
const explicitMatchers = [
    /(Rerun to get | Please \(re\)run | [rR]erun LaTeX\.)/,
    /^No file .*?.aux\.\s*$/gm
];
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 filterLang = (lang)=>{
        if (lang === "ngerman") {
            return "hyphen-german";
        }
        return `hyphen-${lang.toLowerCase()}`;
    };
    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) {
            return filterLang(languageMatch[1]);
        }
    }
    const hyphenRulesRegex = /Package babel Info: Hyphen rules for '(.*?)' set to \\l@nil/m;
    const match = logText.match(hyphenRulesRegex);
    if (match) {
        const language = match[1];
        if (language) {
            return filterLang(language);
        }
    }
}
const kErrorRegex = /^\!\s([\s\S]+)?Here is how much/m;
const kEmptyRegex = /(No pages of output)\./;
function findLatexError(logText, stderr) {
    const errors = [];
    const match = logText.match(kErrorRegex);
    if (match) {
        const hint = suggestHint(logText, stderr);
        if (hint) {
            errors.push(`${match[1]}\n${hint}`);
        } else {
            errors.push(match[1]);
        }
    }
    if (errors.length === 0) {
        const emptyMatch = logText.match(kEmptyRegex);
        if (emptyMatch) {
            errors.push(`${emptyMatch[1]} - the document appears to have produced no output.`);
        }
    }
    return errors.join("\n");
}
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 = join2(dir, kMissingFontLog);
    if (existsSync(missFontLog)) {
        const missFontLogText = Deno.readTextFileSync(missFontLog);
        const fontSearchTerms = findInMissingFontLog(missFontLogText);
        missingFonts.push(...fontSearchTerms);
    }
    return missingFonts;
}
const formatFontFilter = (match, _text)=>{
    const base = basename2(match);
    return fontSearchTerm(base);
};
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: /.* Loading '([^']+)' aborted!.*/g
    },
    {
        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) {
        logProgress("\nRendering PDF");
        logProgress(`running ${mkOptions.engine.pdfEngine} - 1`);
    }
    const [cwd, stem] = dirAndStem(mkOptions.input);
    const workingDir = mkOptions.outputDir ? join2(cwd, mkOptions.outputDir) : cwd;
    if (!existsSync(workingDir)) {
        Deno.mkdirSync(workingDir);
    } else {
        cleanup(workingDir, stem);
    }
    const allowUpdate = await hasTexLive();
    mkOptions.autoInstall = mkOptions.autoInstall && allowUpdate;
    const texLive = await texLiveContext(mkOptions.tinyTex !== false);
    const pkgMgr = packageManager(mkOptions, texLive);
    const response = await initialCompileLatex(mkOptions.input, mkOptions.engine, pkgMgr, texLive, mkOptions.outputDir, mkOptions.texInputDirs, mkOptions.quiet);
    const initialCompileNeedsRerun = needsRecompilation(response.log);
    const indexIntermediateFile = indexIntermediate(workingDir, stem);
    let indexCreated = false;
    if (indexIntermediateFile) {
        info("  Re-compiling document for index");
        await runPdfEngine(mkOptions.input, mkOptions.engine, texLive, mkOptions.outputDir, mkOptions.texInputDirs, pkgMgr, mkOptions.quiet);
        indexCreated = await makeIndexIntermediates(indexIntermediateFile, pkgMgr, texLive, mkOptions.engine.indexEngine, mkOptions.engine.indexEngineOpts, mkOptions.quiet);
    }
    const bibliographyCreated = await makeBibliographyIntermediates(mkOptions.input, mkOptions.engine.bibEngine || "citeproc", pkgMgr, texLive, mkOptions.outputDir, mkOptions.texInputDirs, 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, texLive, mkOptions.outputDir, mkOptions.texInputDirs, mkOptions.quiet);
    }
    if (mkOptions.clean) {
        cleanup(workingDir, stem);
    }
    if (!mkOptions.quiet) {
        info("");
    }
    return mkOptions.outputDir ? join2(mkOptions.outputDir, stem + ".pdf") : join2(cwd, stem + ".pdf");
}
async function initialCompileLatex(input, engine, pkgMgr, texLive, outputDir, texInputDirs, quiet) {
    let packagesUpdated = false;
    while(true){
        const response = await runPdfEngine(input, engine, texLive, outputDir, texInputDirs, 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) {
                    logProgress("updating tlmgr");
                }
                await pkgMgr.updatePackages(false, true);
                info("");
                if (!quiet) {
                    logProgress("updating existing packages");
                }
                await pkgMgr.updatePackages(true, false);
                packagesUpdated = true;
            }
            Deno.readTextFileSync(response.log);
            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(title, log, result1) {
    if (existsSync(log)) {
        const logText = Deno.readTextFileSync(log);
        writeError(title, findLatexError(logText, result1.stderr), log);
    } else {
        writeError(title);
    }
}
function indexIntermediate(dir, stem) {
    const indexFile = join2(dir, `${stem}.idx`);
    if (existsSync(indexFile)) {
        return indexFile;
    } else {
        return undefined;
    }
}
async function makeIndexIntermediates(indexFile, pkgMgr, texLive, engine, args, quiet) {
    if (indexFile) {
        if (!quiet) {
            logProgress("making index");
        }
        try {
            const response = await runIndexEngine(indexFile, texLive, 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 error = findIndexError(logText);
                if (error) {
                    writeError(`error generating index`, error, response.log);
                    return Promise.reject();
                }
            }
            return true;
        } catch  {
            writeError(`error generating index`);
            return Promise.reject();
        }
    } else {
        return false;
    }
}
async function makeBibliographyIntermediates(input, engine, pkgMgr, texLive, outputDir, texInputDirs, 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 ? join2(outputDir, auxBibFile) : auxBibFile;
        const auxBibFullPath = join2(cwd, auxBibPath);
        if (existsSync(auxBibFullPath)) {
            const auxFileData = Deno.readTextFileSync(auxBibFullPath);
            const requiresProcessing = bibCommand === "biber" ? true : containsBiblioData(auxFileData);
            if (requiresProcessing) {
                if (!quiet) {
                    logProgress("generating bibliography");
                }
                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, texLive, pkgMgr, texInputDirs, quiet);
                if (response.result.code !== 0 && pkgMgr.autoInstall) {
                    const log = join2(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) {
    error(`\ncompilation failed- ${primary}`);
    if (secondary) {
        info(secondary);
    }
    if (logFile) {
        info(`see ${logFile} for more information.`);
    }
}
async function recompileLatexUntilComplete(input, engine, pkgMgr, minRuns, maxRuns, texLive, outputDir, texInputDirs, quiet) {
    let runCount = 0;
    minRuns = minRuns - 1;
    while(true){
        if (runCount >= maxRuns) {
            if (!quiet) {
                warn(`maximum number of runs (${maxRuns}) reached`);
            }
            break;
        }
        if (!quiet) {
            logProgress(`running ${engine.pdfEngine} - ${runCount + 2}`);
        }
        const result1 = await runPdfEngine(input, engine, texLive, outputDir, texInputDirs, pkgMgr, quiet);
        if (!result1.result.success) {
            displayError("Error compiling latex", result1.log, result1.result);
            return Promise.reject();
        } else {
            runCount = runCount + 1;
            if (existsSync(result1.log) && needsRecompilation(result1.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)=>join2(workingDir, auxFile(stem, aux)));
    auxFiles.push(join2(workingDir, kMissingFontLog));
    auxFiles.forEach((auxFile)=>{
        if (existsSync(auxFile)) {
            Deno.removeSync(auxFile);
        }
    });
}
function normalizeOutputPath(input, output) {
    if (isAbsolute2(output)) {
        return output;
    } else {
        return relative2(dirname2(input), output);
    }
}
function texToPdfOutputRecipe(input, finalOutput, options, format, pdfIntermediateTo, pdfGenerator, pdfOutputDir) {
    const [inputDir, inputStem] = dirAndStem(input);
    let fixupInputName = "";
    if (format.identifier["target-format"]) {
        const formatDesc = parseFormatString(format.identifier["target-format"]);
        fixupInputName = `${formatDesc.variants.join("")}${formatDesc.modifiers.join("")}`;
    }
    const texStem = texSafeFilename(`${inputStem}${fixupInputName}`);
    const output = texStem + ".tex";
    let args = options.pandocArgs || [];
    const pandoc = {
        ...format.pandoc
    };
    if (options.flags?.output) {
        args = replacePandocOutputArg(args, output);
    } else {
        pandoc[kOutputFile] = output;
    }
    const complete = async (pandocOptions)=>{
        const input = join2(inputDir, output);
        const pdfOutput = await pdfGenerator.generate(input, format, pandocOptions);
        const compileTex = join2(inputDir, output);
        if (!format.render[kKeepTex]) {
            Deno.removeSync(compileTex);
        }
        if (finalOutput) {
            if (finalOutput === kStdOut) {
                writeFileToStdout(pdfOutput);
                Deno.removeSync(pdfOutput);
            } else {
                const outputPdf = expandPath(finalOutput);
                if (normalize2(pdfOutput) !== normalize2(outputPdf)) {
                    ensureDirSync(dirname2(outputPdf));
                    Deno.renameSync(pdfOutput, outputPdf);
                }
            }
            if (pdfOutputDir) {
                try {
                    Deno.removeSync(pdfOutputDir, {
                        recursive: false
                    });
                } catch  {}
            }
            return normalizeOutputPath(input, finalOutput);
        } else {
            return normalizeOutputPath(input, pdfOutput);
        }
    };
    const pdfOutput = finalOutput ? finalOutput === kStdOut ? undefined : normalizeOutputPath(input, finalOutput) : normalizeOutputPath(input, pdfGenerator.computePath(texStem, dirname2(input), format));
    const to = format.pandoc.to === "pdf" ? pdfIntermediateTo : format.pandoc.to;
    return {
        output,
        keepYaml: false,
        args,
        format: {
            ...format,
            pandoc: {
                ...pandoc,
                to
            }
        },
        complete,
        finalOutput: pdfOutput ? relative2(inputDir, pdfOutput) : undefined
    };
}
function useContextPdfOutputRecipe(format, flags) {
    const kContextPdfEngine = "context";
    if (format.pandoc.to === "pdf" && format.render[kOutputExt] === "pdf") {
        const engine = pdfEngine(format.pandoc, format.render, flags);
        return engine.pdfEngine === kContextPdfEngine;
    } else {
        return false;
    }
}
function contextPdfOutputRecipe(input, finalOutput, options, format) {
    const computePath = (stem, dir, _format)=>{
        return join2(dir, stem + ".pdf");
    };
    const generate = async (input, format, pandocOptions)=>{
        const engine = pdfEngine(format.pandoc, format.render, pandocOptions.flags);
        const cmd = [
            "context",
            input
        ];
        if (engine.pdfEngineOpts) {
            cmd.push(...engine.pdfEngineOpts);
        }
        cmd.push("--purgeall", "--batchmode");
        const result1 = await execProcess({
            cmd
        });
        if (result1.success) {
            const [dir, stem] = dirAndStem(input);
            return computePath(stem, dir, format);
        } else {
            throw new Error();
        }
    };
    return texToPdfOutputRecipe(input, finalOutput, options, format, "context", {
        generate,
        computePath
    });
}
function useQuartoLatexmk(format, flags) {
    const to = format.pandoc.to;
    const ext = format.render[kOutputExt] || "html";
    if (format.render[kLatexAutoMk] === false) {
        return false;
    }
    if ([
        "beamer",
        "pdf"
    ].includes(to || "") && ext === "pdf") {
        const engine = pdfEngine(format.pandoc, format.render, flags);
        return isLatexPdfEngine(engine);
    }
    return false;
}
function quartoLatexmkOutputRecipe(input, finalOutput, options, format) {
    const outputDir = format.render[kLatexOutputDir];
    const generate = (input, format, pandocOptions)=>{
        const texInputDirs = [];
        if (format.render[kLatexInputPaths]) {
            texInputDirs.push(...format.render[kLatexInputPaths]);
        }
        const mkOptions = {
            input,
            engine: pdfEngine(format.pandoc, format.render, pandocOptions.flags),
            autoInstall: format.render[kLatexAutoInstall],
            autoMk: format.render[kLatexAutoMk],
            minRuns: format.render[kLatexMinRuns],
            maxRuns: format.render[kLatexMaxRuns],
            tinyTex: format.render[kLatexTinyTex],
            texInputDirs,
            outputDir: outputDir === null ? undefined : outputDir,
            clean: !options.flags?.debug && format.render[kLatexClean] !== false,
            quiet: pandocOptions.flags?.quiet
        };
        return generatePdf(mkOptions);
    };
    const computePath = (texStem, inputDir, format)=>{
        const mkOutputdir = format.render[kLatexOutputDir];
        return mkOutputdir ? join2(mkOutputdir, texStem + ".pdf") : join2(inputDir, texStem + ".pdf");
    };
    return texToPdfOutputRecipe(input, finalOutput, options, format, "latex", {
        generate,
        computePath
    }, outputDir);
}
function typstBinaryPath() {
    return Deno.env.get("QUARTO_TYPST") || architectureToolsPath("typst");
}
function fontPathsArgs(fontPaths) {
    const fontPathsQuarto = [
        "--font-path",
        resourcePath("formats/typst/fonts")
    ];
    const fontPathsEnv = Deno.env.get("TYPST_FONT_PATHS");
    let fontExtrasArgs = [];
    if (fontPaths && fontPaths.length > 0) {
        fontExtrasArgs = fontPaths.map((p)=>[
                "--font-path",
                p
            ]).flat();
    } else if (fontPathsEnv) {
        return fontExtrasArgs = [
            "--font-path",
            fontPathsEnv
        ];
    }
    return fontPathsQuarto.concat(fontExtrasArgs);
}
async function typstCompile(input, output, options = {}) {
    const quiet = options.quiet ?? false;
    const fontPaths = options.fontPaths;
    if (!quiet) {
        typstProgress(input, output);
    }
    const cmd = [
        typstBinaryPath(),
        "compile"
    ];
    if (options.rootDir) {
        cmd.push("--root", options.rootDir);
    }
    cmd.push(input, ...fontPathsArgs(fontPaths), output);
    const result1 = await execProcess({
        cmd
    });
    if (!quiet && result1.success) {
        typstProgressDone();
    }
    return result1;
}
async function typstVersion() {
    const cmd = [
        typstBinaryPath(),
        "--version"
    ];
    try {
        const result1 = await execProcess({
            cmd,
            stdout: "piped",
            stderr: "piped"
        });
        if (result1.success && result1.stdout) {
            const match = result1.stdout.trim().match(/^typst (\d+\.\d+\.\d+)/);
            if (match) {
                return match[1];
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    } catch  {
        return undefined;
    }
}
async function validateRequiredTypstVersion() {
    if (Deno.env.get("QUARTO_TYPST")) {
        const version = await typstVersion();
        if (version) {
            const required = ">=0.8";
            if (!satisfies(version, required)) {
                error("An updated version of the Typst CLI is required for rendering typst documents.\n");
                info(blue(`You are running version ${version} and version ${required} is required.\n`));
                info(blue(`Updating Typst: ${underline("https://github.com/typst/typst#installation")}\n`));
                throw new Error();
            }
        } else {
            error("You need to install the Typst CLI in order to render typst documents.\n");
            info(blue(`Installing Typst: ${underline("https://github.com/typst/typst#installation")}\n`));
            throw new Error();
        }
    }
}
function typstProgress(input, output) {
    info(`[typst]: Compiling ${basename2(input)} to ${basename2(output)}...`, {
        newline: false
    });
}
function typstProgressDone() {
    info("DONE\n");
}
function useTypstPdfOutputRecipe(format) {
    return format.pandoc.to === "typst" && format.render[kOutputExt] === "pdf";
}
function typstPdfOutputRecipe(input, finalOutput, options, format, project) {
    const [inputDir, inputStem] = dirAndStem(input);
    const output = inputStem + ".typ";
    let args = options.pandocArgs || [];
    const pandoc = {
        ...format.pandoc
    };
    if (options.flags?.output) {
        args = replacePandocOutputArg(args, output);
    } else {
        pandoc[kOutputFile] = output;
    }
    const complete = async ()=>{
        const input = join2(inputDir, output);
        await validateRequiredTypstVersion();
        const pdfOutput = join2(inputDir, inputStem + ".pdf");
        const typstOptions = {
            quiet: options.flags?.quiet,
            fontPaths: asArray(format.metadata?.[kFontPaths])
        };
        if (project?.dir) {
            typstOptions.rootDir = project.dir;
        }
        const result1 = await typstCompile(input, pdfOutput, typstOptions);
        if (!result1.success) {
            throw new Error();
        }
        if (!format.render[kKeepTyp]) {
            Deno.removeSync(input);
        }
        if (finalOutput) {
            if (finalOutput === kStdOut) {
                writeFileToStdout(pdfOutput);
                Deno.removeSync(pdfOutput);
            } else {
                const outputPdf = expandPath(finalOutput);
                if (normalize2(pdfOutput) !== normalize2(outputPdf)) {
                    ensureDirSync(dirname2(outputPdf));
                    Deno.renameSync(pdfOutput, outputPdf);
                }
            }
            return normalizeOutputPath(input, finalOutput);
        } else {
            return normalizeOutputPath(input, pdfOutput);
        }
    };
    const pdfOutput = finalOutput ? finalOutput === kStdOut ? undefined : normalizeOutputPath(input, finalOutput) : normalizeOutputPath(input, join2(inputDir, inputStem + ".pdf"));
    const recipe = {
        output,
        keepYaml: false,
        args,
        format: {
            ...format,
            pandoc
        },
        complete,
        finalOutput: pdfOutput ? relative2(inputDir, pdfOutput) : undefined
    };
    if (format.render?.[kVariant]) {
        const to = format.pandoc.to;
        const variant = format.render[kVariant];
        recipe.format = {
            ...recipe.format,
            pandoc: {
                ...recipe.format.pandoc,
                to: `${to}${variant}`
            }
        };
    }
    return recipe;
}
function outputRecipe(context) {
    const input = context.target.input;
    const options = context.options;
    const format = context.format;
    let output = options.flags?.output;
    if (!output) {
        const outputFile = formatOutputFile(format);
        if (outputFile) {
            if (outputFile.match(SEPARATOR_PATTERN2)) {
                throw new Error(`\nIn file ${context.target.source}\n  Invalid value for \`output-file\`: paths are not allowed`);
            }
            output = join2(dirname2(input), outputFile);
        } else {
            output = "";
        }
    }
    if (useQuartoLatexmk(format, options.flags)) {
        return quartoLatexmkOutputRecipe(input, output, options, format);
    } else if (useContextPdfOutputRecipe(format, options.flags)) {
        return contextPdfOutputRecipe(input, output, options, format);
    } else if (useTypstPdfOutputRecipe(format)) {
        return typstPdfOutputRecipe(input, output, options, format, context.project);
    } else {
        const completeActions = [];
        const recipe = {
            output,
            keepYaml: false,
            args: options.pandocArgs || [],
            format: {
                ...format
            },
            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 = format.render[kOutputExt] || "html";
        const [inputDir, inputStem] = dirAndStem(input);
        if (format.render[kVariant]) {
            const to = format.pandoc.to;
            const variant = format.render[kVariant];
            recipe.format = {
                ...recipe.format,
                pandoc: {
                    ...recipe.format.pandoc,
                    to: `${to}${variant}`
                }
            };
            if (recipe.format.pandoc.to?.includes(`+${kYamlMetadataBlock}`)) {
                recipe.keepYaml = true;
            }
        }
        if (recipe.keepYaml || recipe.format.render[kPreserveYaml]) {
            completeActions.push(()=>{
                const inputMd = partitionYamlFrontMatter(context.target.markdown.value);
                if (inputMd) {
                    const outputFile = isAbsolute2(recipe.output) ? recipe.output : join2(dirname2(context.target.input), recipe.output);
                    const output = Deno.readTextFileSync(outputFile);
                    const outputMd = partitionYamlFrontMatter(Deno.readTextFileSync(outputFile));
                    const yaml = parse1(inputMd.yaml.replace(/^---+\n/m, "").replace(/\n---+\n*$/m, "\n"));
                    delete yaml._quarto;
                    const yamlString = `---\n${stringify(yaml)}---\n`;
                    const markdown = outputMd?.markdown || output;
                    Deno.writeTextFileSync(outputFile, yamlString + "\n\n" + markdown);
                }
            });
        }
        if (!recipe.output) {
            let output = inputStem + "." + ext;
            if (extname2(input) === ".md" && ext === "md") {
                output = `${inputStem}-${format.identifier["base-format"]}.md`;
            }
            if (output === basename2(context.target.source)) {
                output = inputStem + `.${kOutExt}.` + ext;
            }
            updateOutput(output);
        } else if (recipe.output === kStdOut) {
            updateOutput(options.services.temp.createFile({
                suffix: "." + ext
            }));
            recipe.isOutputTransient = true;
            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;
    }
}
const kOutExt = "out";
const kProjectFreezeDir = "_freeze";
const kOldFreezeExecuteResults = "execute";
const kFreezeExecuteResults = "execute-results";
function freezeExecuteResult(input, output, result1) {
    result1 = cloneDeep1(result1);
    const resolveIncludes = (name)=>{
        if (result1.includes) {
            if (result1.includes[name]) {
                result1.includes[name] = result1.includes[name].map((file)=>format1(Deno.readTextFileSync(file), LF));
            }
        }
    };
    resolveIncludes(kIncludeInHeader);
    resolveIncludes(kIncludeBeforeBody);
    resolveIncludes(kIncludeAfterBody);
    result1.supporting = result1.supporting.map((file)=>{
        if (isAbsolute2(file)) {
            return relative2(normalizePath(dirname2(input)), file);
        } else {
            return file;
        }
    });
    const hash = freezeInputHash(input);
    const freezeJsonFile = freezeResultFile(input, output, true);
    Deno.writeTextFileSync(freezeJsonFile, JSON.stringify({
        hash,
        result: result1
    }, undefined, 2));
    return freezeJsonFile;
}
function defrostExecuteResult(source, output, temp, force = false) {
    const resultFile = freezeResultFile(source, output);
    if (existsSync(resultFile)) {
        let hash;
        let result1;
        const contents = Deno.readTextFileSync(resultFile);
        try {
            const inp = JSON.parse(contents);
            hash = inp.hash;
            result1 = inp.result;
        } catch (_e) {
            if (contents.match("<<<<<<<") && contents.match(">>>>>>>") && contents.match("=======")) {
                warn(`Error parsing ${resultFile}; it looks possibly like a git merge conflict.`);
            } else {
                warn(`Error parsing ${resultFile}; it may be corrupt.`);
            }
            return;
        }
        if (force || hash === freezeInputHash(source)) {
            result1.supporting = result1.supporting.map((file)=>join2(normalizePath(dirname2(source)), file));
            const resolveIncludes = (name)=>{
                if (result1.includes) {
                    if (result1.includes[name]) {
                        result1.includes[name] = result1.includes[name].map((content)=>{
                            const includeFile = temp.createFile();
                            content = format1(content, EOL);
                            Deno.writeTextFileSync(includeFile, content);
                            return includeFile;
                        });
                    }
                }
            };
            resolveIncludes(kIncludeInHeader);
            resolveIncludes(kIncludeBeforeBody);
            resolveIncludes(kIncludeAfterBody);
            return result1;
        }
    }
}
function projectFreezerDir(dir, hidden) {
    const freezeDir = hidden ? projectScratchPath(dir, kProjectFreezeDir) : join2(dir, kProjectFreezeDir);
    ensureDirSync(freezeDir);
    return normalizePath(freezeDir);
}
function copyToProjectFreezer(project, file, hidden, incremental) {
    const freezerDir = projectFreezerDir(project.dir, hidden);
    const srcFilesDir = join2(project.dir, file);
    const destFilesDir = join2(freezerDir, asFreezerDir(file));
    if (incremental) {
        for (const dir of Deno.readDirSync(srcFilesDir)){
            if (dir.name === kFreezeExecuteResults) {
                const resultsDir = join2(srcFilesDir, dir.name);
                const destResultsDir = join2(destFilesDir, kFreezeExecuteResults);
                ensureDirSync(destResultsDir);
                for (const json of Deno.readDirSync(resultsDir)){
                    if (json.isFile) {
                        copyTo(join2(resultsDir, json.name), join2(destResultsDir, json.name));
                    }
                }
            } else {
                copyMinimal(join2(srcFilesDir, dir.name), join2(destFilesDir, dir.name));
            }
        }
    } else {
        copyMinimal(srcFilesDir, destFilesDir);
    }
}
function copyFromProjectFreezer(project, file, hidden) {
    const freezerDir = projectFreezerDir(project.dir, hidden);
    const srcFilesDir = join2(freezerDir, asFreezerDir(file));
    const destFilesDir = join2(project.dir, file);
    if (existsSync(srcFilesDir)) {
        copyMinimal(srcFilesDir, destFilesDir);
    }
}
function pruneProjectFreezerDir(project, dir, files, hidden) {
    const freezerDir = projectFreezerDir(project.dir, hidden);
    files.map((file)=>{
        const filePath = join2(freezerDir, dir, file);
        safeRemoveIfExists(filePath);
    });
    removeIfEmptyDir(join2(freezerDir, dir));
}
function pruneProjectFreezer(project, hidden) {
    const freezerDir = projectFreezerDir(project.dir, hidden);
    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 join2(project.dir, kProjectFreezeDir, filesDir, kFreezeExecuteResults, basename2(freezeFile));
}
function freezerFigsDir(project, filesDir, figsDir) {
    return join2(project.dir, kProjectFreezeDir, asFreezerDir(filesDir), figsDir);
}
function freezeResultFile(input, output, ensureDir = false) {
    const filesDir = join2(dirname2(input), inputFilesDir(input));
    const freezeDir = join2(filesDir, kFreezeExecuteResults);
    if (ensureDir) {
        ensureDirSync(freezeDir);
    }
    return join2(freezeDir, extname2(output).slice(1) + ".json");
}
function removeFreezeResults(filesDir) {
    const freezeDir = join2(filesDir, kFreezeExecuteResults);
    removeIfExists(freezeDir);
    const oldFreezeDir = join2(filesDir, kOldFreezeExecuteResults);
    removeIfExists(oldFreezeDir);
    if (existsSync(filesDir)) {
        removeIfEmptyDir(filesDir);
    }
}
function freezeInputHash(input) {
    return md5Hash(format1(Deno.readTextFileSync(input), LF));
}
function asFreezerDir(dir) {
    return dir.replace(/_files$/, "");
}
const setExecuteEnvironment = (options)=>{
    if (options.projectDir) {
        Deno.env.set("QUARTO_PROJECT_ROOT", options.projectDir);
        Deno.env.set("QUARTO_DOCUMENT_PATH", dirname2(options.target.source));
    } else {
        if (!options.cwd) {
            throw new InternalError("No project directory or current working directory");
        }
        Deno.env.set("QUARTO_PROJECT_ROOT", options.cwd);
        Deno.env.set("QUARTO_DOCUMENT_PATH", options.cwd);
    }
};
async function renderExecute(context, output, options) {
    const versionConstraint = context.format.metadata[kQuartoRequired];
    if (versionConstraint) {
        const ourVersion = quartoConfig.version();
        let result1;
        try {
            result1 = satisfies(ourVersion, versionConstraint);
        } catch (_e) {
            throw new Error(`In file ${context.target.source}:\nVersion constraint is invalid: ${versionConstraint}.`);
        }
        if (!result1) {
            throw new Error(`in file ${context.target.source}:\nQuarto version ${ourVersion} does not satisfy version constraint ${versionConstraint}.`);
        }
    }
    const { resolveDependencies = 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 = join2(inputDir, filesDir);
    }
    const canFreeze = context.engine.canFreeze && context.format.execute[kExecuteEnabled] !== false;
    if (context.project && !context.project.isSingleFile && !alwaysExecute) {
        const thaw = canFreeze && (context.format.execute[kFreeze] || (context.options.useFreezer ? "auto" : false));
        if (thaw) {
            const hidden = context.format.execute[kFreeze] === false;
            copyFromProjectFreezer(context.project, projRelativeFilesDir, hidden);
            const thawedResult = defrostExecuteResult(context.target.source, output, context.options.services.temp, thaw === true);
            if (thawedResult) {
                const libDir = context.project?.config?.project[kProjectLibDir];
                if (libDir) {
                    copyFromProjectFreezer(context.project, libDir, hidden);
                }
                removeFreezeResults(join2(context.project.dir, projRelativeFilesDir));
                if (context.engine.executeTargetSkipped) {
                    context.engine.executeTargetSkipped(context.target, context.format);
                }
                return thawedResult;
            }
        }
    }
    const figsDir = join2(filesDir, figuresDir(context.format.pandoc.to));
    push("render-execute");
    const executeOptions = {
        target: context.target,
        resourceDir: resourcePath(),
        tempDir: context.options.services.temp.createDir(),
        dependencies: resolveDependencies,
        libDir: context.libDir,
        format: context.format,
        projectDir: context.project?.dir,
        cwd: flags.executeDir || dirname2(normalizePath(context.target.source)),
        params: resolveParams(flags.params, flags.paramsFile),
        quiet: flags.quiet,
        previewServer: context.options.previewServer,
        handledLanguages: languages(),
        project: context.project
    };
    setExecuteEnvironment(executeOptions);
    const executeResult = await context.engine.execute(executeOptions);
    pop();
    if (context.project && !context.project.isSingleFile && 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(join2(context.project.dir, kProjectFreezeDir));
        }
        removeFreezeResults(join2(context.project.dir, projRelativeFilesDir));
    }
    return executeResult;
}
async function renderFiles(files, options, notebookContext, 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 || !!options.quietPandoc;
        const numWidth = String(files.length).length;
        for(let i1 = 0; i1 < files.length; i1++){
            const file = files[i1];
            if (progress) {
                renderProgress(`\r[${String(i1 + 1).padStart(numWidth)}/${files.length}] ${relative2(project.dir, file.path)}`);
            }
            const fileLifetime = await waitUntilNamedLifetime("render-file");
            try {
                await renderFileInternal(fileLifetime, file, options, project, pandocRenderer, files, tempContext, alwaysExecuteFiles, pandocQuiet, notebookContext);
            } finally{
                fileLifetime.cleanup();
            }
        }
        if (progress) {
            info("");
        }
        return await pandocRenderer.onComplete(false, options.flags?.quiet);
    } catch (error) {
        return {
            files: (await pandocRenderer.onComplete(true)).files,
            error: error || new Error()
        };
    } finally{
        tempContext.cleanup();
        if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
            Deno.writeTextFileSync(Deno.env.get("QUARTO_PROFILER_OUTPUT"), JSON.stringify(getData()));
        }
    }
}
async function renderFile(file, options, services, project, enforceProjectFormats = true) {
    const pandocRenderer = defaultPandocRenderer(options, project);
    try {
        options = cloneDeep1(options);
        const pandocQuiet = !!options.quietPandoc;
        const fileLifetime = createNamedLifetime("render-single-file");
        try {
            await renderFileInternal(fileLifetime, file, options, project, pandocRenderer, [
                file
            ], services.temp, [], pandocQuiet, services.notebook, enforceProjectFormats);
        } finally{
            fileLifetime.cleanup();
        }
        return await pandocRenderer.onComplete(false, options.flags?.quiet);
    } catch (error) {
        return {
            files: (await pandocRenderer.onComplete(true)).files,
            error: error || new Error()
        };
    } finally{
        if (Deno.env.get("QUARTO_PROFILER_OUTPUT")) {
            Deno.writeTextFileSync(Deno.env.get("QUARTO_PROFILER_OUTPUT"), JSON.stringify(getData()));
        }
    }
}
async function renderFileInternal(lifetime, file, options, project, pandocRenderer, files, tempContext, alwaysExecuteFiles, pandocQuiet, notebookContext, enforceProjectFormats = true) {
    const outputs = [];
    let contexts;
    try {
        contexts = await renderContexts(file, options, true, notebookContext, project, false, enforceProjectFormats);
        contexts = pandocRenderer.onFilterContexts(file.path, contexts, files, options);
    } catch (e) {
        const { engine, target } = await fileExecutionEngineAndTarget(file.path, options.flags, project);
        const validationResult = await validateDocumentFromSource(target.markdown, engine.name, error);
        if (validationResult.length) {
            throw new RenderInvalidYAMLError();
        } else {
            throw e;
        }
    }
    const mergeHandlerResults = (results, executeResult, context)=>{
        if (results === undefined) {
            return;
        }
        if (executeResult.includes) {
            executeResult.includes = mergeConfigs(executeResult.includes, results.includes);
        } else {
            executeResult.includes = results.includes;
        }
        const extras = resolveDependencies(results.extras, dirname2(context.target.source), context.libDir, tempContext, project);
        if (extras[kIncludeInHeader]) {
            executeResult.includes[kIncludeInHeader] = [
                ...extras[kIncludeInHeader] || [],
                ...executeResult.includes[kIncludeInHeader] || []
            ];
        }
        executeResult.supporting.push(...results.supporting);
    };
    for (const format of Object.keys(contexts)){
        push("render-context");
        const context = __VIRTUAL_FILE107(contexts[format]);
        if (isServerShiny(context.format) && context.project) {
            const src = relative2(context.project?.dir, context.target.source);
            if (projectIsWebsite(context.project)) {
                error(`${src} uses server: shiny so cannot be included in a website project ` + `(shiny documents require a backend server and so can't be published as static web content).`);
                throw new Error();
            } else if (projectOutputDir(context.project) !== normalizePath(context.project.dir) && isServerShinyKnitr(context.format, context.engine.name)) {
                error(`${src} is a knitr engine document that uses server: shiny so cannot be included in a project with an output-dir ` + `(shiny document output must be rendered alongside its source document).`);
                throw new Error();
            }
        }
        const recipe = outputRecipe(context);
        outputs.push({
            path: recipe.finalOutput || recipe.output,
            isTransient: recipe.isOutputTransient,
            format: context.format
        });
        if (context.active) {
            initDayJsPlugins();
            const resolveLang = ()=>{
                const lang = context.format.metadata[kLang] || options.flags?.pandocMetadata?.[kLang];
                if (typeof lang === "string") {
                    return lang;
                } else {
                    return undefined;
                }
            };
            const dateFormatLang = resolveLang();
            if (dateFormatLang) {
                await setDateLocale(dateFormatLang);
            }
            lifetime.attach({
                cleanup () {
                    resetFigureCounter();
                }
            });
            try {
                if (isHtmlCompatible(context.format)) {
                    await initDenoDom();
                }
                const executeOptions = mergeConfigs({
                    alwaysExecute: alwaysExecuteFiles?.includes(file.path)
                }, pandocRenderer.onBeforeExecute(recipe.format));
                const validate = context.format.render?.["validate-yaml"];
                if (validate !== false) {
                    const validationResult = await validateDocument(context);
                    if (validationResult.length) {
                        throw new RenderInvalidYAMLError();
                    }
                }
                const { ojsBlockLineNumbers } = annotateOjsLineNumbers(context);
                const baseExecuteResult = await renderExecute(context, recipe.output, executeOptions);
                let mappedMarkdown;
                withTiming("diff-execute-result", ()=>{
                    if (!isJupyterNotebook(context.target.source)) {
                        mappedMarkdown = mappedDiff(context.target.markdown, baseExecuteResult.markdown);
                    } else {
                        mappedMarkdown = asMappedString(baseExecuteResult.markdown);
                    }
                });
                const resourceFiles = [];
                if (baseExecuteResult.resourceFiles) {
                    resourceFiles.push(...baseExecuteResult.resourceFiles);
                }
                const languageCellHandlerOptions = {
                    name: "",
                    temp: tempContext,
                    format: recipe.format,
                    markdown: mappedMarkdown,
                    context,
                    flags: options.flags || {},
                    stage: "post-engine"
                };
                let unmappedExecuteResult;
                await withTimingAsync("handle-language-cells", async ()=>{
                    const { markdown, results } = await handleLanguageCells(languageCellHandlerOptions);
                    const mappedExecuteResult = {
                        ...baseExecuteResult,
                        markdown
                    };
                    mergeHandlerResults(context.target.preEngineExecuteResults, mappedExecuteResult, context);
                    mergeHandlerResults(results, mappedExecuteResult, context);
                    const { executeResult, resourceFiles: ojsResourceFiles } = await ojsExecuteResult(context, mappedExecuteResult, ojsBlockLineNumbers);
                    resourceFiles.push(...ojsResourceFiles);
                    const keepMd = executionEngineKeepMd(context);
                    if (keepMd && context.format.execute[kKeepMd]) {
                        Deno.writeTextFileSync(keepMd, executeResult.markdown.value);
                    }
                    unmappedExecuteResult = {
                        ...executeResult,
                        markdown: executeResult.markdown.value
                    };
                });
                await ensureNotebookContext(unmappedExecuteResult.markdown, context.options.services, project);
                push("render-pandoc");
                await pandocRenderer.onRender(format, {
                    context,
                    recipe,
                    executeResult: unmappedExecuteResult,
                    resourceFiles
                }, pandocQuiet);
                pop();
            } finally{
                pop();
            }
        }
    }
    await pandocRenderer.onPostProcess(outputs, project);
}
function defaultPandocRenderer(_options, _project) {
    const renderCompletions = [];
    const renderedFiles = [];
    return {
        onFilterContexts: (_file, contexts, _files, _options)=>{
            return contexts;
        },
        onBeforeExecute: (_format)=>({}),
        onRender: async (_format, executedFile, quiet)=>{
            renderCompletions.push(await renderPandoc(executedFile, quiet));
        },
        onPostProcess: async (renderedFormats)=>{
            let completion = renderCompletions.pop();
            while(completion){
                renderedFiles.push(await completion.complete(renderedFormats));
                completion = renderCompletions.pop();
            }
            renderedFiles.reverse();
        },
        onComplete: async ()=>{
            return {
                files: await Promise.resolve(renderedFiles)
            };
        }
    };
}
class RenderInvalidYAMLError extends YAMLValidationError {
    constructor(){
        super("Render failed due to invalid YAML.");
    }
}
const noMutationValidations = (projType, projOutputDir, projDir)=>{
    return [
        {
            val: projType,
            newVal: (context)=>{
                return projectType(context.config?.project?.[kProjectType]);
            },
            msg: "The project type may not be mutated by the pre-render script"
        },
        {
            val: projOutputDir,
            newVal: (context)=>{
                return projectOutputDir(context);
            },
            msg: "The project output-dir may not be mutated by the pre-render script"
        },
        {
            val: projDir,
            newVal: (context)=>{
                return normalizePath(context.dir);
            },
            msg: "The project dir may not be mutated by the pre-render script"
        }
    ];
};
const computeProjectRenderConfig = async (inputs)=>{
    const incremental = !!inputs.files;
    let alwaysExecuteFiles = incremental && !inputs.options.useFreezer ? __VIRTUAL_FILE107(inputs.files) : undefined;
    const normalizeFiles = (targetFiles)=>{
        return targetFiles.map((file)=>{
            const target = isAbsolute2(file) ? file : join2(Deno.cwd(), file);
            if (!existsSync(target)) {
                throw new Error("Render target does not exist: " + file);
            }
            return normalizePath(target);
        });
    };
    if (inputs.files) {
        if (alwaysExecuteFiles) {
            alwaysExecuteFiles = normalizeFiles(alwaysExecuteFiles);
            inputs.files = normalizeFiles(inputs.files);
        } else if (inputs.options.useFreezer) {
            inputs.files = normalizeFiles(inputs.files);
        }
    }
    if (inputs.files && alwaysExecuteFiles && inputs.projType.incrementalRenderAll && await inputs.projType.incrementalRenderAll(inputs.context, inputs.options, inputs.files)) {
        inputs.files = inputs.context.files.input;
        inputs.options = {
            ...inputs.options,
            useFreezer: true
        };
    }
    const renderAll = !inputs.files || inputs.files.length === inputs.context.files.input.length;
    inputs.files = inputs.files || inputs.context.files.input;
    const filesToRender = inputs.files.map((file)=>{
        return {
            path: file
        };
    });
    const projectSupplement = (filesToRender)=>{
        if (inputs.projType.supplementRender && !inputs.options.devServerReload) {
            return inputs.projType.supplementRender(inputs.context, filesToRender, incremental);
        } else {
            return {
                files: []
            };
        }
    };
    const supplements = projectSupplement(filesToRender);
    filesToRender.push(...supplements.files);
    return {
        alwaysExecuteFiles,
        filesToRender,
        options: inputs.options,
        supplements,
        behavior: {
            renderAll,
            incremental
        }
    };
};
const getProjectRenderScripts = async (context)=>{
    const preRenderScripts = [], postRenderScripts = [];
    if (context.config?.project?.[kProjectPreRender]) {
        preRenderScripts.push(...asArray(context.config?.project?.[kProjectPreRender]));
    }
    if (context.config?.project?.[kProjectPostRender]) {
        postRenderScripts.push(...asArray(context.config?.project?.[kProjectPostRender]));
    }
    return {
        preRenderScripts,
        postRenderScripts
    };
};
const mergeExtensionMetadata = async (context, pOptions)=>{
    if (context.config) {
        const extensions = await pOptions.services.extension.extensions(undefined, context.config, context.isSingleFile ? undefined : context.dir, {
            builtIn: false
        });
        const projectMetadata = extensions.map((extension)=>extension.contributes.metadata?.project).filter((project)=>project);
        context.config.project = mergeProjectMetadata(context.config.project, ...projectMetadata);
    }
};
async function renderProject(context, pOptions, pFiles) {
    await mergeExtensionMetadata(context, pOptions);
    const { preRenderScripts, postRenderScripts } = await getProjectRenderScripts(context);
    const projType = projectType(context.config?.project?.[kProjectType]);
    const projOutputDir = projectOutputDir(context);
    const projDir = normalizePath(context.dir);
    let projectRenderConfig = await computeProjectRenderConfig({
        context,
        projType,
        projOutputDir,
        projDir,
        options: pOptions,
        files: pFiles
    });
    await ensureGitignore(context.dir);
    const progress = !!projectRenderConfig.options.progress || projectRenderConfig.filesToRender.length > 1;
    if (projectRenderConfig.behavior.renderAll && hasProjectOutputDir(context) && (projectRenderConfig.options.forceClean || projectRenderConfig.options.flags?.clean == true && projType.cleanOutputDir === true)) {
        const realProjectDir = normalizePath(context.dir);
        if (existsSync(projOutputDir)) {
            const realOutputDir = normalizePath(projOutputDir);
            if (realOutputDir !== realProjectDir && realOutputDir.startsWith(realProjectDir)) {
                removeIfExists(realOutputDir);
            }
        }
        clearProjectIndex(realProjectDir);
    }
    const prePostEnv = {
        "QUARTO_PROJECT_OUTPUT_DIR": projOutputDir,
        ...projectRenderConfig.behavior.renderAll ? {
            QUARTO_PROJECT_RENDER_ALL: "1"
        } : {}
    };
    if (preRenderScripts.length) {
        await runPreRender(projDir, preRenderScripts, progress, !!projectRenderConfig.options.flags?.quiet, {
            ...prePostEnv,
            QUARTO_PROJECT_INPUT_FILES: projectRenderConfig.filesToRender.map((fileToRender)=>fileToRender.path).map((file)=>relative2(projDir, file)).join("\n")
        });
        context = await projectContextForDirectory(context.dir, context.notebookContext, projectRenderConfig.options);
        noMutationValidations(projType, projOutputDir, projDir).some((validation)=>{
            if (!__VIRTUAL_FILE211(validation.newVal(context), validation.val)) {
                throw new Error(`Pre-render script resulted in a project change that is now allowed.\n${validation.msg}`);
            }
        });
        projectRenderConfig = await computeProjectRenderConfig({
            context,
            projType,
            projOutputDir,
            projDir,
            options: pOptions,
            files: pFiles
        });
    }
    if (projType.preRender) {
        await projType.preRender(context);
    }
    const executeDir = context.config?.project?.[kProjectExecuteDir];
    if (projectRenderConfig.options.flags?.executeDir === undefined && executeDir === "project") {
        projectRenderConfig.options = {
            ...projectRenderConfig.options,
            flags: {
                ...projectRenderConfig.options.flags,
                executeDir: projDir
            }
        };
    }
    if (projectRenderConfig.filesToRender.length > 3 && projectRenderConfig.options.flags && projectRenderConfig.options.flags.executeDaemon === undefined) {
        projectRenderConfig.options.flags.executeDaemon = 0;
    }
    const projResults = {
        context,
        baseDir: projDir,
        outputDir: relative2(projDir, projOutputDir),
        files: []
    };
    const outputDir = projResults.outputDir;
    const outputDirAbsolute = outputDir ? join2(projDir, outputDir) : undefined;
    if (outputDirAbsolute) {
        ensureDirSync(outputDirAbsolute);
    }
    const libDir = context.config?.project[kProjectLibDir];
    const resourcesFrom = async (file)=>{
        const partitioned = await partitionedMarkdownForInput(context, file.input);
        const excludeDirs = context ? projectExcludeDirs(context) : [];
        const resourceFiles = resourceFilesFromRenderedFile(projDir, excludeDirs, file, partitioned);
        return resourceFiles;
    };
    const fileResults = await renderFiles(projectRenderConfig.filesToRender, projectRenderConfig.options, context.notebookContext, projectRenderConfig.alwaysExecuteFiles, projType?.pandocRenderer ? projType.pandocRenderer(projectRenderConfig.options, context) : undefined, context);
    const directoryRelocator = (destinationDir)=>{
        return (dir, copy = false)=>{
            const targetDir = join2(destinationDir, dir);
            const srcDir = join2(projDir, dir);
            if (existsSync(srcDir)) {
                if (existsSync(targetDir)) {
                    Deno.removeSync(targetDir, {
                        recursive: true
                    });
                }
                ensureDirSync(dirname2(targetDir));
                if (copy) {
                    copyTo(srcDir, targetDir);
                } else {
                    Deno.renameSync(srcDir, targetDir);
                }
            }
        };
    };
    let moveOutputResult;
    if (outputDirAbsolute) {
        let keepLibsDir = false;
        const fileOperations = [];
        for(let i1 = 0; i1 < fileResults.files.length; i1++){
            const renderedFile = fileResults.files[i1];
            const formatOutputDir = projectFormatOutputDir(renderedFile.format, context, projectType(context.config?.project.type));
            const formatRelocateDir = directoryRelocator(formatOutputDir);
            const moveFormatDir = formatRelocateDir;
            const copyFormatDir = (dir)=>formatRelocateDir(dir, true);
            if (!renderedFile.isTransient) {
                const outputFile = join2(formatOutputDir, renderedFile.file);
                ensureDirSync(dirname2(outputFile));
                Deno.renameSync(join2(projDir, renderedFile.file), outputFile);
            }
            const keepFiles = !!renderedFile.format.execute[kKeepMd] || !!renderedFile.format.render[kKeepTex] || !!renderedFile.format.render[kKeepTyp];
            keepLibsDir = keepLibsDir || keepFiles;
            if (renderedFile.supporting) {
                renderedFile.supporting = renderedFile.supporting.filter((file)=>file !== libDir);
                renderedFile.supporting = renderedFile.supporting.filter((file)=>{
                    return !renderedFile.supporting.some((dir)=>file.startsWith(dir) && file !== dir);
                });
                if (keepFiles) {
                    renderedFile.supporting.forEach((file)=>{
                        fileOperations.push({
                            key: `${file}|copy`,
                            src: file,
                            performOperation: ()=>{
                                copyFormatDir(file);
                            }
                        });
                    });
                } else {
                    renderedFile.supporting.forEach((file)=>{
                        fileOperations.push({
                            key: `${file}|move`,
                            src: file,
                            performOperation: ()=>{
                                moveFormatDir(file);
                                removeIfEmptyDir(dirname2(file));
                            }
                        });
                    });
                }
            }
            if (!keepFiles) {
                const filesDir = join2(projDir, dirname2(renderedFile.file), inputFilesDir(renderedFile.file));
                removeIfEmptyDir(filesDir);
            }
            projResults.files.push({
                isTransient: renderedFile.isTransient,
                input: renderedFile.input,
                markdown: renderedFile.markdown,
                format: renderedFile.format,
                file: renderedFile.file,
                supporting: renderedFile.supporting,
                resourceFiles: await resourcesFrom(renderedFile)
            });
        }
        const uniqOps = __VIRTUAL_FILE210(fileOperations, (op)=>{
            return op.key;
        });
        const sortedOperations = uniqOps.sort((a, b)=>{
            if (a.src === b.src) {
                return 0;
            } else {
                if (isSubdir(a.src, b.src)) {
                    return -1;
                } else {
                    return a.src.localeCompare(b.src);
                }
            }
        });
        if (projType.beforeMoveOutput) {
            moveOutputResult = await projType.beforeMoveOutput(context, projResults.files);
        }
        sortedOperations.forEach((op)=>{
            op.performOperation();
        });
        if (libDir) {
            const libDirFull = join2(context.dir, libDir);
            if (existsSync(libDirFull)) {
                const libsIncremental = !!(projectRenderConfig.behavior.incremental || projectRenderConfig.options.useFreezer);
                const formatLibDirs = projType.formatLibDirs ? projType.formatLibDirs() : [];
                const freezeLibDir = (hidden)=>{
                    copyToProjectFreezer(context, libDir, hidden, false);
                    pruneProjectFreezerDir(context, libDir, formatLibDirs, hidden);
                    pruneProjectFreezer(context, hidden);
                };
                freezeLibDir(true);
                if (existsSync(join2(context.dir, kProjectFreezeDir))) {
                    freezeLibDir(false);
                }
                if (libsIncremental) {
                    for (const lib of Deno.readDirSync(libDirFull)){
                        if (lib.isDirectory) {
                            const copyDir = join2(libDir, lib.name);
                            const srcDir = join2(projDir, copyDir);
                            const targetDir = join2(outputDirAbsolute, copyDir);
                            copyMinimal(srcDir, targetDir);
                            if (!keepLibsDir) {
                                safeRemoveIfExists(srcDir);
                            }
                        }
                    }
                    if (!keepLibsDir) {
                        safeRemoveIfExists(libDirFull);
                    }
                } else {
                    const relocateDir = directoryRelocator(outputDirAbsolute);
                    if (keepLibsDir) {
                        relocateDir(libDir, true);
                    } else {
                        relocateDir(libDir);
                    }
                }
            }
        }
        const outputFiles = projResults.files.map((result1)=>join2(projDir, result1.file));
        projResults.files.forEach((file)=>{
            file.resourceFiles = file.resourceFiles.filter((resource)=>!outputFiles.includes(resource));
        });
        const resourceFilesToCopy = {};
        const projectFormats = {};
        projResults.files.forEach((file)=>{
            if (file.format.identifier[kTargetFormat] && projectFormats[file.format.identifier[kTargetFormat]] === undefined) {
                projectFormats[file.format.identifier[kTargetFormat]] = file.format;
            }
        });
        const isSelfContainedOutput = (format)=>{
            return projType.selfContainedOutput && projType.selfContainedOutput(format);
        };
        Object.values(projectFormats).forEach((format)=>{
            if (isSelfContainedOutput(format)) {
                return;
            }
            const formatOutputDir = projectFormatOutputDir(format, context, projType);
            context.files.resources?.forEach((resource)=>{
                resourceFilesToCopy[resource] = resourceFilesToCopy[resource] || new Set();
                const relativePath = relative2(context.dir, resource);
                resourceFilesToCopy[resource].add(join2(formatOutputDir, relativePath));
            });
        });
        projResults.files.forEach((file)=>{
            if (isSelfContainedOutput(file.format)) {
                return;
            }
            const formatOutputDir = projectFormatOutputDir(file.format, context, projType);
            file.resourceFiles.forEach((file)=>{
                resourceFilesToCopy[file] = resourceFilesToCopy[file] || new Set();
                const relativePath = relative2(projDir, file);
                resourceFilesToCopy[file].add(join2(formatOutputDir, relativePath));
            });
        });
        Object.keys(resourceFilesToCopy).forEach((srcPath)=>{
            const destinationFiles = resourceFilesToCopy[srcPath];
            destinationFiles.forEach((destPath)=>{
                if (existsSync(srcPath)) {
                    if (Deno.statSync(srcPath).isFile) {
                        copyResourceFile(context.dir, srcPath, destPath);
                    }
                } else if (!existsSync(destPath)) {
                    warn(`File '${srcPath}' was not found.`);
                }
            });
        });
    } else {
        for (const result1 of fileResults.files){
            const resourceFiles = await resourcesFrom(result1);
            projResults.files.push({
                input: result1.input,
                markdown: result1.markdown,
                format: result1.format,
                file: result1.file,
                supporting: result1.supporting,
                resourceFiles
            });
        }
    }
    projResults.error = fileResults.error;
    if (!projResults.error) {
        for (const file of projResults.files){
            const path = join2(context.dir, file.input);
            const engine = await fileExecutionEngine(path, projectRenderConfig.options.flags, context);
            if (engine?.postRender) {
                await engine.postRender(file, projResults.context);
            }
        }
        const outputFiles = projResults.files.filter((x)=>!x.isTransient).map((result1)=>{
            const outputDir = projectFormatOutputDir(result1.format, context, projType);
            const file = outputDir ? join2(outputDir, result1.file) : join2(projDir, result1.file);
            return {
                file,
                input: join2(projDir, result1.input),
                format: result1.format,
                resources: result1.resourceFiles,
                supporting: result1.supporting
            };
        });
        if (projType.postRender) {
            await projType.postRender(context, projectRenderConfig.behavior.incremental, outputFiles, moveOutputResult);
        }
        if (postRenderScripts.length) {
            await runPostRender(projDir, postRenderScripts, progress, !!projectRenderConfig.options.flags?.quiet, {
                ...prePostEnv,
                QUARTO_PROJECT_OUTPUT_FILES: outputFiles.map((outputFile)=>relative2(projDir, outputFile.file)).join("\n")
            });
        }
    }
    const supplements = projectRenderConfig.supplements;
    projResults.files.forEach((file)=>{
        if (supplements.files.find((supFile)=>{
            return supFile.path === join2(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, projectRenderConfig.behavior.incremental);
    }
    if (projectRenderConfig.options.forceClean) {
        const scratchDir = join2(projDir, kQuartoScratch);
        if (existsSync(scratchDir)) {
            Deno.removeSync(scratchDir, {
                recursive: true
            });
        }
    }
    return projResults;
}
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);
}
async function runScripts(projDir, scripts, progress, quiet, env) {
    for(let i1 = 0; i1 < scripts.length; i1++){
        const args = parseShellRunCommand(scripts[i1]);
        const script = args[0];
        if (progress && !quiet) {
            info(bold(blue(`${script}`)));
        }
        const handler = handlerForScript(script);
        if (handler) {
            const result1 = await handler.run(script, args.splice(1), undefined, {
                cwd: projDir,
                stdout: quiet ? "piped" : "inherit",
                env
            });
            if (!result1.success) {
                throw new Error();
            }
        } else {
            const result1 = await execProcess({
                cmd: args,
                cwd: projDir,
                stdout: quiet ? "piped" : "inherit",
                env
            });
            if (!result1.success) {
                throw new Error();
            }
        }
    }
    if (scripts.length > 0) {
        info("");
    }
}
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 InternalError("initializer not set!!");
};
async function initState() {
    await initializer();
}
let hasSet = false;
function setInitializer(init) {
    if (hasSet) {
        return;
    }
    initializer = makeInitializer(init);
    hasSet = true;
}
var Module = {};
var wasmBinaryFile;
let wasmInstantiateResolve;
let wasmInstantiatePromise = new Promise((resolve, reject)=>{
    wasmInstantiateResolve = resolve;
});
function setWasmBinaryFile(wbf) {
    wasmBinaryFile = wbf;
}
let init1 = false;
let TreeSitter = function() {
    class Parser {
        constructor(){
            this.initialize();
        }
        initialize() {
            throw new Error("cannot construct a Parser before calling `init()`");
        }
        static async init(moduleOptions) {
            if (init1) return;
            Module = Object.assign({}, Module, moduleOptions);
            var moduleOverrides = {};
            var key;
            for(key in Module){
                if (Module.hasOwnProperty(key)) {
                    moduleOverrides[key] = Module[key];
                }
            }
            var arguments_ = [];
            var thisProgram = './this.program';
            var quit_ = function(status, toThrow) {
                throw toThrow;
            };
            var ENVIRONMENT_IS_DENO = true;
            var read_, readBinary;
            if (ENVIRONMENT_IS_DENO) {
                read_ = function shell_read(filename, binary) {
                    var ret = tryParseAsDataURI(filename);
                    if (ret) {
                        return binary ? ret : ret.toString();
                    }
                    filename = Deno.realPathSync(filename);
                    if (binary) {
                        return Deno.readFileSync(filename);
                    } else {
                        return Deno.readTextFileSync(filename);
                    }
                };
                readBinary = function readBinary(filename) {
                    var ret = read_(filename, true);
                    if (!ret.buffer) {
                        ret = new Uint8Array(ret);
                    }
                    assert(ret.buffer);
                    return ret;
                };
                quit_ = function(status) {
                    Deno.exit(status);
                };
                Module['inspect'] = function() {
                    return '[Emscripten Module object]';
                };
            } else {
                throw new Error('environment detection error');
            }
            var out = Module['print'] || console.log.bind(console);
            var err = Module['printErr'] || console.warn.bind(console);
            for(key in moduleOverrides){
                if (moduleOverrides.hasOwnProperty(key)) {
                    Module[key] = moduleOverrides[key];
                }
            }
            moduleOverrides = null;
            var STACK_ALIGN = 16;
            function alignMemory(size, factor) {
                if (!factor) factor = STACK_ALIGN;
                return Math.ceil(size / factor) * factor;
            }
            function warnOnce(text) {
                if (!warnOnce.shown) warnOnce.shown = {};
                if (!warnOnce.shown[text]) {
                    warnOnce.shown[text] = 1;
                    err(text);
                }
            }
            function convertJsFunctionToWasm(func, sig) {
                if (typeof WebAssembly.Function === "function") {
                    var typeNames = {
                        'i': 'i32',
                        'j': 'i64',
                        'f': 'f32',
                        'd': 'f64'
                    };
                    var type = {
                        parameters: [],
                        results: sig[0] == 'v' ? [] : [
                            typeNames[sig[0]]
                        ]
                    };
                    for(var i1 = 1; i1 < sig.length; ++i1){
                        type.parameters.push(typeNames[sig[i1]]);
                    }
                    return new WebAssembly.Function(type, func);
                }
                var typeSection = [
                    0x01,
                    0x00,
                    0x01,
                    0x60
                ];
                var sigRet = sig.slice(0, 1);
                var sigParam = sig.slice(1);
                var typeCodes = {
                    'i': 0x7f,
                    'j': 0x7e,
                    'f': 0x7d,
                    'd': 0x7c
                };
                typeSection.push(sigParam.length);
                for(var i1 = 0; i1 < sigParam.length; ++i1){
                    typeSection.push(typeCodes[sigParam[i1]]);
                }
                if (sigRet == 'v') {
                    typeSection.push(0x00);
                } else {
                    typeSection = typeSection.concat([
                        0x01,
                        typeCodes[sigRet]
                    ]);
                }
                typeSection[1] = typeSection.length - 2;
                var bytes = new Uint8Array([
                    0x00,
                    0x61,
                    0x73,
                    0x6d,
                    0x01,
                    0x00,
                    0x00,
                    0x00
                ].concat(typeSection, [
                    0x02,
                    0x07,
                    0x01,
                    0x01,
                    0x65,
                    0x01,
                    0x66,
                    0x00,
                    0x00,
                    0x07,
                    0x05,
                    0x01,
                    0x01,
                    0x66,
                    0x00,
                    0x00
                ]));
                var module1 = new WebAssembly.Module(bytes);
                var instance = new WebAssembly.Instance(module1, {
                    'e': {
                        'f': func
                    }
                });
                var wrappedFunc = instance.exports['f'];
                return wrappedFunc;
            }
            var freeTableIndexes = [];
            var functionsInTableMap;
            function getEmptyTableSlot() {
                if (freeTableIndexes.length) {
                    return freeTableIndexes.pop();
                }
                try {
                    wasmTable.grow(1);
                } catch (err) {
                    if (!(err instanceof RangeError)) {
                        throw err;
                    }
                    throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
                }
                return wasmTable.length - 1;
            }
            function addFunctionWasm(func, sig) {
                if (!functionsInTableMap) {
                    functionsInTableMap = new WeakMap();
                    for(var i1 = 0; i1 < wasmTable.length; i1++){
                        var item = wasmTable.get(i1);
                        if (item) {
                            functionsInTableMap.set(item, i1);
                        }
                    }
                }
                if (functionsInTableMap.has(func)) {
                    return functionsInTableMap.get(func);
                }
                var ret = getEmptyTableSlot();
                try {
                    wasmTable.set(ret, func);
                } catch (err) {
                    if (!(err instanceof TypeError)) {
                        throw err;
                    }
                    assert(typeof sig !== 'undefined', 'Missing signature argument to addFunction: ' + func);
                    var wrapped = convertJsFunctionToWasm(func, sig);
                    wasmTable.set(ret, wrapped);
                }
                functionsInTableMap.set(func, ret);
                return ret;
            }
            var setTempRet0 = function(value) {
                value;
            };
            var dynamicLibraries = Module['dynamicLibraries'] || [];
            if (typeof WebAssembly !== 'object') {
                abort('no native wasm support detected');
            }
            function setValue(ptr, value, type, noSafe) {
                type = type || 'i8';
                if (type.charAt(type.length - 1) === '*') type = 'i32';
                switch(type){
                    case 'i1':
                        HEAP8[ptr >> 0] = value;
                        break;
                    case 'i8':
                        HEAP8[ptr >> 0] = value;
                        break;
                    case 'i16':
                        HEAP16[ptr >> 1] = value;
                        break;
                    case 'i32':
                        HEAP32[ptr >> 2] = value;
                        break;
                    case 'i64':
                        tempI64 = [
                            value >>> 0,
                            (tempDouble = value, +Math.abs(tempDouble) >= 1.0 ? tempDouble > 0.0 ? (Math.min(+Math.floor(tempDouble / 4294967296.0), 4294967295.0) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296.0) >>> 0 : 0)
                        ], HEAP32[ptr >> 2] = tempI64[0], HEAP32[ptr + 4 >> 2] = tempI64[1];
                        break;
                    case 'float':
                        HEAPF32[ptr >> 2] = value;
                        break;
                    case 'double':
                        HEAPF64[ptr >> 3] = value;
                        break;
                    default:
                        abort('invalid type for setValue: ' + type);
                }
            }
            function getValue(ptr, type, noSafe) {
                type = type || 'i8';
                if (type.charAt(type.length - 1) === '*') type = 'i32';
                switch(type){
                    case 'i1':
                        return HEAP8[ptr >> 0];
                    case 'i8':
                        return HEAP8[ptr >> 0];
                    case 'i16':
                        return HEAP16[ptr >> 1];
                    case 'i32':
                        return HEAP32[ptr >> 2];
                    case 'i64':
                        return HEAP32[ptr >> 2];
                    case 'float':
                        return HEAPF32[ptr >> 2];
                    case 'double':
                        return HEAPF64[ptr >> 3];
                    default:
                        abort('invalid type for getValue: ' + type);
                }
                return null;
            }
            var wasmMemory;
            var ABORT = false;
            function assert(condition, text) {
                if (!condition) {
                    abort('Assertion failed: ' + text);
                }
            }
            var ALLOC_STACK = 1;
            function allocate(slab, allocator) {
                var ret;
                assert(typeof allocator === 'number', 'allocate no longer takes a type argument');
                assert(typeof slab !== 'number', 'allocate no longer takes a number as arg0');
                if (allocator == ALLOC_STACK) {
                    ret = stackAlloc(slab.length);
                } else {
                    ret = _malloc(slab.length);
                }
                if (slab.subarray || slab.slice) {
                    HEAPU8.set(slab, ret);
                } else {
                    HEAPU8.set(new Uint8Array(slab), ret);
                }
                return ret;
            }
            var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined;
            function UTF8ArrayToString(heap, idx, maxBytesToRead) {
                var endIdx = idx + maxBytesToRead;
                var endPtr = idx;
                while(heap[endPtr] && !(endPtr >= endIdx))++endPtr;
                if (endPtr - idx > 16 && heap.subarray && UTF8Decoder) {
                    return UTF8Decoder.decode(heap.subarray(idx, endPtr));
                } else {
                    var str = '';
                    while(idx < endPtr){
                        var u0 = heap[idx++];
                        if (!(u0 & 0x80)) {
                            str += String.fromCharCode(u0);
                            continue;
                        }
                        var u1 = heap[idx++] & 63;
                        if ((u0 & 0xE0) == 0xC0) {
                            str += String.fromCharCode((u0 & 31) << 6 | u1);
                            continue;
                        }
                        var u2 = heap[idx++] & 63;
                        if ((u0 & 0xF0) == 0xE0) {
                            u0 = (u0 & 15) << 12 | u1 << 6 | u2;
                        } else {
                            if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte 0x' + u0.toString(16) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!');
                            u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heap[idx++] & 63;
                        }
                        if (u0 < 0x10000) {
                            str += String.fromCharCode(u0);
                        } else {
                            var ch = u0 - 0x10000;
                            str += String.fromCharCode(0xD800 | ch >> 10, 0xDC00 | ch & 0x3FF);
                        }
                    }
                }
                return str;
            }
            function UTF8ToString(ptr, maxBytesToRead) {
                return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : '';
            }
            function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
                if (!(maxBytesToWrite > 0)) return 0;
                var startIdx = outIdx;
                var endIdx = outIdx + maxBytesToWrite - 1;
                for(var i1 = 0; i1 < str.length; ++i1){
                    var u = str.charCodeAt(i1);
                    if (u >= 0xD800 && u <= 0xDFFF) {
                        var u1 = str.charCodeAt(++i1);
                        u = 0x10000 + ((u & 0x3FF) << 10) | u1 & 0x3FF;
                    }
                    if (u <= 0x7F) {
                        if (outIdx >= endIdx) break;
                        heap[outIdx++] = u;
                    } else if (u <= 0x7FF) {
                        if (outIdx + 1 >= endIdx) break;
                        heap[outIdx++] = 0xC0 | u >> 6;
                        heap[outIdx++] = 0x80 | u & 63;
                    } else if (u <= 0xFFFF) {
                        if (outIdx + 2 >= endIdx) break;
                        heap[outIdx++] = 0xE0 | u >> 12;
                        heap[outIdx++] = 0x80 | u >> 6 & 63;
                        heap[outIdx++] = 0x80 | u & 63;
                    } else {
                        if (outIdx + 3 >= endIdx) break;
                        if (u >= 0x200000) warnOnce('Invalid Unicode code point 0x' + u.toString(16) + ' encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x1FFFFF).');
                        heap[outIdx++] = 0xF0 | u >> 18;
                        heap[outIdx++] = 0x80 | u >> 12 & 63;
                        heap[outIdx++] = 0x80 | u >> 6 & 63;
                        heap[outIdx++] = 0x80 | u & 63;
                    }
                }
                heap[outIdx] = 0;
                return outIdx - startIdx;
            }
            function stringToUTF8(str, outPtr, maxBytesToWrite) {
                assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
                return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
            }
            function lengthBytesUTF8(str) {
                var len = 0;
                for(var i1 = 0; i1 < str.length; ++i1){
                    var u = str.charCodeAt(i1);
                    if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | str.charCodeAt(++i1) & 0x3FF;
                    if (u <= 0x7F) ++len;
                    else if (u <= 0x7FF) len += 2;
                    else if (u <= 0xFFFF) len += 3;
                    else len += 4;
                }
                return len;
            }
            function AsciiToString(ptr) {
                var str = '';
                while(1){
                    var ch = HEAPU8[ptr++ >> 0];
                    if (!ch) return str;
                    str += String.fromCharCode(ch);
                }
            }
            typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
            function stringToUTF16(str, outPtr, maxBytesToWrite) {
                assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
                assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
                if (maxBytesToWrite === undefined) {
                    maxBytesToWrite = 0x7FFFFFFF;
                }
                if (maxBytesToWrite < 2) return 0;
                maxBytesToWrite -= 2;
                var startPtr = outPtr;
                var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
                for(var i1 = 0; i1 < numCharsToWrite; ++i1){
                    var codeUnit = str.charCodeAt(i1);
                    HEAP16[outPtr >> 1] = codeUnit;
                    outPtr += 2;
                }
                HEAP16[outPtr >> 1] = 0;
                return outPtr - startPtr;
            }
            function allocateUTF8OnStack(str) {
                var size = lengthBytesUTF8(str) + 1;
                var ret = stackAlloc(size);
                stringToUTF8Array(str, HEAP8, ret, size);
                return ret;
            }
            function alignUp(x, multiple) {
                if (x % multiple > 0) {
                    x += multiple - x % multiple;
                }
                return x;
            }
            var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
            function updateGlobalBufferAndViews(buf) {
                buffer = buf;
                Module['HEAP8'] = HEAP8 = new Int8Array(buf);
                Module['HEAP16'] = HEAP16 = new Int16Array(buf);
                Module['HEAP32'] = HEAP32 = new Int32Array(buf);
                Module['HEAPU8'] = HEAPU8 = new Uint8Array(buf);
                Module['HEAPU16'] = HEAPU16 = new Uint16Array(buf);
                Module['HEAPU32'] = HEAPU32 = new Uint32Array(buf);
                Module['HEAPF32'] = HEAPF32 = new Float32Array(buf);
                Module['HEAPF64'] = HEAPF64 = new Float64Array(buf);
            }
            var TOTAL_STACK = 5242880;
            if (Module['TOTAL_STACK']) assert(TOTAL_STACK === Module['TOTAL_STACK'], 'the stack size can no longer be determined at runtime');
            var INITIAL_MEMORY = Module['INITIAL_MEMORY'] || 33554432;
            if (!Object.getOwnPropertyDescriptor(Module, 'INITIAL_MEMORY')) {
                Object.defineProperty(Module, 'INITIAL_MEMORY', {
                    configurable: true,
                    get: function() {
                        abort('Module.INITIAL_MEMORY has been replaced with plain INITIAL_MEMORY (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)');
                    }
                });
            }
            assert(INITIAL_MEMORY >= TOTAL_STACK, 'INITIAL_MEMORY should be larger than TOTAL_STACK, was ' + INITIAL_MEMORY + '! (TOTAL_STACK=' + TOTAL_STACK + ')');
            assert(typeof Int32Array !== 'undefined' && typeof Float64Array !== 'undefined' && Int32Array.prototype.subarray !== undefined && Int32Array.prototype.set !== undefined, 'JS engine does not provide full typed array support');
            if (Module['wasmMemory']) {
                wasmMemory = Module['wasmMemory'];
            } else {
                wasmMemory = new WebAssembly.Memory({
                    'initial': INITIAL_MEMORY / 65536,
                    'maximum': 2147483648 / 65536
                });
            }
            if (wasmMemory) {
                buffer = wasmMemory.buffer;
            }
            INITIAL_MEMORY = buffer.byteLength;
            assert(INITIAL_MEMORY % 65536 === 0);
            updateGlobalBufferAndViews(buffer);
            var wasmTable = new WebAssembly.Table({
                'initial': 21,
                'element': 'anyfunc'
            });
            function writeStackCookie() {
                var max = _emscripten_stack_get_end();
                assert((max & 3) == 0);
                HEAPU32[(max >> 2) + 1] = 0x2135467;
                HEAPU32[(max >> 2) + 2] = 0x89BACDFE;
                HEAP32[0] = 0x63736d65;
            }
            function checkStackCookie() {
                if (ABORT) return;
                var max = _emscripten_stack_get_end();
                var cookie1 = HEAPU32[(max >> 2) + 1];
                var cookie2 = HEAPU32[(max >> 2) + 2];
                if (cookie1 != 0x2135467 || cookie2 != 0x89BACDFE) {
                    abort('Stack overflow! Stack cookie has been overwritten, expected hex dwords 0x89BACDFE and 0x2135467, but received 0x' + cookie2.toString(16) + ' ' + cookie1.toString(16));
                }
                if (HEAP32[0] !== 0x63736d65) abort('Runtime error: The application has corrupted its heap memory area (address zero)!');
            }
            (function() {
                var h16 = new Int16Array(1);
                var h8 = new Int8Array(h16.buffer);
                h16[0] = 0x6373;
                if (h8[0] !== 0x73 || h8[1] !== 0x63) throw 'Runtime error: expected the system to be little-endian! (Run with -s SUPPORT_BIG_ENDIAN=1 to bypass)';
            })();
            var __ATPRERUN__ = [];
            var __ATINIT__ = [];
            var __ATMAIN__ = [];
            var __ATPOSTRUN__ = [];
            var runtimeInitialized = false;
            var runtimeExited = false;
            function preRun() {
                if (Module['preRun']) {
                    if (typeof Module['preRun'] == 'function') Module['preRun'] = [
                        Module['preRun']
                    ];
                    while(Module['preRun'].length){
                        addOnPreRun(Module['preRun'].shift());
                    }
                }
                callRuntimeCallbacks(__ATPRERUN__);
            }
            function initRuntime() {
                checkStackCookie();
                assert(!runtimeInitialized);
                runtimeInitialized = true;
                callRuntimeCallbacks(__ATINIT__);
            }
            function preMain() {
                checkStackCookie();
                callRuntimeCallbacks(__ATMAIN__);
            }
            function exitRuntime() {
                checkStackCookie();
                runtimeExited = true;
            }
            function postRun() {
                checkStackCookie();
                if (Module['postRun']) {
                    if (typeof Module['postRun'] == 'function') Module['postRun'] = [
                        Module['postRun']
                    ];
                    while(Module['postRun'].length){
                        addOnPostRun(Module['postRun'].shift());
                    }
                }
                callRuntimeCallbacks(__ATPOSTRUN__);
            }
            function addOnPreRun(cb) {
                __ATPRERUN__.unshift(cb);
            }
            function addOnInit(cb) {
                __ATINIT__.unshift(cb);
            }
            function addOnPostRun(cb) {
                __ATPOSTRUN__.unshift(cb);
            }
            assert(Math.imul, 'This browser does not support Math.imul(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
            assert(Math.fround, 'This browser does not support Math.fround(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
            assert(Math.clz32, 'This browser does not support Math.clz32(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
            assert(Math.trunc, 'This browser does not support Math.trunc(), build with LEGACY_VM_SUPPORT or POLYFILL_OLD_MATH_FUNCTIONS to add in a polyfill');
            var runDependencies = 0;
            var runDependencyWatcher = null;
            var dependenciesFulfilled = null;
            var runDependencyTracking = {};
            function addRunDependency(id) {
                runDependencies++;
                if (Module['monitorRunDependencies']) {
                    Module['monitorRunDependencies'](runDependencies);
                }
                if (id) {
                    assert(!runDependencyTracking[id]);
                    runDependencyTracking[id] = 1;
                    if (runDependencyWatcher === null && typeof setInterval !== 'undefined') {
                        runDependencyWatcher = setInterval(function() {
                            if (ABORT) {
                                clearInterval(runDependencyWatcher);
                                runDependencyWatcher = null;
                                return;
                            }
                            var shown = false;
                            for(var dep in runDependencyTracking){
                                if (!shown) {
                                    shown = true;
                                    err('still waiting on run dependencies:');
                                }
                                err('dependency: ' + dep);
                            }
                            if (shown) {
                                err('(end of list)');
                            }
                        }, 10000);
                    }
                } else {
                    err('warning: run dependency added without ID');
                }
            }
            function removeRunDependency(id) {
                runDependencies--;
                if (Module['monitorRunDependencies']) {
                    Module['monitorRunDependencies'](runDependencies);
                }
                if (id) {
                    assert(runDependencyTracking[id]);
                    delete runDependencyTracking[id];
                } else {
                    err('warning: run dependency removed without ID');
                }
                if (runDependencies == 0) {
                    if (runDependencyWatcher !== null) {
                        clearInterval(runDependencyWatcher);
                        runDependencyWatcher = null;
                    }
                    if (dependenciesFulfilled) {
                        var callback = dependenciesFulfilled;
                        dependenciesFulfilled = null;
                        callback();
                    }
                }
            }
            Module["preloadedImages"] = {};
            Module["preloadedAudios"] = {};
            Module["preloadedWasm"] = {};
            function abort(what) {
                if (Module['onAbort']) {
                    Module['onAbort'](what);
                }
                what += '';
                err(what);
                ABORT = true;
                1;
                var output = 'abort(' + what + ') at ' + stackTrace();
                what = output;
                var e = new WebAssembly.RuntimeError(what);
                throw e;
            }
            var FS = {
                error: function() {
                    abort('Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with  -s FORCE_FILESYSTEM=1');
                },
                init: function() {
                    FS.error();
                },
                createDataFile: function() {
                    FS.error();
                },
                createPreloadedFile: function() {
                    FS.error();
                },
                createLazyFile: function() {
                    FS.error();
                },
                open: function() {
                    FS.error();
                },
                mkdev: function() {
                    FS.error();
                },
                registerDevice: function() {
                    FS.error();
                },
                analyzePath: function() {
                    FS.error();
                },
                loadFilesFromDB: function() {
                    FS.error();
                },
                ErrnoError: function ErrnoError() {
                    FS.error();
                }
            };
            Module['FS_createDataFile'] = FS.createDataFile;
            Module['FS_createPreloadedFile'] = FS.createPreloadedFile;
            var dataURIPrefix = 'data:application/octet-stream;base64,';
            function isDataURI(filename) {
                return filename.startsWith(dataURIPrefix);
            }
            function createExportWrapper(name, fixedasm) {
                return function() {
                    var displayName = name;
                    var asm = fixedasm;
                    if (!fixedasm) {
                        asm = Module['asm'];
                    }
                    assert(runtimeInitialized, 'native function `' + displayName + '` called before runtime initialization');
                    assert(!runtimeExited, 'native function `' + displayName + '` called after runtime exit (use NO_EXIT_RUNTIME to keep it alive after main() exits)');
                    if (!asm[name]) {
                        assert(asm[name], 'exported native function `' + displayName + '` not found');
                    }
                    return asm[name].apply(null, arguments);
                };
            }
            async function createWasm() {
                var info = {
                    'env': asmLibraryArg,
                    'wasi_snapshot_preview1': asmLibraryArg,
                    'GOT.mem': new Proxy(asmLibraryArg, GOTHandler),
                    'GOT.func': new Proxy(asmLibraryArg, GOTHandler)
                };
                function receiveInstance(instance, module1) {
                    var exports = instance.exports;
                    exports = relocateExports(exports, 1024);
                    Module['asm'] = exports;
                    var metadata = getDylinkMetadata(module1);
                    if (metadata.neededDynlibs) {
                        dynamicLibraries = metadata.neededDynlibs.concat(dynamicLibraries);
                    }
                    mergeLibSymbols(exports, 'main');
                    addOnInit(Module['asm']['__wasm_call_ctors']);
                    removeRunDependency('wasm-instantiate');
                    wasmInstantiateResolve();
                }
                addRunDependency('wasm-instantiate');
                var trueModule = Module;
                function receiveInstantiationResult(result1) {
                    assert(Module === trueModule, 'the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?');
                    trueModule = null;
                    receiveInstance(result1['instance'], result1['module']);
                }
                let wasmModule = new WebAssembly.Module(wasmBinaryFile);
                let wasmInstance = new WebAssembly.Instance(wasmModule, info);
                receiveInstantiationResult({
                    module: wasmModule,
                    instance: wasmInstance
                });
                return {};
            }
            var tempDouble;
            var tempI64;
            var GOT = {};
            var GOTHandler = {
                get: function(obj, symName) {
                    if (!GOT[symName]) {
                        GOT[symName] = new WebAssembly.Global({
                            'value': 'i32',
                            'mutable': true
                        });
                    }
                    return GOT[symName];
                }
            };
            function callRuntimeCallbacks(callbacks) {
                while(callbacks.length > 0){
                    var callback = callbacks.shift();
                    if (typeof callback == 'function') {
                        callback(Module);
                        continue;
                    }
                    var func = callback.func;
                    if (typeof func === 'number') {
                        if (callback.arg === undefined) {
                            wasmTable.get(func)();
                        } else {
                            wasmTable.get(func)(callback.arg);
                        }
                    } else {
                        func(callback.arg === undefined ? null : callback.arg);
                    }
                }
            }
            function demangle(func) {
                warnOnce('warning: build with  -s DEMANGLE_SUPPORT=1  to link in libcxxabi demangling');
                return func;
            }
            function demangleAll(text) {
                var regex = /\b_Z[\w\d_]+/g;
                return text.replace(regex, function(x) {
                    var y = demangle(x);
                    return x === y ? x : y + ' [' + x + ']';
                });
            }
            function getDylinkMetadata(binary) {
                var next = 0;
                function getLEB() {
                    var ret = 0;
                    var mul = 1;
                    while(1){
                        var __byte = binary[next++];
                        ret += (__byte & 0x7f) * mul;
                        mul *= 0x80;
                        if (!(__byte & 0x80)) break;
                    }
                    return ret;
                }
                if (binary instanceof WebAssembly.Module) {
                    var dylinkSection = WebAssembly.Module.customSections(binary, "dylink");
                    assert(dylinkSection.length != 0, 'need dylink section');
                    binary = new Int8Array(dylinkSection[0]);
                } else {
                    var int32View = new Uint32Array(new Uint8Array(binary.subarray(0, 24)).buffer);
                    assert(int32View[0] == 0x6d736100, 'need to see wasm magic number');
                    assert(binary[8] === 0, 'need the dylink section to be first');
                    next = 9;
                    getLEB();
                    assert(binary[next] === 6);
                    next++;
                    assert(binary[next] === 'd'.charCodeAt(0));
                    next++;
                    assert(binary[next] === 'y'.charCodeAt(0));
                    next++;
                    assert(binary[next] === 'l'.charCodeAt(0));
                    next++;
                    assert(binary[next] === 'i'.charCodeAt(0));
                    next++;
                    assert(binary[next] === 'n'.charCodeAt(0));
                    next++;
                    assert(binary[next] === 'k'.charCodeAt(0));
                    next++;
                }
                var customSection = {};
                customSection.memorySize = getLEB();
                customSection.memoryAlign = getLEB();
                customSection.tableSize = getLEB();
                customSection.tableAlign = getLEB();
                var tableAlign = Math.pow(2, customSection.tableAlign);
                assert(tableAlign === 1, 'invalid tableAlign ' + tableAlign);
                var neededDynlibsCount = getLEB();
                customSection.neededDynlibs = [];
                for(var i1 = 0; i1 < neededDynlibsCount; ++i1){
                    var nameLen = getLEB();
                    var nameUTF8 = binary.subarray(next, next + nameLen);
                    next += nameLen;
                    var name = UTF8ArrayToString(nameUTF8, 0);
                    customSection.neededDynlibs.push(name);
                }
                return customSection;
            }
            function jsStackTrace() {
                var error = new Error();
                if (!error.stack) {
                    try {
                        throw new Error();
                    } catch (e) {
                        error = e;
                    }
                    if (!error.stack) {
                        return '(no stack trace available)';
                    }
                }
                return error.stack.toString();
            }
            var runtimeKeepaliveCounter = 0;
            function keepRuntimeAlive() {
                return noExitRuntime || runtimeKeepaliveCounter > 0;
            }
            function asmjsMangle(x) {
                var unmangledSymbols = [
                    'stackAlloc',
                    'stackSave',
                    'stackRestore'
                ];
                return x.indexOf('dynCall_') == 0 || unmangledSymbols.includes(x) ? x : '_' + x;
            }
            function mergeLibSymbols(exports, libName) {
                for(var sym in exports){
                    if (!exports.hasOwnProperty(sym)) {
                        continue;
                    }
                    if (!asmLibraryArg.hasOwnProperty(sym)) {
                        asmLibraryArg[sym] = exports[sym];
                    }
                    var module_sym = asmjsMangle(sym);
                    if (!Module.hasOwnProperty(module_sym)) {
                        Module[module_sym] = exports[sym];
                    }
                }
            }
            var LDSO = {
                nextHandle: 1,
                loadedLibs: {},
                loadedLibNames: {}
            };
            function dynCallLegacy(sig, ptr, args) {
                assert('dynCall_' + sig in Module, 'bad function pointer type - no table for sig \'' + sig + '\'');
                if (args && args.length) {
                    assert(args.length === sig.substring(1).replace(/j/g, '--').length);
                } else {
                    assert(sig.length == 1);
                }
                var f = Module["dynCall_" + sig];
                return args && args.length ? f.apply(null, [
                    ptr
                ].concat(args)) : f.call(null, ptr);
            }
            function dynCall(sig, ptr, args) {
                if (sig.includes('j')) {
                    return dynCallLegacy(sig, ptr, args);
                }
                assert(wasmTable.get(ptr), 'missing table entry in dynCall: ' + ptr);
                return wasmTable.get(ptr).apply(null, args);
            }
            function createInvokeFunction(sig) {
                return function() {
                    var sp = stackSave();
                    try {
                        return dynCall(sig, arguments[0], Array.prototype.slice.call(arguments, 1));
                    } catch (e) {
                        stackRestore(sp);
                        if (e !== e + 0 && e !== 'longjmp') throw e;
                        _setThrew(1, 0);
                    }
                };
            }
            var ___heap_base = 5251008;
            Module["___heap_base"] = ___heap_base;
            function getMemory(size) {
                if (runtimeInitialized) return _malloc(size);
                var ret = ___heap_base;
                var end = ret + size + 15 & -16;
                assert(end <= HEAP8.length, 'failure to getMemory - memory growth etc. is not supported there, call malloc/sbrk directly or increase INITIAL_MEMORY');
                ___heap_base = end;
                GOT['__heap_base'].value = end;
                return ret;
            }
            function isInternalSym(symName) {
                return [
                    '__cpp_exception',
                    '__wasm_apply_data_relocs',
                    '__dso_handle',
                    '__set_stack_limits'
                ].includes(symName);
            }
            function updateGOT(exports) {
                for(var symName in exports){
                    if (isInternalSym(symName)) {
                        continue;
                    }
                    var replace = false;
                    var value = exports[symName];
                    if (symName.startsWith('orig$')) {
                        symName = symName.split('$')[1];
                        replace = true;
                    }
                    if (!GOT[symName]) {
                        GOT[symName] = new WebAssembly.Global({
                            'value': 'i32',
                            'mutable': true
                        });
                    }
                    if (replace || GOT[symName].value == 0) {
                        if (typeof value === 'function') {
                            GOT[symName].value = addFunctionWasm(value);
                        } else if (typeof value === 'number') {
                            GOT[symName].value = value;
                        } else {
                            err("unhandled export type for `" + symName + "`: " + typeof value);
                        }
                    }
                }
            }
            function relocateExports(exports, memoryBase) {
                var relocated = {};
                for(var e in exports){
                    var value = exports[e];
                    if (typeof value === 'object') {
                        value = value.value;
                    }
                    if (typeof value === 'number') {
                        value += memoryBase;
                    }
                    relocated[e] = value;
                }
                updateGOT(relocated);
                return relocated;
            }
            function resolveGlobalSymbol(symName, direct) {
                var sym;
                if (direct) {
                    sym = asmLibraryArg['orig$' + symName];
                }
                if (!sym) {
                    sym = asmLibraryArg[symName];
                }
                if (!sym) {
                    sym = Module[asmjsMangle(symName)];
                }
                if (!sym && symName.startsWith('invoke_')) {
                    sym = createInvokeFunction(symName.split('_')[1]);
                }
                return sym;
            }
            function loadWebAssemblyModule(binary, flags) {
                var metadata = getDylinkMetadata(binary);
                var originalTable = wasmTable;
                function loadModule() {
                    var memAlign = Math.pow(2, metadata.memoryAlign);
                    memAlign = Math.max(memAlign, STACK_ALIGN);
                    var memoryBase = alignMemory(getMemory(metadata.memorySize + memAlign), memAlign);
                    var tableBase = wasmTable.length;
                    wasmTable.grow(metadata.tableSize);
                    for(var i1 = memoryBase; i1 < memoryBase + metadata.memorySize; i1++){
                        HEAP8[i1] = 0;
                    }
                    for(var i1 = tableBase; i1 < tableBase + metadata.tableSize; i1++){
                        wasmTable.set(i1, null);
                    }
                    var moduleExports;
                    function resolveSymbol(sym) {
                        var resolved = resolveGlobalSymbol(sym, false);
                        if (!resolved) {
                            resolved = moduleExports[sym];
                        }
                        assert(resolved, 'undefined symbol `' + sym + '`. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment');
                        return resolved;
                    }
                    var proxyHandler = {
                        'get': function(stubs, prop) {
                            switch(prop){
                                case '__memory_base':
                                    return memoryBase;
                                case '__table_base':
                                    return tableBase;
                            }
                            if (prop in asmLibraryArg) {
                                return asmLibraryArg[prop];
                            }
                            if (!(prop in stubs)) {
                                var resolved;
                                stubs[prop] = function() {
                                    if (!resolved) resolved = resolveSymbol(prop, true);
                                    return resolved.apply(null, arguments);
                                };
                            }
                            return stubs[prop];
                        }
                    };
                    var proxy = new Proxy({}, proxyHandler);
                    var info = {
                        'GOT.mem': new Proxy({}, GOTHandler),
                        'GOT.func': new Proxy({}, GOTHandler),
                        'env': proxy,
                        wasi_snapshot_preview1: proxy
                    };
                    function postInstantiation(instance) {
                        assert(wasmTable === originalTable);
                        for(var i1 = 0; i1 < metadata.tableSize; i1++){
                            var item = wasmTable.get(tableBase + i1);
                            assert(item !== undefined, 'table entry was not filled in');
                            if (item) {
                                functionsInTableMap.set(item, tableBase + i1);
                            }
                        }
                        moduleExports = relocateExports(instance.exports, memoryBase);
                        if (!flags.allowUndefined) {
                            reportUndefinedSymbols();
                        }
                        var init = moduleExports['__wasm_call_ctors'];
                        if (!init) {
                            init = moduleExports['__post_instantiate'];
                        }
                        if (init) {
                            if (runtimeInitialized) {
                                init();
                            } else {
                                __ATINIT__.push(init);
                            }
                        }
                        return moduleExports;
                    }
                    var module1 = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary);
                    var instance = new WebAssembly.Instance(module1, info);
                    return postInstantiation(instance);
                }
                if (flags.loadAsync) {
                    return metadata.neededDynlibs.reduce(function(chain, dynNeeded) {
                        return chain.then(function() {
                            return loadDynamicLibrary(dynNeeded, flags);
                        });
                    }, Promise.resolve()).then(function() {
                        return loadModule();
                    });
                }
                metadata.neededDynlibs.forEach(function(dynNeeded) {
                    loadDynamicLibrary(dynNeeded, flags);
                });
                return loadModule();
            }
            function fetchBinary(url) {
                return fetch(url, {
                    credentials: 'same-origin'
                }).then(function(response) {
                    if (!response['ok']) {
                        throw "failed to load binary file at '" + url + "'";
                    }
                    return response['arrayBuffer']();
                }).then(function(buffer) {
                    return new Uint8Array(buffer);
                });
            }
            function loadDynamicLibrary(lib, flags) {
                if (lib == '__main__' && !LDSO.loadedLibNames[lib]) {
                    LDSO.loadedLibs[-1] = {
                        refcount: Infinity,
                        name: '__main__',
                        module: Module['asm'],
                        global: true
                    };
                    LDSO.loadedLibNames['__main__'] = -1;
                }
                flags = flags || {
                    global: true,
                    nodelete: true
                };
                var handle = LDSO.loadedLibNames[lib];
                var dso;
                if (handle) {
                    dso = LDSO.loadedLibs[handle];
                    if (flags.global && !dso.global) {
                        dso.global = true;
                        if (dso.module !== 'loading') {
                            mergeLibSymbols(dso.module, lib);
                        }
                    }
                    if (flags.nodelete && dso.refcount !== Infinity) {
                        dso.refcount = Infinity;
                    }
                    dso.refcount++;
                    return flags.loadAsync ? Promise.resolve(handle) : handle;
                }
                handle = LDSO.nextHandle++;
                dso = {
                    refcount: flags.nodelete ? Infinity : 1,
                    name: lib,
                    module: 'loading',
                    global: flags.global
                };
                LDSO.loadedLibNames[lib] = handle;
                LDSO.loadedLibs[handle] = dso;
                function loadLibData(libFile) {
                    if (flags.fs) {
                        var libData = flags.fs.readFile(libFile, {
                            encoding: 'binary'
                        });
                        if (!(libData instanceof Uint8Array)) {
                            libData = new Uint8Array(libData);
                        }
                        return flags.loadAsync ? Promise.resolve(libData) : libData;
                    }
                    if (flags.loadAsync) {
                        return fetchBinary(libFile);
                    }
                    return readBinary(libFile);
                }
                function getLibModule() {
                    if (Module['preloadedWasm'] !== undefined && Module['preloadedWasm'][lib] !== undefined) {
                        var libModule = Module['preloadedWasm'][lib];
                        return flags.loadAsync ? Promise.resolve(libModule) : libModule;
                    }
                    if (flags.loadAsync) {
                        return loadLibData(lib).then(function(libData) {
                            return loadWebAssemblyModule(libData, flags);
                        });
                    }
                    return loadWebAssemblyModule(loadLibData(lib), flags);
                }
                function moduleLoaded(libModule) {
                    if (dso.global) {
                        mergeLibSymbols(libModule, lib);
                    }
                    dso.module = libModule;
                }
                if (flags.loadAsync) {
                    return getLibModule().then(function(libModule) {
                        moduleLoaded(libModule);
                        return handle;
                    });
                }
                moduleLoaded(getLibModule());
                return handle;
            }
            function reportUndefinedSymbols() {
                for(var symName in GOT){
                    if (GOT[symName].value == 0) {
                        var value = resolveGlobalSymbol(symName, true);
                        assert(value, 'undefined symbol `' + symName + '`. perhaps a side module was not linked in? if this global was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=1 in the environment');
                        if (typeof value === 'function') {
                            GOT[symName].value = addFunctionWasm(value, value.sig);
                        } else if (typeof value === 'number') {
                            GOT[symName].value = value;
                        } else {
                            assert(false, 'bad export type for `' + symName + '`: ' + typeof value);
                        }
                    }
                }
            }
            function preloadDylibs() {
                if (!dynamicLibraries.length) {
                    reportUndefinedSymbols();
                    return;
                }
                if (!readBinary) {
                    addRunDependency('preloadDylibs');
                    dynamicLibraries.reduce(function(chain, lib) {
                        return chain.then(function() {
                            return loadDynamicLibrary(lib, {
                                loadAsync: true,
                                global: true,
                                nodelete: true,
                                allowUndefined: true
                            });
                        });
                    }, Promise.resolve()).then(function() {
                        removeRunDependency('preloadDylibs');
                        reportUndefinedSymbols();
                    });
                    return;
                }
                dynamicLibraries.forEach(function(lib) {
                    loadDynamicLibrary(lib, {
                        global: true,
                        nodelete: true,
                        allowUndefined: true
                    });
                });
                reportUndefinedSymbols();
            }
            function stackTrace() {
                var js = jsStackTrace();
                if (Module['extraStackTrace']) js += '\n' + Module['extraStackTrace']();
                return demangleAll(js);
            }
            var ___stack_pointer = new WebAssembly.Global({
                'value': 'i32',
                'mutable': true
            }, 5251008);
            function _abort() {
                abort();
            }
            Module["_abort"] = _abort;
            _abort.sig = 'v';
            var _emscripten_get_now = function() {
                return performance.now();
            };
            var _emscripten_get_now_is_monotonic = true;
            function setErrNo(value) {
                HEAP32[___errno_location() >> 2] = value;
                return value;
            }
            function _clock_gettime(clk_id, tp) {
                var now;
                if (clk_id === 0) {
                    now = Date.now();
                } else if ((clk_id === 1 || clk_id === 4) && _emscripten_get_now_is_monotonic) {
                    now = _emscripten_get_now();
                } else {
                    setErrNo(28);
                    return -1;
                }
                HEAP32[tp >> 2] = now / 1000 | 0;
                HEAP32[tp + 4 >> 2] = now % 1000 * 1000 * 1000 | 0;
                return 0;
            }
            _clock_gettime.sig = 'iii';
            function _emscripten_memcpy_big(dest, src, num) {
                HEAPU8.copyWithin(dest, src, src + num);
            }
            function emscripten_realloc_buffer(size) {
                try {
                    wasmMemory.grow(size - buffer.byteLength + 65535 >>> 16);
                    updateGlobalBufferAndViews(wasmMemory.buffer);
                    return 1;
                } catch (e) {
                    console.error('emscripten_realloc_buffer: Attempted to grow heap from ' + buffer.byteLength + ' bytes to ' + size + ' bytes, but got error: ' + e);
                }
            }
            function _emscripten_resize_heap(requestedSize) {
                var oldSize = HEAPU8.length;
                requestedSize = requestedSize >>> 0;
                assert(requestedSize > oldSize);
                var maxHeapSize = 2147483648;
                if (requestedSize > maxHeapSize) {
                    err('Cannot enlarge memory, asked to go up to ' + requestedSize + ' bytes, but the limit is ' + maxHeapSize + ' bytes!');
                    return false;
                }
                for(var cutDown = 1; cutDown <= 4; cutDown *= 2){
                    var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
                    overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
                    var newSize = Math.min(maxHeapSize, alignUp(Math.max(requestedSize, overGrownHeapSize), 65536));
                    var replacement = emscripten_realloc_buffer(newSize);
                    if (replacement) {
                        return true;
                    }
                }
                err('Failed to grow the heap from ' + oldSize + ' bytes to ' + newSize + ' bytes, not enough memory!');
                return false;
            }
            function _exit(status) {
                exit(status);
            }
            _exit.sig = 'vi';
            var SYSCALLS = {
                mappings: {},
                DEFAULT_POLLMASK: 5,
                umask: 511,
                calculateAt: function(dirfd, path, allowEmpty) {
                    if (path[0] === '/') {
                        return path;
                    }
                    var dir;
                    if (dirfd === -100) {
                        dir = FS.cwd();
                    } else {
                        var dirstream = FS.getStream(dirfd);
                        if (!dirstream) throw new FS.ErrnoError(8);
                        dir = dirstream.path;
                    }
                    if (path.length == 0) {
                        if (!allowEmpty) {
                            throw new FS.ErrnoError(44);
                        }
                        return dir;
                    }
                    return PATH.join2(dir, path);
                },
                doStat: function(func, path, buf) {
                    try {
                        var stat = func(path);
                    } catch (e) {
                        if (e && e.node && PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) {
                            return -54;
                        }
                        throw e;
                    }
                    HEAP32[buf >> 2] = stat.dev;
                    HEAP32[buf + 4 >> 2] = 0;
                    HEAP32[buf + 8 >> 2] = stat.ino;
                    HEAP32[buf + 12 >> 2] = stat.mode;
                    HEAP32[buf + 16 >> 2] = stat.nlink;
                    HEAP32[buf + 20 >> 2] = stat.uid;
                    HEAP32[buf + 24 >> 2] = stat.gid;
                    HEAP32[buf + 28 >> 2] = stat.rdev;
                    HEAP32[buf + 32 >> 2] = 0;
                    tempI64 = [
                        stat.size >>> 0,
                        (tempDouble = stat.size, +Math.abs(tempDouble) >= 1.0 ? tempDouble > 0.0 ? (Math.min(+Math.floor(tempDouble / 4294967296.0), 4294967295.0) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296.0) >>> 0 : 0)
                    ], HEAP32[buf + 40 >> 2] = tempI64[0], HEAP32[buf + 44 >> 2] = tempI64[1];
                    HEAP32[buf + 48 >> 2] = 4096;
                    HEAP32[buf + 52 >> 2] = stat.blocks;
                    HEAP32[buf + 56 >> 2] = stat.atime.getTime() / 1000 | 0;
                    HEAP32[buf + 60 >> 2] = 0;
                    HEAP32[buf + 64 >> 2] = stat.mtime.getTime() / 1000 | 0;
                    HEAP32[buf + 68 >> 2] = 0;
                    HEAP32[buf + 72 >> 2] = stat.ctime.getTime() / 1000 | 0;
                    HEAP32[buf + 76 >> 2] = 0;
                    tempI64 = [
                        stat.ino >>> 0,
                        (tempDouble = stat.ino, +Math.abs(tempDouble) >= 1.0 ? tempDouble > 0.0 ? (Math.min(+Math.floor(tempDouble / 4294967296.0), 4294967295.0) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296.0) >>> 0 : 0)
                    ], HEAP32[buf + 80 >> 2] = tempI64[0], HEAP32[buf + 84 >> 2] = tempI64[1];
                    return 0;
                },
                doMsync: function(addr, stream, len, flags, offset) {
                    var buffer = HEAPU8.slice(addr, addr + len);
                    FS.msync(stream, buffer, offset, len, flags);
                },
                doMkdir: function(path, mode) {
                    path = PATH.normalize(path);
                    if (path[path.length - 1] === '/') path = path.substr(0, path.length - 1);
                    FS.mkdir(path, mode, 0);
                    return 0;
                },
                doMknod: function(path, mode, dev) {
                    switch(mode & 61440){
                        case 32768:
                        case 8192:
                        case 24576:
                        case 4096:
                        case 49152:
                            break;
                        default:
                            return -28;
                    }
                    FS.mknod(path, mode, dev);
                    return 0;
                },
                doReadlink: function(path, buf, bufsize) {
                    if (bufsize <= 0) return -28;
                    var ret = FS.readlink(path);
                    var len = Math.min(bufsize, lengthBytesUTF8(ret));
                    var endChar = HEAP8[buf + len];
                    stringToUTF8(ret, buf, bufsize + 1);
                    HEAP8[buf + len] = endChar;
                    return len;
                },
                doAccess: function(path, amode) {
                    if (amode & ~7) {
                        return -28;
                    }
                    var node;
                    var lookup = FS.lookupPath(path, {
                        follow: true
                    });
                    node = lookup.node;
                    if (!node) {
                        return -44;
                    }
                    var perms = '';
                    if (amode & 4) perms += 'r';
                    if (amode & 2) perms += 'w';
                    if (amode & 1) perms += 'x';
                    if (perms && FS.nodePermissions(node, perms)) {
                        return -2;
                    }
                    return 0;
                },
                doDup: function(path, flags, suggestFD) {
                    var suggest = FS.getStream(suggestFD);
                    if (suggest) FS.close(suggest);
                    return FS.open(path, flags, 0, suggestFD, suggestFD).fd;
                },
                doReadv: function(stream, iov, iovcnt, offset) {
                    var ret = 0;
                    for(var i1 = 0; i1 < iovcnt; i1++){
                        var ptr = HEAP32[iov + i1 * 8 >> 2];
                        var len = HEAP32[iov + (i1 * 8 + 4) >> 2];
                        var curr = FS.read(stream, HEAP8, ptr, len, offset);
                        if (curr < 0) return -1;
                        ret += curr;
                        if (curr < len) break;
                    }
                    return ret;
                },
                doWritev: function(stream, iov, iovcnt, offset) {
                    var ret = 0;
                    for(var i1 = 0; i1 < iovcnt; i1++){
                        var ptr = HEAP32[iov + i1 * 8 >> 2];
                        var len = HEAP32[iov + (i1 * 8 + 4) >> 2];
                        var curr = FS.write(stream, HEAP8, ptr, len, offset);
                        if (curr < 0) return -1;
                        ret += curr;
                    }
                    return ret;
                },
                varargs: undefined,
                get: function() {
                    assert(SYSCALLS.varargs != undefined);
                    SYSCALLS.varargs += 4;
                    var ret = HEAP32[SYSCALLS.varargs - 4 >> 2];
                    return ret;
                },
                getStr: function(ptr) {
                    var ret = UTF8ToString(ptr);
                    return ret;
                },
                getStreamFromFD: function(fd) {
                    var stream = FS.getStream(fd);
                    if (!stream) throw new FS.ErrnoError(8);
                    return stream;
                },
                get64: function(low, high) {
                    if (low >= 0) assert(high === 0);
                    else assert(high === -1);
                    return low;
                }
            };
            function _fd_close(fd) {
                try {
                    var stream = SYSCALLS.getStreamFromFD(fd);
                    FS.close(stream);
                    return 0;
                } catch (e) {
                    if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
                    return e.errno;
                }
            }
            _fd_close.sig = 'ii';
            function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
                try {
                    var stream = SYSCALLS.getStreamFromFD(fd);
                    var HIGH_OFFSET = 0x100000000;
                    var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0);
                    var DOUBLE_LIMIT = 0x20000000000000;
                    if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) {
                        return -61;
                    }
                    FS.llseek(stream, offset, whence);
                    tempI64 = [
                        stream.position >>> 0,
                        (tempDouble = stream.position, +Math.abs(tempDouble) >= 1.0 ? tempDouble > 0.0 ? (Math.min(+Math.floor(tempDouble / 4294967296.0), 4294967295.0) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296.0) >>> 0 : 0)
                    ], HEAP32[newOffset >> 2] = tempI64[0], HEAP32[newOffset + 4 >> 2] = tempI64[1];
                    if (stream.getdents && offset === 0 && whence === 0) stream.getdents = null;
                    return 0;
                } catch (e) {
                    if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
                    return e.errno;
                }
            }
            function _fd_write(fd, iov, iovcnt, pnum) {
                try {
                    var stream = SYSCALLS.getStreamFromFD(fd);
                    var num = SYSCALLS.doWritev(stream, iov, iovcnt);
                    HEAP32[pnum >> 2] = num;
                    return 0;
                } catch (e) {
                    if (typeof FS === 'undefined' || !(e instanceof FS.ErrnoError)) abort(e);
                    return e.errno;
                }
            }
            _fd_write.sig = 'iiiii';
            function _setTempRet0(val) {
                setTempRet0(val);
            }
            _setTempRet0.sig = 'vi';
            function _tree_sitter_log_callback(isLexMessage, messageAddress) {
                if (currentLogCallback) {
                    const message = UTF8ToString(messageAddress);
                    currentLogCallback(message, isLexMessage !== 0);
                }
            }
            function _tree_sitter_parse_callback(inputBufferAddress, index, row, column, lengthAddress) {
                var INPUT_BUFFER_SIZE = 10 * 1024;
                var string = currentParseCallback(index, {
                    row: row,
                    column: column
                });
                if (typeof string === 'string') {
                    setValue(lengthAddress, string.length, 'i32');
                    stringToUTF16(string, inputBufferAddress, INPUT_BUFFER_SIZE);
                } else {
                    setValue(lengthAddress, 0, 'i32');
                }
            }
            var ___memory_base = 1024;
            var ___table_base = 1;
            var decodeBase64 = typeof atob === 'function' ? atob : function(input) {
                var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
                var output = '';
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i1 = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
                do {
                    enc1 = keyStr.indexOf(input.charAt(i1++));
                    enc2 = keyStr.indexOf(input.charAt(i1++));
                    enc3 = keyStr.indexOf(input.charAt(i1++));
                    enc4 = keyStr.indexOf(input.charAt(i1++));
                    chr1 = enc1 << 2 | enc2 >> 4;
                    chr2 = (enc2 & 15) << 4 | enc3 >> 2;
                    chr3 = (enc3 & 3) << 6 | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 !== 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 !== 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }while (i1 < input.length)
                return output;
            };
            function intArrayFromBase64(s) {
                try {
                    var decoded = decodeBase64(s);
                    var bytes = new Uint8Array(decoded.length);
                    for(var i1 = 0; i1 < decoded.length; ++i1){
                        bytes[i1] = decoded.charCodeAt(i1);
                    }
                    return bytes;
                } catch (_) {
                    throw new Error('Converting base64 string to bytes failed.');
                }
            }
            function tryParseAsDataURI(filename) {
                if (!isDataURI(filename)) {
                    return undefined;
                }
                return intArrayFromBase64(filename.slice(dataURIPrefix.length));
            }
            var asmLibraryArg = {
                "__heap_base": ___heap_base,
                "__indirect_function_table": wasmTable,
                "__memory_base": ___memory_base,
                "__stack_pointer": ___stack_pointer,
                "__table_base": ___table_base,
                "abort": _abort,
                "clock_gettime": _clock_gettime,
                "emscripten_memcpy_big": _emscripten_memcpy_big,
                "emscripten_resize_heap": _emscripten_resize_heap,
                "exit": _exit,
                "fd_close": _fd_close,
                "fd_seek": _fd_seek,
                "fd_write": _fd_write,
                "memory": wasmMemory,
                "setTempRet0": _setTempRet0,
                "tree_sitter_log_callback": _tree_sitter_log_callback,
                "tree_sitter_parse_callback": _tree_sitter_parse_callback
            };
            await createWasm();
            Module["___wasm_call_ctors"] = createExportWrapper("__wasm_call_ctors");
            Module["_ts_language_symbol_count"] = createExportWrapper("ts_language_symbol_count");
            Module["_ts_language_version"] = createExportWrapper("ts_language_version");
            Module["_ts_language_field_count"] = createExportWrapper("ts_language_field_count");
            Module["_ts_language_symbol_name"] = createExportWrapper("ts_language_symbol_name");
            Module["_ts_language_symbol_for_name"] = createExportWrapper("ts_language_symbol_for_name");
            Module["_ts_language_symbol_type"] = createExportWrapper("ts_language_symbol_type");
            Module["_ts_language_field_name_for_id"] = createExportWrapper("ts_language_field_name_for_id");
            Module["_memcpy"] = createExportWrapper("memcpy");
            Module["_free"] = createExportWrapper("free");
            Module["_calloc"] = createExportWrapper("calloc");
            Module["_ts_parser_delete"] = createExportWrapper("ts_parser_delete");
            Module["_ts_parser_set_language"] = createExportWrapper("ts_parser_set_language");
            Module["_ts_parser_reset"] = createExportWrapper("ts_parser_reset");
            Module["_ts_parser_timeout_micros"] = createExportWrapper("ts_parser_timeout_micros");
            Module["_ts_parser_set_timeout_micros"] = createExportWrapper("ts_parser_set_timeout_micros");
            Module["_ts_query_new"] = createExportWrapper("ts_query_new");
            Module["_ts_query_delete"] = createExportWrapper("ts_query_delete");
            var _malloc = Module["_malloc"] = createExportWrapper("malloc");
            Module["_iswspace"] = createExportWrapper("iswspace");
            Module["_ts_query_pattern_count"] = createExportWrapper("ts_query_pattern_count");
            Module["_ts_query_capture_count"] = createExportWrapper("ts_query_capture_count");
            Module["_ts_query_string_count"] = createExportWrapper("ts_query_string_count");
            Module["_ts_query_capture_name_for_id"] = createExportWrapper("ts_query_capture_name_for_id");
            Module["_ts_query_string_value_for_id"] = createExportWrapper("ts_query_string_value_for_id");
            Module["_ts_query_predicates_for_pattern"] = createExportWrapper("ts_query_predicates_for_pattern");
            Module["_memmove"] = createExportWrapper("memmove");
            Module["_memcmp"] = createExportWrapper("memcmp");
            Module["_ts_tree_copy"] = createExportWrapper("ts_tree_copy");
            Module["_ts_tree_delete"] = createExportWrapper("ts_tree_delete");
            Module["_iswalnum"] = createExportWrapper("iswalnum");
            Module["_ts_init"] = createExportWrapper("ts_init");
            Module["_ts_parser_new_wasm"] = createExportWrapper("ts_parser_new_wasm");
            Module["_ts_parser_enable_logger_wasm"] = createExportWrapper("ts_parser_enable_logger_wasm");
            Module["_ts_parser_parse_wasm"] = createExportWrapper("ts_parser_parse_wasm");
            Module["_ts_language_type_is_named_wasm"] = createExportWrapper("ts_language_type_is_named_wasm");
            Module["_ts_language_type_is_visible_wasm"] = createExportWrapper("ts_language_type_is_visible_wasm");
            Module["_ts_tree_root_node_wasm"] = createExportWrapper("ts_tree_root_node_wasm");
            Module["_ts_tree_edit_wasm"] = createExportWrapper("ts_tree_edit_wasm");
            Module["_ts_tree_get_changed_ranges_wasm"] = createExportWrapper("ts_tree_get_changed_ranges_wasm");
            Module["_ts_tree_cursor_new_wasm"] = createExportWrapper("ts_tree_cursor_new_wasm");
            Module["_ts_tree_cursor_delete_wasm"] = createExportWrapper("ts_tree_cursor_delete_wasm");
            Module["_ts_tree_cursor_reset_wasm"] = createExportWrapper("ts_tree_cursor_reset_wasm");
            Module["_ts_tree_cursor_goto_first_child_wasm"] = createExportWrapper("ts_tree_cursor_goto_first_child_wasm");
            Module["_ts_tree_cursor_goto_next_sibling_wasm"] = createExportWrapper("ts_tree_cursor_goto_next_sibling_wasm");
            Module["_ts_tree_cursor_goto_parent_wasm"] = createExportWrapper("ts_tree_cursor_goto_parent_wasm");
            Module["_ts_tree_cursor_current_node_type_id_wasm"] = createExportWrapper("ts_tree_cursor_current_node_type_id_wasm");
            Module["_ts_tree_cursor_current_node_is_named_wasm"] = createExportWrapper("ts_tree_cursor_current_node_is_named_wasm");
            Module["_ts_tree_cursor_current_node_is_missing_wasm"] = createExportWrapper("ts_tree_cursor_current_node_is_missing_wasm");
            Module["_ts_tree_cursor_current_node_id_wasm"] = createExportWrapper("ts_tree_cursor_current_node_id_wasm");
            Module["_ts_tree_cursor_start_position_wasm"] = createExportWrapper("ts_tree_cursor_start_position_wasm");
            Module["_ts_tree_cursor_end_position_wasm"] = createExportWrapper("ts_tree_cursor_end_position_wasm");
            Module["_ts_tree_cursor_start_index_wasm"] = createExportWrapper("ts_tree_cursor_start_index_wasm");
            Module["_ts_tree_cursor_end_index_wasm"] = createExportWrapper("ts_tree_cursor_end_index_wasm");
            Module["_ts_tree_cursor_current_field_id_wasm"] = createExportWrapper("ts_tree_cursor_current_field_id_wasm");
            Module["_ts_tree_cursor_current_node_wasm"] = createExportWrapper("ts_tree_cursor_current_node_wasm");
            Module["_ts_node_symbol_wasm"] = createExportWrapper("ts_node_symbol_wasm");
            Module["_ts_node_child_count_wasm"] = createExportWrapper("ts_node_child_count_wasm");
            Module["_ts_node_named_child_count_wasm"] = createExportWrapper("ts_node_named_child_count_wasm");
            Module["_ts_node_child_wasm"] = createExportWrapper("ts_node_child_wasm");
            Module["_ts_node_named_child_wasm"] = createExportWrapper("ts_node_named_child_wasm");
            Module["_ts_node_child_by_field_id_wasm"] = createExportWrapper("ts_node_child_by_field_id_wasm");
            Module["_ts_node_next_sibling_wasm"] = createExportWrapper("ts_node_next_sibling_wasm");
            Module["_ts_node_prev_sibling_wasm"] = createExportWrapper("ts_node_prev_sibling_wasm");
            Module["_ts_node_next_named_sibling_wasm"] = createExportWrapper("ts_node_next_named_sibling_wasm");
            Module["_ts_node_prev_named_sibling_wasm"] = createExportWrapper("ts_node_prev_named_sibling_wasm");
            Module["_ts_node_parent_wasm"] = createExportWrapper("ts_node_parent_wasm");
            Module["_ts_node_descendant_for_index_wasm"] = createExportWrapper("ts_node_descendant_for_index_wasm");
            Module["_ts_node_named_descendant_for_index_wasm"] = createExportWrapper("ts_node_named_descendant_for_index_wasm");
            Module["_ts_node_descendant_for_position_wasm"] = createExportWrapper("ts_node_descendant_for_position_wasm");
            Module["_ts_node_named_descendant_for_position_wasm"] = createExportWrapper("ts_node_named_descendant_for_position_wasm");
            Module["_ts_node_start_point_wasm"] = createExportWrapper("ts_node_start_point_wasm");
            Module["_ts_node_end_point_wasm"] = createExportWrapper("ts_node_end_point_wasm");
            Module["_ts_node_start_index_wasm"] = createExportWrapper("ts_node_start_index_wasm");
            Module["_ts_node_end_index_wasm"] = createExportWrapper("ts_node_end_index_wasm");
            Module["_ts_node_to_string_wasm"] = createExportWrapper("ts_node_to_string_wasm");
            Module["_ts_node_children_wasm"] = createExportWrapper("ts_node_children_wasm");
            Module["_ts_node_named_children_wasm"] = createExportWrapper("ts_node_named_children_wasm");
            Module["_ts_node_descendants_of_type_wasm"] = createExportWrapper("ts_node_descendants_of_type_wasm");
            Module["_ts_node_is_named_wasm"] = createExportWrapper("ts_node_is_named_wasm");
            Module["_ts_node_has_changes_wasm"] = createExportWrapper("ts_node_has_changes_wasm");
            Module["_ts_node_has_error_wasm"] = createExportWrapper("ts_node_has_error_wasm");
            Module["_ts_node_is_missing_wasm"] = createExportWrapper("ts_node_is_missing_wasm");
            Module["_ts_query_matches_wasm"] = createExportWrapper("ts_query_matches_wasm");
            Module["_ts_query_captures_wasm"] = createExportWrapper("ts_query_captures_wasm");
            var ___errno_location = Module["___errno_location"] = createExportWrapper("__errno_location");
            Module["_iswalpha"] = createExportWrapper("iswalpha");
            Module["_towupper"] = createExportWrapper("towupper");
            Module["_iswlower"] = createExportWrapper("iswlower");
            Module["_iswdigit"] = createExportWrapper("iswdigit");
            Module["_memchr"] = createExportWrapper("memchr");
            Module["_strlen"] = createExportWrapper("strlen");
            var stackSave = Module["stackSave"] = createExportWrapper("stackSave");
            var stackRestore = Module["stackRestore"] = createExportWrapper("stackRestore");
            var stackAlloc = Module["stackAlloc"] = createExportWrapper("stackAlloc");
            var _emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = function() {
                return (_emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = Module["asm"]["emscripten_stack_set_limits"]).apply(null, arguments);
            };
            var _emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = function() {
                return (_emscripten_stack_get_free = Module["_emscripten_stack_get_free"] = Module["asm"]["emscripten_stack_get_free"]).apply(null, arguments);
            };
            var _emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = function() {
                return (_emscripten_stack_get_end = Module["_emscripten_stack_get_end"] = Module["asm"]["emscripten_stack_get_end"]).apply(null, arguments);
            };
            var _setThrew = Module["_setThrew"] = createExportWrapper("setThrew");
            Module["__Znwm"] = createExportWrapper("_Znwm");
            Module["__ZdlPv"] = createExportWrapper("_ZdlPv");
            Module["__ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv"] = createExportWrapper("_ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv");
            Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev");
            Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm");
            Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm");
            Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm");
            Module["__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm"] = createExportWrapper("_ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm");
            Module["__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc"] = createExportWrapper("_ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc");
            Module["__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev"] = createExportWrapper("_ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev");
            Module["__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw"] = createExportWrapper("_ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw");
            Module["dynCall_jiji"] = createExportWrapper("dynCall_jiji");
            Module["_orig$ts_parser_timeout_micros"] = createExportWrapper("orig$ts_parser_timeout_micros");
            Module["_orig$ts_parser_set_timeout_micros"] = createExportWrapper("orig$ts_parser_set_timeout_micros");
            Module['_stderr'] = 7088;
            Module['_TRANSFER_BUFFER'] = 7472;
            Module['___THREW__'] = 8116;
            Module['___threwValue'] = 8120;
            Module['___cxa_new_handler'] = 8112;
            Module['___data_end'] = 8124;
            if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromString")) Module["intArrayFromString"] = function() {
                abort("'intArrayFromString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "intArrayToString")) Module["intArrayToString"] = function() {
                abort("'intArrayToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ccall")) Module["ccall"] = function() {
                abort("'ccall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "cwrap")) Module["cwrap"] = function() {
                abort("'cwrap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setValue")) Module["setValue"] = function() {
                abort("'setValue' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getValue")) Module["getValue"] = function() {
                abort("'getValue' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            Module["allocate"] = allocate;
            if (!Object.getOwnPropertyDescriptor(Module, "UTF8ArrayToString")) Module["UTF8ArrayToString"] = function() {
                abort("'UTF8ArrayToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "UTF8ToString")) Module["UTF8ToString"] = function() {
                abort("'UTF8ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8Array")) Module["stringToUTF8Array"] = function() {
                abort("'stringToUTF8Array' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF8")) Module["stringToUTF8"] = function() {
                abort("'stringToUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF8")) Module["lengthBytesUTF8"] = function() {
                abort("'lengthBytesUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() {
                abort("'stackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addOnPreRun")) Module["addOnPreRun"] = function() {
                abort("'addOnPreRun' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addOnInit")) Module["addOnInit"] = function() {
                abort("'addOnInit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addOnPreMain")) Module["addOnPreMain"] = function() {
                abort("'addOnPreMain' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addOnExit")) Module["addOnExit"] = function() {
                abort("'addOnExit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addOnPostRun")) Module["addOnPostRun"] = function() {
                abort("'addOnPostRun' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeStringToMemory")) Module["writeStringToMemory"] = function() {
                abort("'writeStringToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeArrayToMemory")) Module["writeArrayToMemory"] = function() {
                abort("'writeArrayToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeAsciiToMemory")) Module["writeAsciiToMemory"] = function() {
                abort("'writeAsciiToMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addRunDependency")) Module["addRunDependency"] = function() {
                abort("'addRunDependency' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "removeRunDependency")) Module["removeRunDependency"] = function() {
                abort("'removeRunDependency' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createFolder")) Module["FS_createFolder"] = function() {
                abort("'FS_createFolder' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createPath")) Module["FS_createPath"] = function() {
                abort("'FS_createPath' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createDataFile")) Module["FS_createDataFile"] = function() {
                abort("'FS_createDataFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createPreloadedFile")) Module["FS_createPreloadedFile"] = function() {
                abort("'FS_createPreloadedFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createLazyFile")) Module["FS_createLazyFile"] = function() {
                abort("'FS_createLazyFile' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createLink")) Module["FS_createLink"] = function() {
                abort("'FS_createLink' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_createDevice")) Module["FS_createDevice"] = function() {
                abort("'FS_createDevice' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "FS_unlink")) Module["FS_unlink"] = function() {
                abort("'FS_unlink' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ). Alternatively, forcing filesystem support (-s FORCE_FILESYSTEM=1) can export this for you");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getLEB")) Module["getLEB"] = function() {
                abort("'getLEB' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getFunctionTables")) Module["getFunctionTables"] = function() {
                abort("'getFunctionTables' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "alignFunctionTables")) Module["alignFunctionTables"] = function() {
                abort("'alignFunctionTables' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerFunctions")) Module["registerFunctions"] = function() {
                abort("'registerFunctions' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "addFunction")) Module["addFunction"] = function() {
                abort("'addFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "removeFunction")) Module["removeFunction"] = function() {
                abort("'removeFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() {
                abort("'getFuncWrapper' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "prettyPrint")) Module["prettyPrint"] = function() {
                abort("'prettyPrint' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() {
                abort("'dynCall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getCompilerSetting")) Module["getCompilerSetting"] = function() {
                abort("'getCompilerSetting' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "print")) Module["print"] = function() {
                abort("'print' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "printErr")) Module["printErr"] = function() {
                abort("'printErr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getTempRet0")) Module["getTempRet0"] = function() {
                abort("'getTempRet0' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setTempRet0")) Module["setTempRet0"] = function() {
                abort("'setTempRet0' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "callMain")) Module["callMain"] = function() {
                abort("'callMain' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "abort")) Module["abort"] = function() {
                abort("'abort' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stringToNewUTF8")) Module["stringToNewUTF8"] = function() {
                abort("'stringToNewUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setFileTime")) Module["setFileTime"] = function() {
                abort("'setFileTime' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "emscripten_realloc_buffer")) Module["emscripten_realloc_buffer"] = function() {
                abort("'emscripten_realloc_buffer' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ENV")) Module["ENV"] = function() {
                abort("'ENV' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_CODES")) Module["ERRNO_CODES"] = function() {
                abort("'ERRNO_CODES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ERRNO_MESSAGES")) Module["ERRNO_MESSAGES"] = function() {
                abort("'ERRNO_MESSAGES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setErrNo")) Module["setErrNo"] = function() {
                abort("'setErrNo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "inetPton4")) Module["inetPton4"] = function() {
                abort("'inetPton4' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "inetNtop4")) Module["inetNtop4"] = function() {
                abort("'inetNtop4' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "inetPton6")) Module["inetPton6"] = function() {
                abort("'inetPton6' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "inetNtop6")) Module["inetNtop6"] = function() {
                abort("'inetNtop6' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "readSockaddr")) Module["readSockaddr"] = function() {
                abort("'readSockaddr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeSockaddr")) Module["writeSockaddr"] = function() {
                abort("'writeSockaddr' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "DNS")) Module["DNS"] = function() {
                abort("'DNS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getHostByName")) Module["getHostByName"] = function() {
                abort("'getHostByName' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GAI_ERRNO_MESSAGES")) Module["GAI_ERRNO_MESSAGES"] = function() {
                abort("'GAI_ERRNO_MESSAGES' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "Protocols")) Module["Protocols"] = function() {
                abort("'Protocols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "Sockets")) Module["Sockets"] = function() {
                abort("'Sockets' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getRandomDevice")) Module["getRandomDevice"] = function() {
                abort("'getRandomDevice' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "traverseStack")) Module["traverseStack"] = function() {
                abort("'traverseStack' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "UNWIND_CACHE")) Module["UNWIND_CACHE"] = function() {
                abort("'UNWIND_CACHE' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "withBuiltinMalloc")) Module["withBuiltinMalloc"] = function() {
                abort("'withBuiltinMalloc' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgsArray")) Module["readAsmConstArgsArray"] = function() {
                abort("'readAsmConstArgsArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "readAsmConstArgs")) Module["readAsmConstArgs"] = function() {
                abort("'readAsmConstArgs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "mainThreadEM_ASM")) Module["mainThreadEM_ASM"] = function() {
                abort("'mainThreadEM_ASM' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "jstoi_q")) Module["jstoi_q"] = function() {
                abort("'jstoi_q' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "jstoi_s")) Module["jstoi_s"] = function() {
                abort("'jstoi_s' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getExecutableName")) Module["getExecutableName"] = function() {
                abort("'getExecutableName' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "listenOnce")) Module["listenOnce"] = function() {
                abort("'listenOnce' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "autoResumeAudioContext")) Module["autoResumeAudioContext"] = function() {
                abort("'autoResumeAudioContext' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "dynCallLegacy")) Module["dynCallLegacy"] = function() {
                abort("'dynCallLegacy' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getDynCaller")) Module["getDynCaller"] = function() {
                abort("'getDynCaller' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "dynCall")) Module["dynCall"] = function() {
                abort("'dynCall' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "callRuntimeCallbacks")) Module["callRuntimeCallbacks"] = function() {
                abort("'callRuntimeCallbacks' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepaliveCounter")) Module["runtimeKeepaliveCounter"] = function() {
                abort("'runtimeKeepaliveCounter' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "keepRuntimeAlive")) Module["keepRuntimeAlive"] = function() {
                abort("'keepRuntimeAlive' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepalivePush")) Module["runtimeKeepalivePush"] = function() {
                abort("'runtimeKeepalivePush' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "runtimeKeepalivePop")) Module["runtimeKeepalivePop"] = function() {
                abort("'runtimeKeepalivePop' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "callUserCallback")) Module["callUserCallback"] = function() {
                abort("'callUserCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "maybeExit")) Module["maybeExit"] = function() {
                abort("'maybeExit' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "asmjsMangle")) Module["asmjsMangle"] = function() {
                abort("'asmjsMangle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "reallyNegative")) Module["reallyNegative"] = function() {
                abort("'reallyNegative' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "unSign")) Module["unSign"] = function() {
                abort("'unSign' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "reSign")) Module["reSign"] = function() {
                abort("'reSign' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "formatString")) Module["formatString"] = function() {
                abort("'formatString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "PATH")) Module["PATH"] = function() {
                abort("'PATH' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "PATH_FS")) Module["PATH_FS"] = function() {
                abort("'PATH_FS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "SYSCALLS")) Module["SYSCALLS"] = function() {
                abort("'SYSCALLS' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "syscallMmap2")) Module["syscallMmap2"] = function() {
                abort("'syscallMmap2' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "syscallMunmap")) Module["syscallMunmap"] = function() {
                abort("'syscallMunmap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getSocketFromFD")) Module["getSocketFromFD"] = function() {
                abort("'getSocketFromFD' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getSocketAddress")) Module["getSocketAddress"] = function() {
                abort("'getSocketAddress' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "JSEvents")) Module["JSEvents"] = function() {
                abort("'JSEvents' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerKeyEventCallback")) Module["registerKeyEventCallback"] = function() {
                abort("'registerKeyEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "specialHTMLTargets")) Module["specialHTMLTargets"] = function() {
                abort("'specialHTMLTargets' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "maybeCStringToJsString")) Module["maybeCStringToJsString"] = function() {
                abort("'maybeCStringToJsString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "findEventTarget")) Module["findEventTarget"] = function() {
                abort("'findEventTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "findCanvasEventTarget")) Module["findCanvasEventTarget"] = function() {
                abort("'findCanvasEventTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getBoundingClientRect")) Module["getBoundingClientRect"] = function() {
                abort("'getBoundingClientRect' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillMouseEventData")) Module["fillMouseEventData"] = function() {
                abort("'fillMouseEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerMouseEventCallback")) Module["registerMouseEventCallback"] = function() {
                abort("'registerMouseEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerWheelEventCallback")) Module["registerWheelEventCallback"] = function() {
                abort("'registerWheelEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerUiEventCallback")) Module["registerUiEventCallback"] = function() {
                abort("'registerUiEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerFocusEventCallback")) Module["registerFocusEventCallback"] = function() {
                abort("'registerFocusEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillDeviceOrientationEventData")) Module["fillDeviceOrientationEventData"] = function() {
                abort("'fillDeviceOrientationEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerDeviceOrientationEventCallback")) Module["registerDeviceOrientationEventCallback"] = function() {
                abort("'registerDeviceOrientationEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillDeviceMotionEventData")) Module["fillDeviceMotionEventData"] = function() {
                abort("'fillDeviceMotionEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerDeviceMotionEventCallback")) Module["registerDeviceMotionEventCallback"] = function() {
                abort("'registerDeviceMotionEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "screenOrientation")) Module["screenOrientation"] = function() {
                abort("'screenOrientation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillOrientationChangeEventData")) Module["fillOrientationChangeEventData"] = function() {
                abort("'fillOrientationChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerOrientationChangeEventCallback")) Module["registerOrientationChangeEventCallback"] = function() {
                abort("'registerOrientationChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillFullscreenChangeEventData")) Module["fillFullscreenChangeEventData"] = function() {
                abort("'fillFullscreenChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerFullscreenChangeEventCallback")) Module["registerFullscreenChangeEventCallback"] = function() {
                abort("'registerFullscreenChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerRestoreOldStyle")) Module["registerRestoreOldStyle"] = function() {
                abort("'registerRestoreOldStyle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "hideEverythingExceptGivenElement")) Module["hideEverythingExceptGivenElement"] = function() {
                abort("'hideEverythingExceptGivenElement' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "restoreHiddenElements")) Module["restoreHiddenElements"] = function() {
                abort("'restoreHiddenElements' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setLetterbox")) Module["setLetterbox"] = function() {
                abort("'setLetterbox' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "currentFullscreenStrategy")) Module["currentFullscreenStrategy"] = function() {
                abort("'currentFullscreenStrategy' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "restoreOldWindowedStyle")) Module["restoreOldWindowedStyle"] = function() {
                abort("'restoreOldWindowedStyle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "softFullscreenResizeWebGLRenderTarget")) Module["softFullscreenResizeWebGLRenderTarget"] = function() {
                abort("'softFullscreenResizeWebGLRenderTarget' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "doRequestFullscreen")) Module["doRequestFullscreen"] = function() {
                abort("'doRequestFullscreen' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillPointerlockChangeEventData")) Module["fillPointerlockChangeEventData"] = function() {
                abort("'fillPointerlockChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerPointerlockChangeEventCallback")) Module["registerPointerlockChangeEventCallback"] = function() {
                abort("'registerPointerlockChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerPointerlockErrorEventCallback")) Module["registerPointerlockErrorEventCallback"] = function() {
                abort("'registerPointerlockErrorEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "requestPointerLock")) Module["requestPointerLock"] = function() {
                abort("'requestPointerLock' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillVisibilityChangeEventData")) Module["fillVisibilityChangeEventData"] = function() {
                abort("'fillVisibilityChangeEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerVisibilityChangeEventCallback")) Module["registerVisibilityChangeEventCallback"] = function() {
                abort("'registerVisibilityChangeEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerTouchEventCallback")) Module["registerTouchEventCallback"] = function() {
                abort("'registerTouchEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillGamepadEventData")) Module["fillGamepadEventData"] = function() {
                abort("'fillGamepadEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerGamepadEventCallback")) Module["registerGamepadEventCallback"] = function() {
                abort("'registerGamepadEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerBeforeUnloadEventCallback")) Module["registerBeforeUnloadEventCallback"] = function() {
                abort("'registerBeforeUnloadEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fillBatteryEventData")) Module["fillBatteryEventData"] = function() {
                abort("'fillBatteryEventData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "battery")) Module["battery"] = function() {
                abort("'battery' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "registerBatteryEventCallback")) Module["registerBatteryEventCallback"] = function() {
                abort("'registerBatteryEventCallback' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setCanvasElementSize")) Module["setCanvasElementSize"] = function() {
                abort("'setCanvasElementSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getCanvasElementSize")) Module["getCanvasElementSize"] = function() {
                abort("'getCanvasElementSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "polyfillSetImmediate")) Module["polyfillSetImmediate"] = function() {
                abort("'polyfillSetImmediate' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "demangle")) Module["demangle"] = function() {
                abort("'demangle' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "demangleAll")) Module["demangleAll"] = function() {
                abort("'demangleAll' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "jsStackTrace")) Module["jsStackTrace"] = function() {
                abort("'jsStackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stackTrace")) Module["stackTrace"] = function() {
                abort("'stackTrace' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getEnvStrings")) Module["getEnvStrings"] = function() {
                abort("'getEnvStrings' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "checkWasiClock")) Module["checkWasiClock"] = function() {
                abort("'checkWasiClock' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64")) Module["writeI53ToI64"] = function() {
                abort("'writeI53ToI64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Clamped")) Module["writeI53ToI64Clamped"] = function() {
                abort("'writeI53ToI64Clamped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToI64Signaling")) Module["writeI53ToI64Signaling"] = function() {
                abort("'writeI53ToI64Signaling' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Clamped")) Module["writeI53ToU64Clamped"] = function() {
                abort("'writeI53ToU64Clamped' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeI53ToU64Signaling")) Module["writeI53ToU64Signaling"] = function() {
                abort("'writeI53ToU64Signaling' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "readI53FromI64")) Module["readI53FromI64"] = function() {
                abort("'readI53FromI64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "readI53FromU64")) Module["readI53FromU64"] = function() {
                abort("'readI53FromU64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "convertI32PairToI53")) Module["convertI32PairToI53"] = function() {
                abort("'convertI32PairToI53' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "convertU32PairToI53")) Module["convertU32PairToI53"] = function() {
                abort("'convertU32PairToI53' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "resolveGlobalSymbol")) Module["resolveGlobalSymbol"] = function() {
                abort("'resolveGlobalSymbol' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GOT")) Module["GOT"] = function() {
                abort("'GOT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GOTHandler")) Module["GOTHandler"] = function() {
                abort("'GOTHandler' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "isInternalSym")) Module["isInternalSym"] = function() {
                abort("'isInternalSym' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "updateGOT")) Module["updateGOT"] = function() {
                abort("'updateGOT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "relocateExports")) Module["relocateExports"] = function() {
                abort("'relocateExports' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "reportUndefinedSymbols")) Module["reportUndefinedSymbols"] = function() {
                abort("'reportUndefinedSymbols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "DLFCN")) Module["DLFCN"] = function() {
                abort("'DLFCN' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "LDSO")) Module["LDSO"] = function() {
                abort("'LDSO' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "createInvokeFunction")) Module["createInvokeFunction"] = function() {
                abort("'createInvokeFunction' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getMemory")) Module["getMemory"] = function() {
                abort("'getMemory' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "fetchBinary")) Module["fetchBinary"] = function() {
                abort("'fetchBinary' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getDylinkMetadata")) Module["getDylinkMetadata"] = function() {
                abort("'getDylinkMetadata' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "mergeLibSymbols")) Module["mergeLibSymbols"] = function() {
                abort("'mergeLibSymbols' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "loadWebAssemblyModule")) Module["loadWebAssemblyModule"] = function() {
                abort("'loadWebAssemblyModule' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "loadDynamicLibrary")) Module["loadDynamicLibrary"] = function() {
                abort("'loadDynamicLibrary' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "preloadDylibs")) Module["preloadDylibs"] = function() {
                abort("'preloadDylibs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "uncaughtExceptionCount")) Module["uncaughtExceptionCount"] = function() {
                abort("'uncaughtExceptionCount' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "exceptionLast")) Module["exceptionLast"] = function() {
                abort("'exceptionLast' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "exceptionCaught")) Module["exceptionCaught"] = function() {
                abort("'exceptionCaught' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ExceptionInfoAttrs")) Module["ExceptionInfoAttrs"] = function() {
                abort("'ExceptionInfoAttrs' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ExceptionInfo")) Module["ExceptionInfo"] = function() {
                abort("'ExceptionInfo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "CatchInfo")) Module["CatchInfo"] = function() {
                abort("'CatchInfo' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "exception_addRef")) Module["exception_addRef"] = function() {
                abort("'exception_addRef' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "exception_decRef")) Module["exception_decRef"] = function() {
                abort("'exception_decRef' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "Browser")) Module["Browser"] = function() {
                abort("'Browser' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "funcWrappers")) Module["funcWrappers"] = function() {
                abort("'funcWrappers' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "getFuncWrapper")) Module["getFuncWrapper"] = function() {
                abort("'getFuncWrapper' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "setMainLoop")) Module["setMainLoop"] = function() {
                abort("'setMainLoop' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "tempFixedLengthArray")) Module["tempFixedLengthArray"] = function() {
                abort("'tempFixedLengthArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "miniTempWebGLFloatBuffers")) Module["miniTempWebGLFloatBuffers"] = function() {
                abort("'miniTempWebGLFloatBuffers' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "heapObjectForWebGLType")) Module["heapObjectForWebGLType"] = function() {
                abort("'heapObjectForWebGLType' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "heapAccessShiftForWebGLHeap")) Module["heapAccessShiftForWebGLHeap"] = function() {
                abort("'heapAccessShiftForWebGLHeap' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GL")) Module["GL"] = function() {
                abort("'GL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGet")) Module["emscriptenWebGLGet"] = function() {
                abort("'emscriptenWebGLGet' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "computeUnpackAlignedImageSize")) Module["computeUnpackAlignedImageSize"] = function() {
                abort("'computeUnpackAlignedImageSize' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetTexPixelData")) Module["emscriptenWebGLGetTexPixelData"] = function() {
                abort("'emscriptenWebGLGetTexPixelData' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetUniform")) Module["emscriptenWebGLGetUniform"] = function() {
                abort("'emscriptenWebGLGetUniform' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "webglGetUniformLocation")) Module["webglGetUniformLocation"] = function() {
                abort("'webglGetUniformLocation' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "webglPrepareUniformLocationsBeforeFirstUse")) Module["webglPrepareUniformLocationsBeforeFirstUse"] = function() {
                abort("'webglPrepareUniformLocationsBeforeFirstUse' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "webglGetLeftBracePos")) Module["webglGetLeftBracePos"] = function() {
                abort("'webglGetLeftBracePos' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "emscriptenWebGLGetVertexAttrib")) Module["emscriptenWebGLGetVertexAttrib"] = function() {
                abort("'emscriptenWebGLGetVertexAttrib' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "writeGLArray")) Module["writeGLArray"] = function() {
                abort("'writeGLArray' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "AL")) Module["AL"] = function() {
                abort("'AL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "SDL_unicode")) Module["SDL_unicode"] = function() {
                abort("'SDL_unicode' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "SDL_ttfContext")) Module["SDL_ttfContext"] = function() {
                abort("'SDL_ttfContext' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "SDL_audio")) Module["SDL_audio"] = function() {
                abort("'SDL_audio' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "SDL")) Module["SDL"] = function() {
                abort("'SDL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "SDL_gfx")) Module["SDL_gfx"] = function() {
                abort("'SDL_gfx' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GLUT")) Module["GLUT"] = function() {
                abort("'GLUT' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "EGL")) Module["EGL"] = function() {
                abort("'EGL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GLFW_Window")) Module["GLFW_Window"] = function() {
                abort("'GLFW_Window' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GLFW")) Module["GLFW"] = function() {
                abort("'GLFW' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "GLEW")) Module["GLEW"] = function() {
                abort("'GLEW' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "IDBStore")) Module["IDBStore"] = function() {
                abort("'IDBStore' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "runAndAbortIfError")) Module["runAndAbortIfError"] = function() {
                abort("'runAndAbortIfError' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "warnOnce")) Module["warnOnce"] = function() {
                abort("'warnOnce' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stackSave")) Module["stackSave"] = function() {
                abort("'stackSave' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stackRestore")) Module["stackRestore"] = function() {
                abort("'stackRestore' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stackAlloc")) Module["stackAlloc"] = function() {
                abort("'stackAlloc' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "AsciiToString")) Module["AsciiToString"] = function() {
                abort("'AsciiToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stringToAscii")) Module["stringToAscii"] = function() {
                abort("'stringToAscii' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "UTF16ToString")) Module["UTF16ToString"] = function() {
                abort("'UTF16ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF16")) Module["stringToUTF16"] = function() {
                abort("'stringToUTF16' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF16")) Module["lengthBytesUTF16"] = function() {
                abort("'lengthBytesUTF16' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "UTF32ToString")) Module["UTF32ToString"] = function() {
                abort("'UTF32ToString' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "stringToUTF32")) Module["stringToUTF32"] = function() {
                abort("'stringToUTF32' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "lengthBytesUTF32")) Module["lengthBytesUTF32"] = function() {
                abort("'lengthBytesUTF32' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8")) Module["allocateUTF8"] = function() {
                abort("'allocateUTF8' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "allocateUTF8OnStack")) Module["allocateUTF8OnStack"] = function() {
                abort("'allocateUTF8OnStack' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            Module["writeStackCookie"] = writeStackCookie;
            Module["checkStackCookie"] = checkStackCookie;
            if (!Object.getOwnPropertyDescriptor(Module, "intArrayFromBase64")) Module["intArrayFromBase64"] = function() {
                abort("'intArrayFromBase64' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "tryParseAsDataURI")) Module["tryParseAsDataURI"] = function() {
                abort("'tryParseAsDataURI' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
            };
            if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_NORMAL")) Object.defineProperty(Module, "ALLOC_NORMAL", {
                configurable: true,
                get: function() {
                    abort("'ALLOC_NORMAL' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
                }
            });
            if (!Object.getOwnPropertyDescriptor(Module, "ALLOC_STACK")) Object.defineProperty(Module, "ALLOC_STACK", {
                configurable: true,
                get: function() {
                    abort("'ALLOC_STACK' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the FAQ)");
                }
            });
            var calledRun;
            function ExitStatus(status) {
                this.name = "ExitStatus";
                this.message = "Program terminated with exit(" + status + ")";
                this.status = status;
            }
            dependenciesFulfilled = function runCaller() {
                if (!calledRun) run();
                if (!calledRun) dependenciesFulfilled = runCaller;
            };
            function callMain(args) {
                assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
                assert(__ATPRERUN__.length == 0, 'cannot call main when preRun functions remain to be called');
                var entryFunction = Module['_main'];
                if (!entryFunction) return;
                args = args || [];
                var argc = args.length + 1;
                var argv = stackAlloc((argc + 1) * 4);
                HEAP32[argv >> 2] = allocateUTF8OnStack(thisProgram);
                for(var i1 = 1; i1 < argc; i1++){
                    HEAP32[(argv >> 2) + i1] = allocateUTF8OnStack(args[i1 - 1]);
                }
                HEAP32[(argv >> 2) + argc] = 0;
                try {
                    var ret = entryFunction(argc, argv);
                    exit(ret, true);
                } catch (e) {
                    if (e instanceof ExitStatus) {
                        return;
                    } else if (e == 'unwind') {
                        return;
                    } else {
                        var toLog = e;
                        if (e && typeof e === 'object' && e.stack) {
                            toLog = [
                                e,
                                e.stack
                            ];
                        }
                        err('exception thrown: ' + toLog);
                        quit_(1, e);
                    }
                } finally{
                    true;
                }
            }
            function stackCheckInit() {
                _emscripten_stack_set_limits(5251008, 8128);
                writeStackCookie();
            }
            var dylibsLoaded = false;
            async function run(args) {
                args = args || arguments_;
                await wasmInstantiatePromise;
                if (runDependencies > 0) {
                    return;
                }
                stackCheckInit();
                if (!dylibsLoaded) {
                    preloadDylibs();
                    dylibsLoaded = true;
                    if (runDependencies > 0) {
                        return;
                    }
                }
                preRun();
                if (runDependencies > 0) {
                    return;
                }
                function doRun() {
                    if (calledRun) return;
                    calledRun = true;
                    Module['calledRun'] = true;
                    if (ABORT) return;
                    initRuntime();
                    preMain();
                    if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();
                    if (shouldRunNow) callMain(args);
                    postRun();
                }
                doRun();
                checkStackCookie();
            }
            Module['run'] = run;
            function checkUnflushedContent() {
                var oldOut = out;
                var oldErr = err;
                var has = false;
                out = err = function(x) {
                    has = true;
                };
                try {
                    var flush = Module['_fflush'];
                    if (flush) flush(0);
                } catch (e) {}
                out = oldOut;
                err = oldErr;
                if (has) {
                    warnOnce('stdio streams had content in them that was not flushed. you should set EXIT_RUNTIME to 1 (see the FAQ), or make sure to emit a newline when you printf etc.');
                    warnOnce('(this may also be due to not including full filesystem support - try building with -s FORCE_FILESYSTEM=1)');
                }
            }
            function exit(status, implicit) {
                status;
                checkUnflushedContent();
                if (implicit && keepRuntimeAlive() && status === 0) {
                    return;
                }
                if (keepRuntimeAlive()) {
                    if (!implicit) {
                        var msg = 'program exited (with status: ' + status + '), but EXIT_RUNTIME is not set, so halting execution but not exiting the runtime or preventing further async execution (build with EXIT_RUNTIME=1, if you want a true shutdown)';
                        err(msg);
                    }
                } else {
                    exitRuntime();
                    if (Module['onExit']) Module['onExit'](status);
                    ABORT = true;
                }
                quit_(status, new ExitStatus(status));
            }
            if (Module['preInit']) {
                if (typeof Module['preInit'] == 'function') Module['preInit'] = [
                    Module['preInit']
                ];
                while(Module['preInit'].length > 0){
                    Module['preInit'].pop()();
                }
            }
            var shouldRunNow = true;
            if (Module['noInitialRun']) shouldRunNow = false;
            const C = Module;
            const INTERNAL = {};
            const SIZE_OF_INT = 4;
            const SIZE_OF_NODE = 5 * 4;
            const SIZE_OF_POINT = 2 * 4;
            const SIZE_OF_RANGE = 2 * 4 + 2 * SIZE_OF_POINT;
            const ZERO_POINT = {
                row: 0,
                column: 0
            };
            const QUERY_WORD_REGEX = /[\w-.]*/g;
            const LANGUAGE_FUNCTION_REGEX = /^_?tree_sitter_\w+/;
            var VERSION;
            var MIN_COMPATIBLE_VERSION;
            var TRANSFER_BUFFER;
            var currentParseCallback;
            var currentLogCallback;
            class ParserImpl {
                static init() {
                    TRANSFER_BUFFER = C._ts_init();
                    VERSION = getValue(TRANSFER_BUFFER, 'i32');
                    MIN_COMPATIBLE_VERSION = getValue(TRANSFER_BUFFER + SIZE_OF_INT, 'i32');
                }
                initialize() {
                    C._ts_parser_new_wasm();
                    this[0] = getValue(TRANSFER_BUFFER, 'i32');
                    this[1] = getValue(TRANSFER_BUFFER + SIZE_OF_INT, 'i32');
                }
                delete() {
                    C._ts_parser_delete(this[0]);
                    C._free(this[1]);
                    this[0] = 0;
                    this[1] = 0;
                }
                setLanguage(language) {
                    let address;
                    if (!language) {
                        address = 0;
                        language = null;
                    } else if (language.constructor === Language) {
                        address = language[0];
                        const version = C._ts_language_version(address);
                        if (version < MIN_COMPATIBLE_VERSION || VERSION < version) {
                            throw new Error(`Incompatible language version ${version}. ` + `Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`);
                        }
                    } else {
                        throw new Error('Argument must be a Language');
                    }
                    this.language = language;
                    C._ts_parser_set_language(this[0], address);
                    return this;
                }
                getLanguage() {
                    return this.language;
                }
                parse(callback, oldTree, options) {
                    if (typeof callback === 'string') {
                        currentParseCallback = (index, _, endIndex)=>callback.slice(index, endIndex);
                    } else if (typeof callback === 'function') {
                        currentParseCallback = callback;
                    } else {
                        throw new Error("Argument must be a string or a function");
                    }
                    if (this.logCallback) {
                        currentLogCallback = this.logCallback;
                        C._ts_parser_enable_logger_wasm(this[0], 1);
                    } else {
                        currentLogCallback = null;
                        C._ts_parser_enable_logger_wasm(this[0], 0);
                    }
                    let rangeCount = 0;
                    let rangeAddress = 0;
                    if (options && options.includedRanges) {
                        rangeCount = options.includedRanges.length;
                        rangeAddress = C._calloc(rangeCount, SIZE_OF_RANGE);
                        let address = rangeAddress;
                        for(let i1 = 0; i1 < rangeCount; i1++){
                            marshalRange(address, options.includedRanges[i1]);
                            address += SIZE_OF_RANGE;
                        }
                    }
                    const treeAddress = C._ts_parser_parse_wasm(this[0], this[1], oldTree ? oldTree[0] : 0, rangeAddress, rangeCount);
                    if (!treeAddress) {
                        currentParseCallback = null;
                        currentLogCallback = null;
                        throw new Error('Parsing failed');
                    }
                    const result1 = new Tree(INTERNAL, treeAddress, this.language, currentParseCallback);
                    currentParseCallback = null;
                    currentLogCallback = null;
                    return result1;
                }
                reset() {
                    C._ts_parser_reset(this[0]);
                }
                setTimeoutMicros(timeout) {
                    C._ts_parser_set_timeout_micros(this[0], timeout);
                }
                getTimeoutMicros() {
                    return C._ts_parser_timeout_micros(this[0]);
                }
                setLogger(callback) {
                    if (!callback) {
                        callback = null;
                    } else if (typeof callback !== "function") {
                        throw new Error("Logger callback must be a function");
                    }
                    this.logCallback = callback;
                    return this;
                }
                getLogger() {
                    return this.logCallback;
                }
            }
            class Tree {
                constructor(internal, address, language, textCallback){
                    assertInternal(internal);
                    this[0] = address;
                    this.language = language;
                    this.textCallback = textCallback;
                }
                copy() {
                    const address = C._ts_tree_copy(this[0]);
                    return new Tree(INTERNAL, address, this.language, this.textCallback);
                }
                delete() {
                    C._ts_tree_delete(this[0]);
                    this[0] = 0;
                }
                edit(edit) {
                    marshalEdit(edit);
                    C._ts_tree_edit_wasm(this[0]);
                }
                get rootNode() {
                    C._ts_tree_root_node_wasm(this[0]);
                    return unmarshalNode(this);
                }
                getLanguage() {
                    return this.language;
                }
                walk() {
                    return this.rootNode.walk();
                }
                getChangedRanges(other) {
                    if (other.constructor !== Tree) {
                        throw new TypeError('Argument must be a Tree');
                    }
                    C._ts_tree_get_changed_ranges_wasm(this[0], other[0]);
                    const count = getValue(TRANSFER_BUFFER, 'i32');
                    const buffer = getValue(TRANSFER_BUFFER + 4, 'i32');
                    const result1 = new Array(count);
                    if (count > 0) {
                        let address = buffer;
                        for(let i1 = 0; i1 < count; i1++){
                            result1[i1] = unmarshalRange(address);
                            address += SIZE_OF_RANGE;
                        }
                        C._free(buffer);
                    }
                    return result1;
                }
            }
            class Node {
                constructor(internal, tree){
                    assertInternal(internal);
                    this.tree = tree;
                }
                get typeId() {
                    marshalNode(this);
                    return C._ts_node_symbol_wasm(this.tree[0]);
                }
                get type() {
                    return this.tree.language.types[this.typeId] || 'ERROR';
                }
                get endPosition() {
                    marshalNode(this);
                    C._ts_node_end_point_wasm(this.tree[0]);
                    return unmarshalPoint(TRANSFER_BUFFER);
                }
                get endIndex() {
                    marshalNode(this);
                    return C._ts_node_end_index_wasm(this.tree[0]);
                }
                get text() {
                    return getText(this.tree, this.startIndex, this.endIndex);
                }
                isNamed() {
                    marshalNode(this);
                    return C._ts_node_is_named_wasm(this.tree[0]) === 1;
                }
                hasError() {
                    marshalNode(this);
                    return C._ts_node_has_error_wasm(this.tree[0]) === 1;
                }
                hasChanges() {
                    marshalNode(this);
                    return C._ts_node_has_changes_wasm(this.tree[0]) === 1;
                }
                isMissing() {
                    marshalNode(this);
                    return C._ts_node_is_missing_wasm(this.tree[0]) === 1;
                }
                equals(other) {
                    return this.id === other.id;
                }
                child(index) {
                    marshalNode(this);
                    C._ts_node_child_wasm(this.tree[0], index);
                    return unmarshalNode(this.tree);
                }
                namedChild(index) {
                    marshalNode(this);
                    C._ts_node_named_child_wasm(this.tree[0], index);
                    return unmarshalNode(this.tree);
                }
                childForFieldId(fieldId) {
                    marshalNode(this);
                    C._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
                    return unmarshalNode(this.tree);
                }
                childForFieldName(fieldName) {
                    const fieldId = this.tree.language.fields.indexOf(fieldName);
                    if (fieldId !== -1) return this.childForFieldId(fieldId);
                    return undefined;
                }
                get childCount() {
                    marshalNode(this);
                    return C._ts_node_child_count_wasm(this.tree[0]);
                }
                get namedChildCount() {
                    marshalNode(this);
                    return C._ts_node_named_child_count_wasm(this.tree[0]);
                }
                get firstChild() {
                    return this.child(0);
                }
                get firstNamedChild() {
                    return this.namedChild(0);
                }
                get lastChild() {
                    return this.child(this.childCount - 1);
                }
                get lastNamedChild() {
                    return this.namedChild(this.namedChildCount - 1);
                }
                get children() {
                    if (!this._children) {
                        marshalNode(this);
                        C._ts_node_children_wasm(this.tree[0]);
                        const count = getValue(TRANSFER_BUFFER, 'i32');
                        const buffer = getValue(TRANSFER_BUFFER + 4, 'i32');
                        this._children = new Array(count);
                        if (count > 0) {
                            let address = buffer;
                            for(let i1 = 0; i1 < count; i1++){
                                this._children[i1] = unmarshalNode(this.tree, address);
                                address += SIZE_OF_NODE;
                            }
                            C._free(buffer);
                        }
                    }
                    return this._children;
                }
                get namedChildren() {
                    if (!this._namedChildren) {
                        marshalNode(this);
                        C._ts_node_named_children_wasm(this.tree[0]);
                        const count = getValue(TRANSFER_BUFFER, 'i32');
                        const buffer = getValue(TRANSFER_BUFFER + 4, 'i32');
                        this._namedChildren = new Array(count);
                        if (count > 0) {
                            let address = buffer;
                            for(let i1 = 0; i1 < count; i1++){
                                this._namedChildren[i1] = unmarshalNode(this.tree, address);
                                address += SIZE_OF_NODE;
                            }
                            C._free(buffer);
                        }
                    }
                    return this._namedChildren;
                }
                descendantsOfType(types, startPosition, endPosition) {
                    if (!Array.isArray(types)) types = [
                        types
                    ];
                    if (!startPosition) startPosition = ZERO_POINT;
                    if (!endPosition) endPosition = ZERO_POINT;
                    const symbols = [];
                    const typesBySymbol = this.tree.language.types;
                    for(let i1 = 0, n = typesBySymbol.length; i1 < n; i1++){
                        if (types.includes(typesBySymbol[i1])) {
                            symbols.push(i1);
                        }
                    }
                    const symbolsAddress = C._malloc(4 * symbols.length);
                    for(let i1 = 0, n = symbols.length; i1 < n; i1++){
                        setValue(symbolsAddress + i1 * 4, symbols[i1], 'i32');
                    }
                    marshalNode(this);
                    C._ts_node_descendants_of_type_wasm(this.tree[0], symbolsAddress, symbols.length, startPosition.row, startPosition.column, endPosition.row, endPosition.column);
                    const descendantCount = getValue(TRANSFER_BUFFER, 'i32');
                    const descendantAddress = getValue(TRANSFER_BUFFER + 4, 'i32');
                    const result1 = new Array(descendantCount);
                    if (descendantCount > 0) {
                        let address = descendantAddress;
                        for(let i1 = 0; i1 < descendantCount; i1++){
                            result1[i1] = unmarshalNode(this.tree, address);
                            address += SIZE_OF_NODE;
                        }
                    }
                    C._free(descendantAddress);
                    C._free(symbolsAddress);
                    return result1;
                }
                get nextSibling() {
                    marshalNode(this);
                    C._ts_node_next_sibling_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                get previousSibling() {
                    marshalNode(this);
                    C._ts_node_prev_sibling_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                get nextNamedSibling() {
                    marshalNode(this);
                    C._ts_node_next_named_sibling_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                get previousNamedSibling() {
                    marshalNode(this);
                    C._ts_node_prev_named_sibling_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                get parent() {
                    marshalNode(this);
                    C._ts_node_parent_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                descendantForIndex(start, end = start) {
                    if (typeof start !== 'number' || typeof end !== 'number') {
                        throw new Error('Arguments must be numbers');
                    }
                    marshalNode(this);
                    let address = TRANSFER_BUFFER + SIZE_OF_NODE;
                    setValue(address, start, 'i32');
                    setValue(address + 4, end, 'i32');
                    C._ts_node_descendant_for_index_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                namedDescendantForIndex(start, end = start) {
                    if (typeof start !== 'number' || typeof end !== 'number') {
                        throw new Error('Arguments must be numbers');
                    }
                    marshalNode(this);
                    let address = TRANSFER_BUFFER + SIZE_OF_NODE;
                    setValue(address, start, 'i32');
                    setValue(address + 4, end, 'i32');
                    C._ts_node_named_descendant_for_index_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                descendantForPosition(start, end = start) {
                    if (!isPoint(start) || !isPoint(end)) {
                        throw new Error('Arguments must be {row, column} objects');
                    }
                    marshalNode(this);
                    let address = TRANSFER_BUFFER + SIZE_OF_NODE;
                    marshalPoint(address, start);
                    marshalPoint(address + SIZE_OF_POINT, end);
                    C._ts_node_descendant_for_position_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                namedDescendantForPosition(start, end = start) {
                    if (!isPoint(start) || !isPoint(end)) {
                        throw new Error('Arguments must be {row, column} objects');
                    }
                    marshalNode(this);
                    let address = TRANSFER_BUFFER + SIZE_OF_NODE;
                    marshalPoint(address, start);
                    marshalPoint(address + SIZE_OF_POINT, end);
                    C._ts_node_named_descendant_for_position_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                walk() {
                    marshalNode(this);
                    C._ts_tree_cursor_new_wasm(this.tree[0]);
                    return new TreeCursor(INTERNAL, this.tree);
                }
                toString() {
                    marshalNode(this);
                    const address = C._ts_node_to_string_wasm(this.tree[0]);
                    const result1 = AsciiToString(address);
                    C._free(address);
                    return result1;
                }
            }
            class TreeCursor {
                constructor(internal, tree){
                    assertInternal(internal);
                    this.tree = tree;
                    unmarshalTreeCursor(this);
                }
                delete() {
                    marshalTreeCursor(this);
                    C._ts_tree_cursor_delete_wasm(this.tree[0]);
                    this[0] = this[1] = this[2] = 0;
                }
                reset(node) {
                    marshalNode(node);
                    marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
                    C._ts_tree_cursor_reset_wasm(this.tree[0]);
                    unmarshalTreeCursor(this);
                }
                get nodeType() {
                    return this.tree.language.types[this.nodeTypeId] || 'ERROR';
                }
                get nodeTypeId() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
                }
                get nodeId() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
                }
                get nodeIsNamed() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
                }
                get nodeIsMissing() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
                }
                get nodeText() {
                    marshalTreeCursor(this);
                    const startIndex = C._ts_tree_cursor_start_index_wasm(this.tree[0]);
                    const endIndex = C._ts_tree_cursor_end_index_wasm(this.tree[0]);
                    return getText(this.tree, startIndex, endIndex);
                }
                get startPosition() {
                    marshalTreeCursor(this);
                    C._ts_tree_cursor_start_position_wasm(this.tree[0]);
                    return unmarshalPoint(TRANSFER_BUFFER);
                }
                get endPosition() {
                    marshalTreeCursor(this);
                    C._ts_tree_cursor_end_position_wasm(this.tree[0]);
                    return unmarshalPoint(TRANSFER_BUFFER);
                }
                get startIndex() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_start_index_wasm(this.tree[0]);
                }
                get endIndex() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_end_index_wasm(this.tree[0]);
                }
                currentNode() {
                    marshalTreeCursor(this);
                    C._ts_tree_cursor_current_node_wasm(this.tree[0]);
                    return unmarshalNode(this.tree);
                }
                currentFieldId() {
                    marshalTreeCursor(this);
                    return C._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
                }
                currentFieldName() {
                    return this.tree.language.fields[this.currentFieldId()];
                }
                gotoFirstChild() {
                    marshalTreeCursor(this);
                    const result1 = C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
                    unmarshalTreeCursor(this);
                    return result1 === 1;
                }
                gotoNextSibling() {
                    marshalTreeCursor(this);
                    const result1 = C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
                    unmarshalTreeCursor(this);
                    return result1 === 1;
                }
                gotoParent() {
                    marshalTreeCursor(this);
                    const result1 = C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
                    unmarshalTreeCursor(this);
                    return result1 === 1;
                }
            }
            class Language {
                constructor(internal, address){
                    assertInternal(internal);
                    this[0] = address;
                    this.types = new Array(C._ts_language_symbol_count(this[0]));
                    for(let i1 = 0, n = this.types.length; i1 < n; i1++){
                        if (C._ts_language_symbol_type(this[0], i1) < 2) {
                            this.types[i1] = UTF8ToString(C._ts_language_symbol_name(this[0], i1));
                        }
                    }
                    this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
                    for(let i1 = 0, n = this.fields.length; i1 < n; i1++){
                        const fieldName = C._ts_language_field_name_for_id(this[0], i1);
                        if (fieldName !== 0) {
                            this.fields[i1] = UTF8ToString(fieldName);
                        } else {
                            this.fields[i1] = null;
                        }
                    }
                }
                get version() {
                    return C._ts_language_version(this[0]);
                }
                get fieldCount() {
                    return this.fields.length - 1;
                }
                fieldIdForName(fieldName) {
                    const result1 = this.fields.indexOf(fieldName);
                    if (result1 !== -1) {
                        return result1;
                    } else {
                        return null;
                    }
                }
                fieldNameForId(fieldId) {
                    return this.fields[fieldId] || null;
                }
                idForNodeType(type, named) {
                    const typeLength = lengthBytesUTF8(type);
                    const typeAddress = C._malloc(typeLength + 1);
                    stringToUTF8(type, typeAddress, typeLength + 1);
                    const result1 = C._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named);
                    C._free(typeAddress);
                    return result1 || null;
                }
                get nodeTypeCount() {
                    return C._ts_language_symbol_count(this[0]);
                }
                nodeTypeForId(typeId) {
                    const name = C._ts_language_symbol_name(this[0], typeId);
                    return name ? UTF8ToString(name) : null;
                }
                nodeTypeIsNamed(typeId) {
                    return C._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
                }
                nodeTypeIsVisible(typeId) {
                    return C._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
                }
                query(source) {
                    const sourceLength = lengthBytesUTF8(source);
                    const sourceAddress = C._malloc(sourceLength + 1);
                    stringToUTF8(source, sourceAddress, sourceLength + 1);
                    const address = C._ts_query_new(this[0], sourceAddress, sourceLength, TRANSFER_BUFFER, TRANSFER_BUFFER + 4);
                    if (!address) {
                        const errorId = getValue(TRANSFER_BUFFER + 4, 'i32');
                        const errorByte = getValue(TRANSFER_BUFFER, 'i32');
                        const errorIndex = UTF8ToString(sourceAddress, errorByte).length;
                        const suffix = source.substr(errorIndex, 100).split('\n')[0];
                        let word = suffix.match(QUERY_WORD_REGEX)[0];
                        let error;
                        switch(errorId){
                            case 2:
                                error = new RangeError(`Bad node name '${word}'`);
                                break;
                            case 3:
                                error = new RangeError(`Bad field name '${word}'`);
                                break;
                            case 4:
                                error = new RangeError(`Bad capture name @${word}`);
                                break;
                            case 5:
                                error = new TypeError(`Bad pattern structure at offset ${errorIndex}: '${suffix}'...`);
                                word = "";
                                break;
                            default:
                                error = new SyntaxError(`Bad syntax at offset ${errorIndex}: '${suffix}'...`);
                                word = "";
                                break;
                        }
                        error.index = errorIndex;
                        error.length = word.length;
                        C._free(sourceAddress);
                        throw error;
                    }
                    const stringCount = C._ts_query_string_count(address);
                    const captureCount = C._ts_query_capture_count(address);
                    const patternCount = C._ts_query_pattern_count(address);
                    const captureNames = new Array(captureCount);
                    const stringValues = new Array(stringCount);
                    for(let i1 = 0; i1 < captureCount; i1++){
                        const nameAddress = C._ts_query_capture_name_for_id(address, i1, TRANSFER_BUFFER);
                        const nameLength = getValue(TRANSFER_BUFFER, 'i32');
                        captureNames[i1] = UTF8ToString(nameAddress, nameLength);
                    }
                    for(let i1 = 0; i1 < stringCount; i1++){
                        const valueAddress = C._ts_query_string_value_for_id(address, i1, TRANSFER_BUFFER);
                        const nameLength = getValue(TRANSFER_BUFFER, 'i32');
                        stringValues[i1] = UTF8ToString(valueAddress, nameLength);
                    }
                    const setProperties = new Array(patternCount);
                    const assertedProperties = new Array(patternCount);
                    const refutedProperties = new Array(patternCount);
                    const predicates = new Array(patternCount);
                    const textPredicates = new Array(patternCount);
                    for(let i1 = 0; i1 < patternCount; i1++){
                        const predicatesAddress = C._ts_query_predicates_for_pattern(address, i1, TRANSFER_BUFFER);
                        const stepCount = getValue(TRANSFER_BUFFER, 'i32');
                        predicates[i1] = [];
                        textPredicates[i1] = [];
                        const steps = [];
                        let stepAddress = predicatesAddress;
                        for(let j = 0; j < stepCount; j++){
                            const stepType = getValue(stepAddress, 'i32');
                            stepAddress += SIZE_OF_INT;
                            const stepValueId = getValue(stepAddress, 'i32');
                            stepAddress += SIZE_OF_INT;
                            if (stepType === 1) {
                                steps.push({
                                    type: 'capture',
                                    name: captureNames[stepValueId]
                                });
                            } else if (stepType === 2) {
                                steps.push({
                                    type: 'string',
                                    value: stringValues[stepValueId]
                                });
                            } else if (steps.length > 0) {
                                if (steps[0].type !== 'string') {
                                    throw new Error('Predicates must begin with a literal value');
                                }
                                const operator = steps[0].value;
                                let isPositive = true;
                                switch(operator){
                                    case 'not-eq?':
                                        isPositive = false;
                                    case 'eq?':
                                        if (steps.length !== 3) throw new Error(`Wrong number of arguments to \`#eq?\` predicate. Expected 2, got ${steps.length - 1}`);
                                        if (steps[1].type !== 'capture') throw new Error(`First argument of \`#eq?\` predicate must be a capture. Got "${steps[1].value}"`);
                                        if (steps[2].type === 'capture') {
                                            const captureName1 = steps[1].name;
                                            const captureName2 = steps[2].name;
                                            textPredicates[i1].push(function(captures) {
                                                let node1, node2;
                                                for (const c of captures){
                                                    if (c.name === captureName1) node1 = c.node;
                                                    if (c.name === captureName2) node2 = c.node;
                                                }
                                                if (node1 === undefined || node2 === undefined) return true;
                                                return node1.text === node2.text === isPositive;
                                            });
                                        } else {
                                            const captureName = steps[1].name;
                                            const stringValue = steps[2].value;
                                            textPredicates[i1].push(function(captures) {
                                                for (const c of captures){
                                                    if (c.name === captureName) {
                                                        return c.node.text === stringValue === isPositive;
                                                    }
                                                }
                                                return true;
                                            });
                                        }
                                        break;
                                    case 'not-match?':
                                        isPositive = false;
                                    case 'match?':
                                        if (steps.length !== 3) throw new Error(`Wrong number of arguments to \`#match?\` predicate. Expected 2, got ${steps.length - 1}.`);
                                        if (steps[1].type !== 'capture') throw new Error(`First argument of \`#match?\` predicate must be a capture. Got "${steps[1].value}".`);
                                        if (steps[2].type !== 'string') throw new Error(`Second argument of \`#match?\` predicate must be a string. Got @${steps[2].value}.`);
                                        const captureName = steps[1].name;
                                        const regex = new RegExp(steps[2].value);
                                        textPredicates[i1].push(function(captures) {
                                            for (const c of captures){
                                                if (c.name === captureName) return regex.test(c.node.text) === isPositive;
                                            }
                                            return true;
                                        });
                                        break;
                                    case 'set!':
                                        if (steps.length < 2 || steps.length > 3) throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
                                        if (steps.some((s)=>s.type !== 'string')) throw new Error(`Arguments to \`#set!\` predicate must be a strings.".`);
                                        if (!setProperties[i1]) setProperties[i1] = {};
                                        setProperties[i1][steps[1].value] = steps[2] ? steps[2].value : null;
                                        break;
                                    case 'is?':
                                    case 'is-not?':
                                        if (steps.length < 2 || steps.length > 3) throw new Error(`Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
                                        if (steps.some((s)=>s.type !== 'string')) throw new Error(`Arguments to \`#${operator}\` predicate must be a strings.".`);
                                        const properties = operator === 'is?' ? assertedProperties : refutedProperties;
                                        if (!properties[i1]) properties[i1] = {};
                                        properties[i1][steps[1].value] = steps[2] ? steps[2].value : null;
                                        break;
                                    default:
                                        predicates[i1].push({
                                            operator,
                                            operands: steps.slice(1)
                                        });
                                }
                                steps.length = 0;
                            }
                        }
                        Object.freeze(setProperties[i1]);
                        Object.freeze(assertedProperties[i1]);
                        Object.freeze(refutedProperties[i1]);
                    }
                    C._free(sourceAddress);
                    return new Query(INTERNAL, address, captureNames, textPredicates, predicates, Object.freeze(setProperties), Object.freeze(assertedProperties), Object.freeze(refutedProperties));
                }
                static load(input) {
                    let bytes;
                    if (input instanceof Uint8Array) {
                        bytes = Promise.resolve(input);
                    } else {
                        bytes = Promise.resolve(Deno.readFileSync(input));
                    }
                    const loadModule = loadWebAssemblyModule;
                    return bytes.then((bytes)=>loadModule(bytes, {
                            loadAsync: true
                        })).then((mod)=>{
                        const symbolNames = Object.keys(mod);
                        const functionName = symbolNames.find((key)=>LANGUAGE_FUNCTION_REGEX.test(key) && !key.includes("external_scanner_"));
                        if (!functionName) {
                            console.log(`Couldn't find language function in WASM file. Symbols:\n${JSON.stringify(symbolNames, null, 2)}`);
                        }
                        const languageAddress = mod[functionName]();
                        return new Language(INTERNAL, languageAddress);
                    });
                }
            }
            class Query {
                constructor(internal, address, captureNames, textPredicates, predicates, setProperties, assertedProperties, refutedProperties){
                    assertInternal(internal);
                    this[0] = address;
                    this.captureNames = captureNames;
                    this.textPredicates = textPredicates;
                    this.predicates = predicates;
                    this.setProperties = setProperties;
                    this.assertedProperties = assertedProperties;
                    this.refutedProperties = refutedProperties;
                    this.exceededMatchLimit = false;
                }
                delete() {
                    C._ts_query_delete(this[0]);
                    this[0] = 0;
                }
                matches(node, startPosition, endPosition, options) {
                    if (!startPosition) startPosition = ZERO_POINT;
                    if (!endPosition) endPosition = ZERO_POINT;
                    if (!options) options = {};
                    let matchLimit = options.matchLimit;
                    if (typeof matchLimit === 'undefined') {
                        matchLimit = 0;
                    } else if (typeof matchLimit !== 'number') {
                        throw new Error('Arguments must be numbers');
                    }
                    marshalNode(node);
                    C._ts_query_matches_wasm(this[0], node.tree[0], startPosition.row, startPosition.column, endPosition.row, endPosition.column, matchLimit);
                    const rawCount = getValue(TRANSFER_BUFFER, 'i32');
                    const startAddress = getValue(TRANSFER_BUFFER + 4, 'i32');
                    const didExceedMatchLimit = getValue(TRANSFER_BUFFER + 2 * 4, 'i32');
                    const result1 = new Array(rawCount);
                    this.exceededMatchLimit = !!didExceedMatchLimit;
                    let filteredCount = 0;
                    let address = startAddress;
                    for(let i1 = 0; i1 < rawCount; i1++){
                        const pattern = getValue(address, 'i32');
                        address += SIZE_OF_INT;
                        const captureCount = getValue(address, 'i32');
                        address += SIZE_OF_INT;
                        const captures = new Array(captureCount);
                        address = unmarshalCaptures(this, node.tree, address, captures);
                        if (this.textPredicates[pattern].every((p)=>p(captures))) {
                            result1[filteredCount++] = {
                                pattern,
                                captures
                            };
                            const setProperties = this.setProperties[pattern];
                            if (setProperties) result1[i1].setProperties = setProperties;
                            const assertedProperties = this.assertedProperties[pattern];
                            if (assertedProperties) result1[i1].assertedProperties = assertedProperties;
                            const refutedProperties = this.refutedProperties[pattern];
                            if (refutedProperties) result1[i1].refutedProperties = refutedProperties;
                        }
                    }
                    result1.length = filteredCount;
                    C._free(startAddress);
                    return result1;
                }
                captures(node, startPosition, endPosition, options) {
                    if (!startPosition) startPosition = ZERO_POINT;
                    if (!endPosition) endPosition = ZERO_POINT;
                    if (!options) options = {};
                    let matchLimit = options.matchLimit;
                    if (typeof matchLimit === 'undefined') {
                        matchLimit = 0;
                    } else if (typeof matchLimit !== 'number') {
                        throw new Error('Arguments must be numbers');
                    }
                    marshalNode(node);
                    C._ts_query_captures_wasm(this[0], node.tree[0], startPosition.row, startPosition.column, endPosition.row, endPosition.column, matchLimit);
                    const count = getValue(TRANSFER_BUFFER, 'i32');
                    const startAddress = getValue(TRANSFER_BUFFER + 4, 'i32');
                    const didExceedMatchLimit = getValue(TRANSFER_BUFFER + 2 * 4, 'i32');
                    const result1 = [];
                    this.exceededMatchLimit = !!didExceedMatchLimit;
                    const captures = [];
                    let address = startAddress;
                    for(let i1 = 0; i1 < count; i1++){
                        const pattern = getValue(address, 'i32');
                        address += SIZE_OF_INT;
                        const captureCount = getValue(address, 'i32');
                        address += SIZE_OF_INT;
                        const captureIndex = getValue(address, 'i32');
                        address += SIZE_OF_INT;
                        captures.length = captureCount;
                        address = unmarshalCaptures(this, node.tree, address, captures);
                        if (this.textPredicates[pattern].every((p)=>p(captures))) {
                            const capture = captures[captureIndex];
                            const setProperties = this.setProperties[pattern];
                            if (setProperties) capture.setProperties = setProperties;
                            const assertedProperties = this.assertedProperties[pattern];
                            if (assertedProperties) capture.assertedProperties = assertedProperties;
                            const refutedProperties = this.refutedProperties[pattern];
                            if (refutedProperties) capture.refutedProperties = refutedProperties;
                            result1.push(capture);
                        }
                    }
                    C._free(startAddress);
                    return result1;
                }
                predicatesForPattern(patternIndex) {
                    return this.predicates[patternIndex];
                }
                didExceedMatchLimit() {
                    return this.exceededMatchLimit;
                }
            }
            function getText(tree, startIndex, endIndex) {
                const length = endIndex - startIndex;
                let result1 = tree.textCallback(startIndex, null, endIndex);
                startIndex += result1.length;
                while(startIndex < endIndex){
                    const string = tree.textCallback(startIndex, null, endIndex);
                    if (string && string.length > 0) {
                        startIndex += string.length;
                        result1 += string;
                    } else {
                        break;
                    }
                }
                if (startIndex > endIndex) {
                    result1 = result1.slice(0, length);
                }
                return result1;
            }
            function unmarshalCaptures(query, tree, address, result1) {
                for(let i1 = 0, n = result1.length; i1 < n; i1++){
                    const captureIndex = getValue(address, 'i32');
                    address += SIZE_OF_INT;
                    const node = unmarshalNode(tree, address);
                    address += SIZE_OF_NODE;
                    result1[i1] = {
                        name: query.captureNames[captureIndex],
                        node
                    };
                }
                return address;
            }
            function assertInternal(x) {
                if (x !== INTERNAL) throw new Error('Illegal constructor');
            }
            function isPoint(point) {
                return point && typeof point.row === 'number' && typeof point.column === 'number';
            }
            function marshalNode(node) {
                let address = TRANSFER_BUFFER;
                setValue(address, node.id, 'i32');
                address += SIZE_OF_INT;
                setValue(address, node.startIndex, 'i32');
                address += SIZE_OF_INT;
                setValue(address, node.startPosition.row, 'i32');
                address += SIZE_OF_INT;
                setValue(address, node.startPosition.column, 'i32');
                address += SIZE_OF_INT;
                setValue(address, node[0], 'i32');
            }
            function unmarshalNode(tree, address = TRANSFER_BUFFER) {
                const id = getValue(address, 'i32');
                address += SIZE_OF_INT;
                if (id === 0) return null;
                const index = getValue(address, 'i32');
                address += SIZE_OF_INT;
                const row = getValue(address, 'i32');
                address += SIZE_OF_INT;
                const column = getValue(address, 'i32');
                address += SIZE_OF_INT;
                const other = getValue(address, 'i32');
                const result1 = new Node(INTERNAL, tree);
                result1.id = id;
                result1.startIndex = index;
                result1.startPosition = {
                    row,
                    column
                };
                result1[0] = other;
                return result1;
            }
            function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
                setValue(address + 0 * 4, cursor[0], 'i32'), setValue(address + 1 * 4, cursor[1], 'i32'), setValue(address + 2 * 4, cursor[2], 'i32');
            }
            function unmarshalTreeCursor(cursor) {
                cursor[0] = getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, 'i32'), cursor[1] = getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, 'i32'), cursor[2] = getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, 'i32');
            }
            function marshalPoint(address, point) {
                setValue(address, point.row, 'i32');
                setValue(address + 4, point.column, 'i32');
            }
            function unmarshalPoint(address) {
                return {
                    row: getValue(address, 'i32'),
                    column: getValue(address + 4, 'i32')
                };
            }
            function marshalRange(address, range) {
                marshalPoint(address, range.startPosition);
                address += SIZE_OF_POINT;
                marshalPoint(address, range.endPosition);
                address += SIZE_OF_POINT;
                setValue(address, range.startIndex, 'i32');
                address += SIZE_OF_INT;
                setValue(address, range.endIndex, 'i32');
                address += SIZE_OF_INT;
            }
            function unmarshalRange(address) {
                const result1 = {};
                result1.startPosition = unmarshalPoint(address);
                address += SIZE_OF_POINT;
                result1.endPosition = unmarshalPoint(address);
                address += SIZE_OF_POINT;
                result1.startIndex = getValue(address, 'i32');
                address += SIZE_OF_INT;
                result1.endIndex = getValue(address, 'i32');
                return result1;
            }
            function marshalEdit(edit) {
                let address = TRANSFER_BUFFER;
                marshalPoint(address, edit.startPosition);
                address += SIZE_OF_POINT;
                marshalPoint(address, edit.oldEndPosition);
                address += SIZE_OF_POINT;
                marshalPoint(address, edit.newEndPosition);
                address += SIZE_OF_POINT;
                setValue(address, edit.startIndex, 'i32');
                address += SIZE_OF_INT;
                setValue(address, edit.oldEndIndex, 'i32');
                address += SIZE_OF_INT;
                setValue(address, edit.newEndIndex, 'i32');
                address += SIZE_OF_INT;
            }
            for (const name of Object.getOwnPropertyNames(ParserImpl.prototype)){
                Object.defineProperty(Parser.prototype, name, {
                    value: ParserImpl.prototype[name],
                    enumerable: false,
                    writable: false
                });
            }
            Parser.Language = Language;
            Module.onRuntimeInitialized = ()=>{
                ParserImpl.init();
            };
            await run();
            init1 = true;
        }
    }
    return Parser;
}();
function setMainPath(path) {
    path;
}
async function initTreeSitter() {
    setWasmBinaryFile(Deno.readFileSync(resourcePath("editor/tools/yaml/tree-sitter.wasm")));
    await TreeSitter.init();
    const parser = new TreeSitter();
    const language = await TreeSitter.Language.load(resourcePath("editor/tools/yaml/tree-sitter-yaml.wasm"));
    parser.setLanguage(language);
    setMainPath("https://example.com");
    setTreeSitter(parser);
}
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);
    }
    try {
        const extendedLangCommentChars = getYamlIntelligenceResource("handlers/lang-comment-chars.yml");
        for (const [lang, comment] of Object.entries(extendedLangCommentChars)){
            kLangCommentChars[lang] = comment;
        }
    } catch (_e) {
        console.warn(`"handlers/lang-comment-chars.yml" not found.
initialization does not contain language extensions`);
    }
    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
    });
    await initTreeSitter();
}
const subarticleTemplatePath = formatResourcePath("jats", join2("pandoc", "subarticle", "template.xml"));
const jatsContributor = {
    resolve: resolveJats,
    render: renderJats,
    outputFile
};
function outputFile(nbAbsPath) {
    return jatsOutputFile(nbAbsPath);
}
function resolveJats(nbAbsPath, token, executedFile, _notebookMetadata) {
    const resolved = __VIRTUAL_FILE107(executedFile);
    const to = resolved.recipe.format.render[kVariant]?.includes("+element_citations") ? "jats+element_citations" : "jats";
    resolved.recipe.format.metadata[kLintXml] = false;
    resolved.recipe.format.metadata[kJatsSubarticle] = true;
    resolved.recipe.format.metadata[kJatsSubarticleId] = token;
    resolved.recipe.format.pandoc[kOutputFile] = outputFile(nbAbsPath);
    resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
    resolved.recipe.format.pandoc.to = to;
    resolved.recipe.format.pandoc[kTemplate] = subarticleTemplatePath;
    resolved.recipe.format.execute.echo = false;
    resolved.recipe.format.execute.warning = false;
    resolved.recipe.format.render[kKeepHidden] = true;
    resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
    resolved.recipe.format.metadata[kRemoveHidden] = "none";
    if (resolved.recipe.format.render[kIpynbProduceSourceNotebook]) {
        resolved.recipe.format.render[kClearCellOptions] = true;
    }
    return resolved;
}
async function renderJats(nbPath, format, subArticleToken, services, _notebookMetadata, project) {
    const to = format.render[kVariant]?.includes("+element_citations") ? "jats+element_citations" : "jats";
    const rendered = await renderFile({
        path: nbPath,
        formats: [
            "jats"
        ]
    }, {
        services,
        flags: {
            metadata: {
                [kTo]: to,
                [kLintXml]: false,
                [kJatsSubarticle]: true,
                [kJatsSubarticleId]: subArticleToken,
                [kOutputFile]: outputFile(nbPath),
                [kTemplate]: subarticleTemplatePath,
                [kNotebookPreserveCells]: true
            },
            quiet: false
        },
        echo: true,
        warning: true,
        quietPandoc: true
    }, services, project);
    if (rendered.error) {
        error("Rendering of subarticle produced an unexpected result");
        throw rendered.error;
    }
    if (rendered.files.length !== 1) {
        throw new InternalError(`Rendering a JATS subarticle should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`);
    }
    return rendered.files[0];
}
function jatsOutputFile(nbAbsPath) {
    const [_dir, stem] = dirAndStem(nbAbsPath);
    return `${stem}.subarticle.xml`;
}
const htmlNotebookContributor = {
    resolve: resolveHtmlNotebook,
    render: renderHtmlNotebook,
    outputFile: outputFile1,
    cachedPath
};
function outputFile1(nbAbsPath) {
    const [_dir, stem] = dirAndStem(basename2(nbAbsPath));
    return `${stem}-preview.html`;
}
function cachedPath(nbAbsPath, project) {
    if (project) {
        const nbRelative = relative2(project.dir, dirname2(nbAbsPath));
        const nbOutputDir = join2(projectOutputDir(project), nbRelative);
        const outFile = outputFile1(nbAbsPath);
        const outPath = join2(nbOutputDir, outFile);
        if (existsSync(outPath)) {
            return outPath;
        }
    }
}
function resolveHtmlNotebook(nbAbsPath, _token, executedFile, notebookMetadata) {
    const resolved = __VIRTUAL_FILE107(executedFile);
    resolved.recipe.format.pandoc[kOutputFile] = `${outputFile1(nbAbsPath)}`;
    resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
    resolved.recipe.format.execute.echo = false;
    resolved.recipe.format.execute.warning = false;
    resolved.recipe.format.render[kKeepHidden] = true;
    resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
    resolved.recipe.format.metadata[kRemoveHidden] = "none";
    if (resolved.recipe.format.render[kIpynbProduceSourceNotebook]) {
        resolved.recipe.format.render[kClearCellOptions] = true;
    }
    const template = formatResourcePath("html", join2("embed", "template.html"));
    resolved.recipe.format.pandoc[kTemplate] = template;
    resolved.recipe.format.metadata["nbMeta"] = {
        ...notebookMetadata,
        downloadLabel: downloadLabel(notebookMetadata?.filename || nbAbsPath, resolved.recipe.format),
        backLabel: resolved.recipe.format.language[kNotebookPreviewBack]
    };
    resolved.recipe.format.render[kNotebookViewStyle] = kNotebookViewStyleNotebook;
    resolved.recipe.format.render[kNotebookPreserveCells] = true;
    resolved.recipe.format.metadata[kUnrollMarkdownCells] = false;
    resolved.recipe.format.pandoc[kToc] = true;
    resolved.recipe.format.metadata[kTocLocation] = "left";
    resolved.recipe.format.metadata[kAppendixStyle] = "none";
    resolved.recipe.format.render[kFormatLinks] = false;
    resolved.recipe.format.metadata[kDisableArticleLayout] = true;
    return resolved;
}
async function renderHtmlNotebook(nbPath, format, _subArticleToken, services, notebookMetadata, project) {
    const template = formatResourcePath("html", join2("embed", "template.html"));
    const rendered = await renderFile({
        path: nbPath,
        formats: [
            "html"
        ]
    }, {
        services,
        flags: {
            metadata: {
                [kTo]: "html",
                [kTheme]: format.metadata[kTheme],
                [kOutputFile]: `${outputFile1(nbPath)}`,
                [kTemplate]: template,
                [kNotebookViewStyle]: kNotebookViewStyleNotebook,
                [kAppendixStyle]: "none",
                [kNotebookPreserveCells]: true,
                ["nbMeta"]: {
                    ...notebookMetadata,
                    downloadLabel: downloadLabel(notebookMetadata?.filename || nbPath, format),
                    backLabel: format.language[kNotebookPreviewBack]
                },
                [kToc]: true,
                [kTocLocation]: "left",
                [kDisableArticleLayout]: true
            },
            quiet: false
        },
        echo: true,
        warning: true,
        quietPandoc: true
    }, services, project);
    if (rendered.error) {
        error("Rendering of output notebook produced an unexpected result");
        throw rendered.error;
    }
    if (rendered.files.length !== 1) {
        throw new InternalError(`Rendering an output notebook should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`);
    }
    return rendered.files[0];
}
function downloadLabel(file, format) {
    return isQmdFile(file) ? format.language[kNotebookPreviewDownloadSrc] : format.language[kNotebookPreviewDownload];
}
const outputNotebookContributor = {
    resolve: resolveOutputNotebook,
    render: renderOutputNotebook,
    outputFile: outputFile2,
    cachedPath: cachedPath1
};
function outputFile2(nbAbsPath) {
    return ipynbOutputFile(nbAbsPath);
}
function cachedPath1(nbAbsPath, project) {
    if (project) {
        const nbRelative = relative2(project.dir, dirname2(nbAbsPath));
        const nbOutputDir = join2(projectOutputDir(project), nbRelative);
        const outFile = outputFile2(nbAbsPath);
        const outPath = join2(nbOutputDir, outFile);
        if (existsSync(outPath)) {
            return outPath;
        }
    }
}
function resolveOutputNotebook(nbAbsPath, _token, executedFile, _notebookMetadata) {
    const resolved = __VIRTUAL_FILE107(executedFile);
    resolved.recipe.format.pandoc[kOutputFile] = outputFile2(nbAbsPath);
    resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
    resolved.recipe.format.pandoc.to = "ipynb";
    const template = ipynbTitleTemplatePath();
    resolved.recipe.format.execute.echo = false;
    resolved.recipe.format.execute.warning = false;
    resolved.recipe.format.render[kKeepHidden] = true;
    resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
    resolved.recipe.format.metadata[kRemoveHidden] = "none";
    resolved.recipe.format.metadata[kIPynbTitleBlockTemplate] = template;
    if (resolved.recipe.format.render[kIpynbProduceSourceNotebook]) {
        resolved.recipe.format.render[kClearCellOptions] = true;
    }
    resolved.recipe.format.metadata[kUnrollMarkdownCells] = false;
    return resolved;
}
async function renderOutputNotebook(nbPath, _format, _subArticleToken, services, _notebookMetadata, project) {
    const rendered = await renderFile({
        path: nbPath,
        formats: [
            "ipynb"
        ]
    }, {
        services,
        flags: {
            metadata: {
                [kTo]: "ipynb",
                [kOutputFile]: outputFile2(nbPath)
            },
            quiet: false
        },
        echo: true,
        warning: true,
        quietPandoc: true
    }, services, project);
    if (rendered.error) {
        error("Rendering of output notebook produced an unexpected result");
        throw rendered.error;
    }
    if (rendered.files.length !== 1) {
        throw new InternalError(`Rendering an output notebook should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`);
    }
    return rendered.files[0];
}
function ipynbOutputFile(nbAbsPath) {
    const [_dir, stem] = dirAndStem(nbAbsPath);
    return `${stem}.out.ipynb`;
}
const qmdNotebookContributor = {
    resolve: resolveOutputNotebook1,
    render: renderOutputNotebook1,
    outputFile: outputFile3,
    cache: cache1,
    cachedPath: cachedPath2
};
function cache1(output, project) {
    if (project) {
        const path = cachePath(output.path, project);
        ensureDirSync(dirname2(path));
        Deno.copyFileSync(output.path, path);
    }
}
function cachedPath2(nbAbsPath, project) {
    if (project) {
        const output = outputFile3(nbAbsPath);
        const outputPath = join2(dirname2(nbAbsPath), output);
        const path = cachePath(outputPath, project);
        if (existsSync(path)) {
            return path;
        }
    }
}
function cachePath(nbAbsPath, project) {
    const basePath = projectScratchPath(project.dir, "embed");
    const outputRel = relative2(project.dir, nbAbsPath);
    return join2(basePath, outputRel);
}
function outputFile3(nbAbsPath) {
    return ipynbOutputFile1(nbAbsPath);
}
function resolveOutputNotebook1(nbAbsPath, _token, executedFile, _notebookMetadata) {
    const resolved = __VIRTUAL_FILE107(executedFile);
    resolved.recipe.format.pandoc[kOutputFile] = ipynbOutputFile1(nbAbsPath);
    resolved.recipe.output = resolved.recipe.format.pandoc[kOutputFile];
    resolved.recipe.format.pandoc.to = "ipynb";
    const template = ipynbTitleTemplatePath();
    resolved.recipe.format.execute.echo = false;
    resolved.recipe.format.execute.warning = false;
    resolved.recipe.format.render[kKeepHidden] = true;
    resolved.recipe.format.render[kNotebookPreserveCells] = true;
    resolved.recipe.format.metadata[kClearHiddenClasses] = "all";
    resolved.recipe.format.metadata[kRemoveHidden] = "none";
    resolved.recipe.format.metadata[kIPynbTitleBlockTemplate] = template;
    resolved.recipe.format.render[kIpynbProduceSourceNotebook] = true;
    resolved.recipe.format.pandoc.citeproc = false;
    resolved.recipe.format.metadata[kUnrollMarkdownCells] = false;
    return resolved;
}
async function renderOutputNotebook1(nbPath, _format, _subArticleToken, services, _notebookMetadata, project) {
    const rendered = await renderFile({
        path: nbPath,
        formats: [
            "ipynb"
        ]
    }, {
        services,
        flags: {
            metadata: {
                [kTo]: "ipynb",
                [kOutputFile]: ipynbOutputFile1(nbPath),
                [kNotebookPreserveCells]: true,
                [kIpynbProduceSourceNotebook]: true,
                citeproc: false
            },
            quiet: false
        },
        echo: true,
        warning: true,
        quietPandoc: true
    }, services, project, false);
    if (rendered.error) {
        error("Rendering of qmd notebook produced an unexpected result");
        throw rendered.error;
    }
    if (rendered.files.length !== 1) {
        throw new InternalError(`Rendering an qmd notebook should only result in a single file. This attempt resulted in ${rendered.files.length} file(s).`);
    }
    return rendered.files[0];
}
function ipynbOutputFile1(nbAbsPath) {
    const [_dir, stem] = dirAndStem(nbAbsPath);
    return `${stem}.embed.ipynb`;
}
const contributors = {
    [kJatsSubarticle]: jatsContributor,
    [kHtmlPreview]: htmlNotebookContributor,
    [kRenderedIPynb]: outputNotebookContributor,
    [kQmdIPynb]: qmdNotebookContributor
};
function notebookContext() {
    const notebooks = {};
    const preserveNotebooks = {};
    let nbCount = 0;
    const token = ()=>{
        return `nb-${++nbCount}`;
    };
    const emptyNotebook = (nbAbsPath)=>{
        return {
            source: nbAbsPath
        };
    };
    const addRendering = (nbAbsPath, renderType, result1, context, cached)=>{
        debug(`[NotebookContext]: Add Rendering (${renderType}):${nbAbsPath}`);
        const hrefPath = join2(dirname2(nbAbsPath), basename2(result1.file));
        const absPath = isAbsolute2(result1.file) ? result1.file : hrefPath;
        const output = {
            path: absPath,
            hrefPath,
            supporting: result1.supporting || [],
            resourceFiles: result1.resourceFiles,
            cached
        };
        const nb = notebooks[nbAbsPath] || emptyNotebook(nbAbsPath);
        nb[renderType] = output;
        notebooks[nbAbsPath] = nb;
        if (context) {
            const contrib = contributor(renderType);
            if (contrib.cache) {
                contrib.cache(output, context);
            }
        }
    };
    const removeRendering = (nbAbsPath, renderType, preserveFiles)=>{
        debug(`[NotebookContext]: Remove Rendering (${renderType}):${nbAbsPath}`);
        if (preserveNotebooks[nbAbsPath] && preserveNotebooks[nbAbsPath].includes(renderType)) {
            return;
        }
        const nb = notebooks[nbAbsPath];
        if (nb) {
            const rendering = nb[renderType];
            if (rendering) {
                safeRemoveIfExists(rendering.path);
                const filteredSupporting = rendering.supporting.filter((file)=>{
                    const absPath = join2(dirname2(nbAbsPath), file);
                    return !preserveFiles.includes(absPath);
                });
                for (const supporting of filteredSupporting){
                    safeRemoveIfExists(supporting);
                }
            }
        }
    };
    function contributor(renderType) {
        const contributor = contributors[renderType];
        if (contributor) {
            return contributor;
        } else {
            throw new InternalError(`Missing contributor ${renderType} when resolving`);
        }
    }
    function addMetadata(nbAbsPath, nbMeta) {
        debug(`[NotebookContext]: Add Notebook Metadata:${nbAbsPath}`);
        const nb = notebooks[nbAbsPath] || emptyNotebook(nbAbsPath);
        nb.metadata = nbMeta;
        notebooks[nbAbsPath] = nb;
    }
    function reviveOutput(nbAbsPath, renderType, context) {
        debug(`[NotebookContext]: Attempting to Revive Rendering (${renderType}):${nbAbsPath}`);
        const contrib = contributor(renderType);
        if (contrib.cachedPath) {
            const existingPath = contrib.cachedPath(nbAbsPath, context);
            if (existingPath) {
                if (safeExistsSync(existingPath)) {
                    const inputTime = Deno.statSync(nbAbsPath).mtime?.valueOf() || 0;
                    const outputTime = Deno.statSync(existingPath).mtime?.valueOf() || 0;
                    if (inputTime <= outputTime) {
                        debug(`[NotebookContext]: Revived Rendering (${renderType}):${nbAbsPath}`);
                        addRendering(nbAbsPath, renderType, {
                            file: existingPath,
                            supporting: [],
                            resourceFiles: {
                                globs: [],
                                files: []
                            }
                        }, context, true);
                    }
                }
            }
        }
    }
    function preserve(nbAbsPath, renderType) {
        debug(`[NotebookContext]: Preserving (${renderType}):${nbAbsPath}`);
        preserveNotebooks[nbAbsPath] = preserveNotebooks[nbAbsPath] || [];
        if (!preserveNotebooks[nbAbsPath].includes(renderType)) {
            preserveNotebooks[nbAbsPath].push(renderType);
        }
    }
    return {
        all: ()=>{
            return Object.values(notebooks);
        },
        get: (nbAbsPath, context)=>{
            debug(`[NotebookContext]: Get Notebook:${nbAbsPath}`);
            const notebook = notebooks[nbAbsPath];
            const reviveRenders = [];
            if (notebook) {
                [
                    kJatsSubarticle,
                    kHtmlPreview,
                    kRenderedIPynb
                ].forEach((renderTypeStr)=>{
                    const renderType = renderTypeStr;
                    if (!notebook[renderType]) {
                        reviveRenders.push(renderType);
                    }
                });
            } else {
                reviveRenders.push(kHtmlPreview);
                reviveRenders.push(kJatsSubarticle);
                reviveRenders.push(kRenderedIPynb);
                reviveRenders.push(kQmdIPynb);
            }
            if (context) {
                for (const renderType of reviveRenders){
                    reviveOutput(nbAbsPath, renderType, context);
                }
            }
            return notebooks[nbAbsPath];
        },
        addMetadata: (nbAbsPath, notebookMetadata)=>{
            addMetadata(nbAbsPath, notebookMetadata);
        },
        resolve: (nbAbsPath, renderType, executedFile, notebookMetadata)=>{
            debug(`[NotebookContext]: Resolving ExecutedFile (${renderType}):${nbAbsPath}`);
            if (notebookMetadata) {
                addMetadata(nbAbsPath, notebookMetadata);
            }
            return contributor(renderType).resolve(nbAbsPath, token(), executedFile, notebookMetadata);
        },
        addRendering,
        removeRendering,
        render: async (nbAbsPath, format, renderType, services, notebookMetadata, project)=>{
            debug(`[NotebookContext]: Rendering (${renderType}):${nbAbsPath}`);
            if (notebookMetadata) {
                addMetadata(nbAbsPath, notebookMetadata);
            }
            const notebook = notebooks[nbAbsPath];
            const toRenderPath = notebook ? notebook[kQmdIPynb] ? notebook[kQmdIPynb].path : nbAbsPath : nbAbsPath;
            const renderedFile = await contributor(renderType).render(toRenderPath, format, token(), services, notebookMetadata, project);
            addRendering(nbAbsPath, renderType, renderedFile, project);
            if (!notebooks[nbAbsPath][renderType]) {
                throw new InternalError("We just rendered and contributed a notebook, but it isn't present in the notebook context.");
            }
            return notebooks[nbAbsPath][renderType];
        },
        preserve,
        cleanup: ()=>{
            debug(`[NotebookContext]: Starting Cleanup`);
            const hasNotebooks = Object.keys(notebooks).length > 0;
            if (hasNotebooks) {
                Object.keys(contributors).forEach((renderTypeStr)=>{
                    Object.values(notebooks).forEach((notebook)=>{
                        const renderType = renderTypeStr;
                        if (!preserveNotebooks[notebook.source] || !preserveNotebooks[notebook.source].includes(renderType)) {
                            const notebookOutput = notebook[renderType];
                            if (notebookOutput && notebookOutput.cached !== true) {
                                debug(`[NotebookContext]: Cleanup (${renderType}):${notebook.source}`);
                                debug(`[NotebookContext]: Deleting (${notebookOutput.path}`);
                                safeRemoveIfExists(notebookOutput.path);
                                for (const supporting of notebookOutput.supporting){
                                    safeRemoveIfExists(supporting);
                                }
                            }
                        }
                    });
                });
            }
        }
    };
}
function singleFileProjectContext(source, notebookContext, flags) {
    const environmentMemoizer = makeProjectEnvironmentMemoizer(notebookContext);
    const result1 = {
        dir: normalizePath(dirname2(source)),
        engines: [],
        files: {
            input: []
        },
        notebookContext,
        environment: ()=>environmentMemoizer(result1),
        renderFormats,
        fileInformationCache: new Map(),
        fileExecutionEngineAndTarget: (file)=>{
            return fileExecutionEngineAndTarget(file, flags, result1);
        },
        resolveFullMarkdownForFile: (engine, file, markdown, force)=>{
            return projectResolveFullMarkdownForFile(result1, engine, file, markdown, force);
        },
        isSingleFile: true
    };
    return result1;
}
async function render(path, options) {
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
    const nbContext = notebookContext();
    let context = await projectContext(path, nbContext, options);
    if (!context && options.flags?.outputDir) {
        context = await projectContextForDirectory(path, nbContext, options);
        options.forceClean = options.flags.clean !== false;
    }
    if (context && options.setProjectDir) {
        Deno.env.set("QUARTO_PROJECT_DIR", context.dir);
    }
    if (Deno.statSync(path).isDirectory) {
        let files;
        if (context) {
            const renderDir = normalizePath(path);
            const projectDir = normalizePath(context.dir);
            if (renderDir !== projectDir) {
                files = context.files.input.filter((file)=>file.startsWith(renderDir));
            }
            return renderProject(context, options, files);
        } else {
            throw new Error("The specified directory ('" + path + "') is not a Quarto project.\n(If you have not specified a path, quarto will attempt to render the entire current directory as a project.)");
        }
    } else if (context?.config) {
        if (isProjectInputFile(path, context)) {
            return renderProject(context, options, [
                path
            ]);
        }
    }
    validateDocumentRenderFlags(options.flags);
    context = singleFileProjectContext(path, nbContext, options.flags);
    const result1 = await renderFiles([
        {
            path
        }
    ], options, nbContext, undefined, undefined, context);
    const { engine } = await context.fileExecutionEngineAndTarget(path);
    const partitioned = engine && result1.files.length > 0 ? await engine.partitionedMarkdown(path) : undefined;
    const excludeDirs = context ? projectExcludeDirs(context) : [];
    const renderResult = {
        context,
        files: await Promise.all(result1.files.map(async (file)=>{
            const resourceFiles = await resourceFilesFromRenderedFile(dirname2(path), excludeDirs, file, partitioned);
            return {
                input: file.input,
                markdown: file.markdown,
                format: file.format,
                file: file.file,
                supporting: file.supporting,
                resourceFiles
            };
        })),
        error: result1.error,
        baseDir: normalizePath(dirname2(path))
    };
    if (!renderResult.error && engine?.postRender) {
        for (const file of renderResult.files){
            await engine.postRender(file, renderResult.context);
        }
    }
    return renderResult;
}
function printWatchingForChangesMessage() {
    info("Watching files for changes", {
        format: green
    });
}
function previewUnableToRenderResponse() {
    return new Response("not found", {
        status: 404,
        headers: {
            "Content-Type": kTextPlain
        }
    });
}
let quartoRenderToken;
function renderToken() {
    const kQuartoRenderToken = "QUARTO_RENDER_TOKEN";
    if (quartoRenderToken === undefined) {
        quartoRenderToken = Deno.env.get(kQuartoRenderToken) || null;
        Deno.env.delete(kQuartoRenderToken);
    }
    return quartoRenderToken;
}
function validateDocumentRenderFlags(flags) {
    if (flags) {
        const projectOnly = {
            ["--output-dir"]: flags.outputDir,
            ["--site-url"]: flags.siteUrl
        };
        for (const arg of Object.keys(projectOnly)){
            if (projectOnly[arg]) {
                throw new Error(`The ${arg} flag can only be used when rendering projects.`);
            }
        }
    }
}
const renderCommand = new Command().name("render").stopEarly().arguments("[input:string] [...args]").description("Render files or projects 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 output to DIR (path is input/project relative)").option("-M, --metadata", "Metadata value (KEY:VALUE).").option("--site-url", "Override site-url for website or book output").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 when executing computations.").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", "quarto render document.qmd\n" + "quarto render document.qmd --to html\n" + "quarto render document.qmd --to pdf --toc").example("Render Notebook", "quarto render notebook.ipynb\n" + "quarto render notebook.ipynb --to docx\n" + "quarto render notebook.ipynb --to pdf --toc").example("Render Project", "quarto render\n" + "quarto render projdir").example("Render w/ Metadata", "quarto render document.qmd -M echo:false\n" + "quarto render document.qmd -M code-fold:true").example("Render to Stdout", "quarto render document.qmd --output -").action(async (options, input, ...args)=>{
    if (options === undefined) {
        throw new InternalError("Expected `options` to be an object");
    }
    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" || args[0] === "-h") {
        renderCommand.showHelp();
        return;
    }
    if (!input || input === kCliffyImplicitCwd) {
        input = Deno.cwd();
        debug(`Render: Using current directory (${input}) as implicit input`);
        const firstArg = args.find((arg)=>arg.endsWith(".qmd") || arg.endsWith(".ipynb"));
        if (firstArg) {
            warn("`quarto render` invoked with no input file specified (the parameter order matters).\nQuarto will render the current directory by default.\n" + `Did you mean to run \`quarto render ${firstArg} ${args.filter((arg)=>arg !== firstArg).join(" ")}\`?\n` + "Use `quarto render --help` for more information.");
        }
    }
    const inputs = [
        input
    ];
    const firstPandocArg = args.findIndex((arg)=>arg.startsWith("-"));
    if (firstPandocArg !== -1) {
        inputs.push(...args.slice(0, firstPandocArg));
        args = args.slice(firstPandocArg);
    }
    const pandocArgsWithOptionalValues = [
        "--file-scope",
        "--sandbox",
        "--standalone",
        "--ascii",
        "--toc",
        "--preserve-tabs",
        "--self-contained",
        "--embed-resources",
        "--no-check-certificate",
        "--strip-comments",
        "--reference-links",
        "--list-tables",
        "--listings",
        "--incremental",
        "--section-divs",
        "--html-q-tags",
        "--epub-title-page",
        "--webtex",
        "--mathjax",
        "--katex",
        "--trace",
        "--dump-args",
        "--ignore-args",
        "--fail-if-warnings",
        "--list-extensions"
    ];
    const normalizedArgs = [];
    for (const arg of args){
        const equalSignIndex = arg.indexOf("=");
        if (equalSignIndex > 0 && arg.startsWith("-") && !pandocArgsWithOptionalValues.includes(arg.slice(0, equalSignIndex))) {
            normalizedArgs.push(arg.slice(0, equalSignIndex));
            normalizedArgs.push(arg.slice(equalSignIndex + 1));
        } else {
            normalizedArgs.push(arg);
        }
    }
    args = normalizedArgs;
    const flags = await parseRenderFlags(args);
    args = fixupPandocArgs(args, flags);
    let renderResult;
    let renderResultInput;
    for (const input of inputs){
        for (const walk of expandGlobSync(input)){
            const services = renderServices(notebookContext());
            try {
                renderResultInput = relative2(Deno.cwd(), walk.path) || ".";
                renderResult = await render(renderResultInput, {
                    services,
                    flags,
                    pandocArgs: args,
                    useFreezer: flags.useFreezer === true,
                    setProjectDir: true
                });
                if (renderResult.error) {
                    throw renderResult.error;
                }
            } finally{
                services.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 resolveHostAndPort(options) {
    const host = options.host || kLocalhost;
    let port = options.port;
    if (port) {
        if (!await waitForPort({
            port: port,
            hostname: host
        })) {
            throw new Error(`Requested port ${options.port} is already in use.`);
        }
    } else {
        port = findOpenPort();
    }
    return {
        host,
        port
    };
}
function previewURL(host, port, path) {
    const showHost = host == "127.0.0.1" ? "localhost" : host;
    const url = `http://${showHost}:${port}/${path}`;
    return url;
}
async function printBrowsePreviewMessage(host, port, path) {
    if ((isJupyterServer() || isVSCodeTerminal()) && isRStudioWorkbench()) {
        const url = await rswURL(port, path);
        info(`\nPreview server: ${previewURL(host, port, path = "")}`);
        info(`\nBrowse at ${url}`, {
            format: green
        });
    } else if (isVSCodeTerminal() && isVSCodeServer()) {
        const proxyUrl = vsCodeServerProxyUri();
        if (proxyUrl.endsWith("/")) {
            path = path.startsWith("/") ? path.slice(1) : path;
        } else {
            path = path.startsWith("/") ? path : "/" + path;
        }
        const browseUrl = proxyUrl.replace("{{port}}", `${port}`) + path;
        info(`\nBrowse at ${browseUrl}`, {
            format: green
        });
    } else if (isJupyterHubServer()) {
        const httpReferrer = `${jupyterHubHttpReferrer() || "<jupyterhub-server-url>/"}user/${jupyterHubUser()}/`;
        info(`\nBrowse at ${httpReferrer}proxy/${port}/${path}`, {
            format: green
        });
    } else {
        const url = previewURL(host, port, path);
        if (!isRStudioServer()) {
            info(`Browse at `, {
                newline: false,
                format: green
            });
        }
        info(url, {
            format: (str)=>underline(green(str))
        });
    }
}
async function rswURL(port, path) {
    const server = Deno.env.get("RS_SERVER_URL");
    const session = Deno.env.get("RS_SESSION_URL");
    const portToken = await rswPortToken(port);
    const url = `${server}${session.slice(1)}p/${portToken}/${path}`;
    return url;
}
async function rswPortToken(port) {
    const result1 = await execProcess({
        cmd: [
            "/usr/lib/rstudio-server/bin/rserver-url",
            String(port)
        ],
        stdout: "piped",
        stderr: "piped"
    });
    if (result1.success) {
        return result1.stdout;
    } else {
        throw new Error(`Failed to map RSW port token (status ${result1.code})\n${result1.stderr}`);
    }
}
async function openUrl(url) {
    const shellOpen = {
        windows: "explorer",
        darwin: "open"
    };
    const cmd = shellOpen[Deno.build.os] || "xdg-open";
    if (Deno.build.os === "windows") {
        const safeArgs = requireQuoting([
            url
        ]);
        if (safeArgs.status) {
            await safeWindowsExec(cmd, safeArgs.args, (cmd)=>{
                return execProcess({
                    cmd,
                    stdout: "piped",
                    stderr: "piped"
                });
            });
        } else {
            if (await which(cmd)) {
                Deno.run({
                    cmd: [
                        cmd,
                        url
                    ]
                });
            }
        }
    } else {
        if (await which(cmd)) {
            Deno.run({
                cmd: [
                    cmd,
                    url
                ]
            });
        }
    }
}
async function renderForServe(file, format) {
    const services = renderServices(notebookContext());
    try {
        const result1 = await render(file, {
            services,
            flags: {
                to: format,
                execute: true
            },
            previewServer: true
        });
        return result1;
    } finally{
        services.cleanup();
    }
}
async function serve(options) {
    const { host, port } = await resolveHostAndPort(options);
    const nbContext = notebookContext();
    const project = await projectContext(options.input, nbContext) || singleFileProjectContext(options.input, nbContext);
    const engine = await fileExecutionEngine(options.input, undefined, project);
    if (engine?.run) {
        if (options.render) {
            const result1 = await renderForServe(options.input, options.format);
            if (result1.error) {
                throw result1.error;
            }
        }
        const onReady = async ()=>{
            if (isRStudio()) {
                const url = previewURL(host, port, "");
                info(`Listening on ${url}`);
            } else {
                printBrowsePreviewMessage(host, port, "");
            }
            if (options.browser && !isServerSession()) {
                await openUrl(previewURL(host, port, ""));
            }
        };
        await engine.run({
            ...options,
            input: options.input,
            host,
            port,
            onReady
        });
        return processSuccessResult();
    }
    return Promise.reject(new Error("Unable to run computations for input file"));
}
function renderEjs(file, data, removeEmptyLines = true, cache = true) {
    const template = compileTemplate(file, removeEmptyLines, cache);
    if (!template) {
        throw new InternalError(`Rendering the template ${file} failed unexpectedly.`);
    }
    return lines(template(data).trimLeft()).filter((line)=>!removeEmptyLines || line.trim().length > 0).join("\n") + "\n";
}
const compiledTemplates = new Map();
function compileTemplate(file, removeEmptyLines, cache = true) {
    const mtime = Deno.statSync(file).mtime?.getTime() || Number.MAX_VALUE;
    const compile = ()=>{
        const template = `<% const partial = (file, data) => print(include(file, data)); %>
    ${Deno.readTextFileSync(file)}`;
        return __VIRTUAL_FILE176(template, {
            imports: {
                include: (includeFile, includeData)=>{
                    return renderEjs(join2(dirname2(file), includeFile), includeData, removeEmptyLines);
                }
            }
        });
    };
    if (!cache) {
        return compile();
    } else {
        const cachedTemplate = compiledTemplates.get(file);
        if (!cachedTemplate || cachedTemplate.mtime < mtime) {
            compiledTemplates.set(file, {
                mtime,
                compileTemplate: compile()
            });
        }
    }
    return compiledTemplates.get(file)?.compileTemplate;
}
function httpDevServer(timeout, isRendering, stopServer, isPresentation) {
    const clients = [];
    const hasClients = ()=>{
        return isRendering() || !!clients.find((client)=>client.socket.readyState !== WebSocket.CLOSED);
    };
    let onSocketClose;
    if (timeout > 0 && !isRStudioPreview()) {
        onSocketClose = debounce1(()=>{
            if (!hasClients()) {
                stopServer();
            }
        }, timeout * 1000);
    }
    const broadcast = (msg)=>{
        for(let i1 = clients.length - 1; i1 >= 0; i1--){
            const socket = clients[i1].socket;
            try {
                socket.send(msg);
            } catch (_e) {}
        }
    };
    HttpDevServerRenderMonitor.monitor({
        onRenderStart: (lastRenderTime)=>{
            broadcast(`render:start:${lastRenderTime || 0}`);
        },
        onRenderStop: (success)=>{
            broadcast(`render:stop:${success}`);
        }
    });
    LogEventsHandler.onLog(async (logRecord, msg)=>{
        broadcast("log:" + JSON.stringify({
            ...logRecord,
            msgFormatted: msg
        }));
    });
    let injectClientInitialized = false;
    let iframeURL;
    const getiFrameURL = (req)=>{
        if (!injectClientInitialized) {
            iframeURL = viewerIFrameURL(req);
            injectClientInitialized = true;
        }
        return iframeURL;
    };
    const kQuartoPreviewJs = "quarto-preview.js";
    return {
        handle: (req)=>{
            const url = new URL(req.url);
            if (url.pathname.endsWith(kQuartoPreviewJs)) {
                return true;
            }
            if (req.headers.get("upgrade") === "websocket") {
                return true;
            }
            return false;
        },
        request: async (req)=>{
            const url = new URL(req.url);
            if (url.pathname.endsWith(kQuartoPreviewJs)) {
                const path = resourcePath(join2("preview", kQuartoPreviewJs));
                const contents = await Deno.readFile(path);
                return httpContentResponse(contents, "text/javascript");
            } else {
                try {
                    const { socket, response } = Deno.upgradeWebSocket(req);
                    const client = {
                        socket
                    };
                    socket.onmessage = (ev)=>{
                        if (ev.data === "stop") {
                            stopServer();
                        }
                    };
                    if (onSocketClose) {
                        socket.onclose = onSocketClose;
                    }
                    clients.push(client);
                    return Promise.resolve(response);
                } catch (e) {
                    maybeDisplaySocketError(e);
                    return Promise.resolve(undefined);
                }
            }
        },
        clientHtml: (req, inputFile)=>{
            const script = devServerClientScript(inputFile, isPresentation, getiFrameURL(req));
            return script;
        },
        injectClient: (req, file, inputFile, contentType)=>{
            const script = devServerClientScript(inputFile, isPresentation, getiFrameURL(req));
            const scriptContents = new TextEncoder().encode("\n" + script);
            const fileWithScript = new Uint8Array(file.length + scriptContents.length);
            fileWithScript.set(file);
            fileWithScript.set(scriptContents, file.length);
            return {
                contentType: contentType || kTextHtml,
                body: fileWithScript
            };
        },
        reloadClients: async (reloadTarget = "")=>{
            for(let i1 = clients.length - 1; i1 >= 0; i1--){
                const socket = clients[i1].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(i1, 1);
                }
            }
        },
        hasClients
    };
}
class HttpDevServerRenderMonitor {
    static onRenderStart() {
        this.renderStart_ = Date.now();
        this.handlers_.forEach((handler)=>handler.onRenderStart(this.lastRenderTime_));
    }
    static onRenderStop(success) {
        if (this.renderStart_) {
            this.lastRenderTime_ = Date.now() - this.renderStart_;
            this.renderStart_ = undefined;
        }
        this.handlers_.forEach((handler)=>handler.onRenderStop(success));
    }
    static monitor(handler) {
        this.handlers_.push(handler);
    }
    static handlers_ = new Array();
    static renderStart_;
    static lastRenderTime_;
}
function devServerClientScript(inputFile, isPresentation, iframeURL) {
    const options = {
        origin: iframeURL ? devserverOrigin(iframeURL) : null,
        search: iframeURL ? iframeURL.search : null,
        inputFile: inputFile || null,
        isPresentation: !!isPresentation
    };
    return renderEjs(resourcePath(`preview/quarto-preview.html`), options);
}
function devserverOrigin(iframeURL) {
    if (isRStudioServer()) {
        return iframeURL.searchParams.get("host") || iframeURL.origin;
    } else {
        return iframeURL.origin;
    }
}
function viewerIFrameURL(req) {
    for (const url of [
        req.url,
        req.referrer
    ]){
        const isViewer = url && (url.includes("capabilities=") || url.includes("vscodeBrowserReqId=") || url.includes("quartoPreviewReqId="));
        if (isViewer) {
            return new URL(url);
        }
    }
}
class PromiseQueue {
    queue = new Array();
    running = false;
    enqueue(promise, clearPending = false) {
        return new Promise((resolve, reject)=>{
            if (clearPending) {
                this.queue.splice(0, this.queue.length);
            }
            this.queue.push({
                promise,
                resolve,
                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) {
    let isViewer;
    return async (file, req)=>{
        if (isViewer === undefined) {
            isViewer = !!viewerIFrameURL(req);
        }
        if (htmlHandler) {
            const contents = await htmlHandler(file, req);
            if (contents) {
                return contents;
            }
        }
        const previewPath = (dir, file)=>{
            return pathWithForwardSlashes(join2(pdfJsBaseDir(), dir, file));
        };
        if (file === previewPath("web", "viewer.js")) {
            let viewerJs = Deno.readTextFileSync(file).replace(kPdfJsDefaultFile, basename2(pdfFile()));
            if (isViewer) {
                viewerJs = viewerJs.replace("sidebarView: sidebarView", "sidebarView: _ui_utils.SidebarView.NONE");
            }
            return {
                contentType: contentType(file),
                body: new TextEncoder().encode(viewerJs)
            };
        } else if (file == previewPath("web", "viewer.css")) {
            const viewerCss = normalizeNewlines(Deno.readTextFileSync(file)).replace(kPdfJsViewerToolbarButtonSelector, kPdfJsViewerToolbarButtonSelector + "\n  z-index: 199;").replace(kPdfJsViewerSidebarTransitionDurationPattern, "$1 0");
            return {
                contentType: contentType(file),
                body: new TextEncoder().encode(viewerCss)
            };
        } else if (file === previewPath("build", "pdf.worker.js")) {
            const filePathHash = "quarto-preview-pdf-" + md5Hash(pdfFile());
            const workerJs = Deno.readTextFileSync(file).replace(/(key: "fingerprint",\s+get: function get\(\) {\s+)(var hash;)/, `$1return "${filePathHash}"; $2`);
            return {
                contentType: contentType(file),
                body: new TextEncoder().encode(workerJs)
            };
        } else if (file === previewPath("web", basename2(pdfFile()))) {
            return {
                contentType: contentType(file),
                body: 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 i1 = 0; i1 < currentFiles.length; i1++){
                        const file = currentFiles[i1];
                        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);
            }
        }
    };
}
const jatsStaticResources = ()=>{
    return [
        {
            name: "quarto-jats-preview.css",
            dir: "jats",
            contentType: "text/css"
        },
        {
            name: "quarto-jats-html.xsl",
            dir: "jats",
            contentType: "text/xsl",
            injectClient: (contents, client)=>{
                const protectedClient = client.replaceAll(/(<style.*?>)|(<script.*?>)/g, (substring)=>{
                    return `${substring}\n<![CDATA[`;
                }).replaceAll(/(<\/style.*?>)|(<\/script.*?>)/g, (substring)=>{
                    return `]]>\n${substring}`;
                }).replaceAll("data-micromodal-close", 'data-micromodal-close="true"');
                const bodyContents = contents.replace("<!-- quarto-after-body -->", protectedClient);
                return new TextEncoder().encode(bodyContents);
            }
        }
    ];
};
async function previewTextContent(file, inputFile, format, req, injectClient) {
    const rawPreviewMode = format.metadata[kPreviewMode] === kPreviewModeRaw;
    if (!rawPreviewMode && isJatsOutput(format.pandoc)) {
        const xml = await jatsPreviewXml(file, req);
        return {
            contentType: kTextXml,
            body: new TextEncoder().encode(xml)
        };
    } else if (!rawPreviewMode && format.identifier[kBaseFormat] === "gfm") {
        const html = await gfmPreview(file, req);
        return injectClient(req, new TextEncoder().encode(html), inputFile);
    } else {
        const html = await textPreviewHtml(file, req);
        const fileContents = new TextEncoder().encode(html);
        return injectClient(req, fileContents, inputFile);
    }
}
async function jatsPreviewXml(file, _request) {
    const fileContents = await Deno.readTextFile(file);
    let xmlContents = fileContents.replace(/<\?xml version="1.0" encoding="utf-8"\s*\?>/, '<?xml version="1.0" encoding="utf-8" ?>\n<?xml-stylesheet href="quarto-jats-html.xsl" type="text/xsl" ?>');
    xmlContents = xmlContents.replace(/<!DOCTYPE((.|\n)*?)>/, "");
    return xmlContents;
}
function darkHighlightStyle(request) {
    const kQuartoPreviewThemeCategory = "quartoPreviewThemeCategory";
    const themeCategory = new URL(request.url).searchParams.get(kQuartoPreviewThemeCategory);
    return themeCategory && themeCategory !== "light";
}
async function textPreviewHtml(file, req) {
    const darkMode = darkHighlightStyle(req);
    const backgroundColor = darkMode ? "rgb(30,30,30)" : "#FFFFFF";
    const frontMatter = [
        "---"
    ];
    frontMatter.push(`pagetitle: "Quarto Preview"`);
    frontMatter.push(`document-css: false`);
    frontMatter.push("---");
    const styles = [
        "```{=html}",
        `<style type="text/css">`,
        `body { margin: 8px 12px; background-color: ${backgroundColor} }`,
        `div.sourceCode { background-color: transparent; }`,
        `</style>`,
        "```"
    ];
    const lang = (extname2(file) || ".default").slice(1).toLowerCase();
    const kFence = "````````````````";
    const markdown = frontMatter.join("\n") + "\n\n" + styles.join("\n") + "\n\n" + kFence + lang + "\n" + Deno.readTextFileSync(file) + "\n" + kFence;
    const cmd = [
        pandocBinaryPath()
    ];
    cmd.push("--to", "html");
    cmd.push("--highlight-style", textHighlightThemePath("atom-one", darkMode ? "dark" : "light"));
    cmd.push("--standalone");
    const result1 = await execProcess({
        cmd,
        stdout: "piped"
    }, markdown);
    if (result1.success) {
        return result1.stdout;
    } else {
        throw new Error();
    }
}
async function gfmPreview(file, request) {
    const workingDir = Deno.makeTempDirSync();
    try {
        const darkMode = darkHighlightStyle(request);
        const template = formatResourcePath("gfm", "template.html");
        const filter = formatResourcePath("gfm", "mermaid.lua");
        const mermaidJs = formatResourcePath("html", join2("mermaid", "mermaid.min.js"));
        const includeInHeader = [];
        for (const path of [
            mermaidJs
        ]){
            const js = Deno.readTextFileSync(path);
            const contents = `<script type="text/javascript">\n${js}\n</script>`;
            const target = join2(workingDir, basename2(path));
            Deno.writeTextFileSync(target, contents);
            includeInHeader.push(target);
        }
        const jsInit = `
<script>
  mermaid.initialize({startOnLoad:true, theme: '${darkMode ? "dark" : "default"}'});
</script>`;
        const css = formatResourcePath("gfm", join2("github-markdown-css", darkMode ? "github-markdown-dark.css" : "github-markdown-light.css"));
        const cssTempFile = join2(workingDir, "github.css");
        const cssContents = `<style>\n${Deno.readTextFileSync(css)}\n</style>\n${jsInit}`;
        Deno.writeTextFileSync(cssTempFile, cssContents);
        includeInHeader.push(cssTempFile);
        const highlightPath = textHighlightThemePath("github", darkMode ? "dark" : "light");
        const cmd = [
            pandocBinaryPath()
        ];
        cmd.push("-f");
        cmd.push("gfm");
        cmd.push("-t");
        cmd.push("html");
        cmd.push("--template");
        cmd.push(template);
        includeInHeader.forEach((include)=>{
            cmd.push("--include-in-header");
            cmd.push(include);
        });
        cmd.push("--lua-filter");
        cmd.push(filter);
        if (highlightPath) {
            cmd.push("--highlight-style");
            cmd.push(highlightPath);
        }
        cmd.push("--mathjax");
        const result1 = await execProcess({
            cmd,
            stdout: "piped",
            stderr: "piped"
        }, Deno.readTextFileSync(file));
        if (result1.success) {
            return result1.stdout;
        } else {
            throw new Error(`Failed to render citation: error code ${result1.code}\n${result1.stderr}`);
        }
    } finally{
        Deno.removeSync(workingDir, {
            recursive: true
        });
    }
}
const staticResource = async (baseDir, file)=>{
    const filename = relative2(baseDir, file);
    const resource = kStaticResources.find((resource)=>{
        return resource.name === filename;
    });
    if (resource) {
        const dir = resource.dir ? join2("preview", resource.dir) : "preview";
        const path = resourcePath(join2(dir, filename));
        const contents = await Deno.readFile(path);
        return {
            ...resource,
            contents
        };
    }
};
const kStaticResources = [
    ...jatsStaticResources()
];
async function resolvePreviewOptions(options, project) {
    if (project?.config?.project.preview) {
        options = mergeConfigs(project.config.project.preview, options);
    }
    const resolved = mergeConfigs({
        host: kLocalhost,
        browser: true,
        [kProjectWatchInputs]: !isRStudio(),
        timeout: 0,
        navigate: true
    }, options);
    if (resolved.port) {
        if (!await waitForPort({
            port: resolved.port,
            hostname: resolved.host
        })) {
            throw new Error(`Requested port ${options.port} is already in use.`);
        }
    } else {
        resolved.port = findOpenPort();
    }
    return resolved;
}
async function preview(file, flags, pandocArgs, options) {
    const nbContext = notebookContext();
    const project = await projectContext(file, nbContext);
    const format = await previewFormat(file, flags.to, undefined, project);
    setPreviewFormat(format, flags, pandocArgs);
    let isRendering = false;
    const render = async (to)=>{
        const renderFlags = {
            ...flags,
            to: to || flags.to
        };
        const services = renderServices(nbContext);
        try {
            HttpDevServerRenderMonitor.onRenderStart();
            isRendering = true;
            const result1 = await renderForPreview(file, services, renderFlags, pandocArgs, project);
            HttpDevServerRenderMonitor.onRenderStop(true);
            return result1;
        } catch (error) {
            HttpDevServerRenderMonitor.onRenderStop(false);
            throw error;
        } finally{
            isRendering = false;
            services.cleanup();
        }
    };
    const result1 = await render();
    options = {
        ...options,
        ...await resolvePreviewOptions(options)
    };
    const listener = Deno.listen({
        port: options.port,
        hostname: options.host
    });
    const stopServer = ()=>listener.close();
    previewEnsureResources(stopServer);
    const reloader = httpDevServer(options.timeout, ()=>isRendering, stopServer, options.presentation || format === "revealjs");
    const changeHandler = createChangeHandler(result1, reloader, render, options[kProjectWatchInputs]);
    const handler = isPdfContent(result1.outputFile) ? pdfFileRequestHandler(result1.outputFile, normalizePath(file), flags, result1.format, options.port, reloader, changeHandler.render) : project ? projectHtmlFileRequestHandler(project, normalizePath(file), flags, result1.format, reloader, changeHandler.render) : htmlFileRequestHandler(result1.outputFile, normalizePath(file), flags, result1.format, reloader, changeHandler.render);
    const initialPath = isPdfContent(result1.outputFile) ? kPdfJsInitialPath : project ? pathWithForwardSlashes(relative2(projectOutputDir(project), result1.outputFile)) : "";
    if (options.browser && !isServerSession() && isBrowserPreviewable(result1.outputFile)) {
        await openUrl(previewURL(options.host, options.port, initialPath));
    }
    await printBrowsePreviewMessage(options.host, options.port, initialPath);
    previewMonitorResources(stopServer);
    for await (const conn of listener){
        (async ()=>{
            try {
                for await (const { request, respondWith } of Deno.serveHttp(conn)){
                    await respondWith(handler(request));
                }
            } catch (err) {
                warn(err.message);
                try {
                    conn.close();
                } catch  {}
            }
        })();
    }
}
function isPreviewRenderRequest(req) {
    if (req.url.includes(kQuartoRenderCommand)) {
        return true;
    } else {
        const token = renderToken();
        if (token) {
            return req.url.includes(token);
        } else {
            return false;
        }
    }
}
function isPreviewTerminateRequest(req) {
    const kTerminateToken = "4231F431-58D3-4320-9713-994558E4CC45";
    return req.url.includes(kTerminateToken);
}
function previewRenderRequest(req, hasClients, baseDir) {
    const match = req.url.match(new RegExp(`/${kQuartoRenderCommand}/(.*)$`));
    if (match && baseDir) {
        return {
            version: 1,
            path: join2(baseDir, match[1])
        };
    } else {
        const token = renderToken();
        if (token && req.url.includes(token)) {
            const url = new URL(req.url);
            const path = url.searchParams.get("path");
            if (path) {
                if (hasClients) {
                    return {
                        version: 2,
                        path,
                        format: url.searchParams.get("format") || undefined
                    };
                }
            }
        }
    }
}
async function previewRenderRequestIsCompatible(request, format, project) {
    if (request.version === 1) {
        return true;
    } else {
        const reqFormat = await previewFormat(request.path, request.format, undefined, project);
        return reqFormat === format;
    }
}
async function previewFormat(file, format, formats, project) {
    if (format) {
        return format;
    }
    const nbContext = notebookContext();
    project = project || singleFileProjectContext(file, nbContext);
    formats = formats || await withRenderServices(nbContext, (services)=>renderFormats(file, services, "all", project));
    format = Object.keys(formats)[0] || "html";
    return format;
}
function setPreviewFormat(format, flags, pandocArgs) {
    flags.to = format;
    replacePandocArg(pandocArgs, "--to", format);
}
function handleRenderResult(file, renderResult) {
    const finalOutput = renderResultFinalOutput(renderResult, dirname2(file));
    if (!finalOutput) {
        throw new Error("No output created by quarto render " + basename2(file));
    }
    info("Output created: " + finalOutput + "\n");
    return finalOutput;
}
async function renderForPreview(file, services, flags, pandocArgs, project) {
    const renderResult = await render(file, {
        services,
        flags,
        pandocArgs: pandocArgs,
        previewServer: true,
        setProjectDir: project !== undefined
    });
    if (renderResult.error) {
        throw renderResult.error;
    }
    const finalOutput = handleRenderResult(file, renderResult);
    printWatchingForChangesMessage();
    file = normalizePath(file);
    const filesDir = join2(dirname2(file), inputFilesDir(file));
    const resourceFiles = renderResult.files.reduce((resourceFiles, file)=>{
        const resources = file.resourceFiles.concat(cssFileResourceReferences(file.resourceFiles));
        return resourceFiles.concat(resources.filter((resFile)=>!resFile.startsWith(filesDir)));
    }, []);
    const extensionFiles = extensionFilesFromDirs(inputExtensionDirs(file, project?.dir));
    extensionFiles.push(...renderResult.files.reduce((extensionFiles, file)=>{
        const shortcodes = file.format.render.shortcodes || [];
        const filters = (file.format.pandoc.filters || []).map((filter)=>isPandocFilter(filter) ? filter.path : filter);
        const ipynbFilters = file.format.execute["ipynb-filters"] || [];
        [
            ...shortcodes,
            ...filters.map((filter)=>filter),
            ...ipynbFilters
        ].forEach((extensionFile)=>{
            if (!isAbsolute2(extensionFile)) {
                const extensionFullPath = join2(dirname2(file.input), extensionFile);
                if (existsSync(extensionFullPath)) {
                    extensionFiles.push(normalizePath(extensionFullPath));
                }
            }
        });
        return extensionFiles;
    }, []));
    return {
        file,
        format: renderResult.files[0].format,
        outputFile: join2(dirname2(file), finalOutput),
        extensionFiles,
        resourceFiles
    };
}
function createChangeHandler(result1, reloader, render, renderOnChange, reloadFileFilter = ()=>true, ignoreChanges) {
    const renderQueue = new PromiseQueue();
    let watcher;
    let lastResult = result1;
    const renderHandler = async (to)=>{
        try {
            if (to && watcher) {
                watcher.stop();
            }
            const result1 = await renderQueue.enqueue(async ()=>{
                return render(to);
            }, true);
            if (result1) {
                sync(result1);
            }
            return result1;
        } catch (e) {
            if (e.message) {
                if (isJupyterNotebook(result1.file) && e.message.indexOf("Unexpected end of JSON input") !== -1) {
                    return;
                }
                logError(e);
            }
        }
    };
    const sync = (result1)=>{
        const requiresSync = !watcher || resultRequiresSync(result1, lastResult);
        lastResult = result1;
        if (requiresSync) {
            if (watcher) {
                watcher.stop();
            }
            const watches = [];
            if (renderOnChange) {
                watches.push({
                    files: [
                        result1.file
                    ],
                    handler: __VIRTUAL_FILE113(renderHandler, 50)
                });
            }
            watches.push({
                files: result1.extensionFiles,
                handler: __VIRTUAL_FILE113(renderHandler, 50)
            });
            const reloadFiles = isPdfContent(result1.outputFile) ? pdfReloadFiles(result1) : resultReloadFiles(result1);
            const reloadTarget = isPdfContent(result1.outputFile) ? "/" + kPdfJsInitialPath : "";
            const removeUrlFragment = (file)=>file.replace(/#.*$/, "").replace(/\?.*$/, "");
            watches.push({
                files: reloadFiles.filter(reloadFileFilter).map(removeUrlFragment),
                handler: __VIRTUAL_FILE113(async ()=>{
                    await renderQueue.enqueue(async ()=>{
                        await reloader.reloadClients(reloadTarget);
                        return undefined;
                    });
                }, 50)
            });
            watcher = previewWatcher(watches, ignoreChanges);
            watcher.start();
        }
    };
    sync(result1);
    return {
        render: renderHandler
    };
}
function previewWatcher(watches, ignoreChanges) {
    existsSync;
    watches = watches.map((watch)=>{
        return {
            ...watch,
            files: watch.files.filter((s)=>existsSync(s)).map((file)=>{
                return normalizePath(file);
            })
        };
    });
    const handlerForFile = (file)=>{
        const watch = watches.find((watch)=>watch.files.includes(file));
        return watch?.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" && (!ignoreChanges || !ignoreChanges(event.paths))) {
                    const handlers = new Set();
                    event.paths.forEach((path)=>{
                        const handler = handlerForFile(path);
                        if (handler && !handlers.has(handler)) {
                            handlers.add(handler);
                        }
                    });
                    for (const handler of handlers){
                        await handler();
                    }
                }
            } catch (e) {
                logError(e);
            }
        }
    };
    return {
        start: watchForChanges,
        stop: ()=>fsWatcher.close()
    };
}
function projectHtmlFileRequestHandler(context, inputFile, flags, format, reloader, renderHandler) {
    return httpFileRequestHandler(htmlFileRequestHandlerOptions(projectOutputDir(context), "index.html", inputFile, flags, format, reloader, renderHandler, context));
}
function htmlFileRequestHandler(htmlFile, inputFile, flags, format, reloader, renderHandler) {
    return httpFileRequestHandler(htmlFileRequestHandlerOptions(dirname2(htmlFile), basename2(htmlFile), inputFile, flags, format, reloader, renderHandler));
}
function htmlFileRequestHandlerOptions(baseDir, defaultFile, inputFile, flags, format, devserver, renderHandler, project) {
    let invalidateDevServerReRender = false;
    return {
        baseDir,
        defaultFile,
        printUrls: "404",
        onRequest: async (req)=>{
            if (devserver.handle(req)) {
                return Promise.resolve(devserver.request(req));
            } else if (isPreviewTerminateRequest(req)) {
                exitWithCleanup(0);
            } else if (req.url.endsWith("/quarto-render/")) {
                renderHandler();
                return Promise.resolve(httpContentResponse("rendered"));
            } else if (isPreviewRenderRequest(req)) {
                const outputFile = format.pandoc[kOutputFile];
                const prevReq = previewRenderRequest(req, !isBrowserPreviewable(outputFile) || devserver.hasClients());
                if (!invalidateDevServerReRender && prevReq && existsSync(prevReq.path) && normalizePath(prevReq.path) === normalizePath(inputFile) && await previewRenderRequestIsCompatible(prevReq, flags.to)) {
                    renderHandler();
                    return Promise.resolve(httpContentResponse("rendered"));
                } else {
                    return Promise.resolve(previewUnableToRenderResponse());
                }
            } else {
                return Promise.resolve(undefined);
            }
        },
        onFile: async (file, req)=>{
            const staticResponse = await staticResource(baseDir, file);
            if (staticResponse) {
                const resolveBody = ()=>{
                    if (staticResponse.injectClient) {
                        const client = devserver.clientHtml(req, inputFile);
                        const contents = new TextDecoder().decode(staticResponse.contents);
                        return staticResponse.injectClient(contents, client);
                    } else {
                        return staticResponse.contents;
                    }
                };
                const body = resolveBody();
                return {
                    body,
                    contentType: staticResponse.contentType
                };
            }
            let renderFormat = format;
            if (project) {
                const input = await inputFileForOutputFile(project, relative2(baseDir, file));
                if (input) {
                    renderFormat = input.format;
                    if (renderFormat !== format && fileRequiresRender(input.file, file)) {
                        invalidateDevServerReRender = true;
                        await renderHandler(renderFormat.identifier[kTargetFormat]);
                    }
                }
            }
            if (req.headers.get("sec-fetch-dest") === "empty" && req.headers.get("sec-fetch-mode") === "cors") {
                return;
            }
            if (isHtmlContent(file)) {
                if (renderFormat.formatPreviewFile) {
                    file = renderFormat.formatPreviewFile(file, renderFormat);
                }
                const fileContents = await Deno.readFile(file);
                return devserver.injectClient(req, fileContents, inputFile);
            } else if (isTextContent(file)) {
                return previewTextContent(file, inputFile, format, req, devserver.injectClient);
            }
        }
    };
}
function fileRequiresRender(inputFile, outputFile) {
    if (safeExistsSync(outputFile)) {
        return (Deno.statSync(inputFile).mtime?.valueOf() || 0) > (Deno.statSync(outputFile).mtime?.valueOf() || 0);
    } else {
        return true;
    }
}
function resultReloadFiles(result1) {
    return [
        result1.outputFile
    ].concat(result1.resourceFiles);
}
function pdfFileRequestHandler(pdfFile, inputFile, flags, format, port, reloader, renderHandler) {
    const pdfOptions = htmlFileRequestHandlerOptions(dirname2(pdfFile), basename2(pdfFile), inputFile, flags, format, reloader, renderHandler);
    pdfOptions.baseDir = pdfJsBaseDir();
    if (pdfOptions.onRequest) {
        const onRequest = pdfOptions.onRequest;
        pdfOptions.onRequest = async (req)=>{
            if (new URL(req.url).pathname === "/") {
                const url = isRStudioWorkbench() ? await rswURL(port, kPdfJsInitialPath) : isVSCodeServer() ? vsCodeServerProxyUri().replace("{{port}}", `${port}`) + kPdfJsInitialPath : "/" + kPdfJsInitialPath;
                return Promise.resolve(serveRedirect(url));
            } else {
                return Promise.resolve(onRequest(req));
            }
        };
    }
    pdfOptions.onFile = pdfJsFileHandler(()=>pdfFile, pdfOptions.onFile);
    return httpFileRequestHandler(pdfOptions);
}
function pdfReloadFiles(result1) {
    return [
        result1.outputFile
    ];
}
function resultRequiresSync(result1, lastResult) {
    if (!lastResult) {
        return true;
    }
    return result1.file !== lastResult.file || result1.outputFile !== lastResult.outputFile || !__VIRTUAL_FILE211(result1.extensionFiles, lastResult.extensionFiles) || !__VIRTUAL_FILE211(result1.resourceFiles, lastResult.resourceFiles);
}
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)").option("--browser", "Open a browser to preview the site.").description("Serve a Shiny 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 serve dashboard.qmd").example("Serve a document without rendering", "quarto serve dashboard.qmd --no-render").action(async (options, input)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    if (!input) {
        error("No input passed to serve.\n" + "If you are attempting to preview a website or book use the " + bold("quarto preview") + " command instead.");
        Deno.exit(1);
    }
    const { host, port } = await resolveHostAndPort(options);
    const nbContext = notebookContext();
    const context = await projectContext(input, nbContext) || singleFileProjectContext(input, nbContext);
    const formats = await withRenderServices(nbContext, (services)=>renderFormats(input, services, undefined, context));
    const format = await previewFormat(input, undefined, formats, context);
    const result1 = await serve({
        input,
        render: options.render,
        format,
        port,
        host,
        browser: options.browser,
        projectDir: context?.dir,
        tempDir: Deno.makeTempDirSync()
    });
    if (!result1.success) {
        Deno.exit(result1.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 result1 = await execProcess({
            cmd: [
                executable,
                "-m",
                "venv",
                kEnvDir
            ],
            cwd: dir
        });
        if (!result1.success) {
            throw new Error();
        }
        const pip3 = join2(dir, kEnvDir, isWindows3() ? "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 = normalizePath(options.dir);
    if (!options.quiet) {
        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 quartoConfig = renderEjs(projCreate.configTemplate, {
        title: options.title,
        editor: options.editor,
        ext: engine.defaultExt
    }, false);
    Deno.writeTextFileSync(join2(options.dir, "_quarto.yml"), quartoConfig);
    if (!options.quiet) {
        info("- Created _quarto.yml", {
            indent: 2
        });
    }
    if (await ensureGitignore(options.dir, !!options.venv || !!options.condaenv) && !options.quiet) {
        info("- Created .gitignore", {
            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 && !options.quiet) {
                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 = join2(projCreate.resourceDir, supporting);
                dest = join2(options.dir, supporting);
                displayName = supporting;
            } else {
                src = join2(projCreate.resourceDir, supporting.from);
                dest = join2(options.dir, supporting.to);
                displayName = supporting.to;
            }
            if (!existsSync(dest)) {
                ensureDirSync(dirname2(dest));
                copyTo(src, dest);
                if (!options.quiet) {
                    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(dir, name, content, engine, kernel, title, noEngineContent, yaml, subdirectory, supporting) {
    const lines = [
        "---"
    ];
    if (title) {
        lines.push(`title: "${title}"`);
    }
    if (yaml) {
        lines.push(yaml);
    }
    if (!noEngineContent) {
        lines.push(...engine.defaultYaml(kernel));
    }
    lines.push("---", "");
    if (lines.length === 3) {
        lines.splice(0, lines.length);
    }
    lines.push(content);
    if (!noEngineContent) {
        const engineContent = engine.defaultContent(kernel);
        if (engineContent.length > 0) {
            lines.push("");
            lines.push(...engineContent);
        }
    }
    name = name + engine.defaultExt;
    const ensureSubDir = (dir, name, subdirectory)=>{
        if (subdirectory) {
            const newDir = join2(dir, subdirectory);
            ensureDirSync(newDir);
            return join2(newDir, name);
        } else {
            return join2(dir, name);
        }
    };
    const path = ensureSubDir(dir, name, subdirectory);
    if (!existsSync(path)) {
        Deno.writeTextFileSync(path, lines.join("\n") + "\n");
        supporting?.forEach((from)=>{
            const name = basename2(from);
            const target = join2(dirname2(path), name);
            copyTo(from, target);
        });
        return subdirectory ? join2(subdirectory, name) : name;
    } else {
        return undefined;
    }
}
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, "l");
RegExp(kPreviewClassPattern, "l");
RegExp(kMdNamedImagePattern, "l");
function findDescription(doc) {
    const paras = doc.querySelectorAll("main.content > p,  main.content > section > p");
    for (const para of paras){
        const paraEl = para;
        if (paraEl.innerText) {
            return paraEl.innerText;
        }
    }
    return undefined;
}
function findPreviewImg(doc, strict) {
    const imgEl = findPreviewImgEl(doc, strict);
    if (imgEl) {
        const src = getDecodedAttribute(imgEl, "src");
        if (src !== null) {
            return src;
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function findPreviewImgEl(doc, strict) {
    const match = doc.querySelector(`img.${kPreviewImgClass}`);
    if (match) {
        return match;
    }
    const codeMatch = doc.querySelector(`div.${kPreviewImgClass} div.cell-output-display img`);
    if (codeMatch) {
        return codeMatch;
    }
    const imgs = doc.querySelectorAll("img");
    for(let i1 = 0; i1 < imgs.length; i1++){
        const img = imgs[i1];
        const src = getDecodedAttribute(img, "src");
        if (src !== null && (src.startsWith("data:") || kNamedFileRegex.test(src))) {
            return img;
        }
    }
    if (!strict) {
        const autoImg = doc.querySelector("#quarto-document-content img");
        if (autoImg) {
            const src = autoImg.getAttribute("src");
            if (src && !src.startsWith("http:") && !src.startsWith("https:")) {
                return autoImg;
            }
        }
    }
}
function estimateReadingTimeMinutes(markdown) {
    if (markdown) {
        const wordCount = markdown.split(" ").length;
        return {
            wordCount,
            readingTime: Math.ceil(wordCount / 200)
        };
    }
    return undefined;
}
const kListing = "listing";
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 kMaxItems = "max-items";
const kFilterUi = "filter-ui";
const kSortUi = "sort-ui";
const kImageHeight1 = "image-height";
const kImageAlign = "image-align";
const kImageAlt1 = "image-alt";
const kImageLazyLoading = "image-lazy-loading";
const kImagePlaceholder = "image-placeholder";
const kGridColumns = "grid-columns";
const kMaxDescLength = "max-description-length";
const kDefaultMaxDescLength = 175;
const kTableStriped = "table-striped";
const kTableHover = "table-hover";
const kInclude1 = "include";
const kExclude = "exclude";
const kFieldTitle = "title";
const kFieldSubtitle = "subtitle";
const kFieldAuthor = "author";
const kFieldFileName = "filename";
const kFieldDateModified = "date-modified";
const kFieldFileModified = "file-modified";
const kFieldDate = "date";
const kFieldImage = "image";
const kFieldImageAlt = "image-alt";
const kFieldImageLazyLoading = "image-lazy-loading";
const kFieldDescription = "description";
const kFieldReadingTime = "reading-time";
const kFieldWordCount = "word-count";
const kFieldCategories = "categories";
const kFieldOrder = "order";
const kCategoryStyle = "category-style";
const kSortAsc = "asc";
const kSortDesc = "desc";
const kFeed = "feed";
const kItems = "items";
const kLanguage = "language";
const kDescription1 = "description";
const kXmlStyleSheet = "xml-stylesheet";
var ListingType;
(function(ListingType) {
    ListingType["Default"] = "default";
    ListingType["Grid"] = "grid";
    ListingType["Table"] = "table";
    ListingType["Custom"] = "custom";
})(ListingType || (ListingType = {}));
var ListingItemSource;
(function(ListingItemSource) {
    ListingItemSource["document"] = "document";
    ListingItemSource["metadata"] = "metadata";
    ListingItemSource["metadataDocument"] = "metadata-document";
    ListingItemSource["rawfile"] = "rawfile";
})(ListingItemSource || (ListingItemSource = {}));
const kInlineCodeStyle = "inline-code-style";
const kUrlsToAbsolute = "urls-to-absolute";
const renderedContentReader = (project, options, siteUrl)=>{
    const renderedContent = {};
    return (filePath, renderedOptions)=>{
        const cacheStr = renderedOptions ? JSON.stringify(renderedOptions) + filePath : filePath;
        const cacheHash = insecureHash(cacheStr);
        const mergedOptions = {
            ...options,
            ...renderedOptions
        };
        if (!renderedContent[cacheHash]) {
            renderedContent[cacheHash] = readRenderedContents(filePath, project, mergedOptions, siteUrl);
        }
        return renderedContent[cacheHash];
    };
};
const isWebUrl = (url)=>{
    return url.startsWith("http:") || url.startsWith("https:");
};
const absoluteUrl = (siteUrl, url)=>{
    if (isWebUrl(url)) {
        return url;
    } else {
        const baseUrl = siteUrl.endsWith("/") ? siteUrl.substring(0, siteUrl.length - 1) : siteUrl;
        let path = url.startsWith("/") ? url.substring(1, url.length) : url;
        if (path.endsWith("/index.html")) {
            path = join2(dirname2(path), "/");
        } else if (path === "index.html") {
            path = "";
        }
        return `${baseUrl}/${path.replaceAll("\\", "/")}`;
    }
};
function readRenderedContents(filePath, project, options, siteUrl) {
    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();
    }
    let description = "";
    const descEl = doc.querySelector("meta[name='description']");
    if (descEl) {
        const descAttrVal = descEl.getAttribute("content");
        if (descAttrVal !== null) {
            description = descAttrVal;
        }
    }
    const navEls = doc.querySelectorAll("nav");
    if (navEls) {
        for (const navEl of navEls){
            navEl.remove();
        }
    }
    if (options.transform?.[kUrlsToAbsolute] && siteUrl) {
        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("/") && !isWebUrl(src)) {
                        src = join2(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 stripTags = [];
    if (options.remove?.images) {
        stripTags.push("img");
    }
    stripTags.forEach((tag)=>{
        const nodes = doc.querySelectorAll(`${tag}`);
        nodes?.forEach((node)=>{
            const el = node;
            el.remove();
        });
    });
    if (options.remove?.anchors) {
        const relativeLinkSel = 'a[href^="#"]';
        const linkNodes = doc.querySelectorAll(relativeLinkSel);
        linkNodes.forEach((linkNode)=>{
            const nodesToMove = linkNode.childNodes;
            const linkEl = linkNode;
            linkEl.after(...nodesToMove);
            linkEl.remove();
        });
    }
    if (options.transform?.[kInlineCodeStyle]) {
        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);
        }
    }
    if (options.transform?.math) {
        const trimMath = (str)=>{
            if (str.length > 4 && (str.startsWith("\\[") || str.startsWith("\\("))) {
                const trimStart = str.slice(2);
                return trimStart.slice(0, trimStart.length - 2);
            } else {
                return str;
            }
        };
        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);
        }
    }
    if (options.remove?.links) {
        const relativeLinkSel = "a";
        const linkNodes = doc.querySelectorAll(relativeLinkSel);
        linkNodes.forEach((linkNode)=>{
            const nodesToMove = linkNode.childNodes;
            const linkEl = linkNode;
            linkEl.after(...nodesToMove);
            linkEl.remove();
        });
    }
    const replaceTagRegex = /\/tag\{(.*)\}/g;
    const cleanMath = (contents)=>{
        if (!contents) {
            return undefined;
        } else {
            return contents.replaceAll(replaceTagRegex, (_match, content)=>{
                return `\\qquad{${content}}`;
            });
        }
    };
    const truncateNode = (node, maxLen)=>{
        if (maxLen === undefined || maxLen < 0) {
            return node;
        }
        let currentLength = 0;
        const shortenNode = (node)=>{
            const cloned = node.cloneNode(true);
            for (const childNode of cloned.childNodes){
                if (childNode.nodeType === NodeType.TEXT_NODE) {
                    const textNodeLen = childNode.nodeValue?.length || 0;
                    if (currentLength > maxLen) {
                        cloned.replaceChild(doc.createTextNode(""), childNode);
                    } else if (currentLength + textNodeLen > maxLen) {
                        const availableChars = maxLen - currentLength;
                        cloned.replaceChild(doc.createTextNode(truncateText(childNode.nodeValue || "", availableChars, "space")), childNode);
                    }
                    currentLength = textNodeLen + currentLength;
                } else {
                    const newNode = shortenNode(childNode);
                    cloned.replaceChild(newNode, childNode);
                }
            }
            return cloned;
        };
        return shortenNode(node);
    };
    const getFirstPara = ()=>{
        const paraNodes = mainEl?.querySelectorAll("p");
        if (paraNodes) {
            for (const paraNode of paraNodes){
                const truncatedNode = truncateNode(paraNode, options["max-length"]);
                const paraContents = cleanMath(truncatedNode.innerHTML);
                if (paraContents) {
                    return paraContents;
                }
            }
        }
        const anyNodes = mainEl?.childNodes;
        if (anyNodes) {
            for (const anyNode of anyNodes){
                if (anyNode.nodeType === 1) {
                    const el = anyNode;
                    const headings = el.querySelectorAll("h1, h2, h3, h4, h5, h6");
                    headings.forEach((heading)=>heading.remove());
                    const truncatedNode = truncateNode(anyNode, options["max-length"]);
                    const contents = cleanMath(truncatedNode.innerHTML);
                    if (contents) {
                        return contents;
                    }
                }
            }
        }
        return undefined;
    };
    const computePreviewImage = ()=>{
        const previewImageEl = findPreviewImgEl(doc, false);
        if (previewImageEl) {
            const previewImageSrc = getDecodedAttribute(previewImageEl, "src");
            if (previewImageSrc !== null) {
                const src = previewImageSrc;
                const alt = previewImageEl.getAttribute("alt") !== null ? previewImageEl.getAttribute("alt") : undefined;
                const title = previewImageEl.getAttribute("title") !== null ? previewImageEl.getAttribute("title") : undefined;
                return {
                    src,
                    alt,
                    title
                };
            }
        }
    };
    const firstPara = getFirstPara();
    const fullContents = cleanMath(mainEl?.innerHTML);
    return {
        title: titleText,
        description,
        fullContents,
        firstPara,
        previewImage: computePreviewImage()
    };
}
const kWebTexUrl = (math, type = "png")=>{
    const encodedMath = encodeURI(math);
    return `https://latex.codecogs.com/${type}.latex?${encodedMath}`;
};
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 kGoogleAnalytics = "google-analytics";
const kTrackingId = "tracking-id";
const kStorage = "storage";
const kAnonymizeIp = "anonymize-ip";
const kVersion1 = "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 version = siteGaMeta[kVersion1];
            gaConfig = googleAnalyticsConfig(project, trackingId, storage, anonymizedIp, version);
        } 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, format, temp) {
    const siteMeta = project.config?.[kWebsite];
    if (siteMeta) {
        const title = siteMeta[kTitle] || "";
        let configuration = undefined;
        let changePrefsText = undefined;
        const consent = siteMeta[kCookieConsent];
        if (typeof consent === "object") {
            const cookieMeta = consent;
            configuration = cookieConsentConfiguration(title, cookieMeta[kCookieConsentType], cookieMeta[kCookieConsentStyle], cookieMeta[kCookieConsentPalette], cookieMeta[kCookieConsentPolicyUrl], cookieMeta[kLanguage] || format.metadata[kLang]);
            changePrefsText = cookieMeta[kCookiePrefsText];
        } else if (consent) {
            configuration = cookieConsentConfiguration(title, undefined, undefined, undefined, undefined, format.metadata[kLang]);
        }
        if (configuration) {
            const consentResourcesDir = join2(projectTypeResourcePath("website"), "cookie-consent");
            const name = "cookie-consent.js";
            const path = join2(consentResourcesDir, name);
            const cssName = "cookie-consent.css";
            const cssPath = join2(consentResourcesDir, cssName);
            return {
                scriptFile: scriptFile(cookieConsentScript(configuration), temp),
                dependency: {
                    name: "cookie-consent",
                    scripts: [
                        {
                            name,
                            path
                        }
                    ],
                    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, language) {
    return {
        siteName: "",
        type: type || "implied",
        style: style || "simple",
        palette: palette || "light",
        policyUrl,
        language
    };
}
function googleAnalyticsConfig(project, trackingId, storage, anoymizeIp, version) {
    return {
        trackingId,
        consent: cookieConsentEnabled(project),
        storage: storage || "cookies",
        anonymizeIp: anoymizeIp === undefined ? true : !!anoymizeIp,
        version: version || (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}"` : "";
    const language = config.language !== undefined ? `,\n"language":"${config.language}"` : "";
    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}
  ${language}
  });
});
</script> 
  `;
}
function scriptFile(script, temp) {
    const gaScriptFile = temp.createFile({
        suffix: "-lytics.js"
    });
    Deno.writeTextFileSync(gaScriptFile, script);
    return gaScriptFile;
}
function computePageTitle(format, extras) {
    const meta = extras?.metadata || {};
    const pageTitle = meta[kPageTitle] || format.metadata[kPageTitle];
    const titlePrefix = extras?.pandoc?.[kTitlePrefix] || format.pandoc[kTitlePrefix] || format.metadata[kWebsite]?.[kTitle];
    const title = format.metadata[kTitle];
    if (pageTitle !== undefined) {
        return pageTitle;
    } else if (titlePrefix !== undefined) {
        if (titlePrefix === title) {
            return title;
        } else if (title !== undefined) {
            return title + " – " + titlePrefix;
        } else {
            return titlePrefix + "";
        }
    } else {
        return title;
    }
}
function inputFileHref(href) {
    const [hrefDir, hrefStem] = dirAndStem(href);
    const htmlHref = "/" + join2(hrefDir, `${hrefStem}.html`);
    return pathWithForwardSlashes(htmlHref);
}
function websiteNavigationConfig(project) {
    let navbar = websiteConfig(kSiteNavbar, project.config);
    if (typeof navbar === "boolean" && navbar) {
        navbar = {
            background: "primary"
        };
    } else 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 = [];
        }
        for (const sb of sidebars){
            if (sb.contents && !Array.isArray(sb.contents)) {
                if (typeof sb.contents === "string") {
                    if (sb.contents === "auto") {
                        sb.contents = [
                            {
                                auto: true
                            }
                        ];
                    } else {
                        sb.contents = [
                            {
                                auto: sb.contents
                            }
                        ];
                    }
                } else {
                    sb.contents = [
                        sb.contents
                    ];
                }
            }
        }
    }
    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 i1 = 1; i1 < sidebars.length; i1++){
            sidebars[i1] = {
                ...sidebarOptions,
                ...sidebars[i1]
            };
        }
    }
    const pageNavigation = websiteConfigBoolean(kSitePageNavigation, false, project.config);
    const footer = resolvePageFooter(project.config);
    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;
    }
    const announcementRaw = websiteConfig(kAnnouncement, project.config);
    let announcement;
    if (typeof announcementRaw === "string") {
        announcement = {
            id: md5Hash(announcementRaw),
            icon: undefined,
            dismissable: true,
            content: announcementRaw,
            position: "above-navbar",
            type: "primary"
        };
    } else if (announcementRaw && !Array.isArray(announcementRaw)) {
        announcement = {
            id: md5Hash(announcementRaw.content),
            icon: announcementRaw.icon,
            dismissable: announcementRaw.dismissable !== false,
            content: announcementRaw.content,
            type: announcementRaw.type || "primary",
            position: announcementRaw.position || "above-navbar"
        };
    }
    return {
        navbar,
        sidebars,
        pageNavigation,
        footer,
        pageMargin,
        bodyDecorators,
        announcement
    };
}
function resolvePageFooter(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, 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);
    }
    return footer;
}
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 breadCrumbs(href, sidebar) {
    if (sidebar?.contents) {
        const crumbs = [];
        const makeBreadCrumbs = (href, sidebarItems)=>{
            if (sidebarItems) {
                for (const item of sidebarItems){
                    if (item.href === href) {
                        crumbs.push(item);
                        return true;
                    } else {
                        if (item.contents) {
                            if (makeBreadCrumbs(href, item.contents)) {
                                const breadCrumbItem = {
                                    ...item
                                };
                                if (!breadCrumbItem.href && breadCrumbItem.contents && breadCrumbItem.contents.length > 0) {
                                    breadCrumbItem.href = breadCrumbItem.contents[0].href;
                                }
                                crumbs.push(breadCrumbItem);
                                return true;
                            }
                        }
                    }
                }
                return false;
            } else {
                return false;
            }
        };
        makeBreadCrumbs(href, sidebar.contents);
        return crumbs.reverse();
    } else {
        return [];
    }
}
const navigation = {
    sidebars: []
};
function sidebarForHref(href, format) {
    if (navigation.sidebars.length === 1 && navigation.sidebars[0].id === undefined) {
        return navigation.sidebars[0];
    } else {
        const explicitSidebar = navigation.sidebars.find((sidebar)=>{
            return sidebar.id === format.metadata[kSiteSidebar];
        });
        if (explicitSidebar) {
            return explicitSidebar;
        } else {
            const containingSidebar = navigation.sidebars.find((sidebar)=>{
                return containsHref(href, sidebar.contents);
            });
            if (containingSidebar) {
                return containingSidebar;
            } else {
                return undefined;
            }
        }
    }
}
function navbarItemForSidebar(sidebar, format) {
    const findNavItemWithSidebar = (navItems)=>{
        if (navItems) {
            const navItem = navItems.find((val)=>{
                let href;
                if (typeof val === "object") {
                    href = val.href;
                } else {
                    href = val;
                }
                if (href) {
                    const navSidebar = sidebarForHref(href, format);
                    if (navSidebar === sidebar) {
                        return true;
                    }
                }
                return false;
            });
            if (navItem) {
                return navItem;
            }
        }
    };
    const leftNavItem = findNavItemWithSidebar(navigation.navbar?.left);
    if (leftNavItem) {
        return leftNavItem;
    }
    const rightNavItem = findNavItemWithSidebar(navigation.navbar?.right);
    if (rightNavItem) {
        return rightNavItem;
    }
    return undefined;
}
function containsHref(href, items) {
    for(let i1 = 0; i1 < items.length; i1++){
        if (items[i1].href && items[i1].href === href) {
            return true;
        } else if (Object.keys(items[i1]).includes("contents")) {
            const subItems = items[i1].contents || [];
            const subItemsHasHref = containsHref(href, subItems);
            if (subItemsHasHref) {
                return true;
            }
        } else {
            if (itemHasNavTarget(items[i1], href)) {
                return true;
            }
        }
    }
    return false;
}
function itemHasNavTarget(item, href) {
    return item.href === href || item.href === href.replace(/\/index\.html/, "/");
}
function removeChapterNumber(item) {
    const numberSpan = item.querySelector(".chapter-number");
    const titleSpan = item.querySelector(".chapter-title");
    if (numberSpan && titleSpan) {
        item.innerHTML = "";
        item.appendChild(titleSpan);
    }
}
function isProjectDraft(input, project) {
    const drafts = websiteConfigArray(kDrafts, project.config);
    if (drafts) {
        return drafts.includes(pathWithForwardSlashes(input));
    }
    return false;
}
function projectDraftMode(project) {
    const draftMode = websiteConfigString(kDraftMode, project.config);
    return draftMode || kDraftModeGone;
}
function isDraftVisible(draftMode) {
    return draftMode === "visible" || draftMode === "preview";
}
async function resolveProjectInputLinks(source, project, doc) {
    const sourceRelative = relative2(project.dir, source);
    const offset = projectOffset(project, source);
    const draftMode = projectDraftMode(project);
    const links = doc.querySelectorAll("a[href]");
    for(let i1 = 0; i1 < links.length; i1++){
        const link = links[i1];
        const resolveInput = link.getAttribute("data-noresolveinput") === null;
        if (!resolveInput) {
            link.removeAttribute("data-noresolveinput");
        }
        const linkHref = getDecodedAttribute(link, "href");
        if (linkHref && !isExternalPath(linkHref)) {
            let projRelativeHref = linkHref.startsWith("/") ? linkHref.slice(1) : join2(dirname2(sourceRelative), linkHref);
            const hashLoc = projRelativeHref.indexOf("#");
            const hash = hashLoc !== -1 ? projRelativeHref.slice(hashLoc) : "";
            if (hash) {
                projRelativeHref = projRelativeHref.slice(0, hashLoc);
            }
            const resolved = resolveInput ? await resolveInputTarget(project, pathWithForwardSlashes(projRelativeHref)) : {
                outputHref: pathWithForwardSlashes(join2("/", projRelativeHref)),
                draft: false
            };
            if (resolved) {
                if (resolved.draft && !isDraftVisible(draftMode)) {
                    link.replaceWith(link.innerHTML);
                } else {
                    link.setAttribute("href", offset + resolved.outputHref + hash);
                }
            } else {
                if (!safeExistsSync(join2(project.dir, projRelativeHref))) {
                    const targetFile = join2(projectOutputDir(project), projRelativeHref);
                    if (engineValidExtensions().includes(extname2(targetFile)) && !safeExistsSync(join2(projectOutputDir(project), projRelativeHref))) {
                        warn("Unable to resolve link target: " + projRelativeHref);
                    }
                }
            }
        }
    }
}
function isExternalPath(path) {
    return /^\w+:/.test(path);
}
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 kBreadcrumbPrefix = "quarto-breadcrumbs";
const kNavbarIdPrefix = "quarto-int-navbar:";
const kToolsPrefix = "quarto-navbar-tools:";
function navigationMarkdownHandlers(context) {
    return [
        sidebarTitleHandler(context),
        navbarTitleHandler(context),
        nextPageTitleHandler(context),
        prevPageTitleHandler(context),
        sidebarContentsHandler(context),
        sidebarHeaderFooterHandler(context),
        navbarContentsHandler(context),
        footerHandler(context),
        marginHeaderFooterHandler(context),
        bodyHeaderFooterHandler(context),
        breadCrumbHandler(context),
        announcementHandler(context)
    ];
}
function title(format) {
    const site = format.metadata[kWebsite];
    if (site && site[kTitle] && typeof site[kTitle] !== "object") {
        return String(site[kTitle]);
    } else if (format.metadata[kTitle] && typeof format.metadata[kTitle] !== "object") {
        return String(format.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 breadCrumbHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.breadCrumbs) {
                const markdown = {};
                for (const item of context.breadCrumbs){
                    if (item.text) {
                        markdown[`${kBreadcrumbPrefix}-${textKey(item.text)}`] = item.text;
                    }
                }
                return {
                    inlines: markdown
                };
            }
        },
        processRendered (rendered, doc) {
            const breadCrumbs = doc.querySelectorAll(".quarto-page-breadcrumbs .breadcrumb-item");
            for (const breadCrumb of breadCrumbs){
                const linkEl = breadCrumb.querySelector("a");
                const breadCrumbEl = linkEl !== null ? linkEl : breadCrumb;
                const key = breadCrumbEl.innerHTML;
                const renderedEl = rendered[`${kBreadcrumbPrefix}-${textKey(key)}`];
                if (renderedEl) {
                    breadCrumbEl.innerHTML = renderedEl.innerHTML;
                }
            }
        }
    };
};
const announcementHandler = (context)=>{
    return {
        getUnrendered () {
            if (context.announcement?.content) {
                return {
                    blocks: {
                        announcement: context.announcement.content
                    }
                };
            }
        },
        processRendered (rendered, doc) {
            const announceEl = doc.querySelector("#quarto-announcement .quarto-announcement-content");
            if (announceEl) {
                const renderedEl = rendered["announcement"];
                announceEl.innerHTML = renderedEl.innerHTML;
            }
        }
    };
};
const textKey = (text)=>{
    return text.replaceAll(/\s|&nbsp;/gm, "-").replaceAll(/"/gm, "'");
};
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}${textKey(item.text)}`] = item.text;
                        }
                    }
                });
                return {
                    inlines: markdown
                };
            }
        },
        processRendered (rendered, doc) {
            const sidebarItemEls = doc.querySelectorAll(".sidebar-item:not(.sidebar-item-section) .sidebar-item-text");
            for(let i1 = 0; i1 < sidebarItemEls.length; i1++){
                const sidebarEl = sidebarItemEls[i1];
                const href = sidebarEl.getAttribute("href");
                const link = sidebarEl.querySelector(".menu-text");
                if (link) {
                    const text = textKey(link.innerHTML);
                    const sidebarText = rendered[`${kSidebarIdPrefix}${href}${text}`];
                    if (sidebarText) {
                        link.innerHTML = sidebarText.innerHTML;
                    }
                }
            }
            const sidebarSectionEls = doc.querySelectorAll(".sidebar-item.sidebar-item-section .sidebar-item-text");
            for(let i1 = 0; i1 < sidebarSectionEls.length; i1++){
                const sectionEl = sidebarSectionEls[i1];
                const target = sectionEl.getAttribute("data-bs-target");
                if (target) {
                    const id = target.slice(1);
                    const sectionText = rendered[`${kSidebarIdPrefix}${id}`];
                    if (sectionText) {
                        const link = sectionEl.querySelector(".menu-text");
                        if (link) {
                            link.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 (typeof entry === "string") {
                        markdown[`${kNavbarIdPrefix}${entry.trim()}`] = entry;
                        return;
                    }
                    if (entry.text) {
                        markdown[`${kNavbarIdPrefix}${entry.text.trim()}`] = entry.text;
                    }
                    if (entry.href) {
                        markdown[`${kNavbarIdPrefix}${entry.href.trim()}`] = mdSafeHref(entry.href);
                    }
                    if (entry.menu?.entries) {
                        for (const childEntry of entry.menu){
                            addEntry(childEntry);
                        }
                    }
                };
                entries.forEach((entry)=>{
                    addEntry(entry);
                });
                const tools = context.navigation.navbar.tools;
                if (tools) {
                    tools.forEach((tool)=>{
                        if (tool.href) {
                            markdown[`${kToolsPrefix}${tool.href.trim()}`] = mdSafeHref(tool.href);
                        }
                    });
                }
                return {
                    inlines: markdown
                };
            }
        },
        processRendered (rendered, doc) {
            const selectors = [
                ".navbar-nav .nav-item a.nav-link .menu-text",
                ".navbar-nav .dropdown-menu .dropdown-item .dropdown-text",
                ".navbar-nav .dropdown-menu .dropdown-header"
            ];
            selectors.forEach((selector)=>{
                const navItemEls = doc.querySelectorAll(selector);
                for(let i1 = 0; i1 < navItemEls.length; i1++){
                    const link = navItemEls[i1];
                    const id = link.innerText.trim();
                    if (id) {
                        const renderedEl = rendered[`${kNavbarIdPrefix}${id}`];
                        if (renderedEl) {
                            link.innerHTML = renderedEl?.innerHTML;
                        }
                    }
                    const textParent = link.parentElement;
                    if (textParent) {
                        const href = textParent.getAttribute("href");
                        if (href) {
                            const renderedHref = rendered[`${kNavbarIdPrefix}${href}`];
                            if (renderedHref) {
                                textParent.setAttribute("href", renderedHref?.innerText);
                            }
                        }
                    }
                }
            });
            [
                ".navbar .quarto-navbar-tools .quarto-navigation-tool"
            ].forEach((sel)=>{
                const toolNodes = doc.querySelectorAll(sel);
                for(let i1 = 0; i1 < toolNodes.length; i1++){
                    const toolEl = toolNodes[i1];
                    const href = toolEl.getAttribute("href");
                    if (href) {
                        const renderedHref = rendered[`${kToolsPrefix}${href}`];
                        if (renderedHref) {
                            toolEl.setAttribute("href", renderedHref?.innerText);
                        }
                    }
                }
            });
        }
    };
};
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 result1 = {};
            if (context.sidebar?.header) {
                if (context.sidebar?.header && context.sidebar?.header.length > 0) {
                    result1[kSidebarHeader] = toHeaderFooterMarkdown(context.source, kSidebarHeader, context.sidebar.header);
                }
            }
            if (context.sidebar?.footer) {
                if (context.sidebar?.footer && context.sidebar?.footer.length > 0) {
                    result1[kSidebarFooter] = toHeaderFooterMarkdown(context.source, kSidebarFooter, context.sidebar.footer);
                }
            }
            return {
                blocks: result1
            };
        },
        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 result1 = {};
            if (context.bodyDecorators?.header) {
                result1[kBodyHeader] = toHeaderFooterMarkdown(context.source, kBodyHeader, context.bodyDecorators?.header);
            }
            if (context.bodyDecorators?.footer) {
                result1[kBodyFooter] = toHeaderFooterMarkdown(context.source, kBodyFooter, context.bodyDecorators?.footer);
            }
            return {
                blocks: result1
            };
        },
        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 result1 = {};
            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) {
                    result1[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) {
                    result1[kMarginFooter] = toHeaderFooterMarkdown(context.source, kMarginFooter, marginFooters);
                }
            }
            return {
                blocks: result1
            };
        },
        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 {
                    blocks: 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 i1 = 0; i1 < navItemEls.length; i1++){
                    const link = navItemEls[i1];
                    const href = link.getAttribute("href");
                    const id = href || link.innerText;
                    if (id) {
                        const renderedEl = rendered[`${kNavFooterPrefix}${key}-${id}`];
                        if (renderedEl) {
                            removeChapterNumber(renderedEl);
                            link.innerHTML = renderedEl?.innerHTML;
                        }
                    }
                }
            };
            process("left");
            process("center");
            process("right");
        }
    };
};
function expandMarkdown(source, name, 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 ${name}:\n${val}`);
    }
}
function expandMarkdownFilePath(source, path) {
    const absPath = isAbsolute2(path) ? path : join2(dirname2(source), path);
    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 path;
    }
}
function mdSafeHref(href) {
    href = href.replaceAll("---", "\\-\\-\\-");
    href = href.replaceAll("--", "\\-\\-");
    href = href.replaceAll("@", "\\@");
    return href;
}
function hasTableOfContents(flags, format) {
    return !!(flags[kToc] || format.pandoc[kToc] || format.pandoc[kTableOfContents]);
}
function disabledTableOfContents(format) {
    return format.pandoc[kToc] === false || format.pandoc[kTableOfContents] === false;
}
const kSearch = "search";
const kType = "type";
const kLocation = "location";
const kCopyButton = "copy-button";
const kCollapseAfter = "collapse-after";
const kPanelPlacement = "panel-placement";
const kKbShortcutSearch = "keyboard-shortcut";
const kLimit = "limit";
const kShowItemContext = "show-item-context";
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";
async function updateSearchIndex(context, outputFiles, incremental) {
    const outputDir = projectOutputDir(context);
    const searchJsonPath = join2(outputDir, "search.json");
    const searchJson = existsSync(searchJsonPath) ? Deno.readTextFileSync(searchJsonPath) : undefined;
    const searchDocs = new Array();
    let generateIndex = true;
    if (incremental && searchJson) {
        try {
            const existingSearchJson = JSON.parse(searchJson);
            searchDocs.push(...existingSearchJson);
        } catch  {
            generateIndex = false;
            warn("Unable to read search index - it may be corrupt. Please re-render the entire site to create a valid search index.");
        }
    }
    if (generateIndex) {
        const draftMode = projectDraftMode(context);
        let updatedSearchDocs = [
            ...searchDocs
        ];
        for (const outputFile of outputFiles){
            const file = outputFile.file;
            const href = pathWithForwardSlashes(relative2(outputDir, file));
            const index = await resolveInputTargetForOutputFile(context, relative2(outputDir, outputFile.file));
            const draft = index ? index.draft : false;
            if (outputFile.format.metadata[kSearch] === false || draft === true && !isDraftVisible(draftMode)) {
                updatedSearchDocs = updatedSearchDocs.filter((doc)=>{
                    return doc.href !== href && !doc.href.startsWith(href + "#");
                });
                continue;
            }
            if (!isHtmlFileOutput(outputFile.format.pandoc)) {
                continue;
            }
            const updateDoc = (doc)=>{
                const idx = updatedSearchDocs.findIndex((d)=>d.href === doc.href);
                if (idx !== -1) {
                    updatedSearchDocs[idx] = doc;
                } else {
                    updatedSearchDocs.push(doc);
                }
            };
            const contents = Deno.readTextFileSync(file);
            const doc = new DOMParser().parseFromString(contents, "text/html");
            const findTitle = ()=>{
                const titleEl = doc.querySelector("h1.title");
                if (titleEl) {
                    return titleEl;
                } else {
                    const title = doc.querySelector("main h1");
                    if (title) {
                        return title;
                    } else {
                        return undefined;
                    }
                }
            };
            const navHref = `/${href}`;
            const sidebar = sidebarForHref(navHref, outputFile.format);
            const bc = breadCrumbs(navHref, sidebar);
            const crumbs = bc.length > 0 ? bc.filter((crumb)=>{
                return crumb.text !== undefined;
            }).map((crumb)=>{
                return crumb.text;
            }) : undefined;
            if (crumbs && sidebar) {
                const navItem = navbarItemForSidebar(sidebar, outputFile.format);
                if (navItem) {
                    if (typeof navItem === "object") {
                        const navbarParentText = navItem.text;
                        if (navbarParentText) {
                            if (crumbs.length > 0 && crumbs[0] !== navbarParentText) {
                                crumbs.unshift(navbarParentText);
                            }
                        }
                    }
                }
            }
            const titleEl = findTitle();
            const title = titleEl ? titleEl.textContent : websiteTitle(context.config) || "";
            const header = doc.getElementById("title-block-header");
            if (header) {
                header.remove();
            }
            const toc = doc.querySelector(`nav[role="doc-toc"]`);
            if (toc) {
                toc.remove();
            }
            [
                "script",
                "style"
            ].forEach((tag)=>{
                const els = doc.querySelectorAll(tag);
                if (els) {
                    els.forEach((el)=>el.remove());
                }
            });
            const sections = doc.querySelectorAll("section.level2,section.footnotes");
            if (sections.length > 0) {
                const mainSelector = projectIsBook(context) ? "main > section:first-of-type" : "main.content";
                const mainEl = doc.querySelector(mainSelector);
                const firstEl = mainEl?.firstElementChild;
                const pageText = [];
                if (firstEl) {
                    const headings = firstEl.querySelectorAll("h1, h2, h3, h4, h5, h6");
                    headings.forEach((heading)=>heading.remove());
                    const trimmed = firstEl.textContent.trim();
                    if (trimmed) {
                        pageText.push(trimmed);
                    }
                    firstEl.remove();
                }
                const pararaphNodes = doc.querySelectorAll(`${mainSelector} > p, ${mainSelector} > div.cell`);
                for (const paragraphNode of pararaphNodes){
                    const text = paragraphNode.textContent.trim();
                    if (text) {
                        pageText.push(text);
                    }
                    paragraphNode.remove();
                }
                if (pageText.length > 0) {
                    updateDoc({
                        objectID: href,
                        href: href,
                        title,
                        section: "",
                        text: encodeHtml(pageText.join("\n")),
                        crumbs
                    });
                }
                for(let i1 = 0; i1 < sections.length; i1++){
                    const section = sections[i1];
                    const h2 = section.querySelector("h2");
                    if (section.id) {
                        const sectionTitle = h2 ? h2.textContent : "";
                        const hrefWithAnchor = `${href}#${section.id}`;
                        const sectionText = section.textContent.trim();
                        if (h2) {
                            h2.remove();
                        }
                        if (sectionText) {
                            updateDoc({
                                objectID: hrefWithAnchor,
                                href: hrefWithAnchor,
                                title,
                                section: sectionTitle,
                                text: encodeHtml(sectionText),
                                crumbs
                            });
                        }
                    }
                }
            } else {
                const main = doc.querySelector("main");
                if (main) {
                    const mainText = main.textContent.trim();
                    if (mainText) {
                        updateDoc({
                            objectID: href,
                            href,
                            title,
                            section: "",
                            text: encodeHtml(mainText),
                            crumbs
                        });
                    }
                }
            }
        }
        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 ? 3 : false;
        return {
            [kLocation]: location,
            [kCopyButton]: searchMetadata[kCopyButton] === true,
            [kCollapseAfter]: collapseMatches,
            [kPanelPlacement]: location === "navbar" ? "end" : "start",
            [kType]: searchType(searchMetadata[kType], location),
            [kLimit]: searchInputLimit(searchMetadata),
            [kAlgolia]: algoliaOptions(searchMetadata, project),
            [kKbShortcutSearch]: searchKbdShortcut(searchMetadata),
            [kShowItemContext]: searchShowItemContext(searchMetadata)
        };
    } else {
        const searchRaw = websiteConfig(kSearch, project.config);
        if (searchRaw === undefined || !!searchRaw) {
            return {
                [kLocation]: location,
                [kCopyButton]: false,
                [kCollapseAfter]: 3,
                [kPanelPlacement]: location === "navbar" ? "end" : "start",
                [kType]: searchType(undefined, location),
                [kLimit]: searchInputLimit(undefined),
                [kKbShortcutSearch]: searchKbdShortcut(undefined),
                [kShowItemContext]: searchShowItemContext(searchMetadata)
            };
        }
    }
}
function searchInputLimit(searchConfig) {
    if (searchConfig && typeof searchConfig === "object") {
        const limit = searchConfig[kLimit];
        if (typeof limit === "number") {
            return limit;
        }
    }
    return 50;
}
function searchKbdShortcut(searchConfig) {
    if (searchConfig && typeof searchConfig === "object") {
        const kbd = searchConfig[kKbShortcutSearch];
        if (kbd) {
            if (Array.isArray(kbd)) {
                return kbd;
            } else {
                return [
                    kbd
                ];
            }
        }
    }
    return [
        "f",
        "/",
        "s"
    ];
}
function searchShowItemContext(searchConfig) {
    if (searchConfig && typeof searchConfig === "object") {
        return searchConfig[kShowItemContext];
    } else {
        return false;
    }
}
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, format, temp) {
    const websiteSearchScript = temp.createFile({
        suffix: "-search.html"
    });
    const options = searchOptions(project) || {};
    options[kLanguageDefaults] = {};
    Object.keys(format.language).forEach((key)=>{
        if (key.startsWith("search-")) {
            options[kLanguageDefaults][key] = format.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 {
                warn("Algolia search is misconfigured. Please ensure that you provide an application-id, search-only-api-key, and index-name.");
            }
        }
        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>
`;
function asNumber(x, defaultValue = 0) {
    if (x === undefined) {
        return x;
    } else if (typeof x === "number") {
        return x;
    } else if (typeof x === "string") {
        try {
            return parseFloat(x);
        } catch  {
            return defaultValue;
        }
    } else if (typeof x === "boolean") {
        return x ? 1 : 0;
    } else {
        return defaultValue;
    }
}
async function expandAutoSidebarItems(project, items) {
    items = normalizeSidebarItems(cloneDeep1(items));
    const expanded = [];
    for (const item of items){
        if (item.auto) {
            const autoItems = await sidebarItemsFromAuto(project, item.auto);
            expanded.push(...autoItems);
        } else {
            if (item.contents) {
                if (typeof item.contents === "string") {
                    if (item.section) {
                        const hasProjectHref = project.files.input.includes(join2(project.dir, item.section)) || item.href && project.files.input.includes(join2(project.dir, item.href));
                        if (!hasProjectHref) {
                            const globbedDir = globbedDirectory(project, item.contents);
                            if (globbedDir) {
                                const indexFileHref = indexFileHrefForDir(project, globbedDir);
                                if (indexFileHref) {
                                    item.text = item.section;
                                    item.section = indexFileHref;
                                }
                            }
                        }
                    }
                }
                item.contents = await expandAutoSidebarItems(project, item.contents);
            }
            expanded.push(item);
        }
    }
    return expanded;
}
function globbedDirectory(project, contentsGlob) {
    const isValidDirectory = (dir)=>{
        return safeExistsSync(dir) && Deno.statSync(dir).isDirectory;
    };
    const literalTargetDir = join2(project.dir, contentsGlob);
    if (isValidDirectory(literalTargetDir)) {
        return literalTargetDir;
    }
    const match = contentsGlob.match(/(.*?)\/\*.*$/);
    if (match) {
        const globTargetDir = join2(project.dir, match[1]);
        if (isValidDirectory(globTargetDir)) {
            return globTargetDir;
        }
    }
}
function normalizeSidebarItems(items) {
    if (!Array.isArray(items)) {
        if (typeof items === "string") {
            if (items === "auto") {
                items = [
                    {
                        auto: true
                    }
                ];
            } else {
                items = [
                    {
                        auto: items
                    }
                ];
            }
        } else {
            items = [
                items
            ];
        }
    }
    return items;
}
async function sidebarItemsFromAuto(project, auto) {
    const isAutoDir = typeof auto === "string" && !!auto.match(/^[^\*]+$/) && safeExistsSync(join2(project.dir, auto));
    const globs = globsFromAuto(project, auto);
    const entries = [];
    for (const nodeSet of autoSidebarNodes(project, globs)){
        if (isAutoDir) {
            const root = nodeSet.root.split("/");
            nodeSet.root = root.slice(0, -1).join("/");
            nodeSet.nodes = {
                [root.slice(-1)[0]]: nodeSet.nodes
            };
        }
        entries.push(...await nodesToEntries(project, `${nodeSet.root ? nodeSet.root + "/" : ""}`, nodeSet.nodes));
    }
    return sidebarItemsFromEntries(entries.sort(sortEntries));
}
function globsFromAuto(project, auto) {
    const globs = [];
    if (typeof auto === "boolean") {
        if (auto === true) {
            globs.push("*");
        }
    } else {
        if (!Array.isArray(auto)) {
            auto = [
                auto
            ];
        }
        globs.push(...auto.map((glob)=>{
            const target = join2(project.dir, glob);
            if (safeExistsSync(target) && Deno.statSync(target).isDirectory) {
                glob = join2(glob, "**");
            }
            return glob;
        }));
    }
    return globs;
}
function autoSidebarNodes(project, globs) {
    return globs.map((glob)=>{
        const inputs = __VIRTUAL_FILE181(filterPaths(project.dir, project.files.input, [
            glob
        ], {
            mode: "always"
        }).include).filter((input)=>!/^index\.\w+$/.test(input)).map((input)=>pathWithForwardSlashes(relative2(project.dir, input)));
        let directory = "";
        const match = glob.match(/(.*?)[\/\\]\*.*$/);
        if (match && safeExistsSync(join2(project.dir, match[1]))) {
            directory = match[1];
        }
        let result1 = {};
        inputs.forEach((p)=>p.split("/").reduce((o, k)=>o[k] = o[k] || {}, result1));
        if (directory) {
            directory.split("/").forEach((p)=>{
                result1 = result1[p];
            });
        }
        return {
            root: directory,
            nodes: result1
        };
    });
}
function indexFileHrefForDir(project, dir) {
    const indexFileExt = engineValidExtensions().find((ext)=>{
        return safeExistsSync(join2(dir, `index${ext}`));
    });
    if (indexFileExt) {
        return relative2(project.dir, join2(dir, `index${indexFileExt}`));
    }
}
async function nodesToEntries(project, root, nodes) {
    nodes = cloneDeep1(nodes);
    const indexFile = findIndexFile(nodes);
    if (indexFile) {
        delete nodes[indexFile];
    }
    const entries = [];
    for (const node of Object.keys(nodes)){
        const href = `${root}${node}`;
        const path = join2(project.dir, href);
        if (safeExistsSync(path)) {
            if (Deno.statSync(path).isDirectory) {
                const childNodes = __VIRTUAL_FILE107(nodes[node]);
                const indexFile = findIndexFile(childNodes);
                if (indexFile) {
                    delete childNodes[indexFile];
                }
                if (indexFile) {
                    entries.push({
                        ...await entryFromHref(project, relative2(project.dir, join2(path, indexFile))),
                        children: childNodes && Object.keys(childNodes).length > 0 ? await nodesToEntries(project, `${root}${node}/`, childNodes) : undefined
                    });
                } else {
                    entries.push({
                        title: titleFromPath(href),
                        basename: basename2(href),
                        children: await nodesToEntries(project, `${root}${node}/`, childNodes)
                    });
                }
            } else {
                entries.push(await entryFromHref(project, href));
            }
        }
    }
    return entries.sort(sortEntries);
}
function findIndexFile(nodes) {
    return Object.keys(nodes).find((input)=>/^index\.\w+$/.test(input));
}
function sortEntries(a, b) {
    const filenameOrder = a.basename.toLocaleUpperCase().localeCompare(b.basename.toLocaleUpperCase());
    if (a.order !== undefined && b.order !== undefined) {
        const order = a.order - b.order;
        return order !== 0 ? order : filenameOrder;
    } else if (a.order !== undefined) {
        return -1;
    } else if (b.order !== undefined) {
        return 1;
    } else {
        if (a.children && !b.children) {
            return 1;
        } else if (b.children && !a.children) {
            return -1;
        } else {
            return filenameOrder;
        }
    }
}
async function entryFromHref(project, href) {
    const index = await inputTargetIndex(project, pathWithForwardSlashes(href));
    const resolved = await resolveInputTarget(project, pathWithForwardSlashes(href));
    const basename = dirAndStem(href)[1];
    return {
        title: index?.title || resolved?.title || titleFromPath(basename),
        basename,
        href: href,
        order: asNumber(index?.markdown.yaml?.[kOrder]),
        empty: index ? inputTargetIsEmpty(index) : false,
        draft: resolved?.draft
    };
}
function titleFromPath(path) {
    const name = basename2(path);
    if (!name.includes(" ")) {
        return capitalizeTitle(name.replaceAll(/[_\-]+/g, " "));
    } else {
        return name;
    }
}
function sidebarItemsFromEntries(entries) {
    return entries.map((entry)=>{
        if (entry.children) {
            return {
                section: !entry.href || entry.empty ? entry.title : entry.href,
                contents: sidebarItemsFromEntries(entry.children)
            };
        } else {
            return {
                text: entry.title,
                href: entry.href,
                draft: entry.draft
            };
        }
    });
}
const kDashboard = "dashboard";
const kDTTableSentinel = "data-dt-support";
const kLayoutAttr = "data-layout";
const kFillAttr = "data-fill";
const kLayoutFill = "fill";
const kLayoutFlow = "flow";
const kCardClass = "card";
const kDashboardGridSkip = "grid-skip";
const kNavButtons = "nav-buttons";
const kDontMutateTags = [
    "P",
    "SCRIPT"
];
const kValueboxClass = "valuebox";
function dashboardScssLayer() {
    const dashboardScss = formatResourcePath("dashboard", "quarto-dashboard.scss");
    const dashboardLayer = sassLayer(dashboardScss);
    const dashboardScssDependency = {
        dependency: kBootstrapDependencyName,
        key: dashboardScss,
        quarto: {
            name: "quarto-dashboard.css",
            ...dashboardLayer
        }
    };
    return dashboardScssDependency;
}
async function dashboardMeta(format) {
    const dashboardRaw = format.metadata;
    const orientation = dashboardRaw && dashboardRaw.orientation === "columns" ? "columns" : "rows";
    const scrolling = dashboardRaw.scrolling === true;
    const expandable = dashboardRaw.expandable !== false;
    const dashboardTitle = format.metadata[kTitle];
    const processNavbarButton = async (buttonRaw)=>{
        if (typeof buttonRaw === "string") {
            if (kNavButtonAliases[buttonRaw] !== undefined) {
                return kNavButtonAliases[buttonRaw](dashboardTitle);
            }
            return undefined;
        } else {
            return buttonRaw;
        }
    };
    const navbarButtons = [];
    const navbarButtonsRaw = format.metadata[kNavButtons];
    if (Array.isArray(navbarButtonsRaw)) {
        for (const btnRaw of navbarButtonsRaw){
            const btn = await processNavbarButton(btnRaw);
            if (btn) {
                navbarButtons.push(btn);
            }
        }
    } else {
        const btn = await processNavbarButton(navbarButtonsRaw);
        if (btn) {
            navbarButtons.push(btn);
        }
    }
    const hasDarkMode = formatDarkMode(format) !== undefined;
    return {
        orientation,
        scrolling,
        expandable,
        hasDarkMode,
        [kNavButtons]: navbarButtons
    };
}
function hasFlowLayout(el) {
    return el.getAttribute(kLayoutAttr) === kLayoutFlow;
}
function makeEl(name, attr, doc) {
    const el = doc.createElement(name);
    if (attr.id) {
        el.id = attr.id;
    }
    for (const cls of attr.classes || []){
        el.classList.add(cls);
    }
    const attribs = attr.attributes || {};
    for (const key of Object.keys(attribs)){
        el.setAttribute(key, attribs[key]);
    }
    return el;
}
const processAndRemoveAttr = (el, attr, process, defaultValue)=>{
    const resolvedAttr = el.getAttribute(attr);
    if (resolvedAttr !== null) {
        process(el, resolvedAttr);
        el.removeAttribute(attr);
    } else if (defaultValue) {
        process(el, defaultValue);
    }
};
const ensureCssUnits = (fn)=>{
    return (el, attrValue)=>{
        if (attrValue === "0") {
            fn(el, attrValue);
        } else {
            const attrWithUnits = attrValue.match(kEndsWithNumber) ? `${attrValue}px` : attrValue;
            fn(el, attrWithUnits);
        }
    };
};
const kEndsWithNumber = /[0-9]$/;
const attrToStyle = (style)=>{
    return (el, attrValue)=>{
        const newStyle = [];
        const currentStyle = el.getAttribute("style");
        if (currentStyle !== null) {
            newStyle.push(currentStyle);
        }
        newStyle.push(`${style}: ${attrValue};`);
        el.setAttribute("style", newStyle.join(" "));
    };
};
const attrToCardBodyStyle = (style)=>{
    return (el, attrValue)=>{
        const cardBodyNodes = el.querySelectorAll(".card-body");
        for (const cardBodyNode of cardBodyNodes){
            const cardBodyEl = cardBodyNode;
            const newStyle = [];
            const currentStyle = el.getAttribute("style");
            if (currentStyle !== null) {
                newStyle.push(currentStyle);
            }
            newStyle.push(`${style}: ${attrValue};`);
            cardBodyEl.setAttribute("style", newStyle.join(" "));
        }
    };
};
const applyClasses = (el, clz)=>{
    for (const cls of clz){
        el.classList.add(cls);
    }
};
const applyAttributes = (el, attr)=>{
    for (const key of Object.keys(attr)){
        el.setAttribute(key, attr[key]);
    }
};
const kNavButtonAliases = {
    linkedin: (text)=>{
        return Promise.resolve({
            icon: "linkedin",
            title: "LinkedIn",
            href: `https://www.linkedin.com/sharing/share-offsite/?url=|url|&title=${text ? encodeURI(text) : undefined}`
        });
    },
    facebook: (_text)=>{
        return Promise.resolve({
            icon: "facebook",
            title: "Facebook",
            href: "https://www.facebook.com/sharer/sharer.php?u=|url|"
        });
    },
    reddit: (text)=>{
        return Promise.resolve({
            icon: "reddit",
            title: "Reddit",
            href: `https://reddit.com/submit?url=|url|&title=${text ? encodeURI(text) : undefined}`
        });
    },
    twitter: (text)=>{
        return Promise.resolve({
            icon: "twitter",
            title: "Twitter",
            href: `https://twitter.com/intent/tweet?url=|url|&text=${text ? encodeURI(text) : undefined}`
        });
    },
    github: async (_text)=>{
        const context = await gitHubContext(Deno.cwd());
        if (context.repoUrl) {
            return {
                icon: "github",
                title: "GitHub",
                href: context.repoUrl
            };
        } else {
            warn("Unable to determine GitHub repository for the `github` nav-button. Is this directory a GitHub repository?");
            return undefined;
        }
    }
};
const kSidebarLogo = "logo";
const kAbout = "about";
const kSidebarLogoHref = "logo-href";
const kSidebarLogoAlt = "logo-alt";
async function initWebsiteNavigation(project) {
    resetMenuIds();
    const { navbar, sidebars, pageNavigation, footer, pageMargin, bodyDecorators, announcement } = websiteNavigationConfig(project);
    if (!navbar && !sidebars && !pageNavigation && !footer && !pageMargin && !bodyDecorators) {
        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;
    navigation.announcement = announcement;
}
async function websiteNoThemeExtras(project, source, _flags, _format, _temp) {
    return {
        html: {
            [kHtmlPostprocessors]: [
                async (doc)=>{
                    await resolveProjectInputLinks(source, project, doc);
                    return Promise.resolve({
                        resources: [],
                        supporting: []
                    });
                }
            ]
        }
    };
}
const kTemplate1 = "template";
const kType1 = "type";
const kLinks = "links";
const kImageWidth1 = "image-width";
const kImageAlt2 = "image-alt";
const kImageTitle = "image-title";
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
];
function isAboutPage(format) {
    return !!format.metadata[kAbout];
}
async function websiteNavigationExtras(project, source, flags, format, temp) {
    const usesCustomLayout = !formatHasArticleLayout(format);
    const hasToc = ()=>{
        if (disabledTableOfContents(format)) {
            return false;
        } else if (hasTableOfContents(flags, format)) {
            return true;
        } else if (usesCustomLayout) {
            return false;
        } else {
            return true;
        }
    };
    const tocLocation = ()=>{
        if (isAboutPage(format)) {
            return "right";
        } else {
            return format.metadata[kTocLocation] || "right";
        }
    };
    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, format, temp));
    }
    sassBundles.push(dashboardScssLayer());
    const disableNavbar = format.metadata[kSiteNavbar] !== undefined && format.metadata[kSiteNavbar] === false;
    const disableSidebar = format.metadata[kSiteSidebar] !== undefined && format.metadata[kSiteSidebar] === false || usesCustomLayout;
    const target = await resolveInputTarget(project, inputRelative);
    const href = target?.outputHref || inputFileHref(inputRelative);
    const sidebar = sidebarForHref(href, format);
    const draftMode = projectDraftMode(project);
    const nav = {
        hasToc: hasToc(),
        [kTocLocation]: tocLocation(),
        layout: formatPageLayout(format),
        navbar: disableNavbar ? undefined : navigation.navbar,
        sidebar: disableSidebar ? undefined : expandedSidebar(href, sidebar),
        sidebarStyle: sidebarStyle(),
        footer: navigation.footer,
        language: format.language,
        showBreadCrumbs: websiteConfigBoolean(kBreadCrumbNavigation, true, project.config),
        announcement: navigation.announcement,
        draftMode
    };
    const formatPageNav = format.metadata[kSitePageNavigation];
    const pageNavigation = nextAndPrevious(href, sidebar);
    if (formatPageNav !== false && (navigation.pageNavigation || formatPageNav === true) && !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
            });
        }
    }
    const crumbs = breadCrumbs(href, sidebar);
    navigation.breadCrumbs = crumbs;
    if (navigation.footer) {
        nav.footer = navigation.footer;
    }
    const darkMode = formatDarkMode(format);
    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 = (template)=>resourcePath(`projects/website/templates/${template}`);
    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,
        sidebar,
        navigation,
        pageNavigation,
        bodyDecorators: navigation.bodyDecorators,
        breadCrumbs: navigation.breadCrumbs,
        announcement: navigation.announcement
    });
    const markdownPipeline = createMarkdownPipeline("quarto-navigation-envelope", pipelineHandlers);
    return {
        [kIncludeInHeader]: includeInHeader,
        html: {
            [kSassBundles]: sassBundles,
            [kDependencies]: dependencies,
            [kBodyEnvelope]: bodyEnvelope,
            [kHtmlPostprocessors]: [
                navigationHtmlPostprocessor(project, format, source, markdownPipeline, format.language)
            ],
            [kMarkdownAfterBody]: [
                markdownPipeline.markdownAfterBody()
            ]
        }
    };
}
async function ensureIndexPage(project) {
    const outputDir = projectOutputDir(project);
    const indexPage = join2(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(path, href) {
    const redirectTemplate = resourcePath("projects/website/templates/redirect-simple.ejs");
    const redirectHtml = renderEjs(redirectTemplate, {
        url: href
    });
    Deno.writeTextFileSync(path, redirectHtml);
}
function navigationHtmlPostprocessor(project, format, source, markdownPipeline, language) {
    const sourceRelative = relative2(project.dir, source);
    const href = inputFileHref(sourceRelative);
    const showBreadCrumbs = websiteConfigBoolean(kBreadCrumbNavigation, true, project.config) && format.metadata[kBreadCrumbNavigation] !== false;
    return async (doc)=>{
        const secondaryNavTitleEl = doc.querySelector(".quarto-secondary-nav .quarto-secondary-nav-title");
        if (secondaryNavTitleEl) {
            if (showBreadCrumbs) {
                const navEl = makeBreadCrumbs(doc);
                if (secondaryNavTitleEl.parentElement) {
                    secondaryNavTitleEl.parentElement.replaceChild(navEl, secondaryNavTitleEl);
                }
            } else {
                const titleEl = doc.querySelector("h1.title");
                if (titleEl) {
                    for (const child of titleEl.childNodes){
                        secondaryNavTitleEl.append(child.cloneNode(true));
                    }
                    titleEl.classList.add("d-none");
                    titleEl.classList.add("d-lg-block");
                }
            }
            const titleBlock = doc.querySelector("header > .quarto-title-block");
            if (titleBlock) {
                titleBlock.classList.add("d-none");
                titleBlock.classList.add("d-lg-block");
            }
        }
        const titleBlockEl = doc.querySelector(".quarto-title-block");
        if (showBreadCrumbs && titleBlockEl) {
            if (navigation.breadCrumbs && navigation.breadCrumbs.length > 1) {
                const titleBreadCrumbEl = makeBreadCrumbs(doc, [
                    "quarto-title-breadcrumbs",
                    "d-none",
                    "d-lg-block"
                ]);
                const bannerTitle = titleBlockEl.querySelector(".quarto-title-banner .quarto-title");
                if (bannerTitle !== null) {
                    bannerTitle.prepend(titleBreadCrumbEl);
                } else {
                    titleBlockEl.prepend(titleBreadCrumbEl);
                }
            }
        }
        markdownPipeline.processRenderedMarkdown(doc);
        const sidebar = sidebarForHref(href, format);
        const sidebarHidden = format.metadata[kSiteSidebar] === false;
        if (sidebar && !sidebarHidden) {
            doc.body.classList.add("nav-sidebar");
        }
        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 headerEl = doc.body.querySelector("#quarto-header.fixed-top nav.navbar");
        if (headerEl) {
            doc.body.classList.add("nav-fixed");
        }
        const navLinks = doc.querySelectorAll("a.nav-link");
        for(let i1 = 0; i1 < navLinks.length; i1++){
            const navLink = navLinks[i1];
            const navLinkHref = navLink.getAttribute("href");
            const sidebarLink = doc.querySelector('.sidebar-navigation a[href="' + navLinkHref + '"]');
            if (sidebarLink || navLinkHref === href) {
                navLink.classList.add("active");
                navLink.setAttribute("aria-current", "page");
                break;
            }
        }
        await resolveProjectInputLinks(source, project, doc);
        handleRepoLinks(format, doc, pathWithForwardSlashes(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 i1 = 0; i1 < sidebarItems.length; i1++){
                const sidebarItem = sidebarItems[i1];
                removeChapterNumber(sidebarItem);
            }
            const sels = [
                "h1.title",
                ".page-navigation .nav-page-next .nav-page-text",
                ".page-navigation .nav-page-previous .nav-page-text",
                "h1.quarto-secondary-nav-title",
                ".breadcrumb-item a"
            ];
            for (const sel of sels){
                const nodes = doc.querySelectorAll(sel);
                if (nodes !== null) {
                    for (const node of nodes){
                        removeChapterNumber(node);
                    }
                }
            }
        }
        const projBackToTop = websiteConfigBoolean(kBackToTopNavigation, false, project.config);
        const formatBackToTop = format.metadata[kBackToTopNavigation];
        if (projBackToTop && formatBackToTop !== false) {
            const contentEl = doc.querySelector("main");
            const backToTopEl = doc.createElement("a");
            backToTopEl.setAttribute("onclick", "window.scrollTo(0, 0); return false;");
            const backText = language[kBackToTop];
            const backIcon = "arrow-up";
            backToTopEl.setAttribute("role", "button");
            backToTopEl.innerHTML = `<i class='bi bi-${backIcon}'></i> ${backText}`;
            backToTopEl.id = "quarto-back-to-top";
            contentEl?.appendChild(backToTopEl);
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function handleRepoLinks(format, doc, source, language, config) {
    if (format.metadata[kSiteRepoActions] === false) {
        return;
    }
    const forceRepoActions = format.metadata[kSiteRepoActions] === true;
    const repoActions = websiteConfigActions(kSiteRepoActions, kWebsite, config);
    const issueUrl = websiteConfigString(kSiteIssueUrl, config);
    if (issueUrl && !repoActions.includes("issue")) {
        repoActions.push("issue");
    }
    const elRepoSource = doc.querySelector("[" + kDataQuartoSourceUrl + '="repo"]');
    if (repoActions.length > 0 || elRepoSource) {
        const repoInfo = websiteRepoInfo(format, config);
        if (repoInfo || issueUrl) {
            if (repoActions.length > 0) {
                const repoTargets = [];
                const tocRepoTarget = doc.querySelector(`nav[role="doc-toc"]`);
                if (tocRepoTarget) {
                    repoTargets.push({
                        el: tocRepoTarget
                    });
                }
                if (repoTargets.length === 0 && forceRepoActions) {
                    const sidebarRepoTarget = doc.querySelector("#quarto-margin-sidebar");
                    if (sidebarRepoTarget) {
                        repoTargets.push({
                            el: sidebarRepoTarget
                        });
                    }
                }
                const footerRepoTarget = doc.querySelector(".nav-footer .nav-footer-center");
                if (footerRepoTarget) {
                    repoTargets.push({
                        el: footerRepoTarget,
                        clz: repoTargets.length > 0 ? [
                            "d-sm-block",
                            "d-md-none"
                        ] : undefined
                    });
                } else {
                    const ensureEl = (doc, tagname, classname, parent, afterEl)=>{
                        let el = parent.querySelector(`${tagname}.${classname}`);
                        if (!el) {
                            el = doc.createElement(tagname);
                            el.classList.add(classname);
                            if (afterEl !== null && afterEl && afterEl.nextElementSibling) {
                                parent.insertBefore(el, afterEl.nextElementSibling);
                            } else {
                                parent.appendChild(el);
                            }
                        }
                        return el;
                    };
                    const footerEl = ensureEl(doc, "footer", "footer", doc.body, doc.querySelector("div#quarto-content"));
                    const footerContainer = ensureEl(doc, "div", "nav-footer", footerEl);
                    const footerCenterEl = ensureEl(doc, "div", "nav-footer-center", footerContainer, footerContainer.querySelector(".nav-footer-left"));
                    repoTargets.push({
                        el: footerCenterEl,
                        clz: repoTargets.length > 0 ? [
                            "d-sm-block",
                            "d-md-none"
                        ] : undefined
                    });
                }
                if (repoTargets.length > 0) {
                    const linkTarget = websiteConfigString(kSiteRepoLinkTarget, config);
                    const linkRel = websiteConfigString(kSiteRepoLinkRel, config);
                    const links = repoInfo ? repoActionLinks(repoActions, repoInfo, websiteRepoBranch(config), source, language, issueUrl) : [
                        {
                            text: language[kRepoActionLinksIssue],
                            url: issueUrl,
                            icon: "chat-right"
                        }
                    ];
                    repoTargets.forEach((repoTarget)=>{
                        const actionsDiv = doc.createElement("div");
                        actionsDiv.classList.add("toc-actions");
                        const ulEl = doc.createElement("ul");
                        links.forEach((link)=>{
                            const a = doc.createElement("a");
                            a.setAttribute("href", link.url);
                            if (linkTarget) {
                                a.setAttribute("target", linkTarget);
                            }
                            if (linkRel) {
                                a.setAttribute("rel", linkRel);
                            }
                            a.classList.add("toc-action");
                            a.innerHTML = link.text;
                            const i1 = doc.createElement("i");
                            i1.classList.add("bi");
                            if (link.icon) {
                                i1.classList.add(`bi-${link.icon}`);
                            } else {
                                i1.classList.add(`empty`);
                            }
                            a.prepend(i1);
                            const liEl = doc.createElement("li");
                            liEl.appendChild(a);
                            ulEl.appendChild(liEl);
                        });
                        actionsDiv.appendChild(ulEl);
                        repoTarget.el.appendChild(actionsDiv);
                        if (repoTarget.clz) {
                            repoTarget.clz.forEach((cls)=>{
                                actionsDiv.classList.add(cls);
                            });
                        }
                    });
                }
            }
            if (elRepoSource && repoInfo) {
                elRepoSource.setAttribute(kDataQuartoSourceUrl, `${repoInfo.baseUrl}blob/${websiteRepoBranch(config)}/${repoInfo.path}${source}`);
            }
        } else {
            warnOnce(`Repository links require that you specify a ${kSiteRepoUrl}`);
        }
    }
}
function repoActionLinks(actions, repoInfo, branch, source, language, issueUrl) {
    const firstIcon = repoUrlIcon(repoInfo.baseUrl);
    return actions.map((action, i1)=>{
        switch(action){
            case "edit":
                if (!isJupyterNotebook(source)) {
                    return {
                        text: language[kRepoActionLinksEdit],
                        url: `${repoInfo.baseUrl}edit/${branch}/${repoInfo.path}${source}`,
                        icon: i1 === 0 ? firstIcon : undefined
                    };
                } else if (repoInfo.baseUrl.indexOf("github.com") !== -1) {
                    return {
                        text: language[kRepoActionLinksEdit],
                        url: `${repoInfo.baseUrl.replace("github.com", "github.dev")}blob/${branch}/${repoInfo.path}${source}`,
                        icon: i1 === 0 ? firstIcon : undefined
                    };
                } else {
                    return null;
                }
            case "source":
                return {
                    text: language[kRepoActionLinksSource],
                    url: `${repoInfo.baseUrl}blob/${branch}/${repoInfo.path}${source}`,
                    icon: i1 === 0 ? firstIcon : undefined
                };
            case "issue":
                return {
                    text: language[kRepoActionLinksIssue],
                    url: issueUrl || `${repoInfo.baseUrl}issues/new`,
                    icon: i1 === 0 ? firstIcon : undefined
                };
            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 i1 = 0; i1 < contents.length; i1++){
                const item = contents[i1];
                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;
}
function makeBreadCrumbs(doc, clz) {
    const navEl = doc.createElement("nav");
    navEl.classList.add("quarto-page-breadcrumbs");
    if (clz && clz.length) {
        clz.forEach((cls)=>{
            navEl.classList.add(cls);
        });
    }
    navEl.setAttribute("aria-label", "breadcrumb");
    const olEl = doc.createElement("ol");
    olEl.classList.add("breadcrumb");
    navEl.append(olEl);
    const breadCrumbEl = ()=>{
        const liEl = doc.createElement("li");
        liEl.classList.add("breadcrumb-item");
        return liEl;
    };
    if (navigation.breadCrumbs && navigation.breadCrumbs.length > 0) {
        for (const item of navigation.breadCrumbs){
            if (item.text || item.icon) {
                const liEl = breadCrumbEl();
                const maybeLink = (liEl, contents)=>{
                    if (item.href) {
                        const linkEl = doc.createElement("a");
                        linkEl.setAttribute("href", item.href);
                        if (typeof contents === "string") {
                            linkEl.innerHTML = contents;
                        } else {
                            linkEl.appendChild(contents);
                        }
                        liEl.appendChild(linkEl);
                        return liEl;
                    } else {
                        if (typeof contents === "string") {
                            liEl.innerHTML = item.text || "";
                        } else {
                            liEl.appendChild(contents);
                        }
                        return liEl;
                    }
                };
                if (item.text) {
                    olEl.appendChild(maybeLink(liEl, item.text || ""));
                } else if (item.icon) {
                    const iconEl = doc.createElement("i");
                    iconEl.classList.add("bi");
                    iconEl.classList.add(`bi-${item.icon}`);
                    olEl.appendChild(maybeLink(liEl, iconEl));
                }
            }
        }
    } else {
        const sidebarTitle = doc.querySelector(".sidebar-title a");
        if (sidebarTitle) {
            const liEl = breadCrumbEl();
            liEl.innerHTML = sidebarTitle.innerHTML;
            olEl.appendChild(liEl);
        } else {
            const sidebarTitleBare = doc.querySelector(".sidebar-title");
            if (sidebarTitleBare) {
                const liEl = breadCrumbEl();
                liEl.innerHTML = sidebarTitleBare.innerHTML;
                olEl.appendChild(liEl);
            } else {
                const title = doc.querySelector("header .title .quarto-section-identifier") || doc.querySelector("header .title");
                if (title) {
                    const liEl = breadCrumbEl();
                    liEl.innerHTML = title.innerHTML;
                    olEl.appendChild(liEl);
                }
            }
        }
    }
    return navEl;
}
async function sidebarsEjsData(project, sidebars) {
    const ejsSidebars = [];
    for(let i1 = 0; i1 < sidebars.length; i1++){
        ejsSidebars.push(await sidebarEjsData(project, sidebars[i1]));
    }
    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.alignment = sidebar.alignment || sidebar.align || "left";
    sidebar.pinned = sidebar.pinned !== undefined ? !!sidebar.pinned : false;
    await resolveSidebarItems(project, sidebar);
    await resolveSidebarTools(project, sidebar.tools);
    return sidebar;
}
async function resolveSidebarItems(project, container) {
    if (!container.contents) {
        return;
    }
    const context = sidebarContext();
    container.contents = await expandAutoSidebarItems(project, container.contents || []);
    const items = container.contents;
    for(let i1 = 0; i1 < items.length; i1++){
        let item = normalizeSidebarItem(project.dir, items[i1], context);
        if (Object.keys(item).includes("contents")) {
            const subItems = item.contents || [];
            if (item.href) {
                item = await resolveItem(project, item.href, item, true);
            }
            for(let i1 = 0; i1 < subItems.length; i1++){
                subItems[i1] = await resolveSidebarItem(project, normalizeSidebarItem(project.dir, subItems[i1], context));
            }
            items[i1] = item;
        } else {
            items[i1] = await resolveSidebarItem(project, item);
        }
    }
}
async function resolveSidebarItem(project, item) {
    if (item.href) {
        item = await resolveItem(project, item.href, item, true);
    }
    if (item.contents !== undefined) {
        await resolveSidebarItems(project, item);
        return item;
    } else {
        return item;
    }
}
async function resolveSidebarTools(project, tools) {
    if (tools) {
        for(let i1 = 0; i1 < tools.length; i1++){
            if (Object.keys(tools[i1]).includes("menu")) {
                const items = tools[i1].menu || [];
                for(let i1 = 0; i1 < items.length; i1++){
                    const toolItem = await navigationItem(project, items[i1], 1);
                    if (typeof toolItem === "object" && toolItem.href) {
                        const tool = await resolveItem(project, toolItem.href, toolItem);
                        validateTool(tool);
                        items[i1] = tool;
                    }
                }
            } else {
                const toolItem = tools[i1];
                resolveHrefAttribute(toolItem);
                if (toolItem.href) {
                    tools[i1] = await resolveItem(project, toolItem.href, toolItem);
                    validateTool(tools[i1]);
                }
            }
        }
    }
}
function validateTool(tool) {
    if (tool.icon === undefined && tool.text === undefined) {
        warn("A sidebar tool is defined without text or an icon.");
    }
}
function sidebarStyle() {
    if (navigation.sidebars.length > 0) {
        return navigation.sidebars[0].style;
    } else {
        return undefined;
    }
}
function expandedSidebar(href, sidebar) {
    if (sidebar) {
        const resolveExpandedItems = (href, items)=>{
            for(let i1 = 0; i1 < items.length; i1++){
                const item = items[i1];
                item.active = itemHasNavTarget(item, href);
                if (Object.keys(item).includes("contents")) {
                    if (resolveExpandedItems(href, item.contents || []) || item.href === href) {
                        item.expanded = true;
                        return true;
                    }
                } else if (item.active) {
                    return true;
                }
            }
            return false;
        };
        const expandedSidebar = __VIRTUAL_FILE107(sidebar);
        resolveExpandedItems(href, expandedSidebar.contents);
        return expandedSidebar;
    }
}
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 && !isExternalPath1(item.href) || isSeparator(item);
        });
        const sidebarItemsUniq = __VIRTUAL_FILE210(sidebarItems, (sidebarItem)=>{
            return sidebarItem.href || Math.random().toString();
        });
        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 data = {
        ...navbar,
        search: searchOpts && searchOpts.location === "navbar" ? searchOpts.type : false,
        background: navbar.background || "primary",
        logo: resolveLogo(navbar.logo),
        [kLogoAlt]: navbar[kLogoAlt],
        [kLogoHref]: navbar[kLogoHref],
        collapse,
        [kCollapseBelow]: !collapse ? "" : "-" + (navbar[kCollapseBelow] || "lg"),
        pinned: navbar.pinned !== undefined ? !!navbar.pinned : false
    };
    if (!data.title && data.title !== false) {
        data.title = websiteTitle(project.config);
    }
    data.title = data.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");
        }
        data.left = new Array();
        for(let i1 = 0; i1 < navbar.left.length; i1++){
            data.left.push(await navigationItem(project, navbar.left[i1], 0, sidebarMenus));
        }
    }
    if (navbar.right) {
        if (!Array.isArray(navbar.right)) {
            throw new Error("navbar 'right' must be an array of nav items");
        }
        data.right = new Array();
        for(let i1 = 0; i1 < navbar.right.length; i1++){
            data.right.push(await navigationItem(project, navbar.right[i1], 0, sidebarMenus));
        }
    }
    if (navbar.tools) {
        await resolveSidebarTools(project, navbar.tools);
        data.tools = navbar.tools;
    }
    return data;
}
function resolveIcon(navItem) {
    navItem.icon = navItem.icon ? !navItem.icon.startsWith("bi-") ? `bi-${navItem.icon}` : navItem.icon : navItem.icon;
}
function resolveSidebarRef(navItem) {
    const ref = navItem.href || navItem.text;
    if (ref) {
        const id = sidebarTargetId(ref);
        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 = join2(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 i1 = 0; i1 < navItem.menu.length; i1++){
            navItem.menu[i1] = await navigationItem(project, navItem.menu[i1], 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 number = menuIds.get(id) || 0;
    menuIds.set(id, number + 1);
    return `nav-menu-${id}${number ? "-" + number : ""}`;
}
async function resolveItem(project, href, item, number = false) {
    if (!isExternalPath1(href)) {
        const resolved = await resolveInputTarget(project, pathWithForwardSlashes(href));
        if (resolved) {
            const inputItem = {
                ...item,
                href: resolved.outputHref,
                text: item.text || resolved.title || basename2(resolved.outputHref),
                draft: resolved.draft
            };
            const projType = projectType(project.config?.project?.[kProjectType]);
            if (projType.navItemText) {
                const navItemFormatted = await projType.navItemText(project, href, inputItem.text, number);
                inputItem.text = navItemFormatted.html;
                inputItem.plainText = navItemFormatted.text;
            }
            return inputItem;
        } else if (looksLikeShortCode(href)) {
            return item;
        } else {
            return {
                ...item,
                href: !href.startsWith("/") ? "/" + href : href
            };
        }
    } else {
        if (!item.text && !item.icon) {
            item.text = item.href;
        }
        return item;
    }
}
function looksLikeShortCode(href) {
    return href.startsWith("{{<") && href.endsWith(">}}");
}
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 && !isExternalPath1(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 isExternalPath1(path) {
    return /^\w+:/.test(path);
}
function resolveNavReferences(collection) {
    if (!collection) {
        return collection;
    }
    __VIRTUAL_FILE144(collection, (value, index, collection)=>{
        const assign = (value)=>{
            if (typeof index === "number") {
                collection[index] = value;
            } else if (typeof index === "string") {
                collection[index] = value;
            }
        };
        if (Array.isArray(value)) {
            assign(resolveNavReferences(value));
        } else if (typeof value === "object") {
            assign(resolveNavReferences(value));
        } else if (typeof value === "string") {
            const navRef = resolveNavReference(value);
            if (navRef) {
                const navItem = collection;
                navItem["href"] = navRef.href;
                navItem["text"] = navRef.text;
            }
        }
    });
    return collection;
}
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;
    }
}
async function aboutHtmlDependencies(source, project, format, _temp, _extras) {
    const aboutPage = await readAbout(source, project, format);
    if (aboutPage) {
        format.pandoc[kToc] = false;
        format.metadata[kTocLocation] = "right";
        format.metadata[kAnchorSections] = false;
    }
    const scssPath = join2(projectTypeResourcePath("website"), `about/about.scss`);
    const aboutLayer = sassLayerFile(scssPath);
    const sassBundles = [
        {
            dependency: kBootstrapDependencyName,
            key: scssPath,
            quarto: {
                name: `quarto-about.css`,
                ...aboutLayer
            }
        }
    ];
    const markdownHandlers = [];
    if (aboutPage) {
        markdownHandlers.push(aboutLinksMarkdownHandler(aboutPage));
    }
    const pipeline = createMarkdownPipeline(`quarto-about-pipeline`, markdownHandlers);
    return {
        [kMarkdownAfterBody]: markdownHandlers.length > 0 ? [
            pipeline.markdownAfterBody()
        ] : [
            ""
        ],
        [kHtmlPostprocessors]: aboutPage ? aboutPagePostProcessor(aboutPage, pipeline) : undefined,
        [kSassBundles]: sassBundles
    };
}
async function readAbout(source, project, format) {
    const about = format.metadata[kAbout];
    if (about) {
        const resolveOptions = (aboutTemplate, aboutObj, aboutPage)=>{
            const knownFieldList = [
                "image",
                kImageAlt2,
                kImageTitle,
                "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 [template, custom] = templatePath(about, source);
            const aboutPage = {
                template,
                custom,
                options: {}
            };
            if (format.metadata[kImage]) {
                aboutPage.image = format.metadata[kImage];
            }
            if (format.metadata[kImageAlt2]) {
                aboutPage[kImageAlt2] = format.metadata[kImageAlt2];
            }
            if (format.metadata[kImageTitle]) {
                aboutPage[kImageTitle] = format.metadata[kImageTitle];
            }
            resolveOptions(about, {}, aboutPage);
            return aboutPage;
        } else if (typeof about === "object") {
            const aboutObj = about;
            const aboutTemplate = aboutObj[kType1] || aboutObj[kTemplate1];
            const [template, custom] = templatePath(aboutTemplate, source);
            const id = aboutObj.id;
            const aboutPage = {
                id,
                template,
                custom,
                options: {}
            };
            const aboutImage = aboutObj[kImage];
            if (aboutImage) {
                aboutPage.image = aboutImage;
            } else {
                if (format.metadata[kImage]) {
                    aboutPage.image = format.metadata[kImage];
                }
            }
            const aboutImageAlt = aboutObj[kImageAlt2];
            if (aboutImageAlt) {
                aboutPage[kImageAlt2] = aboutImageAlt;
            } else {
                if (format.metadata[kImageAlt2]) {
                    aboutPage[kImageAlt2] = format.metadata[kImageAlt2];
                }
            }
            const aboutImageTitle = aboutObj[kImageTitle];
            if (aboutImageTitle) {
                aboutPage[kImageTitle] = aboutImageTitle;
            } else {
                if (format.metadata[kImageTitle]) {
                    aboutPage[kImageTitle] = format.metadata[kImageTitle];
                }
            }
            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(template, source) {
    if (kTemplates.includes(template)) {
        return [
            join2(projectTypeResourcePath("website"), `about/${template}.ejs.html`),
            false
        ];
    } else {
        return [
            join2(dirname2(source), template),
            true
        ];
    }
}
const aboutPagePostProcessor = (aboutPage, pipeline)=>{
    return (doc)=>{
        const titleEl = doc.getElementById("title-block-header");
        titleEl?.remove();
        const title = titleEl?.outerHTML || "";
        let aboutEl = aboutPage.id ? doc.getElementById(aboutPage.id) : undefined;
        if (!aboutEl) {
            aboutEl = doc.querySelector("main.content");
        }
        const body = aboutEl?.outerHTML || "";
        const ejsData = {
            title,
            body,
            image: aboutPage.image,
            [kImageAlt2]: aboutPage[kImageAlt2],
            [kImageTitle]: aboutPage[kImageTitle],
            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;
        aboutEl?.after(...aboutPageContainer.childNodes);
        aboutEl?.remove();
        const result1 = {
            resources: [],
            supporting: []
        };
        if (aboutPage.image) {
            result1.resources.push(aboutPage.image);
        }
        pipeline.processRenderedMarkdown(doc);
        return Promise.resolve(result1);
    };
};
const aboutLinksMarkdownHandler = (aboutPage)=>{
    return {
        getUnrendered: ()=>{
            const pipelineMarkdown = {};
            let count = 1;
            aboutPage.links?.forEach((link)=>{
                if (typeof link === "string") {
                    pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
                    pipelineMarkdown.inlines[link] = link;
                } else {
                    if (link.text) {
                        pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
                        pipelineMarkdown.inlines[link.text] = link.text;
                    }
                    if (link.href) {
                        const newId = `8B1E46B7-render-about-link-${count}`;
                        pipelineMarkdown.inlines = pipelineMarkdown.inlines || {};
                        pipelineMarkdown.inlines[newId] = mdSafeHref(link.href);
                    }
                }
                count++;
            });
            return pipelineMarkdown;
        },
        processRendered: (rendered, doc)=>{
            const aboutLinkNodes = doc.querySelectorAll(".about-links .about-link");
            for (const aboutLinkNode of aboutLinkNodes){
                const aboutLinkEl = aboutLinkNode;
                const aboutLinkTextNode = aboutLinkEl.querySelector(".about-link-text");
                if (aboutLinkTextNode) {
                    const aboutLinkTextEl = aboutLinkTextNode;
                    const aboutLinkRendered = rendered[aboutLinkTextEl.innerText.trim()];
                    if (aboutLinkRendered) {
                        aboutLinkTextEl.innerHTML = aboutLinkRendered.innerHTML;
                    }
                }
                const href = aboutLinkEl.getAttribute("href");
                if (href !== null) {
                    const aboutLinkHref = rendered[href];
                    if (aboutLinkHref) {
                        aboutLinkEl.setAttribute("href", aboutLinkHref.innerText);
                    }
                }
            }
        }
    };
};
class QName {
    _qName;
    _prefix;
    _localPart;
    constructor(qName){
        this._qName = qName;
        const i1 = qName.indexOf(':');
        const q = i1 < 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 Element2 extends QName {
    _attributes = [];
    _parent;
    uri;
    emptyElement = false;
    constructor(name, parent){
        super(name);
        this._parent = parent;
    }
    get parent() {
        return this._parent;
    }
    newAttribute(qName) {
        const attribute = new Attribute(qName);
        this._attributes.push(attribute);
    }
    peekAttribute() {
        const i1 = this._attributes.length - 1;
        if (i1 < 0) {
            return undefined;
        }
        return this._attributes[i1];
    }
    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 Element2(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 isWhitespace2(c) {
    return c === ' ' || c === '\n' || c === '\r' || c === '\t';
}
function isQuote(c) {
    return c === '"' || c === '\'';
}
function resolveEntity(text) {
    let result1 = text;
    [
        {
            reg: /&amp;/g,
            ch: '&'
        },
        {
            reg: /&gt;/g,
            ch: '>'
        },
        {
            reg: /&lt;/g,
            ch: '<'
        },
        {
            reg: /&quot;/g,
            ch: '"'
        },
        {
            reg: /&apos;/g,
            ch: '\''
        }
    ].forEach(({ reg, ch })=>{
        result1 = result1.replace(reg, ch);
    });
    return result1;
}
function handleBeforeDocument(cx, c) {
    if (c === '<') {
        cx.state = 'FOUND_LT';
    } else {
        if (!isWhitespace2(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 (!isWhitespace2(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 (!isWhitespace2(c)) {
                throw new XMLParseError('Invalid character in element name', cx);
            }
            cx.state = 'START_TAG_STUFF';
        }
    }
    return events;
}
function handleStartTagStuff(cx, c) {
    let events = [];
    if (!isWhitespace2(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 (isWhitespace2(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 (!isWhitespace2(c)) {
        throw new XMLParseError('Attribute without value', cx);
    }
    return [];
}
function handleAttributeEqual(cx, c) {
    if (!isWhitespace2(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 (isWhitespace2(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 (isWhitespace2(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 (!isWhitespace2(c)) {
        throw new XMLParseError('Invalid characters in end-tag', cx);
    }
    return events;
}
function handleAfterDocument(cx, c) {
    if (!isWhitespace2(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(state, handler) {
        this._handlers[state] = 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 [name, ...args] = event;
        const list = this._listeners[name] || [];
        for (const listener of list){
            listener.call(this, ...args);
        }
    }
    run() {
        try {
            while(this.hasNext()){
                const state = this.cx.state;
                const handler = this.handlers[state];
                if (!handler) {
                    throw new Error(`Handler for ${state} 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 filteredOutputFiles = [];
    for (const outputFile of outputFiles){
        if (basename2(outputFile.file) === "index.html") {
            const index = await inputTargetIndexForOutputFile(context, relative2(outputDir, outputFile.file));
            if (index && inputTargetIsEmpty(index)) {
                continue;
            }
        }
        filteredOutputFiles.push(outputFile);
    }
    outputFiles = filteredOutputFiles;
    const robotsTxtPath = join2(context.dir, "robots.txt");
    const srcRobotsTxt = existsSync(robotsTxtPath) ? robotsTxtPath : undefined;
    const destRobotsTxt = join2(outputDir, "robots.txt");
    if (srcRobotsTxt) {
        copyTo(srcRobotsTxt, destRobotsTxt);
    }
    const baseUrlConfig = websiteBaseurl(context.config);
    const sitemapPath = join2(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 inputModified = async (output, project)=>{
            const inputFile = await inputFileForOutputFile(project, output);
            if (inputFile) {
                return fileLastMod(inputFile.file);
            } else {
                return fileLastMod(output);
            }
        };
        const isDraft = async (outputFile)=>{
            const index = await resolveInputTargetForOutputFile(context, relative2(outputDir, outputFile.file));
            return index ? index.draft : undefined;
        };
        const urlsetEntry = async (outputFile)=>{
            const file = outputFile.file;
            return {
                loc: fileLoc(file),
                lastmod: await inputModified(file, context),
                draft: await isDraft(outputFile)
            };
        };
        const draftMode = projectDraftMode(context);
        if (!incremental || !existsSync(sitemapPath)) {
            const urlset = [];
            for (const file of outputFiles){
                urlset.push(await urlsetEntry(file));
            }
            writeSitemap(sitemapPath, urlset, draftMode);
        } else {
            const urlSet = await readSitemap(sitemapPath);
            for (const outputFile of outputFiles){
                const file = outputFile.file;
                const loc = fileLoc(file);
                const url = urlSet.find((url)=>url.loc === loc);
                if (url) {
                    url.lastmod = await inputModified(file, context);
                    url.draft = await isDraft(outputFile);
                } else {
                    urlSet.push(await urlsetEntry(outputFile));
                }
            }
            writeSitemap(sitemapPath, urlSet, draftMode);
        }
        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, draftMode) {
    const nonDraftUrls = urlset.filter((url)=>!url.draft || isDraftVisible(draftMode));
    const escapedUrls = nonDraftUrls.map((url)=>{
        url.loc = escape1(url.loc);
        return url;
    });
    const sitemap = renderEjs(resourcePath(join2("projects", "website", "templates", "sitemap.ejs.xml")), {
        urlset: escapedUrls
    });
    Deno.writeTextFileSync(sitemapPath, sitemap);
}
const kAliases = "aliases";
async function updateAliases(context, outputFiles, incremental) {
    const redirectMap = {};
    const allOutputFiles = [];
    const outputDir = projectOutputDir(context);
    for (const outputFile of outputFiles){
        const aliases = outputFile.format.metadata[kAliases];
        if (aliases && Array.isArray(aliases)) {
            addRedirectsToMap(aliases, outputFile.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 format = Object.values(inputIndexEntry.formats)[0];
                const outputTarget = await resolveInputTarget(context, relativePath, false);
                if (outputTarget) {
                    const projOutputDir = projectOutputDir(context);
                    allOutputFiles.push(join2(projOutputDir, outputTarget.outputHref));
                    if (incremental) {
                        const aliases = format.metadata[kAliases];
                        if (aliases && Array.isArray(aliases)) {
                            addRedirectsToMap(aliases, join2(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)) {
            warn(`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("/") ? join2(outputDir, anchor.href.slice(1)) : join2(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(path, redirects) {
    const redirectTemplate = resourcePath("projects/website/templates/redirect-map.ejs");
    const redirectHtml = renderEjs(redirectTemplate, {
        redirects
    });
    Deno.writeTextFileSync(path, redirectHtml);
}
function imageSize(path) {
    if (path !== undefined) {
        if (path.endsWith(".png")) {
            if (existsSync(path)) {
                const imageData = Deno.readFileSync(path);
                try {
                    const png = new PngImage(imageData);
                    return {
                        height: png.height,
                        width: png.width
                    };
                } catch (error) {
                    throw new Error(`Error reading file ${path}\n${error.message}`);
                }
            }
        }
    }
}
function imageContentType(path) {
    const ext = extname2(path);
    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 kCard = "card";
function metadataHtmlDependencies(source, project, format, extras) {
    const pipeline = metaMarkdownPipeline(format, extras);
    return {
        [kHtmlPostprocessors]: metadataHtmlPostProcessor(source, project, format, extras, pipeline),
        [kMarkdownAfterBody]: pipeline.markdownAfterBody()
    };
}
function metadataHtmlPostProcessor(source, project, format, extras, pipeline) {
    return (doc)=>{
        const pageMeta = pageMetadata(format, extras);
        const openGraphMetadataProvider = {
            key: kOpenGraph,
            prefix: "og",
            metadata: {
                ...pageMeta,
                ...opengraphMetadata(format)
            },
            filter: (key)=>{
                if ([
                    kImageHeight,
                    kImageWidth,
                    kImageAlt
                ].includes(key)) {
                    return key.replace("-", ":");
                }
                if (key === kSiteName) {
                    return "site_name";
                }
                return key;
            },
            resolveValue: (key, value)=>{
                if ([
                    kDescription
                ].includes(key)) {
                    return truncateText(value.trim(), 200, "punctuation");
                }
                return value;
            }
        };
        const twitterMetadataProvider = {
            key: kTwitterCard,
            prefix: "twitter",
            metadata: {
                ...pageMeta,
                ...twitterMetadata(format)
            },
            filter: (key)=>{
                if (key === kCardStyle) {
                    return kCard;
                }
                if ([
                    kImageAlt
                ].includes(key)) {
                    return key.replace("-", ":");
                }
                return key;
            },
            resolveValue: (key, value)=>{
                if ([
                    kDescription
                ].includes(key)) {
                    return truncateText(value.trim(), 200, "punctuation");
                }
                return value;
            },
            resolveDefaults: (finalMetadata)=>{
                if (finalMetadata[kCardStyle] === undefined) {
                    finalMetadata[kCardStyle] = finalMetadata[kImage] ? "summary_large_image" : "summary";
                }
            }
        };
        const resources = [];
        [
            openGraphMetadataProvider,
            twitterMetadataProvider
        ].forEach((provider)=>{
            const metadata = provider.metadata;
            const siteMeta = format.metadata[kWebsite];
            if (!format.metadata[provider.key] && (!siteMeta || !siteMeta[provider.key])) {
                return;
            }
            if (metadata[kTitle] === undefined) {
                return;
            }
            if (metadata[kImage] === undefined && format.metadata[kImage] !== false) {
                metadata[kImage] = findPreviewImg(doc, true) || websiteImage(project.config);
            }
            if (metadata[kDescription] === undefined) {
                metadata[kDescription] = findDescription(doc);
            }
            const imagePath = resolveImageMetadata(source, project, format, metadata);
            if (imagePath) {
                if (imagePath.startsWith("/")) {
                    const absPath = join2(project.dir, imagePath);
                    resources.push(relative2(dirname2(source), absPath));
                } else {
                    resources.push(imagePath);
                }
            }
            if (provider.resolveDefaults) {
                provider.resolveDefaults(metadata);
            }
            Object.keys(metadata).forEach((key)=>{
                if (metadata[key] !== undefined) {
                    const data = metadata[key];
                    const value = provider.resolveValue ? provider.resolveValue(key, data) : data;
                    if (provider.filter) {
                        key = provider.filter(key);
                    }
                    writeMetaTag(`${provider.prefix}:${key}`, value, doc);
                }
            });
        });
        pipeline.processRenderedMarkdown(doc);
        return Promise.resolve({
            resources,
            supporting: []
        });
    };
}
function opengraphMetadata(format) {
    const metadata = {};
    const openGraph = mergedSiteAndDocumentData(kOpenGraph, format);
    const siteMeta = format.metadata[kWebsite];
    if (siteMeta && siteMeta[kTitle]) {
        metadata[kSiteName] = siteMeta[kTitle];
    }
    if (openGraph && typeof openGraph === "object") {
        [
            kTitle,
            kDescription,
            kImage,
            kImageAlt,
            kImageHeight,
            kImageWidth,
            kLocale,
            kSiteName
        ].forEach((key)=>{
            if (openGraph[key] !== undefined) {
                metadata[key] = openGraph[key];
            }
        });
    }
    return metadata;
}
function twitterMetadata(format) {
    const metadata = {};
    const twitterData = mergedSiteAndDocumentData(kTwitterCard, format);
    if (twitterData && typeof twitterData === "object") {
        [
            kTitle,
            kDescription,
            kImage,
            kImageAlt,
            kCreator,
            kTwitterSite,
            kCardStyle
        ].forEach((key)=>{
            if (twitterData[key] !== undefined) {
                metadata[key] = twitterData[key];
            }
        });
    }
    return metadata;
}
function pageMetadata(format, extras) {
    const pageTitle = computePageTitle(format, extras);
    const pageDescription = format.metadata[kDescription];
    const pageImage = format.metadata[kImage] ? format.metadata[kImage] : undefined;
    return {
        [kTitle]: pageTitle,
        [kDescription]: pageDescription || format.metadata[kAbstract] || format.metadata[kSubtitle],
        [kImage]: pageImage
    };
}
function resolveImageMetadata(source, project, format, metadata) {
    const siteMeta = format.metadata[kWebsite];
    if (metadata[kImage] && siteMeta && siteMeta[kSiteUrl] !== undefined) {
        const inputRelImg = metadata[kImage];
        const imgMeta = imageMetadata(metadata[kImage], siteMeta[kSiteUrl], source, project);
        metadata[kImage] = imgMeta.href;
        metadata[kImageHeight] = imgMeta.height;
        metadata[kImageWidth] = imgMeta.width;
        const altText = format.metadata[kImageAlt];
        if (altText && !metadata[kImageAlt]) {
            metadata[kImageAlt] = altText;
        }
        return inputRelImg;
    }
}
function mergedSiteAndDocumentData(key, format) {
    const siteData = format.metadata[kWebsite];
    const siteMetadata = siteData && siteData[key] !== undefined ? siteData[key] : false;
    const docMetadata = format.metadata[key] !== undefined ? format.metadata[key] : false;
    if (typeof siteMetadata === "object" && format.metadata[kImage]) {
        const siteMeta = siteMetadata;
        siteMeta[kImage] = format.metadata[kImage];
    }
    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(image, baseUrl, source, context) {
    if (isAbsoluteRef(image)) {
        return {
            href: image
        };
    } else if (image.startsWith("/")) {
        const imagePath = join2(context.dir, image.slice(1));
        const size = imageSize(imagePath);
        return {
            path: image,
            href: `${baseUrl}${image}`,
            height: size?.height,
            width: size?.width
        };
    } else {
        const sourceRelative = relative2(context.dir, source);
        const imageProjectRelative = join2(dirname2(sourceRelative), image);
        const imagePath = join2(context.dir, imageProjectRelative);
        const size = imageSize(imagePath);
        return {
            path: imageProjectRelative,
            href: joinUrl(baseUrl, imageProjectRelative),
            height: size?.height,
            width: size?.width
        };
    }
}
const kMetaTitleId = "quarto-metatitle";
const kTwitterTitle = "quarto-twittercardtitle";
const kTwitterDesc = "quarto-twittercarddesc";
const kOgTitle = "quarto-ogcardtitle";
const kOgDesc = "quarto-ogcardddesc";
const kMetaSideNameId = "quarto-metasitename";
function metaMarkdownPipeline(format, extras) {
    const resolvedTitle = computePageTitle(format);
    const titleMetaHandler = {
        getUnrendered () {
            const inlines = {};
            if (resolvedTitle !== undefined) {
                inlines[kMetaTitleId] = resolvedTitle;
            }
            const twitterMeta = twitterMetadata(format);
            inlines[kTwitterTitle] = twitterMeta.title || resolvedTitle || "";
            const ogMeta = opengraphMetadata(format);
            inlines[kOgTitle] = ogMeta.title || resolvedTitle || "";
            return {
                inlines
            };
        },
        processRendered (rendered, doc) {
            const renderedEl = rendered[kMetaTitleId];
            if (renderedEl) {
                const el = doc.querySelector(`head title`);
                if (el && el.innerText === resolvedTitle) {
                    if (format.pandoc[kNumberSections] === false) {
                        const numberEl = renderedEl.querySelector("span.chapter-number");
                        if (numberEl) {
                            numberEl.remove();
                        }
                        const collapsed = renderedEl.innerText.replaceAll(/\s+/g, " ");
                        el.innerHTML = collapsed;
                    } else {
                        el.innerHTML = renderedEl.innerText;
                    }
                }
            }
            [
                {
                    key: kOgTitle,
                    sel: 'meta[property="og:title"]'
                },
                {
                    key: kTwitterTitle,
                    sel: 'meta[name="twitter:title"]'
                }
            ].forEach((obj)=>{
                const renderedObjEl = rendered[obj.key];
                if (renderedObjEl) {
                    const metaEl = doc.querySelector(obj.sel);
                    if (metaEl) {
                        metaEl.setAttribute("content", renderedObjEl.innerText);
                    }
                }
            });
        }
    };
    const siteTitleMetaHandler = {
        getUnrendered () {
            const siteMeta = format.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);
                }
            }
        }
    };
    const descriptionMetaHandler = {
        getUnrendered () {
            const inlines = {};
            const pageMeta = pageMetadata(format, extras);
            const siteMeta = format.metadata[kWebsite];
            const pageDesc = pageMeta.description;
            const siteDesc = siteMeta.description;
            const description = pageDesc || siteDesc;
            const twitterMeta = twitterMetadata(format);
            inlines[kTwitterDesc] = twitterMeta.description || description || "";
            const ogMeta = opengraphMetadata(format);
            inlines[kOgDesc] = ogMeta.description || description || "";
            return {
                inlines
            };
        },
        processRendered (rendered, doc) {
            const metaVals = [
                {
                    sel: 'meta[property="og:description"]',
                    key: kOgDesc
                },
                {
                    sel: 'meta[name="twitter:description"]',
                    key: kTwitterDesc
                }
            ];
            metaVals.forEach((metaVal)=>{
                const renderedEl = rendered[metaVal.key];
                if (renderedEl) {
                    const metaEl = doc.querySelector(metaVal.sel);
                    if (metaEl) {
                        metaEl.setAttribute("content", renderedEl.innerText);
                    }
                }
            });
        }
    };
    return createMarkdownPipeline("quarto-meta-markdown", [
        titleMetaHandler,
        siteTitleMetaHandler,
        descriptionMetaHandler
    ]);
}
function htmlResourceResolverPostprocessor(source, project, pathResolver) {
    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 resolver = pathResolver ? pathResolver : (href, projectOffset)=>{
            return pathWithForwardSlashes(join2(projectOffset, href));
        };
        const refs = resolveResourceRefs(doc, offset, forceRoot, pathResolver || resolver);
        return Promise.resolve({
            resources: refs,
            supporting: []
        });
    };
}
function resolveResourceRefs(doc, projectOffset, forceRoot, resolvePath) {
    const refs = [];
    Object.keys(kHtmlResourceTags).forEach((tag)=>{
        for (const attrib of kHtmlResourceTags[tag]){
            refs.push(...resolveTag(doc, projectOffset, tag, attrib, forceRoot, resolvePath).map((ref)=>ref.replace(/\/$/, "/index.html")));
        }
    });
    const styles = doc.querySelectorAll("style");
    for(let i1 = 0; i1 < styles.length; i1++){
        const style = styles[i1];
        if (style.innerHTML) {
            style.innerHTML = fixupCssReferences1(style.innerHTML, projectOffset + "/", (ref)=>{
                ref = resolvePath(ref, projectOffset);
                refs.push(ref);
                return ref;
            });
        }
    }
    return refs;
}
function resolveTag(doc, projectOffset, tag, attrib, forceRoot, resolvePath) {
    const refs = [];
    processFileResourceRefs(doc, tag, 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.startsWith("//")) {
            href = resolvePath(projectOffset + href, projectOffset);
            tag.setAttribute(attrib, href);
        } else {
            href = resolvePath(href, projectOffset);
            tag.setAttribute(attrib, href);
        }
        refs.push(href);
    });
    return refs;
}
function localizedString(format, key, options) {
    if (options) {
        let formattedStr = format.language[key];
        for(let i1 = 0; i1 < options.length; i1++){
            const option = options[i1];
            formattedStr = formattedStr.replace(`{${i1}}`, option);
        }
        return formattedStr;
    } else {
        return format.language[key];
    }
}
const kDefaultListingType = ListingType.Default;
const kDefaultContentsGlobToken = "B3049D40";
const kDefaultContentsGlob = [
    kDefaultContentsGlobToken
];
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 = (format)=>{
    return {
        [kFieldImage]: " ",
        [kFieldDate]: format.language[kListingPageFieldDate] || "",
        [kFieldTitle]: format.language[kListingPageFieldTitle] || "",
        [kFieldDescription]: format.language[kListingPageFieldDescription] || "",
        [kFieldAuthor]: format.language[kListingPageFieldAuthor] || "",
        [kFieldFileName]: format.language[kListingPageFieldFileName] || "",
        [kFieldDateModified]: format.language[kListingPageFieldFileModified] || "",
        [kFieldFileModified]: format.language[kListingPageFieldFileModified] || "",
        [kFieldSubtitle]: format.language[kListingPageFieldSubtitle] || "",
        [kFieldReadingTime]: format.language[kListingPageFieldReadingTime] || "",
        [kFieldWordCount]: format.language[kListingPageFieldWordCount] || "",
        [kFieldCategories]: format.language[kListingPageFieldCategories] || ""
    };
};
const kDefaultFieldTypes = {
    [kFieldDate]: "date",
    [kFieldFileModified]: "date",
    [kFieldDateModified]: "date",
    [kFieldReadingTime]: "minutes",
    [kFieldWordCount]: "number"
};
const kDefaultFieldLinks = [
    kFieldTitle,
    kFieldFileName
];
const kDefaultFieldSort = [
    kFieldTitle,
    kFieldDate,
    kFieldAuthor,
    kFieldFileName,
    kFieldFileModified
];
const kDefaultFieldRequired = [];
async function readListings(source, project, format) {
    const listingItems = [];
    const listings = readDehydratedListings(source, format);
    const firstListingValue = (key, defaultValue)=>{
        for (const listing of listings){
            const value = listing[key];
            if (value !== undefined) {
                return value;
            }
        }
        return defaultValue;
    };
    const categories = 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(categories);
    const sharedOptions = {
        [kFieldCategories]: !!categories,
        [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 listing of listings){
        const { items, sources } = await readContents(source, project, listing);
        const listingHydrated = hydrateListing(format, listing, items, sources, sharedOptions);
        const sortedAndFiltered = (listing, items)=>{
            if (listing.sort && listing.sort.length > 0) {
                return __VIRTUAL_FILE217(items, listing.sort.map((l1)=>{
                    return (item)=>{
                        const value = item[l1.field];
                        if (value === undefined && l1.field === kFieldOrder) {
                            if (l1.direction === "asc") {
                                return Number.MAX_SAFE_INTEGER;
                            } else {
                                return 0;
                            }
                        } else {
                            return value;
                        }
                    };
                }), listing.sort.map((l1)=>l1.direction));
            } else {
                return items;
            }
        };
        const orderedItems = sortedAndFiltered(listingHydrated, items);
        listingItems.push({
            listing: listingHydrated,
            items: orderedItems
        });
    }
    return {
        listingDescriptors: listingItems,
        options: sharedOptions
    };
}
function completeListingItems(context, outputFiles, _incremental) {
    debug(`[listing] Completing listing items for ${outputFiles.length} files`);
    const options = {
        remove: {
            links: true,
            images: true
        }
    };
    debug(`[listing] Creating content reader`);
    const contentReader = renderedContentReader(context, options);
    outputFiles.forEach((outputFile)=>{
        debug(`[listing] Completing listing items ${outputFile.input}`);
        if (outputFile.format.metadata[kListing] && isHtmlOutput(outputFile.format.pandoc, true)) {
            let fileContents = Deno.readTextFileSync(outputFile.file);
            const listings = readDehydratedListings(outputFile.file, outputFile.format);
            const listingDefaultImage = {};
            listings.forEach((listing)=>{
                debug(`[listing] Processing listing ${listing.id}`);
                listingDefaultImage[`${listing.id}`] = listing[kImagePlaceholder] !== undefined ? listing[kImagePlaceholder] : undefined;
            });
            const regex = descriptionPlaceholderRegex;
            regex.lastIndex = 0;
            let match = regex.exec(fileContents);
            while(match){
                debug(`[listing] Processing description match`);
                const maxDescLength = parseInt(match[1]);
                const relativePath = match[2];
                const absolutePath = join2(projectOutputDir(context), relativePath);
                const placeholder = descriptionPlaceholder(relativePath, maxDescLength);
                if (existsSync(absolutePath)) {
                    const options = maxDescLength > 0 ? {
                        "max-length": maxDescLength
                    } : {};
                    const contents = contentReader(absolutePath, options);
                    fileContents = fileContents.replace(placeholder, contents.firstPara || "");
                } else {
                    fileContents = fileContents.replace(placeholder, "");
                    warn(`Unable to read listing item description from ${relativePath}`);
                }
                match = regex.exec(fileContents);
            }
            regex.lastIndex = 0;
            const imgRegex = imagePlaceholderRegex;
            imgRegex.lastIndex = 0;
            let imgMatch = imgRegex.exec(fileContents);
            while(imgMatch){
                debug(`[listing] Processing image match`);
                const progressive = imgMatch[1] === "true";
                const imgHeight = imgMatch[2];
                const listingId = imgMatch[3];
                const docRelativePath = imgMatch[4];
                const docAbsPath = join2(projectOutputDir(context), docRelativePath);
                const imgPlaceholder = imagePlaceholder(listingId, docRelativePath, progressive, imgHeight);
                debug(`[listing] ${docAbsPath}`);
                debug(`[listing] ${imgPlaceholder}`);
                if (existsSync(docAbsPath)) {
                    debug(`[listing] exists: ${docAbsPath}`);
                    const contents = contentReader(docAbsPath, {
                        remove: {
                            links: true
                        }
                    });
                    if (contents.previewImage) {
                        debug(`[listing] previewImage: ${docAbsPath}`);
                        const resolveUrl = (path)=>{
                            if (isHttpUrl(path)) {
                                return path;
                            } else {
                                const imgAbsPath = isAbsolute2(path) ? path : join2(dirname2(docAbsPath), path);
                                const imgRelPath = relative2(dirname2(outputFile.file), imgAbsPath);
                                return imgRelPath;
                            }
                        };
                        const imgHtml = imageSrc({
                            ...contents.previewImage,
                            src: resolveUrl(contents.previewImage.src)
                        }, progressive, imgHeight);
                        debug(`[listing] replacing: ${docAbsPath}`);
                        fileContents = fileContents.replace(imgPlaceholder, imgHtml);
                    } else if (listingDefaultImage[listingId] !== undefined) {
                        debug(`[listing] using default image for ${docAbsPath}`);
                        debug(`[listing] from listing id ${listingId}`);
                        debug(`[listing] image used is ${listingDefaultImage[listingId]}`);
                        const imagePreview = {
                            src: listingDefaultImage[listingId]
                        };
                        fileContents = fileContents.replace(imgPlaceholder, imageSrc(imagePreview, progressive, imgHeight));
                    } else {
                        debug(`[listing] using empty div: ${docAbsPath}`);
                        fileContents = fileContents.replace(imgPlaceholder, emptyDiv(imgHeight));
                    }
                } else {
                    debug(`[listing] does not exist: ${docAbsPath}`);
                    fileContents = fileContents.replace(imgPlaceholder, emptyDiv(imgHeight));
                    warn(`Unable to read listing preview image from ${docRelativePath}`);
                }
                imgMatch = imgRegex.exec(fileContents);
            }
            imgRegex.lastIndex = 0;
            Deno.writeTextFileSync(outputFile.file, fileContents);
        }
    });
}
function emptyDiv(height) {
    return `<div class="listing-item-img-placeholder card-img-top" ${height ? `style="height: ${height};"` : ""}>&nbsp;</div>`;
}
function descriptionPlaceholder(file, maxLength) {
    return file ? `<!-- desc(5A0113B34292)[max=${maxLength}]:${file} -->` : "";
}
function imagePlaceholder(id, file, progressive, height) {
    return file ? `<!-- img(9CEB782EFEE6)[progressive=${progressive ? "true" : "false"}, height=${height ? height : ""}]:${id}:${file} -->` : "";
}
function isPlaceHolder(text) {
    return text.match(descriptionPlaceholderRegex);
}
const descriptionPlaceholderRegex = /<!-- desc\(5A0113B34292\)\[max\=(.*)\]:(.*) -->/;
const imagePlaceholderRegex = /<!-- img\(9CEB782EFEE6\)\[progressive\=(.*), height\=(.*)\]:(.*):(.*) -->/;
function hydrateListing(format, listing, items, 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 itemFields = fieldsForItems(items);
    const suggestFields = (type, itemFields)=>{
        if (sources.size === 1 && sources.has(ListingItemSource.rawfile)) {
            return [
                kFieldFileName,
                kFieldFileModified
            ];
        } else if (!sources.has(ListingItemSource.document) && !sources.has(ListingItemSource.metadataDocument)) {
            const undisplayable = [
                "path"
            ];
            return itemFields.filter((field)=>{
                return !undisplayable.includes(field);
            });
        } else {
            return defaultFields(type, itemFields);
        }
    };
    const suggestedFields = suggestFields(listing.type, itemFields);
    const fields = suggestedFields.filter((field)=>{
        if (field === kFieldImage) {
            return true;
        }
        return itemFields.includes(field);
    });
    const finalFields = fields.length > 0 ? fields : itemFields;
    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]: {},
        [kFieldLinks]: defaultLinks,
        [kFieldSort]: defaultSort,
        [kFieldFilter]: hydratedFields,
        [kFieldRequired]: kDefaultFieldRequired,
        [kPageSize]: defaultPageSize(),
        [kFilterUi]: listing[kFilterUi] !== undefined ? listing[kFilterUi] : listing.type === ListingType.Table,
        [kSortUi]: listing[kSortUi] !== undefined ? listing[kSortUi] : listing.type === ListingType.Table,
        ...listing
    });
    const sort = hydratedFields.includes(kFieldTitle) ? [
        {
            field: kFieldOrder,
            direction: "asc"
        },
        {
            field: kFieldTitle,
            direction: "asc"
        }
    ] : undefined;
    if (sort && !listingHydrated.sort && (sources.has(ListingItemSource.document) || sources.has(ListingItemSource.metadataDocument))) {
        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] || kDefaultMaxDescLength;
    } 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] = {
        ...kDefaultFieldTypes,
        ...listing[kFieldTypes]
    };
    listingHydrated[kFieldDisplayNames] = {
        ...defaultFieldDisplayNames(format),
        ...listing[kFieldDisplayNames]
    };
    return listingHydrated;
}
async function readContents(source, project, listing) {
    debug(`[listing] Reading listing '${listing.id}' from ${source}`);
    debug(`[listing] Contents: ${listing.contents.map((lst)=>{
        return typeof lst === "string" ? lst : "<yaml>";
    }).join(",")}`);
    const listingItems = [];
    const listingItemSources = new Set();
    const inputsWithoutSource = project.files.input.filter((file)=>file !== source);
    const filterListingFiles = (globOrPaths)=>{
        const hasDefaultGlob = globOrPaths.some((glob)=>{
            return glob === kDefaultContentsGlobToken;
        });
        const resolvedGlobs = globOrPaths.map((glob)=>{
            if (glob === kDefaultContentsGlobToken) {
                return "*";
            } else {
                return glob;
            }
        });
        const expandedGlobs = resolvedGlobs.map((resolved)=>{
            return expandGlob(source, project, resolved);
        });
        const hasInputs = expandedGlobs.some((expanded)=>{
            return !!expanded.inputs;
        });
        const finalGlobs = expandedGlobs.map((expanded)=>{
            return expanded.glob;
        });
        const outDir = project.config?.project["output-dir"];
        if (outDir) {
            finalGlobs.push(`!/${outDir}/**`);
        }
        if (hasInputs || hasDefaultGlob) {
            const filtered = filterPaths(dirname2(source), inputsWithoutSource, finalGlobs);
            for (const glob of finalGlobs){
                if (safeExistsSync(glob) && Deno.statSync(glob).isFile) {
                    filtered.include.push(isAbsolute2(glob) ? glob : join2(Deno.cwd(), glob));
                }
            }
            return filtered;
        } else {
            return resolvePathGlobs(dirname2(source), finalGlobs, [
                "_*",
                ".*",
                "**/_*",
                "**/.*",
                source
            ]);
        }
    };
    const contentGlobs = listing.contents.filter((content)=>{
        return typeof content === "string";
    });
    const contentMetadatas = listing.contents.filter((content)=>{
        return typeof content !== "string";
    });
    if (contentGlobs.length > 0) {
        const files = filterListingFiles(contentGlobs);
        debug(`[listing] matches ${files.include.length} files:`);
        const readFiles = files.include.filter((file)=>{
            return !files.exclude.includes(file);
        });
        if (readFiles.length === 0) {
            const projRelativePath = relative2(project.dir, source);
            warn(`The listing in '${projRelativePath}' using the following contents:\n- ${contentGlobs.join("\n- ")}\ndoesn't match any files or folders.`);
        }
        for (const file of readFiles){
            if (isYamlPath(file)) {
                debug(`[listing] Reading YAML file ${file}`);
                const yaml = readYaml(file);
                if (Array.isArray(yaml)) {
                    const items = yaml;
                    for (const yamlItem of items){
                        if (typeof yamlItem === "object") {
                            const result1 = await listItemFromMeta(yamlItem, project, listing, dirname2(file));
                            if (result1) {
                                const { item, source } = result1;
                                validateItem(listing, item, (field)=>{
                                    return `An item from the file '${file}' is missing the required field '${field}'.`;
                                });
                                listingItemSources.add(source);
                                listingItems.push(item);
                            }
                        } 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 result1 = await listItemFromMeta(yaml, project, listing, dirname2(file));
                    if (result1) {
                        const { item, source } = result1;
                        validateItem(listing, item, (field)=>{
                            return `The item defined in file '${file}' is missing the required field '${field}'.`;
                        });
                        listingItemSources.add(source);
                        listingItems.push(item);
                    }
                } else {
                    throw new Error(`Unexpected listing contents in file ${file}. The file should contain only one more listing items.`);
                }
            } else {
                const isFile = Deno.statSync(file).isFile;
                if (isFile) {
                    debug(`[listing] Reading file ${file}`);
                    const item = await listItemFromFile(file, project, listing);
                    if (item) {
                        validateItem(listing, item, (field)=>{
                            return `The file ${file} is missing the required field '${field}'.`;
                        });
                        if (item.item.title === undefined) {
                            debug(`[listing] Missing Title in File ${file}`);
                        }
                        listingItemSources.add(item.source);
                        listingItems.push(item.item);
                    }
                }
            }
        }
    }
    if (contentMetadatas.length > 0) {
        for (const content of contentMetadatas){
            const result1 = await listItemFromMeta(content, project, listing, dirname2(source));
            if (result1) {
                const { item, source: itemSource } = result1;
                validateItem(listing, item, (field)=>{
                    return `An item in the listing '${listing.id}' is missing the required field '${field}'.`;
                });
                listingItemSources.add(itemSource);
                listingItems.push(item);
            }
        }
    }
    const matchesField = (item, field, value)=>{
        const simpleValueMatches = (itemValue, listingValue)=>{
            if (typeof itemValue === "string" && typeof listingValue === "string") {
                const regex = globToRegExp2(listingValue);
                return itemValue.match(regex);
            } else {
                return itemValue === listingValue;
            }
        };
        const valueMatches = (item, field, value)=>{
            if (Array.isArray(item[field])) {
                const fieldValues = item[field];
                return fieldValues.some((fieldVal)=>{
                    return simpleValueMatches(fieldVal, value);
                });
            } else {
                return simpleValueMatches(item[field], value);
            }
        };
        if (Array.isArray(value)) {
            return value.some((val)=>{
                return valueMatches(item, field, val);
            });
        } else {
            return valueMatches(item, field, value);
        }
    };
    let filtered = listingItems;
    const includes = listing[kInclude1];
    if (includes) {
        debug(`[listing] applying filter to include only items matching ${includes}`);
        const fields = Object.keys(includes);
        filtered = filtered.filter((item)=>{
            return fields.every((field)=>{
                return matchesField(item, field, includes[field]);
            });
        });
        debug(`[listing] afer including, ${filtered.length} item match listing`);
    }
    const excludes = listing[kExclude];
    if (excludes) {
        debug(`[listing] applying filter to exclude items matching ${includes}`);
        const fields = Object.keys(excludes);
        filtered = filtered.filter((item)=>{
            return !fields.some((field)=>{
                return matchesField(item, field, excludes[field]);
            });
        });
        debug(`[listing] afer excluding, ${filtered.length} item match listing`);
    }
    return {
        items: filtered,
        sources: listingItemSources
    };
}
function validateItem(listing, 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(listing);
    if (validationFields) {
        validationFields.forEach((requiredField)=>{
            if (item[requiredField] === undefined) {
                throw new Error(message(requiredField));
            }
        });
    }
}
async function listItemFromMeta(meta, project, listing, baseDir) {
    let listingItem = __VIRTUAL_FILE107(meta);
    let source = ListingItemSource.metadata;
    if (typeof meta.path === "string") {
        const base = basename2(meta.path);
        const extension = extname2(base).toLocaleLowerCase();
        meta[kFieldFileName] = base;
        meta[kFieldFileModified] = fileModifiedDate(meta.path);
        const markdownExtensions = [
            ".qmd",
            ".md",
            ".rmd"
        ];
        if (markdownExtensions.indexOf(extension) !== -1) {
            const inputPath = isAbsolute2(meta.path) ? meta.path : join2(baseDir, meta.path);
            const fileListing = await listItemFromFile(inputPath, project, listing);
            if (fileListing === undefined) {
                return undefined;
            } else {
                listingItem = {
                    ...fileListing.item || {},
                    ...listingItem
                };
                if (fileListing.item.path) {
                    listingItem.path = fileListing.item.path;
                }
                source = ListingItemSource.metadataDocument;
            }
        }
    }
    if (meta.author) {
        if (!Array.isArray(meta.author)) {
            meta.author = [
                meta.author
            ];
        }
    }
    if (meta.date) {
        if (meta.path !== undefined) {
            listingItem.date = parsePandocDate(resolveDate(meta.path, meta.date));
        } else {
            listingItem.date = parsePandocDate(meta.date);
        }
    }
    return {
        item: listingItem,
        source
    };
}
async function listItemFromFile(input, project, listing) {
    if (!isAbsolute2(input)) {
        throw new InternalError(`input path ${input} must be absolute.`);
    }
    const projectRelativePath = relative2(project.dir, input);
    const target = await inputTargetIndex(project, pathWithForwardSlashes(projectRelativePath));
    const inputTarget = await resolveInputTarget(project, pathWithForwardSlashes(projectRelativePath), false);
    const docRawMetadata = target?.markdown.yaml;
    const directoryMetadata = await directoryMetadataForInputFile(project, dirname2(input));
    const documentMeta = mergeConfigs(project.config, directoryMetadata, docRawMetadata);
    const projectDraft = isProjectDraft(projectRelativePath, project);
    const draftMode = projectDraftMode(project);
    if (!isDraftVisible(draftMode) && (documentMeta?.draft || projectDraft)) {
        return undefined;
    } else {
        if (!docRawMetadata && (extname2(input) === ".qmd" || extname2(input) === ".ipynb")) {
            warn(`File ${input} in the listing '${listing.id}' contains no metadata.`);
        }
        const maxDescLength = listing[kMaxDescLength] || 175;
        const filename = basename2(projectRelativePath);
        const filemodified = fileModifiedDate(input);
        const description = documentMeta?.description || documentMeta?.abstract || descriptionPlaceholder(inputTarget?.outputHref, maxDescLength);
        const imageRaw = documentMeta?.image;
        const image = imageRaw !== undefined && typeof imageRaw === "string" ? pathWithForwardSlashes(listingItemHref(imageRaw, dirname2(projectRelativePath))) : undefined;
        const imageAlt = documentMeta?.[kImageAlt1];
        const imageLazyLoading = documentMeta?.[kImageLazyLoading];
        const date = documentMeta?.date ? parsePandocDate(resolveDate(input, documentMeta?.date)) : undefined;
        const datemodified = documentMeta?.date ? parsePandocDate(resolveDate(input, documentMeta?.[kDateModified])) : undefined;
        const authors = parseAuthor(documentMeta?.author);
        let structuredAuthors;
        if (authors) {
            structuredAuthors = cslNames(authors?.filter((auth)=>auth !== undefined).map((auth)=>auth?.name));
        }
        const author = structuredAuthors ? __VIRTUAL_FILE181(structuredAuthors.map((auth)=>auth.literal || `${auth.given} ${auth.family}`)) : [];
        const readingContext = target?.markdown ? estimateReadingTimeMinutes(target.markdown.markdown) : undefined;
        let readingtime = undefined;
        let wordcount = undefined;
        if (readingContext) {
            readingtime = readingContext.readingTime;
            wordcount = readingContext.wordCount;
        }
        const categories = documentMeta?.categories ? Array.isArray(documentMeta?.categories) ? documentMeta?.categories : [
            documentMeta?.categories
        ] : undefined;
        const item = {
            ...documentMeta,
            path: `/${projectRelativePath}`,
            outputHref: inputTarget?.outputHref,
            [kFieldTitle]: target?.title,
            [kFieldDate]: date,
            [kFieldDateModified]: datemodified,
            [kFieldAuthor]: author,
            [kFieldCategories]: categories,
            [kFieldImage]: image,
            [kFieldImageAlt]: imageAlt,
            [kFieldImageLazyLoading]: imageLazyLoading,
            [kFieldDescription]: description,
            [kFieldFileName]: filename,
            [kFieldFileModified]: filemodified,
            [kFieldReadingTime]: readingtime,
            [kFieldWordCount]: wordcount
        };
        return {
            item,
            source: target !== undefined ? ListingItemSource.document : ListingItemSource.rawfile
        };
    }
}
function imageSrc(image, progressive, height) {
    return `<p class="card-img-top"><img ${progressive ? "data-src" : "src"}="${image.src}" ${image.alt ? `alt="${image.alt}" ` : ""}${height ? `style="height: ${height};" ` : ""}${image.title ? `title="${image.title}"` : ""} class="thumbnail-image card-img"/></p>`;
}
function readDehydratedListings(source, format) {
    const listingConfig = format.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 listingType = meta.type || kDefaultListingType;
    const baseListing = listingForType(listingType);
    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 = join2(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 (typeof rawValue === "boolean") {
        if (rawValue) {
            return undefined;
        } else {
            return [];
        }
    } else {
        if (Array.isArray(rawValue)) {
            return rawValue.map(parseValue).filter((val)=>val !== undefined);
        } else {
            const sort = parseValue(rawValue);
            if (sort) {
                return [
                    sort
                ];
            }
        }
    }
}
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 (safeExistsSync(input)) {
        const fileInfo = Deno.statSync(input);
        return fileInfo.mtime !== null ? fileInfo.mtime : undefined;
    } else {
        return undefined;
    }
}
function listingItemHref(path, projectRelativePath) {
    if (isAbsoluteRef(path) || path.startsWith("/")) {
        return path;
    } else {
        return join2("/", projectRelativePath, path);
    }
}
function expandGlob(source, project, globOrPath) {
    const getPath = ()=>{
        if (globOrPath.startsWith("/")) {
            return join2(project.dir, globOrPath);
        } else {
            const sourcePath = dirname2(source);
            return join2(sourcePath, globOrPath);
        }
    };
    const globOrPathAsPath = getPath();
    try {
        if (Deno.statSync(globOrPathAsPath).isDirectory) {
            return {
                glob: join2(globOrPath, "**"),
                inputs: true
            };
        } else {
            return {
                glob: globOrPath,
                inputs: false
            };
        }
    } catch  {
        return {
            glob: globOrPath,
            inputs: false
        };
    }
}
const kDateFormat1 = "date-format";
const kQuartoListingClass = "quarto-listing";
function templateMarkdownHandler(template, listing, items, format, cache, attributes) {
    const reshapedItems = items.map((item)=>{
        resolveItemForTemplate(item, listing);
        const record = {
            ...item
        };
        if (item.author) {
            if (Array.isArray(item.author)) {
                record.author = item.author.join(", ");
            } else {
                record.author = item.author;
            }
        }
        const dateFormat = listing[kDateFormat1] || format.metadata[kDateFormat1];
        const fieldLabelLangKeys = {
            "word-count": kListingPageWords
        };
        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" ? parsePandocDate(dateRaw) : dateRaw;
                    if (date) {
                        record[field] = dateFormat ? formatDate(date, dateFormat) : includeTime ? formatDate(date, "short", "medium") : formatDate(date, "medium");
                    }
                }
            } else if (fieldTypes[field] === "minutes" && item[field]) {
                const val = item[field];
                record[field] = localizedString(format, kListingPageMinutesCompact, [
                    Math.floor(val).toString()
                ]);
            } else if (fieldTypes[field] === "number" && item[field] !== undefined && fieldLabelLangKeys[field] !== undefined) {
                const val = item[field];
                record[field] = localizedString(format, fieldLabelLangKeys[field], [
                    Math.floor(val).toLocaleString()
                ]);
            }
        }
        if (item.description !== undefined && !isPlaceHolder(item.description)) {
            const maxDescLength = listing[kMaxDescLength] || -1;
            if (maxDescLength > 0) {
                record.description = truncateText(item.description, maxDescLength, "space");
            }
        }
        return record;
    });
    const reshapedListing = reshapeListing(listing, format);
    const tempateItems = listing[kMaxItems] ? reshapedItems.slice(0, listing[kMaxItems]) : reshapedItems;
    const paramsForType = (type)=>{
        const ejsParams = {
            items: tempateItems
        };
        ``;
        if (type !== ListingType.Custom) {
            ejsParams.listing = reshapedListing;
        } else {
            ejsParams["metadataAttrs"] = reshapedListing.utilities.metadataAttrs;
            ejsParams["templateParams"] = reshapedListing["template-params"];
        }
        return ejsParams;
    };
    const filterRendered = renderEjs(resourcePath("projects/website/listing/_filter.ejs.md"), {
        items: tempateItems,
        listing: reshapedListing
    });
    let templateRendered = renderEjs(template, paramsForType(listing.type), false, cache);
    templateRendered = templateRendered.replace(/(\r\n|\r|\n){2,}/g, "$1$1");
    const paginationRendered = renderEjs(resourcePath("projects/website/listing/_pagination.ejs.md"), {
        items: tempateItems,
        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");
                listingEl = doc.createElement("div");
                if (content) {
                    content.appendChild(listingEl);
                } else {
                    const customContent = doc.querySelector("#quarto-content");
                    if (customContent) {
                        customContent.appendChild(listingEl);
                    } else {
                        doc.body.appendChild(listingEl);
                    }
                }
            }
            if (!listingEl?.classList.contains(kQuartoListingClass)) {
                listingEl?.classList.add(kQuartoListingClass);
            }
            listingEl?.classList.add(`quarto-listing-container-${listing.type}`);
            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)];
            if (renderedEl) {
                listingEl.innerHTML = renderedEl.innerHTML;
            }
        }
    };
}
function resolveItemForTemplate(item, listing) {
    const addSortable = (item, field, value)=>{
        item.sortableValues = item.sortableValues || {};
        item.sortableValues[field] = value;
    };
    for (const field of Object.keys(listing[kFieldTypes])){
        const type = listing[kFieldTypes][field];
        if (item[field] !== undefined) {
            if (type === "date") {
                addSortable(item, field, item[field].valueOf().toString());
            } else if (type === "number") {
                addSortable(item, field, item[field].toString());
            } else if (type === "minutes") {
                addSortable(item, field, item[field].toString());
            }
        }
    }
    for (const field of listing[kFieldLinks]){
        const val = item[field];
        if (val !== undefined) {
            addSortable(item, field, val);
        }
    }
}
function reshapeListing(listing, format) {
    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} - ${format.language[kListingPageOrderByDateAsc]}`
                });
                fieldSortData.push({
                    listingSort: {
                        field: sortAttrValue(field),
                        direction: kSortDesc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field} - ${format.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} (${format.language[kListingPageOrderByNumberAsc]})`
                });
                fieldSortData.push({
                    listingSort: {
                        field: sortAttrValue(field),
                        direction: kSortDesc
                    },
                    description: `${reshaped[kFieldDisplayNames][field] || field} (${format.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, clz)=>{
        const fieldLinks = reshaped[kFieldLinks];
        const value = val || item[field] || "&nbsp;";
        const path = item.path;
        if (path && value !== undefined && fieldLinks.includes(field)) {
            return `<a href="${path}" class="${field}${clz ? ` ${clz}` : ""}">${value}</a>`;
        } else {
            if (clz) {
                return `<span class="${clz}">${value}</span>`;
            } else {
                return value;
            }
        }
    };
    utilities.sortTarget = (field)=>{
        if (useSortTarget(listing, field)) {
            return sortAttrValue(field);
        } else {
            return `listing-${field}`;
        }
    };
    let itemNumber = 0;
    utilities.itemNumber = ()=>{
        return ++itemNumber;
    };
    utilities.img = (itemNumber, src, classes, alt, lazy)=>{
        const pageSize = listing[kPageSize];
        const classAttr = classes ? `class="${classes}"` : "";
        const styleAttr = listing[kImageHeight1] ? `style="height: ${listing[kImageHeight1]};"` : "";
        const altAttr = alt ? `alt="${encodeAttributeValue(alt)}"` : "";
        const srcAttr = itemNumber > pageSize ? "data-src" : "src";
        const lazyAttr = lazy === false ? "" : "loading='lazy' ";
        return `<img ${lazyAttr}${srcAttr}="${src}" ${classAttr} ${styleAttr} ${altAttr}>`;
    };
    utilities.imgPlaceholder = (listingId, itemNumber, itemPath)=>{
        const pageSize = listing[kPageSize];
        return imagePlaceholder(listingId, itemPath, itemNumber > pageSize, listing[kImageHeight1]);
    };
    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 = (str)=>{
        const localizedStrings = format.language;
        return localizedStrings[str];
    };
    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, itemCount) {
    const pageSize = listing[kPageSize] || 50;
    const columns = listing[kFields] || [];
    const pageOptions = itemCount > 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 field of listing[kFieldSort]){
        if (useSortTarget(listing, field)) {
            resolvedColumns.push(`{ data: ['${sortAttrValue(field)}'] }`);
        }
    }
    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']();
    }
  });

  window.addEventListener('hashchange',() => {
    if (window['quarto-listing-loaded']) {
      window['quarto-listing-loaded']();
    }
  })
  `;
    return jsScript;
}
function categorySidebar(doc, listingDescriptors, format, options) {
    const categoryStyle = options[kCategoryStyle];
    const headingEl = doc.createElement("h5");
    headingEl.innerText = localizedString(format, 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 defaultFormat = (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" ? defaultFormat : categoryStyle === "category-cloud" ? cloudFormat : unnumberedFormat;
    if (categoryStyle === "category-default") {
        const allCategory = localizedString(format, 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;
}
async function createFeed(doc, source, project, descriptors, options, format) {
    const siteUrl = websiteBaseurl(project.config);
    if (!siteUrl) {
        warn("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) {
        warn("Unable to create a feed as the required `site > title` property is missing from this project.");
        return;
    }
    const feedDescription = options.description || format.metadata[kDescription1] || websiteDescription(project.config) || "";
    const projectRelInput = relative2(project.dir, source);
    const inputTarget = await resolveInputTarget(project, projectRelInput, false);
    const [dir, stem] = dirAndStem(source);
    const finalRelPath = relative2(project.dir, join2(dir, `${stem}.xml`));
    const link = absoluteUrl(siteUrl, inputTarget?.outputHref);
    const feedLink = absoluteUrl(siteUrl, finalRelPath);
    const items = [];
    for (const descriptor of descriptors){
        items.push(...descriptor.items);
    }
    const filteredItems = prepareItems(items, options);
    const mostRecent = mostRecentItem(filteredItems);
    const xmlSheetHref = options[kXmlStyleSheet] ? absoluteUrl(siteUrl, options[kXmlStyleSheet]) : undefined;
    const feed = {
        title: feedTitle,
        description: feedDescription,
        link,
        feedLink,
        generator: `quarto-${quartoConfig.version()}`,
        lastBuildDate: mostRecent && mostRecent.date ? new Date(mostRecent.date).toUTCString() : new Date().toUTCString(),
        language: options.language,
        [kXmlStyleSheet]: xmlSheetHref
    };
    const image = options.image || format.metadata[kImage] || websiteImage(project.config);
    if (image) {
        feed.image = {
            title: feedTitle,
            link: link,
            url: absoluteUrl(siteUrl, image)
        };
        const size = imageSize(image);
        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);
    const feedFiles = [];
    if (options[kXmlStyleSheet]) {
        feedFiles.push(options[kXmlStyleSheet]);
    }
    const rendered = await renderFeed(siteUrl, feed, filteredItems, project, stagedPath);
    if (rendered) {
        feedFiles.push(stagedPath);
        addLinkTagToDocument(doc, feed, `${stem}.xml`);
    }
    options[kFieldCategories] = options[kFieldCategories] || [];
    const feedCategories = Array.isArray(options[kFieldCategories]) ? options[kFieldCategories] : [
        options[kFieldCategories]
    ];
    const categoriesToRender = feedCategories?.map((category)=>{
        const finalRelPath = relative2(project.dir, join2(dir, `${stem}-${category.toLocaleLowerCase()}.xml`));
        return {
            category,
            file: feedPath(dir, `${stem}-${category.toLocaleLowerCase()}`, options.type),
            finalFile: finalRelPath,
            feedLink: absoluteUrl(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;
}
const kFeedOptions = {
    remove: {
        anchors: true
    },
    transform: {
        [kUrlsToAbsolute]: true,
        [kInlineCodeStyle]: true,
        math: true
    }
};
function completeStagedFeeds(context, outputFiles, _incremental) {
    const siteUrl = websiteBaseurl(context.config);
    if (siteUrl !== undefined) {
        outputFiles.forEach((outputFile)=>{
            if (outputFile.format.metadata[kListing] && isHtmlOutput(outputFile.format.pandoc, true)) {
                const [dir, stem] = dirAndStem(outputFile.file);
                const files = resolvePathGlobs(dir, [
                    `${stem}${kStagedFileGlob}`
                ], []);
                const contentReader = renderedContentReader(context, kFeedOptions, siteUrl);
                for (const feedFile of files.include){
                    const [feedDir, feedStem] = dirAndStem(feedFile);
                    try {
                        const type = feedFile.endsWith(kFullStagedExt) ? "full" : feedFile.endsWith(kPartialStagedExt) ? "partial" : "metadata";
                        let feedContents = Deno.readTextFileSync(feedFile);
                        const tagWithReplacements = [
                            {
                                tag: "title",
                                regex: kTitleRegex,
                                replaceValue: (rendered)=>{
                                    if (rendered.title) {
                                        return __VIRTUAL_FILE172(rendered.title);
                                    } else {
                                        return "";
                                    }
                                }
                            },
                            {
                                tag: "description",
                                regex: kDescRegex,
                                replaceValue: (rendered)=>{
                                    if (type === "full") {
                                        return `<![CDATA[ ${rendered.fullContents} ]]>`;
                                    } else if (type === "partial") {
                                        return `<![CDATA[ ${rendered.description || rendered.firstPara} ]]>`;
                                    } else {
                                        return `<![CDATA[ ${rendered.description || ""} ]]>`;
                                    }
                                }
                            }
                        ];
                        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("/") ? join2(projectOutputDir(context), relativePath) : join2(feedDir, relativePath);
                                const contents = contentReader(absolutePath);
                                if (contents) {
                                    const targetStr = placholderForReplace(tag, relativePath);
                                    feedContents = feedContents.replace(targetStr, ()=>{
                                        return `<${tag}>${tagWithReplacement.replaceValue(contents)}</${tag}>`;
                                    });
                                }
                                match = regex.exec(feedContents);
                            }
                            regex.lastIndex = 0;
                        });
                        Deno.writeTextFileSync(join2(feedDir, `${feedStem}.${kFinalExt}`), feedContents);
                    } catch (error) {
                        const errorMessage = error.message;
                        warnOnce(`Unable to generate feed '${feedStem}.xml'\n${errorMessage}`);
                    } finally{
                        try {
                            Deno.removeSync(feedFile);
                        } catch  {}
                    }
                }
            }
        });
    }
}
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, feedPath) {
    const feedItems = [];
    for (const item of items){
        const inputTarget = await resolveInputTarget(project, item.path, false);
        const title = inputTarget?.outputHref ? placeholder(inputTarget?.outputHref) : item.title || "";
        const link = absoluteUrl(siteUrl, inputTarget?.outputHref || "");
        const description = inputTarget?.outputHref ? placeholder(inputTarget?.outputHref) : item.description || "";
        const pubDate = item.date ? new Date(item.date) : new Date();
        const feedItem = {
            title,
            link,
            description,
            guid: link,
            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 image = item[kFieldImage];
            feedItem.image = absoluteUrl(siteUrl, image);
            const imagePath = join2(project.dir, image);
            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, feedPath);
    return true;
}
async function generateFeed(feed, feedItems, path) {
    const feedFile = await Deno.open(path, {
        write: true,
        create: true
    });
    try {
        const textEncoder = new TextEncoder();
        const preamble = renderEjs(resourcePath("projects/website/listing/feed/preamble.ejs.md"), {
            feed,
            escape: __VIRTUAL_FILE172
        });
        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,
                escape: __VIRTUAL_FILE172
            });
            await Deno.write(feedFile.rid, textEncoder.encode(item));
        }
        const postamble = renderEjs(resourcePath("projects/website/listing/feed/postamble.ejs.md"), {
            feed,
            escape: __VIRTUAL_FILE172
        });
        await Deno.write(feedFile.rid, textEncoder.encode(postamble));
    } finally{
        Deno.close(feedFile.rid);
    }
}
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 itemCount = options[kItems] || 20;
    if (sortedItems.length > itemCount) {
        return sortedItems.slice(0, itemCount);
    } 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 mostRecentItem = sortedItems.length > 0 ? sortedItems[0] : undefined;
    return mostRecentItem;
}
function addLinkTagToDocument(doc, feed, path) {
    const linkEl = doc.createElement("link");
    linkEl.setAttribute("rel", "alternate");
    linkEl.setAttribute("type", "application/rss+xml");
    linkEl.setAttribute("title", feed.title);
    linkEl.setAttribute("href", path);
    linkEl.setAttribute("data-external", "1");
    doc.head.appendChild(linkEl);
}
const kFullStagedExt = "feed-full-staged";
const kPartialStagedExt = "feed-partial-staged";
const kMetadataStagedExt = "feed-metadata-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, type) {
    const ext = type === "full" ? kFullStagedExt : type === "partial" ? kPartialStagedExt : kMetadataStagedExt;
    const file = `${stem}.${ext}`;
    return join2(dir, file);
}
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)
        ];
    }
};
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 data = JSON.parse(mapRaw);
        return data;
    } 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 join2(projectScratchPath(dir, kListingDir), kListingMapFile);
}
async function createListingIndex(source, project, descriptors) {
    const projectRelInput = relative2(project.dir, source);
    const inputTarget = await resolveInputTarget(project, projectRelInput, false);
    if (inputTarget) {
        const listingHref = "/" + inputTarget.outputHref;
        const items = [];
        for (const descriptor of descriptors){
            items.push(...descriptor.items);
        }
        const filteredItems = __VIRTUAL_FILE210(items, (item)=>{
            return item.path;
        });
        if (filteredItems) {
            const itemHrefs = [];
            for (const item of filteredItems){
                if (item.path) {
                    const itemTarget = await resolveInputTarget(project, item.path, false);
                    if (itemTarget) {
                        const itemHref = itemTarget.outputHref;
                        itemHrefs.push(itemHref);
                    }
                }
            }
            const listingJson = {
                listing: listingHref,
                items: itemHrefs
            };
            const listingIndexPath = listingIndex(source);
            Deno.writeTextFileSync(listingIndexPath, JSON.stringify(listingJson, undefined, 2));
            return listingIndexPath;
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function updateGlobalListingIndex(context, outputFiles, incremental) {
    const outputDir = projectOutputDir(context);
    const listingJsonPath = join2(outputDir, "listings.json");
    const listingJson = existsSync(listingJsonPath) ? Deno.readTextFileSync(listingJsonPath) : undefined;
    const listingPaths = new Array();
    let generateListings = true;
    if (incremental && listingJson) {
        try {
            const existingListingJson = JSON.parse(listingJson);
            listingPaths.push(...existingListingJson);
        } catch  {
            generateListings = false;
            warn("Unable to read listing index - it may be corrupt. Please re-render the entire site to create a valid listing index.");
        }
    }
    if (generateListings) {
        for (const outputFile of outputFiles){
            const hasListing = !!outputFile.format.metadata[kListing];
            if (hasListing && isHtmlOutput(outputFile.format.pandoc, true)) {
                const indexPath = listingIndex(outputFile.file);
                if (existsSync(indexPath)) {
                    const json = Deno.readTextFileSync(indexPath);
                    const indexJson = JSON.parse(json);
                    const existingIndex = listingPaths.findIndex((paths)=>paths.listing === indexJson.listing);
                    if (existingIndex > -1) {
                        listingPaths[existingIndex] = indexJson;
                    } else {
                        listingPaths.push(indexJson);
                    }
                    Deno.removeSync(indexPath);
                }
            }
        }
        if (listingPaths.length > 0) {
            Deno.writeTextFileSync(listingJsonPath, JSON.stringify(listingPaths, undefined, 2));
        }
    }
}
function listingIndex(input) {
    const [dir, stem] = dirAndStem(input);
    return join2(dir, `${stem}-listing.json`);
}
function listingSupplementalFiles(project, inputs, incremental) {
    if (incremental) {
        const listingProjData = listingProjectData(project);
        const listingMap = listingProjData.listingMap || {};
        const listingFiles = Object.keys(listingMap);
        const inputPaths = inputs.map((inp)=>inp.path);
        const matching = listingFiles.filter((listingFile)=>{
            const listingDir = join2(project.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 join2(project.dir, listingRelativePath);
            });
            const files = __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 = join2(outputDir, file);
                        await touch(filePath);
                    }
                }
            };
            return {
                files: files.map((file)=>{
                    return {
                        path: file,
                        formats: [
                            "html",
                            "html4",
                            "html5"
                        ]
                    };
                }),
                onRenderComplete
            };
        } else {
            return {
                files: []
            };
        }
    } else {
        clearListingProjectData(project);
        return {
            files: []
        };
    }
}
async function listingHtmlDependencies(source, project, format, temp, _extras) {
    const { listingDescriptors, options } = await readListings(source, project, format);
    const pageHasListings = listingDescriptors.length > 0;
    if (pageHasListings) {
        cacheListingProjectData(project, relative2(project.dir, source), listingDescriptors);
    }
    const markdownHandlers = [];
    listingDescriptors.forEach((listingDescriptor)=>{
        markdownHandlers.push(markdownHandler(format, listingDescriptor.listing, listingDescriptor.items));
    });
    markdownHandlers.push({
        getUnrendered: ()=>{
            return {
                inlines: {
                    "quarto-enable-math-inline": "$e = mC^2$"
                }
            };
        },
        processRendered: (_rendered, _doc)=>{}
    });
    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((path)=>{
                return {
                    name: basename2(path),
                    path
                };
            })
        }
    ];
    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, format);
        const supporting = [];
        if (options[kFeed]) {
            const listingOptions = {
                type: "full",
                ...options[kFeed]
            };
            const feedAbsPaths = await createFeed(doc, source, project, listingDescriptors, listingOptions, format);
            if (feedAbsPaths) {
                feedAbsPaths.forEach((feedAbsPath)=>{
                    supporting.push(feedAbsPath);
                });
            }
        }
        const listingIndexPath = await createListingIndex(source, project, listingDescriptors);
        if (listingIndexPath) {
            supporting.push(listingIndexPath);
        }
        return Promise.resolve({
            resources: [],
            supporting
        });
    };
    return {
        [kSassBundles]: formatHasBootstrap(format) ? [
            listingSassBundle()
        ] : [],
        [kDependencies]: pageHasListings ? listingDependencies : [],
        [kMarkdownAfterBody]: pageHasListings ? pipeline.markdownAfterBody() : undefined,
        [kIncludeInHeader]: pageHasListings ? [
            scriptFileForScripts(generateScriptListJsScript(), temp)
        ] : [],
        [kHtmlPostprocessors]: pageHasListings ? listingPostProcessor : undefined
    };
}
function completeListingGeneration(context, outputFiles, incremental) {
    debug(`[listing] Completing staged feeds in ${context.dir}`);
    completeStagedFeeds(context, outputFiles, incremental);
    debug(`[listing] Completing listing items in ${context.dir}`);
    completeListingItems(context, outputFiles, incremental);
    debug(`[listing] Writing global listing index for ${context.dir}`);
    updateGlobalListingIndex(context, outputFiles, incremental);
}
function markdownHandler(format, listing, items) {
    switch(listing.type){
        case ListingType.Table:
            {
                return templateMarkdownHandler(resourcePath("projects/website/listing/listing-table.ejs.md"), listing, items, format, true);
            }
        case ListingType.Grid:
            {
                return templateMarkdownHandler(resourcePath("projects/website/listing/listing-grid.ejs.md"), listing, items, format, 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, format, false);
            }
        case ListingType.Default:
        default:
            {
                return templateMarkdownHandler(resourcePath("projects/website/listing/listing-default.ejs.md"), listing, items, format, true);
            }
    }
}
function listingPostProcess(doc, listingDescriptors, options, format) {
    debug(`[listing] Post processing ${listingDescriptors.length} listings`);
    const categories = options[kFieldCategories];
    if (categories) {
        const { headingEl, categoriesEl } = categorySidebar(doc, listingDescriptors, format, options);
        const rightSidebar = doc.getElementById(kMarginSidebarId);
        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 kMarginSidebarId = "quarto-margin-sidebar";
function scriptFileForScripts(scripts, temp) {
    const scriptFile = temp.createFile({
        suffix: "-listing.html"
    });
    const contents = `<script>\n${scripts.join("\n")}</script>`;
    Deno.writeTextFileSync(scriptFile, contents);
    return scriptFile;
}
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 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;
}
var GiscusThemeDefault;
(function(GiscusThemeDefault) {
    GiscusThemeDefault["light"] = "light";
    GiscusThemeDefault["dark"] = "dark";
})(GiscusThemeDefault || (GiscusThemeDefault = {}));
const buildGiscusThemeKeys = (darkModeDefault, theme)=>{
    if (typeof theme === "string") {
        if (theme.length > 0) {
            return {
                baseTheme: theme,
                altTheme: theme
            };
        } else {
            theme = {
                light: GiscusThemeDefault.light,
                dark: GiscusThemeDefault.dark
            };
        }
    }
    const themeRecord = theme;
    const result1 = {
        baseTheme: themeRecord.light ?? GiscusThemeDefault.light,
        altTheme: themeRecord.dark ?? GiscusThemeDefault.dark
    };
    if (darkModeDefault) {
        [result1.baseTheme, result1.altTheme] = [
            result1.altTheme,
            result1.baseTheme
        ];
    }
    return result1;
};
const kGiscusDir = "giscus";
async function resolveFormatForGiscus(project, format) {
    const comments = format.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 path = join2(giscusPath, fileName.replace("/", "."));
                try {
                    const giscusJson = Deno.readTextFileSync(path);
                    giscusMeta = JSON.parse(giscusJson);
                } catch  {
                    removeIfExists(path);
                    giscusMeta = await getGithubDiscussionsMetadata(repo);
                    const jsonStr = JSON.stringify(giscusMeta, undefined, 2);
                    Deno.writeTextFileSync(path, jsonStr);
                }
                if (giscusOptions[kGiscusRepoId] === undefined) {
                    giscusOptions[kGiscusRepoId] = giscusMeta.repositoryId;
                }
                if (giscusOptions[kGiscusCategoryId] === undefined) {
                    giscusOptions[kGiscusCategoryId] = getDiscussionCategoryId(giscusOptions[kGiscusCategoryId] || "", giscusMeta);
                }
            }
        }
    }
}
const kDraftStatus = "draft-remove";
const websiteDraftPostProcessor = (doc)=>{
    const documentStatusEl = doc.querySelector("meta[name='quarto:status']");
    if (documentStatusEl !== null) {
        const status = documentStatusEl.getAttribute("content");
        if (status === kDraftStatus && doc.documentElement) {
            doc.documentElement.innerHTML = "";
        }
    }
    return Promise.resolve({
        resources: [],
        supporting: []
    });
};
const kSiteTemplateDefault = "default";
const kSiteTemplateBlog = "blog";
const websiteProjectType = {
    type: kWebsite,
    typeAliases: [
        "site"
    ],
    templates: [
        kSiteTemplateDefault,
        kSiteTemplateBlog
    ],
    create: (title, template)=>{
        const resourceDir = resourcePath(join2("projects", "website"));
        return websiteTemplate(resourceDir, title, template);
    },
    libDir: "site_libs",
    outputDir: "_site",
    cleanOutputDir: true,
    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, format, services)=>{
        if (isHtmlFileOutput(format.pandoc)) {
            const extras = formatHasBootstrap(format) ? await websiteNavigationExtras(project, source, flags, format, services.temp) : await websiteNoThemeExtras(project, source, flags, format, services.temp);
            extras.pandoc = extras.pandoc || {};
            extras.metadata = extras.metadata || {};
            resolveFormatForGiscus(project, format);
            const title = websiteTitle(project.config);
            if (title) {
                extras.pandoc = {
                    [kTitlePrefix]: title
                };
            }
            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 && !format.metadata[kTitle] && !format.metadata[kPageTitle] && title) {
                extras.metadata[kPageTitle] = title;
            }
            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, projectExtensionPathResolver(project.config?.project[kProjectLibDir] || "", project.dir))
            ]);
            extras.html[kHtmlPostprocessors].unshift(websiteDraftPostProcessor);
            const hasBootstrap = formatHasBootstrap(format);
            const htmlListingDependencies = await listingHtmlDependencies(source, project, format, services.temp, extras);
            if (htmlListingDependencies) {
                const listingPostProcessor = htmlListingDependencies[kHtmlPostprocessors];
                if (listingPostProcessor) {
                    extras.html[kHtmlPostprocessors]?.unshift(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]);
            }
            if (hasBootstrap) {
                const aboutDependencies = await aboutHtmlDependencies(source, project, format, services.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]);
                    extras.html[kMarkdownAfterBody] = extras.html[kMarkdownAfterBody] || [];
                    extras.html[kMarkdownAfterBody].push(...aboutDependencies[kMarkdownAfterBody]);
                }
            }
            const htmlMetadataDependencies = metadataHtmlDependencies(source, project, format, extras);
            extras.html[kHtmlPostprocessors]?.push(htmlMetadataDependencies[kHtmlPostprocessors]);
            extras.html[kMarkdownAfterBody]?.push(htmlMetadataDependencies[kMarkdownAfterBody]);
            const analyticsDependency = websiteAnalyticsScriptFile(project, services.temp);
            if (analyticsDependency) {
                extras[kIncludeInHeader] = extras[kIncludeInHeader] || [];
                extras[kIncludeInHeader]?.push(analyticsDependency);
            }
            const cookieDep = cookieConsentDependencies(project, format, services.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));
    },
    filterInputTarget: (inputTarget, context)=>{
        const drafts = websiteConfigArray(kDrafts, context.config);
        const isDraft = drafts?.some((val)=>{
            return val === inputTarget.input;
        });
        if (isDraft) {
            inputTarget.draft = true;
        }
        return inputTarget;
    },
    filterParams: async (options)=>{
        if (options.project) {
            const draftMode = projectDraftMode(options.project);
            const drafts = websiteConfigArray(kDrafts, options.project.config);
            if (drafts || draftMode) {
                const draftsAbs = (drafts || []).map((path)=>{
                    return join2(options.project.dir, path);
                });
                return {
                    [kDraftMode]: draftMode,
                    [kDrafts]: draftsAbs
                };
            }
        }
        return undefined;
    }
};
async function websitePostRender(context, incremental, outputFiles) {
    const doc404 = join2(projectOutputDir(context), kProject404File);
    outputFiles = outputFiles.filter((file)=>{
        return file.file !== doc404;
    });
    await updateSitemap(context, outputFiles, incremental);
    await updateSearchIndex(context, outputFiles, incremental);
    completeListingGeneration(context, outputFiles, incremental);
    await updateAliases(context, outputFiles, incremental);
    await ensureIndexPage(context);
}
function websiteOutputFiles(outputFiles) {
    return outputFiles.filter((outputFile)=>{
        return isHtmlFileOutput(outputFile.format.pandoc);
    }).map((outputFile)=>{
        const contents = Deno.readTextFileSync(outputFile.file);
        const doctypeMatch = contents.match(/^<!DOCTYPE.*?>/);
        return {
            ...outputFile,
            doctype: doctypeMatch ? doctypeMatch[0] : undefined
        };
    });
}
function websiteTemplate(resourceDir, title, template) {
    if (template === kSiteTemplateBlog) {
        const today = new Date();
        const secondPostDateStr = formatDate(today, "iso");
        today.setDate(today.getDate() - 3);
        const firstPostDateStr = formatDate(today, "iso");
        return {
            configTemplate: join2(resourceDir, "templates", "blog", "_quarto-blog.ejs.yml"),
            resourceDir,
            scaffold: ()=>[
                    {
                        name: "index",
                        content: "",
                        noEngineContent: true,
                        title,
                        yaml: 'listing:\n  contents: posts\n  sort: "date desc"\n  type: default\n  categories: true\n  sort-ui: false\n  filter-ui: false\npage-layout: full\ntitle-block-banner: 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: [
                            join2(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: [
                            join2(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: [
                            join2(resourceDir, "templates", "blog", "profile.jpg")
                        ],
                        noEngineContent: true
                    }
                ],
            supporting: [
                "styles.css",
                {
                    from: join2("templates", "blog", "_metadata.yml"),
                    to: join2("posts", "_metadata.yml")
                }
            ]
        };
    } else {
        return {
            configTemplate: join2(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
                    },
                    {
                        name: "about",
                        content: "About this site",
                        title: "About"
                    }
                ],
            supporting: [
                "styles.css"
            ]
        };
    }
}
async function bookProjectConfig(project, config, flags) {
    const projectDir = project.dir;
    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[kSiteRepoLinkTarget] = book[kSiteRepoLinkTarget];
        site[kSiteRepoLinkRel] = book[kSiteRepoLinkRel];
        site[kSiteRepoSubdir] = book[kSiteRepoSubdir];
        site[kSiteRepoBranch] = book[kSiteRepoBranch];
        site[kSiteRepoActions] = book[kSiteRepoActions];
        site[kSiteIssueUrl] = book[kSiteIssueUrl];
        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];
        site[kBreadCrumbNavigation] = book[kBreadCrumbNavigation];
        site[kOtherLinks] = book[kOtherLinks];
        site[kCodeLinks] = book[kCodeLinks];
        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] = siteSidebar[kSiteTitle] || book?.[kSiteTitle];
    siteSidebar[kSidebarLogo] = siteSidebar[kSidebarLogo] || book?.[kSidebarLogo];
    siteSidebar[kSidebarLogoHref] = siteSidebar[kSidebarLogoHref] || book?.[kSidebarLogoHref];
    siteSidebar[kSidebarLogoAlt] = siteSidebar[kSidebarLogoAlt] || book?.[kSidebarLogoAlt];
    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
            })
        ]);
    }
    siteSidebar[kSiteSidebarStyle] = siteSidebar[kSiteSidebarStyle] || "floating";
    const tools = [];
    if (site[kSiteRepoUrl]) {
        const repoUrl = siteRepoUrl(site);
        const icon = repoUrlIcon(repoUrl);
        tools.push({
            text: language[kCodeToolsSourceCode] || "Source Code",
            icon,
            href: repoUrl
        });
    }
    tools.push(...downloadTools(projectDir, config, language) || []);
    tools.push(...sharingTools(config, language) || []);
    if (site[kSiteNavbar]) {
        site[kSiteNavbar][kBookTools] = tools;
    } else {
        siteSidebar[kBookTools] = siteSidebar[kBookTools] || [];
        siteSidebar[kBookTools].push(...tools);
    }
    const renderItems = await bookRenderItems(project, language, config);
    book[kBookRender] = renderItems;
    config.project[kProjectRender] = renderItems.filter((target)=>!!target.file).map((target)=>target.file);
    const footerFiles = [];
    const pageFooter = resolvePageFooter(config);
    const addFooterItems = (region)=>{
        if (region) {
            for (const item of region){
                if (typeof item !== "string") {
                    const navItem = item;
                    if (navItem.href && !isAbsoluteRef(navItem.href)) {
                        footerFiles.push(navItem.href);
                    }
                }
            }
        }
    };
    addFooterItems(pageFooter.left);
    addFooterItems(pageFooter.right);
    addFooterItems(pageFooter.center);
    config.project[kProjectRender].push(...footerFiles);
    const ext404 = engineValidExtensions().find((ext)=>existsSync(join2(projectDir, `404${ext}`)));
    if (ext404) {
        config.project[kProjectRender].push(`404${ext404}`);
    }
    return await websiteProjectConfig(project, config);
}
function siteRepoUrl(site) {
    const repoUrl = site[kSiteRepoUrl];
    const branch = site[kSiteRepoBranch] || "main";
    if (site[kSiteRepoSubdir]) {
        const subdir = ensureTrailingSlash(site[kSiteRepoSubdir]);
        return `${ensureTrailingSlash(repoUrl)}tree/${branch}/${subdir}`;
    } else {
        return repoUrl;
    }
}
function bookConfigRenderItems(project) {
    return bookConfig(kBookRender, project);
}
async function bookRenderItems(project, language, config) {
    const projectDir = project.dir;
    if (!config) {
        return [];
    }
    let nextNumber = 1;
    const inputs = [];
    const findInputs = async (type, items, depth = 0)=>{
        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,
                    depth
                });
                await findInputs(type, item.contents, depth + 1);
            } else if (item.href) {
                const itemPath = join2(projectDir, item.href);
                if (safeExistsSync(itemPath)) {
                    const engine = await fileExecutionEngine(itemPath, undefined, project);
                    if (engine) {
                        let number;
                        if (type === kBookItemChapter && await inputIsNumbered(project, item.href)) {
                            number = nextNumber++;
                        }
                        inputs.push({
                            type,
                            file: item.href,
                            number,
                            depth
                        });
                    }
                } else {
                    throwInputNotFound(item.href);
                }
            } else if (item.text && !item.text.trim().match(/^-+$/)) {
                throwInputNotFound(item.text);
            }
        }
    };
    const context = sidebarContext();
    const findChapters = async (key, delimiter)=>{
        nextNumber = 1;
        const bookInputs = bookConfig(key, config);
        if (bookInputs) {
            if (delimiter) {
                inputs.push(delimiter);
            }
            await findInputs(kBookItemChapter, bookChaptersToSidebarItems(bookInputs).map((item)=>normalizeSidebarItem(projectDir, item, context)), key === "chapters" ? 0 : 1);
        }
    };
    await findChapters(kBookChapters);
    const references = bookConfig("references", config);
    if (references) {
        await findInputs(kBookItemChapter, [
            normalizeSidebarItem(projectDir, references, context)
        ]);
    }
    await findChapters(kBookAppendix, {
        type: kBookItemAppendix,
        text: language[kSectionTitleAppendices] + " {.unnumbered}",
        depth: 0
    });
    const missing = inputs.filter((input)=>input.file && !existsSync(join2(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, language) {
    const downloadActions = websiteConfigActions(kBookDownloads, kBook, config);
    const filteredActions = downloadActions.filter((action)=>{
        const format = defaultWriterFormat(action);
        if (format) {
            return format.extensions?.book && !isMultiFileBookFormat(format);
        } else {
            return false;
        }
    });
    const outputStem = bookOutputStem(projectDir, config);
    const projType = projectType(config.project.type);
    const downloads = filteredActions.map((action)=>{
        const format = defaultWriterFormat(action);
        const outputDir = projType.formatOutputDirectory ? projType.formatOutputDirectory(format) || "" : "";
        const downloadItem = kDownloadableItems[action];
        if (downloadItem) {
            return {
                icon: downloadItem.icon,
                text: `${language[kToolsDownload] || "Download"} ${downloadItem.name}`,
                href: pathWithForwardSlashes(join2("/", outputDir, `/${outputStem}.${format.render[kOutputExt]}`))
            };
        } else {
            return {
                text: `Download action}`,
                href: pathWithForwardSlashes(join2("/", outputDir, `${outputStem}.${format.render[kOutputExt]}`))
            };
        }
    });
    if (downloads.length === 0) {
        return undefined;
    } else if (downloads.length === 1) {
        return [
            {
                icon: "download",
                ...downloads[0]
            }
        ];
    } else {
        return [
            {
                icon: "download",
                text: language[kToolsDownload] || "Download",
                menu: downloads
            }
        ];
    }
}
function sharingTools(projectConfig, language) {
    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: language[kToolsShare] || "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(project, input) {
    const partitioned = await partitionedMarkdownForInput(project, input);
    if (partitioned) {
        return isNumberedChapter(partitioned);
    } else {
        return false;
    }
}
function onSingleFileBookPreRender(format, config) {
    const extension = format.extensions?.book;
    if (extension && extension.onSingleFilePreRender) {
        extension.onSingleFilePreRender(format, config);
    }
    return format;
}
function onSingleFileBookPostRender(project, file) {
    const extension = file.format.extensions?.book;
    if (extension && extension.onSingleFilePostRender) {
        extension.onSingleFilePostRender(project, file);
    }
}
async function bookMultiFileHtmlOutputs(context) {
    const renderFiles = bookConfigRenderItems(context.config).filter((item)=>!!item.file);
    if (renderFiles.length === 0) {
        return [];
    }
    const index = await inputTargetIndex(context, renderFiles[0].file);
    if (!index) {
        return [];
    }
    const formatName = Object.keys(index.formats).find((name)=>{
        if (isMultiFileBookFormat(defaultWriterFormat(name))) {
            const format = index.formats[name];
            return isHtmlOutput(format.pandoc, true) && !!format.pandoc[kOutputFile];
        } else {
            return false;
        }
    });
    if (!formatName) {
        return [];
    }
    const outputFiles = [];
    for(let i1 = 0; i1 < renderFiles.length; i1++){
        const file = renderFiles[i1].file;
        const index = await inputTargetIndex(context, file);
        const outputFile = index?.formats[formatName].pandoc[kOutputFile];
        if (outputFile) {
            outputFiles.push(join2(projectOutputDir(context), dirname2(file), outputFile));
        }
    }
    return outputFiles;
}
function withChapterMetadata(format, headingText, headingAttr, chapterInfo, config) {
    format = cloneDeep1(format);
    if (headingText) {
        format.metadata[kTitle] = formatChapterTitle(format, headingText, headingAttr, chapterInfo);
    }
    format.metadata[kCrossref] = format.metadata[kCrossref] || {};
    const crossref = format.metadata[kCrossref];
    if (headingAttr?.id) {
        crossref[kCrossrefChapterId] = headingAttr?.id;
    }
    if (chapterInfo) {
        format.pandoc[kNumberOffset] = [
            chapterInfo.number
        ];
        if (chapterInfo.appendix) {
            crossref[kCrossrefChaptersAppendix] = true;
            crossref[kCrossrefChaptersAlpha] = true;
        }
    } else {
        format.pandoc[kNumberSections] = false;
    }
    format.pandoc[kToc] = format.pandoc[kToc] !== undefined ? format.pandoc[kToc] : isListedChapter(headingAttr);
    delete format.metadata[kDoi];
    const description = bookConfig("description", config);
    if (description) {
        format.metadata[kDescription] = description;
    }
    return format;
}
function isListedChapter(headingAttr) {
    return !headingAttr || !headingAttr.classes.includes("unlisted");
}
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 formatChapterTitle(format, label, attr, info) {
    const withIdSpan = (text)=>{
        if (!attr?.id) {
            return text;
        } else {
            return `[${text}]{#${attr.id} .quarto-section-identifier}`;
        }
    };
    if (!info) {
        return withIdSpan(label);
    }
    if (info.appendix) {
        const crossref = format.metadata?.crossref;
        const title = crossref?.[kCrossrefAppendixTitle] || format.language[kCrossrefApxPrefix] || "Appendix";
        const delim = crossref?.[kCrossrefAppendixDelim] !== undefined ? crossref?.[kCrossrefAppendixDelim] : " —";
        return withIdSpan(`${title} ${info.labelPrefix}${delim} ${label}`);
    } else {
        if (format.pandoc[kNumberSections] === false) {
            return withIdSpan(`[${label}]{.chapter-title}`);
        } else {
            return withIdSpan(`[${info.labelPrefix}]{.chapter-number}\u00A0 [${label}]{.chapter-title}`);
        }
    }
}
function numberChapterHtmlNav(label, info) {
    if (info) {
        return `<span class='chapter-number'>${info.labelPrefix}</span>\u00A0 <span class='chapter-title'>${label}</span>`;
    } else {
        return label;
    }
}
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) {
                const doc = await parseHtml(Deno.readTextFileSync(outputFile.file));
                resolveCrossrefs(context, fileRelative, outputFile.format, doc, index);
                writeDomToHtmlFile(doc, outputFile.file, outputFile.doctype);
            }
        }
    }
}
function resolveCrossrefs(context, file, format, doc, index) {
    const projOutput = projectOutputDir(context);
    const relativePathTo = (target)=>{
        const currentFile = join2(projOutput, file);
        const targetFile = join2(projOutput, target);
        return pathWithForwardSlashes(relative2(dirname2(currentFile), targetFile));
    };
    const refs = doc.querySelectorAll(".quarto-unresolved-ref");
    for(let i1 = 0; i1 < refs.length; i1++){
        const ref = refs[i1];
        const id = ref.textContent;
        const noPrefix = ref.classList.contains("ref-noprefix");
        const type = refType(id);
        if (!type) {
            continue;
        }
        const entry = index.entries[id];
        let parentLink;
        if (ref.parentElement?.tagName === "A" && ref.parentElement?.getAttribute("href") === `#${id}`) {
            parentLink = ref.parentElement;
        }
        if (entry) {
            if (parentLink && file !== entry.file) {
                const relativeFilePath = relativePathTo(entry.file);
                const hash = isChapterRef(entry) ? "" : `#${id}`;
                parentLink.setAttribute("href", `${relativeFilePath}${hash}`);
            }
            ref.innerHTML = formatCrossref(type, index.files[entry.file], entry, noPrefix, format, entry.parent ? index.entries[entry.parent] : undefined);
            ref.removeAttribute("class");
        } else {
            warn(`${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 link = links[i1];
        const href = link.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]);
                    link.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 renderFiles = bookConfigRenderItems(context.config).filter((item)=>!!item.file);
    for (const renderFile of renderFiles){
        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 format = index.formats[formatName];
                    if (format.pandoc[kOutputFile]) {
                        const outputFile = join2(dirname2(file), format.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, noPrefix, format, parent) {
    const { language } = format;
    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("");
    }
    if (format.pandoc["number-sections"] === false && type === "sec") {
        return entry.caption || entry.key;
    }
    const refNumber = numberOption(entry.order, options, type);
    if (type === "sec" && !noPrefix) {
        const prefix = options[kCrossrefChapters] && isChapterRef(entry) ? options[kCrossrefChaptersAppendix] ? language[kCrossrefApxPrefix] : language[kCrossrefChPrefix] : language[kCrossrefSecPrefix];
        const crossref = prefix + " " + refNumber;
        return crossref;
    } else {
        return refNumber;
    }
}
function refWithChapter(options, ref, section) {
    if (options[kCrossrefChapters] !== false) {
        const chapter = section ? section[0] : undefined;
        const chapterPrefix = chapter ? formatChapterIndex(options, chapter) + "." : "";
        return chapterPrefix + ref;
    } else {
        return ref;
    }
}
function refType(id) {
    const match = id.match(/^(\w+)-/);
    return (match ? match[1] : "fig").toLowerCase();
}
function numberOption(order, options, type, defaultFormat) {
    if (type === "sec" && order.section) {
        return sectionNumber(options, order.section);
    }
    const style = numberStyle(options, type, defaultFormat);
    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, defaultFormat) {
    const opt = `${type}-labels`;
    if (defaultFormat === undefined) {
        defaultFormat = "arabic";
    }
    const labelOpt = options[kCrossrefLabels] || defaultFormat;
    return options[opt] || labelOpt;
}
function sectionNumber(options, section) {
    let lastIndex = 0;
    for(let i1 = section.length - 1; i1 >= 0; i1--){
        if (section[i1] > 0) {
            lastIndex = i1;
            break;
        }
    }
    const num = [];
    for(let i1 = 0; i1 <= lastIndex; i1++){
        if (i1 === 0) {
            const chapIndex = formatChapterIndex(options, section[i1]);
            if (chapIndex) {
                num.push(chapIndex);
            }
        } else {
            num.push(section[i1].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 str = "";
    for (const i1 of Object.keys(roman)){
        const q = Math.floor(num / roman[i1]);
        num -= q * roman[i1];
        str += lower ? i1.toLowerCase().repeat(q) : i1.repeat(q);
    }
    return str;
}
async function bookBibliography(outputFiles, context) {
    const file = outputFiles[0];
    const bibliography = file.format.metadata[kBibliography];
    const nocite = typeof file.format.metadata[kNoCite] === "string" ? file.format.metadata[kNoCite] : undefined;
    const projType = projectType(context.config?.project?.[kProjectType]);
    if (!bibliography) {
        return {
            bibliographyPaths: []
        };
    }
    const fileRelativePath = relative2(projectFormatOutputDir(file.format, context, projType), file.file);
    const inputfile = await inputFileForOutputFile(context, fileRelativePath);
    const bibliographyPaths = [];
    let csl = file.format.metadata[kCsl];
    if (inputfile) {
        const firstFileDir = dirname2(inputfile.file);
        bibliographyPaths.push(...bibliography.map((file)=>isAbsolute2(file) || isAbsoluteRef(file) ? file : join2(firstFileDir, file)));
        if (csl) {
            const absPath = isAbsolute2(csl) ? csl : join2(firstFileDir, csl);
            const safeAbsPath = pathWithForwardSlashes(absPath);
            if (safeExistsSync(safeAbsPath)) {
                csl = safeAbsPath;
            }
        }
        return {
            csl,
            bibliographyPaths,
            nocite: nocite ? nocite.split(",").map((x)=>x.trim().replace(/^@/, "")) : []
        };
    } else {
        throw new Error(`Unable to determine proper path to use when computing bibliography path for ${fileRelativePath}.`);
    }
}
async function bookBibliographyPostRender(context, incremental, outputFiles) {
    await initDenoDom();
    const renderFiles = context.config?.project[kProjectRender] || [];
    let refsHtml;
    for (const file of renderFiles){
        const index = await inputTargetIndex(context, file);
        if (index?.markdown.containsRefs) {
            const target = await resolveInputTarget(context, file, false);
            if (target) {
                refsHtml = join2(projectOutputDir(context), target.outputHref);
            }
            break;
        }
    }
    if (refsHtml && outputFiles.length > 0) {
        const { bibliographyPaths, csl, nocite } = await bookBibliography(outputFiles, context);
        const citeIds = [];
        for (const file of outputFiles){
            let changed = false;
            const refsRelative = pathWithForwardSlashes(relative2(dirname2(file.file), refsHtml));
            const doc = await parseHtml(Deno.readTextFileSync(file.file));
            forEachCite(doc, (cite)=>{
                citeIds.push(...citeIdsFromCite(cite));
                const citeLinks = cite.querySelectorAll("a[role='doc-biblioref']");
                for(let l1 = 0; l1 < citeLinks.length; l1++){
                    const link = citeLinks[l1];
                    link.setAttribute("href", refsRelative + link.getAttribute("href"));
                    changed = true;
                }
            });
            const refsDiv = doc.getElementById("refs");
            if (refsDiv) {
                refsDiv.setAttribute("style", "display: none");
                changed = true;
            }
            if (changed) {
                await writeDomToHtmlFile(doc, file.file, file.doctype);
            }
        }
        const refsOutputFile = outputFiles.find((file)=>file.file === refsHtml);
        if (refsOutputFile) {
            if (incremental) {
                const bookHtmlOutputs = await bookMultiFileHtmlOutputs(context);
                for (const htmlOutput of bookHtmlOutputs){
                    if (outputFiles.findIndex((file)=>file.file === htmlOutput) === -1) {
                        if (existsSync(htmlOutput)) {
                            const doc = await parseHtml(Deno.readTextFileSync(htmlOutput));
                            if (doc) {
                                forEachCite(doc, (cite)=>{
                                    citeIds.push(...citeIdsFromCite(cite));
                                });
                            }
                        }
                    }
                }
            }
            if (nocite) {
                citeIds.push(...nocite);
            }
            if (citeIds.length > 0) {
                const biblioHtml = await generateBibliography(context, bibliographyPaths, citeIds, "html", csl);
                const doc = await parseHtml(Deno.readTextFileSync(refsOutputFile.file));
                const newRefsDiv = doc.createElement("div");
                newRefsDiv.innerHTML = biblioHtml;
                const refsDiv = doc.getElementById("refs");
                let changed = false;
                if (refsDiv) {
                    changed = true;
                    refsDiv.replaceWith(newRefsDiv.firstChild);
                } else {
                    const mainEl = doc.querySelector("main");
                    if (mainEl) {
                        changed = true;
                        mainEl.appendChild(newRefsDiv.firstChild);
                    }
                }
                if (changed) {
                    await writeDomToHtmlFile(doc, refsOutputFile.file, refsOutputFile.doctype);
                }
            }
        }
    }
}
async function generateBibliography(context, bibliography, citeIds, to, csl) {
    const biblioPaths = bibliography.map((biblio)=>{
        if (isAbsolute2(biblio)) {
            return relative2(context.dir, biblio);
        } else {
            return biblio;
        }
    });
    const yaml = {
        [kBibliography]: biblioPaths.map(pathWithForwardSlashes),
        [kNoCite]: __VIRTUAL_FILE181(citeIds).map((id)=>"@" + id).join(", ")
    };
    if (csl) {
        yaml[kCsl] = isAbsolute2(csl) ? pathWithForwardSlashes(relative2(context.dir, csl)) : csl;
    }
    const frontMatter = `---\n${stringify(yaml, {
        indent: 2
    })}\n---\n`;
    const result1 = await execProcess({
        cmd: [
            pandocBinaryPath(),
            "--from",
            "markdown",
            "--to",
            to,
            "--citeproc"
        ],
        cwd: context.dir,
        stdout: "piped"
    }, frontMatter);
    if (result1.success) {
        return result1.stdout;
    } else {
        error(result1.stderr);
        throw new Error();
    }
}
function forEachCite(doc, f) {
    const cites = doc.querySelectorAll(".citation");
    for(let i1 = 0; i1 < cites.length; i1++){
        const cite = cites[i1];
        f(cite);
    }
}
function citeIdsFromCite(cite) {
    const citeTarget = cite.getAttribute("data-cites");
    if (citeTarget) {
        return citeTarget.split(" ");
    } else {
        return [];
    }
}
function bookPandocRenderer(options, project) {
    const renderCompletions = [];
    const renderedFiles = [];
    const executedFiles = {};
    const cleanupExecutedFiles = ()=>{
        for (const format of Object.keys(executedFiles)){
            executedFiles[format].forEach((executedFile)=>{
                cleanupExecutedFile(executedFile, executedFile.recipe.output);
            });
        }
    };
    return {
        onFilterContexts: (_file, contexts, _files, _options)=>{
            return contexts;
        },
        onBeforeExecute: (format)=>{
            return {
                resolveDependencies: isMultiFileBookFormat(format)
            };
        },
        onRender: async (format, file, quiet)=>{
            if (isMultiFileBookFormat(file.context.format)) {
                const partitioned = partitionMarkdown(file.executeResult.markdown);
                const fileRelative = pathWithForwardSlashes(relative2(project.dir, file.context.target.source));
                const isIndex = isBookIndexPage(fileRelative);
                if (isIndex) {
                    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 coverImageAlt = file.recipe.format.metadata[kBookCoverImageAlt] || bookConfig(kBookCoverImageAlt, project.config);
                        const title = file.recipe.format.metadata[kTitle] || "";
                        const alt = coverImageAlt ? ` fig-alt="${coverImageAlt}"` : "";
                        file.executeResult.markdown = `![](${coverImage} "${title}"){.quarto-cover-image${alt}}\n\n` + file.executeResult.markdown;
                    }
                } else {
                    const chapterInfo = isHtmlOutput(file.recipe.format.pandoc) ? chapterInfoForInput(project, fileRelative) : undefined;
                    file.recipe.format.metadata[kHideDescription] = true;
                    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);
                        }
                        const executeMarkdownPartitioned = partitionYamlFrontMatter(file.executeResult.markdown);
                        if (executeMarkdownPartitioned) {
                            file.executeResult.markdown = executeMarkdownPartitioned.yaml + "\n\n" + partitioned.markdown;
                        } else {
                            file.executeResult.markdown = partitioned.markdown;
                        }
                    }
                }
                if (file.recipe.format.extensions?.book) {
                    const bookExtension = file.recipe.format.extensions?.book;
                    if (bookExtension.onMultiFilePrePrender) {
                        const result1 = await bookExtension.onMultiFilePrePrender(isIndex, file.recipe.format, file.executeResult.markdown, project);
                        if (result1.format) {
                            file.recipe.format = result1.format;
                        }
                        if (result1.markdown) {
                            file.executeResult.markdown = result1.markdown;
                        }
                    }
                }
                file.recipe.format.render[kFormatLinks] = false;
                const renderCompletion = await renderPandoc(file, quiet);
                renderCompletions.push(renderCompletion);
            } else {
                executedFiles[format] = executedFiles[format] || [];
                executedFiles[format].push(file);
            }
        },
        onPostProcess: async (renderedFormats)=>{
            let completion = renderCompletions.pop();
            while(completion){
                renderedFiles.push(await completion.complete(renderedFormats));
                completion = renderCompletions.pop();
            }
        },
        onComplete: async (error, quiet)=>{
            if (error) {
                cleanupExecutedFiles();
                return {
                    files: renderedFiles
                };
            }
            try {
                const renderFormats = Object.keys(executedFiles);
                for (const renderFormat of renderFormats){
                    const files = executedFiles[renderFormat];
                    if (files.length > 0) {
                        const format = files[0].context.format;
                        if (!isMultiFileBookFormat(format)) {
                            renderedFiles.push(await renderSingleFileBook(project, options, files, !!quiet));
                        }
                    }
                    delete executedFiles[renderFormat];
                }
                return {
                    files: renderedFiles
                };
            } catch (error) {
                cleanupExecutedFiles();
                return {
                    files: renderedFiles,
                    error: error ? typeof error === "string" ? new Error(error) : error : new Error()
                };
            }
        }
    };
}
async function renderSingleFileBook(project, options, files, quiet) {
    const fileLifetime = await waitUntilNamedLifetime("render-file");
    try {
        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 renderCompletion = await renderPandoc(executedFile, quiet);
        const renderedFormats = [];
        const renderedFile = await renderCompletion.complete(renderedFormats);
        files.forEach((file)=>{
            file.recipe.format.render[kKeepTex] = executedFile.recipe.format.render[kKeepTex];
            cleanupExecutedFile(file, join2(project.dir, renderedFile.file));
        });
        onSingleFileBookPostRender(project, renderedFile);
        return renderedFile;
    } finally{
        fileLifetime.cleanup();
    }
}
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 markdown = renderItems.reduce((markdown, item)=>{
        let itemMarkdown = "";
        if (item.file) {
            const itemInputPath = join2(project.dir, item.file);
            const file = files.find((file)=>file.context.target.source === itemInputPath);
            if (file) {
                const partitioned = partitionMarkdown(file.executeResult.markdown);
                const resolveTitleMarkdown = (partitioned)=>{
                    const createMarkdownTitle = (text, attr)=>{
                        let attrStr = "";
                        if (attr) {
                            const idStr = attr.id !== "" ? `#${attr.id} ` : "";
                            const clzStr = attr.classes.map((clz)=>{
                                return `.${clz} `;
                            }).join("");
                            const keyValueStr = attr.keyvalue.map((kv)=>{
                                const escapedValue = kv[1].replaceAll(/"/gm, '\\"');
                                return `${kv[0]}="${escapedValue}" `;
                            }).join("");
                            const attrContents = `${idStr}${clzStr}${keyValueStr}`.trim();
                            attrStr = `{${attrContents}}`;
                        }
                        return `# ${text} ${attrStr}\n\n`;
                    };
                    let titleText;
                    let titleAttr;
                    if (partitioned.yaml) {
                        const frontTitle = frontMatterTitle(partitioned.yaml);
                        if (frontTitle) {
                            titleText = frontTitle;
                        } else {
                            titleText = partitioned.headingText;
                            titleAttr = partitioned.headingAttr;
                        }
                    } else {
                        titleText = partitioned.headingText;
                        titleAttr = partitioned.headingAttr;
                    }
                    if (titleText === undefined) {
                        titleText = "";
                    }
                    return createMarkdownTitle(titleText, titleAttr);
                };
                const resolveTitleBlockMarkdown = (yaml)=>{
                    if (yaml) {
                        const titleBlockPath = resourcePath("projects/book/pandoc/title-block.md");
                        const titleAttr = `template='${titleBlockPath}'`;
                        const frontMatter = `---\n${stringify(yaml, {
                            indent: 2
                        })}\n---\n`;
                        const titleBlockMd = "```````{.quarto-title-block " + titleAttr + "}\n" + frontMatter + "\n```````\n\n";
                        return titleBlockMd;
                    } else {
                        return "";
                    }
                };
                const titleMarkdown = resolveTitleMarkdown(partitioned);
                const titleBlockMarkdown = resolveTitleBlockMarkdown(partitioned.yaml);
                const bodyMarkdown = partitioned.yaml?.title ? partitioned.srcMarkdownNoYaml : partitioned.markdown;
                itemMarkdown = bookItemMetadata(project, item, file) + titleMarkdown + titleBlockMarkdown + bodyMarkdown;
            } 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 supporting = 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 engineDependencies = 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 preserve = files.reduce((preserve, file)=>{
        return {
            ...preserve,
            ...file.executeResult.preserve
        };
    }, {});
    const postProcess = 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,
            supporting,
            filters,
            engineDependencies,
            preserve,
            postProcess
        },
        resourceFiles
    });
}
async function bookPostRender(context, incremental, outputFiles) {
    const websiteFiles = websiteOutputFiles(outputFiles);
    if (websiteFiles.length > 0) {
        await bookBibliographyPostRender(context, incremental, websiteFiles);
        await bookCrossrefsPostRender(context, websiteFiles);
        await websitePostRender(context, incremental, outputFiles);
    }
    const outputFormats = {};
    outputFiles.forEach((file)=>{
        if (file.format.pandoc.to) {
            outputFormats[file.format.pandoc.to] = outputFormats[file.format.pandoc.to] || file.format;
        }
    });
    for (const outputFormat of Object.values(outputFormats)){
        const bookExt = outputFormat.extensions?.book;
        if (bookExt.bookPostRender) {
            await bookExt.bookPostRender(outputFormat, context, incremental, outputFiles);
        }
    }
}
async function bookIncrementalRenderAll(context, options, files) {
    for(let i1 = 0; i1 < files.length; i1++){
        const contexts = await renderContexts({
            path: files[i1]
        }, options, false, context.notebookContext, context);
        for (const context of Object.values(contexts)){
            if (context.active && !isMultiFileBookFormat(context.format)) {
                return true;
            }
        }
    }
    return false;
}
function cleanupExecutedFile(file, finalOutput) {
    renderCleanup(file.context.target.input, finalOutput, file.recipe.format, file.executeResult.supporting, executionEngineKeepMd(file.context));
}
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,
        bookItemDepth: item.depth
    };
    const inlineMetadataEncoded = encodeBase64(JSON.stringify(inlineMetadata));
    const blockMetadataEncoded = encodeBase64(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(format, config) {
    format = cloneDeep1(format);
    if (config) {
        const setMetadata = (key)=>{
            const value = bookConfig(key, config);
            if (value) {
                format.metadata[key] = value;
            }
        };
        setMetadata(kTitle);
        setMetadata(kSubtitle);
        setMetadata(kAuthor);
        setMetadata(kDate);
        setMetadata(kDateFormat1);
        setMetadata(kAbstract);
        setMetadata(kDescription);
        setMetadata(kDoi);
    }
    return format;
}
function frontMatterTitle(yaml) {
    if (yaml) {
        return yaml[kTitle];
    } else {
        return undefined;
    }
}
const kSingleFileBook = "single-file-book";
const bookProjectType = {
    type: "book",
    inheritsType: websiteProjectType.type,
    create: (_title)=>{
        const resourceDir = resourcePath(join2("projects", "book"));
        return {
            configTemplate: join2(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",
    cleanOutputDir: true,
    filterFormat: (source, format, project)=>{
        if (format.extensions?.book) {
            const bookExt = format.extensions?.book;
            if (bookExt.filterFormat) {
                return bookExt.filterFormat(source, format, project);
            } else {
                return format;
            }
        } else {
            return format;
        }
    },
    formatOutputDirectory: (format)=>{
        if (format.extensions?.book) {
            const bookExt = format.extensions?.book;
            if (bookExt.formatOutputDirectory) {
                return bookExt.formatOutputDirectory();
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    },
    selfContainedOutput: (format)=>{
        const bookExtension = format.extensions?.book;
        return bookExtension?.selfContainedOutput || false;
    },
    config: bookProjectConfig,
    projectFormatsOnly: true,
    isSupportedFormat: (format)=>{
        return !!format.extensions?.book;
    },
    filterParams: async (options)=>{
        if (options.format.extensions?.book) {
            const bookExt = options.format.extensions?.book;
            const filterParams = bookExt.filterParams ? bookExt.filterParams(options) : {};
            if (isMultiFileBookFormat(options.format)) {
                return {
                    ...filterParams,
                    [kCrossrefResolveRefs]: false
                };
            } else {
                return {
                    ...filterParams,
                    [kSingleFileBook]: true
                };
            }
        }
    },
    pandocRenderer: bookPandocRenderer,
    navItemText: (context, input, text, number)=>{
        const chapterInfo = chapterInfoForInput(context, input);
        if (chapterInfo && number) {
            return Promise.resolve({
                text,
                html: numberChapterHtmlNav(text, chapterInfo)
            });
        } else {
            return Promise.resolve({
                html: text,
                text: text
            });
        }
    },
    incrementalRenderAll: bookIncrementalRenderAll,
    preRender: bookPreRender,
    postRender: bookPostRender,
    formatLibDirs: websiteProjectType.formatLibDirs,
    metadataFields: ()=>[
            ...websiteProjectType.metadataFields(),
            "book"
        ],
    resourceIgnoreFields: ()=>[
            ...websiteProjectType.resourceIgnoreFields(),
            kBook
        ],
    formatExtras: async (context, source, flags, format, services)=>{
        let extras = {
            pandoc: {
                [kToc]: !isEpubOutput(format.pandoc),
                [kNumberSections]: true
            },
            metadata: {
                [kCrossref]: {
                    [kCrossrefChapters]: true
                }
            }
        };
        if (isHtmlOutput(format.pandoc, true)) {
            if (formatHasBootstrap(format)) {
                extras.html = {
                    [kSassBundles]: [
                        bookScssBundle()
                    ],
                    [kHtmlPostprocessors]: [
                        bookHtmlPostprocessor()
                    ]
                };
            }
            const websiteExtras = await websiteProjectType.formatExtras(context, source, flags, format, services);
            extras = mergeConfigs(extras, websiteExtras);
        } else if (isLatexOutput(format.pandoc)) {
            extras = mergeConfigs(extras, {
                metadata: {
                    [kDocumentClass]: "scrreprt",
                    [kPaperSize]: "letter"
                },
                pandoc: {
                    [kTopLevelDivision]: "chapter"
                }
            });
        }
        return extras;
    }
};
function bookPreRender(context) {
    const date = bookConfig(kDate, context.config);
    if (context.config && isSpecialDate(date)) {
        setBookConfig(kDate, parseSpecialDate(context.files.input, date), context.config);
    }
    if (websiteProjectType.preRender) {
        return websiteProjectType.preRender(context);
    } else {
        return Promise.resolve();
    }
}
function bookHtmlPostprocessor() {
    return (doc)=>{
        const coverImage = doc.querySelector(".quarto-cover-image");
        const nextEl = coverImage?.parentNode?.nextElementSibling;
        if (nextEl && nextEl.tagName === "SECTION" && coverImage?.parentNode) {
            coverImage?.parentElement?.remove();
            nextEl.firstElementChild?.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)
        }
    };
}
async function bibliographyCslJson(input, metadata) {
    const bibliography = metadata[kBibliography];
    if (bibliography) {
        const references = await renderToCSLJSON(dirname2(input), asArray(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 result1 = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "piped"
    }, cslStr);
    if (result1.success) {
        return result1.stdout;
    } else {
        throw new Error(`Failed to render citation: error code ${result1.code}\n${result1.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 result1 = await execProcess({
        cmd,
        stdout: "piped",
        stderr: "piped"
    }, cslStr);
    if (result1.success) {
        return result1.stdout;
    } else {
        throw new Error(`Failed to generate bibtex, rendering failed with code ${result1.code}\n${result1.stderr}`);
    }
}
async function renderToCSLJSON(dir, biblios) {
    const bibloEntries = [];
    for (const biblio of biblios){
        const biblioPath = join2(dir, biblio);
        const cmd = [
            pandocBinaryPath()
        ];
        cmd.push(isAbsolute2(biblioPath) ? biblioPath : join2(Deno.cwd(), biblioPath));
        cmd.push("-t");
        cmd.push("csljson");
        cmd.push("--citeproc");
        const result1 = await execProcess({
            cmd,
            stdout: "piped",
            stderr: "piped",
            cwd: dir
        });
        if (result1.success) {
            if (result1.stdout) {
                const entries = JSON.parse(result1.stdout);
                bibloEntries.push(...entries);
            }
        } else {
            throw new Error(`Failed to generate bibliography, rendering failed with code ${result1.code}\n${result1.stderr}`);
        }
    }
    return bibloEntries;
}
const kDOI = "DOI";
const kCitation1 = "citation";
const kURL = "URL";
const kId = "id";
const kCitationKey = "citation-key";
const kEditor = "editor";
const kType2 = "type";
const kCategories = "categories";
const kLanguage1 = "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 = "page-first";
const kLastPage = "page-last";
const kPage = "page";
const kNumber = "number";
const kCustom = "custom";
const kArchiveCollection = "archive_collection";
const kArchiveLocation = "archive_location";
const getCSLPath = (input, format)=>{
    const cslPath = format.metadata[kCsl];
    if (cslPath) {
        if (isAbsolute2(cslPath)) {
            return cslPath;
        } else {
            return join2(dirname2(input), cslPath);
        }
    } else {
        return undefined;
    }
};
function documentCSL(input, inputMetadata, defaultType, outputFile, offset) {
    const citationMetadata = citationMeta(inputMetadata);
    const type = citationMetadata[kType2] ? cslType(citationMetadata[kType2]) : defaultType;
    const title = citationMetadata[kTitle] || inputMetadata[kTitle];
    const csl = {
        title,
        type
    };
    const key = citationMetadata[kCitationKey];
    if (key) {
        csl[kCitationKey] = key;
    }
    const authors = parseAuthor(citationMetadata[kAuthor] || inputMetadata[kAuthor] || inputMetadata[kAuthors]);
    csl.author = cslNames(authors?.filter((auth)=>auth !== undefined).map((auth)=>auth?.name));
    const editors = parseAuthor(citationMetadata[kEditor]);
    csl.editor = cslNames(editors?.filter((editor)=>editor !== undefined).map((editor)=>editor?.name));
    if (csl.editor && csl.editor.length === 0) {
        delete csl.editor;
    }
    const categories = citationMetadata[kCategories] || inputMetadata[kCategories];
    if (categories) {
        csl.categories = Array.isArray(categories) ? categories : [
            categories
        ];
    }
    const language = citationMetadata[kLanguage1] || inputMetadata[kLang];
    if (language) {
        csl.language = language;
    }
    const availableDate = citationMetadata[kAvailableDate] || resolveAndFormatDate(input, inputMetadata[kDate1]);
    if (availableDate) {
        csl[kAvailableDate] = cslDate(availableDate);
    }
    const issued = citationMetadata[kIssued] || resolveAndFormatDate(input, inputMetadata[kDate1]);
    if (issued) {
        csl.issued = cslDate(issued);
    }
    const __abstract = citationMetadata[kAbstract] || inputMetadata[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 keys = [
            baseKey,
            transform(baseKey)
        ];
        for (const key of keys){
            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, inputMetadata, outputFile, offset);
    }
    const doi = findValue(kDOI, [
        citationMetadata,
        inputMetadata
    ], 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 number = citationMetadata[kNumber];
    if (number) {
        csl.number = number;
    }
    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;
    }
    const extras = {};
    const kwString = citationMetadata.keyword;
    if (kwString && typeof kwString === "string") {
        extras.keywords = kwString.split(",");
    } else if (inputMetadata.keywords) {
        const kw = inputMetadata.keywords;
        extras.keywords = Array.isArray(kw) ? kw : [
            kw
        ];
    }
    if (citationMetadata[kPdfUrl]) {
        extras[kPdfUrl] = citationMetadata[kPdfUrl];
    }
    if (citationMetadata[kAbstractUrl]) {
        extras[kAbstractUrl] = citationMetadata[kAbstractUrl];
    }
    if (citationMetadata[kEIssn]) {
        extras[kEIssn] = citationMetadata[kEIssn];
    }
    return {
        csl,
        extras
    };
}
function citationMeta(metadata) {
    if (typeof metadata[kCitation1] === "object") {
        return metadata[kCitation1];
    } else {
        return {};
    }
}
function synthesizeCitationUrl(input, metadata, outputFile, offset) {
    const siteMeta = metadata[kWebsite];
    let baseUrl = siteMeta?.[kSiteUrl];
    if (baseUrl && outputFile && offset) {
        baseUrl = baseUrl.replace(/\/$/, "");
        const rootDir = normalizePath(join2(dirname2(input), offset));
        if (outputFile === "index.html") {
            const part = pathWithForwardSlashes(relative2(rootDir, dirname2(input)));
            if (part.length === 0) {
                return `${baseUrl}/`;
            } else {
                return `${baseUrl}/${part}/`;
            }
        } else {
            const relativePath = relative2(rootDir, join2(dirname2(input), basename2(outputFile)));
            const part = pathWithForwardSlashes(relativePath);
            return `${baseUrl}/${part}`;
        }
    } else {
        return undefined;
    }
}
function pages(citationMetadata) {
    let firstPage = citationMetadata[kFirstPage];
    let lastPage = citationMetadata[kLastPage];
    let pages = citationMetadata[kPage] ? `${citationMetadata[kPage]}` : undefined;
    if (pages && pages.includes("-")) {
        const pagesSplit = pages.split("-");
        if (!firstPage) {
            firstPage = pagesSplit[0];
        }
        if (!lastPage) {
            lastPage = pagesSplit[1];
        }
    } else if (pages && !firstPage) {
        firstPage = pages;
    } else if (!pages) {
        if (firstPage && lastPage) {
            pages = `${firstPage} - ${lastPage}`;
        } else if (firstPage) {
            pages = `${firstPage}`;
        }
    }
    return {
        firstPage: firstPage,
        lastPage: lastPage,
        page: pages
    };
}
const kGoogleScholar = "google-scholar";
function metadataPostProcessor(input, format, offset) {
    return async (doc, options)=>{
        if (format.render[kCanonicalUrl]) {
            writeCanonicalUrl(doc, format.render[kCanonicalUrl], input, options.inputMetadata, format.pandoc["output-file"], offset);
        }
        if (googleScholarEnabled(format)) {
            const { csl, extras } = documentCSL(input, options.inputMetadata, "webpage", format.pandoc["output-file"], offset);
            const documentMetadata = googleScholarMeta(csl, extras);
            const referenceMetadata = await googleScholarReferences(input, options.inputMetadata);
            [
                ...documentMetadata,
                ...referenceMetadata
            ].forEach((meta)=>{
                writeMetaTag(meta.name, meta.content, doc);
            });
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
function googleScholarEnabled(format) {
    if (format.metadata[kGoogleScholar] === true) {
        return true;
    }
    const siteMeta = format.metadata[kWebsite];
    if (siteMeta && siteMeta[kGoogleScholar] === true) {
        return true;
    }
    return false;
}
function googleScholarMeta(csl, extras) {
    const scholarMeta = [];
    const write = metadataWriter(scholarMeta);
    if (csl.title) {
        write("citation_title", csl.title);
    }
    if (csl.abstract) {
        write("citation_abstract", csl.abstract);
    }
    if (extras.keywords) {
        write("citation_keywords", extras.keywords);
    }
    if (csl.author) {
        csl.author.forEach((author)=>{
            write("citation_author", author.literal || `${author.given} ${author.family}`);
        });
    }
    if (csl.editor) {
        csl.editor.forEach((editor)=>{
            write("citation_editor", editor.literal || `${editor.given} ${editor.family}`);
        });
    }
    if (csl.issued) {
        const edtfIssued = cslDateToEDTFDate(csl.issued);
        if (edtfIssued) {
            write("citation_publication_date", edtfIssued);
            write("citation_cover_date", edtfIssued);
        }
        const parts = csl.issued["date-parts"];
        if (parts && parts.length > 0) {
            write("citation_year", parts[0][0]);
        }
    }
    if (csl["available-date"]) {
        const edtfAvailable = cslDateToEDTFDate(csl["available-date"]);
        if (edtfAvailable) {
            write("citation_online_date", edtfAvailable);
        }
    }
    if (csl.URL) {
        write("citation_fulltext_html_url", csl.URL);
    }
    if (extras[kPdfUrl]) {
        write("citation_pdf_url", extras[kPdfUrl]);
    }
    if (extras[kAbstractUrl]) {
        write("citation_abstract_html_url", extras[kAbstractUrl]);
    }
    if (csl.issue) {
        write("citation_issue", csl.issue);
    }
    if (csl.DOI) {
        write("citation_doi", csl.DOI);
    }
    if (csl.ISBN) {
        write("citation_isbn", csl.ISBN);
    }
    if (csl.ISSN) {
        write("citation_issn", csl.ISSN);
    }
    if (extras[kEIssn]) {
        write("citation_eissn", extras[kEIssn]);
    }
    if (csl.PMID) {
        write("citation_pmid", csl.PMID);
    }
    if (csl.volume) {
        write("citation_volume", csl.volume);
    }
    if (csl.language) {
        write("citation_language", csl.language);
    }
    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") {
        if (csl["container-title"]) {
            write("citation_conference_title", csl["container-title"]);
        }
        if (csl.publisher) {
            write("citation_conference", csl.publisher);
        }
    } else if (type === "thesis") {
        if (csl.publisher) {
            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 if (type === "book") {
        if (csl["container-title"]) {
            write("citation_book_title", csl["container-title"]);
        }
    } else if (type === "chapter") {
        write("citation_inbook_title", csl["container-title"]);
    } else {
        if (csl["container-title"]) {
            write("citation_journal_title", csl["container-title"]);
        }
        if (csl["container-title-short"]) {
            write("citation_journal_abbrev", csl["container-title-short"]);
        }
        if (csl.publisher) {
            write("citation_publisher", csl.publisher);
        }
    }
    if (csl["collection-title"]) {
        write("citation_series_title", csl["collection-title"]);
    }
    return scholarMeta;
}
async function googleScholarReferences(input, metadata) {
    const scholarMeta = [];
    const write = metadataWriter(scholarMeta);
    const references = await bibliographyCslJson(input, metadata);
    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 writeCanonicalUrl(doc, url, input, inputMetadata, outputFile, offset) {
    if (typeof url === "string") {
        writeLinkTag("canonical", url, doc);
    } else if (url) {
        const canonicalUrl = synthesizeCitationUrl(input, inputMetadata, outputFile, offset);
        if (canonicalUrl) {
            writeLinkTag("canonical", canonicalUrl, doc);
        }
    }
}
const $XML = Symbol("x/xml");
const schema1 = {
    comment: "#comment",
    text: "#text",
    stylesheets: "$stylesheets",
    attribute: {
        prefix: "@"
    },
    property: {
        prefix: "@"
    },
    space: {
        name: "xml:space",
        preserve: "preserve"
    }
};
const SeekMode = Object.freeze({
    Current: Deno?.SeekMode?.Current ?? 0,
    Start: Deno?.SeekMode?.Start ?? 1,
    End: Deno?.SeekMode?.End ?? 2
});
const entities = {
    xml: {
        "&lt;": "<",
        "&gt;": ">",
        "&apos;": "'",
        "&quot;": '"',
        "&amp;": "&"
    },
    char: {
        "&": "&amp;",
        '"': "&quot;",
        "<": "&lt;",
        ">": "&gt;",
        "'": "&apos;"
    }
};
const tokens = {
    entity: {
        regex: {
            entities: /&#(?<hex>x?)(?<code>\d+);/g
        }
    },
    prolog: {
        start: "<?xml",
        end: "?>"
    },
    stylesheet: {
        start: "<?xml-stylesheet",
        end: "?>"
    },
    doctype: {
        start: "<!DOCTYPE",
        end: ">",
        elements: {
            start: "[",
            end: "]"
        },
        element: {
            start: "<!ELEMENT",
            end: ">",
            value: {
                start: "(",
                end: ")",
                regex: {
                    end: {
                        until: /\)/,
                        bytes: 1
                    }
                }
            }
        }
    },
    comment: {
        start: "<!--",
        end: "-->",
        regex: {
            end: {
                until: /(?<!-)-->/,
                bytes: 4,
                length: 3
            }
        }
    },
    cdata: {
        start: "<![CDATA[",
        end: "]]>",
        regex: {
            end: {
                until: /\]\]>/,
                bytes: 3
            }
        }
    },
    tag: {
        start: "<",
        end: ">",
        close: {
            start: "</",
            end: ">",
            self: "/",
            regex: {
                start: /<\//,
                end: /\/?>/
            }
        },
        attribute: {
            regex: {
                name: {
                    until: /=/,
                    bytes: 1
                }
            }
        },
        regex: {
            name: {
                until: /[\s\/>]/,
                bytes: 1
            },
            start: {
                until: /</,
                bytes: 1
            }
        }
    },
    text: {
        regex: {
            end: {
                until: /(<\/)|(<!)/,
                bytes: 2
            }
        }
    }
};
class Stream {
    constructor(content){
        this.#content = content;
    }
    #decoder = new TextDecoder();
    #encoder = new TextEncoder();
    #content;
    get cursor() {
        return this.#content.seekSync(0, SeekMode.Current);
    }
    peek(bytes = 1, offset = 0) {
        const buffer = new Uint8Array(bytes);
        const cursor = this.cursor;
        if (offset) {
            this.#content.seekSync(offset, SeekMode.Current);
        }
        if (this.#content.readSync(buffer)) {
            this.#content.seekSync(cursor, SeekMode.Start);
            return this.#decoder.decode(buffer);
        }
        throw new Deno.errors.UnexpectedEof();
    }
    read(bytes = 1) {
        const buffer = new Uint8Array(bytes);
        if (this.#content.readSync(buffer)) {
            return buffer;
        }
        throw new Deno.errors.UnexpectedEof();
    }
    capture({ until, bytes, trim = true, length = bytes }) {
        if (trim) {
            this.trim();
        }
        const buffer = [];
        while(!until.test(this.peek(bytes))){
            buffer.push(this.read(1)[0]);
        }
        if (bytes !== length) {
            buffer.push(...this.read(bytes - length));
        }
        if (trim) {
            this.trim();
        }
        return this.#decoder.decode(Uint8Array.from(buffer));
    }
    consume({ content, trim = true }) {
        if (trim) {
            this.trim();
        }
        const bytes = this.#encoder.encode(content).length;
        if (content === this.peek(bytes)) {
            this.read(bytes);
            if (trim) {
                this.trim();
            }
            return;
        }
        throw Object.assign(new SyntaxError(`Expected next sequence to be "${content}", got "${this.peek(bytes)}" instead`), {
            stack: false
        });
    }
    trim() {
        try {
            while(/\s/.test(this.peek())){
                this.read(1);
            }
        } catch (error) {
            if (error instanceof Deno.errors.UnexpectedEof) {
                return;
            }
            throw error;
        }
    }
}
class Stringifier {
    constructor(document1, options = {}){
        this.#document = document1;
        this.#options = options;
        this.#options.replacer ??= function({ value }) {
            return value;
        };
    }
    stringify() {
        const document1 = this.#make.extraction(this.#document);
        if (document1.raw.xml) {
            this.#prolog(document1);
        }
        if (document1.raw[schema1.stylesheets]) {
            this.#stylesheet(document1);
        }
        if (document1.raw.doctype) {
            this.#doctype(document1);
        }
        this.#tag({
            document: document1.raw,
            path: [],
            name: "",
            ...document1
        });
        return this.#result.trim();
    }
    #options;
    #document;
    #debug(path, string) {
        if (this.#options.debug) {
            console.debug(`${path.join(" > ")} | ${string}`.trim());
        }
    }
    #prolog({ raw: node }) {
        this.#debug([], "stringifying prolog");
        const attributes = this.#attributes({
            tag: "prolog",
            ...this.#make.extraction(node.xml)
        });
        this.#write(`${tokens.prolog.start}${attributes}${tokens.prolog.end}`);
    }
    #stylesheet({ raw: node }) {
        this.#debug([], "stringifying stylesheets");
        for (const stylesheet of node[schema1.stylesheets]){
            const attributes = this.#attributes({
                tag: "stylesheet",
                ...this.#make.extraction(stylesheet)
            });
            this.#write(`${tokens.stylesheet.start}${attributes}${tokens.stylesheet.end}`);
        }
    }
    #doctype({ raw: node }) {
        this.#debug([], "stringifying doctype");
        const { raw: doctype, attributes, children: elements } = this.#make.extraction(node.doctype);
        this.#write(`${tokens.doctype.start}${this.#properties({
            attributes
        })}`, {
            newline: !!elements.length
        });
        if (elements.length) {
            this.#debug([], "stringifying doctype elements");
            this.#down();
            this.#write(tokens.doctype.elements.start);
            this.#down();
            for (const key of elements){
                this.#debug([], `stringifying doctype elements ${key}`);
                const value = `${tokens.doctype.element.value.start}${doctype[key]}${tokens.doctype.element.value.end}`;
                this.#write(`${tokens.doctype.element.start} ${this.#quote(key, {
                    optional: true
                })} ${value} ${tokens.doctype.element.end}`);
            }
            this.#up();
            this.#write(tokens.doctype.elements.end);
            this.#up();
        }
        this.#write(tokens.doctype.end);
    }
    #tag({ document: document1, path, name, raw: node, text: content, comments, attributes, children }) {
        if (name) {
            this.#debug(path, `stringifying tag ${name}`);
        }
        if (this.#options.progress) {
            this.#options.progress(this.#result.length);
        }
        const selfclosed = content === null && !comments.length && !children.length;
        let inline = false;
        if (name) {
            this.#write(`${tokens.tag.start}${name}${this.#attributes({
                raw: node,
                attributes,
                tag: name
            })}${selfclosed ? tokens.tag.close.self : ""}${tokens.tag.end}`);
            this.#down();
        }
        if (!selfclosed) {
            if ([
                "string",
                "boolean",
                "number",
                "undefined"
            ].includes(typeof content) || content === null) {
                let cdata = false;
                if (document1[$XML]?.cdata?.find((cpath)=>cpath.join(">") === path.join(">"))) {
                    this.#debug(path, `stringifying text content`);
                    cdata = true;
                }
                this.#debug(path, `stringifying text content`);
                inline = this.#text({
                    path,
                    text: content,
                    tag: name,
                    properties: Object.fromEntries(attributes.map((attribute)=>[
                            attribute.substring(schema1.attribute.prefix.length),
                            node[attribute]
                        ])),
                    cdata
                });
            }
            if (comments.length) {
                this.#debug(path, `stringifying comments`);
                const commentArr = Array.isArray(comments) ? comments : [
                    comments
                ];
                for (const comment of commentArr){
                    this.#write("\n", {
                        newline: false,
                        indent: false
                    });
                    this.#comment({
                        text: comment,
                        tag: name
                    });
                }
            }
            if (children.length) {
                this.#debug(path, `stringifying children`);
                this.#write("\n", {
                    newline: false,
                    indent: false
                });
                const handle = ({ child, name })=>{
                    switch(true){
                        case Array.isArray(child):
                            {
                                for (const value of child){
                                    handle({
                                        child: value,
                                        name
                                    });
                                }
                                break;
                            }
                        case typeof child === "object" && !!child:
                            {
                                this.#tag({
                                    document: document1,
                                    name,
                                    path: [
                                        ...path,
                                        name
                                    ],
                                    ...this.#make.extraction(child)
                                });
                                break;
                            }
                        default:
                            {
                                this.#tag({
                                    document: document1,
                                    name,
                                    path: [
                                        ...path,
                                        name
                                    ],
                                    ...this.#make.extraction({
                                        [schema1.text]: child
                                    })
                                });
                                break;
                            }
                    }
                };
                for (const name of children){
                    const child = node[name];
                    handle({
                        child,
                        name
                    });
                }
                inline = false;
            }
        }
        if (name) {
            this.#up();
            if (!selfclosed) {
                this.#write(`${tokens.tag.close.start}${name}${tokens.tag.close.end}`, {
                    indent: !inline
                });
            }
        }
    }
    #comment({ text, tag }) {
        const comment = this.#replace({
            value: text,
            key: schema1.comment,
            tag,
            properties: null
        });
        this.#write(`${tokens.comment.start} ${comment} ${tokens.comment.end}`, {
            newline: false
        });
    }
    #text({ path, text, tag, properties, cdata }) {
        if (cdata) {
            text = `${tokens.cdata.start}${text}${tokens.cdata.end}`;
        }
        const lines = this.#replace({
            value: text,
            key: schema1.text,
            tag,
            properties,
            escape: !cdata
        }).split("\n");
        let trim = true;
        if (properties[schema1.space.name] === schema1.space.preserve) {
            this.#debug(path, `${schema1.space.name} is set to ${schema1.space.preserve}`);
            trim = false;
        }
        const inline = lines.length <= 1;
        if (inline) {
            this.#trim();
        }
        for (const line of lines){
            this.#write(trim ? line.trimStart() : line, {
                indent: !inline,
                newline: !inline
            });
        }
        return inline;
    }
    #attributes({ raw: node, attributes, tag }) {
        const stringified = attributes.map((key)=>`${key.substring(schema1.attribute.prefix.length)}=${this.#quote(this.#replace({
                key,
                value: node[key],
                tag,
                properties: null
            }))}`).join(" ");
        return stringified.length ? ` ${stringified}` : "";
    }
    #properties({ attributes }) {
        const stringified = attributes.map((key)=>`${this.#quote(key.substring(schema1.property.prefix.length), {
                optional: true
            })}`).join(" ");
        return stringified.length ? ` ${stringified}` : "";
    }
    #replace({ key, value, tag, properties, escape = true }) {
        return `${this.#options.replacer.call(null, {
            key,
            tag,
            properties,
            value: (()=>{
                switch(true){
                    case (this.#options.nullToEmpty ?? true) && value === null:
                        return "";
                    default:
                        {
                            if (escape) {
                                for (const [__char, entity] of Object.entries(entities.char)){
                                    value = `${value}`.replaceAll(__char, entity);
                                }
                            }
                        }
                }
                return `${value}`;
            })()
        })}`;
    }
    #result = "";
    #write(text, { newline = true, indent = true } = {}) {
        this.#result += `${`${indent ? " ".repeat((this.#options?.indentSize ?? 2) * this.#depth) : ""}`}${text}${newline ? "\n" : ""}`;
    }
    #trim() {
        this.#result = this.#result.trim();
    }
    #depth = 0;
    #down() {
        this.#depth++;
    }
    #up() {
        this.#depth--;
        this.#depth = Math.max(0, this.#depth);
    }
    #quote(content, { optional = false } = {}) {
        if (optional) {
            if (/^[\w_]+$/i.test(`${content}`)) {
                return `${content}`;
            }
        }
        return `"${`${content}`.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
    }
    #make = {
        extraction (node) {
            const keys = Object.keys(node ?? {});
            return {
                raw: node,
                text: node?.[schema1.text] ?? null,
                comments: node?.[schema1.comment] ?? [],
                attributes: keys.filter((key)=>key.startsWith(schema1.attribute.prefix) || key.startsWith(schema1.property.prefix)),
                children: keys.filter((key)=>![
                        schema1.text,
                        schema1.comment,
                        schema1.stylesheets,
                        "xml",
                        "doctype"
                    ].includes(key) && !(key.startsWith(schema1.attribute.prefix) || key.startsWith(schema1.property.prefix))),
                meta: node?.[$XML] ?? {}
            };
        }
    };
}
function stringify2(content, options) {
    return new Stringifier(content, options).stringify();
}
const kMecaVersion = "1";
function toXml(manifest) {
    const mecaJson = {
        xml: {
            "@version": "1.0",
            "@encoding": "UTF-8"
        },
        doctype: {
            "@manifest": true,
            "@PUBLIC": true,
            "@-//MECA//DTD Manifest v1.0//en": true,
            "@MECA_manifest.dtd": true
        },
        manifest: {
            "@manifest-version": manifest.version,
            "@xmlns": "https://manuscriptexchange.org/schema/manifest",
            "@xmlns:xlink": "http://www.w3.org/1999/xlink",
            item: manifest.items.map(toMecaXMLItem)
        }
    };
    return stringify2(mecaJson);
}
function toMecaXMLItem(item) {
    const xmlItem = {};
    if (item.id) {
        xmlItem["@id"] = item.id;
    }
    if (item.type) {
        xmlItem["@item-type"] = item.type;
    }
    if (item.version) {
        xmlItem["@version"] = item.version;
    }
    if (item.metadataId) {
        xmlItem["metadata-id"] = item.metadataId;
    }
    if (item.title) {
        xmlItem["item-title"] = item.title;
    }
    if (item.description) {
        xmlItem["item-description"] = item.description;
    }
    if (item.order) {
        xmlItem["file-order"] = item.order;
    }
    if (item.metadata) {
        const metaValues = {};
        if (item.metadata) {
            for (const key of Object.keys(item.metadata)){
                const value = item.metadata[key];
                metaValues["metadata"] = {
                    ["@metadata-name"]: key,
                    ["#text"]: value
                };
            }
        }
        const itemMetadata = Object.keys(metaValues).length > 0 ? {
            ["item-metadata"]: metaValues
        } : undefined;
        xmlItem["item-metadata"] = itemMetadata;
    }
    xmlItem["instance"] = {
        ["@media-type"]: item.instance.mediaType,
        ["@xlink:href"]: item.instance.href
    };
    return xmlItem;
}
function unzip(file, dir) {
    if (!dir) dir = dirname2(file);
    if (file.endsWith("zip")) {
        if (isWindows3()) {
            const args = [
                "-Command",
                `"& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('${file}', '${dir}'); }"`
            ];
            return safeWindowsExec("powershell", args, (cmd)=>{
                return execProcess({
                    cmd: cmd,
                    stdout: "piped"
                });
            });
        } else {
            return execProcess({
                cmd: [
                    "unzip",
                    "-o",
                    file
                ],
                cwd: dir,
                stdout: "piped"
            });
        }
    } else {
        return execProcess({
            cmd: [
                "tar",
                "xfz",
                file
            ],
            cwd: dir,
            stdout: "piped"
        });
    }
}
function zip(files, archive, options) {
    if (options?.overwrite === false && existsSync(archive)) {
        throw new Error(`An archive already exits at ${archive}`);
    }
    const filesArr = Array.isArray(files) ? files : [
        files
    ];
    const zipCmd = ()=>{
        if (Deno.build.os === "windows") {
            return [
                "PowerShell",
                "Compress-Archive",
                "-Path",
                filesArr.join(", "),
                "-DestinationPath",
                archive,
                "-Force"
            ];
        } else {
            return [
                "zip",
                "-r",
                archive,
                ...filesArr
            ];
        }
    };
    return execProcess({
        cmd: zipCmd(),
        cwd: options?.cwd,
        stdout: "piped",
        stderr: "piped"
    });
}
const kExecutionFiles = [
    "environment.yml",
    "requirements.txt",
    "renv.lock",
    "Pipfile",
    "Pipfile.lock",
    "setup.py",
    "Project.toml",
    "REQUIRE",
    "install.R",
    "apt.txt",
    "DESCRIPTION",
    "postBuild",
    "start",
    "runtime.txt",
    "default.nix",
    "Dockerfile"
];
function isReesEnvronmentFile(path) {
    return kExecutionFiles.includes(basename2(path));
}
function codeSpacesUrl(repoUrl) {
    const containerUrl = repoUrl.replace(/(https?\:\/\/github.com)\/([a-zA-Z0-9-_\.]+?)\/([a-zA-Z0-9-_\.]+?)\//, "$1/codespaces/new/$2/$3?resume=1");
    return containerUrl;
}
function binderUrl(organization, repository, binderOptions) {
    const url = [
        `https://mybinder.org/v2/gh/${organization}/${repository}/HEAD`
    ];
    const params = [];
    if (binderOptions && binderOptions.openFile) {
        params.push(`labpath=${binderOptions.openFile}`);
    }
    if (binderOptions?.editor) {
        switch(binderOptions.editor){
            case "rstudio":
                params.push(`urlpath=rstudio`);
                break;
            case "vscode":
                params.push(`urlpath=vscode`);
                break;
            case "jupyterlab":
            default:
                break;
        }
    }
    if (params.length > 0) {
        url.push("?");
        url.push(params.join("&"));
    }
    return url.join("");
}
function isDevContainerFile(relPath) {
    if (relPath === join2(".devcontainer", "devcontainer.json")) {
        return true;
    }
    if (relPath === ".devcontainer.json") {
        return true;
    }
    if (relPath.match(/^\.devcontainer[\/\\][^\/\\]+?[\/\\]devcontainer.json$/)) {
        return true;
    }
    return false;
}
const kArticleMetadata = "article-metadata";
const kArticleSupportingFile = "article-supporting-file";
const kArticleSource = "article-source";
const kArticleSourceEnvironment = "article-source-environment";
const kManuscript = "manuscript";
const kManuscriptSupportingFile = "manuscript-supporting-file";
const kSrcDirName = "source";
const kSrcDirMecaType = "article-source-directory";
const kMecaSuffix = "-meca.zip";
const shouldMakeMecaBundle = (formats, manuConfig)=>{
    if (!manuConfig || manuConfig[kMecaBundle] !== false) {
        if (manuConfig && manuConfig[kMecaBundle] === true) {
            return true;
        }
        return formats.find((format)=>{
            if (typeof format === "string") {
                return isJatsOutput(format);
            } else {
                return isJatsOutput(format.pandoc);
            }
        });
    } else {
        return false;
    }
};
const mecaFileName = (file, config)=>{
    if (typeof config[kMecaBundle] === "string") {
        return config[kMecaBundle];
    } else {
        const [_, stem] = dirAndStem(file);
        return `${stem}${kMecaSuffix}`;
    }
};
const createMecaBundle = async (mecaFile, context, outputDir, outputFiles, manuscriptConfig, otherOutputBundle)=>{
    const workingDir = globalTempContext().createDir();
    const srcDir = join2(workingDir, kSrcDirName);
    ensureDirSync(srcDir);
    const srcFiles = {};
    const addSrcFile = (absPath, type)=>{
        if (srcFiles[absPath] === undefined) {
            srcFiles[absPath] = type;
        }
    };
    let hasExplicitEnvironment = false;
    if (manuscriptConfig[kEnvironmentFiles]) {
        manuscriptConfig[kEnvironmentFiles].forEach((file)=>{
            const absPath = join2(context.dir, file);
            addSrcFile(absPath, kArticleSourceEnvironment);
            hasExplicitEnvironment = true;
        });
    }
    const srcType = (path)=>{
        return !hasExplicitEnvironment && isReesEnvronmentFile(path) || isDevContainerFile(path) ? kArticleSourceEnvironment : kArticleSource;
    };
    const skip = [
        kSkipHidden,
        /\.DS_Store/
    ];
    const projType = projectType(context.config?.project?.[kProjectType]);
    if (projType.outputDir) {
        skip.push(RegExp(`^${join2(context.dir, projType.outputDir)}[\/\\\\]`));
        skip.push(RegExp(`[\/\\\\]${projType.outputDir}[\/\\\\]`));
        engineIgnoreDirs().map((ignore)=>skip.push(globToRegExp2(join2(context.dir, ignore) + SEPARATOR2)));
    }
    let gitFiles = await lsFiles(context.dir);
    if (gitFiles) {
        const unstagedDeletes = await lsFiles(context.dir, [
            "--deleted"
        ]);
        if (unstagedDeletes) {
            gitFiles = gitFiles.filter((file)=>{
                return !unstagedDeletes.includes(file);
            });
        }
        for (const file of gitFiles){
            addSrcFile(join2(context.dir, file), srcType(file));
        }
    } else {
        for (const walkEntry of walkSync(context.dir, {
            skip
        })){
            if (walkEntry.isFile) {
                addSrcFile(walkEntry.path, srcType(walkEntry.path));
            }
        }
    }
    const sourceFiles = [];
    const sourceZipFiles = [];
    const copySrcFile = (file, type)=>{
        const relPath = join2(kSrcDirName, relative2(context.dir, file));
        const targetPath = join2(workingDir, relPath);
        ensureDirSync(dirname2(targetPath));
        Deno.copyFileSync(file, targetPath);
        const item = toMecaItem(relPath, type);
        sourceFiles.push(item);
        sourceZipFiles.push(relPath);
    };
    const srcDirMetaItem = {
        type: kSrcDirMecaType,
        instance: {
            mediaType: "application/x-directory",
            href: kSrcDirName
        }
    };
    for (const path of Object.keys(srcFiles)){
        const type = srcFiles[path];
        copySrcFile(path, type);
    }
    const filters = [
        isPdfOutput,
        isDocxOutput
    ];
    const articleRenderings = outputFiles.filter((outputFile)=>{
        return filters.some((filter)=>{
            return filter(outputFile.format.identifier["base-format"] || "html");
        });
    });
    let jatsArticle;
    for (const outputFile of outputFiles.reverse()){
        if (isJatsOutput(outputFile.format.pandoc)) {
            const input = await inputFileForOutputFile(context, outputFile.file);
            if (input) {
                if (relative2(context.dir, input.file) === manuscriptConfig.article) {
                    jatsArticle = outputFile;
                    break;
                }
            }
        }
    }
    if (jatsArticle) {
        const toWorkingDir = (input, outputRelative, move = false)=>{
            const target = join2(workingDir, outputRelative);
            const targetDir = dirname2(target);
            ensureDirSync(targetDir);
            if (move) {
                moveSync(input, target);
            } else {
                copySync(input, target, {
                    overwrite: true
                });
            }
            return outputRelative;
        };
        const articleRenderingPaths = articleRenderings.map((out)=>{
            return toWorkingDir(out.file, relative2(outputDir, out.file), false);
        });
        const articlePath = toWorkingDir(jatsArticle.file, relative2(outputDir, jatsArticle?.file), false);
        const manuscriptResources = [];
        const manuscriptZipFiles = [];
        if (jatsArticle.supporting) {
            __VIRTUAL_FILE181(jatsArticle.supporting).forEach((file)=>{
                const relPath = isAbsolute2(file) ? relative2(outputDir, file) : file;
                const absPath = isAbsolute2(file) ? file : join2(outputDir, file);
                const workingPath = toWorkingDir(absPath, relPath, false);
                const items = mecaItemsForPath(workingDir, workingPath, "manuscript");
                manuscriptResources.push(...items);
                manuscriptZipFiles.push(workingPath);
            });
        }
        if (otherOutputBundle) {
            if (otherOutputBundle.manuscript) {
                const relativePath = toWorkingDir(otherOutputBundle.manuscript, relative2(outputDir, otherOutputBundle.manuscript), false);
                articleRenderingPaths.push(relativePath);
            }
            for (const otherSupporting of otherOutputBundle.supporting){
                const relativePath = toWorkingDir(otherSupporting, relative2(outputDir, otherSupporting), false);
                const isDir = Deno.statSync(otherSupporting).isDirectory;
                const otherItems = mecaItemsForPath(workingDir, relativePath, "manuscript", isDir);
                manuscriptResources.push(...otherItems);
                manuscriptZipFiles.push(relativePath);
            }
        }
        const msg = (count, nameSing, namePlur)=>{
            if (count === 1) {
                info(`  ${count} ${nameSing}`);
            } else if (count > 1) {
                info(`  ${count} ${namePlur}`);
            }
        };
        msg(1 + manuscriptResources.length + articleRenderingPaths.length, "article file", "article files");
        msg(Object.keys(srcFiles).length, "source file", "source files");
        const resources = [];
        resources.push(...jatsArticle.resources);
        if (context.config?.project.resources) {
            resources.push(...context.config?.project.resources);
        }
        const notebooks = manuscriptConfig.notebooks;
        notebooks.forEach((notebook)=>{
            resources.push(notebook.notebook);
        });
        msg(notebooks.length, "notebook", "notebooks");
        resources.forEach((file)=>{
            const relPath = isAbsolute2(file) ? relative2(context.dir, file) : file;
            const absPath = isAbsolute2(file) ? file : join2(context.dir, file);
            const workingPath = toWorkingDir(absPath, relPath, false);
            manuscriptResources.push(toMecaItem(relPath, kManuscriptSupportingFile));
            manuscriptZipFiles.push(workingPath);
        });
        msg(resources.length, "other file", "other files");
        const articleItem = toMecaItem(articlePath, kArticleMetadata);
        const renderedItems = articleRenderingPaths.map((path)=>{
            return toMecaItem(path, kManuscript);
        });
        const manifest = {
            version: kMecaVersion,
            items: [
                articleItem,
                ...renderedItems,
                ...manuscriptResources,
                ...sourceFiles,
                srcDirMetaItem
            ]
        };
        info("");
        const manifestFile = "manifest.xml";
        const manifestXML = toXml(manifest);
        Deno.writeTextFileSync(join2(workingDir, manifestFile), manifestXML);
        const filesToZip = __VIRTUAL_FILE181([
            manifestFile,
            articlePath,
            ...articleRenderingPaths,
            ...manuscriptZipFiles,
            ...sourceZipFiles
        ]);
        const zipResult = await zip(filesToZip, mecaFile, {
            cwd: workingDir
        });
        if (zipResult.success) {
            return join2(workingDir, mecaFile);
        } else {
            throw new Error(`An error occurred while attempting to generate MECA archive.\n${zipResult.stderr}`);
        }
    }
};
const toMecaItem = (href, type)=>{
    const mediaType = contentType(href) || "application/octet-stream";
    return {
        type,
        instance: {
            href,
            mediaType
        }
    };
};
const mecaItemsForPath = (basePath, relPath, type, isDir)=>{
    const path = join2(basePath, relPath);
    if (isDir === true || Deno.statSync(path).isDirectory) {
        const items = [];
        for (const subPath of Deno.readDirSync(path)){
            if (subPath.isDirectory) {
                items.push(...mecaItemsForPath(basePath, join2(relPath, subPath.name), type, true));
            } else {
                const filePath = join2(relPath, subPath.name);
                items.push(toMecaItem(filePath, mecaType(filePath, type)));
            }
        }
        return items;
    } else {
        return [
            toMecaItem(relPath, mecaType(path, type))
        ];
    }
};
const mecaType = (_path, type)=>{
    if (type === "article") {
        return kArticleSupportingFile;
    } else {
        return kManuscriptSupportingFile;
    }
};
const notebookDescriptor = (nbPath, manuscriptConfig, project)=>{
    const notebooks = manuscriptConfig.notebooks;
    return notebooks.find((notebook)=>{
        return notebook.notebook === relative2(project.dir, nbPath);
    });
};
const isArticle = (file, project, manuscriptConfig)=>{
    const articlePath = isAbsolute2(file) ? join2(project.dir, manuscriptConfig.article) : manuscriptConfig.article;
    return file === articlePath;
};
const isArticleManuscript = (file, format, project, manuscriptConfig)=>{
    return isArticle(file, project, manuscriptConfig) && format.render[kNotebookViewStyle] !== "notebook";
};
const computeProjectArticleFile = (projectDir, config)=>{
    let defaultRenderFile = undefined;
    if (config.article) {
        defaultRenderFile = config.article;
    } else {
        const defaultArticleFiles = [
            "index.qmd",
            "index.ipynb"
        ];
        const defaultArticleFile = defaultArticleFiles.find((file)=>{
            return existsSync(join2(projectDir, file));
        });
        if (defaultArticleFile !== undefined) {
            defaultRenderFile = defaultArticleFile;
        } else {
            throw new Error("Unable to determine the root input document for this manuscript. Please specify an `article` in your `_quarto.yml` file.");
        }
    }
    return defaultRenderFile;
};
const codeHintRegexes = [
    /`+{[^\.]+.*}/,
    /.*"cell_type"\s*:\s*"code".*/
];
const hasComputations = async (file)=>{
    const reader = await Deno.open(file);
    try {
        for await (const line of readLines(reader)){
            if (line) {
                if (codeHintRegexes.find((regex)=>{
                    return regex.exec(line);
                })) {
                    return true;
                }
            }
        }
        return false;
    } finally{
        reader.close();
    }
};
const manuscriptRenderer = (options, context)=>{
    const renderCompletions = [];
    const renderedFiles = [];
    const nbContext = options.services.notebook;
    const articleOutputFiles = {};
    const manuscriptConfig = context.config?.[kManuscriptType] || {};
    const isNotebook = (path)=>{
        return !isArticle(path, context, manuscriptConfig);
    };
    const pandocRenderNb = async (input, parentOutputFiles, executedFile, project, isArticle, quiet)=>{
        const displayPath = relative2(project.dir, input);
        const progressMessage = (msg)=>{
            if (!quiet) {
                logProgress(`${msg} [${displayPath}]`);
            }
        };
        if (isJatsOutput(executedFile.context.format.pandoc)) {
            progressMessage("Rendering JATS embedded notebook");
            const resolvedExecutedFile = nbContext.resolve(input, kJatsSubarticle1, executedFile);
            return [
                {
                    completion: await renderPandoc(resolvedExecutedFile, true),
                    cleanup: !isArticle,
                    contribute: kJatsSubarticle1
                }
            ];
        } else if (isHtmlOutput(executedFile.context.format.pandoc, true)) {
            const result1 = [];
            const notebook = nbContext.get(input, context);
            if (isQmdFile(input) && (!notebook || !notebook[kQmdIPynb])) {
                progressMessage("Rendering qmd embeds");
                const qmdExecuted = nbContext.resolve(input, kQmdIPynb, executedFile);
                result1.push({
                    completion: await renderPandoc(qmdExecuted, true),
                    cleanup: true,
                    contribute: kQmdIPynb
                });
            }
            let downloadHref;
            if (!notebook || !notebook[kRenderedIPynb]) {
                progressMessage("Rendering output notebook");
                const ipynbExecutedFile = nbContext.resolve(input, kRenderedIPynb, executedFile);
                downloadHref = outputFile2(input);
                result1.push({
                    completion: await renderPandoc(ipynbExecutedFile, true),
                    cleanup: !isArticle,
                    contribute: kRenderedIPynb
                });
            }
            progressMessage("Rendering HTML preview");
            let title;
            const nbDescriptor = notebookDescriptor(input, manuscriptConfig, context);
            if (nbDescriptor) {
                title = nbDescriptor.title;
                downloadHref = nbDescriptor["download-url"];
            }
            if (!title) {
                const inputIndex = await readBaseInputIndex(input, context);
                if (inputIndex) {
                    title = inputIndex.title;
                }
            }
            const dirOffset = relative2(dirname2(input), context.dir);
            const index = join2(dirOffset, "index.html");
            const notebookMetadata = {
                title: title || basename2(input),
                filename: basename2(input),
                backHref: parentOutputFiles["html"] || index,
                downloadHref: downloadHref || basename2(input),
                downloadFile: basename2(input)
            };
            const resolvedExecutedFile = nbContext.resolve(input, kHtmlPreview, executedFile, notebookMetadata);
            result1.push({
                completion: await renderPandoc(resolvedExecutedFile, true),
                cleanup: !isArticle,
                contribute: kHtmlPreview
            });
            return result1;
        }
    };
    return {
        onFilterContexts: (file, contexts, _files, _options)=>{
            const isValidNotebookOutput = (to)=>{
                return [
                    isJatsOutput,
                    (format)=>{
                        return isHtmlOutput(format, true);
                    }
                ].find((fn)=>{
                    return fn(to);
                });
            };
            if (isNotebook(file)) {
                const outContexts = {};
                const allowedFormats = Object.keys(contexts).filter(isValidNotebookOutput);
                for (const allowedFormat of allowedFormats || []){
                    outContexts[allowedFormat] = contexts[allowedFormat];
                }
                return outContexts;
            } else {
                Object.keys(contexts).forEach((fmt)=>{
                    const outputFile = contexts[fmt].format.pandoc[kOutputFile];
                    if (outputFile) {
                        articleOutputFiles[fmt] = outputFile;
                    }
                });
            }
            return contexts;
        },
        onBeforeExecute: (_format)=>{
            return {};
        },
        onRender: async (_format, executedFile, quiet)=>{
            const target = executedFile.context.target;
            if (isArticle(target.source, context, manuscriptConfig)) {
                if (await hasComputations(target.source)) {
                    const renderedNb = await pandocRenderNb(target.source, articleOutputFiles, executedFile, context, true, quiet);
                    if (renderedNb) {
                        renderCompletions.push(...renderedNb);
                    }
                }
                renderCompletions.push({
                    completion: await renderPandoc(executedFile, quiet)
                });
            } else {
                const renderedNb = await pandocRenderNb(target.source, articleOutputFiles, executedFile, context, false, quiet);
                if (renderedNb) {
                    renderCompletions.push(...renderedNb);
                } else {
                    throw new InternalError("Manuscript asked to render a notebook to an unsupported format.");
                }
            }
        },
        onPostProcess: async (renderedFormats, projectContext)=>{
            if (projectContext === undefined) {
                throw new InternalError("Manuscript pandoc rendered is being used without a project context - this is not allowed.");
            }
            let manuscriptCompletion = renderCompletions.shift();
            while(manuscriptCompletion){
                const renderedFile = await manuscriptCompletion.completion.complete(renderedFormats, manuscriptCompletion.cleanup);
                const contributeNotebook = (renderedFile, renderType)=>{
                    const nbAbsPath = join2(projectContext.dir, renderedFile.input);
                    nbContext.addRendering(nbAbsPath, renderType, renderedFile, context);
                };
                if (manuscriptCompletion.contribute) {
                    contributeNotebook(renderedFile, manuscriptCompletion.contribute);
                    if (manuscriptCompletion.contribute !== kJatsSubarticle1) {
                        renderedFiles.unshift(renderedFile);
                    }
                } else {
                    renderedFiles.unshift(renderedFile);
                }
                manuscriptCompletion = renderCompletions.shift();
            }
        },
        onComplete: async ()=>{
            const files = await Promise.resolve(renderedFiles);
            return {
                files
            };
        }
    };
};
const kTitleBlockStyle = "title-block-style";
const kTitleBlockBanner = "title-block-banner";
const ktitleBlockColor = "title-block-banner-color";
const kTitleBlockCategories = "title-block-categories";
function documentTitleScssLayer(format) {
    if (format.metadata[kTitleBlockStyle] === false || format.metadata[kTitleBlockStyle] === "none" || format.metadata[kTitleBlockStyle] === "plain") {
        return undefined;
    } else if (format.metadata[kTitleBlockStyle] === "manuscript") {
        const titleBlockScss = formatResourcePath("html", join2("templates", "title-block.scss"));
        return sassLayer(titleBlockScss);
    } else {
        const titleBlockScss = formatResourcePath("html", join2("templates", "title-block.scss"));
        return sassLayer(titleBlockScss);
    }
}
function documentTitleMetadata(format) {
    if (format.metadata[kTitleBlockStyle] !== false && format.metadata[kTitleBlockStyle] !== "none" && format.metadata[kDateFormat] === undefined) {
        return {
            [kDateFormat]: "long"
        };
    } else {
        return undefined;
    }
}
function documentTitleIncludeInHeader(input, format, temp) {
    const headingVars = [];
    const containerVars = [];
    const banner = format.metadata[kTitleBlockBanner];
    if (banner) {
        const titleBlockColor = titleColor(format.metadata[ktitleBlockColor]);
        if (titleBlockColor) {
            const color = `color: ${titleBlockColor};`;
            headingVars.push(color);
            containerVars.push(color);
        }
        if (banner === true) {} else if (isBannerImage(input, banner)) {
            containerVars.push(`background-image: url(${banner});`);
            containerVars.push(`background-size: cover;`);
        } else {
            containerVars.push(`background: ${banner};`);
        }
    }
    if (headingVars.length || containerVars.length) {
        const styles = [
            "<style>"
        ];
        if (headingVars.length) {
            styles.push(`
      .quarto-title-block .quarto-title-banner h1,
      .quarto-title-block .quarto-title-banner h2,
      .quarto-title-block .quarto-title-banner h3,
      .quarto-title-block .quarto-title-banner h4,
      .quarto-title-block .quarto-title-banner h5,
      .quarto-title-block .quarto-title-banner h6
      {
        ${headingVars.join("\n")}
      }`);
        }
        if (containerVars.length) {
            styles.push(`
      .quarto-title-block .quarto-title-banner {
        ${containerVars.join("\n")}
      }`);
        }
        styles.push("</style>");
        const file = temp.createFile({
            suffix: ".css"
        });
        Deno.writeTextFileSync(file, styles.join("\n"));
        return file;
    }
}
function documentTitlePartial(format) {
    if (format.metadata[kTitleBlockStyle] === false || format.metadata[kTitleBlockStyle] === "none") {
        return {
            partials: [],
            templateParams: {}
        };
    } else {
        const partials = [];
        const templateParams = {};
        templateParams[kTitleBlockCategories] = format.metadata[kTitleBlockCategories] !== false ? "true" : "";
        const banner = format.metadata[kTitleBlockBanner];
        const manuscriptTitle = format.metadata[kTitleBlockStyle] === "manuscript";
        partials.push("_title-meta-author.html");
        partials.push("title-metadata.html");
        if (manuscriptTitle) {
            partials.push("manuscript/title-block.html");
            partials.push("manuscript/title-metadata.html");
        } else if (banner) {
            partials.push("banner/title-block.html");
        } else {
            partials.push("title-block.html");
        }
        if (banner || manuscriptTitle) {
            const tocLeft = format.metadata[kTocLocation] === "left";
            if (tocLeft) {
                templateParams["banner-header-class"] = "toc-left";
            }
        }
        return {
            partials: partials.map((partial)=>{
                return formatResourcePath("html", join2("templates", partial));
            }),
            templateParams
        };
    }
}
function processDocumentTitle(input, format, _flags, doc) {
    const resources = [];
    const banner = format.metadata[kTitleBlockBanner];
    const manuscriptTitle = format.metadata[kTitleBlockStyle] === "manuscript";
    if (banner || manuscriptTitle) {
        const headerEl = doc.getElementById("title-block-header");
        const contentEl = doc.getElementById("quarto-content");
        if (contentEl && headerEl) {
            headerEl.remove();
            contentEl.parentElement?.insertBefore(headerEl, contentEl);
        }
        const mainEl = doc.querySelector("main.content");
        mainEl?.classList.add("quarto-banner-title-block");
        if (isBannerImage(input, banner)) {
            resources.push(banner);
        }
        const quartoHeaderEl = doc.getElementById("quarto-header");
        if (quartoHeaderEl) {
            quartoHeaderEl.classList.add("quarto-banner");
        }
    }
    return resources;
}
function isBannerImage(input, banner) {
    if (typeof banner === "string") {
        let path;
        if (isAbsolute2(banner)) {
            path = banner;
        } else {
            path = join2(dirname2(input), banner);
        }
        return existsSync(path);
    } else {
        return false;
    }
}
const titleColor = (block)=>{
    if (block === "body" || block === "body-bg") {
        return undefined;
    } else {
        return block;
    }
};
const kMecaIcon = "archive";
const kOutputDir = "_manuscript";
const kTexOutputBundle = "tex-bundle";
const manuscriptProjectType = {
    type: kManuscriptType,
    libDir: "site_libs",
    config: async (project, config, flags)=>{
        const projectDir = project.dir;
        const manuscriptConfig = config[kManuscriptType] || {};
        if (manuscriptConfig[kResources]) {
            config.project.resources = config.project.resources || [];
            config.project.resources = Array.isArray(config.project.resources) ? config.project.resources : [
                config.project.resources
            ];
            if (Array.isArray(manuscriptConfig[kResources])) {
                config.project.resources.push(...manuscriptConfig[kResources]);
            } else {
                config.project.resources.push(manuscriptConfig[kResources]);
            }
        }
        const language = await formatLanguage(config, config[kLanguageDefaults], flags);
        const inputs = await projectInputFiles(project, config);
        const article = computeProjectArticleFile(projectDir, manuscriptConfig);
        const notebooks = [];
        const explicitNotebooks = manuscriptConfig[kNotebooks];
        if (explicitNotebooks) {
            resolveNotebookDescriptors(explicitNotebooks, true).forEach((nb)=>{
                notebooks.push(nb);
            });
        } else {
            const inputNotebooks = inputs.files.map((input)=>{
                return relative2(projectDir, input);
            }).filter((file)=>{
                if (file === article) {
                    return false;
                }
                const excludeSuffixes = [
                    ".out.ipynb",
                    ".embed.ipynb"
                ];
                if (excludeSuffixes.some((suffix)=>{
                    return file.endsWith(suffix);
                })) {
                    return false;
                }
                if (file.match(/\.embed\./)) {
                    return false;
                }
                return true;
            });
            if (inputNotebooks) {
                resolveNotebookDescriptors(inputNotebooks).forEach((nb)=>{
                    notebooks.push(nb);
                });
            }
        }
        config.project.render = [
            ...Object.values(notebooks).map((nb)=>nb.notebook),
            article
        ];
        let count = 0;
        const jatsNotebooks = Object.values(notebooks).map((notebookDesc)=>{
            return {
                input: join2(projectDir, notebookDesc.notebook),
                token: `nb-${++count}`,
                render: true
            };
        });
        if (await hasComputations1(join2(projectDir, article))) {
            if (!notebooks.find((nb)=>{
                return nb.notebook === article;
            })) {
                notebooks.unshift({
                    notebook: article,
                    title: language[kArticleNotebookLabel],
                    order: 9999
                });
            }
            jatsNotebooks.unshift({
                input: join2(projectDir, article),
                token: `nb-article`,
                render: true
            });
        }
        config[kQuartoInternal] = {
            [kSubArticles]: jatsNotebooks
        };
        const userConfig = manuscriptConfig[kEnvironmentFiles];
        const environmentFiles = userConfig !== undefined ? Array.isArray(userConfig) ? userConfig : [
            userConfig
        ] : undefined;
        const mecaFileOutput = mecaFileName(article, manuscriptConfig);
        const resolvedManuscriptOptions = {
            ...manuscriptConfig,
            article,
            notebooks: notebooks,
            mecaFile: mecaFileOutput,
            [kEnvironmentFiles]: environmentFiles
        };
        config[kManuscriptType] = resolvedManuscriptOptions;
        config[kEcho] = false;
        config[kWarning] = false;
        const previewOptions = {
            back: true
        };
        config[kNotebookPreviewOptions] = previewOptions;
        config[kTheme] = "cosmo";
        config[kTitleBlockStyle] = "manuscript";
        config[kLightbox] = "auto";
        return config;
    },
    create: (title)=>{
        const resourceDir = resourcePath(join2("projects", "manuscript"));
        return {
            configTemplate: join2(resourceDir, "templates", "_quarto.ejs.yml"),
            resourceDir,
            scaffold: ()=>[
                    {
                        name: "index",
                        content: [
                            "---",
                            `title: ${title}`,
                            `authors:`,
                            `  - name: Norah Jones`,
                            `    affiliation: The University`,
                            `    roles: writing`,
                            `    corresponding: true`,
                            `bibliography: references.bib`,
                            "---",
                            "",
                            "## Section",
                            "This is a simple placeholder for the manuscript's main document [@knuth84]."
                        ].join("\n")
                    }
                ],
            supporting: [
                "references.bib"
            ]
        };
    },
    pandocRenderer: manuscriptRenderer,
    outputDir: kOutputDir,
    outputFile: (input, format, project)=>{
        const manuscriptConfig = project.config?.[kManuscriptType];
        if (!isArticleManuscript(input, format, project, manuscriptConfig) && isHtmlOutput(format.pandoc)) {
            return outputFile1(input);
        } else {
            return undefined;
        }
    },
    cleanOutputDir: true,
    incrementalFormatPreviewing: true,
    filterParams: async (options)=>{
        if (options.project) {
            const filterParams = {};
            const manuscriptConfig = options.project.config?.[kManuscriptType];
            if (manuscriptConfig) {
                let baseUrl = manuscriptConfig[kManuscriptUrl];
                if (baseUrl === undefined) {
                    const ghContext = await gitHubContext(options.project.dir);
                    baseUrl = ghContext.siteUrl;
                }
                if (baseUrl) {
                    filterParams[kManuscriptUrl] = baseUrl;
                }
            }
            if (options.format.render[kNotebookLinks] !== undefined) {
                filterParams[kNotebookLinks] = options.format.render[kNotebookLinks];
            }
            return filterParams;
        } else {
            throw new InternalError("Filters params being requested for project without providing a project.");
        }
    },
    filterFormat: (source, format, project)=>{
        if (project) {
            const manuscriptConfig = project.config?.[kManuscriptType];
            const formats = project.config?.format ? Object.keys(project.config?.format) : [];
            if (isArticleManuscript(source, format, project, manuscriptConfig)) {
                if (shouldMakeMecaBundle(formats, manuscriptConfig)) {
                    if (format.render[kFormatLinks] !== false) {
                        const links = [];
                        if (typeof format.render[kFormatLinks] !== "boolean") {
                            links.push(...format.render[kFormatLinks] || []);
                        }
                        links.push({
                            text: format.language[kManuscriptMecaBundle] || "MECA Bundle",
                            href: mecaFileName(source, manuscriptConfig),
                            icon: kMecaIcon,
                            attr: {
                                "data-meca-link": "true"
                            },
                            order: 1000
                        });
                        format.render[kFormatLinks] = links;
                    }
                }
                if (format.metadata[kGoogleScholar] !== false) {
                    format.metadata[kGoogleScholar] = true;
                }
                if (isHtmlOutput(format.pandoc, true)) {
                    if (format.pandoc[kToc] !== false) {
                        format.pandoc[kToc] = true;
                    }
                    if (format.pandoc[kOutputFile] === undefined) {
                        format.pandoc[kOutputFile] = "index.html";
                    }
                    if (format.metadata[kTocLocation] === undefined) {
                        format.metadata[kTocLocation] = "left";
                    }
                }
            }
            const userEcho = format.execute.echo;
            const userWarning = format.execute.warning;
            const clearVal = [];
            const removeVal = [];
            format.execute.echo = false;
            format.execute.warning = false;
            format.render[kKeepHidden] = true;
            if (!isArticle(source, project, manuscriptConfig) && isQmdFile(source)) {
                format.render[kIpynbProduceSourceNotebook] = true;
            }
            if (userEcho === true) {
                clearVal.push("code");
            } else {
                removeVal.push("code");
            }
            if (userWarning === true) {
                clearVal.push("warning");
            } else {
                removeVal.push("warning");
            }
            const resolveValue = (vals)=>{
                if (vals.length === 0) {
                    return "none";
                } else if (vals.length === 1) {
                    return vals[0];
                } else {
                    return "all";
                }
            };
            format.metadata[kClearHiddenClasses] = resolveValue(clearVal);
            format.metadata[kRemoveHidden] = resolveValue(removeVal);
            format.render[kNotebookPreserveCells] = true;
            format.metadata[kUnrollMarkdownCells] = true;
            return format;
        } else {
            throw new InternalError("Filter format being called for project without providing a project.");
        }
    },
    formatExtras: async (context, source, _flags, format, _services)=>{
        const manuscriptConfig = context.config?.[kManuscriptType];
        const extras = {};
        extras.metadata = {};
        const isArticle = isArticleManuscript(source, format, context, manuscriptConfig);
        if (isArticle && isHtmlOutput(format.pandoc)) {
            extras.metadata[kCodeLinks] = manuscriptConfig[kCodeLinks];
            const notebooks = manuscriptConfig.notebooks || [];
            const orderedNbs = [];
            for (const notebook of notebooks){
                const createTitle = async ()=>{
                    const target = await resolveInputTarget(context, relative2(context.dir, notebook.notebook), false);
                    if (target) {
                        return target.title;
                    }
                };
                orderedNbs.push({
                    ...notebook,
                    title: notebook.title || await createTitle()
                });
            }
            extras[kNotebooks] = orderedNbs;
        } else if (isArticle && isLatexOutput(format.pandoc)) {
            if (isLatexOutput(format.pandoc)) {
                format.render[kKeepTex] = true;
            }
        }
        extras.html = extras.html || {};
        extras.html[kHtmlPostprocessors] = [
            async (doc, _options)=>{
                await resolveProjectInputLinks(source, context, doc);
                return Promise.resolve(kHtmlEmptyPostProcessResult);
            }
        ];
        if (!isArticle) {
            extras.html[kDependencies] = [
                {
                    name: "manuscript-notebook",
                    scripts: [
                        {
                            name: "headroom.min.js",
                            path: resourcePath(`projects/website/navigation/headroom.min.js`)
                        }
                    ]
                }
            ];
        }
        return Promise.resolve(extras);
    },
    previewSkipUnmodified: true,
    renderResultFinalOutput: (renderResults)=>{
        if (renderResults.context) {
            const manuscriptConfig = renderResults.context.config?.[kManuscriptType];
            const articleResults = renderResults.files.filter((file)=>{
                return file.input === manuscriptConfig.article;
            });
            if (articleResults.length === 1) {
                return articleResults[0];
            } else if (articleResults.length > 1) {
                const preferredFormats = [
                    "html",
                    "pdf",
                    "docx"
                ];
                const sorted = __VIRTUAL_FILE217(articleResults, (item)=>{
                    const formatStr = item.format.identifier["base-format"];
                    if (formatStr) {
                        const index = preferredFormats.indexOf(formatStr);
                        if (index > -1) {
                            if (item.format.identifier[kExtensionName]) {
                                return index * 2;
                            } else {
                                return index * 2 + 1;
                            }
                        }
                    }
                    return Number.MAX_SAFE_INTEGER;
                }, "asc");
                return sorted[0];
            }
            return undefined;
        }
    },
    beforeMoveOutput: async (context, renderedFiles)=>{
        let outBundle;
        for (const renderedFile of renderedFiles){
            const format = renderedFile.format;
            if (isLatexOutput(format.pandoc) && format.render[kKeepTex]) {
                outBundle = createTexOutputBundle(renderedFile, context);
            }
        }
        if (outBundle) {
            return {
                [kTexOutputBundle]: outBundle
            };
        }
    },
    postRender: async (context, _incremental, outputFiles, moveOutputResult)=>{
        const manuscriptConfig = context.config?.[kManuscriptType];
        if (shouldMakeMecaBundle(outputFiles.map((file)=>file.format), manuscriptConfig) && outputFiles.length > 0) {
            let outBundle;
            if (moveOutputResult) {
                outBundle = moveOutputResult[kTexOutputBundle];
            }
            const language = outputFiles[0].format.language;
            logProgress(`Creating ${language[kManuscriptMecaBundle]}`);
            const mecaFileName = manuscriptConfig.mecaFile;
            const mecaBundle = await createMecaBundle(mecaFileName, context, projectOutputDir(context), outputFiles, manuscriptConfig, outBundle);
            if (mecaBundle) {
                const target = projectOutputDir(context);
                Deno.copyFileSync(mecaBundle, join2(target, mecaFileName));
            }
        }
        return Promise.resolve();
    }
};
const codeHintRegexes1 = [
    /`+{[^\.]+.*}/,
    /.*"cell_type"\s*:\s*"code".*/
];
const hasComputations1 = async (file)=>{
    const reader = await Deno.open(file);
    try {
        for await (const line of readLines(reader)){
            if (line) {
                if (codeHintRegexes1.find((regex)=>{
                    return regex.exec(line);
                })) {
                    return true;
                }
            }
        }
        return false;
    } finally{
        reader.close();
    }
};
const resolveNotebookDescriptor = (nb, order)=>{
    if (typeof nb === "string") {
        nb = {
            notebook: nb,
            order
        };
    }
    return nb;
};
const resolveNotebookDescriptors = (nbs, orderNotebooks = false)=>{
    const resolvedNbs = [];
    let order = 0;
    for (const nb of nbs){
        resolvedNbs.push(resolveNotebookDescriptor(nb, orderNotebooks ? order : undefined));
        order++;
    }
    return resolvedNbs;
};
const kTexOutDir = "_tex";
const createTexOutputBundle = (outputFile, context)=>{
    const format = outputFile.format;
    const outDir = projectOutputDir(context);
    const texDirAbs = join2(outDir, `${kTexOutDir}`);
    ensureDirSync(texDirAbs);
    if (format.pandoc["output-file"]) {
        const baseDir = join2(context.dir, dirname2(outputFile.input));
        const texInputFile = join2(baseDir, format.pandoc["output-file"]);
        const texInputDir = dirname2(texInputFile);
        const texOutputFile = join2(texDirAbs, format.pandoc["output-file"]);
        const textOutputDir = dirname2(texOutputFile);
        Deno.copyFileSync(texInputFile, texOutputFile);
        Deno.removeSync(texInputFile);
        const texBundle = {
            manuscript: texOutputFile,
            supporting: []
        };
        if (outputFile.supporting) {
            const uniqSupporting = __VIRTUAL_FILE181(outputFile.supporting);
            for (const file of uniqSupporting){
                const supportingAbs = isAbsolute2(file) ? file : join2(texInputDir, file);
                const outPath = join2(texDirAbs, relative2(context.dir, supportingAbs));
                ensureDirSync(dirname2(outPath));
                copySync(supportingAbs, outPath, {
                    overwrite: true
                });
                Deno.removeSync(supportingAbs, {
                    recursive: true
                });
                texBundle.supporting.push(outPath);
            }
        }
        if (outputFile.resourceFiles) {
            const uniqResources = __VIRTUAL_FILE181(outputFile.resourceFiles);
            for (const file of uniqResources){
                const outPath = join2(texDirAbs, relative2(context.dir, file));
                ensureDirSync(dirname2(outPath));
                copySync(file, outPath, {
                    overwrite: true
                });
                texBundle.supporting.push(outPath);
            }
        }
        const docClass = format.metadata[kDocumentClass];
        const classFile = `${docClass}.cls`;
        const classFilePath = join2(texInputDir, classFile);
        if (existsSync(classFilePath)) {
            const outClassPath = join2(textOutputDir, classFile);
            copySync(classFilePath, outClassPath, {
                overwrite: true
            });
            texBundle.supporting.push(outClassPath);
        }
        if (format.metadata[kBibliography]) {
            const bibliographies = Array.isArray(format.metadata[kBibliography]) ? format.metadata[kBibliography] : [
                format.metadata[kBibliography]
            ];
            for (const bibligography of bibliographies){
                const bibPath = join2(context.dir, bibligography);
                const bibOutPath = join2(textOutputDir, bibligography);
                ensureDirSync(dirname2(bibOutPath));
                copySync(bibPath, bibOutPath, {
                    overwrite: true
                });
                texBundle.supporting.push(bibOutPath);
            }
        }
        const formatResources = format.render[kFormatResources];
        if (formatResources) {
            for (const formatResource of formatResources){
                const resourcePath = join2(context.dir, formatResource);
                const resourceOutPath = join2(textOutputDir, basename2(formatResource));
                if (!safeExistsSync(resourceOutPath)) {
                    copySync(resourcePath, resourceOutPath, {
                        overwrite: true
                    });
                    texBundle.supporting.push(resourceOutPath);
                }
            }
        }
        return texBundle;
    } else {
        throw new InternalError("Was expecting there to a Pandoc output file since we're rendering LaTeX");
    }
};
registerProjectType(bookProjectType);
registerProjectType(defaultProjectType);
registerProjectType(websiteProjectType);
registerProjectType(manuscriptProjectType);
const kProjectTypes = projectTypes();
const kProjectTypeAliases = projectTypeAliases();
const kProjectTypesAndAliases = [
    ...kProjectTypes,
    ...kProjectTypeAliases
];
const kExecutionEngines = executionEngines().reverse();
const kEditorTypes = [
    "source",
    "visual"
];
const createProjectCommand = new Command().name("create-project").description("Create a project for rendering multiple documents").arguments("[dir:string]").hidden().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:string>", "Default editor for project ('source' or 'visual')").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)=>{
    if (dir === undefined || 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 } = parseProjectType(options.type);
    const projectTemplate = options.template || template;
    if (kProjectTypesAndAliases.indexOf(type) === -1) {
        throw new Error(`Project type must be one of ${kProjectTypes.join(", ")}, but got "${type}".`);
    }
    const editorType = options.editor;
    if (editorType && !kEditorTypes.includes(editorType)) {
        throw new Error(`Editor type must be one of ${kEditorTypes.join(", ")}, but got "${editorType}".`);
    }
    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: editorType,
        venv: !!options.withVenv,
        condaenv: !!options.withCondaenv,
        envPackages,
        template: projectTemplate
    });
});
const osType1 = (()=>{
    const { Deno: Deno1 } = globalThis;
    if (typeof Deno1?.build?.os === "string") {
        return Deno1.build.os;
    }
    const { navigator } = globalThis;
    if (navigator?.appVersion?.includes?.("Win")) {
        return "windows";
    }
    return "linux";
})();
const isWindows4 = osType1 === "windows";
const CHAR_FORWARD_SLASH1 = 47;
function assertPath1(path) {
    if (typeof path !== "string") {
        throw new TypeError(`Path must be a string. Received ${JSON.stringify(path)}`);
    }
}
function isPosixPathSeparator2(code) {
    return code === 47;
}
function isPathSeparator1(code) {
    return isPosixPathSeparator2(code) || code === 92;
}
function isWindowsDeviceRoot1(code) {
    return code >= 97 && code <= 122 || code >= 65 && code <= 90;
}
function normalizeString1(path, allowAboveRoot, separator, isPathSeparator) {
    let res = "";
    let lastSegmentLength = 0;
    let lastSlash = -1;
    let dots = 0;
    let code;
    for(let i1 = 0, len = path.length; i1 <= len; ++i1){
        if (i1 < len) code = path.charCodeAt(i1);
        else if (isPathSeparator(code)) break;
        else code = CHAR_FORWARD_SLASH1;
        if (isPathSeparator(code)) {
            if (lastSlash === i1 - 1 || dots === 1) {} else if (lastSlash !== i1 - 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 = i1;
                        dots = 0;
                        continue;
                    } else if (res.length === 2 || res.length === 1) {
                        res = "";
                        lastSegmentLength = 0;
                        lastSlash = i1;
                        dots = 0;
                        continue;
                    }
                }
                if (allowAboveRoot) {
                    if (res.length > 0) res += `${separator}..`;
                    else res = "..";
                    lastSegmentLength = 2;
                }
            } else {
                if (res.length > 0) res += separator + path.slice(lastSlash + 1, i1);
                else res = path.slice(lastSlash + 1, i1);
                lastSegmentLength = i1 - lastSlash - 1;
            }
            lastSlash = i1;
            dots = 0;
        } else if (code === 46 && dots !== -1) {
            ++dots;
        } else {
            dots = -1;
        }
    }
    return res;
}
function _format1(sep, pathObject) {
    const dir = pathObject.dir || pathObject.root;
    const base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
    if (!dir) return base;
    if (base === sep) return dir;
    if (dir === pathObject.root) return dir + base;
    return dir + sep + base;
}
const WHITESPACE_ENCODINGS1 = {
    "\u0009": "%09",
    "\u000A": "%0A",
    "\u000B": "%0B",
    "\u000C": "%0C",
    "\u000D": "%0D",
    "\u0020": "%20"
};
function encodeWhitespace1(string) {
    return string.replaceAll(/[\s]/g, (c)=>{
        return WHITESPACE_ENCODINGS1[c] ?? c;
    });
}
function lastPathSegment1(path, isSep, start = 0) {
    let matchedNonSeparator = false;
    let end = path.length;
    for(let i1 = path.length - 1; i1 >= start; --i1){
        if (isSep(path.charCodeAt(i1))) {
            if (matchedNonSeparator) {
                start = i1 + 1;
                break;
            }
        } else if (!matchedNonSeparator) {
            matchedNonSeparator = true;
            end = i1 + 1;
        }
    }
    return path.slice(start, end);
}
function stripTrailingSeparators1(segment, isSep) {
    if (segment.length <= 1) {
        return segment;
    }
    let end = segment.length;
    for(let i1 = segment.length - 1; i1 > 0; i1--){
        if (isSep(segment.charCodeAt(i1))) {
            end = i1;
        } else {
            break;
        }
    }
    return segment.slice(0, end);
}
function stripSuffix1(name, suffix) {
    if (suffix.length >= name.length) {
        return name;
    }
    const lenDiff = name.length - suffix.length;
    for(let i1 = suffix.length - 1; i1 >= 0; --i1){
        if (name.charCodeAt(lenDiff + i1) !== suffix.charCodeAt(i1)) {
            return name;
        }
    }
    return name.slice(0, -suffix.length);
}
const sep = "\\";
const delimiter = ";";
function resolve3(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for(let i1 = pathSegments.length - 1; i1 >= -1; i1--){
        let path;
        const { Deno: Deno1 } = globalThis;
        if (i1 >= 0) {
            path = pathSegments[i1];
        } else if (!resolvedDevice) {
            if (typeof Deno1?.cwd !== "function") {
                throw new TypeError("Resolved a drive-letter-less path without a CWD.");
            }
            path = Deno1.cwd();
        } else {
            if (typeof Deno1?.env?.get !== "function" || typeof Deno1?.cwd !== "function") {
                throw new TypeError("Resolved a relative path without a CWD.");
            }
            path = Deno1.cwd();
            if (path === undefined || path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`) {
                path = `${resolvedDevice}\\`;
            }
        }
        assertPath1(path);
        const len = path.length;
        if (len === 0) continue;
        let rootEnd = 0;
        let device = "";
        let isAbsolute = false;
        const code = path.charCodeAt(0);
        if (len > 1) {
            if (isPathSeparator1(code)) {
                isAbsolute = true;
                if (isPathSeparator1(path.charCodeAt(1))) {
                    let j = 2;
                    let last = j;
                    for(; j < len; ++j){
                        if (isPathSeparator1(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        const firstPart = path.slice(last, j);
                        last = j;
                        for(; j < len; ++j){
                            if (!isPathSeparator1(path.charCodeAt(j))) break;
                        }
                        if (j < len && j !== last) {
                            last = j;
                            for(; j < len; ++j){
                                if (isPathSeparator1(path.charCodeAt(j))) break;
                            }
                            if (j === len) {
                                device = `\\\\${firstPart}\\${path.slice(last)}`;
                                rootEnd = j;
                            } else if (j !== last) {
                                device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                                rootEnd = j;
                            }
                        }
                    }
                } else {
                    rootEnd = 1;
                }
            } else if (isWindowsDeviceRoot1(code)) {
                if (path.charCodeAt(1) === 58) {
                    device = path.slice(0, 2);
                    rootEnd = 2;
                    if (len > 2) {
                        if (isPathSeparator1(path.charCodeAt(2))) {
                            isAbsolute = true;
                            rootEnd = 3;
                        }
                    }
                }
            }
        } else if (isPathSeparator1(code)) {
            rootEnd = 1;
            isAbsolute = 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 = `${path.slice(rootEnd)}\\${resolvedTail}`;
            resolvedAbsolute = isAbsolute;
        }
        if (resolvedAbsolute && resolvedDevice.length > 0) break;
    }
    resolvedTail = normalizeString1(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator1);
    return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
}
function normalize3(path) {
    assertPath1(path);
    const len = path.length;
    if (len === 0) return ".";
    let rootEnd = 0;
    let device;
    let isAbsolute = false;
    const code = path.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator1(code)) {
            isAbsolute = true;
            if (isPathSeparator1(path.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator1(path.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    const firstPart = path.slice(last, j);
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator1(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator1(path.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            return `\\\\${firstPart}\\${path.slice(last)}\\`;
                        } else if (j !== last) {
                            device = `\\\\${firstPart}\\${path.slice(last, j)}`;
                            rootEnd = j;
                        }
                    }
                }
            } else {
                rootEnd = 1;
            }
        } else if (isWindowsDeviceRoot1(code)) {
            if (path.charCodeAt(1) === 58) {
                device = path.slice(0, 2);
                rootEnd = 2;
                if (len > 2) {
                    if (isPathSeparator1(path.charCodeAt(2))) {
                        isAbsolute = true;
                        rootEnd = 3;
                    }
                }
            }
        }
    } else if (isPathSeparator1(code)) {
        return "\\";
    }
    let tail;
    if (rootEnd < len) {
        tail = normalizeString1(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator1);
    } else {
        tail = "";
    }
    if (tail.length === 0 && !isAbsolute) tail = ".";
    if (tail.length > 0 && isPathSeparator1(path.charCodeAt(len - 1))) {
        tail += "\\";
    }
    if (device === undefined) {
        if (isAbsolute) {
            if (tail.length > 0) return `\\${tail}`;
            else return "\\";
        } else if (tail.length > 0) {
            return tail;
        } else {
            return "";
        }
    } else if (isAbsolute) {
        if (tail.length > 0) return `${device}\\${tail}`;
        else return `${device}\\`;
    } else if (tail.length > 0) {
        return device + tail;
    } else {
        return device;
    }
}
function isAbsolute3(path) {
    assertPath1(path);
    const len = path.length;
    if (len === 0) return false;
    const code = path.charCodeAt(0);
    if (isPathSeparator1(code)) {
        return true;
    } else if (isWindowsDeviceRoot1(code)) {
        if (len > 2 && path.charCodeAt(1) === 58) {
            if (isPathSeparator1(path.charCodeAt(2))) return true;
        }
    }
    return false;
}
function join4(...paths) {
    const pathsCount = paths.length;
    if (pathsCount === 0) return ".";
    let joined;
    let firstPart = null;
    for(let i1 = 0; i1 < pathsCount; ++i1){
        const path = paths[i1];
        assertPath1(path);
        if (path.length > 0) {
            if (joined === undefined) joined = firstPart = path;
            else joined += `\\${path}`;
        }
    }
    if (joined === undefined) return ".";
    let needsReplace = true;
    let slashCount = 0;
    assert1(firstPart != null);
    if (isPathSeparator1(firstPart.charCodeAt(0))) {
        ++slashCount;
        const firstLen = firstPart.length;
        if (firstLen > 1) {
            if (isPathSeparator1(firstPart.charCodeAt(1))) {
                ++slashCount;
                if (firstLen > 2) {
                    if (isPathSeparator1(firstPart.charCodeAt(2))) ++slashCount;
                    else {
                        needsReplace = false;
                    }
                }
            }
        }
    }
    if (needsReplace) {
        for(; slashCount < joined.length; ++slashCount){
            if (!isPathSeparator1(joined.charCodeAt(slashCount))) break;
        }
        if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`;
    }
    return normalize3(joined);
}
function relative3(from, to) {
    assertPath1(from);
    assertPath1(to);
    if (from === to) return "";
    const fromOrig = resolve3(from);
    const toOrig = resolve3(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 i1 = 0;
    for(; i1 <= length; ++i1){
        if (i1 === length) {
            if (toLen > length) {
                if (to.charCodeAt(toStart + i1) === 92) {
                    return toOrig.slice(toStart + i1 + 1);
                } else if (i1 === 2) {
                    return toOrig.slice(toStart + i1);
                }
            }
            if (fromLen > length) {
                if (from.charCodeAt(fromStart + i1) === 92) {
                    lastCommonSep = i1;
                } else if (i1 === 2) {
                    lastCommonSep = 3;
                }
            }
            break;
        }
        const fromCode = from.charCodeAt(fromStart + i1);
        const toCode = to.charCodeAt(toStart + i1);
        if (fromCode !== toCode) break;
        else if (fromCode === 92) lastCommonSep = i1;
    }
    if (i1 !== length && lastCommonSep === -1) {
        return toOrig;
    }
    let out = "";
    if (lastCommonSep === -1) lastCommonSep = 0;
    for(i1 = fromStart + lastCommonSep + 1; i1 <= fromEnd; ++i1){
        if (i1 === fromEnd || from.charCodeAt(i1) === 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 toNamespacedPath1(path) {
    if (typeof path !== "string") return path;
    if (path.length === 0) return "";
    const resolvedPath = resolve3(path);
    if (resolvedPath.length >= 3) {
        if (resolvedPath.charCodeAt(0) === 92) {
            if (resolvedPath.charCodeAt(1) === 92) {
                const code = resolvedPath.charCodeAt(2);
                if (code !== 63 && code !== 46) {
                    return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
                }
            }
        } else if (isWindowsDeviceRoot1(resolvedPath.charCodeAt(0))) {
            if (resolvedPath.charCodeAt(1) === 58 && resolvedPath.charCodeAt(2) === 92) {
                return `\\\\?\\${resolvedPath}`;
            }
        }
    }
    return path;
}
function dirname3(path) {
    assertPath1(path);
    const len = path.length;
    if (len === 0) return ".";
    let rootEnd = -1;
    let end = -1;
    let matchedSlash = true;
    let offset = 0;
    const code = path.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator1(code)) {
            rootEnd = offset = 1;
            if (isPathSeparator1(path.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator1(path.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator1(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator1(path.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            return path;
                        }
                        if (j !== last) {
                            rootEnd = offset = j + 1;
                        }
                    }
                }
            }
        } else if (isWindowsDeviceRoot1(code)) {
            if (path.charCodeAt(1) === 58) {
                rootEnd = offset = 2;
                if (len > 2) {
                    if (isPathSeparator1(path.charCodeAt(2))) rootEnd = offset = 3;
                }
            }
        }
    } else if (isPathSeparator1(code)) {
        return path;
    }
    for(let i1 = len - 1; i1 >= offset; --i1){
        if (isPathSeparator1(path.charCodeAt(i1))) {
            if (!matchedSlash) {
                end = i1;
                break;
            }
        } else {
            matchedSlash = false;
        }
    }
    if (end === -1) {
        if (rootEnd === -1) return ".";
        else end = rootEnd;
    }
    return stripTrailingSeparators1(path.slice(0, end), isPosixPathSeparator2);
}
function basename3(path, suffix = "") {
    assertPath1(path);
    if (path.length === 0) return path;
    if (typeof suffix !== "string") {
        throw new TypeError(`Suffix must be a string. Received ${JSON.stringify(suffix)}`);
    }
    let start = 0;
    if (path.length >= 2) {
        const drive = path.charCodeAt(0);
        if (isWindowsDeviceRoot1(drive)) {
            if (path.charCodeAt(1) === 58) start = 2;
        }
    }
    const lastSegment = lastPathSegment1(path, isPathSeparator1, start);
    const strippedSegment = stripTrailingSeparators1(lastSegment, isPathSeparator1);
    return suffix ? stripSuffix1(strippedSegment, suffix) : strippedSegment;
}
function extname3(path) {
    assertPath1(path);
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path.length >= 2 && path.charCodeAt(1) === 58 && isWindowsDeviceRoot1(path.charCodeAt(0))) {
        start = startPart = 2;
    }
    for(let i1 = path.length - 1; i1 >= start; --i1){
        const code = path.charCodeAt(i1);
        if (isPathSeparator1(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 path.slice(startDot, end);
}
function format2(pathObject) {
    if (pathObject === null || typeof pathObject !== "object") {
        throw new TypeError(`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`);
    }
    return _format1("\\", pathObject);
}
function parse7(path) {
    assertPath1(path);
    const ret = {
        root: "",
        dir: "",
        base: "",
        ext: "",
        name: ""
    };
    const len = path.length;
    if (len === 0) return ret;
    let rootEnd = 0;
    let code = path.charCodeAt(0);
    if (len > 1) {
        if (isPathSeparator1(code)) {
            rootEnd = 1;
            if (isPathSeparator1(path.charCodeAt(1))) {
                let j = 2;
                let last = j;
                for(; j < len; ++j){
                    if (isPathSeparator1(path.charCodeAt(j))) break;
                }
                if (j < len && j !== last) {
                    last = j;
                    for(; j < len; ++j){
                        if (!isPathSeparator1(path.charCodeAt(j))) break;
                    }
                    if (j < len && j !== last) {
                        last = j;
                        for(; j < len; ++j){
                            if (isPathSeparator1(path.charCodeAt(j))) break;
                        }
                        if (j === len) {
                            rootEnd = j;
                        } else if (j !== last) {
                            rootEnd = j + 1;
                        }
                    }
                }
            }
        } else if (isWindowsDeviceRoot1(code)) {
            if (path.charCodeAt(1) === 58) {
                rootEnd = 2;
                if (len > 2) {
                    if (isPathSeparator1(path.charCodeAt(2))) {
                        if (len === 3) {
                            ret.root = ret.dir = path;
                            ret.base = "\\";
                            return ret;
                        }
                        rootEnd = 3;
                    }
                } else {
                    ret.root = ret.dir = path;
                    return ret;
                }
            }
        }
    } else if (isPathSeparator1(code)) {
        ret.root = ret.dir = path;
        ret.base = "\\";
        return ret;
    }
    if (rootEnd > 0) ret.root = path.slice(0, rootEnd);
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i1 = path.length - 1;
    let preDotState = 0;
    for(; i1 >= rootEnd; --i1){
        code = path.charCodeAt(i1);
        if (isPathSeparator1(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 = path.slice(startPart, end);
        }
    } else {
        ret.name = path.slice(startPart, startDot);
        ret.base = path.slice(startPart, end);
        ret.ext = path.slice(startDot, end);
    }
    ret.base = ret.base || "\\";
    if (startPart > 0 && startPart !== rootEnd) {
        ret.dir = path.slice(0, startPart - 1);
    } else ret.dir = ret.root;
    return ret;
}
function fromFileUrl3(url) {
    url = url instanceof URL ? url : new URL(url);
    if (url.protocol != "file:") {
        throw new TypeError("Must be a file URL.");
    }
    let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\");
    if (url.hostname != "") {
        path = `\\\\${url.hostname}${path}`;
    }
    return path;
}
function toFileUrl3(path) {
    if (!isAbsolute3(path)) {
        throw new TypeError("Must be an absolute path.");
    }
    const [, hostname, pathname] = path.match(/^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/);
    const url = new URL("file:///");
    url.pathname = encodeWhitespace1(pathname.replace(/%/g, "%25"));
    if (hostname != null && hostname != "localhost") {
        url.hostname = hostname;
        if (!url.hostname) {
            throw new TypeError("Invalid hostname.");
        }
    }
    return url;
}
const mod4 = {
    sep: sep,
    delimiter: delimiter,
    resolve: resolve3,
    normalize: normalize3,
    isAbsolute: isAbsolute3,
    join: join4,
    relative: relative3,
    toNamespacedPath: toNamespacedPath1,
    dirname: dirname3,
    basename: basename3,
    extname: extname3,
    format: format2,
    parse: parse7,
    fromFileUrl: fromFileUrl3,
    toFileUrl: toFileUrl3
};
const sep1 = "/";
const delimiter1 = ":";
function resolve4(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for(let i1 = pathSegments.length - 1; i1 >= -1 && !resolvedAbsolute; i1--){
        let path;
        if (i1 >= 0) path = pathSegments[i1];
        else {
            const { Deno: Deno1 } = globalThis;
            if (typeof Deno1?.cwd !== "function") {
                throw new TypeError("Resolved a relative path without a CWD.");
            }
            path = Deno1.cwd();
        }
        assertPath1(path);
        if (path.length === 0) {
            continue;
        }
        resolvedPath = `${path}/${resolvedPath}`;
        resolvedAbsolute = isPosixPathSeparator2(path.charCodeAt(0));
    }
    resolvedPath = normalizeString1(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator2);
    if (resolvedAbsolute) {
        if (resolvedPath.length > 0) return `/${resolvedPath}`;
        else return "/";
    } else if (resolvedPath.length > 0) return resolvedPath;
    else return ".";
}
function normalize4(path) {
    assertPath1(path);
    if (path.length === 0) return ".";
    const isAbsolute = isPosixPathSeparator2(path.charCodeAt(0));
    const trailingSeparator = isPosixPathSeparator2(path.charCodeAt(path.length - 1));
    path = normalizeString1(path, !isAbsolute, "/", isPosixPathSeparator2);
    if (path.length === 0 && !isAbsolute) path = ".";
    if (path.length > 0 && trailingSeparator) path += "/";
    if (isAbsolute) return `/${path}`;
    return path;
}
function isAbsolute4(path) {
    assertPath1(path);
    return path.length > 0 && isPosixPathSeparator2(path.charCodeAt(0));
}
function join5(...paths) {
    if (paths.length === 0) return ".";
    let joined;
    for(let i1 = 0, len = paths.length; i1 < len; ++i1){
        const path = paths[i1];
        assertPath1(path);
        if (path.length > 0) {
            if (!joined) joined = path;
            else joined += `/${path}`;
        }
    }
    if (!joined) return ".";
    return normalize4(joined);
}
function relative4(from, to) {
    assertPath1(from);
    assertPath1(to);
    if (from === to) return "";
    from = resolve4(from);
    to = resolve4(to);
    if (from === to) return "";
    let fromStart = 1;
    const fromEnd = from.length;
    for(; fromStart < fromEnd; ++fromStart){
        if (!isPosixPathSeparator2(from.charCodeAt(fromStart))) break;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 1;
    const toEnd = to.length;
    for(; toStart < toEnd; ++toStart){
        if (!isPosixPathSeparator2(to.charCodeAt(toStart))) break;
    }
    const toLen = toEnd - toStart;
    const length = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i1 = 0;
    for(; i1 <= length; ++i1){
        if (i1 === length) {
            if (toLen > length) {
                if (isPosixPathSeparator2(to.charCodeAt(toStart + i1))) {
                    return to.slice(toStart + i1 + 1);
                } else if (i1 === 0) {
                    return to.slice(toStart + i1);
                }
            } else if (fromLen > length) {
                if (isPosixPathSeparator2(from.charCodeAt(fromStart + i1))) {
                    lastCommonSep = i1;
                } else if (i1 === 0) {
                    lastCommonSep = 0;
                }
            }
            break;
        }
        const fromCode = from.charCodeAt(fromStart + i1);
        const toCode = to.charCodeAt(toStart + i1);
        if (fromCode !== toCode) break;
        else if (isPosixPathSeparator2(fromCode)) lastCommonSep = i1;
    }
    let out = "";
    for(i1 = fromStart + lastCommonSep + 1; i1 <= fromEnd; ++i1){
        if (i1 === fromEnd || isPosixPathSeparator2(from.charCodeAt(i1))) {
            if (out.length === 0) out += "..";
            else out += "/..";
        }
    }
    if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
    else {
        toStart += lastCommonSep;
        if (isPosixPathSeparator2(to.charCodeAt(toStart))) ++toStart;
        return to.slice(toStart);
    }
}
function toNamespacedPath2(path) {
    return path;
}
function dirname4(path) {
    if (path.length === 0) return ".";
    let end = -1;
    let matchedNonSeparator = false;
    for(let i1 = path.length - 1; i1 >= 1; --i1){
        if (isPosixPathSeparator2(path.charCodeAt(i1))) {
            if (matchedNonSeparator) {
                end = i1;
                break;
            }
        } else {
            matchedNonSeparator = true;
        }
    }
    if (end === -1) {
        return isPosixPathSeparator2(path.charCodeAt(0)) ? "/" : ".";
    }
    return stripTrailingSeparators1(path.slice(0, end), isPosixPathSeparator2);
}
function basename4(path, suffix = "") {
    assertPath1(path);
    if (path.length === 0) return path;
    if (typeof suffix !== "string") {
        throw new TypeError(`Suffix must be a string. Received ${JSON.stringify(suffix)}`);
    }
    const lastSegment = lastPathSegment1(path, isPosixPathSeparator2);
    const strippedSegment = stripTrailingSeparators1(lastSegment, isPosixPathSeparator2);
    return suffix ? stripSuffix1(strippedSegment, suffix) : strippedSegment;
}
function extname4(path) {
    assertPath1(path);
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for(let i1 = path.length - 1; i1 >= 0; --i1){
        const code = path.charCodeAt(i1);
        if (isPosixPathSeparator2(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 path.slice(startDot, end);
}
function format3(pathObject) {
    if (pathObject === null || typeof pathObject !== "object") {
        throw new TypeError(`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`);
    }
    return _format1("/", pathObject);
}
function parse8(path) {
    assertPath1(path);
    const ret = {
        root: "",
        dir: "",
        base: "",
        ext: "",
        name: ""
    };
    if (path.length === 0) return ret;
    const isAbsolute = isPosixPathSeparator2(path.charCodeAt(0));
    let start;
    if (isAbsolute) {
        ret.root = "/";
        start = 1;
    } else {
        start = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let i1 = path.length - 1;
    let preDotState = 0;
    for(; i1 >= start; --i1){
        const code = path.charCodeAt(i1);
        if (isPosixPathSeparator2(code)) {
            if (!matchedSlash) {
                startPart = i1 + 1;
                break;
            }
            continue;
        }
        if (end === -1) {
            matchedSlash = false;
            end = i1 + 1;
        }
        if (code === 46) {
            if (startDot === -1) startDot = i1;
            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 && isAbsolute) {
                ret.base = ret.name = path.slice(1, end);
            } else {
                ret.base = ret.name = path.slice(startPart, end);
            }
        }
        ret.base = ret.base || "/";
    } else {
        if (startPart === 0 && isAbsolute) {
            ret.name = path.slice(1, startDot);
            ret.base = path.slice(1, end);
        } else {
            ret.name = path.slice(startPart, startDot);
            ret.base = path.slice(startPart, end);
        }
        ret.ext = path.slice(startDot, end);
    }
    if (startPart > 0) {
        ret.dir = stripTrailingSeparators1(path.slice(0, startPart - 1), isPosixPathSeparator2);
    } else if (isAbsolute) ret.dir = "/";
    return ret;
}
function fromFileUrl4(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 toFileUrl4(path) {
    if (!isAbsolute4(path)) {
        throw new TypeError("Must be an absolute path.");
    }
    const url = new URL("file:///");
    url.pathname = encodeWhitespace1(path.replace(/%/g, "%25").replace(/\\/g, "%5C"));
    return url;
}
const mod5 = {
    sep: sep1,
    delimiter: delimiter1,
    resolve: resolve4,
    normalize: normalize4,
    isAbsolute: isAbsolute4,
    join: join5,
    relative: relative4,
    toNamespacedPath: toNamespacedPath2,
    dirname: dirname4,
    basename: basename4,
    extname: extname4,
    format: format3,
    parse: parse8,
    fromFileUrl: fromFileUrl4,
    toFileUrl: toFileUrl4
};
const path = isWindows4 ? mod4 : mod5;
const { join: join6, normalize: normalize5 } = path;
const path1 = isWindows4 ? mod4 : mod5;
const { basename: basename5, delimiter: delimiter2, dirname: dirname5, extname: extname5, format: format4, fromFileUrl: fromFileUrl5, isAbsolute: isAbsolute5, join: join7, normalize: normalize6, parse: parse9, relative: relative5, resolve: resolve5, toFileUrl: toFileUrl5, toNamespacedPath: toNamespacedPath3 } = path1;
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: "›",
    POINTER_SMALL_LEFT: "‹",
    LINE: "─",
    POINTER: "❯",
    POINTER_LEFT: "❮",
    INFO: "ℹ",
    TAB_LEFT: "⇤",
    TAB_RIGHT: "⇥",
    ESCAPE: "⎋",
    BACKSPACE: "⌫",
    PAGE_UP: "⇞",
    PAGE_DOWN: "⇟",
    ENTER: "↵",
    SEARCH: "🔎",
    FOLDER: "📁",
    FOLDER_OPEN: "📂"
};
const win = {
    ...main,
    RADIO_ON: "(*)",
    RADIO_OFF: "( )",
    TICK: "√",
    CROSS: "×",
    POINTER_SMALL: "»"
};
const Figures = Deno.build.os === "windows" ? win : main;
const keyMap = {
    up: "ARROW_UP",
    down: "ARROW_DOWN",
    left: "ARROW_LEFT",
    right: "ARROW_RIGHT",
    pageup: "PAGE_UP",
    pagedown: "PAGE_DOWN",
    tab: "TAB_RIGHT",
    enter: "ENTER",
    return: "ENTER"
};
function getFiguresByKeys(keys) {
    const figures = [];
    for (const key of keys){
        const figure = Figures[keyMap[key]] ?? key;
        if (!figures.includes(figure)) {
            figures.push(figure);
        }
    }
    return figures;
}
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 parse10(data) {
    let index = -1;
    const keys = [];
    const input = data instanceof Uint8Array ? new TextDecoder().decode(data) : data;
    const hasNext = ()=>input.length - 1 >= index + 1;
    const next = ()=>input[++index];
    parseNext();
    return keys;
    function parseNext() {
        let ch = next();
        let s = ch;
        let escaped = false;
        const key = {
            name: undefined,
            char: 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 code = ch;
            let modifier = 0;
            if (ch === "O") {
                s += ch = next();
                if (ch >= "0" && ch <= "9") {
                    modifier = (Number(ch) >> 0) - 1;
                    s += ch = next();
                }
                code += ch;
            } else if (ch === "[") {
                s += ch = next();
                if (ch === "[") {
                    code += 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))?([~^$])$/)) {
                    code += match[1] + match[4];
                    modifier = (Number(match[3]) || 1) - 1;
                } else if (match = cmd.match(/^((\d;)?(\d))?([A-Za-z])$/)) {
                    code += match[4];
                    modifier = (Number(match[3]) || 1) - 1;
                } else {
                    code += cmd;
                }
            }
            key.ctrl = !!(modifier & 4);
            key.meta = !!(modifier & 10);
            key.shift = !!(modifier & 1);
            key.code = code;
            if (code in KeyMap) {
                key.name = KeyMap[code];
            } else if (code in KeyMapShift) {
                key.name = KeyMapShift[code];
                key.shift = true;
            } else if (code in KeyMapCtrl) {
                key.name = KeyMapCtrl[code];
                key.ctrl = true;
            } else {
                key.name = "undefined";
            }
        } else if (ch in SpecialKeyMap) {
            key.name = SpecialKeyMap[ch];
            key.meta = escaped;
            if (key.name === "space") {
                key.char = ch;
            }
        } else if (!escaped && ch <= "\x1a") {
            key.name = String.fromCharCode(ch.charCodeAt(0) + "a".charCodeAt(0) - 1);
            key.ctrl = true;
            key.char = key.name;
        } else if (/^[0-9A-Za-z]$/.test(ch)) {
            key.name = ch.toLowerCase();
            key.shift = /^[A-Z]$/.test(ch);
            key.meta = escaped;
            key.char = ch;
        } else if (escaped) {
            key.name = ch.length ? undefined : "escape";
            key.meta = true;
        } else {
            key.name = ch;
            key.char = ch;
        }
        key.sequence = s;
        if (s.length !== 0 && (key.name !== undefined || escaped) || charLengthAt(s, 0) === s.length) {
            keys.push(key);
        } else {
            throw new Error("Unrecognized or broken escape sequence");
        }
        if (hasNext()) {
            parseNext();
        }
    }
}
function charLengthAt(str, i1) {
    const pos = str.codePointAt(i1);
    if (typeof pos === "undefined") {
        return 1;
    }
    return pos >= 0x10000 ? 2 : 1;
}
class GenericPrompt {
    static injectedValue;
    cursor = {
        x: 0,
        y: 0
    };
    #value;
    #lastError;
    #isFirstRun = true;
    #encoder = new TextEncoder();
    static inject(value) {
        GenericPrompt.injectedValue = value;
    }
    getDefaultSettings(options) {
        return {
            ...options,
            tty: tty({
                reader: Deno.stdin,
                writer: options.writer ?? Deno.stdout
            }),
            cbreak: options.cbreak ?? false,
            reader: options.reader ?? Deno.stdin,
            writer: options.writer ?? Deno.stdout,
            pointer: options.pointer ?? brightBlue(Figures.POINTER_SMALL),
            prefix: options.prefix ?? yellow1("? "),
            indent: options.indent ?? "",
            keys: {
                submit: [
                    "enter",
                    "return"
                ],
                ...options.keys ?? {}
            }
        };
    }
    async prompt() {
        try {
            return await this.#execute();
        } finally{
            this.settings.tty.cursorShow();
        }
    }
    clear() {
        this.settings.tty.cursorLeft.eraseDown();
    }
    #execute = async ()=>{
        if (typeof GenericPrompt.injectedValue !== "undefined" && this.#lastError) {
            throw new Error(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) {
            this.settings.writer.writeSync(this.#encoder.encode(successMessage + "\n"));
        }
        GenericPrompt.injectedValue = undefined;
        this.settings.tty.cursorShow();
        return this.#value;
    };
    async render() {
        const result1 = await Promise.all([
            this.message(),
            this.body?.(),
            this.footer()
        ]);
        const content = result1.filter(Boolean).join("\n");
        const lines = content.split("\n");
        const columns = getColumns();
        const linesCount = columns ? lines.reduce((prev, next)=>{
            const length = stripColor1(next).length;
            return prev + (length > columns ? Math.ceil(length / columns) : 1);
        }, 0) : content.split("\n").length;
        const y = linesCount - this.cursor.y - 1;
        if (!this.#isFirstRun || this.#lastError) {
            this.clear();
        }
        this.#isFirstRun = false;
        this.settings.writer.writeSync(this.#encoder.encode(content));
        if (y) {
            this.settings.tty.cursorUp(y);
        }
        this.settings.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}` + bold1(this.settings.message) + this.defaults();
    }
    defaults() {
        let defaultMessage = "";
        if (typeof this.settings.default !== "undefined" && !this.settings.hideDefault) {
            defaultMessage += dim1(` (${this.format(this.settings.default)})`);
        }
        return defaultMessage;
    }
    success(value) {
        return `${this.settings.indent}${this.settings.prefix}` + bold1(this.settings.message) + this.defaults() + " " + this.settings.pointer + " " + green1(this.format(value));
    }
    footer() {
        return this.error() ?? this.hint();
    }
    error() {
        return this.#lastError ? this.settings.indent + red1(bold1(`${Figures.CROSS} `) + this.#lastError) : undefined;
    }
    hint() {
        return this.settings.hint ? this.settings.indent + italic(brightBlue(dim1(`${Figures.POINTER} `) + this.settings.hint)) : undefined;
    }
    setErrorMessage(message) {
        this.#lastError = message;
    }
    async handleEvent(event) {
        switch(true){
            case event.name === "c" && event.ctrl:
                this.clear();
                this.settings.tty.cursorShow();
                Deno.exit(130);
                return;
            case this.isKey(this.settings.keys, "submit", event):
                await this.submit();
                break;
        }
    }
    #readKey = async ()=>{
        const data = await this.#readChar();
        return data.length ? parse10(data) : [];
    };
    #readChar = async ()=>{
        const buffer = new Uint8Array(8);
        const isTty = Deno.isatty(this.settings.reader.rid);
        if (isTty) {
            this.settings.reader.setRaw(true, {
                cbreak: this.settings.cbreak
            });
        }
        const nread = await this.settings.reader.read(buffer);
        if (isTty) {
            this.settings.reader.setRaw(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(keys, name, event) {
        const keyNames = keys?.[name];
        return typeof keyNames !== "undefined" && (typeof event.name !== "undefined" && keyNames.indexOf(event.name) !== -1 || typeof event.sequence !== "undefined" && keyNames.indexOf(event.sequence) !== -1);
    }
}
function getColumns() {
    try {
        return Deno.consoleSize().columns ?? null;
    } catch (_error) {
        return null;
    }
}
class GenericInput extends GenericPrompt {
    inputValue = "";
    inputIndex = 0;
    getDefaultSettings(options) {
        const settings = super.getDefaultSettings(options);
        return {
            ...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 = stripColor1(message).length + this.inputIndex + 1;
        return message + this.input();
    }
    input() {
        return underline1(this.inputValue);
    }
    highlight(value, color1 = dim1, color2 = brightBlue) {
        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 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 event.char && !event.meta && !event.ctrl:
                this.addChar(event.char);
                break;
            default:
                await super.handleEvent(event);
        }
    }
    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 {
    parentOptions = [];
    get selectedOption() {
        return this.options.at(this.listIndex);
    }
    static separator(label = "------------") {
        return {
            name: label
        };
    }
    getDefaultSettings({ groupIcon = true, groupOpenIcon = groupIcon, ...options }) {
        const settings = super.getDefaultSettings(options);
        return {
            ...settings,
            listPointer: options.listPointer ?? brightBlue(Figures.POINTER),
            searchLabel: options.searchLabel ?? brightBlue(Figures.SEARCH),
            backPointer: options.backPointer ?? brightBlue(Figures.POINTER_LEFT),
            groupPointer: options.groupPointer ?? options.listPointer ?? brightBlue(Figures.POINTER),
            groupIcon: !groupIcon ? false : typeof groupIcon === "string" ? groupIcon : Figures.FOLDER,
            groupOpenIcon: !groupOpenIcon ? false : typeof groupOpenIcon === "string" ? groupOpenIcon : Figures.FOLDER_OPEN,
            maxBreadcrumbItems: options.maxBreadcrumbItems ?? 5,
            breadcrumbSeparator: options.breadcrumbSeparator ?? ` ${Figures.POINTER_SMALL} `,
            maxRows: options.maxRows ?? 10,
            options: this.mapOptions(options, options.options),
            keys: {
                next: options.search ? [
                    "down"
                ] : [
                    "down",
                    "d",
                    "n",
                    "2"
                ],
                previous: options.search ? [
                    "up"
                ] : [
                    "up",
                    "u",
                    "p",
                    "8"
                ],
                nextPage: [
                    "pagedown",
                    "right"
                ],
                previousPage: [
                    "pageup",
                    "left"
                ],
                open: [
                    "right",
                    "enter",
                    "return"
                ],
                back: [
                    "left",
                    "escape",
                    "enter",
                    "return"
                ],
                ...settings.keys ?? {}
            }
        };
    }
    mapOption(options, option) {
        if (isOption1(option)) {
            return {
                value: option.value,
                name: typeof option.name === "undefined" ? options.format?.(option.value) ?? String(option.value) : option.name,
                disabled: "disabled" in option && option.disabled === true,
                indentLevel: 0
            };
        } else {
            return {
                value: null,
                name: option.name,
                disabled: true,
                indentLevel: 0
            };
        }
    }
    mapOptionGroup(options, option, recursive = true) {
        return {
            name: option.name,
            disabled: !!option.disabled,
            indentLevel: 0,
            options: recursive ? this.mapOptions(options, option.options) : []
        };
    }
    match() {
        const input = this.getCurrentInputValue().toLowerCase();
        let options = this.getCurrentOptions().slice();
        if (input.length) {
            const matches = matchOptions(input, this.getCurrentOptions());
            options = flatMatchedOptions(matches);
        }
        this.setOptions(options);
    }
    setOptions(options) {
        this.options = [
            ...options
        ];
        const parent = this.getParentOption();
        if (parent && this.options[0] !== parent) {
            this.options.unshift(parent);
        }
        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));
    }
    getCurrentOptions() {
        return this.getParentOption()?.options ?? this.settings.options;
    }
    getParentOption(index = -1) {
        return this.parentOptions.at(index);
    }
    submitBackButton() {
        const parentOption = this.parentOptions.pop();
        if (!parentOption) {
            return;
        }
        this.match();
        this.listIndex = this.options.indexOf(parentOption);
    }
    submitGroupOption(selectedOption) {
        this.parentOptions.push(selectedOption);
        this.match();
        this.listIndex = 1;
    }
    isBackButton(option) {
        return option === this.getParentOption();
    }
    hasParent() {
        return this.parentOptions.length > 0;
    }
    isSearching() {
        return this.getCurrentInputValue() !== "";
    }
    message() {
        let message = `${this.settings.indent}${this.settings.prefix}` + bold1(this.settings.message) + this.defaults();
        if (this.settings.search) {
            const input = this.isSearchSelected() ? this.input() : dim1(this.input());
            message += " " + this.settings.searchLabel + " ";
            this.cursor.x = stripColor1(message).length + this.inputIndex + 1;
            message += input;
        }
        return message;
    }
    body() {
        return this.getList() + this.getInfo();
    }
    getInfo() {
        if (!this.settings.info) {
            return "";
        }
        const selected = this.listIndex + 1;
        const hasGroups = this.options.some((option)=>isOptionGroup(option));
        const groupActions = hasGroups ? [
            [
                "Open",
                getFiguresByKeys(this.settings.keys.open ?? [])
            ],
            [
                "Back",
                getFiguresByKeys(this.settings.keys.back ?? [])
            ]
        ] : [];
        const actions = [
            [
                "Next",
                getFiguresByKeys(this.settings.keys.next ?? [])
            ],
            [
                "Previous",
                getFiguresByKeys(this.settings.keys.previous ?? [])
            ],
            ...groupActions,
            [
                "Next Page",
                getFiguresByKeys(this.settings.keys.nextPage ?? [])
            ],
            [
                "Previous Page",
                getFiguresByKeys(this.settings.keys.previousPage ?? [])
            ],
            [
                "Submit",
                getFiguresByKeys(this.settings.keys.submit ?? [])
            ]
        ];
        return "\n" + this.settings.indent + brightBlue(Figures.INFO) + bold1(` ${selected}/${this.options.length} `) + actions.map((cur)=>`${cur[0]}: ${bold1(cur[1].join(", "))}`).join(", ");
    }
    getList() {
        const list = [];
        const height = this.getListHeight();
        for(let i1 = this.listOffset; i1 < this.listOffset + height; i1++){
            list.push(this.getListItem(this.options[i1], this.listIndex === i1));
        }
        if (!list.length) {
            list.push(this.settings.indent + dim1("  No matches..."));
        }
        return list.join("\n");
    }
    getListItem(option, isSelected) {
        let line = this.getListItemIndent(option);
        line += this.getListItemPointer(option, isSelected);
        line += this.getListItemIcon(option);
        line += this.getListItemLabel(option, isSelected);
        return line;
    }
    getListItemIndent(option) {
        const indentLevel = this.isSearching() ? option.indentLevel : this.hasParent() && !this.isBackButton(option) ? 1 : 0;
        return this.settings.indent + " ".repeat(indentLevel);
    }
    getListItemPointer(option, isSelected) {
        if (!isSelected) {
            return "  ";
        }
        if (this.isBackButton(option)) {
            return this.settings.backPointer + " ";
        } else if (isOptionGroup(option)) {
            return this.settings.groupPointer + " ";
        }
        return this.settings.listPointer + " ";
    }
    getListItemIcon(option) {
        if (this.isBackButton(option)) {
            return this.settings.groupOpenIcon ? this.settings.groupOpenIcon + " " : "";
        } else if (isOptionGroup(option)) {
            return this.settings.groupIcon ? this.settings.groupIcon + " " : "";
        }
        return "";
    }
    getListItemLabel(option, isSelected) {
        let label = option.name;
        if (this.isBackButton(option)) {
            label = this.getBreadCrumb();
            label = isSelected && !option.disabled ? label : yellow1(label);
        } else {
            label = isSelected && !option.disabled ? this.highlight(label, (val)=>val) : this.highlight(label);
        }
        if (this.isBackButton(option) || isOptionGroup(option)) {
            label = bold1(label);
        }
        return label;
    }
    getBreadCrumb() {
        if (!this.parentOptions.length || !this.settings.maxBreadcrumbItems) {
            return "";
        }
        const names = this.parentOptions.map((option)=>option.name);
        const breadCrumb = names.length > this.settings.maxBreadcrumbItems ? [
            names[0],
            "..",
            ...names.slice(-this.settings.maxBreadcrumbItems + 1)
        ] : names;
        return breadCrumb.join(this.settings.breadcrumbSeparator);
    }
    getListHeight() {
        return Math.min(this.options.length, this.settings.maxRows || this.options.length);
    }
    getListIndex(value) {
        return Math.max(0, typeof value === "undefined" ? this.options.findIndex((option)=>!option.disabled) || 0 : this.options.findIndex((option)=>isOption1(option) && option.value === value) || 0);
    }
    getPageOffset(index) {
        if (index === 0) {
            return 0;
        }
        const height = this.getListHeight();
        return Math.floor(index / height) * height;
    }
    getOptionByValue(value) {
        const option = this.options.find((option)=>isOption1(option) && option.value === value);
        return option && isOptionGroup(option) ? undefined : option;
    }
    read() {
        if (!this.settings.search) {
            this.settings.tty.cursorHide();
        }
        return super.read();
    }
    selectSearch() {
        this.listIndex = -1;
    }
    isSearchSelected() {
        return this.listIndex === -1;
    }
    async handleEvent(event) {
        if (this.isKey(this.settings.keys, "open", event) && isOptionGroup(this.selectedOption) && !this.isBackButton(this.selectedOption) && !this.isSearchSelected()) {
            this.submitGroupOption(this.selectedOption);
        } else if (this.isKey(this.settings.keys, "back", event) && (this.isBackButton(this.selectedOption) || event.name === "escape") && !this.isSearchSelected()) {
            this.submitBackButton();
        } else if (this.isKey(this.settings.keys, "next", event)) {
            this.selectNext();
        } else if (this.isKey(this.settings.keys, "previous", event)) {
            this.selectPrevious();
        } else if (this.isKey(this.settings.keys, "nextPage", event) && !this.isSearchSelected()) {
            this.selectNextPage();
        } else if (this.isKey(this.settings.keys, "previousPage", event) && !this.isSearchSelected()) {
            this.selectPreviousPage();
        } else {
            await super.handleEvent(event);
        }
    }
    async submit() {
        if (this.isSearchSelected()) {
            this.selectNext();
            return;
        }
        await super.submit();
    }
    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(loop = true) {
        if (this.options.length < 2 && !this.isSearchSelected()) {
            return;
        }
        if (this.listIndex > 0) {
            this.listIndex--;
            if (this.listIndex < this.listOffset) {
                this.listOffset--;
            }
            if (this.selectedOption?.disabled) {
                this.selectPrevious();
            }
        } else if (this.settings.search && this.listIndex === 0 && this.getCurrentInputValue().length) {
            this.listIndex = -1;
        } else if (loop) {
            this.listIndex = this.options.length - 1;
            this.listOffset = this.options.length - this.getListHeight();
            if (this.selectedOption?.disabled) {
                this.selectPrevious();
            }
        }
    }
    selectNext(loop = true) {
        if (this.options.length < 2 && !this.isSearchSelected()) {
            return;
        }
        if (this.listIndex < this.options.length - 1) {
            this.listIndex++;
            if (this.listIndex >= this.listOffset + this.getListHeight()) {
                this.listOffset++;
            }
            if (this.selectedOption?.disabled) {
                this.selectNext();
            }
        } else if (this.settings.search && this.listIndex === this.options.length - 1 && this.getCurrentInputValue().length) {
            this.listIndex = -1;
        } else if (loop) {
            this.listIndex = this.listOffset = 0;
            if (this.selectedOption?.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;
            } else {
                this.listIndex = 0;
            }
            if (this.selectedOption?.disabled) {
                this.selectPrevious(false);
            }
            if (this.selectedOption?.disabled) {
                this.selectNext(false);
            }
        }
    }
    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;
            } else {
                this.listIndex = this.options.length - 1;
            }
            if (this.selectedOption?.disabled) {
                this.selectNext(false);
            }
            if (this.selectedOption?.disabled) {
                this.selectPrevious(false);
            }
        }
    }
}
function isOption1(option) {
    return !!option && typeof option === "object" && "value" in option;
}
function isOptionGroup(option) {
    return option !== null && typeof option === "object" && "options" in option && Array.isArray(option.options);
}
function matchOptions(searchInput, options) {
    const matched = [];
    for (const option of options){
        if (isOptionGroup(option)) {
            const children = matchOptions(searchInput, option.options).sort(sortByDistance);
            if (children.length) {
                matched.push({
                    option,
                    distance: Math.min(...children.map((item)=>item.distance)),
                    children
                });
                continue;
            }
        }
        if (matchOption(searchInput, option)) {
            matched.push({
                option,
                distance: distance(option.name, searchInput),
                children: []
            });
        }
    }
    return matched.sort(sortByDistance);
    function sortByDistance(a, b) {
        return a.distance - b.distance;
    }
}
function matchOption(inputString, option) {
    return matchInput(inputString, option.name) || isOption1(option) && option.name !== option.value && matchInput(inputString, String(option.value));
}
function matchInput(inputString, value) {
    return stripColor1(value).toLowerCase().includes(inputString);
}
function flatMatchedOptions(matches, indentLevel = 0, result1 = []) {
    for (const { option, children } of matches){
        option.indentLevel = indentLevel;
        result1.push(option);
        flatMatchedOptions(children, indentLevel + 1, result1);
    }
    return result1;
}
class Checkbox extends GenericList {
    settings;
    options;
    listIndex;
    listOffset;
    confirmSubmit = false;
    static prompt(options) {
        return new this(options).prompt();
    }
    static inject(value) {
        GenericPrompt.inject(value);
    }
    constructor(options){
        super();
        this.settings = this.getDefaultSettings(options);
        this.options = this.settings.options.slice();
        this.listIndex = this.getListIndex();
        this.listOffset = this.getPageOffset(this.listIndex);
    }
    getDefaultSettings(options) {
        const settings = super.getDefaultSettings(options);
        return {
            confirmSubmit: true,
            ...settings,
            check: options.check ?? green1(Figures.TICK),
            uncheck: options.uncheck ?? red1(Figures.CROSS),
            partialCheck: options.partialCheck ?? green1(Figures.RADIO_ON),
            minOptions: options.minOptions ?? 0,
            maxOptions: options.maxOptions ?? Infinity,
            options: this.mapOptions(options, options.options),
            keys: {
                check: [
                    "space"
                ],
                checkAll: [
                    "a"
                ],
                ...settings.keys ?? {},
                open: options.keys?.open ?? [
                    "right"
                ],
                back: options.keys?.back ?? [
                    "left",
                    "escape"
                ]
            }
        };
    }
    mapOptions(promptOptions, options) {
        return options.map((option)=>typeof option === "string" || typeof option === "number" ? this.mapOption(promptOptions, {
                value: option
            }) : isCheckboxOptionGroup(option) ? this.mapOptionGroup(promptOptions, option) : this.mapOption(promptOptions, option));
    }
    mapOption(options, option) {
        if (isOption1(option)) {
            return {
                ...super.mapOption(options, option),
                checked: typeof option.checked === "undefined" && options.default && options.default.indexOf(option.value) !== -1 ? true : !!option.checked,
                icon: typeof option.icon === "undefined" ? true : option.icon
            };
        } else {
            return {
                ...super.mapOption(options, option),
                checked: false,
                icon: false
            };
        }
    }
    mapOptionGroup(promptOptions, option) {
        const options = this.mapOptions(promptOptions, option.options);
        return {
            ...super.mapOptionGroup(promptOptions, option, false),
            get checked () {
                return areAllChecked(options);
            },
            options,
            icon: typeof option.icon === "undefined" ? true : option.icon
        };
    }
    match() {
        super.match();
        if (this.isSearching()) {
            this.selectSearch();
        }
    }
    getListItemIcon(option) {
        return this.getCheckboxIcon(option) + super.getListItemIcon(option);
    }
    getCheckboxIcon(option) {
        if (!option.icon) {
            return "";
        }
        const icon = option.checked ? this.settings.check + " " : isOptionGroup(option) && areSomeChecked(option.options) ? this.settings.partialCheck + " " : this.settings.uncheck + " ";
        return option.disabled ? dim1(icon) : icon;
    }
    getValue() {
        return flatOptions(this.settings.options).filter((option)=>option.checked).map((option)=>option.value);
    }
    async handleEvent(event) {
        const hasConfirmed = this.confirmSubmit;
        this.confirmSubmit = false;
        switch(true){
            case this.isKey(this.settings.keys, "check", event) && !this.isSearchSelected():
                this.checkValue();
                break;
            case this.isKey(this.settings.keys, "submit", event):
                await this.submit(hasConfirmed);
                break;
            case event.ctrl && this.isKey(this.settings.keys, "checkAll", event):
                this.checkAllOption();
                break;
            default:
                await super.handleEvent(event);
        }
    }
    hint() {
        if (this.confirmSubmit) {
            const info = this.isBackButton(this.selectedOption) ? ` To leave the current group press ${getFiguresByKeys(this.settings.keys.back ?? []).join(", ")}.` : isOptionGroup(this.selectedOption) ? ` To open the selected group press ${getFiguresByKeys(this.settings.keys.open ?? []).join(", ")}.` : ` To check or uncheck the selected option press ${getFiguresByKeys(this.settings.keys.check ?? []).join(", ")}.`;
            return this.settings.indent + brightBlue(`Press ${getFiguresByKeys(this.settings.keys.submit ?? [])} again to submit.${info}`);
        }
        return super.hint();
    }
    async submit(hasConfirmed) {
        if (!hasConfirmed && this.settings.confirmSubmit && !this.isSearchSelected()) {
            this.confirmSubmit = true;
            return;
        }
        await super.submit();
    }
    checkValue() {
        const option = this.options.at(this.listIndex);
        if (!option) {
            this.setErrorMessage("No option available to select.");
            return;
        } else if (option.disabled) {
            this.setErrorMessage("This option is disabled and cannot be changed.");
            return;
        }
        this.checkOption(option, !option.checked);
    }
    checkOption(option, checked) {
        if (isOption1(option)) {
            option.checked = checked;
        } else {
            for (const childOption of option.options){
                this.checkOption(childOption, checked);
            }
        }
    }
    checkAllOption() {
        const checked = this.options.some((option)=>option.checked);
        for (const option of this.options){
            this.checkOption(option, !checked);
        }
    }
    validate(value) {
        const options = flatOptions(this.settings.options);
        const isValidValue = Array.isArray(value) && value.every((val)=>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;
    }
    format(value) {
        return value.map((val)=>this.settings.format?.(val) ?? this.getOptionByValue(val)?.name ?? String(val)).join(", ");
    }
}
function areSomeChecked(options) {
    return options.some((option)=>isOptionGroup(option) ? areSomeChecked(option.options) : option.checked);
}
function areAllChecked(options) {
    return options.every((option)=>isOptionGroup(option) ? areAllChecked(option.options) : option.checked);
}
function flatOptions(options) {
    return flat(options);
    function flat(options, indentLevel = 0, opts = []) {
        for (const option of options){
            option.indentLevel = indentLevel;
            if (isOption1(option)) {
                opts.push(option);
            }
            if (isOptionGroup(option)) {
                flat(option.options, ++indentLevel, opts);
            }
        }
        return opts;
    }
}
function isCheckboxOptionGroup(option) {
    return isOptionGroup(option);
}
const sep2 = Deno.build.os === "windows" ? "\\" : "/";
class GenericSuggestions extends GenericInput {
    suggestionsIndex = -1;
    suggestionsOffset = 0;
    suggestions = [];
    #hasReadPermissions;
    getDefaultSettings(options) {
        const settings = super.getDefaultSettings(options);
        return {
            ...settings,
            listPointer: options.listPointer ?? brightBlue(Figures.POINTER),
            maxRows: options.maxRows ?? 8,
            keys: {
                complete: [
                    "tab"
                ],
                next: [
                    "up"
                ],
                previous: [
                    "down"
                ],
                nextPage: [
                    "pageup"
                ],
                previousPage: [
                    "pagedown"
                ],
                ...settings.keys ?? {}
            }
        };
    }
    get localStorage() {
        if (this.settings.id && "localStorage" in window) {
            try {
                return window.localStorage;
            } catch (_) {}
        }
        return null;
    }
    loadSuggestions() {
        if (this.settings.id) {
            const json = this.localStorage?.getItem(this.settings.id);
            const suggestions = json ? JSON.parse(json) : [];
            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)));
        }
    }
    async render() {
        if (this.settings.files && this.#hasReadPermissions === undefined) {
            const status = await Deno.permissions.request({
                name: "read"
            });
            this.#hasReadPermissions = status.state === "granted";
        }
        await this.match();
        return super.render();
    }
    async match() {
        this.suggestions = await this.getSuggestions();
        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() + dim1(this.getSuggestion());
    }
    getSuggestion() {
        return this.suggestions[this.suggestionsIndex]?.toString().substr(this.getCurrentInputValue().length) ?? "";
    }
    async getUserSuggestions(input) {
        return typeof this.settings.suggestions === "function" ? await this.settings.suggestions(input) : this.settings.suggestions ?? [];
    }
    #isFileModeEnabled() {
        return !!this.settings.files && this.#hasReadPermissions === true;
    }
    async getFileSuggestions(input) {
        if (!this.#isFileModeEnabled()) {
            return [];
        }
        const path = await Deno.stat(input).then((file)=>file.isDirectory ? input : dirname5(input)).catch(()=>dirname5(input));
        return await listDir(path, this.settings.files);
    }
    async getSuggestions() {
        const input = this.getCurrentInputValue();
        const suggestions = [
            ...this.loadSuggestions(),
            ...await this.getUserSuggestions(input),
            ...await this.getFileSuggestions(input)
        ].filter(uniqueSuggestions);
        if (!input.length) {
            return suggestions;
        }
        return suggestions.filter((value)=>stripColor1(value.toString()).toLowerCase().startsWith(input.toLowerCase())).sort((a, b)=>distance((a || a).toString(), input) - distance((b || b).toString(), input));
    }
    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.suggestions.length) {
            if (this.settings.list) {
                actions.push([
                    "Next",
                    getFiguresByKeys(this.settings.keys?.next ?? [])
                ], [
                    "Previous",
                    getFiguresByKeys(this.settings.keys?.previous ?? [])
                ], [
                    "Next Page",
                    getFiguresByKeys(this.settings.keys?.nextPage ?? [])
                ], [
                    "Previous Page",
                    getFiguresByKeys(this.settings.keys?.previousPage ?? [])
                ]);
            } else {
                actions.push([
                    "Next",
                    getFiguresByKeys(this.settings.keys?.next ?? [])
                ], [
                    "Previous",
                    getFiguresByKeys(this.settings.keys?.previous ?? [])
                ]);
            }
            actions.push([
                "Complete",
                getFiguresByKeys(this.settings.keys?.complete ?? [])
            ]);
        }
        actions.push([
            "Submit",
            getFiguresByKeys(this.settings.keys?.submit ?? [])
        ]);
        let info = this.settings.indent;
        if (this.suggestions.length) {
            info += brightBlue(Figures.INFO) + bold1(` ${selected}/${matched} `);
        }
        info += actions.map((cur)=>`${cur[0]}: ${bold1(cur[1].join(" "))}`).join(", ");
        return info;
    }
    getList() {
        if (!this.suggestions.length || !this.settings.list) {
            return "";
        }
        const list = [];
        const height = this.getListHeight();
        for(let i1 = this.suggestionsOffset; i1 < this.suggestionsOffset + height; i1++){
            list.push(this.getListItem(this.suggestions[i1], this.suggestionsIndex === i1));
        }
        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 += underline1(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):
                await this.#completeValue();
                break;
            case this.isKey(this.settings.keys, "moveCursorRight", event):
                if (this.inputIndex < this.inputValue.length) {
                    this.moveCursorRight();
                } else {
                    await this.#completeValue();
                }
                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;
            }
        }
    }
    async #completeValue() {
        this.inputValue = await this.complete();
        this.inputIndex = this.inputValue.length;
        this.suggestionsIndex = 0;
        this.suggestionsOffset = 0;
    }
    async complete() {
        let input = this.getCurrentInputValue();
        const suggestion = this.suggestions[this.suggestionsIndex]?.toString();
        if (this.settings.complete) {
            input = await this.settings.complete(input, suggestion);
        } else if (this.#isFileModeEnabled() && input.at(-1) !== sep2 && await isDirectory(input) && (this.getCurrentInputValue().at(-1) !== "." || this.getCurrentInputValue().endsWith(".."))) {
            input += sep2;
        } else if (suggestion) {
            input = suggestion;
        }
        return this.#isFileModeEnabled() ? normalize6(input) : input;
    }
    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, self1) {
    return typeof value !== "undefined" && value !== "" && self1.indexOf(value) === index;
}
function isDirectory(path) {
    return Deno.stat(path).then((file)=>file.isDirectory).catch(()=>false);
}
async function listDir(path, mode) {
    const fileNames = [];
    for await (const file of Deno.readDir(path || ".")){
        if (mode === true && (file.name.startsWith(".") || file.name.endsWith("~"))) {
            continue;
        }
        const filePath = join7(path, file.name);
        if (mode instanceof RegExp && !mode.test(filePath)) {
            continue;
        }
        fileNames.push(filePath);
    }
    return fileNames.sort(function(a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });
}
class Confirm extends GenericSuggestions {
    settings;
    static prompt(options) {
        return new this(options).prompt();
    }
    static inject(value) {
        GenericPrompt.inject(value);
    }
    constructor(options){
        super();
        if (typeof options === "string") {
            options = {
                message: options
            };
        }
        this.settings = this.getDefaultSettings(options);
    }
    getDefaultSettings(options) {
        return {
            ...super.getDefaultSettings(options),
            active: options.active || "Yes",
            inactive: options.inactive || "No",
            files: false,
            complete: undefined,
            suggestions: [
                options.active || "Yes",
                options.inactive || "No"
            ],
            list: false,
            info: false
        };
    }
    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 ? dim1(` (${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 Input extends GenericSuggestions {
    settings;
    static prompt(options) {
        return new this(options).prompt();
    }
    static inject(value) {
        GenericPrompt.inject(value);
    }
    constructor(options){
        super();
        if (typeof options === "string") {
            options = {
                message: options
            };
        }
        this.settings = this.getDefaultSettings(options);
    }
    getDefaultSettings(options) {
        return {
            ...super.getDefaultSettings(options),
            minLength: options.minLength ?? 0,
            maxLength: options.maxLength ?? Infinity
        };
    }
    success(value) {
        this.saveSuggestions(value);
        return super.success(value);
    }
    getValue() {
        return this.settings.files ? normalize6(this.inputValue) : this.inputValue;
    }
    validate(value) {
        if (typeof value !== "string") {
            return false;
        }
        if (value.length < this.settings.minLength) {
            return `Value must be longer than ${this.settings.minLength} but has a length of ${value.length}.`;
        }
        if (value.length > this.settings.maxLength) {
            return `Value can't be longer than ${this.settings.maxLength} but has a length of ${value.length}.`;
        }
        return true;
    }
    transform(value) {
        return value.trim();
    }
    format(value) {
        return value;
    }
}
class Secret extends GenericInput {
    settings;
    static prompt(options) {
        return new this(options).prompt();
    }
    static inject(value) {
        GenericPrompt.inject(value);
    }
    constructor(options){
        super();
        if (typeof options === "string") {
            options = {
                message: options
            };
        }
        this.settings = this.getDefaultSettings(options);
    }
    getDefaultSettings(options) {
        return {
            ...super.getDefaultSettings(options),
            label: options.label ?? "Secret",
            hidden: options.hidden ?? false,
            minLength: options.minLength ?? 0,
            maxLength: options.maxLength ?? Infinity
        };
    }
    input() {
        return underline1(this.settings.hidden ? "" : "*".repeat(this.inputValue.length));
    }
    read() {
        if (this.settings.hidden) {
            this.settings.tty.cursorHide();
        }
        return super.read();
    }
    validate(value) {
        if (typeof value !== "string") {
            return false;
        }
        if (value.length < this.settings.minLength) {
            return `${this.settings.label} must be longer than ${this.settings.minLength} but has a length of ${value.length}.`;
        }
        if (value.length > this.settings.maxLength) {
            return `${this.settings.label} can't be longer than ${this.settings.maxLength} but has a length of ${value.length}.`;
        }
        return true;
    }
    transform(value) {
        return value;
    }
    format(value) {
        return this.settings.hidden ? "*".repeat(8) : "*".repeat(value.length);
    }
    getValue() {
        return this.inputValue;
    }
}
class Select extends GenericList {
    settings;
    options;
    listIndex;
    listOffset;
    static prompt(options) {
        return new this(options).prompt();
    }
    static inject(value) {
        GenericPrompt.inject(value);
    }
    constructor(options){
        super();
        this.settings = this.getDefaultSettings(options);
        this.options = this.settings.options.slice();
        this.listIndex = this.getListIndex(this.settings.default);
        this.listOffset = this.getPageOffset(this.listIndex);
    }
    getDefaultSettings(options) {
        return {
            ...super.getDefaultSettings(options),
            options: this.mapOptions(options, options.options)
        };
    }
    mapOptions(promptOptions, options) {
        return options.map((option)=>isSelectOptionGroup(option) ? this.mapOptionGroup(promptOptions, option) : typeof option === "string" || typeof option === "number" ? this.mapOption(promptOptions, {
                value: option
            }) : this.mapOption(promptOptions, option));
    }
    input() {
        return underline1(brightBlue(this.inputValue));
    }
    async submit() {
        if (this.isBackButton(this.selectedOption) || isOptionGroup(this.selectedOption)) {
            const info = isOptionGroup(this.selectedOption) ? ` To select a group use ${getFiguresByKeys(this.settings.keys.open ?? []).join(", ")}.` : "";
            this.setErrorMessage(`No option selected.${info}`);
            return;
        }
        await super.submit();
    }
    getValue() {
        const option = this.options[this.listIndex];
        assertIsOption(option);
        return option.value;
    }
    validate(value) {
        return this.options.findIndex((option)=>isOption1(option) && option.value === value) !== -1;
    }
    transform(value) {
        return value;
    }
    format(value) {
        return this.settings.format?.(value) ?? this.getOptionByValue(value)?.name ?? String(value);
    }
}
function assertIsOption(option) {
    if (!isOption1(option)) {
        throw new Error("Expected an option but got an option group.");
    }
}
function isSelectOptionGroup(option) {
    return isOptionGroup(option);
}
let injected = {};
function prompt(prompts, options) {
    return new PromptList(prompts, options).run(options?.initial);
}
class PromptList {
    prompts;
    options;
    result;
    index;
    names;
    isInBeforeHook;
    tty;
    get prompt() {
        return this.prompts[this.index];
    }
    constructor(prompts, options){
        this.prompts = prompts;
        this.options = options;
        this.result = {};
        this.index = -1;
        this.isInBeforeHook = false;
        this.names = this.prompts.map((prompt)=>prompt.name);
        this.tty = tty({
            writer: options?.writer ?? Deno.stdout
        });
    }
    async run(name) {
        this.index = -1;
        this.result = {};
        this.isInBeforeHook = false;
        await this.next(name);
        return this.result;
    }
    async next(name) {
        if (this.updateIndex(name)) {
            await this.runBeforeHook(async ()=>{
                this.isInBeforeHook = false;
                await this.runPrompt();
                await this.runAfterHook();
            });
        }
    }
    updateIndex(name) {
        if (name && typeof name === "string") {
            this.index = this.names.indexOf(name);
            if (this.index === -1) {
                throw new Error(`Invalid prompt name: ${name}, allowed prompt names: ${this.names.join(", ")}`);
            }
        } else if (typeof name === "number") {
            if (name < 0 || name > this.names.length) {
                throw new Error(`Invalid prompt index: ${name}, prompt length: ${this.names.length}`);
            }
            this.index = name;
        } else if (name === true && !this.isInBeforeHook) {
            this.index++;
            if (this.index < this.names.length - 1) {
                this.index++;
            }
        } else {
            this.index++;
        }
        this.isInBeforeHook = false;
        if (this.index < this.names.length) {
            return true;
        } else if (this.index === this.names.length) {
            return false;
        } else {
            throw new Error("next() called multiple times");
        }
    }
    async runBeforeHook(run) {
        this.isInBeforeHook = true;
        const next = async (name)=>{
            if (name || typeof name === "number") {
                return this.next(name);
            }
            await run();
        };
        if (this.options?.before) {
            await this.options.before(this.prompt.name, this.result, async (name)=>{
                if (name || typeof name === "number") {
                    return this.next(name);
                } else if (this.prompt.before) {
                    await this.prompt.before(this.result, next);
                } else {
                    await run();
                }
            });
            return;
        } else if (this.prompt.before) {
            await this.prompt.before(this.result, next);
            return;
        }
        await run();
    }
    async runPrompt() {
        const prompt = this.prompt.type;
        if (typeof injected[this.prompt.name] !== "undefined") {
            if (prompt.inject) {
                prompt.inject(injected[this.prompt.name]);
            } else {
                GenericPrompt.inject(injected[this.prompt.name]);
            }
        }
        try {
            this.result[this.prompt.name] = await prompt.prompt({
                reader: this.options?.reader,
                writer: this.options?.writer,
                cbreak: this.options?.cbreak,
                ...this.prompt
            });
        } finally{
            this.tty.cursorShow();
        }
    }
    async runAfterHook() {
        if (this.options?.after) {
            await this.options.after(this.prompt.name, this.result, async (name)=>{
                if (name) {
                    return this.next(name);
                } else if (this.prompt.after) {
                    await this.prompt.after(this.result, (name)=>this.next(name));
                } else {
                    await this.next();
                }
            });
        } else if (this.prompt.after) {
            await this.prompt.after(this.result, (name)=>this.next(name));
        } else {
            await this.next();
        }
    }
}
const kUpdatePath = "update-path";
async function getLatestRelease(repo) {
    const url = `https://api.github.com/repos/${repo}/releases/latest`;
    const headers = Deno.env.get("GH_TOKEN") ? {
        headers: {
            Authorization: "Bearer " + Deno.env.get("GH_TOKEN")
        }
    } : undefined;
    const response = await fetch(url, headers);
    if (response.status !== 200) {
        throw new Error(`Unable to determine latest release for ${repo}\n${response.status} - ${response.statusText}`);
    } else {
        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 = "rstudio/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: ()=>{
                const needsSource = needsSourceInstall();
                return Promise.resolve(!needsSource);
            },
            os: [
                "linux"
            ],
            message: "This platform doesn't support installation at this time. Please install manually instead. See https://yihui.org/tinytex/#installation."
        }
    ],
    installed,
    installDir,
    binDir,
    installedVersion,
    verifyConfiguration,
    latestRelease: remotePackageInfo,
    preparePackage,
    install: install1,
    afterInstall,
    uninstall
};
async function installed() {
    const hasTiny = hasTinyTex();
    if (hasTiny) {
        return true;
    } else {
        if (await hasTexLive()) {
            return await isTinyTex();
        } else {
            return false;
        }
    }
}
async function installDir() {
    if (await installed()) {
        return Promise.resolve(tinyTexInstallDir());
    } else {
        return Promise.resolve(undefined);
    }
}
function verifyConfiguration() {
    return Promise.resolve({
        status: "ok"
    });
}
async function binDir() {
    if (await installed()) {
        const installDir = tinyTexInstallDir();
        if (installDir) {
            return Promise.resolve(binFolder(installDir));
        } else {
            warn("Failed to resolve tinytex install directory even though it is installed.");
            return Promise.resolve(undefined);
        }
    } else {
        return Promise.resolve(undefined);
    }
}
async function installedVersion() {
    const installDir = tinyTexInstallDir();
    if (installDir) {
        const versionFile = join2(installDir, kVersionFileName);
        if (existsSync(versionFile)) {
            return await Deno.readTextFile(versionFile);
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function noteInstalledVersion(version) {
    const installDir = tinyTexInstallDir();
    if (installDir) {
        const versionFile = join2(installDir, kVersionFileName);
        Deno.writeTextFileSync(versionFile, version);
    }
}
async function preparePackage(context) {
    const pkgInfo = await remotePackageInfo();
    const version = pkgInfo.version;
    const pkgName = tinyTexPkgName(kPackageMaximal, version);
    const filePath = join2(context.workingDir, pkgName);
    const url = tinyTexUrl(pkgName, pkgInfo);
    if (url) {
        await context.download(`TinyTex ${version}`, url, filePath);
        return {
            filePath,
            version
        };
    } else {
        context.error("Couldn't determine what URL to use to download");
        return Promise.reject();
    }
}
async function install1(pkgInfo, context) {
    const installDir = tinyTexInstallDir();
    if (installDir) {
        const parentDir = join2(installDir, "..");
        const realParentDir = expandPath(parentDir);
        const tinyTexDirName = Deno.build.os === "linux" ? ".TinyTeX" : "TinyTeX";
        debug(`TinyTex Directory Information:`);
        debug(`> installDir:  ${installDir}`);
        debug(`> parentDir:  ${parentDir}`);
        debug(`> realParentDir:  ${realParentDir}`);
        if (existsSync(realParentDir)) {
            debug(`Unzipping file ${pkgInfo.filePath}`);
            await context.withSpinner({
                message: `Unzipping ${basename2(pkgInfo.filePath)}`
            }, async ()=>{
                await unzip(pkgInfo.filePath);
            });
            await context.withSpinner({
                message: `Moving files`
            }, ()=>{
                const from = join2(context.workingDir, tinyTexDirName);
                debug(`Moving files\n> from ${from}\n> to   ${installDir}`);
                copyTo(from, installDir);
                if (Deno.build.os === "darwin") {
                    for (const file of walkSync(from)){
                        if (file.isFile) {
                            const relativePath = relative2(from, file.path);
                            const destPath = join2(installDir, relativePath);
                            const srcStat = Deno.statSync(file.path);
                            const destStat = Deno.statSync(destPath);
                            if (srcStat.mode !== null && srcStat.mode !== destStat.mode) {
                                Deno.chmodSync(destPath, srcStat.mode);
                            }
                        }
                    }
                }
                Deno.removeSync(from, {
                    recursive: true
                });
                noteInstalledVersion(pkgInfo.version);
                return Promise.resolve();
            });
            context.props[kTlMgrKey] = Deno.build.os === "windows" ? join2(binFolder(installDir), "tlmgr.bat") : join2(binFolder(installDir), "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();
    }
}
function binFolder(installDir) {
    const nixBinFolder = ()=>{
        const oldBinFolder = join2(installDir, "bin", `${Deno.build.arch}-${Deno.build.os}`);
        if (existsSync(oldBinFolder)) {
            return oldBinFolder;
        } else {
            return join2(installDir, "bin", `universal-${Deno.build.os}`);
        }
    };
    const winBinFolder = ()=>{
        const oldBinFolder = join2(installDir, "bin", "win32");
        if (existsSync(oldBinFolder)) {
            return oldBinFolder;
        } else {
            return join2(installDir, "bin", "windows");
        }
    };
    return Deno.build.os === "windows" ? winBinFolder() : nixBinFolder();
}
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"
                ]);
            }
        });
        await context.withSpinner({
            message: "Configuring font paths"
        }, async ()=>{
            await exec(tlmgrPath, [
                "postaction",
                "install",
                "script",
                "xetex"
            ]);
        });
        let restartRequired = false;
        const defaultRepo = await textLiveRepo();
        await context.withSpinner({
            message: `Setting default repository`,
            doneMessage: `Default Repository: ${defaultRepo}`
        }, async ()=>{
            await exec(tlmgrPath, [
                "-q",
                "option",
                "repository",
                defaultRepo
            ]);
        });
        if (context.flags[kUpdatePath]) {
            const message = `Unable to determine a path to use when installing TeX Live. 
To complete the installation, please run the following:

${tlmgrPath} option sys_bin <bin_dir_on_path>
${tlmgrPath} path add

This will instruct TeX Live to create symlinks that it needs in <bin_dir_on_path>.`;
            const configureBinPath = async (path)=>{
                if (Deno.build.os !== "windows") {
                    const expandedPath = expandPath(path);
                    ensureDirSync(expandedPath);
                    await exec(tlmgrPath, [
                        "option",
                        "sys_bin",
                        expandedPath
                    ]);
                    return true;
                } else {
                    return true;
                }
            };
            const paths = [];
            const envPath = Deno.env.get("QUARTO_TEXLIVE_BINPATH");
            if (envPath) {
                paths.push(envPath);
            } else if (Deno.build.os !== "windows") {
                paths.push(...suggestUserBinPaths());
            } else {
                paths.push(tlmgrPath);
            }
            const binPathMessage = envPath ? `Setting TeXLive Binpath: ${envPath}` : Deno.build.os !== "windows" ? `Updating Path (inspecting ${paths.length} possible paths)` : "Updating Path";
            await context.withSpinner({
                message: binPathMessage
            }, async ()=>{
                let result1;
                for (const path of paths){
                    const pathConfigured = await configureBinPath(path);
                    if (pathConfigured) {
                        result1 = await exec(tlmgrPath, [
                            "path",
                            "add"
                        ]);
                        if (result1.success) {
                            break;
                        }
                    }
                }
                if (result1 && !result1.success) {
                    warn(message);
                }
            });
            if (Deno.build.os === "windows") {
                const texLiveInstalled = await hasTexLive();
                const texLivePath = await texLiveInPath();
                restartRequired = restartRequired || !texLiveInstalled || !texLivePath;
            }
        }
        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();
    }
    if (context.flags[kUpdatePath]) {
        if (await texLiveInPath()) {
            await context.withSpinner({
                message: "Removing commands"
            }, async ()=>{
                const texLive = await texLiveContext(true);
                const result1 = await removePath(texLive);
                if (!result1.success) {
                    context.error("Failed to uninstall");
                    return Promise.reject();
                }
            });
        }
    }
    await context.withSpinner({
        message: "Removing directory"
    }, async ()=>{
        const installDir = tinyTexInstallDir();
        if (installDir) {
            await Deno.remove(installDir, {
                recursive: true
            });
        } else {
            context.error("Couldn't find install directory");
            return Promise.reject();
        }
    });
}
function exec(path, cmd) {
    return execProcess({
        cmd: [
            path,
            ...cmd
        ],
        stdout: "piped",
        stderr: "piped"
    });
}
const kTlMgrKey = "tlmgr";
async function textLiveRepo() {
    let autoUrl;
    try {
        const url = "https://mirror.ctan.org/systems/texlive/tlnet";
        const response = await fetch(url, {
            redirect: "follow"
        });
        autoUrl = response.url;
    } catch (_e) {}
    if (!autoUrl) {
        const randomInt = Math.floor(Math.random() * kDefaultRepos.length);
        autoUrl = kDefaultRepos[randomInt];
    }
    return autoUrl;
}
function tinyTexPkgName(base, ver) {
    const ext = Deno.build.os === "windows" ? "zip" : Deno.build.os === "linux" ? "tar.gz" : "tgz";
    base = base || "TinyTeX";
    if (ver) {
        return `${base}-${ver}.${ext}`;
    } else {
        return `${base}.${ext}`;
    }
}
function tinyTexUrl(pkg, remotePkgInfo) {
    const asset = remotePkgInfo.assets.find((asset)=>{
        return asset.name === pkg;
    });
    return asset?.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(path) {
    const desc = {
        name: "write",
        path
    };
    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 root = await texLiveRoot();
    if (root) {
        if (root.match(/[/\\][Tt]iny[Tt]e[Xx][/\\]?/)) {
            return true;
        }
        const cnfFile = join2(root, "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 join2(realPath, "..", "..", "..");
        } else {
            const root = join2(realPath, "..", "..", "..", "..");
            const tlBin = join2(root, "bin");
            if (existsSync(tlBin)) {
                return root;
            } else {
                return undefined;
            }
        }
    } else {
        const installDir = tinyTexInstallDir();
        if (installDir && existsSync(installDir)) {
            return installDir;
        } else {
            return undefined;
        }
    }
}
async function installDir1() {
    if (await installed1()) {
        return Promise.resolve(chromiumInstallDir());
    } else {
        return Promise.resolve(undefined);
    }
}
const chromiumInstallable = {
    name: "Chromium",
    prereqs: [],
    installed: installed1,
    installedVersion: installedVersion1,
    latestRelease,
    preparePackage: preparePackage1,
    install: install2,
    afterInstall: afterInstall1,
    uninstall: uninstall1,
    installDir: installDir1
};
async function installed1() {
    const fetcherObj = await fetcher();
    const version = await supportedRevision();
    const localRevisions = await fetcherObj.localRevisions();
    return localRevisions.includes(version);
}
async function installedVersion1() {
    const fetcherObj = await fetcher();
    const localRevisions = await fetcherObj.localRevisions();
    if (localRevisions.length) {
        return localRevisions[localRevisions.length - 1];
    }
}
async function latestRelease() {
    const fetcherObj = await fetcher();
    const version = await supportedRevision();
    const revisionInfo = await fetcherObj.revisionInfo(version);
    return Promise.resolve({
        url: revisionInfo.url,
        version,
        assets: [
            {
                name: "",
                url: ""
            }
        ]
    });
}
async function preparePackage1(_ctx) {
    const revision = await supportedRevision();
    const progress = progressBar(100, `Downloading Chromium ${revision}`);
    let spinnerStatus;
    const fetcherObj = await fetcher();
    const revisionInfo = await fetcherObj.download(revision, (x, total)=>{
        const percent = x / total * 100;
        if (percent < 100) {
            progress.update(percent);
        } else {
            progress.complete(true);
            clearLine();
            spinnerStatus = spinner(`Installing Chromium ${revision}`);
        }
    });
    if (spinnerStatus !== undefined) {
        spinnerStatus();
    }
    return {
        filePath: revisionInfo.folderPath,
        version: revisionInfo.revision
    };
}
function install2(_pkg, _ctx) {
    return Promise.resolve();
}
function afterInstall1(_ctx) {
    return Promise.resolve(false);
}
async function uninstall1(_ctx) {
    await withSpinner({
        message: "Removing Chromium..."
    }, async ()=>{
        const fetcherObj = await fetcher();
        const version = await supportedRevision();
        return fetcherObj.remove(version);
    });
    return Promise.resolve();
}
async function supportedRevision() {
    return (await getPuppeteer())._preferredRevision;
}
async function downloadWithProgress(url, msg, toFile) {
    const response = await (typeof url === "string" ? fetch(url, {
        redirect: "follow"
    }) : url);
    if (response.status === 200 && response.body) {
        const pkgFile = await Deno.open(toFile, {
            create: true,
            write: true
        });
        const contentLength = response.headers.get("content-length") || 0;
        const contentLengthMb = contentLength / 1024 / 1024;
        const prog = progressBar(contentLengthMb, msg);
        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 {
        throw new Error(`download failed (HTTP status ${response.status} - ${response.statusText})`);
    }
}
const kInstallableTools = {
    tinytex: tinyTexInstallable,
    chromium: chromiumInstallable
};
async function allTools() {
    const installed = [];
    const notInstalled = [];
    const tools = installableTools();
    for (const name of tools){
        const tool = installableTool(name);
        const isInstalled = await tool.installed();
        if (isInstalled) {
            installed.push(tool);
        } else {
            notInstalled.push(tool);
        }
    }
    return {
        installed,
        notInstalled
    };
}
function installableTools() {
    const tools = [];
    Object.keys(kInstallableTools).forEach((key)=>{
        const tool = kInstallableTools[key];
        tools.push(tool.name.toLowerCase());
    });
    return tools;
}
async function printToolInfo(name) {
    name = name || "";
    const tool = installableTool(name);
    if (tool) {
        const response = {
            name: tool.name,
            installed: await tool.installed(),
            version: await tool.installedVersion(),
            directory: await tool.installDir()
        };
        if (tool.binDir) {
            response["bin-directory"] = await tool.binDir();
        }
        if (response.installed && tool.verifyConfiguration) {
            response["configuration"] = await tool.verifyConfiguration();
        }
        Deno.stdout.writeSync(new TextEncoder().encode(JSON.stringify(response, null, 2) + "\n"));
    }
}
function checkToolRequirement(name) {
    if (name.toLowerCase() === "chromium" && isWSL()) {
        const troubleshootUrl = "https://pptr.dev/next/troubleshooting#running-puppeteer-on-wsl-windows-subsystem-for-linux.";
        warn([
            `${name} can't be installed fully on WSL with Quarto as system requirements could be missing.`,
            `- Please do a manual installation following recommandations at ${troubleshootUrl}`,
            "- See https://github.com/quarto-dev/quarto-cli/issues/1822 for more context."
        ].join("\n"));
        return false;
    } else {
        return true;
    }
}
async function installTool(name, updatePath) {
    name = name || "";
    const tool = installableTool(name);
    if (tool) {
        if (checkToolRequirement(name)) {
            const workingDir = Deno.makeTempDirSync();
            try {
                const context = installContext(workingDir, updatePath);
                context.info(`Installing ${name}`);
                const alreadyInstalled = await tool.installed();
                if (alreadyInstalled) {
                    context.error(`Install canceled - ${name} is already installed.`);
                    return Promise.reject();
                } else {
                    const platformPrereqs = tool.prereqs.filter((prereq)=>prereq.os.includes(Deno.build.os));
                    for (const prereq of platformPrereqs){
                        const met = await prereq.check(context);
                        if (!met) {
                            context.error(prereq.message);
                            return Promise.reject();
                        }
                    }
                    const pkgInfo = await tool.preparePackage(context);
                    await tool.install(pkgInfo, context);
                    const restartRequired = await tool.afterInstall(context);
                    context.info("Installation successful");
                    if (restartRequired) {
                        context.info("To complete this installation, please restart your system.");
                    }
                }
            } finally{
                Deno.removeSync(workingDir, {
                    recursive: true
                });
            }
        }
    } else {
        info(`Could not install '${name}'- try again with one of the following:`);
        installableTools().forEach((name)=>info("quarto install " + name, {
                indent: 2
            }));
    }
}
async function uninstallTool(name, updatePath) {
    const tool = installableTool(name);
    if (tool) {
        const installed = await tool.installed();
        if (installed) {
            const workingDir = Deno.makeTempDirSync();
            const context = installContext(workingDir, updatePath);
            context.info(`Uninstalling ${name}`);
            try {
                await tool.uninstall(context);
                info(`Uninstallation successful`);
            } catch (e) {
                logError(e);
            } finally{
                Deno.removeSync(workingDir, {
                    recursive: true
                });
            }
        } else {
            info(`${name} is not installed use 'quarto install ${name} to install it.`);
        }
    }
}
async function updateTool(name) {
    const summary = await toolSummary(name);
    const tool = installableTool(name);
    if (tool && summary && summary.installed) {
        const workingDir = Deno.makeTempDirSync();
        const context = installContext(workingDir);
        try {
            context.info(`Updating ${tool.name} from ${summary.installedVersion} to ${summary.latestRelease.version}`);
            const pkgInfo = await tool.preparePackage(context);
            context.info(`Removing ${summary.installedVersion}`);
            await tool.uninstall(context);
            context.info(`Installing ${summary.latestRelease.version}`);
            await tool.install(pkgInfo, context);
            context.info("Finishing update");
            const restartRequired = await tool.afterInstall(context);
            context.info("Update successful");
            if (restartRequired) {
                context.info("To complete this update, please restart your system.");
            }
        } catch (e) {
            logError(e);
        } finally{
            Deno.removeSync(workingDir, {
                recursive: true
            });
        }
    } else {
        info(`${name} is not installed use 'quarto install ${name.toLowerCase()} to install it.`);
    }
}
async function toolSummary(name) {
    const tool = installableTool(name);
    if (tool) {
        const installed = await tool.installed();
        const installedVersion = await tool.installedVersion();
        const latestRelease = await tool.latestRelease();
        const configuration = tool.verifyConfiguration && installed ? await tool.verifyConfiguration() : {
            status: "ok"
        };
        return {
            installed,
            installedVersion,
            latestRelease,
            configuration
        };
    } else {
        return undefined;
    }
}
function installableTool(name) {
    return kInstallableTools[name.toLowerCase()];
}
const installContext = (workingDir, updatePath)=>{
    const installMessaging = {
        info: (msg)=>{
            info(msg);
        },
        error: (msg)=>{
            info(msg);
        },
        confirm: (msg, def)=>{
            if (def !== undefined) {
                return Confirm.prompt({
                    message: msg,
                    default: def
                });
            } else {
                return Confirm.prompt(msg);
            }
        },
        withSpinner
    };
    return {
        download: async (name, url, target)=>{
            try {
                await downloadWithProgress(url, `Downloading ${name}`, target);
            } catch (error) {
                installMessaging.error(error.message);
                return Promise.reject();
            }
        },
        workingDir,
        ...installMessaging,
        props: {},
        flags: {
            [kUpdatePath]: updatePath
        }
    };
};
async function outputTools() {
    const toolRows = [];
    const statusMsgs = [];
    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 "External Installation";
            }
        } else {
            return "Not installed";
        }
    };
    const tools = await loadTools();
    for (const tool of tools){
        const summary = await toolSummary(tool.tool.name);
        if (summary) {
            const toolDetails = [
                tool.tool.name.toLowerCase(),
                installStatus(summary),
                summary.installedVersion || "---",
                summary.latestRelease.version
            ];
            toolRows.push(toolDetails);
            if (summary.configuration.status !== "ok") {
                statusMsgs.push(`${summary.configuration.message}`);
            }
        }
    }
    info("");
    const table = new Table().header([
        bold("Tool"),
        bold("Status"),
        bold("Installed"),
        bold("Latest")
    ]).body(toolRows).padding(5);
    info(table.toString());
    statusMsgs.forEach((msg)=>{
        warn(msg);
    });
}
async function loadTools() {
    let sorted = [];
    await withSpinner({
        message: "Inspecting tools"
    }, async ()=>{
        const all = await allTools();
        const toolsWithInstall = [
            {
                tools: all.installed,
                installed: true
            },
            {
                tools: all.notInstalled,
                installed: false
            }
        ];
        const toolInfos = [];
        for (const toolWithInstall of toolsWithInstall){
            for (const tool of toolWithInstall.tools){
                const version = await tool.installedVersion();
                const latest = await tool.latestRelease();
                toolInfos.push({
                    tool,
                    version,
                    installed: toolWithInstall.installed,
                    latest
                });
            }
        }
        sorted = toolInfos.sort((tool1, tool2)=>{
            return tool1.tool.name.localeCompare(tool2.tool.name);
        });
    });
    return sorted;
}
async function afterConfirm(message, action, prompt) {
    if (prompt !== false) {
        const confirmed = await Confirm.prompt({
            message,
            default: true
        });
        if (confirmed) {
            info("");
            return action();
        } else {
            return Promise.resolve();
        }
    } else {
        return action();
    }
}
const removeTool = (toolname, prompt, updatePath)=>{
    return afterConfirm(`Are you sure you'd like to remove ${toolname}?`, ()=>{
        return uninstallTool(toolname, updatePath);
    }, prompt);
};
async function updateOrInstallTool(tool, action, prompt, updatePath) {
    const summary = await toolSummary(tool);
    if (action === "update") {
        if (!summary?.installed) {
            return afterConfirm(`${tool} is not installed. Do you want to install it now?`, ()=>{
                return installTool(tool, updatePath);
            }, prompt);
        } else {
            if (summary.installedVersion === undefined) {
                info(`${tool} was not installed using Quarto. Please use the tool that you used to install ${tool} instead.`);
            } else if (summary.installedVersion === summary.latestRelease.version) {
                info(`${tool} is already up to date.`);
            } else {
                return afterConfirm(`Do you want to update ${tool} from ${summary.installedVersion} to ${summary.latestRelease.version}?`, ()=>{
                    return updateTool(tool);
                }, prompt);
            }
        }
    } else {
        if (summary && summary.installed) {
            if (summary.installedVersion === summary.latestRelease.version) {
                info(`${tool} is already installed and up to date.`);
            } else {
                return afterConfirm(`${tool} is already installed. Do you want to update to ${summary.latestRelease.version}?`, ()=>{
                    return updateTool(tool);
                }, prompt);
            }
        } else {
            return installTool(tool, updatePath);
        }
    }
}
async function selectTool(toolsInfo, action) {
    const name = (toolInfo)=>{
        if (action === "install" || action == "update") {
            if (toolInfo.installed) {
                return `${toolInfo.tool.name}${toolInfo.version ? " (" + toolInfo.version + " installed)" : ""}`;
            } else {
                return `${toolInfo.tool.name}${toolInfo.latest.version ? " (" + toolInfo.latest.version + ")" : ""}`;
            }
        } else {
            if (!toolInfo.installed) {
                return `${toolInfo.tool.name} (not installed)`;
            } else {
                return `${toolInfo.tool.name}${toolInfo.version ? " (" + toolInfo.version + " installed)" : ""}`;
            }
        }
    };
    const toolTarget = (await Select.prompt({
        message: `Select a tool to ${action}`,
        options: toolsInfo.map((toolInfo)=>{
            return {
                name: name(toolInfo),
                value: toolInfo.tool.name.toLowerCase(),
                disabled: action === "install" ? toolInfo.installed : !toolInfo.installed
            };
        })
    })).value;
    return toolTarget;
}
const toolsCommand = new Command().name("tools").description(`Display the status of Quarto installed dependencies`).example("Show tool status", "quarto tools").action(async (_options)=>{
    await outputTools();
}).command("install <tool:string>").hidden().action(async (_options, tool)=>{
    info("This command has been superseded. Please use `quarto install` instead.\n");
    await updateOrInstallTool(tool, "install");
}).command("info <tool:string>").hidden().action(async (_options, tool)=>{
    await printToolInfo(tool);
}).command("uninstall <tool:string>").hidden().action(async (_options, tool)=>{
    info("This command has been superseded. Please use `quarto uninstall` instead.\n");
    await removeTool(tool);
}).command("update <tool:string>").hidden().action(async (_options, tool)=>{
    info("This command has been superseded. Please use `quarto update` instead.\n");
    await updateOrInstallTool(tool, "update");
}).command("list").hidden().action(async ()=>{
    info("This command has been superseded. Please use `quarto tools` with no arguments to list tools and status.\n");
    await outputTools();
});
function watchProject(project, extensionDirs, resourceFiles, renderOptions, pandocArgs, options, renderingOnReload, renderManager, stopServer) {
    const nbContext = notebookContext();
    const flags = renderOptions.flags;
    const refreshProjectConfig = async ()=>{
        project = await projectContext(project.dir, nbContext, renderOptions, false);
    };
    if (project.config) {
        if (project.config.website) {
            project.config.website[kDraftMode] = kDraftModeVisible;
        }
    }
    const projDir = normalizePath(project.dir);
    const projDirHidden = projDir + "/.";
    const outputDir = projectOutputDir(project);
    const libDirConfig = project.config?.project[kProjectLibDir];
    const libDirSource = libDirConfig ? join2(project.dir, libDirConfig) : undefined;
    const isResourceFile = (path)=>{
        if (libDirSource && path.startsWith(libDirSource)) {
            return false;
        } else {
            return project.files.resources?.includes(path) || resourceFiles.includes(path);
        }
    };
    const extensionFiles = extensionFilesFromDirs(extensionDirs);
    const isExtensionFile = (path)=>{
        return extensionFiles.includes(path);
    };
    const isInputFile = (path)=>{
        return project.files.input.includes(path);
    };
    const rendered = new Map();
    const handleWatchEvent = async (event)=>{
        try {
            const paths = __VIRTUAL_FILE181(event.paths.filter((path)=>!path.startsWith(projDirHidden)).filter((path)=>outputDir === project.dir || !path.startsWith(outputDir)));
            if (paths.length === 0) {
                return;
            }
            if ([
                "modify",
                "create"
            ].includes(event.kind)) {
                if (options[kProjectWatchInputs]) {
                    const inputs = paths.filter(isInputFile).filter(existsSync1).filter((input)=>{
                        return !rendered.has(input) || rendered.get(input) !== md5Hash(Deno.readTextFileSync(input));
                    });
                    if (inputs.length) {
                        const services = renderServices(nbContext);
                        try {
                            const result1 = await renderManager.submitRender(()=>{
                                if (inputs.length > 1) {
                                    return renderProject(project, {
                                        services,
                                        progress: true,
                                        flags,
                                        pandocArgs,
                                        previewServer: true
                                    }, inputs);
                                } else {
                                    return render(inputs[0], {
                                        services,
                                        flags,
                                        pandocArgs: pandocArgs,
                                        previewServer: true
                                    });
                                }
                            });
                            if (result1.error) {
                                renderManager.onRenderError(result1.error);
                                return undefined;
                            } else {
                                for (const input of inputs.filter(existsSync1)){
                                    rendered.set(input, md5Hash(Deno.readTextFileSync(input)));
                                }
                                renderManager.onRenderResult(result1, extensionDirs, resourceFiles, project);
                                const nonSupplementalFiles = result1.files.filter((renderResultFile)=>{
                                    return !renderResultFile.supplemental;
                                });
                                return {
                                    config: false,
                                    output: true,
                                    reloadTarget: nonSupplementalFiles.length && !isPdfContent(nonSupplementalFiles[0].file) ? join2(outputDir, nonSupplementalFiles[0].file) : undefined
                                };
                            }
                        } finally{
                            services.cleanup();
                        }
                    }
                }
                const configFile = paths.some((path)=>(project.files.config || []).includes(path));
                const inputFileRemoved = project.files.input.some((file)=>!existsSync(file));
                const configResourceFile = paths.some((path)=>(project.files.configResources || []).includes(path) && !project.files.input.includes(path));
                const resourceFile = paths.some(isResourceFile);
                const extensionFile = paths.some(isExtensionFile);
                const reload = configFile || configResourceFile || resourceFile || extensionFile || inputFileRemoved;
                if (reload) {
                    return {
                        config: configFile || configResourceFile || inputFileRemoved,
                        output: false
                    };
                } else {
                    return;
                }
            } else {
                return;
            }
        } catch (e) {
            logError(e);
            return;
        }
    };
    const devServer = httpDevServer(options.timeout, ()=>renderManager.isRendering(), stopServer);
    const reloadClients = __VIRTUAL_FILE113(async (changes)=>{
        const services = renderServices(nbContext);
        try {
            if (!changes.output && !renderingOnReload) {
                await refreshProjectConfig();
                const result1 = await renderManager.submitRender(()=>renderProject(project, {
                        services,
                        useFreezer: true,
                        devServerReload: true,
                        flags,
                        pandocArgs,
                        previewServer: true
                    }));
                if (result1.error) {
                    renderManager.onRenderError(result1.error);
                } else {
                    renderManager.onRenderResult(result1, extensionDirs, resourceFiles, project);
                }
            }
            if (changes.config) {
                await refreshProjectConfig();
            }
            let reloadTarget = changes.reloadTarget || "";
            if (reloadTarget && await preventReload(project, reloadTarget, options)) {
                return;
            }
            if (reloadTarget && options.navigate) {
                if (reloadTarget.startsWith(outputDir)) {
                    reloadTarget = relative2(outputDir, reloadTarget);
                } else {
                    reloadTarget = relative2(projDir, reloadTarget);
                }
                if (existsSync(join2(outputDir, reloadTarget))) {
                    reloadTarget = "/" + pathWithForwardSlashes(reloadTarget);
                } else {
                    reloadTarget = "";
                }
            } else {
                reloadTarget = "";
            }
            devServer.reloadClients(reloadTarget);
        } catch (e) {
            logError(e);
        } finally{
            services.cleanup();
        }
    }, 100);
    const watcher = watchForFileChanges(()=>{
        return __VIRTUAL_FILE181([
            ...project.files.input,
            ...project.files.resources || [],
            ...project.files.config || [],
            ...project.files.configResources || [],
            ...resourceFiles,
            ...extensionFiles
        ]);
    });
    const watchForChanges = async ()=>{
        for await (const event of watcher){
            const result1 = await handleWatchEvent(event);
            if (result1) {
                await reloadClients(result1);
            }
        }
    };
    watchForChanges();
    return Promise.resolve({
        handle: (req)=>{
            return devServer.handle(req);
        },
        request: devServer.request,
        injectClient: (req, file, inputFile, contentType)=>{
            return devServer.injectClient(req, file, inputFile, contentType);
        },
        clientHtml: (req, inputFile)=>{
            return devServer.clientHtml(req, inputFile);
        },
        hasClients: ()=>devServer.hasClients(),
        reloadClients: async (output, reloadTarget)=>{
            await reloadClients({
                config: false,
                output,
                reloadTarget
            });
        },
        project: ()=>project,
        refreshProject: async ()=>{
            await refreshProjectConfig();
            return project;
        }
    });
}
async function preventReload(project, lastHtmlFile, options) {
    if (isRStudio() && !options[kProjectWatchInputs]) {
        const index = await inputTargetIndexForOutputFile(project, relative2(projectOutputDir(project), lastHtmlFile));
        if (index) {
            return isRevealjsOutput(Object.keys(index.formats)[0]);
        }
    }
    return false;
}
class ServeRenderManager {
    fileRequiresReRender(file, inputFile, extensionDirs, resourceFiles, project) {
        const lastRenderHash = this.fileRenders_.get(file);
        if (lastRenderHash) {
            return lastRenderHash !== this.fileRenderHash(file, inputFile, extensionDirs, resourceFiles, project);
        } else {
            return true;
        }
    }
    submitRender(render) {
        HttpDevServerRenderMonitor.onRenderStart();
        return this.renderQueue_.enqueue(render);
    }
    isRendering() {
        return this.renderQueue_.isRunning();
    }
    onRenderError(error) {
        HttpDevServerRenderMonitor.onRenderStop(false);
        if (error.message) {
            logError(error);
        }
    }
    onRenderResult(result1, extensionDirs, resourceFiles, project) {
        HttpDevServerRenderMonitor.onRenderStop(true);
        const fileOutputDir = (file)=>{
            const format = file.format;
            return projectFormatOutputDir(format, project, projectType(project.config?.project?.[kProjectType]));
        };
        result1.files.forEach((resultFile)=>{
            const file = isAbsolute2(resultFile.file) ? resultFile.file : join2(fileOutputDir(resultFile), resultFile.file);
            const inputFile = isAbsolute2(resultFile.input) ? resultFile.input : join2(project.dir, resultFile.input);
            this.fileRenders_.set(file, this.fileRenderHash(file, inputFile, extensionDirs, resourceFiles, project));
        });
    }
    fileRenderHash(file, inputFile, extensionDirs, resourceFiles, project) {
        const resourceHash = [
            file,
            inputFile,
            ...resourceFiles,
            ...extensionFilesFromDirs(extensionDirs),
            ...project.files.config || [],
            ...project.files.configResources || [],
            ...project.files.resources || []
        ].reduce((hash, file)=>{
            try {
                return hash + Deno.statSync(file).mtime?.toUTCString();
            } catch  {
                return hash;
            }
        }, "");
        if (isJupyterNotebook(inputFile) || !isHtmlContent(file)) {
            return String(Deno.statSync(file).mtime) + String(Deno.statSync(inputFile).mtime) + resourceHash;
        } else {
            return md5Hash(Deno.readTextFileSync(file)) + md5Hash(Deno.readTextFileSync(inputFile)) + resourceHash;
        }
    }
    fileRenders_ = new Map();
    renderQueue_ = new PromiseQueue();
}
async function handleHttpRequests(listener, handler) {
    for await (const conn of listener){
        (async ()=>{
            try {
                for await (const { request, respondWith } of Deno.serveHttp(conn)){
                    await respondWith(handler(request));
                }
            } catch (err) {
                warn(err.message);
                try {
                    conn.close();
                } catch  {}
            }
        })();
    }
}
const kRenderNone = "none";
const kRenderDefault = "default";
async function serveProject(target, renderOptions, pandocArgs, options, noServe) {
    let project;
    let flags = renderOptions.flags;
    const nbContext = renderOptions.services.notebook;
    if (typeof target === "string") {
        if (target === ".") {
            target = Deno.cwd();
        }
        project = await projectContext(target, nbContext, renderOptions);
        if (!project || !project?.config) {
            throw new Error(`${target} is not a project`);
        }
        const isMdFormat = (mdFormat, format)=>{
            if (!format) {
                return false;
            }
            if (typeof format === "string") {
                return format === mdFormat;
            } else if (typeof format === "object") {
                const formats = Object.keys(format);
                if (formats.length > 0) {
                    const firstFormat = Object.keys(format)[0];
                    return firstFormat === mdFormat;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        };
        const projType = projectType(project?.config?.project?.[kProjectType]);
        if (projType.type === "default" && !isMdFormat("docusaurus-md", project?.config?.format) && !isMdFormat("hugo-md", project?.config?.format)) {
            const hasIndex = project.files.input.some((file)=>{
                let relPath = file;
                if (project) {
                    relPath = relative2(project.dir, file);
                }
                const [dir, stem] = dirAndStem(relPath);
                return dir === "." && stem === "index";
            });
            if (!hasIndex && options.browser !== false) {
                throw new Error(`The project '${project.config.project.title || ""}' is a default type project which doesn't support project wide previewing unless there is an 'index' file present.\n\nPlease preview an individual file within this project instead.`);
            }
        }
    } else {
        project = target;
    }
    acquirePreviewLock(project);
    previewEnsureResources();
    previewMonitorResources();
    clearProjectIndex(project.dir);
    Deno.env.set("QUARTO_PROJECT_DIR", project.dir);
    options = {
        ...options,
        ...await resolvePreviewOptions(options, project)
    };
    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 || "");
    const services = renderServices(nbContext);
    let files;
    let resourceFiles = [];
    if (!renderBefore) {
        if (pdfOutput) {
            files = project.files.input;
        } else {
            const srvFiles = await serveFiles(project);
            files = srvFiles.files;
            resourceFiles = srvFiles.resourceFiles;
        }
    }
    let renderResult;
    try {
        renderResult = await renderProject(project, {
            services,
            progress: true,
            useFreezer: !renderBefore,
            flags,
            pandocArgs,
            previewServer: true
        }, files);
    } finally{
        services.cleanup();
    }
    if (renderResult.error) {
        throw renderResult.error;
    }
    resourceFiles.push(...__VIRTUAL_FILE181(renderResult.files.flatMap((file)=>file.resourceFiles)));
    const extensionDirs = projectExtensionDirs(project);
    const renderManager = new ServeRenderManager();
    renderManager.onRenderResult(renderResult, extensionDirs, resourceFiles, project);
    let stopServer = ()=>{};
    const watcher = await watchProject(project, extensionDirs, resourceFiles, {
        ...renderOptions,
        flags
    }, pandocArgs, options, !pdfOutput, renderManager, stopServer);
    printWatchingForChangesMessage();
    const serve = noServe ? false : projectPreviewServe(project) || true;
    const previewServer = serve === false ? await noPreviewServer() : serve === true ? await internalPreviewServer(project, renderResult, renderManager, pdfOutput, watcher, extensionDirs, resourceFiles, flags, pandocArgs, options) : await externalPreviewServer(project, serve, options, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs);
    stopServer = previewServer.stop;
    const path = await previewServer.start();
    if (path !== undefined) {
        printBrowsePreviewMessage(options.host, options.port, path);
        if (options.browser && !isServerSession()) {
            await openUrl(previewURL(options.host, options.port, path));
        }
    }
    onCleanup(stopServer);
    if (options.touchPath) {
        await touch(options.touchPath);
    }
    await previewServer.serve();
}
function externalPreviewServer(project, serve, options, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs) {
    let controlListener;
    if (renderToken()) {
        const outputDir = projectOutputDir(project);
        const handlerOptions = {
            baseDir: outputDir,
            onRequest: previewControlChannelRequestHandler(project, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs, false)
        };
        const handler = httpFileRequestHandler(handlerOptions);
        const port = findOpenPort();
        controlListener = Deno.listen({
            port,
            hostname: kLocalhost
        });
        handleHttpRequests(controlListener, handler).then(()=>{}).catch((_error)=>{});
        info(`Preview service running (${port})`);
    }
    const cmd = serve.cmd.split(/[\t ]/).map((arg, index)=>{
        if (Deno.build.os === "windows" && index === 0 && arg === "npm") {
            return "npm.cmd";
        } else if (arg === "{host}") {
            return options.host || kLocalhost;
        } else if (arg === "{port}") {
            return String(options.port);
        } else {
            return arg;
        }
    });
    if (serve.args) {
        cmd.push(...serve.args);
    }
    const readyPattern = new RegExp(serve.ready);
    const server = runExternalPreviewServer({
        cmd,
        readyPattern,
        env: serve.env,
        cwd: projectOutputDir(project)
    });
    return Promise.resolve({
        start: async ()=>{
            return server.start();
        },
        serve: async ()=>{
            return server.serve();
        },
        stop: ()=>{
            if (controlListener) {
                controlListener.close();
            }
            return server.stop();
        }
    });
}
async function internalPreviewServer(project, renderResult, renderManager, pdfOutput, watcher, extensionDirs, resourceFiles, flags, pandocArgs, options) {
    const projType = projectType(project?.config?.project?.[kProjectType]);
    const outputDir = projectOutputDir(project);
    const finalOutput = renderResultFinalOutput(renderResult);
    const pdfOutputFile = finalOutput && pdfOutput ? ()=>{
        const project = watcher.project();
        if (projType.type == kManuscriptType) {
            return finalOutput;
        } else {
            const outputFile = join2(dirname2(finalOutput), bookOutputStem(project.dir, project.config) + ".pdf");
            return outputFile;
        }
    } : undefined;
    const handlerOptions = {
        baseDir: outputDir,
        printUrls: "all",
        onRequest: previewControlChannelRequestHandler(project, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs, isBrowserPreviewable(finalOutput)),
        onFile: async (file, req)=>{
            const baseDir = projectOutputDir(project);
            const staticResponse = await staticResource(baseDir, file);
            if (staticResponse) {
                const resolveBody = ()=>{
                    if (staticResponse.injectClient) {
                        const contents = new TextDecoder().decode(staticResponse.contents);
                        return staticResponse.injectClient(contents, watcher.clientHtml(req));
                    } else {
                        return staticResponse.contents;
                    }
                };
                const body = resolveBody();
                const response = {
                    body,
                    contentType: staticResponse.contentType
                };
                return response;
            } else if (isHtmlContent(file) || isPdfContent(file) || isDocxContent(file) || isTextContent(file)) {
                const serveDir = projectOutputDir(watcher.project());
                const filePathRelative = relative2(serveDir, file);
                let inputFile = await inputFileForOutputFile(watcher.project(), filePathRelative);
                if (!inputFile) {
                    const fileSourcePath = join2(watcher.project().dir, filePathRelative);
                    const projectResourceFiles = watcher.project().files.resources;
                    if (projectResourceFiles?.includes(fileSourcePath)) {
                        return undefined;
                    }
                }
                if (!inputFile || !existsSync(inputFile.file)) {
                    inputFile = await inputFileForOutputFile(await watcher.refreshProject(), filePathRelative);
                }
                let result1;
                let renderError;
                if (inputFile) {
                    if (renderManager.fileRequiresReRender(file, inputFile.file, extensionDirs, resourceFiles, watcher.project())) {
                        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";
                        }
                        if (projType.incrementalFormatPreviewing) {
                            renderFlags.to = inputFile.format.identifier[kTargetFormat];
                            delete renderFlags?.clean;
                        }
                        const services = renderServices(notebookContext());
                        try {
                            result1 = await renderManager.submitRender(()=>renderProject(watcher.project(), {
                                    services,
                                    useFreezer: true,
                                    devServerReload: true,
                                    flags: renderFlags,
                                    pandocArgs: renderPandocArgs
                                }, [
                                    inputFile.file
                                ]));
                            if (result1.error) {
                                renderManager.onRenderError(result1.error);
                                renderError = result1.error;
                            } else {
                                renderManager.onRenderResult(result1, extensionDirs, resourceFiles, project);
                            }
                        } catch (e) {
                            logError(e);
                            renderError = e;
                        } finally{
                            services.cleanup();
                        }
                    }
                }
                const fileContents = renderError ? renderErrorPage(renderError) : Deno.readFileSync(file);
                if (isHtmlContent(file) && inputFile) {
                    const projInputFile = join2(project.dir, relative2(watcher.project().dir, inputFile.file));
                    return watcher.injectClient(req, fileContents, projInputFile);
                } else if (isTextContent(file) && inputFile) {
                    return previewTextContent(file, inputFile.file, inputFile.format, req, watcher.injectClient);
                } else {
                    return {
                        contentType: contentType(file),
                        body: fileContents
                    };
                }
            } else {
                return undefined;
            }
        },
        on404: (url, req)=>{
            const print = !basename2(url).startsWith("jupyter-");
            let body = new TextEncoder().encode("Not Found");
            const custom404 = join2(outputDir, kProject404File);
            if (existsSync(custom404)) {
                let content404 = Deno.readTextFileSync(custom404);
                const sitePath = websitePath(project?.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,
                response: watcher.injectClient(req, body)
            };
        }
    };
    if (finalOutput && pdfOutput) {
        handlerOptions.baseDir = pdfJsBaseDir();
        handlerOptions.onFile = pdfJsFileHandler(pdfOutputFile, async (file, req)=>{
            if (isHtmlContent(file)) {
                const fileContents = await Deno.readFile(file);
                return watcher.injectClient(req, fileContents);
            } else {
                return undefined;
            }
        });
    }
    const handler = httpFileRequestHandler(handlerOptions);
    let browserPath = options.browserPath ? options.browserPath.replace(/^\//, "") : undefined;
    if (browserPath) {
        const browserPathTarget = await resolveInputTarget(project, browserPath, false);
        if (browserPathTarget) {
            browserPath = browserPathTarget.outputHref;
        }
    }
    const targetPath = browserPath ? browserPath : pdfOutput ? kPdfJsInitialPath : renderResultUrlPath(renderResult);
    const path = targetPath && targetPath !== "index.html" ? targetPath : "";
    const listener = Deno.listen({
        port: options.port,
        hostname: options.host
    });
    return {
        start: ()=>Promise.resolve(path),
        serve: async ()=>{
            await handleHttpRequests(listener, handler);
        },
        stop: ()=>{
            listener.close();
            return Promise.resolve();
        }
    };
}
function previewControlChannelRequestHandler(project, renderManager, watcher, extensionDirs, resourceFiles, flags, pandocArgs, requireActiveClient) {
    return async (req)=>{
        if (watcher.handle(req)) {
            return await watcher.request(req);
        } else if (isPreviewTerminateRequest(req)) {
            exitWithCleanup(0);
        } else if (isPreviewRenderRequest(req)) {
            const prevReq = previewRenderRequest(req, requireActiveClient ? watcher.hasClients() : true, project.dir);
            if (prevReq && await previewRenderRequestIsCompatible(prevReq, flags.to, project)) {
                if (isProjectInputFile(prevReq.path, project)) {
                    const services = renderServices(notebookContext());
                    const to = flags.to === "all" ? prevReq.format || "html" : flags.to;
                    renderManager.submitRender(()=>render(prevReq.path, {
                            services,
                            flags: {
                                ...flags,
                                to
                            },
                            pandocArgs,
                            previewServer: true
                        })).then((result1)=>{
                        if (result1.error) {
                            renderManager.onRenderError(result1.error);
                        } else {
                            const finalOutput = renderResultFinalOutput(result1, dirname2(prevReq.path));
                            if (!finalOutput) {
                                throw new Error("No output created by quarto render " + basename2(prevReq.path));
                            }
                            renderManager.onRenderResult(result1, extensionDirs, resourceFiles, watcher.project());
                            info("Output created: " + finalOutput + "\n");
                            printWatchingForChangesMessage();
                            watcher.reloadClients(true, !isPdfContent(finalOutput) ? join2(dirname2(prevReq.path), finalOutput) : undefined);
                        }
                    }).finally(()=>{
                        services.cleanup();
                    });
                    return httpContentResponse("rendered");
                } else if (extname2(prevReq.path) === ".md" && projectPreviewServe(project)) {
                    return httpContentResponse("rendered");
                } else {
                    return previewUnableToRenderResponse();
                }
            } else {
                return previewUnableToRenderResponse();
            }
        } else {
            return undefined;
        }
    };
}
function sleepSync(timeout) {
    const sab = new SharedArrayBuffer(1024);
    const int32 = new Int32Array(sab);
    Atomics.wait(int32, 0, 0, timeout);
}
function acquirePreviewLock(project) {
    const lockfile = previewLockFile(project);
    if (existsSync(lockfile)) {
        const pid = parseInt(Deno.readTextFileSync(lockfile)) || undefined;
        if (pid) {
            info(bold(blue("Terminating existing preview server....")), {
                newline: false
            });
            try {
                Deno.kill(pid, "SIGTERM");
                sleepSync(3000);
            } catch  {} finally{
                info(bold(blue("DONE\n")));
            }
        }
    }
    Deno.writeTextFileSync(lockfile, String(Deno.pid));
    onCleanup(()=>releasePreviewLock(project));
}
function releasePreviewLock(project) {
    try {
        Deno.removeSync(previewLockFile(project));
    } catch  {}
}
function previewLockFile(project) {
    return projectScratchPath(project.dir, join2("preview", "lock"));
}
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) {
    const projType = projectType(project.config?.project?.[kProjectType]);
    await initDenoDom();
    const files = [];
    const resourceFiles = [];
    for(let i1 = 0; i1 < project.files.input.length; i1++){
        const inputFile = project.files.input[i1];
        const projRelative = relative2(project.dir, inputFile);
        const target = await resolveInputTarget(project, projRelative, false);
        if (target) {
            const outputFile = join2(projectOutputDir(project), target?.outputHref);
            if (isModifiedAfter(inputFile, outputFile) || projType.previewSkipUnmodified === false) {
                files.push(inputFile);
            } else {
                const outputResources = [];
                if (isHtmlContent(outputFile)) {
                    const htmlInput = Deno.readTextFileSync(outputFile);
                    const doc = new DOMParser().parseFromString(htmlInput, "text/html");
                    const resolver = htmlResourceResolverPostprocessor(inputFile, project);
                    outputResources.push(...(await resolver(doc)).resources);
                }
                const partitioned = await partitionedMarkdownForInput(project, projRelative);
                const globs = [];
                if (partitioned?.yaml) {
                    const metadata = partitioned.yaml;
                    globs.push(...resourcesFromMetadata(metadata[kResources]));
                }
                resourceFiles.push(...await resourceFilesFromFile(project.dir, projectExcludeDirs(project), projRelative, {
                    files: outputResources,
                    globs
                }, false, [
                    join2(dirname2(projRelative), inputFilesDir(projRelative))
                ], partitioned));
            }
        } else {
            warn("Unabled to resolve output target for " + inputFile);
        }
    }
    return {
        files,
        resourceFiles: __VIRTUAL_FILE181(resourceFiles)
    };
}
async function previewShiny(options) {
    previewMonitorResources();
    let rendering = false;
    const renderingFile = isAbsolute2(options.input) ? options.input : join2(Deno.cwd(), options.input);
    const render = async (to)=>{
        to = to || options.format;
        const renderFlags = {
            to,
            execute: true
        };
        const services = renderServices(notebookContext());
        try {
            rendering = true;
            const result1 = await renderForPreview(options.input, services, renderFlags, options.pandocArgs, options.project);
            return result1;
        } finally{
            services.cleanup();
            rendering = false;
        }
    };
    const result1 = await render();
    const changeHandler = createChangeHandler(result1, {
        reloadClients: async ()=>{
            await render();
        }
    }, render, options.watchInputs, (file)=>{
        const ext = extname2(file);
        return ![
            ".py",
            ".html",
            ".htm"
        ].includes(ext);
    }, (files)=>{
        if (files.length === 1 && files[0] === renderingFile && extname2(files[0]) === ".ipynb") {
            return rendering;
        }
        return false;
    });
    if (renderToken()) {
        runPreviewControlService(options, changeHandler.render);
    }
    return await serve({
        ...options,
        render: false,
        reload: true
    });
}
function runPreviewControlService(options, renderHandler) {
    const isCompatibleRequest = async (prevReq)=>{
        return normalizePath(options.input) === normalizePath(prevReq.path) && await previewRenderRequestIsCompatible(prevReq, options.format, options.project);
    };
    const baseDir = dirname2(options.input);
    const handlerOptions = {
        baseDir,
        onRequest: async (req)=>{
            if (isPreviewTerminateRequest(req)) {
                exitWithCleanup(0);
            } else if (isPreviewRenderRequest(req)) {
                const prevReq = previewRenderRequest(req, true, baseDir);
                if (prevReq && await isCompatibleRequest(prevReq)) {
                    renderHandler();
                    return httpContentResponse("rendered");
                } else {
                    return previewUnableToRenderResponse();
                }
            } else {
                return undefined;
            }
        }
    };
    const handler = httpFileRequestHandler(handlerOptions);
    const port = findOpenPort();
    const controlListener = Deno.listen({
        port,
        hostname: kLocalhost
    });
    onCleanup(()=>controlListener.close());
    handleHttpRequests(controlListener, handler).then(()=>{}).catch((_error)=>{});
    info(`Preview service running (${port})`);
}
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-serve", "Don't run a local preview web server (just monitor and re-render input files)").option("--no-navigate", "Don't navigate the browser automatically when outputs are updated.").option("--no-browser", "Don't open a browser to preview the site.").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 document or website project.\n\nAutomatically reloads the browser when " + "input files 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();
    if (!file || file === kCliffyImplicitCwd) {
        file = Deno.cwd();
        const firstArg = args.find((arg)=>arg.endsWith(".qmd") || arg.endsWith(".ipynb"));
        if (firstArg) {
            warn("`quarto preview` invoked with no input file specified (the parameter order matters).\nQuarto will preview the current directory by default.\n" + `Did you mean to run \`quarto preview ${firstArg} ${args.filter((arg)=>arg !== firstArg).join(" ")}\`?\n` + "Use `quarto preview --help` for more information.");
        }
    }
    file = file || Deno.cwd();
    if (!existsSync(file)) {
        throw new Error(`${file} not found`);
    }
    if (args.length > 0 && args[0] === "--help") {
        previewCommand.showHelp();
        return;
    }
    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 noServePos = args.indexOf("--no-serve");
    if (noServePos !== -1) {
        options.noServe = true;
        args.splice(noServePos, 1);
    }
    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 navigatePos = args.indexOf("--navigate");
    if (navigatePos !== -1) {
        options.navigate = true;
        args.splice(navigatePos, 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);
    }
    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.port) {
        const port = parseInt(options.port);
        if (await waitForPort({
            port,
            hostname: kLocalhost
        })) {
            options.port = port;
        } else {
            throw new Error(`Requested port ${options.port} is already in use.`);
        }
    }
    const flags = await parseRenderFlags(args);
    args = fixupPandocArgs(args, flags);
    let touchPath;
    let projectTarget = file;
    if (Deno.statSync(file).isFile) {
        const nbContext = notebookContext();
        const project = await projectContext(dirname2(file), nbContext) || singleFileProjectContext(file, nbContext);
        const formats = await (async ()=>{
            const services = renderServices(nbContext);
            try {
                return await renderFormats(file, services, undefined, project);
            } finally{
                services.cleanup();
            }
        })();
        const format = await previewFormat(file, flags.to, formats, project);
        if (isHtmlOutput(parseFormatString(format).baseFormat)) {
            const renderFormat = formats[format];
            if (renderFormat && isServerShiny(renderFormat)) {
                const engine = await fileExecutionEngine(file, flags, project);
                setPreviewFormat(format, flags, args);
                if (isServerShinyPython(renderFormat, engine?.name)) {
                    const result1 = await previewShiny({
                        input: file,
                        render: !!options.render,
                        port: typeof options.port === "string" ? parseInt(options.port) : options.port,
                        host: options.host,
                        browser: options.browser,
                        projectDir: project?.dir,
                        tempDir: Deno.makeTempDirSync(),
                        format,
                        pandocArgs: args,
                        watchInputs: options.watchInputs
                    });
                    Deno.exit(result1.code);
                } else {
                    const result1 = await serve({
                        input: file,
                        render: !!options.render,
                        port: typeof options.port === "string" ? parseInt(options.port) : options.port,
                        host: options.host,
                        format: format,
                        browser: options.browser,
                        projectDir: project?.dir,
                        tempDir: Deno.makeTempDirSync()
                    });
                    Deno.exit(result1.code);
                }
            }
        }
        if (project && projectIsServeable(project)) {
            const filePath = normalizePath(file);
            if (!project.files.input.includes(filePath)) {
                if (extname2(file) === ".md" && projectPreviewServe(project)) {
                    setPreviewFormat(format, flags, args);
                    touchPath = filePath;
                    options.browserPath = "";
                    file = project.dir;
                    projectTarget = project;
                }
            } else {
                if (isHtmlOutput(parseFormatString(format).baseFormat, true) || projectPreviewServe(project)) {
                    setPreviewFormat(format, flags, args);
                    const services = renderServices(notebookContext());
                    try {
                        const renderResult = await renderProject(project, {
                            services,
                            progress: false,
                            useFreezer: false,
                            flags,
                            pandocArgs: args,
                            previewServer: true
                        }, [
                            file
                        ]);
                        if (renderResult.error) {
                            throw renderResult.error;
                        }
                        handleRenderResult(file, renderResult);
                        if (projectPreviewServe(project) && renderResult.baseDir) {
                            touchPath = join2(renderResult.baseDir, renderResult.files[0].file);
                        }
                    } finally{
                        services.cleanup();
                    }
                    if (projectPreviewServe(project)) {
                        options.browserPath = "";
                    } else {
                        options.browserPath = relative2(project.dir, file);
                    }
                    file = project.dir;
                    projectTarget = project;
                }
            }
        }
    }
    if (Deno.statSync(file).isDirectory) {
        const renderOptions = {
            services: renderServices(notebookContext()),
            flags
        };
        await serveProject(projectTarget, renderOptions, args, {
            port: options.port,
            host: options.host,
            browser: options.browser === false || options.browse === false ? false : undefined,
            [kProjectWatchInputs]: options.watchInputs,
            timeout: options.timeout,
            render: options.render,
            touchPath,
            browserPath: options.browserPath,
            navigate: options.navigate
        }, options.noServe === true);
    } else {
        if (options.render !== kRenderNone && options.render !== kRenderDefault && args.indexOf("--to") === -1) {
            args.push("--to", options.render);
        }
        await preview(relative2(Deno.cwd(), file), flags, args, {
            port: options.port,
            host: options.host,
            browser: options.browser === false || options.browse === false ? false : undefined,
            [kProjectWatchInputs]: options.watchInputs,
            timeout: options.timeout,
            presentation: options.presentation
        });
    }
});
async function markdownToJupyterNotebook(file, includeIds) {
    const markdown = Deno.readTextFileSync(file);
    const notebook = await quartoMdToJupyter(markdown, includeIds);
    return JSON.stringify(notebook, null, 2);
}
async function jupyterNotebookToMarkdown(file, includeIds) {
    const notebook = fixupFrontMatter(jupyterFromFile(file));
    const kernelspec = notebook.metadata.kernelspec;
    const md = [];
    let frontMatter;
    for(let i1 = 0; i1 < notebook.cells.length; i1++){
        {
            const cell = notebook.cells[i1];
            const cellWithOptions = jupyterCellWithOptions(i1, kernelspec.language, cell);
            switch(cell.cell_type){
                case "markdown":
                    md.push(...mdFromContentCell(cellWithOptions));
                    break;
                case "raw":
                    if (frontMatter === undefined) {
                        frontMatter = partitionYamlFrontMatter(jupyterCellSrcAsStr(cell))?.yaml;
                        if (!frontMatter) {
                            md.push(...mdFromRawCell(cellWithOptions));
                        }
                    } else {
                        md.push(...mdFromRawCell(cellWithOptions));
                    }
                    break;
                case "code":
                    md.push(...await mdFromCodeCell1(kernelspec.language.toLowerCase(), cell, includeIds));
                    break;
                default:
                    throw new Error("Unexpected cell type " + cell.cell_type);
            }
            if (i1 > 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,
        lineWidth: -1,
        sortKeys: false,
        skipInvalid: true
    });
    return `---\n${yamlText}---\n\n${mdSource}`;
}
async function mdFromCodeCell1(language, cell, includeIds) {
    if (!cell.source.length) {
        return [];
    }
    const maxBackticks = Math.max(...jupyterCellSrcAsLines(cell).map((line)=>line.match(/^`+/g)?.[0].length || 0), 2);
    const backticks = "`".repeat(maxBackticks + 1);
    const md = [
        backticks + "{" + language + "}\n"
    ];
    const { yaml, source } = await partitionCellOptions(language, jupyterCellSrcAsLines(cell));
    const options = yaml ? yaml : {};
    if (!includeIds) {
        delete cell.id;
        delete cell.metadata["id"];
        delete cell.metadata["outputId"];
    } else {
        if (cell.id) {
            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(backticks + "\n");
    return md;
}
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)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    if (!existsSync(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 = join2(dir, stem + (srcFormat === kMarkdownFormat ? ".ipynb" : ".qmd"));
    }
    Deno.writeTextFileSync(output, converted);
    info(`Converted to ${output}`);
});
async function runScript(args, env) {
    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), undefined, {
        env
    });
}
const runCommand = new Command().name("run").stopEarly().arguments("[script:string] [...args]").description("Run a TypeScript, R, Python, or Lua script.\n\n" + "Run a utility script written in a variety of languages. For details, see:\n" + "https://quarto.org/docs/projects/scripts.html#periodic-scripts");
const pandocCommand = new Command().name("pandoc").stopEarly().arguments("[...args]").description("Run the version of Pandoc embedded within Quarto.\n\n" + "You can pass arbitrary command line arguments to quarto pandoc (they will\n" + "be passed through unmodified to Pandoc)").example("Render markdown to HTML", "quarto pandoc document.md --to html --output document.html").example("List Pandoc output formats", "quarto pandoc --list-output-formats");
const typstCommand = new Command().name("typst").stopEarly().arguments("[...args]").description("Run the version of Typst embedded within Quarto.\n\n" + "You can pass arbitrary command line arguments to quarto typst (they will\n" + "be passed through unmodified to Typst)").example("Compile Typst to PDF", "quarto typst compile document.typ").example("List all discovered fonts in system and custom font paths", "quarto typst fonts");
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 formats = await pandocListFormats();
    const commonFormats = [
        "html",
        "pdf",
        "docx",
        "odt",
        "pptx",
        "beamer",
        "revealjs",
        "gfm",
        "epub",
        "dashboard",
        "email"
    ];
    const excludedFormats = [
        "bibtex",
        "biblatex",
        "csljson"
    ];
    return __VIRTUAL_FILE137(commonFormats.concat(__VIRTUAL_FILE137(formats, commonFormats)), excludedFormats);
}
async function themes() {
    const themesPath = formatResourcePath("html", join2("bootstrap", "themes"));
    const themes = [
        "default"
    ];
    const kScss = ".scss";
    for await (const dirEntry of Deno.readDir(themesPath)){
        if (dirEntry.isFile && dirEntry.name.endsWith(kScss)) {
            themes.push(basename2(dirEntry.name, kScss));
        }
    }
    return themes;
}
const capabilitiesCommand = new Command().name("capabilities").description("Query for current capabilities (formats, engines, kernels etc.)").hidden().action(async ()=>{
    const capsJSON = JSON.stringify(await capabilities(), undefined, 2);
    writeAllSync(Deno.stdout, new TextEncoder().encode(capsJSON));
});
const kIndent = "      ";
async function check(target) {
    const services = renderServices(notebookContext());
    try {
        info(`Quarto ${quartoConfig.version()}`);
        if (target === "versions" || target === "all") {
            await checkVersions(services);
        }
        if (target === "install" || target === "all") {
            await checkInstall(services);
        }
        if (target === "jupyter" || target === "all") {
            await checkJupyterInstallation(services);
        }
        if (target === "knitr" || target === "all") {
            await checkKnitrInstallation(services);
        }
    } finally{
        services.cleanup();
    }
}
async function checkVersions(_services) {
    const checkVersion = async (version, constraint, name)=>{
        if (typeof version !== "string") {
            throw new Error(`Unable to determine ${name} version`);
        }
        if (!satisfies(version, constraint)) {
            info(`      NOTE: ${name} version ${version} is too old. Please upgrade to ${constraint.slice(2)} or later.`);
        } else {
            info(`      ${name} version ${version}: OK`);
        }
    };
    completeMessage("Checking versions of quarto binary dependencies...");
    let pandocVersion = lines((await execProcess({
        cmd: [
            pandocBinaryPath(),
            "--version"
        ],
        stdout: "piped"
    })).stdout)[0]?.split(" ")[1];
    if (pandocVersion) {
        const versionParts = pandocVersion.split(".");
        if (versionParts.length > 3) {
            pandocVersion = versionParts.slice(0, 3).join(".");
        } else if (versionParts.length < 3) {
            pandocVersion = versionParts.concat(Array(3 - versionParts.length).fill("0")).join(".");
        }
    }
    checkVersion(pandocVersion, ">=2.19.2", "Pandoc");
    const sassVersion = (await dartCommand([
        "--version"
    ]))?.trim();
    checkVersion(sassVersion, ">=1.32.8", "Dart Sass");
    if (!satisfies(Deno.version.deno, ">=1.33.1")) {
        info(`      NOTE: Deno version ${Deno.version.deno} is too old. Please upgrade to 1.33.1 or later.`);
    } else {
        info(`      Deno version ${Deno.version.deno}: OK`);
    }
    let typstVersion = lines((await execProcess({
        cmd: [
            typstBinaryPath(),
            "--version"
        ],
        stdout: "piped"
    })).stdout)[0].split(" ")[1];
    checkVersion(typstVersion, ">=0.10.0", "Typst");
    completeMessage("Checking versions of quarto dependencies......OK");
}
async function checkInstall(services) {
    completeMessage("Checking Quarto installation......OK");
    info(`${kIndent}Version: ${quartoConfig.version()}`);
    if (quartoConfig.version() === "99.9.9") {
        const quartoRoot = Deno.env.get("QUARTO_ROOT");
        if (quartoRoot) {
            const gitHead = await execProcess({
                cmd: [
                    "git",
                    "-C",
                    quartoRoot,
                    "rev-parse",
                    "HEAD"
                ],
                stdout: "piped",
                stderr: "piped"
            });
            if (gitHead.success && gitHead.stdout) {
                info(`${kIndent}commit: ${gitHead.stdout.trim()}`);
            }
        }
    }
    info(`${kIndent}Path: ${quartoConfig.binPath()}`);
    if (Deno.build.os === "windows") {
        try {
            const codePage = readCodePage();
            clearCodePageCache();
            await cacheCodePage();
            const codePage2 = readCodePage();
            info(`${kIndent}CodePage: ${codePage2 || "unknown"}`);
            if (codePage && codePage !== codePage2) {
                info(`${kIndent}NOTE: Code page updated from ${codePage} to ${codePage2}. Previous rendering may have been affected.`);
            }
            const nonAscii = /[^\x00-\x7F]+/;
            if (nonAscii.test(quartoConfig.binPath())) {
                info(`${kIndent}ERROR: Non-ASCII characters in Quarto path causes rendering problems.`);
            }
        } catch  {
            info(`${kIndent}CodePage: Unable to read code page`);
        }
    }
    info("");
    const toolsMessage = "Checking tools....................";
    const toolsOutput = [];
    await withSpinner({
        message: toolsMessage,
        doneMessage: toolsMessage + "OK"
    }, async ()=>{
        const tools = await allTools();
        for (const tool of tools.installed){
            const version = await tool.installedVersion() || "(external install)";
            toolsOutput.push(`${kIndent}${tool.name}: ${version}`);
        }
        for (const tool of tools.notInstalled){
            toolsOutput.push(`${kIndent}${tool.name}: (not installed)`);
        }
    });
    toolsOutput.forEach((out)=>info(out));
    info("");
    const latexMessage = "Checking LaTeX....................";
    const latexOutput = [];
    await withSpinner({
        message: latexMessage,
        doneMessage: latexMessage + "OK"
    }, async ()=>{
        const tlContext = await texLiveContext(true);
        if (tlContext.hasTexLive) {
            const version = await tlVersion(tlContext);
            if (tlContext.usingGlobal) {
                const tlMgrPath = await which("tlmgr");
                latexOutput.push(`${kIndent}Using: Installation From Path`);
                if (tlMgrPath) {
                    latexOutput.push(`${kIndent}Path: ${dirname2(tlMgrPath)}`);
                }
            } else {
                latexOutput.push(`${kIndent}Using: TinyTex`);
                if (tlContext.binDir) {
                    latexOutput.push(`${kIndent}Path: ${tlContext.binDir}`);
                }
            }
            latexOutput.push(`${kIndent}Version: ${version}`);
        } else {
            latexOutput.push(`${kIndent}Tex:  (not detected)`);
        }
    });
    latexOutput.forEach((out)=>info(out));
    info("");
    const kMessage = "Checking basic markdown render....";
    await withSpinner({
        message: kMessage,
        doneMessage: kMessage + "OK\n"
    }, async ()=>{
        const mdPath = services.temp.createFile({
            suffix: "check.md"
        });
        Deno.writeTextFileSync(mdPath, `
---
title: "Title"
---

## Header
`);
        const result1 = await render(mdPath, {
            services,
            flags: {
                quiet: true
            }
        });
        if (result1.error) {
            throw result1.error;
        }
    });
}
async function checkJupyterInstallation(services) {
    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) {
            if (await jupyterKernelspecForLanguage("python")) {
                const kJupyterMessage = "Checking Jupyter engine render....";
                await withSpinner({
                    message: kJupyterMessage,
                    doneMessage: kJupyterMessage + "OK\n"
                }, async ()=>{
                    await checkJupyterRender(services);
                });
            } else {
                info(kIndent + "NOTE: No Jupyter kernel for Python found");
                info("");
            }
        } else {
            info(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(services) {
    const qmdPath = services.temp.createFile({
        suffix: "check.qmd"
    });
    Deno.writeTextFileSync(qmdPath, `
---
title: "Title"
---

## Header

\`\`\`{python}
1 + 1
\`\`\`
`);
    const result1 = await render(qmdPath, {
        services,
        flags: {
            quiet: true,
            executeDaemon: 0
        }
    });
    if (result1.error) {
        throw result1.error;
    }
}
async function checkKnitrInstallation(services) {
    const kMessage = "Checking R installation...........";
    let caps;
    let rBin;
    await withSpinner({
        message: kMessage,
        doneMessage: false
    }, async ()=>{
        rBin = await checkRBinary();
        caps = await knitrCapabilities(rBin);
    });
    if (rBin && caps) {
        completeMessage(kMessage + "OK");
        info(knitrCapabilitiesMessage(caps, kIndent));
        info("");
        if (caps.packages.rmarkdownVersOk && caps.packages.knitrVersOk) {
            const kKnitrMessage = "Checking Knitr engine render......";
            await withSpinner({
                message: kKnitrMessage,
                doneMessage: kKnitrMessage + "OK\n"
            }, async ()=>{
                await checkKnitrRender(services);
            });
        } else {
            if (!!!caps.packages.knitr || !caps.packages.knitrVersOk) {
                info(knitrInstallationMessage(kIndent, "knitr", !!caps.packages.knitr && !caps.packages.knitrVersOk));
            }
            if (!!!caps.packages.rmarkdown || !caps.packages.rmarkdownVersOk) {
                info(knitrInstallationMessage(kIndent, "rmarkdown", !!caps.packages.rmarkdown && !caps.packages.rmarkdownVersOk));
            }
            info("");
        }
    } else if (rBin === undefined) {
        completeMessage(kMessage + "(None)\n");
        info(rInstallationMessage(kIndent));
        info("");
    } else if (caps === undefined) {
        completeMessage(kMessage + "(None)\n");
        info(`R succesfully found at ${rBin}.`);
        info("However, a problem was encountered when checking configurations of packages.");
        info("Please check your installation of R.");
        info("");
    }
}
async function checkKnitrRender(services) {
    const rmdPath = services.temp.createFile({
        suffix: "check.rmd"
    });
    Deno.writeTextFileSync(rmdPath, `
---
title: "Title"
---

## Header

\`\`\`{r}
1 + 1
\`\`\`
`);
    const result1 = await render(rmdPath, {
        services,
        flags: {
            quiet: true
        }
    });
    if (result1.error) {
        throw result1.error;
    }
}
const kTargets = [
    "install",
    "jupyter",
    "knitr",
    "versions",
    "all"
];
const checkCommand = new Command().name("check").arguments("[target:string]").description("Verify correct functioning of Quarto installation.\n\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);
});
function isDocumentConfig(config) {
    return config.formats !== undefined;
}
async function inspectConfig(path) {
    path = path || Deno.cwd();
    if (!existsSync(path)) {
        throw new Error(`${path} not found`);
    }
    let version = quartoConfig.version();
    if (version === kLocalDevelopment) {
        version = "99.9.9";
    }
    const nbContext = notebookContext();
    const context = await projectContext(path, nbContext);
    const inspectedProjectConfig = async ()=>{
        if (context?.config) {
            const fileInformation = {};
            for (const file of context.files.input){
                const engine = await fileExecutionEngine(file, undefined, context);
                const src = await context.resolveFullMarkdownForFile(engine, file);
                if (engine) {
                    const errors = await validateDocumentFromSource(src, engine.name, error);
                    if (errors.length) {
                        throw new Error(`${path} is not a valid Quarto input document`);
                    }
                }
                await projectResolveCodeCellsForFile(context, engine, file);
                fileInformation[file] = {
                    includeMap: context.fileInformationCache.get(file)?.includeMap ?? [],
                    codeCells: context.fileInformationCache.get(file)?.codeCells ?? []
                };
            }
            const config = {
                quarto: {
                    version
                },
                dir: context.dir,
                engines: context.engines,
                config: context.config,
                files: context.files,
                fileInformation
            };
            return config;
        } else {
            return undefined;
        }
    };
    const stat = Deno.statSync(path);
    if (stat.isDirectory) {
        const config = await inspectedProjectConfig();
        if (config) {
            return config;
        } else {
            throw new Error(`${path} is not a Quarto project.`);
        }
    } else {
        const project = await projectContext(path, nbContext) || singleFileProjectContext(path, nbContext);
        const engine = await fileExecutionEngine(path, undefined, project);
        if (engine) {
            const partitioned = await engine.partitionedMarkdown(path);
            const context = await projectContext(path, nbContext) || singleFileProjectContext(path, nbContext);
            const src = await context.resolveFullMarkdownForFile(engine, path);
            if (engine) {
                const errors = await validateDocumentFromSource(src, engine.name, error);
                if (errors.length) {
                    throw new Error(`${path} is not a valid Quarto input document`);
                }
            }
            const formats = await withRenderServices(nbContext, (services)=>renderFormats(path, services, "all", context));
            const resourceConfig = Object.values(formats).reduce((resources, format)=>{
                resources = uniq1(resources.concat(resourcesFromMetadata(format.metadata[kResources])));
                if (format.pandoc[kCss]) {
                    return __VIRTUAL_FILE181(resources.concat(resourcesFromMetadata(format.pandoc[kCss])));
                } else {
                    return resources;
                }
            }, []);
            const fileDir = normalizePath(dirname2(path));
            const excludeDirs = context ? projectExcludeDirs(context) : [];
            const resources = await resolveResources(context ? context.dir : fileDir, fileDir, excludeDirs, partitioned.markdown, resourceConfig);
            const extensions = join2(fileDir, kExtensionDir);
            if (safeExistsSync(extensions)) {
                resources.push(...extensionFilesFromDirs([
                    extensions
                ]).map((file)=>relative2(fileDir, file)));
            }
            await context.resolveFullMarkdownForFile(engine, path);
            await projectResolveCodeCellsForFile(context, engine, path);
            const fileInformation = context.fileInformationCache.get(path);
            const config = {
                quarto: {
                    version
                },
                engines: [
                    engine.name
                ],
                formats,
                resources,
                fileInformation: {
                    [path]: {
                        includeMap: fileInformation?.includeMap ?? [],
                        codeCells: fileInformation?.codeCells ?? []
                    }
                }
            };
            if (context?.config) {
                config.project = await inspectedProjectConfig();
            }
            return config;
        } else {
            throw new Error(`${path} is not a valid Quarto input document`);
        }
    }
}
async function resolveResources(rootDir, fileDir, excludeDirs, markdown, globs) {
    const resolved = await resolveFileResources(rootDir, fileDir, excludeDirs, markdown, globs);
    const resources = __VIRTUAL_FILE137(resolved.include, resolved.exclude);
    const allResources = resources.concat(cssFileResourceReferences(resources));
    return allResources.map((file)=>relative2(rootDir, file));
}
const inspectCommand = new Command().name("inspect").arguments("[path] [output]").description("Inspect a Quarto project or input path.\n\nInspecting 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 output (or stdout if not provided).").hidden().example("Inspect project in current directory", "quarto inspect").example("Inspect project in directory", "quarto inspect myproject").example("Inspect input path", "quarto inspect document.md").example("Inspect input path and write to file", "quarto inspect document.md output.json").action(async (_options, path, output)=>{
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
    path = path || Deno.cwd();
    const config = await inspectConfig(path);
    const outputJson = JSON.stringify(config, undefined, 2);
    if (!output) {
        Deno.stdout.writeSync(new TextEncoder().encode(outputJson + "\n"));
    } else {
        Deno.writeTextFileSync(output, outputJson + "\n");
    }
});
let schemaResourcesLoaded = false;
async function ensureSchemaResources() {
    if (!schemaResourcesLoaded) {
        schemaResourcesLoaded = true;
        const resources = {};
        for (const walk of expandGlobSync1(resourcePath("schema/*.yml"))){
            resources[`schema/${walk.name}`] = readYaml(walk.path);
        }
        resources[`pandoc/formats.yml`] = await pandocListFormats();
        setYamlIntelligenceResources(resources);
        await loadDefaultSchemaDefinitions();
    }
}
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");
async function generateTypesFromSchemas(resourcePath) {
    const definitionsSchema = parse1(Deno.readTextFileSync(join2(resourcePath, "/schema/definitions.yml")));
    const projectSchema = parse1(Deno.readTextFileSync(join2(resourcePath, "/schema/project.yml")));
    const schemas = [];
    for (const definition of definitionsSchema){
        schemas.push({
            name: capitalizeWord(toCapitalizationCase(definition.id)),
            schema: definition
        });
    }
    schemas.push({
        name: "ProjectConfig",
        schema: projectSchema[0]
    }, {
        name: "BookProject",
        schema: projectSchema[2]
    });
    const autoGeneratedTypes = [
        `// This file is automatically generated by \`quarto build-js\`! Do not edit.",
//
// If you find yourself trying to rebuild types and \`quarto build-js\` won't run because
// of bad type definitions, run the following:
// $ cd $QUARTO_ROOT
// $ ./package/dist/bin/tools/deno run --importmap=./src/dev_import_map.json --allow-all ./package/src/common/create-schema-types.ts ./src/resources

export type MaybeArrayOf<T> = (T | T[]);
export type SchemaObject = { [key: string]: string };`
    ];
    for (const { name, schema } of schemas){
        try {
            autoGeneratedTypes.push(`export type ${name} = ${schemaToType(schema)}`);
        } catch (e) {
            console.error(JSON.stringify(schema, null, 2));
            throw e;
        }
    }
    Deno.mkdirSync(join2(resourcePath, "/types"), {
        recursive: true
    });
    Deno.writeTextFileSync(join2(resourcePath, "/types/schema-types.ts"), autoGeneratedTypes.join("\n\n"));
    await Deno.run({
        cmd: [
            Deno.execPath(),
            "fmt",
            join2(resourcePath, "/types/schema-types.ts")
        ]
    }).status();
}
function yamlToTypeScriptKey(key) {
    if (!/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(key)) {
        return JSON.stringify(key);
    }
    return key;
}
function schemaToType(schema) {
    if ([
        true,
        false,
        null
    ].indexOf(schema) !== -1) {
        return String(schema);
    }
    if (typeof schema === "string") {
        switch(schema){
            case "number":
            case "boolean":
            case "string":
            case "null":
                return schema;
            case "path":
                return "string";
            case "object":
                return "SchemaObject";
        }
        throw new Error(`Unimplemented: ${schema}`);
    }
    const document1 = (schemaStr, entry)=>{
        if (typeof entry.description === "string") {
            return `${schemaStr} /* ${entry.description.trim()} */`;
        } else if (typeof schema.description === "string") {
            return `${schemaStr} /* ${schema.description.trim()} */`;
        } else if (typeof entry.description === "object") {
            return `${schemaStr} /* ${entry.description.long.trim()} */`;
        } else if (typeof schema.description === "object") {
            return `${schemaStr} /* ${schema.description.long.trim()} */`;
        } else {
            return schemaStr;
        }
    };
    if (typeof schema === "object") {
        if (schema.schema) return schemaToType(schema.schema);
        if (schema.string) {
            return document1("string", schema.string);
        }
        if (schema.number) {
            return document1("number", schema.number);
        }
        if (schema.boolean) {
            return document1("boolean", schema.boolean);
        }
        if (schema.path) {
            return document1("string", schema.path);
        }
        if (schema.arrayOf) {
            return document1(`(${schemaToType(schema.arrayOf)})[]`, schema.arrayOf);
        }
        if (schema.maybeArrayOf) {
            const t = schemaToType(schema.maybeArrayOf);
            return document1(`MaybeArrayOf<${t}>`, schema.maybeArrayOf);
        }
        if (schema.record) {
            return document1("{" + Object.entries(schema.record).map(([key, value])=>{
                return `${yamlToTypeScriptKey(key)}: ${schemaToType(value)}`;
            }).join("; ") + "}", {});
        }
        if (schema.enum) {
            const doIt = (v)=>{
                if (v.length === 1) {
                    return JSON.stringify(v[0]);
                }
                return document1("(" + v.map((x)=>JSON.stringify(x)).join(" | ") + ")", schema.enum);
            };
            if (Array.isArray(schema.enum.values)) {
                return doIt(schema.enum.values);
            }
            if (!Array.isArray(schema.enum)) {
                throw new Error(`Unimplemented: ${JSON.stringify(schema)}`);
            }
            return doIt(schema.enum);
        }
        if (schema.ref) {
            return capitalizeWord(toCapitalizationCase(schema.ref));
        }
        if (schema.allOf) {
            if (!Array.isArray(schema.allOf)) {
                throw new Error(`Unimplemented: ${JSON.stringify(schema)}`);
            }
            return document1("(" + schema.allOf.map(schemaToType).join(" & ") + ")", schema.allOf);
        }
        if (schema.anyOf) {
            if (!Array.isArray(schema.anyOf)) {
                throw new Error(`Unimplemented: ${JSON.stringify(schema)}`);
            }
            return document1("(" + schema.anyOf.map(schemaToType).join(" | ") + ")", schema.anyOf);
        }
        if (schema.object) {
            const mainType = schema.object.properties === undefined ? "SchemaObject" : "{" + Object.entries(schema.object.properties).map(([key, value])=>{
                const optionalFlag = schema.object.required === "all" ? false : schema.object.required === undefined ? true : schema.object.required.indexOf(key) === -1;
                return `${yamlToTypeScriptKey(key)}${optionalFlag ? "?" : ""}: ${schemaToType(value)}`;
            }).sort(([k1, _v1], [k2, _v2])=>k1.localeCompare(k2)).join("; ") + "}";
            if (schema.object?.super?.resolveRef) {
                return document1("(" + mainType + " & " + capitalizeWord(toCapitalizationCase(schema.object?.super?.resolveRef)) + ")", schema.object);
            } else {
                return document1(mainType, schema.object);
            }
        }
    }
    throw new Error(`Unimplemented: ${JSON.stringify(schema)}`);
}
async function buildIntelligenceResources() {
    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,
        "handlers/languages.yml": languages(),
        "handlers/lang-comment-chars.yml": kLangCommentChars
    });
    for (const language of languages()){
        let schema = await languageSchema(language);
        if (schema) {
            schema = idSchema(schema, `handlers/${language}`);
            setYamlIntelligenceResources({
                [`handlers/${language}/schema.yml`]: schema
            });
        }
    }
    const yamlResources = exportYamlIntelligenceResources(true);
    const yamlResourcesPath = resourcePath("/editor/tools/yaml/yaml-intelligence-resources.json");
    Deno.writeTextFileSync(yamlResourcesPath, yamlResources);
    await generateTypesFromSchemas(resourcePath());
}
function getMarkdownDescriptions() {
    const result1 = [];
    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;
            }
            result1.push(`## annotation\n`);
            if (typeof description === "string") {
                result1.push(`### string\n`);
                result1.push(description);
                result1.push("");
            } else {
                result1.push(`### short\n`);
                result1.push(description?.short || "");
                result1.push("");
                result1.push(`### long\n`);
                result1.push(description?.long || "");
                result1.push("");
            }
            return;
        });
    }
    return result1.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 InternalError("Couldn't run pandoc");
    }
    await initDenoDom();
    const doc = await parseHtml(pandocResult.stdout);
    for (const entryNode of doc.querySelectorAll("h2")){
        const entry = entryNode;
        const values = {};
        for (const value of filter1(stopWhen(siblings(entry), (e)=>e.tagName === "H2"), (e)=>e.tagName === "H3")){
            const name = value.textContent;
            const html = [];
            for (const p of stopWhen(siblings(value), (e)=>e.tagName !== "P")){
                html.push(p.innerHTML);
            }
            values[name] = html.join("\n");
        }
        if (values["string"]) {
            descriptionList.push(values["string"]);
        } else if (values["short"] || values["long"]) {
            descriptionList.push({
                short: values["short"],
                long: values["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 getDefaultExportFromNamespaceIfNotNamed(n) {
    return n && Object.prototype.hasOwnProperty.call(n, "default") && Object.keys(n).length === 1 ? n["default"] : n;
}
var require$$0 = getDefaultExportFromNamespaceIfNotNamed(mod2);
const getPrototype1 = Object.getPrototypeOf || ((o)=>o.__proto__);
const getAcorn = (Parser)=>{
    if (Parser.acorn) return Parser.acorn;
    const acorn2 = require$$0;
    if (acorn2.version.indexOf("6.") != 0 && acorn2.version.indexOf("6.0.") == 0 && acorn2.version.indexOf("7.") != 0) {
        throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn2.version}`);
    }
    for(let cur = Parser; cur && cur !== acorn2.Parser; cur = getPrototype1(cur)){
        if (cur !== acorn2.Parser) {
            throw new Error("acorn-private-class-elements does not support mixing different acorn copies");
        }
    }
    return acorn2;
};
var acornPrivateClassElements = function(Parser) {
    if (Parser.prototype.parsePrivateName) {
        return Parser;
    }
    const acorn2 = getAcorn(Parser);
    Parser = class extends Parser {
        _branch() {
            this.__branch = this.__branch || new Parser({
                ecmaVersion: this.options.ecmaVersion
            }, this.input);
            this.__branch.end = this.end;
            this.__branch.pos = this.pos;
            this.__branch.type = this.type;
            this.__branch.value = this.value;
            this.__branch.containsEsc = this.containsEsc;
            return this.__branch;
        }
        parsePrivateClassElementName(element) {
            element.computed = false;
            element.key = this.parsePrivateName();
            if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
            const accept = {
                get: "set",
                set: "get"
            }[element.kind];
            const privateBoundNames = this._privateBoundNames;
            if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
                this.raise(element.start, "Duplicate private element");
            }
            privateBoundNames[element.key.name] = element.kind || true;
            delete this._unresolvedPrivateNames[element.key.name];
            return element.key;
        }
        parsePrivateName() {
            const node = this.startNode();
            node.name = this.value;
            this.next();
            this.finishNode(node, "PrivateIdentifier");
            if (this.options.allowReserved == "never") this.checkUnreserved(node);
            return node;
        }
        getTokenFromCode(code) {
            if (code === 35) {
                ++this.pos;
                const word = this.readWord1();
                return this.finishToken(this.privateIdentifierToken, word);
            }
            return super.getTokenFromCode(code);
        }
        parseClass(node, isStatement) {
            const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
            this._outerPrivateBoundNames = this._privateBoundNames;
            this._privateBoundNames = Object.create(this._privateBoundNames || null);
            const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
            this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
            this._unresolvedPrivateNames = Object.create(null);
            const _return = super.parseClass(node, isStatement);
            const unresolvedPrivateNames = this._unresolvedPrivateNames;
            this._privateBoundNames = this._outerPrivateBoundNames;
            this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
            this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
            this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
            if (!this._unresolvedPrivateNames) {
                const names = Object.keys(unresolvedPrivateNames);
                if (names.length) {
                    names.sort((n1, n2)=>unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
                    this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
                }
            } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
            return _return;
        }
        parseClassSuper(node) {
            const privateBoundNames = this._privateBoundNames;
            this._privateBoundNames = this._outerPrivateBoundNames;
            const unresolvedPrivateNames = this._unresolvedPrivateNames;
            this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
            const _return = super.parseClassSuper(node);
            this._privateBoundNames = privateBoundNames;
            this._unresolvedPrivateNames = unresolvedPrivateNames;
            return _return;
        }
        parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
            const optionalSupported = this.options.ecmaVersion >= 11 && acorn2.tokTypes.questionDot;
            const branch = this._branch();
            if (!((branch.eat(acorn2.tokTypes.dot) || optionalSupported && branch.eat(acorn2.tokTypes.questionDot)) && branch.type == this.privateIdentifierToken)) {
                return super.parseSubscript.apply(this, arguments);
            }
            let optional = false;
            if (!this.eat(acorn2.tokTypes.dot)) {
                this.expect(acorn2.tokTypes.questionDot);
                optional = true;
            }
            let node = this.startNodeAt(startPos, startLoc);
            node.object = base;
            node.computed = false;
            if (optionalSupported) {
                node.optional = optional;
            }
            if (this.type == this.privateIdentifierToken) {
                if (base.type == "Super") {
                    this.raise(this.start, "Cannot access private element on super");
                }
                node.property = this.parsePrivateName();
                if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
                    if (!this._unresolvedPrivateNames) {
                        this.raise(node.property.start, "Usage of undeclared private name");
                    }
                    this._unresolvedPrivateNames[node.property.name] = node.property.start;
                }
            } else {
                node.property = this.parseIdent(true);
            }
            return this.finishNode(node, "MemberExpression");
        }
        parseMaybeUnary(refDestructuringErrors, sawUnary) {
            const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
            if (_return.operator == "delete") {
                if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateIdentifier") {
                    this.raise(_return.start, "Private elements may not be deleted");
                }
            }
            return _return;
        }
    };
    Parser.prototype.privateIdentifierToken = new acorn2.TokenType("privateIdentifier");
    return Parser;
};
function getDefaultExportFromNamespaceIfNotNamed1(n) {
    return n && Object.prototype.hasOwnProperty.call(n, "default") && Object.keys(n).length === 1 ? n["default"] : n;
}
var require$$01 = getDefaultExportFromNamespaceIfNotNamed1(mod2);
var acornClassFields = function(Parser) {
    const acorn2 = Parser.acorn || require$$01;
    const tt = acorn2.tokTypes;
    Parser = acornPrivateClassElements(Parser);
    return class extends Parser {
        _maybeParseFieldValue(field) {
            if (this.eat(tt.eq)) {
                const oldInFieldValue = this._inFieldValue;
                this._inFieldValue = true;
                if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
                    field.value = this.parseAwait();
                } else field.value = this.parseExpression();
                this._inFieldValue = oldInFieldValue;
            } else field.value = null;
        }
        parseClassElement(_constructorAllowsSuper) {
            if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateIdentifierToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
                const branch = this._branch();
                if (branch.type == tt.bracketL) {
                    let count = 0;
                    do {
                        if (branch.eat(tt.bracketL)) ++count;
                        else if (branch.eat(tt.bracketR)) --count;
                        else branch.next();
                    }while (count > 0)
                } else branch.next(true);
                let isField = branch.type == tt.eq || branch.type == tt.semi;
                if (!isField && branch.canInsertSemicolon()) {
                    isField = branch.type != tt.parenL;
                }
                if (isField) {
                    const node = this.startNode();
                    if (this.type == this.privateIdentifierToken) {
                        this.parsePrivateClassElementName(node);
                    } else {
                        this.parsePropertyName(node);
                    }
                    if (node.key.type === "Identifier" && node.key.name === "constructor" || node.key.type === "Literal" && node.key.value === "constructor") {
                        this.raise(node.key.start, "Classes may not have a field called constructor");
                    }
                    this.enterScope(64 | 2 | 1);
                    this._maybeParseFieldValue(node);
                    this.exitScope();
                    this.finishNode(node, "PropertyDefinition");
                    this.semicolon();
                    return node;
                }
            }
            return super.parseClassElement.apply(this, arguments);
        }
        parseIdent(liberal, isBinding) {
            const ident = super.parseIdent(liberal, isBinding);
            if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
            return ident;
        }
    };
};
function ensureAllowableIDESyntax(src, filename) {
    const ast = Parser1.extend(acornClassFields).parse(src, {
        ecmaVersion: "2020",
        sourceType: "module"
    });
    let failed = false;
    simple1(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 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 result1 = await esbuildCompile("", cwd, [
            filename
        ], outputType);
        if (checkIde) {
            ensureAllowableIDESyntax(result1, filename);
        }
        return result1;
    };
    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 buildIntelligenceResources();
    await buildYAMLJS();
}
const buildJsCommand = new Command().name("build-js").hidden().description("Builds all the javascript assets necessary for IDE support.\n\n").action(async ()=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    await buildAssets();
});
async function extensionSource(target) {
    if (!target.match(/^https?:\/\/.*$/) && existsSync(target)) {
        return {
            type: "local",
            resolvedTarget: target
        };
    }
    for (const resolver of extensionHostResolvers){
        const resolved = resolver(target);
        if (!resolved) {
            continue;
        }
        try {
            const response = await resolved.response;
            if (response.status === 200) {
                return {
                    type: "remote",
                    resolvedTarget: response,
                    resolvedFile: resolved?.urlFile,
                    owner: resolved?.owner,
                    targetSubdir: resolved?.subdirectory,
                    learnMoreUrl: resolved?.learnMoreUrl
                };
            }
        } catch (err) {
            err.message = `A network error occurred when attempting to inspect the extension '${target}'. Please try again.\n\n` + err.message;
            throw err;
        }
    }
    return undefined;
}
const archiveExt = isWindows3() ? ".zip" : ".tar.gz";
const githubLatestUrlProvider = {
    extensionUrl: (host)=>{
        if (host.modifier === undefined || host.modifier === "latest") {
            return `https://github.com/${host.organization}/${host.repo}/archive/refs/heads/main${archiveExt}`;
        }
    },
    archiveSubdir: (host)=>{
        const baseDir = `${host.repo}-main`;
        if (host.subdirectory) {
            return baseDir + "/" + host.subdirectory;
        } else {
            return baseDir;
        }
    },
    learnMoreUrl: (host)=>{
        return `https://www.github.com/${host.organization}/${host.repo}#readme`;
    }
};
const githubTagUrlProvider = {
    extensionUrl: (host)=>{
        if (host.modifier) {
            return `https://github.com/${host.organization}/${host.repo}/archive/refs/tags/${host.modifier}${archiveExt}`;
        }
    },
    archiveSubdir: (host)=>{
        const baseDir = `${host.repo}-${tagSubDirectory(host.modifier)}`;
        if (host.subdirectory) {
            return baseDir + "/" + host.subdirectory;
        } else {
            return baseDir;
        }
    },
    learnMoreUrl: (host)=>{
        return `https://github.com/${host.organization}/${host.repo}/tree/${host.modifier}#readme`;
    }
};
const githubBranchUrlProvider = {
    extensionUrl: (host)=>{
        if (host.modifier) {
            return `https://github.com/${host.organization}/${host.repo}/archive/refs/heads/${host.modifier}${archiveExt}`;
        }
    },
    archiveSubdir: (host)=>{
        const baseDir = `${host.repo}-${host.modifier}`;
        if (host.subdirectory) {
            return baseDir + "/" + host.subdirectory;
        } else {
            return baseDir;
        }
    },
    learnMoreUrl: (host)=>{
        return `https://github.com/${host.organization}/${host.repo}/tree/${host.modifier}#readme`;
    }
};
const kGithubExtensionSource = {
    parse: (name)=>{
        const match = name.match(kGithubExtensionNameRegex);
        if (match) {
            return {
                name,
                organization: match[1],
                repo: match[2],
                subdirectory: match[3],
                modifier: match[4]
            };
        } else {
            return undefined;
        }
    },
    urlProviders: [
        githubLatestUrlProvider,
        githubTagUrlProvider,
        githubBranchUrlProvider
    ]
};
const kGithubExtensionNameRegex = /^([a-zA-Z0-9-_\.]*?)\/([a-zA-Z0-9-_\.]*?)(?:\/(.*?)\/?)?(?:@([a-zA-Z0-9-_\.\/]*))?$/;
const kGithubArchiveUrlSource = {
    parse: (name)=>{
        const match = name.match(kGithubArchiveUrlRegex);
        if (match) {
            return {
                name,
                organization: match[1],
                repo: match[2],
                subdirectory: undefined,
                modifier: match[3]
            };
        } else {
            return undefined;
        }
    },
    urlProviders: [
        {
            extensionUrl: (host)=>host.name,
            archiveSubdir: (host)=>{
                return `${host.repo}-${tagSubDirectory(host.modifier)}`;
            },
            learnMoreUrl: (host)=>`https://www.github.com/${host.organization}/${host.repo}`
        }
    ]
};
const kGithubArchiveUrlRegex = /https?\:\/\/github.com\/([a-zA-Z0-9-_\.]+?)\/([a-zA-Z0-9-_\.]+?)\/archive\/refs\/(?:tags|heads)\/(.+)(?:\.tar\.gz|\.zip)$/;
function tagSubDirectory(tag) {
    if (tag) {
        return tag.startsWith("v") ? tag.slice(1) : tag;
    } else {
        return tag;
    }
}
function makeResolvers(source) {
    return source.urlProviders.map((urlProvider)=>{
        return (name)=>{
            const host = source.parse(name);
            if (!host) {
                return undefined;
            }
            const url = urlProvider.extensionUrl(host);
            if (url) {
                return {
                    url,
                    urlFile: url.split("/").pop(),
                    response: fetch(url),
                    owner: host.organization,
                    subdirectory: urlProvider.archiveSubdir(host),
                    learnMoreUrl: urlProvider.learnMoreUrl(host)
                };
            } else {
                return undefined;
            }
        };
    });
}
const kGithubResolvers = [
    ...makeResolvers(kGithubExtensionSource),
    ...makeResolvers(kGithubArchiveUrlSource)
];
const unknownUrlResolver = (name)=>{
    try {
        new URL(name);
    } catch  {
        return undefined;
    }
    return {
        url: name,
        response: fetch(name)
    };
};
const extensionHostResolvers = [
    ...kGithubResolvers,
    unknownUrlResolver
];
const kUnversionedFrom = "  (?)";
const kUnversionedTo = "(?)  ";
async function installExtension(target, temp, allowPrompt, embed) {
    const source = await extensionSource(target);
    if (!source) {
        info(`Extension not found in local or remote sources`);
        return;
    }
    const trusted = await isTrusted(source, allowPrompt);
    if (!trusted) {
        cancelInstallation();
    } else {
        const currentDir = Deno.cwd();
        const installDir = await determineInstallDir(currentDir, allowPrompt, embed);
        const extensionDir = await stageExtension(source, temp.createDir());
        const stagedExtensions = await validateExtension1(extensionDir);
        const confirmed = await confirmInstallation(stagedExtensions, installDir, {
            allowPrompt
        });
        if (confirmed) {
            await completeInstallation(extensionDir, installDir);
            await withSpinner({
                message: "Extension installation complete"
            }, ()=>{
                return Promise.resolve();
            });
            if (source.learnMoreUrl) {
                info("");
                if (allowPrompt) {
                    const open = await Confirm.prompt({
                        message: "View documentation using default browser?",
                        default: true
                    });
                    if (open) {
                        await openUrl(source.learnMoreUrl);
                    }
                } else {
                    info(`\nLearn more about this extension at:\n${source.learnMoreUrl}\n`);
                }
            }
        } else {
            cancelInstallation();
        }
    }
}
function cancelInstallation() {
    info("Installation canceled\n");
}
async function isTrusted(source, allowPrompt) {
    if (allowPrompt && source.type === "remote") {
        const preamble = `\nQuarto extensions may execute code when documents are rendered. If you do not \ntrust the authors of the extension, we recommend that you do not install or \nuse the extension.`;
        info(preamble);
        const question = "Do you trust the authors of this extension";
        const confirmed = await Confirm.prompt({
            message: question,
            default: true
        });
        return confirmed;
    } else {
        return true;
    }
}
async function determineInstallDir(dir, allowPrompt, embed) {
    if (embed) {
        const extensionName = embed;
        const context = createExtensionContext();
        const extension = await context.extension(extensionName, dir);
        if (extension) {
            if (Object.keys(extension?.contributes.formats || {}).length > 0) {
                return extension?.path;
            } else {
                throw new Error(`The extension ${embed} does not contribute a format.\nYou can only embed extensions within an extension which itself contributes a format.`);
            }
        } else {
            throw new Error(`Unable to locate the extension '${embed}' that you'd like to embed this within.`);
        }
    } else {
        const nbContext = notebookContext();
        const project = await projectContext(dir, nbContext);
        if (project && project.dir !== dir) {
            const question = "Install extension into project?";
            if (allowPrompt) {
                const useProject = await Confirm.prompt(question);
                if (useProject) {
                    return project.dir;
                } else {
                    return dir;
                }
            } else {
                return dir;
            }
        } else {
            return dir;
        }
    }
}
async function stageExtension(source, workingDir) {
    if (source.type === "remote") {
        const archiveDir = join2(workingDir, "archive");
        ensureDirSync(archiveDir);
        const filename = (typeof source.resolvedTarget === "string" ? source.resolvedTarget : source.resolvedFile) || "extension.zip";
        const toFile = join2(archiveDir, filename);
        await downloadWithProgress(source.resolvedTarget, `Downloading`, toFile);
        return unzipAndStage(toFile, source);
    } else {
        if (typeof source.resolvedTarget !== "string") {
            throw new InternalError("local resolved extension should always have a string target.");
        }
        if (Deno.statSync(source.resolvedTarget).isDirectory) {
            const srcDir = extensionDir(source.resolvedTarget);
            if (srcDir) {
                const destDir = join2(workingDir, kExtensionDir);
                await readAndCopyExtensions(srcDir, destDir);
            }
            return workingDir;
        } else {
            const filename = basename2(source.resolvedTarget);
            const toFile = join2(workingDir, filename);
            copyTo(source.resolvedTarget, toFile);
            return unzipAndStage(toFile, source);
        }
    }
}
async function unzipAndStage(zipFile, source) {
    await withSpinner({
        message: "Unzipping"
    }, async ()=>{
        const result1 = await unzip(zipFile);
        if (!result1.success) {
            throw new Error("Failed to unzip extension.\n" + result1.stderr);
        }
        await Deno.remove(zipFile);
        return Promise.resolve();
    });
    const archiveDir = dirname2(zipFile);
    const findExtensionDir = ()=>{
        if (source.targetSubdir) {
            const subDirPath = join2(archiveDir, source.targetSubdir);
            if (existsSync(subDirPath)) {
                return subDirPath;
            }
        }
        if (safeExistsSync(join2(archiveDir, kExtensionDir))) {
            return archiveDir;
        } else {
            const dirEntries = Deno.readDirSync(archiveDir);
            let count = 0;
            let name;
            for (const dirEntry of dirEntries){
                if (dirEntry.isDirectory) {
                    name = dirEntry.name;
                    count++;
                }
            }
            if (count === 1 && name && name !== kExtensionDir) {
                if (safeExistsSync(join2(archiveDir, name, kExtensionDir))) {
                    return join2(archiveDir, name);
                } else {
                    return archiveDir;
                }
            } else {
                return archiveDir;
            }
        }
    };
    const extensionsDir = join2(findExtensionDir(), kExtensionDir);
    const finalDir = join2(archiveDir, "staged");
    await copyExtensions(source, extensionsDir, finalDir);
    return finalDir;
}
async function copyExtensions(source, srcDir, targetDir) {
    const finalExtensionsDir = join2(targetDir, kExtensionDir);
    const finalExtensionTargetDir = source.owner ? join2(finalExtensionsDir, source.owner) : finalExtensionsDir;
    ensureDirSync(finalExtensionTargetDir);
    await readAndCopyExtensions(srcDir, finalExtensionTargetDir);
}
async function readAndCopyExtensions(extensionsDir, targetDir) {
    const extensions = await readExtensions(extensionsDir);
    info(`    Found ${extensions.length} ${extensions.length === 1 ? "extension" : "extensions"}.`);
    for (const extension of extensions){
        copyTo(extension.path, join2(targetDir, extension.id.name));
    }
}
async function validateExtension1(path) {
    const extensionsFolder = extensionDir(path);
    if (!extensionsFolder) {
        throw new Error(`Invalid extension\nThe extension staged at ${path} is missing an '_extensions' folder.`);
    }
    const extensions = await readExtensions(extensionsFolder);
    if (extensions.length === 0) {
        throw new Error(`Invalid extension\nThe extension staged at ${path} does not provide any valid extensions.`);
    }
    return extensions;
}
async function confirmInstallation(extensions, installDir, options) {
    const readExisting = async ()=>{
        try {
            const existingExtensions = await readExtensions(join2(installDir, kExtensionDir));
            return existingExtensions;
        } catch  {
            return [];
        }
    };
    const name = (extension)=>{
        const idStr = extension.id.organization ? `${extension.id.organization}/${extension.id.name}` : extension.id.name;
        return extension.title || idStr;
    };
    const existingExtensions = await readExisting();
    const existing = (extension)=>{
        return existingExtensions.find((existing)=>{
            return existing.id.name === extension.id.name && existing.id.organization === extension.id.organization;
        });
    };
    if (existingExtensions.length > 0 && !options.allowPrompt && options.throw) {
        throw new Error(`There are extensions installed which would be overwritten. Aborting installation.\n${existingExtensions.map((ext)=>{
            return ext.title;
        }).join("\n - ")}`);
    }
    const typeStr = (to)=>{
        const contributes = to.contributes;
        const extTypes = [];
        if (contributes.formats && Object.keys(contributes.formats).length > 0) {
            Object.keys(contributes.formats).length === 1 ? extTypes.push("format") : extTypes.push("formats");
        }
        if (contributes.shortcodes && contributes.shortcodes.length > 0) {
            contributes.shortcodes.length === 1 ? extTypes.push("shortcode") : extTypes.push("shortcodes");
        }
        if (contributes.filters && contributes.filters.length > 0) {
            contributes.filters.length === 1 ? extTypes.push("filter") : extTypes.push("filters");
        }
        if (extTypes.length > 0) {
            return `(${extTypes.join(",")})`;
        } else {
            return "";
        }
    };
    const versionMessage = (to, from)=>{
        if (to && !from) {
            const versionStr = to.version?.format();
            return {
                action: "Install",
                from: "",
                to: versionStr
            };
        } else {
            if (to.version && from?.version) {
                const comparison = to.version.compare(from.version);
                if (comparison === 0) {
                    return {
                        action: "No Change",
                        from: "",
                        to: ""
                    };
                } else if (comparison > 0) {
                    return {
                        action: "Update",
                        from: from.version.format(),
                        to: to.version.format()
                    };
                } else {
                    return {
                        action: "Revert",
                        from: from.version.format(),
                        to: to.version.format()
                    };
                }
            } else if (to.version && !from?.version) {
                return {
                    action: "Update",
                    from: kUnversionedFrom,
                    to: to.version.format()
                };
            } else if (!to.version && from?.version) {
                return {
                    action: "Update",
                    from: from.version.format(),
                    to: kUnversionedTo
                };
            } else {
                return {
                    action: "Update",
                    from: kUnversionedFrom,
                    to: kUnversionedTo
                };
            }
        }
    };
    const extensionRows = [];
    for (const stagedExtension of extensions){
        const installedExtension = existing(stagedExtension);
        const message = versionMessage(stagedExtension, installedExtension);
        const types = typeStr(stagedExtension);
        if (message) {
            extensionRows.push([
                name(stagedExtension) + "  ",
                `[${message.action}]`,
                message.from || "",
                message.to && message.from ? "->" : "",
                message.to || "",
                types
            ]);
        }
    }
    if (extensionRows.length > 0) {
        const table = new Table(...extensionRows);
        info(`\n${options.message || "The following changes will be made:"}\n${table.toString()}`);
        const question = "Would you like to continue";
        return !options.allowPrompt || await Confirm.prompt({
            message: question,
            default: true
        });
    } else {
        info(`\nNo changes required - extensions already installed.`);
        return true;
    }
}
async function completeInstallation(downloadDir, installDir) {
    info("");
    await withSpinner({
        message: `Copying`
    }, async ()=>{
        const stagingDir = join2(installDir, "._extensions.staging");
        try {
            const downloadedExtDir = join2(downloadDir, kExtensionDir);
            const stagingExtDir = join2(stagingDir, kExtensionDir);
            ensureDirSync(stagingExtDir);
            const installExtDir = join2(installDir, kExtensionDir);
            ensureDirSync(installExtDir);
            const extensions = await readExtensions(downloadedExtDir);
            extensions.forEach((extension)=>{
                const extensionRelativeDir = relative2(downloadedExtDir, extension.path);
                const stagingPath = join2(stagingExtDir, extensionRelativeDir);
                copyTo(extension.path, stagingPath);
                const installPath = join2(installExtDir, extensionRelativeDir);
                if (existsSync(installPath)) {
                    Deno.removeSync(installPath, {
                        recursive: true
                    });
                }
                ensureDirSync(dirname2(installPath));
                Deno.renameSync(stagingPath, installPath);
            });
        } finally{
            Deno.removeSync(stagingDir, {
                recursive: true
            });
        }
        return Promise.resolve();
    });
}
const extensionDir = (path)=>{
    if (basename2(path) === kExtensionDir) {
        return path;
    } else {
        const extDir = join2(path, kExtensionDir);
        if (existsSync(extDir) && Deno.statSync(extDir).isDirectory) {
            return extDir;
        } else {
            return path;
        }
    }
};
async function removeExtension(extension) {
    if (extension.id.organization === kBuiltInExtOrg) {
        throw new Error(`The extension ${extension.title} can't be removed since it is a built in extension.`);
    }
    await Deno.remove(extension.path, {
        recursive: true
    });
    const extensionDir = dirname2(extension.path);
    removeIfEmptyDir(extensionDir);
    const parentDir = dirname2(extensionDir);
    if (parentDir && basename2(parentDir) === kExtensionDir) {
        removeIfEmptyDir(parentDir);
    }
}
const removeCommand = new Command().name("remove").arguments("[target...]").option("--no-prompt", "Do not prompt to confirm actions").option("--embed <extensionId>", "Remove this extension from within another extension (used when authoring extensions).").option("--update-path", "Update system path when a tool is installed", {
    hidden: true
}).description("Removes an extension.").example("Remove extension using name", "quarto remove <extension-name>").action(async (options, ...target)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    const extensionContext = createExtensionContext();
    try {
        const resolved = resolveCompatibleArgs(target || [], "extension");
        if (resolved.action === "tool") {
            if (resolved.name) {
                await removeTool(resolved.name, options.prompt, options.updatePath);
            } else {
                const allTools = await loadTools();
                if (allTools.filter((tool)=>tool.installed).length === 0) {
                    info("No tools are installed.");
                } else {
                    const toolTarget = await selectTool(allTools, "remove");
                    if (toolTarget) {
                        info("");
                        await removeTool(toolTarget);
                    }
                }
            }
        } else {
            const workingDir = Deno.cwd();
            const resolveTargetDir = async ()=>{
                if (options.embed) {
                    const context = createExtensionContext();
                    const extension = await context.extension(options.embed, workingDir);
                    if (extension) {
                        return extension?.path;
                    } else {
                        throw new Error(`Unable to find extension '${options.embed}.`);
                    }
                } else {
                    return workingDir;
                }
            };
            const targetDir = await resolveTargetDir();
            if (resolved.name) {
                const extensions = await extensionContext.find(resolved.name, targetDir, undefined, undefined, undefined, {
                    builtIn: false
                });
                if (extensions.length > 0) {
                    await removeExtensions(extensions.slice(), options.prompt);
                } else {
                    info("No matching extension found.");
                }
            } else {
                const nbContext = notebookContext();
                const project = await projectContext(targetDir, nbContext);
                const extensions = await extensionContext.extensions(targetDir, project?.config, project?.dir, {
                    builtIn: false
                });
                if (extensions.length > 0) {
                    const extensionsToRemove = await selectExtensions(extensions);
                    if (extensionsToRemove.length > 0) {
                        await removeExtensions(extensionsToRemove);
                    }
                } else {
                    info("No extensions installed.");
                }
            }
        }
    } finally{
        temp.cleanup();
    }
});
const resolveCompatibleArgs = (args, defaultAction)=>{
    if (args.length === 1) {
        const extname = args[0];
        if (extname === "tool") {
            return {
                action: "tool"
            };
        } else if (extname === "extension") {
            return {
                action: "extension"
            };
        } else if (extname === "tinytex" || extname === "chromium") {
            return {
                action: "tool",
                name: args[0]
            };
        } else {
            return {
                action: defaultAction,
                name: args[0]
            };
        }
    } else if (args.length > 1) {
        const action = args[0];
        const name = args[1];
        if (action === "tool") {
            return {
                action,
                name
            };
        } else if (action === "extension") {
            return {
                action: "extension",
                name
            };
        } else {
            return {
                action: defaultAction,
                name
            };
        }
    } else {
        return {
            action: defaultAction
        };
    }
};
function removeExtensions(extensions, prompt) {
    const removeOneExtension = async (extension)=>{
        return await afterConfirm(`Are you sure you'd like to remove ${extension.title}?`, async ()=>{
            await removeExtension(extension);
            info("Extension removed.");
        }, prompt);
    };
    const removeMultipleExtensions = async (extensions)=>{
        return await afterConfirm(`Are you sure you'd like to remove ${extensions.length} ${extensions.length === 1 ? "extension" : "extensions"}?`, async ()=>{
            for (const extensionToRemove of extensions){
                await removeExtension(extensionToRemove);
            }
            info(`${extensions.length} ${extensions.length === 1 ? "extension" : "extensions"} removed.`);
        }, prompt);
    };
    info("");
    if (extensions.length === 1) {
        return removeOneExtension(extensions[0]);
    } else {
        return removeMultipleExtensions(extensions);
    }
}
async function selectExtensions(extensions) {
    const sorted = extensions.sort((ext1, ext2)=>{
        const orgSort = (ext1.id.organization || "").localeCompare(ext2.id.organization || "");
        if (orgSort !== 0) {
            return orgSort;
        } else {
            return ext1.title.localeCompare(ext2.title);
        }
    });
    const extsToKeep = (await Checkbox.prompt({
        message: "Select extension(s) to keep",
        options: sorted.map((ext)=>{
            return {
                name: `${ext.title}${ext.id.organization ? " (" + ext.id.organization + ")" : ""}`,
                value: extensionIdString(ext.id),
                checked: true
            };
        }),
        hint: `Use the arrow keys and spacebar to specify extensions you'd like to remove.\n` + "   Press Enter to confirm the list of accounts you wish to remain available."
    })).map((x)=>x.value);
    return extensions.filter((extension)=>{
        return !extsToKeep.includes(extensionIdString(extension.id));
    });
}
const installCommand = new Command().name("install").arguments("[target...]").option("--no-prompt", "Do not prompt to confirm actions").option("--embed <extensionId>", "Embed this extension within another extension (used when authoring extensions).", {
    hidden: true
}).option("--update-path", "Update system path when a tool is installed").description("Installs a global dependency (TinyTex or Chromium).").example("Install TinyTeX", "quarto install tinytex").example("Install Chromium", "quarto install chromium").example("Choose tool to install", "quarto install").action(async (options, ...target)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    const resolved = resolveCompatibleArgs(target || [], "tool");
    try {
        if (resolved.action === "extension") {
            if (resolved.name) {
                await installExtension(resolved.name, temp, options.prompt !== false, options.embed);
            } else {
                info("Please provide an extension name, url, or path.");
            }
        } else if (resolved.action === "tool") {
            if (resolved.name) {
                await updateOrInstallTool(resolved.name, "install", options.prompt, options.updatePath);
            } else {
                const allTools = await loadTools();
                if (allTools.filter((tool)=>!tool.installed).length === 0) {
                    info("All tools are already installed.");
                } else {
                    const toolTarget = await selectTool(allTools, "install");
                    if (toolTarget) {
                        info("");
                        await installTool(toolTarget, options.updatePath);
                    }
                }
            }
        } else {
            info(`Unrecognized option '${resolved.action}' - please choose 'tool' or 'extension'.`);
        }
    } finally{
        temp.cleanup();
    }
});
const updateCommand = new Command().name("update").arguments("[target...]").option("--no-prompt", "Do not prompt to confirm actions").option("--embed <extensionId>", "Embed this extension within another extension (used when authoring extensions).").description("Updates an extension or global dependency.").example("Update extension (Github)", "quarto update extension <gh-org>/<gh-repo>").example("Update extension (file)", "quarto update extension <path-to-zip>").example("Update extension (url)", "quarto update extension <url>").example("Update TinyTeX", "quarto update tool tinytex").example("Update Chromium", "quarto update tool chromium").example("Choose tool to update", "quarto update tool").action(async (options, ...target)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
        const resolved = resolveCompatibleArgs(target, "extension");
        if (resolved.action === "extension") {
            if (resolved.name) {
                await installExtension(resolved.name, temp, options.prompt !== false, options.embed);
            } else {
                info("Please provide an extension name, url, or path.");
            }
        } else if (resolved.action === "tool") {
            if (resolved.name) {
                await updateOrInstallTool(resolved.name, "update", options.prompt);
            } else {
                const allTools = await loadTools();
                if (allTools.filter((tool)=>!tool.installed).length === 0) {
                    info("All tools are already installed.");
                } else {
                    const toolTarget = await selectTool(allTools, "update");
                    if (toolTarget) {
                        info("");
                        await updateOrInstallTool(toolTarget, "update");
                    }
                }
            }
        } else {
            info(`Unrecognized option '${resolved.action}' - please choose 'tool' or 'extension'.`);
        }
    } finally{
        temp.cleanup();
    }
});
class BaseHttpRequest {
    config;
    constructor(config){
        this.config = config;
    }
}
class ApiError extends Error {
    url;
    status;
    statusText;
    body;
    constructor(response, message){
        super(message);
        this.name = "ApiError";
        this.url = response.url;
        this.status = response.status;
        this.statusText = response.statusText;
        this.body = response.body;
    }
}
class CancelError extends Error {
    constructor(message){
        super(message);
        this.name = "CancelError";
    }
    get isCancelled() {
        return true;
    }
}
class CancelablePromise {
    [Symbol.toStringTag] = "";
    _isResolved;
    _isRejected;
    _isCancelled;
    _cancelHandlers;
    _promise;
    _resolve;
    _reject;
    constructor(executor){
        this._isResolved = false;
        this._isRejected = false;
        this._isCancelled = false;
        this._cancelHandlers = [];
        this._promise = new Promise((resolve, reject)=>{
            this._resolve = resolve;
            this._reject = reject;
            const onResolve = (value)=>{
                if (this._isResolved || this._isRejected || this._isCancelled) {
                    return;
                }
                this._isResolved = true;
                this._resolve?.(value);
            };
            const onReject = (reason)=>{
                if (this._isResolved || this._isRejected || this._isCancelled) {
                    return;
                }
                this._isRejected = true;
                this._reject?.(reason);
            };
            const onCancel = (cancelHandler)=>{
                if (this._isResolved || this._isRejected || this._isCancelled) {
                    return;
                }
                this._cancelHandlers.push(cancelHandler);
            };
            Object.defineProperty(onCancel, "isResolved", {
                get: ()=>this._isResolved
            });
            Object.defineProperty(onCancel, "isRejected", {
                get: ()=>this._isRejected
            });
            Object.defineProperty(onCancel, "isCancelled", {
                get: ()=>this._isCancelled
            });
            return executor(onResolve, onReject, onCancel);
        });
    }
    then(onFulfilled, onRejected) {
        return this._promise.then(onFulfilled, onRejected);
    }
    catch(onRejected) {
        return this._promise.catch(onRejected);
    }
    finally(onFinally) {
        return this._promise.finally(onFinally);
    }
    cancel() {
        if (this._isResolved || this._isRejected || this._isCancelled) {
            return;
        }
        this._isCancelled = true;
        if (this._cancelHandlers.length) {
            try {
                for (const cancelHandler of this._cancelHandlers){
                    cancelHandler();
                }
            } catch (error) {
                console.warn("Cancellation threw an error", error);
                return;
            }
        }
        this._cancelHandlers.length = 0;
        this._reject?.(new CancelError("Request aborted"));
    }
    get isCancelled() {
        return this._isCancelled;
    }
}
const isDefined = (value)=>{
    return value !== undefined && value !== null;
};
const isString = (value)=>{
    return typeof value === "string";
};
const isStringWithValue = (value)=>{
    return isString(value) && value !== "";
};
const isBlob = (value)=>{
    return typeof value === "object" && typeof value.type === "string" && typeof value.stream === "function" && typeof value.arrayBuffer === "function" && typeof value.constructor === "function" && typeof value.constructor.name === "string" && /^(Blob|File)$/.test(value.constructor.name) && /^(Blob|File)$/.test(value[Symbol.toStringTag]);
};
const isFormData = (value)=>{
    return value instanceof FormData;
};
const base64 = (str)=>{
    try {
        return btoa(str);
    } catch (err) {
        return Buffer.from(str).toString("base64");
    }
};
const getQueryString = (params)=>{
    const qs = [];
    const append = (key, value)=>{
        qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
    };
    const process = (key, value)=>{
        if (isDefined(value)) {
            if (Array.isArray(value)) {
                value.forEach((v)=>{
                    process(key, v);
                });
            } else if (typeof value === "object") {
                Object.entries(value).forEach(([k, v])=>{
                    process(`${key}[${k}]`, v);
                });
            } else {
                append(key, value);
            }
        }
    };
    Object.entries(params).forEach(([key, value])=>{
        process(key, value);
    });
    if (qs.length > 0) {
        return `?${qs.join("&")}`;
    }
    return "";
};
const getUrl = (config, options)=>{
    const encoder = config.ENCODE_PATH || encodeURI;
    const path = options.url.replace("{api-version}", config.VERSION).replace(/{(.*?)}/g, (substring, group)=>{
        if (options.path?.hasOwnProperty(group)) {
            return encoder(String(options.path[group]));
        }
        return substring;
    });
    const url = `${config.BASE}${path}`;
    if (options.query) {
        return `${url}${getQueryString(options.query)}`;
    }
    return url;
};
const getFormData = (options)=>{
    if (options.formData) {
        const formData = new FormData();
        const process = (key, value)=>{
            if (isString(value) || isBlob(value)) {
                formData.append(key, value);
            } else {
                formData.append(key, JSON.stringify(value));
            }
        };
        Object.entries(options.formData).filter(([_, value])=>isDefined(value)).forEach(([key, value])=>{
            if (Array.isArray(value)) {
                value.forEach((v)=>process(key, v));
            } else {
                process(key, value);
            }
        });
        return formData;
    }
    return undefined;
};
const resolve6 = async (options, resolver)=>{
    if (typeof resolver === "function") {
        return resolver(options);
    }
    return resolver;
};
const getHeaders = async (config, options)=>{
    const token = await resolve6(options, config.TOKEN);
    const username = await resolve6(options, config.USERNAME);
    const password = await resolve6(options, config.PASSWORD);
    const additionalHeaders = await resolve6(options, config.HEADERS);
    const headers = Object.entries({
        Accept: "application/json",
        ...additionalHeaders,
        ...options.headers
    }).filter(([_, value])=>isDefined(value)).reduce((headers, [key, value])=>({
            ...headers,
            [key]: String(value)
        }), {});
    if (isStringWithValue(token)) {
        headers["Authorization"] = `Bearer ${token}`;
    }
    if (isStringWithValue(username) && isStringWithValue(password)) {
        const credentials = base64(`${username}:${password}`);
        headers["Authorization"] = `Basic ${credentials}`;
    }
    if (options.body) {
        if (options.mediaType) {
            headers["Content-Type"] = options.mediaType;
        } else if (isBlob(options.body)) {
            headers["Content-Type"] = options.body.type || "application/octet-stream";
        } else if (isString(options.body)) {
            headers["Content-Type"] = "text/plain";
        } else if (!isFormData(options.body)) {
            headers["Content-Type"] = "application/json";
        }
    }
    return new Headers(headers);
};
const getRequestBody = (options)=>{
    if (options.body) {
        if (options.mediaType?.includes("/json")) {
            return JSON.stringify(options.body);
        } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) {
            return options.body;
        } else {
            return JSON.stringify(options.body);
        }
    }
    return undefined;
};
const sendRequest = async (config, options, url, body, formData, headers, onCancel)=>{
    const controller = new AbortController();
    const request = {
        headers,
        body: body ?? formData,
        method: options.method,
        signal: controller.signal
    };
    if (config.WITH_CREDENTIALS) {
        request.credentials = config.CREDENTIALS;
    }
    onCancel(()=>controller.abort());
    return await fetch(url, request);
};
const getResponseHeader = (response, responseHeader)=>{
    if (responseHeader) {
        const content = response.headers.get(responseHeader);
        if (isString(content)) {
            return content;
        }
    }
    return undefined;
};
const getResponseBody = async (response)=>{
    if (response.status !== 204) {
        try {
            const contentType = response.headers.get("Content-Type");
            if (contentType) {
                const isJSON = contentType.toLowerCase().startsWith("application/json");
                if (isJSON) {
                    return await response.json();
                } else {
                    return await response.text();
                }
            }
        } catch (error) {
            console.error(error);
        }
    }
    return undefined;
};
const catchErrorCodes = (options, result1)=>{
    const errors = {
        400: "Bad Request",
        401: "Unauthorized",
        403: "Forbidden",
        404: "Not Found",
        500: "Internal Server Error",
        502: "Bad Gateway",
        503: "Service Unavailable",
        ...options.errors
    };
    const error = errors[result1.status];
    if (error) {
        throw new ApiError(result1, error);
    }
    if (!result1.ok) {
        throw new ApiError(result1, "Generic Error");
    }
};
const request = (config, options)=>{
    return new CancelablePromise(async (resolve, reject, onCancel)=>{
        try {
            const url = getUrl(config, options);
            const formData = getFormData(options);
            const body = getRequestBody(options);
            const headers = await getHeaders(config, options);
            if (!onCancel.isCancelled) {
                const response = await sendRequest(config, options, url, body, formData, headers, onCancel);
                const responseBody = await getResponseBody(response);
                const responseHeader = getResponseHeader(response, options.responseHeader);
                const result1 = {
                    url,
                    ok: response.ok,
                    status: response.status,
                    statusText: response.statusText,
                    body: responseHeader ?? responseBody
                };
                catchErrorCodes(options, result1);
                resolve(result1.body);
            }
        } catch (error) {
            reject(error);
        }
    });
};
class FetchHttpRequest extends BaseHttpRequest {
    constructor(config){
        super(config);
    }
    request(options) {
        return request(this.config, options);
    }
}
class AccessTokenService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    exchangeTicket({ ticketId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/oauth/tickets/{ticket_id}/exchange",
            path: {
                "ticket_id": ticketId
            }
        });
    }
}
class AccountMembershipService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listAccountsForUser() {
        return this.httpRequest.request({
            method: "GET",
            url: "/accounts"
        });
    }
    createAccount({ accountSetup }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/accounts",
            body: accountSetup
        });
    }
    getAccount({ accountId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/accounts/{account_id}",
            path: {
                "account_id": accountId
            }
        });
    }
    updateAccount({ accountId, accountUpdateSetup }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/accounts/{account_id}",
            path: {
                "account_id": accountId
            },
            body: accountUpdateSetup
        });
    }
    cancelAccount({ accountId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/accounts/{account_id}",
            path: {
                "account_id": accountId
            }
        });
    }
}
class AccountTypeService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listAccountTypesForUser() {
        return this.httpRequest.request({
            method: "GET",
            url: "/accounts/types"
        });
    }
}
class AssetService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteAssets({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/assets",
            path: {
                "site_id": siteId
            }
        });
    }
    createSiteAsset({ siteId, name, size, contentType, visibility }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/assets",
            path: {
                "site_id": siteId
            },
            query: {
                "name": name,
                "size": size,
                "content_type": contentType,
                "visibility": visibility
            }
        });
    }
    getSiteAssetInfo({ siteId, assetId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/assets/{asset_id}",
            path: {
                "site_id": siteId,
                "asset_id": assetId
            }
        });
    }
    updateSiteAsset({ siteId, assetId, state }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/assets/{asset_id}",
            path: {
                "site_id": siteId,
                "asset_id": assetId
            },
            query: {
                "state": state
            }
        });
    }
    deleteSiteAsset({ siteId, assetId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/sites/{site_id}/assets/{asset_id}",
            path: {
                "site_id": siteId,
                "asset_id": assetId
            }
        });
    }
}
class AssetPublicSignatureService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    getSiteAssetPublicSignature({ siteId, assetId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/assets/{asset_id}/public_signature",
            path: {
                "site_id": siteId,
                "asset_id": assetId
            }
        });
    }
}
class AuditLogService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listAccountAuditEvents({ accountId, query, logType, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/accounts/{account_id}/audit",
            path: {
                "account_id": accountId
            },
            query: {
                "query": query,
                "log_type": logType,
                "page": page,
                "per_page": perPage
            }
        });
    }
}
class BuildService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteBuilds({ siteId, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/builds",
            path: {
                "site_id": siteId
            },
            query: {
                "page": page,
                "per_page": perPage
            }
        });
    }
    createSiteBuild({ siteId, build }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/builds",
            path: {
                "site_id": siteId
            },
            body: build
        });
    }
    getSiteBuild({ buildId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/builds/{build_id}",
            path: {
                "build_id": buildId
            }
        });
    }
    notifyBuildStart({ buildId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/builds/{build_id}/start",
            path: {
                "build_id": buildId
            }
        });
    }
    getAccountBuildStatus({ accountId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/{account_id}/builds/status",
            path: {
                "account_id": accountId
            }
        });
    }
}
class BuildHookService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteBuildHooks({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/build_hooks",
            path: {
                "site_id": siteId
            }
        });
    }
    createSiteBuildHook({ siteId, buildHook }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/build_hooks",
            path: {
                "site_id": siteId
            },
            body: buildHook
        });
    }
    getSiteBuildHook({ siteId, id }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/build_hooks/{id}",
            path: {
                "site_id": siteId,
                "id": id
            }
        });
    }
    updateSiteBuildHook({ siteId, id, buildHook }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/build_hooks/{id}",
            path: {
                "site_id": siteId,
                "id": id
            },
            body: buildHook
        });
    }
    deleteSiteBuildHook({ siteId, id }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/sites/{site_id}/build_hooks/{id}",
            path: {
                "site_id": siteId,
                "id": id
            }
        });
    }
}
class BuildLogMsgService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    updateSiteBuildLog({ buildId, msg }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/builds/{build_id}/log",
            path: {
                "build_id": buildId
            },
            body: msg
        });
    }
}
class DeployService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteDeploys({ siteId, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/deploys",
            path: {
                "site_id": siteId
            },
            query: {
                "page": page,
                "per_page": perPage
            }
        });
    }
    createSiteDeploy({ siteId, deploy, title }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/deploys",
            path: {
                "site_id": siteId
            },
            query: {
                "title": title
            },
            body: deploy
        });
    }
    getSiteDeploy({ siteId, deployId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/deploys/{deploy_id}",
            path: {
                "site_id": siteId,
                "deploy_id": deployId
            }
        });
    }
    updateSiteDeploy({ siteId, deployId, deploy }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/deploys/{deploy_id}",
            path: {
                "site_id": siteId,
                "deploy_id": deployId
            },
            body: deploy
        });
    }
    cancelSiteDeploy({ deployId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/deploys/{deploy_id}/cancel",
            path: {
                "deploy_id": deployId
            }
        });
    }
    restoreSiteDeploy({ siteId, deployId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/deploys/{deploy_id}/restore",
            path: {
                "site_id": siteId,
                "deploy_id": deployId
            }
        });
    }
    rollbackSiteDeploy({ siteId }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/rollback",
            path: {
                "site_id": siteId
            }
        });
    }
    getDeploy({ deployId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/deploys/{deploy_id}",
            path: {
                "deploy_id": deployId
            }
        });
    }
    lockDeploy({ deployId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/deploys/{deploy_id}/lock",
            path: {
                "deploy_id": deployId
            }
        });
    }
    unlockDeploy({ deployId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/deploys/{deploy_id}/unlock",
            path: {
                "deploy_id": deployId
            }
        });
    }
}
class DeployedBranchService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteDeployedBranches({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/deployed-branches",
            path: {
                "site_id": siteId
            }
        });
    }
}
class DeployKeyService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listDeployKeys() {
        return this.httpRequest.request({
            method: "GET",
            url: "/deploy_keys"
        });
    }
    createDeployKey() {
        return this.httpRequest.request({
            method: "POST",
            url: "/deploy_keys"
        });
    }
    getDeployKey({ keyId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/deploy_keys/{key_id}",
            path: {
                "key_id": keyId
            }
        });
    }
    deleteDeployKey({ keyId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/deploy_keys/{key_id}",
            path: {
                "key_id": keyId
            }
        });
    }
}
class DnsZoneService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    getDnsForSite({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/dns",
            path: {
                "site_id": siteId
            }
        });
    }
    configureDnsForSite({ siteId }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/dns",
            path: {
                "site_id": siteId
            }
        });
    }
    createDnsZone({ dnsZoneParams }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/dns_zones",
            body: dnsZoneParams
        });
    }
    getDnsZones({ accountSlug }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/dns_zones",
            query: {
                "account_slug": accountSlug
            }
        });
    }
    getDnsZone({ zoneId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/dns_zones/{zone_id}",
            path: {
                "zone_id": zoneId
            }
        });
    }
    deleteDnsZone({ zoneId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/dns_zones/{zone_id}",
            path: {
                "zone_id": zoneId
            }
        });
    }
    transferDnsZone({ zoneId, accountId, transferAccountId, transferUserId }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/dns_zones/{zone_id}/transfer",
            path: {
                "zone_id": zoneId
            },
            query: {
                "account_id": accountId,
                "transfer_account_id": transferAccountId,
                "transfer_user_id": transferUserId
            }
        });
    }
    getDnsRecords({ zoneId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/dns_zones/{zone_id}/dns_records",
            path: {
                "zone_id": zoneId
            }
        });
    }
    createDnsRecord({ zoneId, dnsRecord }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/dns_zones/{zone_id}/dns_records",
            path: {
                "zone_id": zoneId
            },
            body: dnsRecord
        });
    }
    getIndividualDnsRecord({ zoneId, dnsRecordId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/dns_zones/{zone_id}/dns_records/{dns_record_id}",
            path: {
                "zone_id": zoneId,
                "dns_record_id": dnsRecordId
            }
        });
    }
    deleteDnsRecord({ zoneId, dnsRecordId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/dns_zones/{zone_id}/dns_records/{dns_record_id}",
            path: {
                "zone_id": zoneId,
                "dns_record_id": dnsRecordId
            }
        });
    }
}
class FileService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteFiles({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/files",
            path: {
                "site_id": siteId
            }
        });
    }
    getSiteFileByPathName({ siteId, filePath }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/files/{file_path}",
            path: {
                "site_id": siteId,
                "file_path": filePath
            }
        });
    }
    uploadDeployFile({ deployId, path, fileBody, size }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/deploys/{deploy_id}/files/{path}",
            path: {
                "deploy_id": deployId,
                "path": path
            },
            query: {
                "size": size
            },
            body: fileBody
        });
    }
}
class FormService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteForms({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/forms",
            path: {
                "site_id": siteId
            }
        });
    }
    deleteSiteForm({ siteId, formId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/sites/{site_id}/forms/{form_id}",
            path: {
                "site_id": siteId,
                "form_id": formId
            }
        });
    }
}
class FunctionService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    uploadDeployFunction({ deployId, name, fileBody, runtime, size }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/deploys/{deploy_id}/functions/{name}",
            path: {
                "deploy_id": deployId,
                "name": name
            },
            query: {
                "runtime": runtime,
                "size": size
            },
            body: fileBody
        });
    }
}
class HookService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listHooksBySiteId({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/hooks",
            query: {
                "site_id": siteId
            }
        });
    }
    createHookBySiteId({ siteId, hook }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/hooks",
            query: {
                "site_id": siteId
            },
            body: hook
        });
    }
    getHook({ hookId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/hooks/{hook_id}",
            path: {
                "hook_id": hookId
            }
        });
    }
    updateHook({ hookId, hook }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/hooks/{hook_id}",
            path: {
                "hook_id": hookId
            },
            body: hook
        });
    }
    deleteHook({ hookId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/hooks/{hook_id}",
            path: {
                "hook_id": hookId
            }
        });
    }
    enableHook({ hookId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/hooks/{hook_id}/enable",
            path: {
                "hook_id": hookId
            }
        });
    }
}
class HookTypeService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listHookTypes() {
        return this.httpRequest.request({
            method: "GET",
            url: "/hooks/types"
        });
    }
}
class MemberService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listMembersForAccount({ accountSlug }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/{account_slug}/members",
            path: {
                "account_slug": accountSlug
            }
        });
    }
    addMemberToAccount({ accountSlug, email, role }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/{account_slug}/members",
            path: {
                "account_slug": accountSlug
            },
            query: {
                "role": role,
                "email": email
            }
        });
    }
}
class MetadataService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    getSiteMetadata({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/metadata",
            path: {
                "site_id": siteId
            }
        });
    }
    updateSiteMetadata({ siteId, metadata }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/metadata",
            path: {
                "site_id": siteId
            },
            body: metadata
        });
    }
}
class PaymentMethodService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listPaymentMethodsForUser() {
        return this.httpRequest.request({
            method: "GET",
            url: "/billing/payment_methods"
        });
    }
}
class ServiceService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    getServices({ search }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/services/",
            query: {
                "search": search
            }
        });
    }
    showService({ addonName }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/services/{addonName}",
            path: {
                "addonName": addonName
            }
        });
    }
    showServiceManifest({ addonName }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/services/{addonName}/manifest",
            path: {
                "addonName": addonName
            }
        });
    }
}
class ServiceInstanceService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listServiceInstancesForSite({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/service-instances",
            path: {
                "site_id": siteId
            }
        });
    }
    createServiceInstance({ siteId, addon, config }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/services/{addon}/instances",
            path: {
                "site_id": siteId,
                "addon": addon
            },
            body: config
        });
    }
    showServiceInstance({ siteId, addon, instanceId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/services/{addon}/instances/{instance_id}",
            path: {
                "site_id": siteId,
                "addon": addon,
                "instance_id": instanceId
            }
        });
    }
    updateServiceInstance({ siteId, addon, instanceId, config }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/services/{addon}/instances/{instance_id}",
            path: {
                "site_id": siteId,
                "addon": addon,
                "instance_id": instanceId
            },
            body: config
        });
    }
    deleteServiceInstance({ siteId, addon, instanceId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/sites/{site_id}/services/{addon}/instances/{instance_id}",
            path: {
                "site_id": siteId,
                "addon": addon,
                "instance_id": instanceId
            }
        });
    }
}
class SiteService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSites({ name, filter, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites",
            query: {
                "name": name,
                "filter": filter,
                "page": page,
                "per_page": perPage
            }
        });
    }
    createSite({ site, configureDns }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites",
            query: {
                "configure_dns": configureDns
            },
            body: site
        });
    }
    getSite({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}",
            path: {
                "site_id": siteId
            }
        });
    }
    updateSite({ siteId, site }) {
        return this.httpRequest.request({
            method: "PATCH",
            url: "/sites/{site_id}",
            path: {
                "site_id": siteId
            },
            body: site
        });
    }
    deleteSite({ siteId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/sites/{site_id}",
            path: {
                "site_id": siteId
            }
        });
    }
    unlinkSiteRepo({ siteId }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/unlink_repo",
            path: {
                "site_id": siteId
            },
            errors: {
                404: `Site not found`
            }
        });
    }
    createSiteInTeam({ accountSlug, site, configureDns }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/{account_slug}/sites",
            path: {
                "account_slug": accountSlug
            },
            query: {
                "configure_dns": configureDns
            },
            body: site
        });
    }
    listSitesForAccount({ accountSlug, name, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/{account_slug}/sites",
            path: {
                "account_slug": accountSlug
            },
            query: {
                "name": name,
                "page": page,
                "per_page": perPage
            }
        });
    }
}
class SniCertificateService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    provisionSiteTlsCertificate({ siteId, certificate, key, caCertificates }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/ssl",
            path: {
                "site_id": siteId
            },
            query: {
                "certificate": certificate,
                "key": key,
                "ca_certificates": caCertificates
            }
        });
    }
    showSiteTlsCertificate({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/ssl",
            path: {
                "site_id": siteId
            }
        });
    }
}
class SnippetService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteSnippets({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/snippets",
            path: {
                "site_id": siteId
            }
        });
    }
    createSiteSnippet({ siteId, snippet }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/snippets",
            path: {
                "site_id": siteId
            },
            body: snippet
        });
    }
    getSiteSnippet({ siteId, snippetId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/snippets/{snippet_id}",
            path: {
                "site_id": siteId,
                "snippet_id": snippetId
            }
        });
    }
    updateSiteSnippet({ siteId, snippetId, snippet }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/snippets/{snippet_id}",
            path: {
                "site_id": siteId,
                "snippet_id": snippetId
            },
            body: snippet
        });
    }
    deleteSiteSnippet({ siteId, snippetId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/sites/{site_id}/snippets/{snippet_id}",
            path: {
                "site_id": siteId,
                "snippet_id": snippetId
            }
        });
    }
}
class SplitTestService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    createSplitTest({ siteId, branchTests }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/traffic_splits",
            path: {
                "site_id": siteId
            },
            body: branchTests
        });
    }
    getSplitTests({ siteId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/traffic_splits",
            path: {
                "site_id": siteId
            }
        });
    }
    updateSplitTest({ siteId, splitTestId, branchTests }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/traffic_splits/{split_test_id}",
            path: {
                "site_id": siteId,
                "split_test_id": splitTestId
            },
            body: branchTests
        });
    }
    getSplitTest({ siteId, splitTestId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/traffic_splits/{split_test_id}",
            path: {
                "site_id": siteId,
                "split_test_id": splitTestId
            }
        });
    }
    enableSplitTest({ siteId, splitTestId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/traffic_splits/{split_test_id}/publish",
            path: {
                "site_id": siteId,
                "split_test_id": splitTestId
            }
        });
    }
    disableSplitTest({ siteId, splitTestId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/sites/{site_id}/traffic_splits/{split_test_id}/unpublish",
            path: {
                "site_id": siteId,
                "split_test_id": splitTestId
            }
        });
    }
}
class SubmissionService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    listSiteSubmissions({ siteId, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/submissions",
            path: {
                "site_id": siteId
            },
            query: {
                "page": page,
                "per_page": perPage
            }
        });
    }
    listFormSubmissions({ formId, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/forms/{form_id}/submissions",
            path: {
                "form_id": formId
            },
            query: {
                "page": page,
                "per_page": perPage
            }
        });
    }
    listFormSubmission({ submissionId, query, page, perPage }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/submissions/{submission_id}",
            path: {
                "submission_id": submissionId
            },
            query: {
                "query": query,
                "page": page,
                "per_page": perPage
            }
        });
    }
    deleteSubmission({ submissionId }) {
        return this.httpRequest.request({
            method: "DELETE",
            url: "/submissions/{submission_id}",
            path: {
                "submission_id": submissionId
            }
        });
    }
}
class TicketService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    createTicket({ clientId }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/oauth/tickets",
            query: {
                "client_id": clientId
            }
        });
    }
    showTicket({ ticketId }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/oauth/tickets/{ticket_id}",
            path: {
                "ticket_id": ticketId
            }
        });
    }
}
class UserService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    getCurrentUser() {
        return this.httpRequest.request({
            method: "GET",
            url: "/user"
        });
    }
}
class XInternalService {
    httpRequest;
    constructor(httpRequest){
        this.httpRequest = httpRequest;
    }
    updatePlugin({ siteId, _package, pluginParams }) {
        return this.httpRequest.request({
            method: "PUT",
            url: "/sites/{site_id}/plugins/{package}",
            path: {
                "site_id": siteId,
                "package": _package
            },
            body: pluginParams
        });
    }
    getLatestPluginRuns({ siteId, packages, state }) {
        return this.httpRequest.request({
            method: "GET",
            url: "/sites/{site_id}/plugin_runs/latest",
            path: {
                "site_id": siteId
            },
            query: {
                "packages": packages,
                "state": state
            }
        });
    }
    createPluginRun({ deployId, pluginRun }) {
        return this.httpRequest.request({
            method: "POST",
            url: "/deploys/{deploy_id}/plugin_runs",
            path: {
                "deploy_id": deployId
            },
            body: pluginRun
        });
    }
}
class NetlifyClient {
    accessToken;
    accountMembership;
    accountType;
    asset;
    assetPublicSignature;
    auditLog;
    build;
    buildHook;
    buildLogMsg;
    deploy;
    deployedBranch;
    deployKey;
    dnsZone;
    file;
    form;
    function;
    hook;
    hookType;
    member;
    metadata;
    paymentMethod;
    service;
    serviceInstance;
    site;
    sniCertificate;
    snippet;
    splitTest;
    submission;
    ticket;
    user;
    xInternal;
    request;
    constructor(config, HttpRequest = FetchHttpRequest){
        this.request = new HttpRequest({
            BASE: config?.BASE ?? "https://api.netlify.com/api/v1",
            VERSION: config?.VERSION ?? "2.9.0",
            WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false,
            CREDENTIALS: config?.CREDENTIALS ?? "include",
            TOKEN: config?.TOKEN,
            USERNAME: config?.USERNAME,
            PASSWORD: config?.PASSWORD,
            HEADERS: config?.HEADERS,
            ENCODE_PATH: config?.ENCODE_PATH
        });
        this.accessToken = new AccessTokenService(this.request);
        this.accountMembership = new AccountMembershipService(this.request);
        this.accountType = new AccountTypeService(this.request);
        this.asset = new AssetService(this.request);
        this.assetPublicSignature = new AssetPublicSignatureService(this.request);
        this.auditLog = new AuditLogService(this.request);
        this.build = new BuildService(this.request);
        this.buildHook = new BuildHookService(this.request);
        this.buildLogMsg = new BuildLogMsgService(this.request);
        this.deploy = new DeployService(this.request);
        this.deployedBranch = new DeployedBranchService(this.request);
        this.deployKey = new DeployKeyService(this.request);
        this.dnsZone = new DnsZoneService(this.request);
        this.file = new FileService(this.request);
        this.form = new FormService(this.request);
        this.function = new FunctionService(this.request);
        this.hook = new HookService(this.request);
        this.hookType = new HookTypeService(this.request);
        this.member = new MemberService(this.request);
        this.metadata = new MetadataService(this.request);
        this.paymentMethod = new PaymentMethodService(this.request);
        this.service = new ServiceService(this.request);
        this.serviceInstance = new ServiceInstanceService(this.request);
        this.site = new SiteService(this.request);
        this.sniCertificate = new SniCertificateService(this.request);
        this.snippet = new SnippetService(this.request);
        this.splitTest = new SplitTestService(this.request);
        this.submission = new SubmissionService(this.request);
        this.ticket = new TicketService(this.request);
        this.user = new UserService(this.request);
        this.xInternal = new XInternalService(this.request);
    }
}
var accountSetup;
(function(accountSetup) {
    let period;
    (function(period) {
        period["MONTHLY"] = "monthly";
        period["YEARLY"] = "yearly";
    })(period = accountSetup.period || (accountSetup.period = {}));
})(accountSetup || (accountSetup = {}));
var AccountTokenType;
(function(AccountTokenType) {
    AccountTokenType[AccountTokenType["Environment"] = 0] = "Environment";
    AccountTokenType[AccountTokenType["Authorized"] = 1] = "Authorized";
    AccountTokenType[AccountTokenType["Anonymous"] = 2] = "Anonymous";
})(AccountTokenType || (AccountTokenType = {}));
function publishDataDir() {
    return quartoDataDir("publish");
}
function publishRecordsPath() {
    return join2(publishDataDir(), "records.json");
}
function accountsDataDir() {
    const accountsDir = join2(publishDataDir(), "accounts");
    ensureDirSync(accountsDir);
    return accountsDir;
}
async function readAccountsPublishedTo(input, provider, record) {
    const source = normalizePath(typeof input === "string" ? input : input.dir);
    const tokens = [];
    const publishRecordsFile = publishRecordsPath();
    if (existsSync(publishRecordsFile)) {
        const records = JSON.parse(Deno.readTextFileSync(publishRecordsFile));
        if (records[source] && records[source][provider.name]) {
            const publishIdentifiers = records[source][provider.name];
            const accounts = await provider.accountTokens();
            for (const publishIdentifier of publishIdentifiers){
                const account = accounts.find((account)=>publishIdentifier === publishRecordIdentifier(record, account));
                if (account) {
                    tokens.push(account);
                }
            }
        }
    }
    return tokens;
}
function writePublishRecord(source, provider, account, record) {
    source = normalizePath(source);
    const publishRecordsFile = publishRecordsPath();
    const publishRecords = existsSync(publishRecordsFile) ? JSON.parse(Deno.readTextFileSync(publishRecordsFile)) : {};
    if (!publishRecords[source]) {
        publishRecords[source] = {
            [provider]: []
        };
    }
    if (!publishRecords[source][provider]) {
        publishRecords[source][provider] = [];
    }
    const publishedTo = publishRecordIdentifier(record, account);
    if (!publishRecords[source][provider].includes(publishedTo)) {
        publishRecords[source][provider].push(publishedTo);
    }
    Deno.writeTextFileSync(publishRecordsFile, JSON.stringify(publishRecords, undefined, 2));
}
function publishRecordIdentifier(record, account) {
    return `${record.id}/${account?.server ? account.server + "/" : ""}${account?.name || ""}`;
}
async function authorizeAccessToken(handler) {
    const ticket = await handler.createTicket();
    const ticketUrl = handler.authorizationUrl(ticket);
    if (isServerSession()) {
        info("Please authorize by opening this url: " + underline(ticketUrl));
    } else {
        await openUrl(handler.authorizationUrl(ticket));
    }
    let authorizedTicket;
    const checkTicket = async ()=>{
        const t = await handler.checkTicket(ticket);
        if (t.authorized) {
            authorizedTicket = t;
        }
        return Boolean(t.authorized);
    };
    const pollingStart = Date.now();
    const kPollingTimeout = 60 * 1000;
    while(Date.now() - pollingStart < kPollingTimeout){
        if (await checkTicket()) {
            break;
        }
        await sleep1(500);
    }
    if (authorizedTicket) {
        const accessToken = await handler.exchangeTicket(authorizedTicket);
        writeAccessToken(handler.name, accessToken, handler.compareTokens);
        return accessToken;
    } else {
        return undefined;
    }
}
function readAccessTokens(provider) {
    const tokenPath = accessTokensPath(provider);
    if (existsSync(tokenPath)) {
        const tokens = JSON.parse(Deno.readTextFileSync(tokenPath));
        return tokens;
    } else {
        return undefined;
    }
}
function writeAccessTokens(provider, tokens) {
    const tokensPath = accessTokensPath(provider);
    Deno.writeTextFileSync(tokensPath, JSON.stringify(tokens, undefined, 2));
    if (!isWindows3()) {
        Deno.chmod(tokensPath, 0o600);
    }
}
function writeAccessToken(provider, token, compareTokens) {
    let writeTokens;
    writeTokens = readAccessTokens(provider) || [];
    if (compareTokens) {
        const updateIdx = writeTokens.findIndex((t)=>compareTokens(t, token));
        if (updateIdx !== -1) {
            writeTokens[updateIdx] = token;
        } else {
            writeTokens.push(token);
        }
    } else {
        writeTokens = [
            token
        ];
    }
    writeAccessTokens(provider, writeTokens);
}
function accessTokensPath(provider) {
    const dir = join2(accountsDataDir(), provider);
    ensureDirSync(dir);
    return join2(dir, "accounts.json");
}
async function withRetry(fn, options) {
    const { attempts = 10, minWait = 1000, maxWait = 4000, retry = ()=>true } = options || {};
    let attempt = 0;
    while(true){
        try {
            return fn();
        } catch (err) {
            if (attempt++ >= attempts || retry && !retry(err)) {
                throw err;
            }
            const delay = minWait + Math.floor(Math.random() * (maxWait - minWait));
            await sleep1(delay);
        }
    }
}
const hexTable = new TextEncoder().encode("0123456789abcdef");
new TextEncoder();
const textDecoder = new TextDecoder();
function encodeHex2(src) {
    const u8 = validateBinaryLike(src);
    const dst = new Uint8Array(u8.length * 2);
    for(let i1 = 0; i1 < dst.length; i1++){
        const v = u8[i1];
        dst[i1 * 2] = hexTable[v >> 4];
        dst[i1 * 2 + 1] = hexTable[v & 0x0f];
    }
    return textDecoder.decode(dst);
}
function fileProgress(files) {
    const numWidth = String(files.length).length;
    let i1 = 0;
    return {
        status: ()=>{
            return `[${String(i1 + 1).padStart(numWidth)}/${files.length}] ${files[i1]}`;
        },
        next: ()=>{
            i1++;
        }
    };
}
async function handlePublish(handler, type, title, slug, render, target) {
    if (!target?.id) {
        if (handler.slugAvailable) {
            slug = await promptForSlug(type, handler.slugAvailable, slug);
        }
        info("");
        await withSpinner({
            message: `Creating ${handler.name} ${type}`
        }, async ()=>{
            const site = await handler.createSite(type, title, slug);
            target = {
                id: site.id,
                url: site.url,
                code: !!site.code
            };
        });
        info("");
    }
    target = target;
    const publishFiles = await renderForPublish(render, handler.name, type, title, type === "site" ? target.url : undefined);
    const publishFilePath = (file)=>{
        return join2(publishFiles.baseDir, file);
    };
    let siteDeploy;
    const files = [];
    await withSpinner({
        message: `Preparing to publish ${type}`
    }, async ()=>{
        let size = 0;
        for (const file of publishFiles.files){
            const filePath = publishFilePath(file);
            const fileBuffer = Deno.readFileSync(filePath);
            size = size + fileBuffer.byteLength;
            const sha1 = await stdCrypto.subtle.digest("SHA-1", fileBuffer);
            const encodedSha1 = encodeHex2(new Uint8Array(sha1));
            files.push([
                file,
                encodedSha1
            ]);
        }
        const deploy = {
            files: {}
        };
        for (const file of files){
            deploy.files[`/${pathWithForwardSlashes(file[0])}`] = file[1];
        }
        siteDeploy = await handler.createDeploy(target.id, deploy.files, size);
        while(true){
            siteDeploy = await handler.getDeploy(siteDeploy.id);
            if (siteDeploy.state === "prepared" || siteDeploy.state === "ready") {
                break;
            }
            await sleep1(250);
        }
    });
    const required = siteDeploy?.required.map((sha1)=>{
        const file = files.find((file)=>file[1] === sha1);
        return file ? file[0] : null;
    }).filter((file)=>file);
    const progress = fileProgress(required);
    await withSpinner({
        message: ()=>`Uploading files ${progress.status()}`,
        doneMessage: false
    }, async ()=>{
        for (const requiredFile of required){
            const filePath = publishFilePath(requiredFile);
            const fileArray = Deno.readFileSync(filePath);
            await handler.uploadDeployFile(siteDeploy?.id, requiredFile, new Blob([
                fileArray.buffer
            ]));
            progress.next();
        }
    });
    completeMessage(`Uploading files (complete)`);
    let targetUrl = target.url;
    let adminUrl = target.url;
    let launchUrl = target.url;
    await withSpinner({
        message: `Deploying published ${type}`
    }, async ()=>{
        while(true){
            const deployReady = await handler.getDeploy(siteDeploy?.id);
            if (deployReady.state === "ready") {
                targetUrl = deployReady.url || targetUrl;
                adminUrl = deployReady.admin_url || targetUrl;
                launchUrl = deployReady.launch_url || adminUrl;
                break;
            }
            await sleep1(500);
        }
    });
    completeMessage(`Published ${type}: ${targetUrl}`);
    if (handler.updateAccountSite) {
        let accountSite;
        await withSpinner({
            message: `Updating account site`,
            doneMessage: false
        }, async ()=>{
            accountSite = await handler.updateAccountSite();
        });
        completeMessage(`Account site updated: ${accountSite.url}`);
    }
    info("");
    return [
        {
            ...target,
            url: targetUrl
        },
        launchUrl ? new URL(launchUrl) : undefined
    ];
}
async function renderForPublish(render, providerName, type, title, siteUrl) {
    let publishFiles = await render({
        siteUrl
    });
    if (type === "document" && !isHtmlContent(publishFiles.rootFile) && !isPdfContent(publishFiles.rootFile)) {
        throw new Error(`Documents published to ${providerName} must be either HTML or PDF.`);
    }
    if (type === "document") {
        publishFiles = stageDocumentPublish(title, publishFiles);
    }
    return publishFiles;
}
function stageDocumentPublish(title, publishFiles) {
    const publishDir = globalTempContext().createDir();
    const stagedFiles = window.structuredClone(publishFiles);
    stagedFiles.baseDir = publishDir;
    for (const file of publishFiles.files){
        const src = join2(publishFiles.baseDir, file);
        const target = join2(stagedFiles.baseDir, file);
        ensureDirSync(dirname2(target));
        copyTo(src, target);
    }
    const kIndex = "index.html";
    if (isHtmlContent(publishFiles.rootFile)) {
        if (stagedFiles.rootFile !== "index.html") {
            copyTo(join2(stagedFiles.baseDir, stagedFiles.rootFile), join2(stagedFiles.baseDir, kIndex));
        }
    } else if (isPdfContent(publishFiles.rootFile)) {
        const src = formatResourcePath("pdf", "pdfjs");
        const dest = join2(stagedFiles.baseDir, "pdfjs");
        for (const walk of walkSync(src)){
            if (walk.isFile) {
                const destFile = join2(dest, relative2(src, walk.path));
                ensureDirSync(dirname2(destFile));
                copyTo(walk.path, destFile);
                stagedFiles.files.push(relative2(stagedFiles.baseDir, destFile));
            }
        }
        const indexHtml = `<!DOCTYPE html>
<html>
<head>
<title>${encodeAttributeValue(title)}</title>
<style type="text/css">
  body, html {
    margin: 0; padding: 0; height: 100%; overflow: hidden;
  }
</style>
</head>
<body>
<iframe id="pdf-js-viewer" src="pdfjs/web/viewer.html?file=../../${encodeAttributeValue(stagedFiles.rootFile)}" title="${encodeAttributeValue(title)}" frameborder="0" width="100%" height="100%"></iframe>

</body>
</html>
`;
        Deno.writeTextFileSync(join2(stagedFiles.baseDir, kIndex), indexHtml);
    }
    if (!stagedFiles.files.includes(kIndex)) {
        stagedFiles.files.push(kIndex);
    }
    stagedFiles.rootFile = kIndex;
    return stagedFiles;
}
async function promptForSlug(type, slugAvailable, slug) {
    const available = await slugAvailable(slug);
    if (!available && type === "document") {
        slug = slug + "-" + randomHex(4);
    }
    if (await slugAvailable(slug)) {
        const kConfirmed = "confirmed";
        const input = await Select.prompt({
            indent: "",
            message: `${typeName(type)} name:`,
            options: [
                {
                    name: slug,
                    value: kConfirmed
                },
                {
                    name: "Use another name...",
                    value: "another"
                }
            ]
        });
        if (input === kConfirmed) {
            return slug;
        }
    }
    let hint = `The ${typeName(type).toLowerCase()} name is included within your published URL\n` + `  (e.g. https://username.quarto.pub/${slug}/)`;
    while(true){
        const input = await Input.prompt({
            indent: "",
            message: `Publish with name:`,
            hint,
            transform: (slug)=>gfmAutoIdentifier(slug, false),
            validate: (slug)=>{
                if (slug.length === 0) {
                    return true;
                } else if (slug.length < 2) {
                    return `${typeName(type)} name must be at least 2 characters.`;
                } else {
                    return true;
                }
            }
        });
        hint = undefined;
        if (input.length === 0) {
            throw new Error();
        }
        if (await slugAvailable(input)) {
            return input;
        } else {
            info(red(`  The specified name is already in use within your account.`));
        }
    }
}
function typeName(type) {
    return capitalizeWord(type);
}
async function authorizePrompt(provider) {
    const result1 = await prompt([
        {
            indent: "",
            name: "confirmed",
            message: "Authorize",
            default: true,
            hint: `In order to publish to ${provider.description} you need to authorize your account.\n` + `  Please be sure you are logged into the correct ${provider.description} account in your\n` + "  default web browser, then press Enter or 'Y' to authorize.",
            type: Confirm
        }
    ]);
    return !!result1.confirmed;
}
async function reauthorizePrompt(provider) {
    const result1 = await prompt([
        {
            indent: "",
            name: "confirmed",
            message: "Re-authorize account",
            default: true,
            hint: `The authorization saved for ${provider.description} is no longer valid.\n` + `  Please be sure you are logged into the correct ${provider.description} account in your\n` + "  default web browser, then press Enter to re-authorize.",
            type: Confirm
        }
    ]);
    return !!result1.confirmed;
}
async function handleUnauthorized(provider, account) {
    if (account.type === AccountTokenType.Environment) {
        error(`Unable to authenticate with the provided ${account.name}. Please be sure this token is valid.`);
        return false;
    } else if (account.type === AccountTokenType.Authorized) {
        return await reauthorizePrompt(provider);
    }
}
const kNetlify = "netlify";
const kNetlifyDescription = "Netlify";
const kNetlifyAuthTokenVar = "NETLIFY_AUTH_TOKEN";
const netlifyProvider = {
    name: kNetlify,
    description: kNetlifyDescription,
    requiresServer: false,
    listOriginOnly: false,
    accountTokens,
    authorizeToken,
    removeToken,
    resolveTarget,
    publish,
    isUnauthorized,
    isNotFound
};
function accountTokens() {
    const envTk = environmentAuthToken();
    const accessTkns = accessTokens();
    const accounts = [];
    if (envTk) {
        accounts.push({
            type: AccountTokenType.Environment,
            name: kNetlifyAuthTokenVar,
            server: null,
            token: envTk
        });
    }
    if (accessTkns) {
        for (const accessTk of accessTkns){
            if (accessTk?.access_token) {
                accounts.push({
                    type: AccountTokenType.Authorized,
                    name: accessTk.email,
                    server: null,
                    token: accessTk?.access_token
                });
            }
        }
    }
    return Promise.resolve(accounts);
}
async function authorizeToken(_options) {
    if (await authorizePrompt(netlifyProvider)) {
        const token = await authorizeNetlifyAccessToken();
        if (token) {
            return {
                type: AccountTokenType.Authorized,
                name: token.email,
                server: null,
                token: token.access_token
            };
        }
    } else {
        return undefined;
    }
}
function removeToken(token) {
    writeAccessTokens(netlifyProvider.name, readAccessTokens(netlifyProvider.name)?.filter((accessToken)=>{
        return accessToken.email !== token.name;
    }) || []);
}
function environmentAuthToken() {
    return Deno.env.get(kNetlifyAuthTokenVar);
}
function accessTokens() {
    return readAccessTokens(kNetlify);
}
async function authorizeNetlifyAccessToken() {
    const client = new NetlifyClient({});
    const clientId = (await quartoConfig.dotenv())["NETLIFY_APP_CLIENT_ID"];
    const handler = {
        name: kNetlifyDescription,
        createTicket: function() {
            return client.ticket.createTicket({
                clientId
            });
        },
        authorizationUrl: function(ticket) {
            return `https://app.netlify.com/authorize?response_type=ticket&ticket=${ticket.id}`;
        },
        checkTicket: function(ticket) {
            return client.ticket.showTicket({
                ticketId: ticket.id
            });
        },
        exchangeTicket: function(ticket) {
            return client.accessToken.exchangeTicket({
                ticketId: ticket.id
            });
        },
        compareTokens: (a, b)=>a.email === b.email
    };
    return authorizeAccessToken(handler);
}
async function resolveTarget(account, target) {
    const client = new NetlifyClient({
        TOKEN: account.token
    });
    const site = await client.site.getSite({
        siteId: target.id
    });
    if (updateProcessingSettings(site)) {
        await client.site.updateSite({
            siteId: target.id,
            site: {
                processing_settings: {
                    css: {
                        bundle: false,
                        minify: false
                    },
                    html: {
                        pretty_urls: false
                    },
                    js: {
                        bundle: false,
                        minify: false
                    }
                }
            }
        });
    }
    target.url = site?.ssl_url || site?.url || target.url;
    return target;
}
function updateProcessingSettings(site) {
    return site.processing_settings?.skip !== true && (site.processing_settings?.css?.bundle || site.processing_settings?.css?.minify || site.processing_settings?.html?.pretty_urls || site.processing_settings?.js?.bundle || site.processing_settings?.js?.minify);
}
function publish(account, type, _input, title, slug, render, _options, target) {
    const client = new NetlifyClient({
        TOKEN: account.token
    });
    const handler = {
        name: kNetlify,
        createSite: async (_type, _title, _slug)=>{
            return withSslUrl(await client.site.createSite({
                site: {
                    force_ssl: true,
                    processing_settings: {
                        skip: true
                    }
                }
            }));
        },
        createDeploy: async (siteId, files)=>{
            return withSslUrl(await client.deploy.createSiteDeploy({
                siteId,
                deploy: {
                    files,
                    async: true
                }
            }));
        },
        getDeploy: async (deployId)=>{
            return withSslUrl(await client.deploy.getDeploy({
                deployId
            }));
        },
        uploadDeployFile: async (deployId, path, fileBody)=>{
            await withRetry(async ()=>{
                await client.file.uploadDeployFile({
                    deployId,
                    path,
                    fileBody
                });
            });
        }
    };
    return handlePublish(handler, type, title, slug, render, target);
}
function withSslUrl(obj) {
    return {
        ...obj,
        url: obj.ssl_url || obj.url
    };
}
function isUnauthorized(err) {
    return err instanceof ApiError && err.status === 401;
}
function isNotFound(err) {
    return err instanceof ApiError && err.status === 404;
}
const throwUnableToPublish = (reason, provider)=>{
    throw new Error(`Unable to publish to ${provider} (${reason})`);
};
async function gitHubContextForPublish(input) {
    const dir = typeof input === "string" ? dirname2(input) : input.dir;
    const context = await gitHubContext(dir);
    if (typeof input !== "string") {
        const configSiteUrl = websiteBaseurl(input?.config);
        if (configSiteUrl) {
            context.siteUrl = configSiteUrl;
        }
    }
    return context;
}
function anonymousAccount() {
    return {
        type: AccountTokenType.Anonymous,
        name: "anonymous",
        server: null,
        token: "anonymous"
    };
}
function verifyContext(ghContext, provider) {
    if (!ghContext.git) {
        throwUnableToPublish("git does not appear to be installed on this system", provider);
    }
    if (!ghContext.repo) {
        throwUnableToPublish("the target directory is not a git repository", provider);
    }
    if (!ghContext.originUrl) {
        throwUnableToPublish("the git repository does not have a remote origin", provider);
    }
}
const kGhpages = "gh-pages";
const kGhpagesDescription = "GitHub Pages";
const ghpagesProvider = {
    name: kGhpages,
    description: kGhpagesDescription,
    requiresServer: false,
    listOriginOnly: false,
    accountTokens: accountTokens1,
    authorizeToken: authorizeToken1,
    removeToken: removeToken1,
    publishRecord,
    resolveTarget: resolveTarget1,
    publish: publish1,
    isUnauthorized: isUnauthorized1,
    isNotFound: isNotFound1
};
function accountTokens1() {
    return Promise.resolve([
        anonymousAccount()
    ]);
}
async function authorizeToken1(options) {
    const ghContext = await gitHubContextForPublish(options.input);
    verifyContext(ghContext, "GitHub Pages");
    return Promise.resolve(anonymousAccount());
}
function removeToken1(_token) {}
async function publishRecord(input) {
    const ghContext = await gitHubContextForPublish(input);
    if (ghContext.ghPagesRemote) {
        return {
            id: "gh-pages",
            url: ghContext.siteUrl || ghContext.originUrl
        };
    }
}
function resolveTarget1(_account, target) {
    return Promise.resolve(target);
}
async function publish1(_account, type, input, title, _slug, render, options, target) {
    input = Deno.statSync(input).isDirectory ? input : dirname2(input);
    const version = await gitVersion();
    if (version.compare("2.17.0") < 0) {
        throw new Error("git version 2.17.0 or higher is required to publish to GitHub Pages");
    }
    const ghContext = await gitHubContextForPublish(options.input);
    verifyContext(ghContext, "GitHub Pages");
    const createGhPagesBranchRemote = !ghContext.ghPagesRemote;
    const createGhPagesBranchLocal = !ghContext.ghPagesLocal;
    if (createGhPagesBranchRemote) {
        let confirmed = await Confirm.prompt({
            indent: "",
            message: `Publish site to ${ghContext.siteUrl || ghContext.originUrl} using gh-pages?`,
            default: true
        });
        if (confirmed && !createGhPagesBranchLocal) {
            confirmed = await Confirm.prompt({
                indent: "",
                message: `A local gh-pages branch already exists. Should it be pushed to remote 'origin'?`,
                default: true
            });
        }
        if (!confirmed) {
            throw new Error();
        }
        const stash = !await gitDirIsClean(input);
        if (stash) {
            await gitStash(input);
        }
        const oldBranch = await gitCurrentBranch(input);
        try {
            if (createGhPagesBranchLocal) {
                await gitCreateGhPages(input);
            } else {
                await gitPushGhPages(input);
            }
        } catch  {
            if (createGhPagesBranchLocal && await gitBranchExists("gh-pages")) {
                await gitCmds(input, [
                    [
                        "checkout",
                        oldBranch
                    ],
                    [
                        "branch",
                        "-D",
                        "gh-pages"
                    ]
                ]);
            }
            throw new Error("Publishing to gh-pages with `quarto publish gh-pages` failed.");
        } finally{
            if (await gitCurrentBranch(input) !== oldBranch) {
                await gitCmds(input, [
                    [
                        "checkout",
                        oldBranch
                    ]
                ]);
            }
            if (stash) {
                await gitStashApply(input);
            }
        }
    }
    await gitCmds(input, [
        [
            "remote",
            "set-branches",
            "--add",
            "origin",
            "gh-pages"
        ],
        [
            "fetch",
            "origin",
            "gh-pages"
        ]
    ]);
    const renderResult = await renderForPublish(render, "gh-pages", type, title, type === "site" ? target?.url : undefined);
    const tempDir = Deno.makeTempDirSync({
        dir: input
    });
    removeIfExists(tempDir);
    const deployId = shortUuid();
    await withWorktree(input, relative2(input, tempDir), async ()=>{
        await copy1(renderResult.baseDir, tempDir, {
            overwrite: true
        });
        Deno.writeTextFileSync(join2(tempDir, ".nojekyll"), deployId);
        await gitCmds(tempDir, [
            [
                "add",
                "-Af",
                "."
            ],
            [
                "commit",
                "--allow-empty",
                "-m",
                "Built site for gh-pages"
            ],
            [
                "remote",
                "-v"
            ],
            [
                "push",
                "--force",
                "origin",
                "HEAD:gh-pages"
            ]
        ]);
    });
    info("");
    let notifyGhPagesBranch = false;
    let defaultSiteMatch;
    if (ghContext.siteUrl) {
        defaultSiteMatch = ghContext.siteUrl.match(/^https:\/\/(.+?)\.github\.io\/$/);
        if (defaultSiteMatch) {
            if (createGhPagesBranchRemote) {
                notifyGhPagesBranch = true;
            } else {
                try {
                    const response = await fetch(ghContext.siteUrl);
                    if (response.status === 404) {
                        notifyGhPagesBranch = true;
                    }
                } catch  {}
            }
        }
    }
    if (!createGhPagesBranchRemote && !notifyGhPagesBranch) {
        info(yellow("NOTE: GitHub Pages sites use caching so you might need to click the refresh\n" + "button within your web browser to see changes after deployment.\n"));
    }
    let verified = false;
    if (options.browser && ghContext.siteUrl && !notifyGhPagesBranch) {
        await withSpinner({
            message: "Deploying gh-pages branch to website (this may take a few minutes)"
        }, async ()=>{
            const noJekyllUrl = joinUrl(ghContext.siteUrl, ".nojekyll");
            while(true){
                await sleep1(2000);
                const response = await fetch(noJekyllUrl);
                if (response.status === 200) {
                    if ((await response.text()).trim() === deployId) {
                        verified = true;
                        await sleep1(2000);
                        break;
                    }
                } else if (response.status !== 404) {
                    break;
                }
            }
        });
    }
    completeMessage(`Published to ${ghContext.siteUrl || ghContext.originUrl}`);
    info("");
    if (notifyGhPagesBranch) {
        info(yellow("To complete publishing, change the source branch for this site to " + bold("gh-pages") + ".\n\n" + `Set the source branch at: ` + underline(`https://github.com/${defaultSiteMatch[1]}/${defaultSiteMatch[1]}.github.io/settings/pages`) + "\n"));
    } else if (!verified) {
        info(yellow("NOTE: GitHub Pages deployments normally take a few minutes (your site updates\n" + "will be visible once the deploy completes)\n"));
    }
    return Promise.resolve([
        undefined,
        verified ? new URL(ghContext.siteUrl) : undefined
    ]);
}
function isUnauthorized1(_err) {
    return false;
}
function isNotFound1(_err) {
    return false;
}
async function gitStash(dir) {
    const result1 = await execProcess({
        cmd: [
            "git",
            "stash"
        ],
        cwd: dir
    });
    if (!result1.success) {
        throw new Error();
    }
}
async function gitStashApply(dir) {
    const result1 = await execProcess({
        cmd: [
            "git",
            "stash",
            "apply"
        ],
        cwd: dir
    });
    if (!result1.success) {
        throw new Error();
    }
}
async function gitDirIsClean(dir) {
    const result1 = await execProcess({
        cmd: [
            "git",
            "diff",
            "HEAD"
        ],
        cwd: dir,
        stdout: "piped"
    });
    if (result1.success) {
        return result1.stdout.trim().length === 0;
    } else {
        throw new Error();
    }
}
async function gitCurrentBranch(dir) {
    const result1 = await execProcess({
        cmd: [
            "git",
            "rev-parse",
            "--abbrev-ref",
            "HEAD"
        ],
        cwd: dir,
        stdout: "piped"
    });
    if (result1.success) {
        return result1.stdout.trim();
    } else {
        throw new Error();
    }
}
async function withWorktree(dir, siteDir, f) {
    await execProcess({
        cmd: [
            "git",
            "worktree",
            "add",
            "--track",
            "-B",
            "gh-pages",
            siteDir,
            "origin/gh-pages"
        ],
        cwd: dir
    });
    await execProcess({
        cmd: [
            "git",
            "rm",
            "-r",
            "--quiet",
            "."
        ],
        cwd: join2(dir, siteDir)
    });
    try {
        await f();
    } finally{
        await execProcess({
            cmd: [
                "git",
                "worktree",
                "remove",
                siteDir
            ],
            cwd: dir
        });
    }
}
async function gitCreateGhPages(dir) {
    await gitCmds(dir, [
        [
            "checkout",
            "--orphan",
            "gh-pages"
        ],
        [
            "rm",
            "-rf",
            "--quiet",
            "."
        ],
        [
            "commit",
            "--allow-empty",
            "-m",
            "Initializing gh-pages branch"
        ]
    ]);
    await gitPushGhPages(dir);
}
async function gitPushGhPages(dir) {
    if (await gitCurrentBranch(dir) !== "gh-pages") {
        await gitCmds(dir, [
            [
                "checkout",
                "gh-pages"
            ]
        ]);
    }
    await gitCmds(dir, [
        [
            "push",
            "origin",
            "HEAD:gh-pages"
        ]
    ]);
}
class ApiError1 extends Error {
    status;
    statusText;
    description;
    constructor(status, statusText, description = undefined){
        let message = `API Error: ${status} - ${statusText}`;
        if (description) {
            message = `${message} (${description})`;
        }
        super(message);
        this.status = status;
        this.statusText = statusText;
        this.description = description;
    }
}
const acceptApplicationJsonHeader = {
    Accept: "application/json"
};
const contentTypeApplicationJsonHeader = {
    "Content-Type": "application/json"
};
const kUrlResolveRegex = /https:\/\/quartopub\.com\/sites\/([^\/]+)\/(.*)/;
const authorizationHeader = (token)=>!token ? {} : {
        Authorization: `Bearer ${token}`
    };
class QuartoPubClient {
    token_;
    baseURL_;
    constructor(environment, token_){
        this.token_ = token_;
        this.createTicket = async (client_id)=>{
            const response = await fetch(this.createURL(`tickets?${new URLSearchParams({
                application_id: client_id
            })}`), {
                method: "POST",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader
                }
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
            return await response.json();
        };
        this.showTicket = async (id)=>{
            const response = await fetch(this.createURL(`tickets/${id}`), {
                method: "GET",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader
                }
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
            return await response.json();
        };
        this.exchangeTicket = async (id)=>{
            const response = await fetch(this.createURL(`tickets/${id}/exchange`), {
                method: "POST",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader
                }
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
            return await response.json();
        };
        this.slugAvailable = async (slug)=>{
            const response = await fetch(this.createURL(`slugs/${slug}`), {
                method: "HEAD",
                headers: {
                    ...authorizationHeader(this.token_)
                }
            });
            if (response.ok) {
                return false;
            }
            if (response.status == 404) {
                return true;
            }
            throw new ApiError1(response.status, response.statusText);
        };
        this.createSite = async (type, title, slug)=>{
            const response = await fetch(this.createURL("sites"), {
                method: "POST",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader
                },
                body: new URLSearchParams({
                    type,
                    title,
                    slug
                })
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
            const site = await response.json();
            site.url = this.resolveUrl(site.url);
            return site;
        };
        this.createDeploy = async (siteId, files, size)=>{
            const response = await fetch(this.createURL(`sites/${siteId}/deploys`), {
                method: "POST",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader,
                    ...contentTypeApplicationJsonHeader
                },
                body: JSON.stringify({
                    size,
                    files
                })
            });
            if (!response.ok) {
                const description = await descriptionFromErrorResponse(response);
                throw new ApiError1(response.status, description || response.statusText);
            }
            const deploy = await response.json();
            deploy.url = this.resolveUrl(deploy.url);
            return deploy;
        };
        this.getDeploy = async (deployId)=>{
            const response = await fetch(this.createURL(`deploys/${deployId}`), {
                method: "GET",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader
                }
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
            const deploy = await response.json();
            deploy.url = this.resolveUrl(deploy.url);
            return deploy;
        };
        this.uploadDeployFile = async (deployId, path, fileBody)=>{
            const response = await fetch(this.createURL(`deploys/${deployId}/files/${path}`), {
                method: "PUT",
                headers: {
                    ...authorizationHeader(this.token_)
                },
                body: fileBody
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
        };
        this.updateAccountSite = async ()=>{
            const response = await fetch(this.createURL("update-account-site"), {
                method: "PUT",
                headers: {
                    ...authorizationHeader(this.token_),
                    ...acceptApplicationJsonHeader
                }
            });
            if (!response.ok) {
                throw new ApiError1(response.status, response.statusText);
            }
            return await response.json();
        };
        this.createURL = (path)=>`${this.baseURL_}/${path}`;
        this.resolveUrl = (url)=>{
            const match = url.match(kUrlResolveRegex);
            if (match) {
                return `https://${match[1]}.quarto.pub/${match[2]}`;
            } else {
                return url;
            }
        };
        switch(environment){
            case "LOCAL":
                this.baseURL_ = "http://localhost:3000/api/v1";
                break;
            case "PRODUCTION":
            default:
                this.baseURL_ = "https://quartopub.com/api/v1";
                break;
        }
    }
    createTicket;
    showTicket;
    exchangeTicket;
    slugAvailable;
    createSite;
    createDeploy;
    getDeploy;
    uploadDeployFile;
    updateAccountSite;
    createURL;
    resolveUrl;
}
async function descriptionFromErrorResponse(response) {
    if (response.body) {
        try {
            const result1 = await response.json();
            if (typeof result1.description === "string") {
                return result1.description;
            }
        } catch  {}
    }
}
const kQuartoPub = "quarto-pub";
const kQuartoPubAuthTokenVar = "QUARTO_PUB_AUTH_TOKEN";
const quartoPubProvider = {
    name: kQuartoPub,
    description: "Quarto Pub",
    requiresServer: false,
    listOriginOnly: false,
    accountTokens: accountTokens2,
    authorizeToken: authorizeToken2,
    removeToken: removeToken2,
    resolveTarget: resolveTarget2,
    publish: publish2,
    isUnauthorized: isUnauthorized2,
    isNotFound: isNotFound2
};
function accountTokens2() {
    const envTk = environmentAuthToken1();
    const accessTks = readAccessTokens(quartoPubProvider.name);
    const accounts = [];
    if (envTk) {
        accounts.push({
            type: AccountTokenType.Environment,
            name: kQuartoPubAuthTokenVar,
            server: null,
            token: envTk
        });
    }
    if (accessTks) {
        for (const accessTk of accessTks){
            accounts.push({
                type: AccountTokenType.Authorized,
                name: accessTk.email,
                server: null,
                token: accessTk.application_token
            });
        }
    }
    return Promise.resolve(accounts);
}
async function authorizeToken2(_options) {
    if (await authorizePrompt(quartoPubProvider)) {
        const token = await authorizeQuartoPubAccessToken();
        if (token) {
            return {
                type: AccountTokenType.Authorized,
                name: token.email,
                server: null,
                token: token.application_token
            };
        } else {
            return undefined;
        }
    }
}
function removeToken2(token) {
    writeAccessTokens(quartoPubProvider.name, readAccessTokens(quartoPubProvider.name)?.filter((accessToken)=>{
        return accessToken.email !== token.name;
    }) || []);
}
const dotenvConfig1 = await quartoConfig.dotenv();
const quartoPubEnvironment = dotenvConfig1["QUARTO_PUB_ENVIRONMENT"];
function environmentAuthToken1() {
    return Deno.env.get(kQuartoPubAuthTokenVar);
}
function authorizeQuartoPubAccessToken() {
    const client = new QuartoPubClient(quartoPubEnvironment);
    const provider = {
        name: kQuartoPub,
        createTicket: ()=>client.createTicket(dotenvConfig1["QUARTO_PUB_APP_CLIENT_ID"]),
        authorizationUrl: (ticket)=>ticket.authorization_url,
        checkTicket: (ticket)=>client.showTicket(ticket.id),
        exchangeTicket: (ticket)=>client.exchangeTicket(ticket.id),
        compareTokens: (a, b)=>a.account_identifier === b.account_identifier
    };
    return authorizeAccessToken(provider);
}
function resolveTarget2(_account, target) {
    return Promise.resolve(target);
}
function publish2(accountToken, type, _input, title, slug, render, _options, target) {
    const client = new QuartoPubClient(quartoPubEnvironment, accountToken.token);
    const handler = {
        name: kQuartoPub,
        slugAvailable: (slug)=>client.slugAvailable(slug),
        createSite: (type, title, slug)=>client.createSite(type, title, slug),
        createDeploy: (siteId, files, size)=>client.createDeploy(siteId, files, size),
        getDeploy: (deployId)=>client.getDeploy(deployId),
        uploadDeployFile: (deployId, path, fileBody)=>client.uploadDeployFile(deployId, path, fileBody),
        updateAccountSite: ()=>client.updateAccountSite()
    };
    return handlePublish(handler, type, title, slug, render, target);
}
function isUnauthorized2(err) {
    return err instanceof ApiError1 && err.status === 401;
}
function isNotFound2(err) {
    return err instanceof ApiError1 && err.status === 404;
}
const CONTROL_CHARS = /[\x00-\x1F\x7F]/;
const COOKIE_NAME_BLOCKED = /[()<>@,;:\\"/[\]?={}]/;
const COOKIE_OCTET_BLOCKED = /[\s",;\\]/;
const COOKIE_OCTET = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
const TERMINATORS = [
    "\n",
    "\r",
    "\0"
];
function isSameDomainOrSubdomain(domainA, domainB) {
    if (!domainA || !domainB) {
        return false;
    }
    let longerDomain;
    let shorterDomain;
    if (domainB.length > domainA.length) {
        longerDomain = domainB;
        shorterDomain = domainA;
    } else {
        longerDomain = domainA;
        shorterDomain = domainB;
    }
    const indexOfDomain = longerDomain.indexOf(shorterDomain);
    if (indexOfDomain === -1) {
        return false;
    } else if (indexOfDomain > 0) {
        if (longerDomain.charAt(indexOfDomain - 1) !== ".") {
            return false;
        }
    }
    return true;
}
function trimTerminator(str) {
    if (str === undefined || str === "") return str;
    for(let t = 0; t < TERMINATORS.length; t++){
        const terminatorIdx = str.indexOf(TERMINATORS[t]);
        if (terminatorIdx !== -1) {
            str = str.substr(0, terminatorIdx);
        }
    }
    return str;
}
function isValidName(name) {
    if (!name) {
        return false;
    }
    if (CONTROL_CHARS.test(name) || COOKIE_NAME_BLOCKED.test(name)) {
        return false;
    }
    return true;
}
function trimWrappingDoubleQuotes(val) {
    if (val.length >= 2 && val.at(0) === '"' && val.at(-1) === '"') {
        return val.slice(1, -1);
    }
    return val;
}
function isValidValue(val) {
    if (val === "") {
        return true;
    }
    if (!val) {
        return false;
    }
    if (CONTROL_CHARS.test(val) || COOKIE_OCTET_BLOCKED.test(val) || !COOKIE_OCTET.test(val)) {
        return false;
    }
    return true;
}
function parseURL(input) {
    let copyUrl;
    if (input instanceof Request) {
        copyUrl = input.url;
    } else if (input instanceof URL) {
        copyUrl = input.toString();
    } else {
        copyUrl = input;
    }
    copyUrl = copyUrl.replace(/^\./, "");
    if (!copyUrl.includes("://")) {
        copyUrl = "http://" + copyUrl;
    }
    return new URL(copyUrl);
}
class Cookie {
    name;
    value;
    path;
    domain;
    expires;
    maxAge;
    secure;
    httpOnly;
    sameSite;
    creationDate = Date.now();
    creationIndex;
    static cookiesCreated = 0;
    constructor(options){
        if (options) {
            this.name = options.name;
            this.value = options.value;
            this.path = options.path;
            this.domain = options.domain;
            this.expires = options.expires;
            this.maxAge = options.maxAge;
            this.secure = options.secure;
            this.httpOnly = options.httpOnly;
            this.sameSite = options.sameSite;
            if (options.creationDate) {
                this.creationDate = options.creationDate;
            }
        }
        Object.defineProperty(this, "creationIndex", {
            configurable: false,
            enumerable: false,
            writable: true,
            value: ++Cookie.cookiesCreated
        });
    }
    static from(cookieStr) {
        const options = {
            name: undefined,
            value: undefined,
            path: undefined,
            domain: undefined,
            expires: undefined,
            maxAge: undefined,
            secure: undefined,
            httpOnly: undefined,
            sameSite: undefined,
            creationDate: Date.now()
        };
        const unparsed = cookieStr.slice().trim();
        const attrAndValueList = unparsed.split(";");
        const keyValuePairString = trimTerminator(attrAndValueList.shift() || "").trim();
        const keyValuePairEqualsIndex = keyValuePairString.indexOf("=");
        if (keyValuePairEqualsIndex < 0) {
            return new Cookie();
        }
        const name = keyValuePairString.slice(0, keyValuePairEqualsIndex);
        const value = trimWrappingDoubleQuotes(keyValuePairString.slice(keyValuePairEqualsIndex + 1));
        if (!(isValidName(name) && isValidValue(value))) {
            return new Cookie();
        }
        options.name = name;
        options.value = value;
        while(attrAndValueList.length){
            const cookieAV = attrAndValueList.shift()?.trim();
            if (!cookieAV) {
                continue;
            }
            const avSeperatorIndex = cookieAV.indexOf("=");
            let attrKey, attrValue;
            if (avSeperatorIndex === -1) {
                attrKey = cookieAV;
                attrValue = "";
            } else {
                attrKey = cookieAV.substr(0, avSeperatorIndex);
                attrValue = cookieAV.substr(avSeperatorIndex + 1);
            }
            attrKey = attrKey.trim().toLowerCase();
            if (attrValue) {
                attrValue = attrValue.trim();
            }
            switch(attrKey){
                case "expires":
                    if (attrValue) {
                        const expires = new Date(attrValue).getTime();
                        if (expires && !isNaN(expires)) {
                            options.expires = expires;
                        }
                    }
                    break;
                case "max-age":
                    if (attrValue) {
                        const maxAge = parseInt(attrValue, 10);
                        if (!isNaN(maxAge)) {
                            options.maxAge = maxAge;
                        }
                    }
                    break;
                case "domain":
                    if (attrValue) {
                        const domain = parseURL(attrValue).hostname;
                        if (domain) {
                            options.domain = domain;
                        }
                    }
                    break;
                case "path":
                    if (attrValue) {
                        options.path = attrValue.startsWith("/") ? attrValue : "/" + attrValue;
                    }
                    break;
                case "secure":
                    options.secure = true;
                    break;
                case "httponly":
                    options.httpOnly = true;
                    break;
                case "samesite":
                    {
                        const lowerCasedSameSite = attrValue.toLowerCase();
                        switch(lowerCasedSameSite){
                            case "strict":
                                options.sameSite = "Strict";
                                break;
                            case "lax":
                                options.sameSite = "Lax";
                                break;
                            case "none":
                                options.sameSite = "None";
                                break;
                            default:
                                break;
                        }
                        break;
                    }
                default:
                    break;
            }
        }
        return new Cookie(options);
    }
    isValid() {
        return isValidName(this.name) && isValidValue(this.value);
    }
    canSendTo(url) {
        const urlObj = parseURL(url);
        if (this.secure && urlObj.protocol !== "https:") {
            return false;
        }
        if (this.sameSite === "None" && !this.secure) return false;
        if (this.path) {
            if (this.path === urlObj.pathname) {
                return true;
            }
            if (urlObj.pathname.startsWith(this.path) && this.path[this.path.length - 1] === "/") {
                return true;
            }
            if (this.path.length < urlObj.pathname.length && urlObj.pathname.startsWith(this.path) && urlObj.pathname[this.path.length] === "/") {
                return true;
            }
            return false;
        }
        if (this.domain) {
            const hostname = urlObj.hostname;
            if (isSameDomainOrSubdomain(this.domain, hostname)) {
                return true;
            }
        }
        return false;
    }
    getCookieString() {
        return `${this.name || ""}=${this.value || ""}`;
    }
    setDomain(url) {
        this.domain = parseURL(url).hostname;
    }
    setPath(url) {
        const uriPath = parseURL(url).pathname;
        if (!uriPath || uriPath[0] !== "/") {
            this.path = "/";
        } else {
            const rightmostSlashIdx = uriPath.lastIndexOf("/");
            if (rightmostSlashIdx <= 0) {
                this.path = "/";
            } else {
                this.path = uriPath.slice(0, rightmostSlashIdx);
            }
        }
    }
    setExpires(exp) {
        if (exp instanceof Date) {
            this.expires = exp.getTime();
        } else if (typeof exp === "number" && exp >= 0) {
            this.expires = exp;
        }
    }
    isExpired() {
        if (this.maxAge !== undefined) {
            if (Date.now() - this.creationDate >= this.maxAge * 1000) {
                return true;
            }
        }
        if (this.expires !== undefined) {
            if (Date.now() - this.expires >= 0) {
                return true;
            }
        }
        return false;
    }
    toString() {
        let str = this.getCookieString();
        if (this.expires && this.expires !== Infinity) {
            str += "; Expires=" + new Date(this.expires).toUTCString();
        }
        if (this.maxAge && this.maxAge !== Infinity) {
            str += `; Max-Age=${this.maxAge}`;
        }
        if (this.domain) {
            str += `; Domain=${this.domain}`;
        }
        if (this.path) {
            str += `; Path=${this.path}`;
        }
        if (this.secure) {
            str += "; Secure";
        }
        if (this.httpOnly) {
            str += "; HttpOnly";
        }
        if (this.sameSite) {
            str += `; SameSite=${this.sameSite}`;
        }
        return str;
    }
    clone() {
        return new Cookie(JSON.parse(JSON.stringify(this)));
    }
}
const strictMatchProps = [
    "value",
    "secure",
    "httpOnly",
    "maxAge",
    "expires",
    "sameSite"
];
function cookieMatches(options, comparedWith, strictMatch = false) {
    if (options.path !== undefined && !comparedWith.path?.startsWith(options.path)) {
        return false;
    }
    if (options.domain) {
        if (!isSameDomainOrSubdomain(options.domain, comparedWith.domain)) {
            return false;
        }
    }
    if (options.name !== undefined && options.name !== comparedWith.name) {
        return false;
    }
    if (strictMatch && strictMatchProps.some((propKey)=>options[propKey] !== undefined && options[propKey] !== comparedWith[propKey])) {
        return false;
    }
    return true;
}
function cookieCompare(a, b) {
    let cmp = 0;
    const aPathLen = a.path?.length || 0;
    const bPathLen = b.path?.length || 0;
    cmp = bPathLen - aPathLen;
    if (cmp !== 0) {
        return cmp;
    }
    const aTime = a.creationDate || 2147483647000;
    const bTime = b.creationDate || 2147483647000;
    cmp = aTime - bTime;
    if (cmp !== 0) {
        return cmp;
    }
    cmp = a.creationIndex - b.creationIndex;
    return cmp;
}
class CookieJar {
    cookies = Array();
    constructor(cookies){
        this.replaceCookies(cookies);
    }
    setCookie(cookie, url) {
        let cookieObj;
        if (typeof cookie === "string") {
            cookieObj = Cookie.from(cookie);
        } else {
            cookieObj = cookie;
        }
        if (url) {
            if (!cookieObj.domain) {
                cookieObj.setDomain(url);
            }
            if (!cookieObj.path) {
                cookieObj.setPath(url);
            }
        }
        if (!cookieObj.isValid()) {
            return;
        }
        const foundCookie = this.getCookie(cookieObj);
        if (foundCookie) {
            const indexOfCookie = this.cookies.indexOf(foundCookie);
            if (!cookieObj.isExpired()) {
                this.cookies.splice(indexOfCookie, 1, cookieObj);
            } else {
                this.cookies.splice(indexOfCookie, 1);
            }
        } else if (!cookieObj.isExpired()) {
            this.cookies.push(cookieObj);
        }
        this.cookies.sort(cookieCompare);
    }
    getCookie(options) {
        const strictMatch = typeof options.isValid !== "function";
        for (const [index, cookie] of this.cookies.entries()){
            if (cookieMatches(options, cookie, strictMatch)) {
                if (!cookie.isExpired()) {
                    return cookie;
                } else {
                    this.cookies.splice(index, 1);
                    return undefined;
                }
            }
        }
    }
    getCookies(options) {
        if (options) {
            const matchedCookies = [];
            const removeCookies = [];
            for (const cookie of this.cookies){
                if (cookieMatches(options, cookie)) {
                    if (!cookie.isExpired()) {
                        matchedCookies.push(cookie);
                    } else {
                        removeCookies.push(cookie);
                    }
                }
            }
            if (removeCookies.length) {
                this.cookies = this.cookies.filter((cookie)=>!removeCookies.includes(cookie));
            }
            return matchedCookies;
        } else {
            return this.cookies;
        }
    }
    getCookieString(url) {
        const searchCookie = new Cookie();
        searchCookie.setDomain(url);
        const cookiesToSend = this.getCookies(searchCookie).filter((cookie)=>{
            return cookie.canSendTo(parseURL(url));
        }).map((c)=>c.getCookieString()).join("; ");
        return cookiesToSend;
    }
    toJSON() {
        return this.cookies;
    }
    removeCookie(options) {
        for (const [index, cookie] of this.cookies.entries()){
            if (cookieMatches(options, cookie)) {
                return this.cookies.splice(index, 1)[0];
            }
        }
    }
    removeCookies(options) {
        if (options) {
            const deletedCookies = [];
            this.cookies = this.cookies.filter((cookie)=>{
                if (cookieMatches(options, cookie)) {
                    deletedCookies.push(cookie);
                    return false;
                }
                return true;
            });
            return deletedCookies.length ? deletedCookies : undefined;
        } else {
            this.cookies = [];
        }
    }
    replaceCookies(cookies) {
        if (cookies?.length) {
            if (typeof cookies[0].isValid === "function") {
                this.cookies = cookies;
            } else {
                this.cookies = [];
                for (const option of cookies){
                    this.cookies.push(new Cookie(option));
                }
            }
        } else {
            this.cookies = [];
        }
    }
}
const redirectStatus = new Set([
    301,
    302,
    303,
    307,
    308
]);
function isRedirect(status) {
    return redirectStatus.has(status);
}
function isDomainOrSubdomain(destination, original) {
    const orig = new URL(original).hostname;
    const dest = new URL(destination).hostname;
    return orig === dest || orig.endsWith(`.${dest}`);
}
function wrapFetch(options) {
    const { cookieJar = new CookieJar(), fetch: fetch1 = globalThis.fetch } = options || {};
    async function wrappedFetch(input, init) {
        if (!input) {
            return await fetch1(input);
        }
        const cookieString = cookieJar.getCookieString(input);
        let originalRedirectOption;
        const originalRequestUrl = input.url || input.toString();
        if (input instanceof Request) {
            originalRedirectOption = input.redirect;
        }
        if (init?.redirect) {
            originalRedirectOption = init?.redirect;
        }
        const interceptedInit = {
            ...init,
            redirect: "manual"
        };
        const reqHeaders = new Headers(input.headers || {});
        if (init?.headers) {
            new Headers(init.headers).forEach((value, key)=>{
                reqHeaders.set(key, value);
            });
        }
        reqHeaders.set("cookie", cookieString);
        reqHeaders.delete("cookie2");
        interceptedInit.headers = reqHeaders;
        const response = await fetch1(input, interceptedInit);
        response.headers.forEach((value, key)=>{
            if (key.toLowerCase() === "set-cookie") {
                cookieJar.setCookie(value, response.url);
            }
        });
        const redirectCount = interceptedInit.redirectCount ?? 0;
        const redirectUrl = response.headers.has("location") ? new URL(response.headers.get("location").toString(), originalRequestUrl).toString() : undefined;
        if (redirectCount > 0) {
            Object.defineProperty(response, "redirected", {
                value: true
            });
        }
        if (!isRedirect(response.status) || !redirectUrl || redirectCount === 0 && originalRedirectOption === "manual") {
            return response;
        }
        if (originalRedirectOption === "error") {
            await response.body?.cancel();
            throw new TypeError(`URI requested responded with a redirect and redirect mode is set to error: ${response.url}`);
        }
        if (redirectCount >= 20) {
            await response.body?.cancel();
            throw new TypeError(`Reached maximum redirect of ${20} for URL: ${response.url}`);
        }
        await response.body?.cancel();
        interceptedInit.redirectCount = redirectCount + 1;
        const filteredHeaders = new Headers(interceptedInit.headers);
        if (!isDomainOrSubdomain(originalRequestUrl, redirectUrl)) {
            for (const name of [
                "authorization",
                "www-authenticate"
            ]){
                filteredHeaders.delete(name);
            }
        }
        if (interceptedInit.method === "POST") {
            filteredHeaders.delete("content-length");
            interceptedInit.method = "GET";
            interceptedInit.body = undefined;
        }
        interceptedInit.headers = filteredHeaders;
        return await wrappedFetch(redirectUrl, interceptedInit);
    }
    return wrappedFetch;
}
const fetch1 = wrapFetch();
class RSConnectClient {
    server_;
    key_;
    constructor(server_, key_){
        this.server_ = server_;
        this.key_ = key_;
        this.get = (path)=>this.fetch("GET", path);
        this.post = (path, body)=>this.fetch("POST", path, body);
        this.fetch = async (method, path, body)=>{
            return this.handleResponse(await fetch1(this.apiUrl(path), {
                method,
                headers: {
                    Accept: "application/json",
                    ...authorizationHeader1(this.key_)
                },
                body
            }));
        };
        this.apiUrl = (path)=>`${this.server_}__api__/v1/${path}`;
        this.cookies_ = new Map();
        this.server_ = ensureProtocolAndTrailingSlash(this.server_);
    }
    getUser() {
        return this.get("user");
    }
    createContent(name, title) {
        return this.post("content", JSON.stringify({
            name,
            title
        }));
    }
    getContent(guid) {
        return this.get(`content/${guid}`);
    }
    uploadBundle(guid, fileBody) {
        return this.post(`content/${guid}/bundles`, fileBody);
    }
    deployBundle(bundle) {
        return this.post(`content/${bundle.content_guid}/deploy`, JSON.stringify({
            bundle_id: bundle.id
        }));
    }
    getTaskStatus(task) {
        return this.get(`tasks/${task.task_id}?${new URLSearchParams({
            wait: "1"
        })}`);
    }
    get;
    post;
    fetch;
    apiUrl;
    handleResponse(response) {
        if (response.ok) {
            return response.json();
        } else if (response.status !== 200) {
            throw new ApiError1(response.status, response.statusText);
        } else {
            throw new Error(`${response.status} - ${response.statusText}`);
        }
    }
    cookies_;
}
const authorizationHeader1 = (key)=>!key ? {} : {
        Authorization: `Key ${key}`
    };
var FileTypes;
(function(FileTypes) {
    FileTypes[FileTypes["file"] = 0] = "file";
    FileTypes[FileTypes["link"] = 1] = "link";
    FileTypes[FileTypes["symlink"] = 2] = "symlink";
    FileTypes[FileTypes["character-device"] = 3] = "character-device";
    FileTypes[FileTypes["block-device"] = 4] = "block-device";
    FileTypes[FileTypes["directory"] = 5] = "directory";
    FileTypes[FileTypes["fifo"] = 6] = "fifo";
    FileTypes[FileTypes["contiguous-file"] = 7] = "contiguous-file";
})(FileTypes || (FileTypes = {}));
const ustarStructure = [
    {
        field: "fileName",
        length: 100
    },
    {
        field: "fileMode",
        length: 8
    },
    {
        field: "uid",
        length: 8
    },
    {
        field: "gid",
        length: 8
    },
    {
        field: "fileSize",
        length: 12
    },
    {
        field: "mtime",
        length: 12
    },
    {
        field: "checksum",
        length: 8
    },
    {
        field: "type",
        length: 1
    },
    {
        field: "linkName",
        length: 100
    },
    {
        field: "ustar",
        length: 8
    },
    {
        field: "owner",
        length: 32
    },
    {
        field: "group",
        length: 32
    },
    {
        field: "majorNumber",
        length: 8
    },
    {
        field: "minorNumber",
        length: 8
    },
    {
        field: "fileNamePrefix",
        length: 155
    },
    {
        field: "padding",
        length: 12
    }
];
const USTAR_MAGIC_HEADER = "ustar\u000000";
class FileReader {
    filePath;
    #file;
    constructor(filePath){
        this.filePath = filePath;
    }
    async read(p) {
        if (!this.#file) {
            this.#file = await Deno.open(this.filePath, {
                read: true
            });
        }
        const res = await this.#file.read(p);
        if (res === null) {
            this.#file.close();
            this.#file = undefined;
        }
        return res;
    }
}
function clean(length) {
    const buffer = new Uint8Array(length);
    return buffer;
}
function pad(num, bytes, base = 8) {
    const numString = num.toString(base);
    return "000000000000".slice(numString.length + 12 - bytes) + numString;
}
function formatHeader(data) {
    const encoder = new TextEncoder();
    const buffer = clean(512);
    let offset = 0;
    ustarStructure.forEach(function(value) {
        const entry = encoder.encode(data[value.field] || "");
        buffer.set(entry, offset);
        offset += value.length;
    });
    return buffer;
}
class Tar {
    data;
    constructor(){
        this.data = [];
    }
    async append(filenameInArchive, source) {
        if (typeof filenameInArchive !== "string") {
            throw new Error("file name not specified");
        }
        let fileName = filenameInArchive;
        let fileNamePrefix;
        if (fileName.length > 100) {
            let i1 = fileName.length;
            while(i1 >= 0){
                i1 = fileName.lastIndexOf("/", i1);
                if (i1 <= 155) {
                    fileNamePrefix = fileName.slice(0, i1);
                    fileName = fileName.slice(i1 + 1);
                    break;
                }
                i1--;
            }
            const errMsg = "ustar format does not allow a long file name (length of [file name" + "prefix] + / + [file name] must be shorter than 256 bytes)";
            if (i1 < 0 || fileName.length > 100) {
                throw new Error(errMsg);
            } else {
                assert(fileNamePrefix !== undefined);
                if (fileNamePrefix.length > 155) {
                    throw new Error(errMsg);
                }
            }
        }
        source = source || {};
        let info;
        if (source.filePath) {
            info = await Deno.stat(source.filePath);
            if (info.isDirectory) {
                info.size = 0;
                source.reader = new Buffer2();
            }
        }
        const mode = source.fileMode || info && info.mode || parseInt("777", 8) & 0xfff;
        const mtime = Math.floor(source.mtime ?? (info?.mtime ?? new Date()).valueOf() / 1000);
        const uid = source.uid || 0;
        const gid = source.gid || 0;
        if (typeof source.owner === "string" && source.owner.length >= 32) {
            throw new Error("ustar format does not allow owner name length >= 32 bytes");
        }
        if (typeof source.group === "string" && source.group.length >= 32) {
            throw new Error("ustar format does not allow group name length >= 32 bytes");
        }
        const fileSize = info?.size ?? source.contentSize;
        assert(fileSize !== undefined, "fileSize must be set");
        const type = source.type ? FileTypes[source.type] : info?.isDirectory ? FileTypes.directory : FileTypes.file;
        const tarData = {
            fileName,
            fileNamePrefix,
            fileMode: pad(mode, 7),
            uid: pad(uid, 7),
            gid: pad(gid, 7),
            fileSize: pad(fileSize, 11),
            mtime: pad(mtime, 11),
            checksum: "        ",
            type: type.toString(),
            ustar: USTAR_MAGIC_HEADER,
            owner: source.owner || "",
            group: source.group || "",
            filePath: source.filePath,
            reader: source.reader
        };
        let checksum = 0;
        const encoder = new TextEncoder();
        Object.keys(tarData).filter((key)=>[
                "filePath",
                "reader"
            ].indexOf(key) < 0).forEach(function(key) {
            checksum += encoder.encode(tarData[key]).reduce((p, c)=>p + c, 0);
        });
        tarData.checksum = pad(checksum, 6) + "\u0000 ";
        this.data.push(tarData);
    }
    getReader() {
        const readers = [];
        this.data.forEach((tarData)=>{
            let { reader } = tarData;
            const { filePath } = tarData;
            const headerArr = formatHeader(tarData);
            readers.push(new Buffer2(headerArr));
            if (!reader) {
                assert(filePath !== undefined);
                reader = new FileReader(filePath);
            }
            readers.push(reader);
            assert(tarData.fileSize !== undefined, "fileSize must be set");
            readers.push(new Buffer2(clean(512 - (parseInt(tarData.fileSize, 8) % 512 || 512))));
        });
        readers.push(new Buffer2(clean(512 * 2)));
        return new MultiReader(readers);
    }
}
async function createBundle(type, files, tempContext) {
    const manifestFiles = {};
    for (const file of files.files){
        const filePath = join2(files.baseDir, file);
        if (Deno.statSync(filePath).isFile) {
            const fileBytes = Deno.readFileSync(filePath);
            const checksum = md5HashBytes(fileBytes);
            manifestFiles[file] = {
                checksum
            };
        }
    }
    const manifest = {
        version: 1,
        locale: "en_US",
        platform: "4.2.0",
        metadata: {
            appmode: "static",
            primary_rmd: null,
            primary_html: files.rootFile,
            content_category: type === "site" ? "site" : null,
            has_parameters: false
        },
        packages: null,
        files: manifestFiles,
        users: null
    };
    const stageDir = tempContext.createDir();
    files.files.forEach((file)=>{
        const filePath = join2(files.baseDir, file);
        if (Deno.statSync(filePath).isFile) {
            const targetDir = join2(stageDir, dirname2(file));
            ensureDirSync(targetDir);
            Deno.copyFileSync(filePath, join2(stageDir, file));
        }
    });
    Deno.writeTextFileSync(join2(stageDir, "manifest.json"), JSON.stringify(manifest, undefined, 2));
    const tar = new Tar();
    const tarFiles = [
        ...files.files,
        "manifest.json"
    ];
    for (const tarFile of tarFiles){
        await tar.append(pathWithForwardSlashes(tarFile), {
            filePath: join2(stageDir, tarFile)
        });
    }
    const tarFile = tempContext.createFile({
        suffix: ".tar"
    });
    const writer = Deno.openSync(tarFile, {
        write: true,
        create: true
    });
    await copy2(tar.getReader(), writer);
    writer.close();
    const targzFile = `${tarFile}.gz`;
    const src = await Deno.open(tarFile);
    const dest = await Deno.open(targzFile, {
        create: true,
        write: true
    });
    await src.readable.pipeThrough(new CompressionStream("gzip")).pipeTo(dest.writable);
    return {
        bundlePath: targzFile,
        manifest
    };
}
const kRSConnect = "connect";
const kRSConnectDescription = "Posit Connect";
const kRSConnectServerVar = "CONNECT_SERVER";
const kRSConnectAuthTokenVar = "CONNECT_API_KEY";
const rsconnectProvider = {
    name: kRSConnect,
    description: kRSConnectDescription,
    requiresServer: true,
    listOriginOnly: true,
    accountTokens: accountTokens3,
    authorizeToken: authorizeToken3,
    removeToken: removeToken3,
    resolveTarget: resolveTarget3,
    publish: publish3,
    isUnauthorized: isUnauthorized3,
    isNotFound: isNotFound3
};
function accountTokens3() {
    const accounts = [];
    const server = Deno.env.get(kRSConnectServerVar);
    const apiKey = Deno.env.get(kRSConnectAuthTokenVar);
    if (server && apiKey) {
        accounts.push({
            type: AccountTokenType.Environment,
            name: kRSConnectAuthTokenVar,
            server,
            token: apiKey
        });
    }
    const tokens = readAccessTokens(kRSConnect);
    if (tokens) {
        accounts.push(...tokens.map((token)=>({
                type: AccountTokenType.Authorized,
                name: token.username,
                server: token.server,
                token: token.key
            })));
    }
    return Promise.resolve(accounts);
}
function removeToken3(token) {
    writeAccessTokens(rsconnectProvider.name, readAccessTokens(rsconnectProvider.name)?.filter((accessToken)=>{
        return accessToken.server !== token.server && accessToken.username !== token.name;
    }) || []);
}
async function authorizeToken3(options, target) {
    let server = target?.url ? new URL(target.url).origin : options.server || undefined;
    if (server) {
        server = ensureProtocolAndTrailingSlash(server);
    }
    while(server === undefined){
        server = await Input.prompt({
            message: "Server URL:",
            hint: "e.g. https://connect.example.com/",
            validate: (value)=>{
                if (value.length === 0) {
                    throw new Error();
                }
                try {
                    const url = new URL(ensureProtocolAndTrailingSlash(value));
                    if (![
                        "http:",
                        "https:"
                    ].includes(url.protocol)) {
                        return `${value} is not an HTTP URL`;
                    } else {
                        return true;
                    }
                } catch  {
                    return `${value} is not a valid URL`;
                }
            },
            transform: ensureProtocolAndTrailingSlash
        });
        const client = new RSConnectClient(server);
        try {
            await client.getUser();
        } catch (err) {
            if (isUnauthorized3(err)) {
                break;
            } else {
                info(red("   Unable to connect to server (is this a valid Posit Connect Server?)"));
                server = undefined;
            }
        }
    }
    while(true){
        const apiKey = await Secret.prompt({
            message: "API Key:",
            hint: "Learn more at https://docs.rstudio.com/connect/user/api-keys/"
        });
        if (apiKey.length === 0) {
            throw new Error();
        }
        try {
            const client = new RSConnectClient(server, apiKey);
            const user = await client.getUser();
            if (user.user_role !== "viewer") {
                const account = {
                    username: user.username,
                    server,
                    key: apiKey
                };
                writeAccessToken(kRSConnect, account, (a, b)=>a.server === b.server && a.username === b.username);
                return {
                    type: AccountTokenType.Authorized,
                    name: user.username,
                    server,
                    token: apiKey
                };
            } else {
                promptError("API key is for an Posit Connect viewer rather than a publisher.");
            }
        } catch (err) {
            if (isUnauthorized3(err)) {
                promptError("API key is not authorized for this Posit Connect server.");
            } else {
                throw err;
            }
        }
    }
}
async function resolveTarget3(account, target) {
    const client = new RSConnectClient(account.server, account.token);
    const content = await client.getContent(target.id);
    return contentAsTarget(content);
}
async function publish3(account, type, _input, title, slug, render, _options, target) {
    const client = new RSConnectClient(account.server, account.token);
    let content;
    await withSpinner({
        message: `Preparing to publish ${type}`
    }, async ()=>{
        if (!target) {
            content = await createContent(client, title, slug);
            if (content) {
                target = contentAsTarget(content);
            } else {
                throw new Error();
            }
        } else {
            content = await client.getContent(target.id);
        }
    });
    info("");
    const publishFiles = await render();
    const tempContext = createTempContext();
    try {
        let task;
        await withSpinner({
            message: ()=>`Uploading files`
        }, async ()=>{
            const { bundlePath } = await createBundle(type, publishFiles, tempContext);
            const bundleBytes = Deno.readFileSync(bundlePath);
            const bundleBlob = new Blob([
                bundleBytes.buffer
            ]);
            const bundle = await client.uploadBundle(target.id, bundleBlob);
            task = await client.deployBundle(bundle);
        });
        await withSpinner({
            message: `Publishing ${type}`
        }, async ()=>{
            while(true){
                const status = await client.getTaskStatus(task);
                if (status.finished) {
                    if (status.code === 0) {
                        break;
                    } else {
                        throw new Error(`Error attempting to publish content: ${status.code} - ${status.error}`);
                    }
                }
            }
        });
        completeMessage(`Published: ${content.content_url}\n`);
        return Promise.resolve([
            target,
            new URL(content.dashboard_url)
        ]);
    } finally{
        tempContext.cleanup();
    }
}
function isUnauthorized3(err) {
    return err instanceof ApiError1 && err.status === 401;
}
function isConflict(err) {
    return err instanceof ApiError1 && err.status === 409;
}
function isNotFound3(err) {
    return err instanceof ApiError1 && err.status === 404;
}
function contentAsTarget(content) {
    return {
        id: content.guid,
        url: content.content_url,
        code: false
    };
}
async function createContent(client, title, slug) {
    while(true){
        const name = slug + "-" + randomHex(4);
        try {
            return await client.createContent(name, title);
        } catch (err) {
            if (!isConflict(err)) {
                throw err;
            }
        }
    }
}
function promptError(msg) {
    info(red(`  ${msg}`));
}
class PositCloudClient {
    server;
    token;
    token_secret;
    key;
    constructor(server, token, token_secret){
        this.server = server;
        this.token = token;
        this.token_secret = token_secret;
        this.get = (path, queryParams)=>this.fetch("GET", path, {
                queryParams
            });
        this.post = (path, body)=>this.fetch("POST", path, {
                body
            });
        this.fetch = async (method, path, opts)=>{
            const fullPath = `/v1/${path}`;
            const pathAndQuery = opts.queryParams ? `${fullPath}?${opts.queryParams}` : fullPath;
            const url = `${this.server}${pathAndQuery}`;
            const authHeaders = await this.authorizationHeaders(method, fullPath, opts.body);
            const contentTypeHeader = opts.body ? {
                "Content-Type": "application/json"
            } : {};
            const headers = {
                Accept: "application/json",
                "User-Agent": `quarto-cli/${quartoConfig.version()}`,
                ...authHeaders,
                ...contentTypeHeader
            };
            const requestInit = {
                method,
                headers,
                body: opts.body,
                redirect: "manual"
            };
            const request = new Request(url, requestInit);
            return await this.handleResponse(await fetch(request));
        };
        this.handleResponse = async (response)=>{
            if (response.status >= 200 && response.status < 400) {
                if (response.headers.get("Content-Type")?.startsWith("application/json")) {
                    return await response.json();
                } else {
                    return await response.text();
                }
            } else if (response.status >= 400) {
                const json = await response.json();
                let errorDescription = undefined;
                if (json.error) {
                    errorDescription = json.error;
                    if (json.error_type) {
                        errorDescription = `${errorDescription}, code=${json.error_type}`;
                    }
                }
                throw new ApiError1(response.status, response.statusText, errorDescription);
            } else {
                throw new Error(`${response.status} - ${response.statusText}`);
            }
        };
        this.authorizationHeaders = async (method, path, body)=>{
            const date = new Date().toUTCString();
            const checksum = md5Hash(body || "");
            const canonicalRequest = [
                method,
                path,
                date,
                checksum
            ].join("\n");
            const signature = await this.getSignature(canonicalRequest);
            return {
                "X-Auth-Token": this.token,
                "X-Auth-Signature": `${signature}; version=1`,
                "Date": date,
                "X-Content-Checksum": checksum
            };
        };
        this.server = server;
        this.token = token;
        this.token_secret = token_secret;
    }
    getUser() {
        return this.get("users/me");
    }
    getApplication(id) {
        return this.get(`applications/${id}`);
    }
    createOutput(name, spaceId, projectId, contentCategory) {
        return this.post("outputs", JSON.stringify({
            name: name,
            application_type: "static",
            space: spaceId,
            project: projectId,
            content_category: contentCategory
        }));
    }
    setBundleReady(bundleId) {
        return this.post(`bundles/${bundleId}/status`, JSON.stringify({
            status: "ready"
        }));
    }
    createBundle(applicationId, contentLength, checksum) {
        return this.post(`bundles`, JSON.stringify({
            "application": applicationId,
            "content_type": "application/x-tar",
            "content_length": contentLength,
            "checksum": checksum
        }));
    }
    getTask(id) {
        return this.get(`tasks/${id}`, {
            legacy: "false"
        });
    }
    createRevision(outputId, contentCategory) {
        return this.post(`outputs/${outputId}/revisions`, JSON.stringify({
            content_category: contentCategory
        }));
    }
    getContent(id) {
        return this.get(`content/${id}`);
    }
    deployApplication(applicationId, bundleId) {
        return this.post(`applications/${applicationId}/deploy`, JSON.stringify({
            "bundle": bundleId,
            rebuild: false
        }));
    }
    get;
    post;
    fetch;
    handleResponse;
    authorizationHeaders;
    async getSignature(data) {
        if (!this.key) {
            const decodedTokenSecret = decodeBase64(this.token_secret);
            this.key = await stdCrypto.subtle.importKey("raw", decodedTokenSecret, {
                name: "HMAC",
                hash: "SHA-256"
            }, false, [
                "sign"
            ]);
        }
        const canonicalRequestBytes = new TextEncoder().encode(data);
        const signatureArrayBuffer = await stdCrypto.subtle.sign("HMAC", this.key, canonicalRequestBytes);
        const signatureBytes = Array.from(new Uint8Array(signatureArrayBuffer));
        const signatureHex = signatureBytes.map((b)=>b.toString(16).padStart(2, "0")).join("");
        return encodeBase64(signatureHex);
    }
}
class UploadClient {
    url;
    constructor(url){
        this.url = url;
        this.upload = async (fileBody, bundleSize, presignedChecksum)=>{
            const response = await fetch(this.url, {
                method: "PUT",
                headers: {
                    Accept: "application/json",
                    "content-type": "application/x-tar",
                    "content-length": bundleSize.toString(),
                    "content-md5": presignedChecksum
                },
                body: fileBody
            });
            if (!response.ok) {
                if (response.status !== 200) {
                    throw new ApiError1(response.status, response.statusText);
                } else {
                    throw new Error(`${response.status} - ${response.statusText}`);
                }
            }
        };
        this.url = url;
    }
    upload;
}
const kPositCloud = "posit-cloud";
const kPositCloudDescription = "Posit Cloud";
const kPositCloudServerVar = "POSIT_CLOUD_SERVER";
const kPositCloudTokenVar = "POSIT_CLOUD_TOKEN";
const kPositCloudAuthTokenSecretVar = "POSIT_CLOUD_SECRET";
const positCloudProvider = {
    name: kPositCloud,
    description: kPositCloudDescription,
    requiresServer: true,
    listOriginOnly: true,
    hidden: true,
    accountDescriptor: "credential",
    accountTokens: accountTokens4,
    authorizeToken: authorizeToken4,
    removeToken: removeToken4,
    resolveTarget: resolveTarget4,
    publish: publish4,
    isUnauthorized: isUnauthorized4,
    isNotFound: isNotFound4
};
function getServer() {
    return Deno.env.get(kPositCloudServerVar) || "https://api.posit.cloud";
}
function createClientFromAccountToken(accountToken) {
    const [token, tokenSecret] = accountToken.token.split("|");
    return new PositCloudClient(getServer(), token, tokenSecret);
}
function combineTokenAndSecret(token, tokenSecret) {
    return `${token}|${tokenSecret}`;
}
function accountTokens4() {
    const accounts = [];
    const server = Deno.env.get(kPositCloudServerVar);
    const token = Deno.env.get(kPositCloudTokenVar);
    const tokenSecret = Deno.env.get(kPositCloudAuthTokenSecretVar);
    if (server && token && tokenSecret) {
        accounts.push({
            type: AccountTokenType.Environment,
            name: kPositCloudTokenVar,
            server,
            token: combineTokenAndSecret(token, tokenSecret)
        });
    }
    const tokens = readAccessTokens(kPositCloud);
    if (tokens) {
        accounts.push(...tokens.map((token)=>({
                type: AccountTokenType.Authorized,
                name: token.username,
                server: null,
                token: combineTokenAndSecret(token.token, token.tokenSecret)
            })));
    }
    return Promise.resolve(accounts);
}
function removeToken4(token) {
    writeAccessTokens(positCloudProvider.name, readAccessTokens(positCloudProvider.name)?.filter((accessToken)=>{
        return accessToken.username !== token.name;
    }) || []);
}
async function authorizeToken4(_options, _target) {
    while(true){
        const token = await Input.prompt({
            message: "Token:"
        });
        if (token.length === 0) {
            throw new Error();
        }
        const tokenSecret = await Secret.prompt({
            message: "Token secret:"
        });
        if (tokenSecret.length === 0) {
            throw new Error();
        }
        const tokenAndSecret = combineTokenAndSecret(token, tokenSecret);
        try {
            const client = new PositCloudClient(getServer(), token, tokenSecret);
            const user = await client.getUser();
            const account = {
                username: user.email,
                token,
                tokenSecret
            };
            writeAccessToken(kPositCloud, account, (a, b)=>a.username === b.username);
            return {
                type: AccountTokenType.Authorized,
                name: user.email,
                server: null,
                token: tokenAndSecret
            };
        } catch (err) {
            if (isUnauthorized4(err)) {
                promptError1("Credential is unauthorized.");
            } else {
                throw err;
            }
        }
    }
}
async function resolveTarget4(account, target) {
    const client = createClientFromAccountToken(account);
    const content = await client.getContent(target.id);
    return contentAsTarget1(content);
}
async function publish4(account, type, _input, title, _slug, render, _options, target) {
    const client = createClientFromAccountToken(account);
    const publishFiles = await render();
    const tempContext = createTempContext();
    const { bundlePath, manifest } = await createBundle(type, publishFiles, tempContext);
    const { content_category } = manifest.metadata;
    const { content, applicationId } = await withSpinner({
        message: `Preparing to publish ${type}`
    }, async ()=>{
        if (target) {
            const content = await client.getContent(target.id);
            const revision = await client.createRevision(content.id, content_category);
            return {
                content,
                applicationId: revision.application_id
            };
        } else {
            const content = await createContent1(client, title, content_category);
            target = {
                id: content.id.toString(),
                url: content.url,
                code: false
            };
            return {
                content,
                applicationId: content.source_id
            };
        }
    });
    info("");
    try {
        const bundle = await withSpinner({
            message: ()=>`Uploading files`
        }, async ()=>{
            const bundleBytes = Deno.readFileSync(bundlePath);
            const bundleSize = bundleBytes.length;
            const bundleHash = md5HashBytes(bundleBytes);
            const bundle = await client.createBundle(applicationId, bundleSize, bundleHash);
            const bundleBlob = new Blob([
                bundleBytes.buffer
            ]);
            const uploadClient = new UploadClient(bundle.presigned_url);
            await uploadClient.upload(bundleBlob, bundleSize, bundle.presigned_checksum);
            return bundle;
        });
        await withSpinner({
            message: `Publishing ${type}`
        }, async ()=>{
            await client.setBundleReady(bundle.id);
            const initialTask = await client.deployApplication(applicationId, bundle.id);
            while(true){
                await new Promise((resolve)=>setTimeout(resolve, 1000));
                const task = await client.getTask(initialTask.task_id);
                if (task.finished) {
                    break;
                }
            }
        });
        completeMessage(`Published: ${content.url}\n`);
        return [
            target,
            new URL(content.url)
        ];
    } finally{
        tempContext.cleanup();
    }
}
function isUnauthorized4(err) {
    return err instanceof ApiError1 && err.status === 401;
}
function isNotFound4(err) {
    return err instanceof ApiError1 && err.status === 404;
}
function contentAsTarget1(content) {
    return {
        id: content.id.toString(),
        url: content.url,
        code: false
    };
}
async function createContent1(client, title, contentCategory) {
    let spaceId = null;
    let projectId = null;
    const projectApplicationId = Deno.env.get("LUCID_APPLICATION_ID");
    if (projectApplicationId) {
        const projectApplication = await client.getApplication(projectApplicationId);
        const project = await client.getContent(projectApplication.content_id);
        projectId = project.id;
        spaceId = project.space_id;
    }
    return await client.createOutput(title, spaceId, projectId, contentCategory);
}
function promptError1(msg) {
    info(red(`  ${msg}`));
}
var LogLevel;
(function(LogLevel) {
    LogLevel["DEBUG"] = "DEBUG";
    LogLevel["INFO"] = "INFO";
    LogLevel["WARN"] = "WARN";
    LogLevel["ERROR"] = "ERROR";
})(LogLevel || (LogLevel = {}));
var LogPrefix;
(function(LogPrefix) {
    LogPrefix["GENERAL"] = "[General]";
    LogPrefix["ATTACHMENT"] = "[Attach]";
    LogPrefix["RENDER"] = "[Render]";
})(LogPrefix || (LogPrefix = {}));
const PAGE_TYPE = "page";
const EMPTY_PARENT = {
    space: "",
    parent: ""
};
var ContentStatusEnum;
(function(ContentStatusEnum) {
    ContentStatusEnum["current"] = "current";
    ContentStatusEnum["deleted"] = "deleted";
    ContentStatusEnum["historical"] = "historical";
    ContentStatusEnum["draft"] = "draft";
})(ContentStatusEnum || (ContentStatusEnum = {}));
var PublishTypeEnum;
(function(PublishTypeEnum) {
    PublishTypeEnum["document"] = "document";
    PublishTypeEnum["site"] = "site";
})(PublishTypeEnum || (PublishTypeEnum = {}));
var ContentBodyRepresentation;
(function(ContentBodyRepresentation) {
    ContentBodyRepresentation["storage"] = "storage";
})(ContentBodyRepresentation || (ContentBodyRepresentation = {}));
var ContentChangeType;
(function(ContentChangeType) {
    ContentChangeType["create"] = "create";
    ContentChangeType["update"] = "update";
    ContentChangeType["delete"] = "delete";
})(ContentChangeType || (ContentChangeType = {}));
var ContentPropertyKey;
(function(ContentPropertyKey) {
    ContentPropertyKey["fileName"] = "fileName";
    ContentPropertyKey["isQuartoSiteParent"] = "isQuartoSiteParent";
})(ContentPropertyKey || (ContentPropertyKey = {}));
const DESCENDANT_PAGE_SIZE = 200;
const V2EDITOR_METADATA = {
    metadata: {
        properties: {
            editor: {
                value: "v2"
            }
        }
    }
};
const CAN_SET_PERMISSIONS_DISABLED = "CONFLUENCE_LOCAL_STORAGE_CAN_SET_PERMISSIONS_DISABLED";
const CAN_SET_PERMISSIONS_ENABLED_CACHED = "CONFLUENCE_LOCAL_STORAGE_CAN_SET_PERMISSIONS_ENABLED_CACHED";
const trace2 = (message, value = "", prefix = LogPrefix.GENERAL, level = LogLevel.DEBUG)=>{
    const logger = {
        [LogLevel.DEBUG]: debug,
        [LogLevel.INFO]: info,
        [LogLevel.WARN]: warn,
        [LogLevel.ERROR]: error
    };
    const prefixedMessage = `\n[Confluence] ${prefix} ${message}`;
    logger[level](`${prefixedMessage} ${Deno.inspect(value)}`);
};
const logError1 = (message, value, prefix = LogPrefix.GENERAL)=>trace2(message, value, prefix, LogLevel.ERROR);
const LINK_FINDER = /(\S*.qmd'|\S*.qmd#\S*')/g;
const FILE_FINDER = /(?<=href=\')(.*)(?=\.qmd)/;
const ATTACHMENT_FINDER = /(?<=ri:attachment ri:filename=["\'])[^"\']+?\.(?:jpe?g|png|gif|m4a|mp3|txt|svg|ai|pdf)(?=["\'])/g;
const capitalizeFirstLetter = (value = "")=>{
    if (!value || value.length === 0) {
        return "";
    }
    return value[0].toUpperCase() + value.slice(1);
};
const transformAtlassianDomain = (domain)=>{
    return ensureTrailingSlash(isHttpUrl(domain) ? domain : `https://${domain}.atlassian.net`);
};
const isUnauthorized5 = (error)=>{
    return error instanceof ApiError1 && (error.status === 401 || error.status === 403);
};
const isNotFound5 = (error)=>{
    return error instanceof ApiError1 && error.status === 404;
};
const exitIfNoValue = (value)=>{
    if (value?.length === 0) {
        throw new Error("");
    }
};
const validateServer = (value)=>{
    exitIfNoValue(value);
    try {
        new URL(transformAtlassianDomain(value));
        return true;
    } catch  {
        return `Not a valid URL`;
    }
};
const validateEmail = (value)=>{
    exitIfNoValue(value);
    const expression = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
    const isValid = expression.test(value);
    if (!isValid) {
        return "Invalid email address";
    }
    return true;
};
const validateToken = (value)=>{
    exitIfNoValue(value);
    return true;
};
const validateParentURL = (value)=>{
    exitIfNoValue(value);
    return true;
};
const getMessageFromAPIError = (error)=>{
    if (error instanceof ApiError1) {
        return `${error.status} - ${error.statusText}`;
    }
    if (error?.message) {
        return error.message;
    }
    return "Unknown error";
};
const tokenFilterOut = (accessToken, token)=>{
    return accessToken.server !== token.server && accessToken.name !== token.name;
};
const confluenceParentFromString = (url)=>{
    let toMatch = url;
    const urlNoParamsList = url?.split("?");
    if (urlNoParamsList.length === 2) {
        toMatch = urlNoParamsList[0] ?? url;
    }
    const match = toMatch.match(/^https.*?wiki\/spaces\/(?:(~?\w+)|(~?\w+)\/overview|(~?.+)\/pages\/(\d+).*)$/);
    if (match) {
        return {
            space: match[1] || match[2] || match[3],
            parent: match[4]
        };
    }
    return EMPTY_PARENT;
};
const wrapBodyForConfluence = (value)=>{
    const body = {
        storage: {
            value,
            representation: ContentBodyRepresentation.storage
        }
    };
    return body;
};
const buildPublishRecordForContent = (server, content)=>{
    if (!content?.id || !content?.space || !(server.length > 0)) {
        throw new Error("Invalid Content");
    }
    const url = `${ensureTrailingSlash(server)}wiki/spaces/${content.space.key}/pages/${content.id}`;
    const newPublishRecord = {
        id: content.id,
        url
    };
    return [
        newPublishRecord,
        new URL(url)
    ];
};
const doWithSpinner = async (message, toDo)=>{
    return await withSpinner({
        message
    }, toDo);
};
const getNextVersion = (previousPage)=>{
    const previousNumber = previousPage.version?.number ?? 0;
    return {
        number: previousNumber + 1
    };
};
const writeTokenComparator = (a, b)=>a.server === b.server && a.name === b.name;
const filterFilesForUpdate = (allFiles)=>{
    const fileFilter = (fileName)=>{
        if (!fileName.endsWith(".xml")) {
            return false;
        }
        return true;
    };
    const result1 = allFiles.filter(fileFilter);
    return result1;
};
const isContentCreate = (content)=>{
    return content.contentChangeType === ContentChangeType.create;
};
const isContentUpdate = (content)=>{
    return content.contentChangeType === ContentChangeType.update;
};
const isContentDelete = (content)=>{
    return content.contentChangeType === ContentChangeType.delete;
};
const buildContentCreate = (title, space, body, fileName, parent, status = ContentStatusEnum.current, id = null, type = PAGE_TYPE)=>{
    return {
        contentChangeType: ContentChangeType.create,
        title,
        type,
        space,
        status,
        ancestors: parent ? [
            {
                id: parent
            }
        ] : null,
        body,
        fileName
    };
};
const buildContentUpdate = (id, title, body, fileName, parent, status = ContentStatusEnum.current, type = PAGE_TYPE, version = null, ancestors = null)=>{
    return {
        contentChangeType: ContentChangeType.update,
        id,
        version,
        title,
        type,
        status,
        ancestors: parent ? [
            {
                id: parent
            }
        ] : ancestors,
        body,
        fileName
    };
};
const findPagesToDelete = (fileMetadataList, existingSite = [])=>{
    const activeParents = existingSite.reduce((accumulator, page)=>{
        return [
            ...accumulator,
            ...page.ancestors ?? []
        ];
    }, []);
    const isActiveParent = (id)=>!!activeParents.find((parent)=>parent.id === id);
    return existingSite.reduce((accumulator, page)=>{
        if (!fileMetadataList.find((file)=>(pathWithForwardSlashes(file.fileName) === page?.metadata?.fileName) ?? "") && !isActiveParent(page.id)) {
            return [
                ...accumulator,
                page
            ];
        }
        return accumulator;
    }, []);
};
const buildSpaceChanges = (fileMetadataList, parent, space, existingSite = [])=>{
    const spaceChangesCallback = (accumulatedChanges, fileMetadata)=>{
        const findPageInExistingSite = (fileName)=>existingSite.find((page)=>page?.metadata?.fileName === fileName);
        const universalFileName = pathWithForwardSlashes(fileMetadata.fileName);
        const existingPage = findPageInExistingSite(universalFileName);
        let spaceChangeList = [];
        const pathList = universalFileName.split("/");
        let pageParent = pathList.length > 1 ? pathList.slice(0, pathList.length - 1).join("/") : parent?.parent;
        const checkCreateParents = ()=>{
            if (pathList.length < 2) {
                return null;
            }
            let existingSiteParent = null;
            const parentsList = pathList.slice(0, pathList.length - 1);
            parentsList.forEach((parentFileName, index)=>{
                const ancestorFilePath = parentsList.slice(0, index).join("/");
                const ancestor = index > 0 ? ancestorFilePath : parent?.parent;
                let fileName = `${ancestorFilePath}/${parentFileName}`;
                if (fileName.startsWith("/")) {
                    fileName = parentFileName;
                }
                const existingParentCreateChange = accumulatedChanges.find((spaceChange)=>{
                    if (spaceChange.fileName) {
                        return spaceChange?.fileName === fileName;
                    }
                    return false;
                });
                existingSiteParent = existingSite.find((page)=>{
                    if (page?.metadata?.fileName) {
                        return page.metadata.fileName === fileName;
                    }
                    return false;
                });
                if (!existingParentCreateChange && !existingSiteParent) {
                    const existingAncestor = findPageInExistingSite(ancestor ?? "");
                    spaceChangeList = [
                        ...spaceChangeList,
                        buildContentCreate(capitalizeFirstLetter(parentFileName), space, {
                            storage: {
                                value: "",
                                representation: "storage"
                            }
                        }, fileName, existingAncestor ? existingAncestor.id : ancestor, ContentStatusEnum.current)
                    ];
                }
            });
            return existingSiteParent;
        };
        const existingParent = checkCreateParents();
        pageParent = existingParent ? existingParent.id : pageParent;
        if (existingPage) {
            spaceChangeList = [
                buildContentUpdate(existingPage.id, fileMetadata.title, fileMetadata.contentBody, universalFileName, pageParent)
            ];
        } else {
            spaceChangeList = [
                ...spaceChangeList,
                buildContentCreate(fileMetadata.title, space, fileMetadata.contentBody, universalFileName, pageParent, ContentStatusEnum.current)
            ];
        }
        return [
            ...accumulatedChanges,
            ...spaceChangeList
        ];
    };
    const pagesToDelete = findPagesToDelete(fileMetadataList, existingSite);
    const deleteChanges = pagesToDelete.map((toDelete)=>{
        return {
            contentChangeType: ContentChangeType.delete,
            id: toDelete.id
        };
    });
    let spaceChanges = fileMetadataList.reduce(spaceChangesCallback, deleteChanges);
    const activeAncestorIds = spaceChanges.reduce((accumulator, change)=>{
        if (change?.ancestors?.length) {
            const idList = change.ancestors.map((ancestor)=>ancestor?.id ?? "");
            return [
                ...accumulator,
                ...idList
            ];
        }
        return accumulator;
    }, []);
    spaceChanges = spaceChanges.filter((change)=>{
        if (isContentDelete(change) && activeAncestorIds.includes(change.id)) {
            return false;
        }
        return true;
    });
    return spaceChanges;
};
const flattenIndexes = (changes, metadataByFileName, siteParentId)=>{
    const getFileNameForChange = (change)=>{
        if (isContentDelete(change)) {
            return "";
        }
        return pathWithForwardSlashes(change?.fileName ?? "");
    };
    const isIndexFile = (change)=>{
        return getFileNameForChange(change)?.endsWith("/index.xml");
    };
    const toIndexPageLookup = (accumulator, change)=>{
        if (isContentDelete(change)) {
            return accumulator;
        }
        const fileName = getFileNameForChange(change);
        const isIndex = isIndexFile(change);
        if (isIndex) {
            const folderFileName = fileName.replace("/index.xml", "");
            return {
                ...accumulator,
                [folderFileName]: change
            };
        }
        return accumulator;
    };
    const indexLookup = changes.reduce(toIndexPageLookup, {});
    const toFlattenedIndexes = (accumulator, change)=>{
        if (isContentDelete(change)) {
            return [
                ...accumulator,
                change
            ];
        }
        const fileName = getFileNameForChange(change);
        if (fileName === "index.xml") {
            const rootUpdate = buildContentUpdate(siteParentId, change.title, change.body, "index.xml");
            return [
                ...accumulator,
                rootUpdate
            ];
        }
        const parentFileName = fileName.replace("/index.xml", "");
        const parentSitePage = metadataByFileName[parentFileName];
        if (isIndexFile(change)) {
            if (parentSitePage) {
                const parentUpdate = buildContentUpdate(parentSitePage.id, change.title, change.body, parentSitePage.metadata.fileName ?? "", "", ContentStatusEnum.current, PAGE_TYPE, null, parentSitePage.ancestors);
                return [
                    ...accumulator,
                    parentUpdate
                ];
            } else {
                return [
                    ...accumulator
                ];
            }
        }
        const indexCreateChange = indexLookup[fileName];
        if (indexCreateChange && !isContentDelete(indexCreateChange)) {
            change.title = indexCreateChange.title ?? change.title;
            change.body = indexCreateChange.body ?? change.body;
        }
        return [
            ...accumulator,
            change
        ];
    };
    const flattenedIndexes = changes.reduce(toFlattenedIndexes, []);
    return flattenedIndexes;
};
const replaceExtension = (fileName, oldExtension, newExtension)=>{
    return fileName.replace(oldExtension, newExtension);
};
const getTitle = (fileName, metadataByInput)=>{
    const qmdFileName = replaceExtension(fileName, ".xml", ".qmd");
    const metadataTitle = metadataByInput[qmdFileName]?.title;
    const titleFromFilename = capitalizeWord(fileName.split(".")[0] ?? fileName);
    const title = metadataTitle ?? titleFromFilename;
    return title;
};
const flattenMetadata = (list = [])=>{
    const result1 = list.reduce((accumulator, currentValue)=>{
        const updated = accumulator;
        updated[currentValue.key] = currentValue.value;
        return updated;
    }, {});
    return result1;
};
const mergeSitePages = (shallowPages = [], contentProperties = [])=>{
    const result1 = shallowPages.map((contentSummary, index)=>{
        const sitePage = {
            title: contentSummary.title,
            id: contentSummary.id ?? "",
            metadata: flattenMetadata(contentProperties[index]),
            ancestors: contentSummary.ancestors ?? []
        };
        return sitePage;
    });
    return result1;
};
const buildFileToMetaTable = (fileMetadata)=>{
    return fileMetadata.reduce((accumulator, page)=>{
        const fileName = page?.metadata?.fileName ?? "";
        const fileNameQMD = fileName.replace("xml", "qmd");
        if (fileName.length === 0) {
            return accumulator;
        }
        accumulator[fileNameQMD] = page;
        return accumulator;
    }, {});
};
const updateLinks = (fileMetadataTable, spaceChanges, server, parent)=>{
    `${server}`;
    const url = `${ensureTrailingSlash(server)}wiki/spaces/${parent.space}/pages/`;
    let collectedPass2Changes = [];
    const changeMapper = (changeToProcess)=>{
        const replacer = (match)=>{
            let documentFileName = "";
            if (isContentUpdate(changeToProcess) || isContentCreate(changeToProcess)) {
                documentFileName = changeToProcess.fileName ?? "";
            }
            const docFileNamePathList = documentFileName.split("/");
            let updated = match;
            const linkFileNameMatch = FILE_FINDER.exec(match);
            const linkFileName = linkFileNameMatch ? linkFileNameMatch[0] ?? "" : "";
            linkFileName.split("/");
            const linkFullFileName = `${linkFileName}.qmd`;
            let siteFilePath = linkFullFileName;
            const isAbsolute = siteFilePath.startsWith("/");
            if (!isAbsolute && docFileNamePathList.length > 1) {
                const relativePath = docFileNamePathList.slice(0, docFileNamePathList.length - 1).join("/");
                if (siteFilePath.startsWith("./")) {
                    siteFilePath = siteFilePath.replace("./", `${relativePath}/`);
                } else {
                    siteFilePath = `${relativePath}/${linkFullFileName}`;
                }
            }
            if (isAbsolute) {
                siteFilePath = siteFilePath.slice(1);
            }
            if (siteFilePath.endsWith("/index.qmd")) {
                const siteFilePathParent = siteFilePath.replace("/index.qmd", "");
                if (fileMetadataTable[siteFilePathParent]) {
                    siteFilePath = siteFilePathParent;
                }
            }
            if (!documentFileName.endsWith(".xml")) {
                const siteFilePathParent = `${documentFileName}/${linkFullFileName}`;
                if (fileMetadataTable[siteFilePathParent]) {
                    siteFilePath = siteFilePathParent;
                }
            }
            const sitePage = fileMetadataTable[siteFilePath] ?? null;
            if (sitePage) {
                updated = match.replace('href="', `href="${url}`);
                const pagePath = `${url}${sitePage.id}`;
                updated = updated.replace(linkFullFileName, pagePath);
            } else {
                if (!collectedPass2Changes.includes(changeToProcess)) {
                    collectedPass2Changes = [
                        ...collectedPass2Changes,
                        changeToProcess
                    ];
                }
            }
            return updated;
        };
        if (isContentUpdate(changeToProcess) || isContentCreate(changeToProcess)) {
            const valueToProcess = changeToProcess?.body?.storage?.value;
            if (valueToProcess) {
                const replacedLinks = valueToProcess.replaceAll(LINK_FINDER, replacer);
                changeToProcess.body.storage.value = replacedLinks;
            }
        }
        return changeToProcess;
    };
    const updatedChanges = spaceChanges.map(changeMapper);
    return {
        pass1Changes: updatedChanges,
        pass2Changes: collectedPass2Changes
    };
};
const convertForSecondPass = (fileMetadataTable, spaceChanges, server, parent)=>{
    const toUpdatesReducer = (accumulator, change)=>{
        if (isContentUpdate(change)) {
            accumulator = [
                ...accumulator,
                change
            ];
        }
        if (isContentCreate(change)) {
            const qmdFileName = replaceExtension(change.fileName ?? "", ".xml", ".qmd");
            const updateId = fileMetadataTable[qmdFileName]?.id;
            if (updateId) {
                const convertedUpdate = buildContentUpdate(updateId, change.title, change.body, change.fileName ?? "", "", ContentStatusEnum.current, PAGE_TYPE, null, change.ancestors);
                accumulator = [
                    ...accumulator,
                    convertedUpdate
                ];
            } else {
                trace2("update ID not found for", change.fileName);
            }
        }
        return accumulator;
    };
    const changesAsUpdates = spaceChanges.reduce(toUpdatesReducer, []);
    const updateLinkResults = updateLinks(fileMetadataTable, changesAsUpdates, server, parent);
    return updateLinkResults.pass1Changes;
};
const updateImagePaths = (body)=>{
    const replacer = (match)=>{
        let updated = match.replace(/^.*[\\\/]/, "");
        return updated;
    };
    const bodyValue = body?.storage?.value;
    if (!bodyValue) {
        return body;
    }
    findAttachments(bodyValue);
    const withReplacedImages = bodyValue.replaceAll(ATTACHMENT_FINDER, replacer);
    body.storage.value = withReplacedImages;
    return body;
};
const findAttachments = (bodyValue, publishFiles = [], filePathParam = "")=>{
    const filePath = pathWithForwardSlashes(filePathParam);
    const pathList = filePath.split("/");
    const parentPath = pathList.slice(0, pathList.length - 1).join("/");
    const imageFinderMatches = bodyValue.match(ATTACHMENT_FINDER);
    let uniqueFoundImages = [
        ...new Set(imageFinderMatches)
    ];
    if (publishFiles.length > 0) {
        uniqueFoundImages = uniqueFoundImages.map((assetFileName)=>{
            const assetInPublishFiles = publishFiles.find((assetPathParam)=>{
                const assetPath = pathWithForwardSlashes(assetPathParam);
                const toCheck = pathWithForwardSlashes(join2(parentPath, assetFileName));
                return assetPath === toCheck;
            });
            return assetInPublishFiles ?? assetFileName;
        });
    }
    return uniqueFoundImages ?? [];
};
const buildConfluenceAnchor = (id)=>`<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:local-id="a6aa6f25-0bee-4a7f-929b-71fcb7eba592" ac:macro-id="d2cb5be1217ae6e086bc60005e9d27b7"><ac:parameter ac:name="">${id}</ac:parameter></ac:structured-macro>`;
const footnoteTransform = (bodyValue)=>{
    const BACK_ANCHOR_FINDER = /<a href="#fn(\d)"/g;
    const ANCHOR_FINDER = /<a href="#fnref(\d)"/g;
    const CONFLUENCE_ANCHOR_FINDER = /ac:macro-id="d2cb5be1217ae6e086bc60005e9d27b7"><ac:parameter ac:name="">fn/g;
    if (bodyValue.search(CONFLUENCE_ANCHOR_FINDER) !== -1) {
        return bodyValue;
    }
    const replacer = (prefix)=>(match, p1)=>`${buildConfluenceAnchor(`${prefix}${p1}`)}${match}`;
    let replacedBody = bodyValue.replaceAll(BACK_ANCHOR_FINDER, replacer("fnref"));
    replacedBody = replacedBody.replaceAll(ANCHOR_FINDER, replacer("fn"));
    return replacedBody;
};
class ConfluenceClient {
    token_;
    constructor(token_){
        this.token_ = token_;
        this.get = (path)=>this.fetch("GET", path);
        this.delete = (path)=>this.fetch("DELETE", path);
        this.post = (path, body)=>this.fetch("POST", path, body);
        this.put = (path, body)=>this.fetch("PUT", path, body);
        this.putAttachment = (path, file, comment = "")=>this.fetchWithAttachment("PUT", path, file, comment);
        this.fetch = async (method, path, body)=>{
            const headers = {
                Accept: "application/json",
                ...[
                    "POST",
                    "PUT"
                ].includes(method) ? {
                    "Content-Type": "application/json"
                } : {},
                ...this.authorizationHeader()
            };
            const request = {
                method,
                headers,
                body
            };
            return this.handleResponse(await fetch(this.apiUrl(path), request));
        };
        this.fetchWithAttachment = async (method, path, file, comment = "")=>{
            const formData = new FormData();
            formData.append("file", file);
            formData.append("minorEdit", "true");
            formData.append("comment", comment);
            const headers = {
                ["X-Atlassian-Token"]: "nocheck",
                ...this.authorizationHeader()
            };
            const request = {
                method,
                headers,
                body: formData
            };
            return this.handleResponse(await fetch(this.apiUrl(path), request));
        };
        this.apiUrl = (path)=>`${ensureTrailingSlash(this.token_.server)}wiki/rest/api/${path}`;
    }
    getUser(expand = [
        "operations"
    ]) {
        return this.get(`user/current?expand=${expand}`);
    }
    getSpace(spaceId, expand = [
        "homepage"
    ]) {
        return this.get(`space/${spaceId}?expand=${expand}`);
    }
    getContent(id) {
        return this.get(`content/${id}`);
    }
    async getContentProperty(id) {
        const result1 = await this.get(`content/${id}/property`);
        return result1.results;
    }
    getDescendantsPage(id, start = 0, expand = [
        "metadata.properties",
        "ancestors"
    ]) {
        const url = `content/${id}/descendant/page?limit=${200}&start=${start}&expand=${expand}`;
        return this.get(url);
    }
    async isTitleUniqueInSpace(title, space, idToIgnore = "") {
        const result1 = await this.fetchMatchingTitlePages(title, space);
        if (result1.length === 1 && result1[0].id === idToIgnore) {
            return true;
        }
        return result1.length === 0;
    }
    async fetchMatchingTitlePages(title, space, isFuzzy = false) {
        const encodedTitle = encodeURIComponent(title);
        let cql = `title="${encodedTitle}"`;
        const CQL_CONTEXT = "%7B%22contentStatuses%22%3A%5B%22archived%22%2C%20%22current%22%2C%20%22draft%22%5D%7D";
        cql = `${cql}&spaces=${space.key}&cqlcontext=${CQL_CONTEXT}`;
        const result1 = await this.get(`content/search?cql=${cql}`);
        return result1?.results ?? [];
    }
    async canSetPermissions(parent, space, user) {
        let result1 = true;
        trace2("canSetPermissions check");
        trace2("localStorage.getItem(CAN_SET_PERMISSIONS_DISABLED)", localStorage.getItem(CAN_SET_PERMISSIONS_DISABLED));
        trace2("localStorage.getItem(CAN_SET_PERMISSIONS_ENABLED_CACHED)", localStorage.getItem(CAN_SET_PERMISSIONS_ENABLED_CACHED));
        const permissionsTestDisabled = localStorage.getItem(CAN_SET_PERMISSIONS_DISABLED) === "true" || localStorage.getItem(CAN_SET_PERMISSIONS_ENABLED_CACHED) === "true";
        trace2("permissionsTestDisabled", permissionsTestDisabled);
        if (permissionsTestDisabled) {
            return Promise.resolve(true);
        }
        const testContent = buildContentCreate(`quarto-permission-test-${globalThis.crypto.randomUUID()}`, space, {
            storage: {
                value: "",
                representation: "storage"
            }
        }, "permisson-test");
        const testContentCreated = await this.createContent(user, testContent);
        const testContentId = testContentCreated.id ?? "";
        try {
            await this.put(`content/${testContentId}/restriction/byOperation/update/user?accountId=${user.accountId}`);
        } catch (error) {
            trace2("lockDownResult Error", error);
            if (error?.status === 403) {
                result1 = false;
            }
        }
        const contentDelete = {
            id: testContentId,
            contentChangeType: ContentChangeType.delete
        };
        let attemptArchive = false;
        try {
            await this.deleteContent(contentDelete);
        } catch (error) {
            trace2("delete canSetPermissions Test Error", error);
            if (error?.status === 403) {
                attemptArchive = true;
            }
        }
        try {
            await this.archiveContent(contentDelete);
        } catch (error) {
            trace2("archive canSetPermissions Test Error", error);
        }
        if (attemptArchive) {
            trace2("Disabling Permissions Test: confluenceCanSetPermissionsDisabled", "true");
            localStorage.setItem(CAN_SET_PERMISSIONS_DISABLED, "true");
        }
        return result1;
    }
    async lockDownPermissions(contentId, user) {
        try {
            return await this.put(`content/${contentId}/restriction/byOperation/update/user?accountId=${user.accountId}`);
        } catch (error) {
            trace2("lockDownResult Error", error);
        }
    }
    async createContent(user, content, metadata = V2EDITOR_METADATA) {
        const toCreate = {
            ...content,
            ...metadata
        };
        trace2("to create", toCreate);
        trace2("createContent body", content.body.storage.value);
        const createBody = JSON.stringify(toCreate);
        const result1 = await this.post("content", createBody);
        await this.lockDownPermissions(result1.id ?? "", user);
        return result1;
    }
    async updateContent(user, content, metadata = V2EDITOR_METADATA) {
        const toUpdate = {
            ...content,
            ...metadata
        };
        const result1 = await this.put(`content/${content.id}`, JSON.stringify(toUpdate));
        await this.lockDownPermissions(content.id ?? "", user);
        return result1;
    }
    createContentProperty(id, content) {
        return this.post(`content/${id}/property`, JSON.stringify(content));
    }
    deleteContent(content) {
        trace2("deleteContent", content);
        return this.delete(`content/${content.id}`);
    }
    archiveContent(content) {
        trace2("archiveContent", content);
        const toArchive = {
            pages: [
                {
                    id: content.id
                }
            ]
        };
        return this.post(`content/archive`, JSON.stringify(toArchive));
    }
    async getAttachments(id) {
        const wrappedResult = await this.get(`content/${id}/child/attachment`);
        const result1 = wrappedResult?.results ?? [];
        return result1;
    }
    async createOrUpdateAttachment(parentId, file, comment = "") {
        trace2("createOrUpdateAttachment", {
            file,
            parentId
        }, LogPrefix.ATTACHMENT);
        const wrappedResult = await this.putAttachment(`content/${parentId}/child/attachment`, file, comment);
        trace2("createOrUpdateAttachment", wrappedResult, LogPrefix.ATTACHMENT);
        const result1 = wrappedResult.results[0] ?? null;
        return result1;
    }
    get;
    delete;
    post;
    put;
    putAttachment;
    fetch;
    fetchWithAttachment;
    apiUrl;
    authorizationHeader() {
        const auth = encodeBase64(this.token_.name + ":" + this.token_.token);
        return {
            Authorization: `Basic ${auth}`
        };
    }
    handleResponse(response) {
        if (response.ok) {
            if (response.body) {
                return response.json();
            } else {
                return response;
            }
        } else if (response.status === 403) {
            throw new ApiError1(response.status, response.statusText);
        } else if (response.status !== 200) {
            logError1("response.status !== 200", response);
            throw new ApiError1(response.status, response.statusText);
        } else {
            logError1("handleResponse", response);
            throw new Error(`${response.status} - ${response.statusText}`);
        }
    }
}
const verifyWithSpinner = async (verifyCommand, message = "Verifying...")=>{
    return await withSpinner({
        message
    }, verifyCommand);
};
const verifyAccountToken = async (accountToken)=>{
    try {
        const client = new ConfluenceClient(accountToken);
        await client.getUser();
    } catch (error) {
        throw new Error(`Unable to sign into Confluence account: ${getMessageFromAPIError(error)}`);
    }
};
const verifyLocation = async (locationURL)=>{
    return await verifyWithSpinner(()=>verifyLocationExists(locationURL));
};
const verifyLocationExists = async (server)=>{
    try {
        const result1 = await fetch(server);
        if (!result1.ok) {
            throw new Error("");
        }
    } catch (error) {
        trace2("server doesnt exist", error);
        throw new Error(`${server} doesn't exist`);
    }
};
const verifyConfluenceParent = async (parentUrl, parent)=>{
    if (parent.space.length === 0) {
        throw new Error("Invalid Confluence parent URL: " + parentUrl);
    }
    await verifyLocation(parentUrl);
};
const verifyOrWarnManagePermissions = async (client, space, parent, user)=>{
    const canManagePermissions = await client.canSetPermissions(parent, space, user);
    if (canManagePermissions) {
        localStorage.setItem(CAN_SET_PERMISSIONS_ENABLED_CACHED, "true");
        trace2("Caching permission check success");
    } else {
        const confirmed = await Confirm.prompt("We've detected that your account is not able to manage the permissions for this destination.\n\nPublished pages will be directly editable within the Confluence web editor.\n\nThis means that if you republish the page from Quarto, you may be overwriting the web edits.\nWe recommend that you establish a clear policy about how this published page will be revised.\n\nAre you sure you want to continue?");
        if (!confirmed) {
            throw new Error("");
        }
    }
};
const CONFLUENCE_ID = "confluence";
const getAccountTokens = ()=>{
    const getConfluenceEnvironmentAccount = ()=>{
        const server = Deno.env.get("CONFLUENCE_DOMAIN");
        const name = Deno.env.get("CONFLUENCE_USER_EMAIL");
        const token = Deno.env.get("CONFLUENCE_AUTH_TOKEN");
        if (server && name && token) {
            return {
                type: AccountTokenType.Environment,
                name,
                server: transformAtlassianDomain(server),
                token
            };
        }
    };
    const readConfluenceAccessTokens = ()=>{
        const result1 = readAccessTokens(CONFLUENCE_ID) ?? [];
        return result1;
    };
    let accounts = [];
    const envAccount = getConfluenceEnvironmentAccount();
    if (envAccount) {
        accounts = [
            ...accounts,
            envAccount
        ];
    }
    const tempStoredAccessTokens = readConfluenceAccessTokens();
    accounts = [
        ...accounts,
        ...tempStoredAccessTokens
    ];
    return Promise.resolve(accounts);
};
const removeToken5 = (token)=>{
    const existingTokens = readAccessTokens(CONFLUENCE_ID) ?? [];
    const toWrite = existingTokens.filter((accessToken)=>tokenFilterOut(accessToken, token));
    writeAccessTokens(CONFLUENCE_ID, toWrite);
};
const promptAndAuthorizeToken = async ()=>{
    const server = await Input.prompt({
        indent: "",
        message: "Confluence Domain:",
        hint: "e.g. https://mydomain.atlassian.net/",
        validate: validateServer,
        transform: transformAtlassianDomain
    });
    await verifyLocation(server);
    const name = await Input.prompt({
        indent: "",
        message: `Confluence Account Email:`,
        validate: validateEmail
    });
    const token = await Secret.prompt({
        indent: "",
        message: "Confluence API Token:",
        hint: "Create an API token at https://id.atlassian.com/manage/api-tokens",
        validate: validateToken
    });
    const accountToken = {
        type: AccountTokenType.Authorized,
        name,
        server,
        token
    };
    await withSpinner({
        message: "Verifying account..."
    }, ()=>verifyAccountToken(accountToken));
    writeAccessToken(CONFLUENCE_ID, accountToken, writeTokenComparator);
    return Promise.resolve(accountToken);
};
const promptForParentURL = async ()=>{
    return await Input.prompt({
        indent: "",
        message: `Space or Parent Page URL:`,
        hint: "Browse in Confluence to the space or parent, then copy the URL",
        validate: validateParentURL
    });
};
const resolveTarget5 = async (accountToken, target)=>{
    return Promise.resolve(target);
};
const loadDocument = (baseDirectory, rootFile)=>{
    const documentValue = Deno.readTextFileSync(join2(baseDirectory, rootFile));
    const body = wrapBodyForConfluence(documentValue);
    return body;
};
const renderDocument = async (render)=>{
    const flags = {
        to: "confluence-publish"
    };
    return await render(flags);
};
const renderSite = async (render)=>{
    const flags = {
        to: "confluence-publish"
    };
    const renderResult = await render(flags);
    return renderResult;
};
async function publish5(account, type, _input, title, _slug, render, _options, publishRecord) {
    trace2("publish", {
        account,
        type,
        _input,
        title,
        _slug,
        _options,
        publishRecord
    });
    const client = new ConfluenceClient(account);
    const user = await client.getUser();
    let parentUrl = publishRecord?.url ?? await promptForParentURL();
    const parent = confluenceParentFromString(parentUrl);
    const server = account?.server ?? "";
    await verifyConfluenceParent(parentUrl, parent);
    const space = await client.getSpace(parent.space);
    trace2("publish", {
        parent,
        server,
        id: space.id,
        key: space.key
    });
    await verifyOrWarnManagePermissions(client, space, parent, user);
    const uniquifyTitle = async (title, idToIgnore = "")=>{
        trace2("uniquifyTitle", title);
        const titleIsUnique = await client.isTitleUniqueInSpace(title, space, idToIgnore);
        if (titleIsUnique) {
            return title;
        }
        const uuid = globalThis.crypto.randomUUID();
        const shortUUID = uuid.split("-")[0] ?? uuid;
        const uuidTitle = `${title} ${shortUUID}`;
        return uuidTitle;
    };
    const fetchExistingSite = async (parentId)=>{
        let descendants = [];
        let start = 0;
        for(let i1 = 0; i1 < 100; i1++){
            const result1 = await client.getDescendantsPage(parentId, start);
            if (result1.results.length === 0) {
                break;
            }
            descendants = [
                ...descendants,
                ...result1.results
            ];
            start = start + DESCENDANT_PAGE_SIZE;
        }
        trace2("descendants.length", descendants);
        const contentProperties = await Promise.all(descendants.map((page)=>client.getContentProperty(page.id ?? "")));
        const sitePageList = mergeSitePages(descendants, contentProperties);
        return sitePageList;
    };
    const uploadAttachments = (baseDirectory, attachmentsToUpload, parentId, filePath, existingAttachments = [])=>{
        const uploadAttachment = async (attachmentPath)=>{
            let fileBuffer;
            let fileHash;
            const path = join2(baseDirectory, attachmentPath);
            trace2("uploadAttachment", {
                baseDirectory,
                attachmentPath,
                attachmentsToUpload,
                parentId,
                existingAttachments,
                path
            }, LogPrefix.ATTACHMENT);
            try {
                fileBuffer = await Deno.readFile(path);
                fileHash = md5Hash(fileBuffer.toString());
            } catch (error) {
                logError1(`${path} not found`, error);
                return null;
            }
            const fileName = pathWithForwardSlashes(attachmentPath);
            const existingDuplicateAttachment = existingAttachments.find((attachment)=>{
                return attachment?.metadata?.comment === fileHash;
            });
            if (existingDuplicateAttachment) {
                trace2("existing duplicate attachment found", existingDuplicateAttachment.title, LogPrefix.ATTACHMENT);
                return existingDuplicateAttachment;
            }
            const file = new File([
                fileBuffer
            ], fileName);
            const attachment = await client.createOrUpdateAttachment(parentId, file, fileHash);
            trace2("attachment", attachment, LogPrefix.ATTACHMENT);
            return attachment;
        };
        return attachmentsToUpload.map(uploadAttachment);
    };
    const updateContent = async (user, publishFiles, id, body, titleToUpdate = title, fileName = "", uploadFileAttachments = true)=>{
        const previousPage = await client.getContent(id);
        const attachmentsToUpload = findAttachments(body.storage.value, publishFiles.files, fileName);
        let uniqueTitle = titleToUpdate;
        if (previousPage.title !== titleToUpdate) {
            uniqueTitle = await uniquifyTitle(titleToUpdate, id);
        }
        trace2("attachmentsToUpload", attachmentsToUpload, LogPrefix.ATTACHMENT);
        const updatedBody = updateImagePaths(body);
        updatedBody.storage.value = footnoteTransform(updatedBody.storage.value);
        const toUpdate = {
            contentChangeType: ContentChangeType.update,
            id,
            version: getNextVersion(previousPage),
            title: uniqueTitle,
            type: PAGE_TYPE,
            status: ContentStatusEnum.current,
            ancestors: null,
            body: updatedBody
        };
        trace2("updateContent", toUpdate);
        trace2("updateContent body", toUpdate?.body?.storage?.value);
        const updatedContent = await client.updateContent(user, toUpdate);
        if (toUpdate.id && uploadFileAttachments) {
            const existingAttachments = await client.getAttachments(toUpdate.id);
            trace2("attachments", {
                existingAttachments,
                attachmentsToUpload
            }, LogPrefix.ATTACHMENT);
            const uploadAttachmentsResult = await Promise.all(uploadAttachments(publishFiles.baseDir, attachmentsToUpload, toUpdate.id, fileName, existingAttachments));
            trace2("uploadAttachmentsResult", uploadAttachmentsResult, LogPrefix.ATTACHMENT);
        }
        return {
            content: updatedContent,
            hasAttachments: attachmentsToUpload.length > 0
        };
    };
    const createSiteParent = async (title, body)=>{
        let ancestors = [];
        if (parent?.parent) {
            ancestors = [
                {
                    id: parent.parent
                }
            ];
        } else if (space.homepage?.id) {
            ancestors = [
                {
                    id: space.homepage?.id
                }
            ];
        }
        const toCreate = {
            contentChangeType: ContentChangeType.create,
            title,
            type: PAGE_TYPE,
            space,
            status: ContentStatusEnum.current,
            ancestors,
            body
        };
        const createdContent = await client.createContent(user, toCreate);
        return createdContent;
    };
    const checkToCreateSiteParent = async (parentId = "")=>{
        let isQuartoSiteParent = false;
        const existingSiteParent = await client.getContent(parentId);
        if (existingSiteParent?.id) {
            const siteParentContentProperties = await client.getContentProperty(existingSiteParent.id ?? "");
            isQuartoSiteParent = siteParentContentProperties.find((property)=>property.key === ContentPropertyKey.isQuartoSiteParent) !== undefined;
        }
        if (!isQuartoSiteParent) {
            const body = {
                storage: {
                    value: "",
                    representation: ContentBodyRepresentation.storage
                }
            };
            const siteParentTitle = await uniquifyTitle(title);
            const siteParent = await createSiteParent(siteParentTitle, body);
            const newSiteParentId = siteParent.id ?? "";
            await client.createContentProperty(newSiteParentId, {
                key: ContentPropertyKey.isQuartoSiteParent,
                value: true
            });
            parentId = newSiteParentId;
        }
        return parentId;
    };
    const createContent = async (publishFiles, body, titleToCreate = title, createParent = parent, fileNameParam = "")=>{
        const createTitle = await uniquifyTitle(titleToCreate);
        const fileName = pathWithForwardSlashes(fileNameParam);
        const attachmentsToUpload = findAttachments(body.storage.value, publishFiles.files, fileName);
        trace2("attachmentsToUpload", attachmentsToUpload, LogPrefix.ATTACHMENT);
        const updatedBody = updateImagePaths(body);
        updatedBody.storage.value = footnoteTransform(updatedBody.storage.value);
        const toCreate = {
            contentChangeType: ContentChangeType.create,
            title: createTitle,
            type: PAGE_TYPE,
            space,
            status: ContentStatusEnum.current,
            ancestors: createParent?.parent ? [
                {
                    id: createParent.parent
                }
            ] : null,
            body: updatedBody
        };
        trace2("createContent", {
            publishFiles,
            toCreate
        });
        const createdContent = await client.createContent(user, toCreate);
        if (createdContent.id) {
            const uploadAttachmentsResult = await Promise.all(uploadAttachments(publishFiles.baseDir, attachmentsToUpload, createdContent.id, fileName));
            trace2("uploadAttachmentsResult", uploadAttachmentsResult, LogPrefix.ATTACHMENT);
        }
        return {
            content: createdContent,
            hasAttachments: attachmentsToUpload.length > 0
        };
    };
    const publishDocument = async ()=>{
        const publishFiles = await renderDocument(render);
        const body = loadDocument(publishFiles.baseDir, publishFiles.rootFile);
        trace2("publishDocument", {
            publishFiles,
            body
        }, LogPrefix.RENDER);
        let publishResult;
        let message = "";
        let doOperation;
        if (publishRecord) {
            message = `Updating content at ${publishRecord.url}...`;
            doOperation = async ()=>{
                const result1 = await updateContent(user, publishFiles, publishRecord.id, body);
                publishResult = result1;
            };
        } else {
            message = `Creating content in space ${parent.space}...`;
            doOperation = async ()=>{
                const result1 = await createContent(publishFiles, body);
                publishResult = result1;
            };
        }
        try {
            await doWithSpinner(message, doOperation);
            return [
                buildPublishRecordForContent(server, publishResult?.content),
                !!publishResult?.hasAttachments
            ];
        } catch (error) {
            trace2("Error Performing Operation", error);
            trace2("Value to Update", body?.storage?.value);
            throw error;
        }
    };
    const publishSite = async ()=>{
        let parentId = parent?.parent ?? space.homepage.id ?? "";
        parentId = await checkToCreateSiteParent(parentId);
        const siteParent = {
            space: parent.space,
            parent: parentId
        };
        let existingSite = await fetchExistingSite(parentId);
        trace2("existingSite", existingSite);
        const publishFiles = await renderSite(render);
        const metadataByInput = publishFiles.metadataByInput ?? {};
        trace2("metadataByInput", metadataByInput);
        trace2("publishSite", {
            parentId,
            publishFiles
        });
        const filteredFiles = filterFilesForUpdate(publishFiles.files);
        trace2("filteredFiles", filteredFiles);
        const assembleSiteFileMetadata = async (fileName)=>{
            const fileToContentBody = async (fileName)=>{
                return loadDocument(publishFiles.baseDir, fileName);
            };
            const originalTitle = getTitle(fileName, metadataByInput);
            const title = originalTitle;
            return await {
                fileName,
                title,
                originalTitle,
                contentBody: await fileToContentBody(fileName)
            };
        };
        const fileMetadata = await Promise.all(filteredFiles.map(assembleSiteFileMetadata));
        trace2("fileMetadata", fileMetadata);
        let metadataByFilename = buildFileToMetaTable(existingSite);
        trace2("metadataByFilename", metadataByFilename);
        let changeList = buildSpaceChanges(fileMetadata, siteParent, space, existingSite);
        changeList = flattenIndexes(changeList, metadataByFilename, parentId);
        const { pass1Changes, pass2Changes } = updateLinks(metadataByFilename, changeList, server, siteParent);
        changeList = pass1Changes;
        trace2("changelist Pass 1", changeList);
        let pathsToId = {};
        const handleChangeError = (label, currentChange, error)=>{
            if (isContentUpdate(currentChange) || isContentCreate(currentChange)) {
                trace2("currentChange.fileName", currentChange.fileName);
                trace2("Value to Update", currentChange.body.storage.value);
            }
            if (false) {
                throw error;
            }
        };
        let hasAttachments = false;
        const doChange = async (change, uploadFileAttachments = true)=>{
            if (isContentCreate(change)) {
                if (change.fileName === "sitemap.xml") {
                    trace2("sitemap.xml skipped", change);
                    return;
                }
                let ancestorId = (change?.ancestors && change?.ancestors[0]?.id) ?? null;
                if (ancestorId && pathsToId[ancestorId]) {
                    ancestorId = pathsToId[ancestorId];
                }
                const ancestorParent = {
                    space: parent.space,
                    parent: ancestorId ?? siteParent.parent
                };
                const universalPath = pathWithForwardSlashes(change.fileName ?? "");
                const result1 = await createContent(publishFiles, change.body, change.title ?? "", ancestorParent, universalPath);
                if (universalPath) {
                    pathsToId[universalPath] = result1.content.id ?? "";
                }
                await client.createContentProperty(result1.content.id ?? "", {
                    key: ContentPropertyKey.fileName,
                    value: change.fileName
                });
                hasAttachments = hasAttachments || result1.hasAttachments;
                return result1;
            } else if (isContentUpdate(change)) {
                const update = change;
                const result1 = await updateContent(user, publishFiles, update.id ?? "", update.body, update.title ?? "", update.fileName ?? "", uploadFileAttachments);
                hasAttachments = hasAttachments || result1.hasAttachments;
                return result1;
            } else if (isContentDelete(change)) {
                if (false) {
                    console.warn("DELETE DISABELD");
                    return null;
                }
                const result1 = await client.deleteContent(change);
                await sleep(1000);
                return {
                    content: result1,
                    hasAttachments: false
                };
            } else {
                console.error("Space Change not defined");
                return null;
            }
        };
        let pass1Count = 0;
        for (let currentChange of changeList){
            try {
                pass1Count = pass1Count + 1;
                const doOperation = async ()=>await doChange(currentChange);
                await doWithSpinner(`Site Updates [${pass1Count}/${changeList.length}]`, doOperation);
            } catch (error) {
                handleChangeError("Error Performing Change Pass 1", currentChange, error);
            }
        }
        if (pass2Changes.length) {
            trace2("changelist Pass 2", pass2Changes);
            existingSite = await fetchExistingSite(parentId);
            metadataByFilename = buildFileToMetaTable(existingSite);
            const linkUpdateChanges = convertForSecondPass(metadataByFilename, pass2Changes, server, parent);
            let pass2Count = 0;
            for (let currentChange of linkUpdateChanges){
                try {
                    pass2Count = pass2Count + 1;
                    const doOperation = async ()=>await doChange(currentChange, false);
                    await doWithSpinner(`Updating Links [${pass2Count}/${linkUpdateChanges.length}]`, doOperation);
                } catch (error) {
                    handleChangeError("Error Performing Change Pass 2", currentChange, error);
                }
            }
        }
        const parentPage = await client.getContent(parentId);
        return [
            buildPublishRecordForContent(server, parentPage),
            hasAttachments
        ];
    };
    if (type === PublishTypeEnum.document) {
        const [publishResult, hasAttachments] = await publishDocument();
        if (hasAttachments) {
            info("\nNote: The published content includes attachments or images. You may see a placeholder for a few moments while Confluence processes the image or atachment.\n");
        }
        return publishResult;
    } else {
        const [publishResult, hasAttachments] = await publishSite();
        if (hasAttachments) {
            info("\nNote: The published content includes attachments or images. You may see a placeholder for a few moments while Confluence processes the image or atachment.\n");
        }
        return publishResult;
    }
}
const confluenceProvider = {
    name: CONFLUENCE_ID,
    description: "Confluence",
    hidden: false,
    requiresServer: true,
    requiresRender: true,
    accountTokens: getAccountTokens,
    authorizeToken: promptAndAuthorizeToken,
    removeToken: removeToken5,
    resolveTarget: resolveTarget5,
    publish: publish5,
    isUnauthorized: isUnauthorized5,
    isNotFound: isNotFound5
};
const kHuggingFace = "huggingface";
const kHuggingFaceDescription = "Hugging Face Spaces";
const huggingfaceProvider = {
    name: kHuggingFace,
    description: kHuggingFaceDescription,
    requiresServer: false,
    listOriginOnly: false,
    accountTokens: ()=>Promise.resolve([
            anonymousAccount()
        ]),
    authorizeToken: authorizeToken5,
    removeToken: ()=>{},
    publishRecord: publishRecord1,
    resolveTarget: (_account, target)=>Promise.resolve(target),
    publish: publish6,
    isUnauthorized: ()=>false,
    isNotFound: ()=>false,
    resolveProjectPath: (path)=>join2(path, "src")
};
async function authorizeToken5(options) {
    const ghContext = await gitHubContextForPublish(options.input);
    const provider = "Hugging Face Spaces";
    verifyContext(ghContext, provider);
    if (!ghContext.originUrl.match(/^https:\/\/(.*:.*@)?huggingface.co\/spaces\//)) {
        throwUnableToPublish("the git repository does not appear to have a Hugging Face Space origin", provider);
    }
    return Promise.resolve(anonymousAccount());
}
async function publishRecord1(input) {
    const ghContext = await gitHubContextForPublish(input);
    if (ghContext.ghPagesRemote) {
        return {
            id: kHuggingFace,
            url: ghContext.siteUrl || ghContext.originUrl
        };
    }
}
async function publish6(_account, _type, input, _title, _slug, _render, options, _target) {
    input = Deno.statSync(input).isDirectory ? input : dirname2(input);
    const version = await gitVersion();
    if (version.compare("2.17.0") < 0) {
        throw new Error("git version 2.17.0 or higher is required to publish to GitHub Pages");
    }
    const ghContext = await gitHubContextForPublish(options.input);
    verifyContext(ghContext, "Hugging Face Spaces");
    if (!ghContext.originUrl.match(/^https:\/\/.*:.*@huggingface.co\/spaces\//)) {
        const previousRemotePath = ghContext.originUrl.match(/.*huggingface.co(\/spaces\/.*)/);
        assert2(previousRemotePath);
        info(yellow([
            "The current git repository needs to be reconfigured to allow `quarto publish`",
            "to publish to Hugging Face Spaces. Please enter your username and authentication token.",
            "Refer to https://huggingface.co/blog/password-git-deprecation#switching-to-personal-access-token",
            "for more information on how to obtain a personal access token."
        ].join("\n")));
        const username = await Input.prompt({
            indent: "",
            message: "Hugging Face username"
        });
        const token = await Secret.prompt({
            indent: "",
            message: "Hugging Face authentication token:",
            hint: "Create a token at https://huggingface.co/settings/tokens"
        });
        await gitCmds(input, [
            [
                "remote",
                "set-url",
                "origin",
                `https://${username}:${token}@huggingface.co${previousRemotePath[1]}`
            ]
        ]);
    }
    await gitCmds(input, [
        [
            "stash"
        ],
        [
            "fetch",
            "origin",
            "main"
        ]
    ]);
    try {
        await gitCmds(input, [
            [
                "merge",
                "origin/main"
            ]
        ]);
    } catch (_e) {
        info(yellow([
            "Could not merge origin/main. This is likely because of git conflicts.",
            "Please resolve those manually and run `quarto publish` again."
        ].join("\n")));
        return Promise.resolve([
            undefined,
            undefined
        ]);
    }
    try {
        await gitCmds(input, [
            [
                "stash",
                "pop"
            ]
        ]);
    } catch (_e) {
        info(yellow([
            "Could not pop git stash.",
            "This is likely because there are no changes to push to the repository."
        ].join("\n")));
        return Promise.resolve([
            undefined,
            undefined
        ]);
    }
    await gitCmds(input, [
        [
            "add",
            "-Af",
            "."
        ],
        [
            "commit",
            "--allow-empty",
            "-m",
            "commit from `quarto publish`"
        ],
        [
            "push",
            "origin",
            "main"
        ]
    ]);
    info(yellow("NOTE: Hugging Face Space sites build the content remotely and use caching.\n" + "You will need to wait a moment for Hugging Face to rebuild your site, and\n" + "then click the refresh button within your web browser to see changes after deployment.\n\n" + "Specifically, you need to:\n" + "- wait for your space's status to go from 'Building' to 'Running'\n" + "  (this is visible in the status bar above the space)\n" + "- force-reload the web page by holding Shift and hitting the reload button in your browser.\n"));
    await new Promise((resolve)=>setTimeout(resolve, 3000));
    return Promise.resolve([
        undefined,
        new URL(ghContext.originUrl)
    ]);
}
function accountTokenText(token) {
    return token.name + (token.server ? ` (${token.server})` : "");
}
const kPublishProviders = [
    quartoPubProvider,
    ghpagesProvider,
    rsconnectProvider,
    positCloudProvider,
    netlifyProvider,
    confluenceProvider,
    huggingfaceProvider
];
function publishProviders() {
    return kPublishProviders.slice();
}
function findProvider(name) {
    return kPublishProviders.find((provider)=>provider.name === name);
}
function readPublishDeployments(source) {
    const [deployDir, deploySource] = resolveDeploymentSource(source);
    const deplomentsFile = publishDeploymentsFile(deployDir);
    if (deplomentsFile) {
        const deployments = readYaml(deplomentsFile);
        if (deployments) {
            if (isDeploymentsArray(deployments)) {
                const sourceDeployments = deployments.find((deployment)=>deployment.source === basename2(deploySource));
                if (sourceDeployments) {
                    delete sourceDeployments.source;
                    Object.values(sourceDeployments).forEach((deployment)=>{
                        if (Array.isArray(deployment)) {
                            deployment = deployment.map((d)=>{
                                d.code = !!d.code;
                                return d;
                            });
                        }
                    });
                    return {
                        dir: deployDir,
                        source: deploySource,
                        records: sourceDeployments
                    };
                }
            } else {
                warn("Unexpcted format for _publish.yml file (not reading publish history)");
            }
        }
    }
    return {
        dir: deployDir,
        source: deploySource,
        records: {}
    };
}
function writePublishDeployment(source, provider, account, publish) {
    publish = cloneDeep1(publish);
    if (publish.code === false) {
        delete publish.code;
    }
    let indent = 2;
    const [deployDir, deploySource] = resolveDeploymentSource(source);
    const deploymentsFile = publishDeploymentsFile(deployDir);
    if (deploymentsFile) {
        const deploymentsFileYaml = Deno.readTextFileSync(deploymentsFile);
        indent = detectIndentLevel(deploymentsFileYaml);
        const deployments = readYamlFromString(deploymentsFileYaml);
        if (isDeploymentsArray(deployments)) {
            const docDeploymentsIdx = deployments.findIndex((deployment)=>deployment.source === basename2(deploySource));
            if (docDeploymentsIdx !== -1) {
                const docDeployments = deployments[docDeploymentsIdx];
                if (docDeployments[provider]) {
                    const deploymentIdx = docDeployments[provider].findIndex((published)=>published.id === publish.id);
                    if (deploymentIdx !== -1) {
                        docDeployments[provider][deploymentIdx] = publish;
                    } else {
                        docDeployments[provider].push(publish);
                    }
                } else {
                    docDeployments[provider] = [
                        publish
                    ];
                }
            } else {
                const deployment = {
                    source: deploySource,
                    [provider]: [
                        publish
                    ]
                };
                deployments.push(deployment);
            }
            Deno.writeTextFileSync(deploymentsFile, stringifyPublishConfig(deployments, indent));
        } else {
            warn("Unexpcted format for _publish.yml file (not writing to publish history)");
        }
    } else {
        Deno.writeTextFileSync(join2(deployDir, kDefaultPublishDeploymentsFile), stringifyPublishConfig([
            {
                source: deploySource,
                [provider]: [
                    publish
                ]
            }
        ], indent));
    }
    writePublishRecord(source, provider, account, publish);
}
function resolveDeploymentSource(source) {
    const deployDir = Deno.statSync(source).isDirectory ? source : dirname2(source);
    const deploySource = Deno.statSync(source).isDirectory ? "project" : basename2(source);
    return [
        deployDir,
        deploySource
    ];
}
function readProjectPublishDeployments(project) {
    return readPublishDeployments(project.dir);
}
function writeProjectPublishDeployment(project, provider, account, publish) {
    writePublishDeployment(project.dir, provider, account, publish);
}
function isDeploymentsArray(obj) {
    return Array.isArray(obj) && typeof obj[0].source === "string";
}
function stringifyPublishConfig(config, indent) {
    return stringify(config, {
        indent,
        lineWidth: -1,
        sortKeys: false,
        skipInvalid: true
    });
}
function detectIndentLevel(yaml) {
    const spaceMatch = yaml.match(/\n(\s+)/);
    return spaceMatch ? spaceMatch[1].length : 2;
}
const kDefaultPublishDeploymentsFile = "_publish.yml";
function publishDeploymentsFile(dir) {
    return [
        kDefaultPublishDeploymentsFile,
        "_publish.yaml"
    ].map((file)=>join2(dir, file)).find(existsSync1);
}
async function resolveDeployment(options, providerFilter) {
    const deployments = await publishDeployments(options, providerFilter);
    if (deployments && deployments.length > 0) {
        const siteId = options.id;
        if (siteId) {
            const deployment = deployments.find((deployment)=>{
                return deployment.target.id === siteId;
            });
            if (deployment) {
                if (options.prompt) {
                    const confirmed = await Confirm.prompt({
                        indent: "",
                        message: `Update site at ${deployment.target.url}?`,
                        default: true
                    });
                    if (!confirmed) {
                        throw new Error();
                    }
                }
                return deployment;
            } else {
                throw new Error(`No previous publish with site-id ${siteId} was found`);
            }
        } else if (options.prompt) {
            const confirmPrompt = async (hint)=>{
                return await Confirm.prompt({
                    indent: "",
                    message: `Update site at ${deployments[0].target.url}?`,
                    default: true,
                    hint
                });
            };
            if (deployments.length === 1 && deployments[0].provider.publishRecord && providerFilter === deployments[0].provider.name) {
                const confirmed = await confirmPrompt();
                if (confirmed) {
                    return deployments[0];
                } else {
                    throw new Error();
                }
            } else {
                return await chooseDeployment(deployments);
            }
        } else if (deployments.length === 1) {
            return deployments[0];
        } else {
            throw new Error(`Multiple previous publishes exist (specify one with --id when using --no-prompt)`);
        }
    } else if (!options.prompt) {
        if (providerFilter === kGhpages) {
            throw new Error(`Unable to publish to GitHub Pages (the remote origin does not have a branch named "gh-pages". Use first \`quarto publish gh-pages\` locally to initialize the remote repository for publishing.)`);
        } else {
            throw new Error(`No _publish.yml file available (_publish.yml specifying a destination required for non-interactive publish)`);
        }
    }
}
async function publishDeployments(options, providerFilter) {
    const deployments = [];
    for (const provider of publishProviders()){
        if ((!providerFilter || providerFilter === provider.name) && provider.publishRecord) {
            const record = await provider.publishRecord(options.input);
            if (record) {
                deployments.push({
                    provider,
                    target: record
                });
            }
        }
    }
    const config = typeof options.input === "string" ? readPublishDeployments(options.input) : readProjectPublishDeployments(options.input);
    for (const providerName of Object.keys(config.records)){
        if (providerFilter && providerName !== providerFilter) {
            continue;
        }
        const provider = findProvider(providerName);
        if (provider) {
            for (const record of config.records[providerName]){
                let account;
                const publishedToAccounts = await readAccountsPublishedTo(options.input, provider, record);
                if (publishedToAccounts.length === 1) {
                    account = publishedToAccounts[0];
                }
                if (account) {
                    const target = await resolveDeploymentTarget(provider, account, record);
                    if (target) {
                        deployments.push({
                            provider,
                            target,
                            account
                        });
                    }
                } else {
                    deployments.push({
                        provider,
                        target: record
                    });
                }
            }
        } else {
            warn(`Unkonwn provider ${providerName}`);
        }
    }
    return deployments;
}
async function chooseDeployment(depoyments) {
    depoyments = depoyments.filter((deployment)=>!!deployment.target.url);
    const originCounts = depoyments.reduce((origins, deployment)=>{
        try {
            const originUrl = new URL(deployment.target.url).origin;
            const count = origins.get(originUrl) || 0;
            origins.set(originUrl, count + 1);
        } catch  {}
        return origins;
    }, new Map());
    const kOther = "other";
    const options = depoyments.map((deployment)=>{
        let url = deployment.target.url;
        try {
            const targetOrigin = new URL(deployment.target.url).origin;
            if (originCounts.get(targetOrigin) === 1 && (deployment.provider?.listOriginOnly ?? false)) {
                url = targetOrigin;
            }
        } catch  {}
        return {
            name: `${url} (${deployment.provider.description}${deployment.account ? " - " + deployment.account.name : ""})`,
            value: publishRecordIdentifier(deployment.target, deployment.account)
        };
    });
    options.push({
        name: "Add a new destination...",
        value: kOther
    });
    const confirm = await prompt([
        {
            name: "destination",
            indent: "",
            message: "Publish update to:",
            options,
            type: Select
        }
    ]);
    if (confirm.destination !== kOther) {
        return depoyments.find((deployment)=>publishRecordIdentifier(deployment.target, deployment.account) === confirm.destination);
    } else {
        return undefined;
    }
}
async function resolveDeploymentTarget(provider, account, record) {
    try {
        return await provider.resolveTarget(account, record);
    } catch (err) {
        if (provider.isNotFound(err)) {
            warn(`${record.url} not found (you may need to remove it from the publish configuration)`);
            return undefined;
        } else if (!provider.isUnauthorized(err)) {
            throw err;
        }
    }
    return record;
}
async function resolveAccount(provider, prompt, options, hintAccount, target) {
    if (options.token) {
        if (provider.requiresServer && !options.server) {
            throw new Error(`You must provide the --server argument along with --token for ${provider.description}`);
        }
        return {
            type: AccountTokenType.Authorized,
            name: provider.name,
            server: options.server ? options.server : null,
            token: options.token
        };
    }
    let token;
    let accounts = (await provider.accountTokens()).filter((account)=>{
        if (account.server && target?.url) {
            return target.url.startsWith(account.server);
        } else {
            return true;
        }
    });
    if (prompt === "never") {
        return accounts.length === 1 ? accounts[0] : undefined;
    } else if (prompt === "multiple" && accounts.length === 1) {
        return accounts[0];
    } else if (accounts.length === 1 && accounts[0].type === AccountTokenType.Anonymous) {
        return accounts[0];
    } else {
        if (accounts.length > 0) {
            if (hintAccount) {
                const hintIdx = accounts.findIndex((account)=>account.token === hintAccount.token);
                if (hintIdx !== -1) {
                    const newAccounts = [
                        accounts[hintIdx]
                    ];
                    if (hintIdx > 0) {
                        newAccounts.push(...accounts.slice(0, hintIdx));
                    }
                    if (hintIdx < accounts.length - 1) {
                        newAccounts.push(...accounts.slice(hintIdx + 1));
                    }
                    accounts = newAccounts;
                }
            }
            token = await accountPrompt(provider, accounts);
        }
        if (!token) {
            token = await provider.authorizeToken(options, target);
        }
        return token;
    }
}
async function accountPrompt(_provider, accounts) {
    const options = accounts.filter((account)=>account.type !== AccountTokenType.Anonymous).map((account)=>({
            name: accountTokenText(account),
            value: account.token
        }));
    const kAuthorize = "authorize";
    const accountDescriptor = _provider.accountDescriptor || "account";
    options.push({
        name: `Use another ${accountDescriptor}...`,
        value: kAuthorize
    });
    const result1 = await prompt([
        {
            indent: "",
            name: "token",
            message: `Publish with ${accountDescriptor}:`,
            options,
            type: Select
        }
    ]);
    if (result1.token !== kAuthorize) {
        return accounts.find((account)=>account.token === result1.token);
    }
}
async function manageAccounts() {
    const accounts = [];
    for (const provider of publishProviders()){
        for (const account of (await provider.accountTokens())){
            if (account.type === AccountTokenType.Authorized) {
                accounts.push({
                    provider: provider.name,
                    ...account
                });
            }
        }
    }
    if (accounts.length === 0) {
        info("No publishing accounts currently authorized.");
        throw new Error();
    }
    const keepAccounts = await prompt([
        {
            name: "accounts",
            message: "Manage Publishing Accounts",
            type: Checkbox,
            indent: "",
            options: accounts.map((account)=>({
                    name: `${findProvider(account.provider)?.description}: ${account.name}${account.server ? " (" + account.server + ")" : ""}`,
                    value: JSON.stringify(account),
                    checked: true
                })),
            hint: `Use the arrow keys and spacebar to specify accounts you would like to remove.\n` + `   Press Enter to confirm the list of accounts you wish to remain available.`
        }
    ]);
    const removeAccounts = [];
    for (const account of accounts){
        if (!keepAccounts.accounts?.find((keepAccountJson)=>{
            const keepAccount = JSON.parse(keepAccountJson);
            return account.provider == keepAccount.provider && account.name == keepAccount.name && account.server == keepAccount.server;
        })) {
            info(`Removing ${findProvider(account.provider)?.description} account ${account.name}`);
            removeAccounts.push(account);
        }
    }
    for (const account of removeAccounts){
        const provider = findProvider(account.provider);
        provider?.removeToken(account);
    }
}
const kSiteContent = "site";
const kDocumentContent = "document";
async function publishSite(project, provider, account, options, target) {
    const renderForPublish = async (flags)=>{
        let metadataByInput = {};
        if (options.render) {
            renderProgress("Rendering for publish:\n");
            const services = renderServices(notebookContext());
            try {
                const result1 = await render(project.dir, {
                    services,
                    flags,
                    setProjectDir: true
                });
                metadataByInput = result1.files.reduce((accumulatedResult, currentInput)=>{
                    const key = currentInput.input;
                    accumulatedResult[key] = {
                        title: currentInput.format.metadata.title,
                        author: currentInput.format.metadata.author,
                        date: currentInput.format.metadata.date
                    };
                    return accumulatedResult;
                }, {});
                if (result1.error) {
                    throw result1.error;
                }
            } finally{
                services.cleanup();
            }
        }
        const outputDir = projectOutputDir(project);
        const files = [];
        for (const walk of walkSync(outputDir)){
            if (walk.isFile) {
                files.push(relative2(outputDir, walk.path));
            }
        }
        return normalizePublishFiles({
            baseDir: outputDir,
            rootFile: "index.html",
            files,
            metadataByInput
        });
    };
    const siteTitle = websiteTitle(project.config) || basename2(project.dir);
    const siteSlug = gfmAutoIdentifier(siteTitle, false);
    const [publishRecord, siteUrl] = await provider.publish(account, kSiteContent, project.dir, siteTitle, siteSlug, renderForPublish, options, target);
    if (publishRecord) {
        if (options.id === undefined) {
            writeProjectPublishDeployment(project, provider.name, account, publishRecord);
        }
    }
    return siteUrl;
}
async function publishDocument(document1, provider, account, options, target) {
    let title = basename2(document1, extname2(document1));
    const fileConfig = await inspectConfig(document1);
    if (isDocumentConfig(fileConfig)) {
        title = Object.values(fileConfig.formats)[0].metadata[kTitle] || title;
    }
    const renderForPublish = async (flags)=>{
        const files = [];
        if (options.render) {
            renderProgress("Rendering for publish:\n");
            const services = renderServices(notebookContext());
            try {
                const result1 = await render(document1, {
                    services,
                    flags
                });
                if (result1.error) {
                    throw result1.error;
                }
                if (result1.baseDir) {
                    result1.baseDir = normalizePath(result1.baseDir);
                    const docDir = normalizePath(dirname2(document1));
                    if (result1.baseDir !== docDir) {
                        const docRelative = (file)=>{
                            if (!isAbsolute2(file)) {
                                file = join2(result1.baseDir, file);
                            }
                            return relative2(docDir, file);
                        };
                        result1.files = result1.files.map((resultFile)=>{
                            return {
                                ...resultFile,
                                file: docRelative(resultFile.file),
                                supporting: resultFile.supporting ? resultFile.supporting.map(docRelative) : undefined,
                                resourceFiles: resultFile.resourceFiles.map(docRelative)
                            };
                        });
                        result1.baseDir = docDir;
                    }
                }
                const baseDir = result1.baseDir || dirname2(document1);
                const asRelative = (file)=>{
                    if (isAbsolute2(file)) {
                        return relative2(baseDir, file);
                    } else {
                        return file;
                    }
                };
                const findRootFile = (files)=>{
                    const rootFile = files.find((renderResult)=>{
                        return isHtmlContent(renderResult.file);
                    }) || files.find((renderResult)=>{
                        return isPdfContent(renderResult.file);
                    }) || files[0];
                    if (rootFile) {
                        return asRelative(rootFile.file);
                    } else {
                        return undefined;
                    }
                };
                const rootFile = findRootFile(result1.files);
                for (const resultFile of result1.files){
                    const file = asRelative(resultFile.file);
                    files.push(file);
                    if (resultFile.supporting) {
                        files.push(...resultFile.supporting.map((sf)=>{
                            if (isAbsolute2(sf)) {
                                return relative2(baseDir, sf);
                            } else {
                                return sf;
                            }
                        }).map(asRelative));
                    }
                    files.push(...resultFile.resourceFiles.map(asRelative));
                }
                let finalBaseDir = baseDir;
                if (result1.outputDir && result1.context) {
                    const relBasePath = relative2(result1.context.dir, baseDir);
                    finalBaseDir = join2(result1.context.dir, result1.outputDir, relBasePath);
                }
                return normalizePublishFiles({
                    baseDir: finalBaseDir,
                    rootFile: rootFile,
                    files
                });
            } finally{
                services.cleanup();
            }
        } else {
            const baseDir = dirname2(document1);
            if (isDocumentConfig(fileConfig)) {
                let rootFile;
                for (const format of Object.values(fileConfig.formats)){
                    title = format.metadata[kTitle] || title;
                    const outputFile = format.pandoc[kOutputFile];
                    if (outputFile && existsSync(join2(baseDir, outputFile))) {
                        files.push(outputFile);
                        if (!rootFile) {
                            rootFile = outputFile;
                        }
                    } else {
                        throw new Error(`Output file ${outputFile} does not exist.`);
                    }
                }
                const filesDir = inputFilesDir(document1);
                if (existsSync(filesDir)) {
                    files.push(filesDir);
                }
                files.push(...fileConfig.resources);
                return normalizePublishFiles({
                    baseDir,
                    rootFile: rootFile,
                    files
                });
            } else {
                throw new Error(`The specifed document (${document1}) is not a valid quarto input file`);
            }
        }
    };
    const [publishRecord, siteUrl] = await provider.publish(account, kDocumentContent, document1, title, gfmAutoIdentifier(title, false), renderForPublish, options, target);
    if (publishRecord) {
        if (options.id === undefined) {
            writePublishDeployment(document1, provider.name, account, publishRecord);
        }
    }
    return siteUrl;
}
function normalizePublishFiles(publishFiles) {
    publishFiles.files = publishFiles.files.reduce((files, file)=>{
        const filePath = join2(publishFiles.baseDir, file);
        if (Deno.statSync(filePath).isDirectory) {
            for (const walk of walkSync(filePath)){
                if (walk.isFile) {
                    files.push(relative2(publishFiles.baseDir, walk.path));
                }
            }
        } else {
            files.push(file);
        }
        return files;
    }, new Array());
    publishFiles.files = uniq1(publishFiles.files);
    return publishFiles;
}
const publishCommand = new Command().name("publish").description("Publish a document or project to a provider.\n\nAvailable providers include:\n\n" + " - Quarto Pub (quarto-pub)\n" + " - GitHub Pages (gh-pages)\n" + " - Posit Connect (connect)\n" + " - Posit Cloud (posit-cloud)\n" + " - Netlify (netlify)\n" + " - Confluence (confluence)\n" + " - Hugging Face Spaces (huggingface)\n\n" + "Accounts are configured interactively during publishing.\n" + "Manage/remove accounts with: quarto publish accounts").arguments("[provider] [path]").option("--id <id:string>", "Identifier of content to publish").option("--server <server:string>", "Server to publish to").option("--token <token:string>", "Access token for publising provider").option("--no-render", "Do not render before publishing.").option("--no-prompt", "Do not prompt to confirm publishing destination").option("--no-browser", "Do not open a browser to the site after publishing").example("Publish project (prompt for provider)", "quarto publish").example("Publish document (prompt for provider)", "quarto publish document.qmd").example("Publish project to Hugging Face Spaces", "quarto publish huggingface").example("Publish project to Netlify", "quarto publish netlify").example("Publish with explicit target", "quarto publish netlify --id DA36416-F950-4647-815C-01A24233E294").example("Publish project to GitHub Pages", "quarto publish gh-pages").example("Publish project to Posit Connect", "quarto publish connect").example("Publish with explicit credentials", "quarto publish connect --server example.com --token 01A24233E294").example("Publish project to Posit Cloud", "quarto publish posit-cloud").example("Publish without confirmation prompt", "quarto publish --no-prompt").example("Publish without rendering", "quarto publish --no-render").example("Publish without opening browser", "quarto publish --no-browser").example("Manage/remove publishing accounts", "quarto publish accounts").action(async (options, provider, path)=>{
    if (provider && !path && existsSync(provider)) {
        path = provider;
        provider = undefined;
    }
    if (provider === "accounts") {
        await manageAccounts();
    } else {
        let providerInterface;
        if (provider) {
            providerInterface = findProvider(provider);
            if (!providerInterface) {
                throw new Error(`Publishing source '${provider}' not found`);
            }
        }
        await publishAction(options, providerInterface, path);
    }
});
async function publishAction(options, provider, path) {
    await initYamlIntelligence1();
    const publishOptions = await createPublishOptions(options, provider, path);
    const doPublish = async (publishProvider, accountPrompt, publishTarget, account)=>{
        if (publishProvider.requiresRender && publishOptions.render === false) {
            throw new Error(`${publishProvider.description} requires rendering before publish.`);
        }
        account = account && !publishOptions.prompt ? account : await resolveAccount(publishProvider, publishOptions.prompt ? accountPrompt : "never", publishOptions, account, publishTarget);
        if (account) {
            await publish7(publishProvider, account, publishOptions, publishTarget);
        }
    };
    const deployment = provider && publishOptions.id ? {
        provider,
        target: {
            id: publishOptions.id
        }
    } : await resolveDeployment(publishOptions, provider?.name);
    provider = deployment?.provider || provider;
    if (deployment) {
        await doPublish(deployment.provider, deployment.account ? "multiple" : "always", deployment.target, deployment.account);
    } else if (publishOptions.prompt) {
        const providers = publishProviders();
        if (!provider) {
            const result1 = await prompt([
                {
                    indent: "",
                    name: "provider",
                    message: "Provider:",
                    options: providers.filter((provider)=>!provider.hidden).map((provider)=>({
                            name: provider.description,
                            value: provider.name
                        })),
                    type: Select
                }
            ]);
            if (result1.provider) {
                provider = findProvider(result1.provider);
            }
        }
        if (provider) {
            await doPublish(provider, "always");
        }
    } else {
        throw new Error("No re-publishing target found (--no-prompt requires an existing 'publish' config to update)");
    }
}
async function publish7(provider, account, options, target) {
    try {
        const siteUrl = typeof options.input !== "string" ? await publishSite(options.input, provider, account, options, target) : await publishDocument(options.input, provider, account, options, target);
        if (siteUrl && options.browser) {
            await openUrl(siteUrl.toString());
        }
    } catch (err) {
        if (provider.isUnauthorized(err) && options.prompt) {
            if (await handleUnauthorized(provider, account)) {
                const authorizedAccount = await provider.authorizeToken(options, target);
                if (authorizedAccount) {
                    return await publish7(provider, authorizedAccount, options, target);
                }
            }
        } else {
            throw err;
        }
    }
}
async function createPublishOptions(options, provider, path) {
    const nbContext = notebookContext();
    path = path || Deno.cwd();
    if (!existsSync(path)) {
        throw new Error(`The specified path (${path}) does not exist so cannot be published.`);
    }
    let input;
    if (provider && provider.resolveProjectPath) {
        const resolvedPath = provider.resolveProjectPath(path);
        try {
            if (Deno.statSync(resolvedPath).isDirectory) {
                path = resolvedPath;
            }
        } catch (_e) {}
    }
    const project = await projectContext(path, nbContext) || singleFileProjectContext(path, nbContext);
    if (Deno.statSync(path).isDirectory) {
        if (projectIsWebsite(project)) {
            input = project;
        } else if (projectIsManuscript(project) && project.files.input.length > 0) {
            input = project;
        } else if (project.files.input.length === 1) {
            input = project.files.input[0];
        } else {
            throw new Error(`The specified path (${path}) is not a website, manuscript or book project so cannot be published.`);
        }
    } else {
        if (project && projectIsWebsite(project)) {
            throw new Error(`The specified path (${path}) is within a website or book project so cannot be published individually`);
        }
        input = path;
    }
    const interactive = isInteractiveTerminal() && !runningInCI() && !options.id;
    return {
        input,
        server: options.server || null,
        token: options.token,
        id: options.id,
        render: !!options.render,
        prompt: !!options.prompt && interactive,
        browser: !!options.browser && interactive && !isServerSession()
    };
}
async function initYamlIntelligence1() {
    setInitializer(initYamlIntelligenceResourcesFromFilesystem);
    await initState();
}
const listCommand = new Command().hidden().name("list").arguments("<type:string>").description("Lists an extension or global dependency.").example("List installed extensions", "quarto list extensions").example("List global tools", "quarto list tools").action(async (_options, type)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    const extensionContext = createExtensionContext();
    try {
        if (type.toLowerCase() === "extensions") {
            await outputExtensions(Deno.cwd(), extensionContext);
        } else if (type.toLowerCase() === "tools") {
            await outputTools();
        } else {
            info(`Unrecognized option '${type}' - please choose 'tools' or 'extensions'.`);
        }
    } finally{
        temp.cleanup();
    }
});
async function outputExtensions(path, extensionContext) {
    const nbContext = notebookContext();
    const project = await projectContext(path, nbContext);
    const extensions = await extensionContext.extensions(path, project?.config, project?.dir, {
        builtIn: false
    });
    if (extensions.length === 0) {
        info(`No extensions are installed in this ${project ? "project" : "directory"}.`);
    } else {
        const extensionEntries = [];
        const provides = (extension)=>{
            const contribs = [];
            if (extension.contributes.filters && extension.contributes.filters?.length > 0) {
                contribs.push("filters");
            }
            if (extension.contributes.shortcodes && extension.contributes.shortcodes?.length > 0) {
                contribs.push("shortcodes");
            }
            if (extension.contributes.formats && Object.keys(extension.contributes.formats).length > 0) {
                contribs.push("formats");
            }
            return contribs.join(", ");
        };
        extensions.forEach((ext)=>{
            const row = [
                extensionIdString(ext.id),
                ext.version?.toString() || "(none)",
                `${provides(ext)}`
            ];
            extensionEntries.push(row);
        });
        const table = new Table().header([
            "Id",
            "Version",
            "Contributes"
        ]).body(extensionEntries).padding(4);
        info(table.toString());
    }
}
const kQuartoIgnore1 = ".quartoignore";
function templateFiles(dir) {
    const excludes = [];
    const includes = [];
    const ignoreFile = join2(dir, kQuartoIgnore1);
    if (existsSync(ignoreFile)) {
        const ignoreFileContents = Deno.readTextFileSync(ignoreFile);
        const ignoreLines = lines(ignoreFileContents.trim());
        ignoreLines.forEach((line)=>{
            const splitOnComment = line.split("#");
            const exclude = splitOnComment[0];
            if (exclude && exclude.startsWith("!")) {
                if (exclude.length > 1) {
                    includes.push(exclude.substring(1));
                } else {
                    warn(`Unknown ignore pattern '${exclude}'`);
                }
            } else if (exclude) {
                excludes.push(exclude);
            }
        });
    }
    excludes.push(...kBuiltInExcludes);
    const filtered = excludes.filter((ex)=>{
        return !includes.includes(ex);
    });
    const resolved = resolvePathGlobs(dir, [
        "**/*"
    ], filtered);
    return resolved.include;
}
const kBuiltInExcludes = [
    ".*",
    "COPYING.md",
    "COPYRIGHT",
    "README.md",
    "CHANGELOG.md",
    "COPYRIGHT",
    "LICENSE",
    "_extensions"
];
const kRootTemplateName = "template.qmd";
const useTemplateCommand = new Command().name("template").arguments("<target:string>").description("Use a Quarto template for this directory or project.").option("--no-prompt", "Do not prompt to confirm actions").example("Use a template from Github", "quarto use template <gh-org>/<gh-repo>").action(async (options, target)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
        await useTemplate(options, target, temp);
    } finally{
        temp.cleanup();
    }
});
async function useTemplate(options, target, tempContext) {
    const source = await extensionSource(target);
    if (!source) {
        info(`Extension not found in local or remote sources`);
        return;
    }
    const trusted = await isTrusted1(source, options.prompt !== false);
    if (trusted) {
        const outputDirectory = await determineDirectory(options.prompt !== false);
        const stagedDir = await stageTemplate1(source, tempContext);
        const filesToCopy = templateFiles(stagedDir);
        const extDir = join2(stagedDir, kExtensionDir);
        const templateExtensions = await readExtensions(extDir);
        const installedExtensions = [];
        let installExtensions = false;
        if (templateExtensions.length > 0) {
            installExtensions = await confirmInstallation(templateExtensions, outputDirectory, {
                allowPrompt: options.prompt !== false,
                throw: true,
                message: "The template requires the following changes to extensions:"
            });
            if (!installExtensions) {
                return;
            }
        }
        info(`\nPreparing template files...`);
        const copyActions = [];
        for (const fileToCopy of filesToCopy){
            const isDir = Deno.statSync(fileToCopy).isDirectory;
            const rel = relative2(stagedDir, fileToCopy);
            if (!isDir) {
                let target = join2(outputDirectory, rel);
                let displayName = rel;
                const targetDir = dirname2(target);
                if (rel === kRootTemplateName) {
                    displayName = `${basename2(targetDir)}.qmd`;
                    target = join2(targetDir, displayName);
                }
                const copyAction = {
                    file: displayName,
                    copy: async ()=>{
                        await ensureDir(targetDir);
                        await Deno.copyFile(fileToCopy, target);
                    }
                };
                if (existsSync(target)) {
                    if (options.prompt) {
                        const proceed = await Confirm.prompt({
                            message: `Overwrite file ${displayName}?`
                        });
                        if (proceed) {
                            copyActions.push(copyAction);
                        }
                    } else {
                        throw new Error(`The file ${displayName} already exists and would be overwritten by this action.`);
                    }
                } else {
                    copyActions.push(copyAction);
                }
            }
        }
        if (installExtensions) {
            installedExtensions.push(...templateExtensions);
            await withSpinner({
                message: "Installing extensions..."
            }, async ()=>{
                const subStagedDir = tempContext.createDir();
                await copyExtensions(source, stagedDir, subStagedDir);
                await completeInstallation(subStagedDir, outputDirectory);
            });
        }
        if (copyActions.length > 0) {
            await withSpinner({
                message: "Copying files..."
            }, async ()=>{
                for (const copyAction of copyActions){
                    await copyAction.copy();
                }
            });
        }
        if (installedExtensions.length > 0) {
            info(`\nExtensions installed:`);
            for (const extension of installedExtensions){
                info(` - ${extension.title}`);
            }
        }
        if (copyActions.length > 0) {
            info(`\nFiles created:`);
            for (const copyAction of copyActions){
                info(` - ${copyAction.file}`);
            }
        }
    } else {
        return Promise.resolve();
    }
}
async function stageTemplate1(source, tempContext) {
    if (source.type === "remote") {
        const workingDir = tempContext.createDir();
        const archiveDir = join2(workingDir, "archive");
        ensureDirSync(archiveDir);
        const filename = (typeof source.resolvedTarget === "string" ? source.resolvedTarget : source.resolvedFile) || "extension.zip";
        const toFile = join2(archiveDir, filename);
        await downloadWithProgress(source.resolvedTarget, `Downloading`, toFile);
        await unzipInPlace(toFile);
        if (source.targetSubdir) {
            const sourceSubDir = join2(archiveDir, source.targetSubdir);
            if (existsSync(sourceSubDir)) {
                return sourceSubDir;
            }
        }
        const dirEntries = Deno.readDirSync(archiveDir);
        let count = 0;
        let name;
        let hasFiles = false;
        for (const dirEntry of dirEntries){
            if (dirEntry.isDirectory) {
                name = dirEntry.name;
                count++;
            } else {
                hasFiles = true;
            }
        }
        if (!hasFiles && count === 1 && name) {
            return join2(archiveDir, name);
        }
        return archiveDir;
    } else {
        if (typeof source.resolvedTarget !== "string") {
            throw new InternalError("Local resolved extension should always have a string target.");
        }
        if (Deno.statSync(source.resolvedTarget).isDirectory) {
            return source.resolvedTarget;
        } else {
            const workingDir = tempContext.createDir();
            const targetFile = join2(workingDir, basename2(source.resolvedTarget));
            Deno.copyFileSync(source.resolvedTarget, targetFile);
            await unzipInPlace(targetFile);
            return workingDir;
        }
    }
}
async function isTrusted1(source, allowPrompt) {
    if (allowPrompt && source.type === "remote") {
        const preamble = `\nQuarto templates may execute code when documents are rendered. If you do not \ntrust the authors of the template, we recommend that you do not install or \nuse the template.`;
        info(preamble);
        const question = "Do you trust the authors of this template";
        const confirmed = await Confirm.prompt({
            message: question,
            default: true
        });
        return confirmed;
    } else {
        return true;
    }
}
async function determineDirectory(allowPrompt) {
    const currentDir = Deno.cwd();
    if (!allowPrompt) {
        if (!directoryEmpty(currentDir)) {
            throw new Error(`Unable to install in ${currentDir} as the directory isn't empty.`);
        } else {
            return currentDir;
        }
    } else {
        return promptForDirectory(currentDir, directoryEmpty(currentDir));
    }
}
async function promptForDirectory(root, isEmpty) {
    const useSubDir = await Confirm.prompt({
        message: "Create a subdirectory for template?",
        default: !isEmpty,
        hint: "Use a subdirectory for the template rather than the current directory."
    });
    if (!useSubDir) {
        return root;
    }
    const dirName = await Input.prompt({
        message: "Directory name:",
        validate: (input)=>{
            if (input.length === 0 || input === ".") {
                return true;
            }
            const dir = join2(root, input);
            if (!existsSync(dir)) {
                ensureDirSync(dir);
            }
            return true;
        }
    });
    if (dirName.length === 0 || dirName === ".") {
        return root;
    } else {
        return join2(root, dirName);
    }
}
async function unzipInPlace(zipFile) {
    await withSpinner({
        message: "Unzipping"
    }, async ()=>{
        const result1 = await unzip(zipFile);
        if (!result1.success) {
            throw new Error("Failed to unzip template.\n" + result1.stderr);
        }
        await Deno.remove(zipFile);
        return Promise.resolve();
    });
}
function directoryEmpty(path) {
    const dirContents = Deno.readDirSync(path);
    for (const _content of dirContents){
        return false;
    }
    return true;
}
const safeFileWriter = (projectDir, prompt = true)=>{
    const idxPath = join2(projectScratchPath(projectDir), "use", "binder.json");
    ensureDirSync(dirname2(idxPath));
    let fileIndex = {};
    if (existsSync(idxPath)) {
        fileIndex = JSON.parse(Deno.readTextFileSync(idxPath));
    }
    return async (projRelativePath, contents)=>{
        const absPath = join2(projectDir, projRelativePath);
        const write = ()=>{
            fileIndex[projRelativePath] = hash;
            Deno.writeTextFileSync(absPath, contents);
            Deno.writeTextFileSync(idxPath, JSON.stringify(fileIndex, null, 2));
            info(`[✓] ${projRelativePath}`);
        };
        const hash = md5Hash(contents);
        if (existsSync(absPath)) {
            const lastHash = fileIndex[projRelativePath];
            const currentContents = Deno.readTextFileSync(absPath);
            const currentHash = md5Hash(currentContents);
            let writeFile = true;
            if (!lastHash || lastHash !== currentHash) {
                if (prompt) {
                    const question = lastHash ? `File ${projRelativePath} was modified since last generated. Overwrite?` : `File ${projRelativePath} wasn't created by the this command. Overwrite?`;
                    writeFile = await Confirm.prompt({
                        message: question
                    });
                } else {
                    writeFile = false;
                    lastHash ? warn(`Skipped ${projRelativePath} - modified since last generated.`) : warn(`Skipped ${projRelativePath} - wasn't created by the this command.`);
                }
            }
            if (writeFile) {
                write();
            }
        } else {
            write();
        }
    };
};
const useBinderCommand = new Command().name("binder").description("Configure the current project with Binder support.").option("--no-prompt", "Do not prompt to confirm actions").example("Configure project to use Binder", "quarto use binder").action(async (options)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
        logProgress("Determining configuration");
        const nbContext = notebookContext();
        const context = await projectContext(Deno.cwd(), nbContext);
        if (!context) {
            throw new Error("You must be in a Quarto project in order to configure Binder support.");
        }
        const projEnv = await withSpinner({
            message: "Inspecting project configuration:",
            doneMessage: "Detected Project configuration:\n"
        }, ()=>{
            return context.environment();
        });
        const jupyterLab4 = jupyterLabVersion(context, projEnv);
        const rConfig = {};
        if (projectHasR(context, projEnv)) {
            const result1 = await execProcess({
                cmd: [
                    await rBinaryPath("R"),
                    "--version"
                ],
                stdout: "piped",
                stderr: "piped"
            });
            if (result1.success) {
                const output = result1.stdout;
                const verMatch = output?.match(/R version (\d+\.\d+\.\d+) \((\d\d\d\d-\d\d-\d\d)\)/m);
                if (verMatch) {
                    const version = verMatch[1];
                    rConfig.version = new SemVer(version);
                    rConfig.date = verMatch[2];
                }
            } else {
                warn("Unable to detect R version, ommitting R configuration");
            }
        }
        const quartoVersion = typeof projEnv.quarto === "string" ? projEnv.quarto === "prerelease" ? "most recent prerelease" : "most recent release" : projEnv.quarto.toString();
        const table = new Table();
        table.push([
            "Quarto",
            quartoVersion
        ]);
        table.push([
            "JupyterLab",
            jupyterLab4 ? "4.x" : "default"
        ]);
        if (projEnv.engines.length > 0) {
            table.push([
                projEnv.engines.length === 1 ? "Engine" : "Engines",
                projEnv.engines.join("\n")
            ]);
        }
        if (rConfig.version || rConfig.date) {
            const verStr = [];
            if (rConfig.version) {
                verStr.push(`${rConfig.version?.toString()}`);
            }
            if (rConfig.date) {
                verStr.push(`(${rConfig.date})`);
            }
            table.push([
                "R",
                verStr.join(" ")
            ]);
        }
        if (projEnv.tools.length > 0) {
            table.push([
                "Tools",
                projEnv.tools.join("\n")
            ]);
        }
        table.push([
            "Editor",
            projEnv.codeEnvironment
        ]);
        if (projEnv.environments.length > 0) {
            table.push([
                "Environments",
                projEnv.environments.join("\n")
            ]);
        }
        table.indent(4).minColWidth(12).render();
        const isMarkdownEngineOnly = (engines)=>{
            return engines.length === 1 && engines.includes("markdown");
        };
        if (projEnv.environments.length === 0 && !isMarkdownEngineOnly(projEnv.engines)) {
            info("\nNo files which provide dependencies were discovered. If you continue, no dependencies will be restored when running this project with Binder.\n\nLearn more at:\nhttps://www.quarto.org/docs/prerelease/1.4/binder.html#dependencies\n");
            const proceed = !options.prompt || await Confirm.prompt({
                message: "Do you want to continue?",
                default: true
            });
            if (!proceed) {
                return;
            }
        }
        const fileOperations = await binderFileOperations(projEnv, jupyterLab4, context, options, rConfig);
        info("\nThe following files will be written:");
        const changeTable = new Table();
        fileOperations.forEach((op)=>{
            changeTable.push([
                op.file,
                op.desc
            ]);
        });
        changeTable.border(true).render();
        info("");
        const writeFiles = !options.prompt || await Confirm.prompt({
            message: "Continue?",
            default: true
        });
        if (writeFiles) {
            logProgress("\nWriting configuration files");
            for (const fileOperation of fileOperations){
                await fileOperation.performOp();
            }
        }
    } finally{
        temp.cleanup();
    }
});
const createPostBuild = (quartoConfig, vscodeConfig, pythonConfig)=>{
    const postBuildScript = [];
    postBuildScript.push("#!/usr/bin/env bash -v");
    postBuildScript.push("");
    postBuildScript.push(`# determine which version of Quarto to install`);
    postBuildScript.push(`QUARTO_VERSION=${quartoConfig.version}`);
    postBuildScript.push(kLookupQuartoVersion);
    postBuildScript.push(msg("Installing Quarto $QUARTO_VERSION"));
    postBuildScript.push(kInstallQuarto);
    postBuildScript.push(msg("Installed Quarto"));
    if (quartoConfig.tinytex) {
        postBuildScript.push(msg("Installing TinyTex"));
        postBuildScript.push("# install tinytex");
        postBuildScript.push("quarto install tinytex --no-prompt");
        postBuildScript.push(msg("Installed TinyTex"));
    }
    if (quartoConfig.chromium) {
        postBuildScript.push(msg("Installing Chromium"));
        postBuildScript.push("# install chromium");
        postBuildScript.push("quarto install chromium --no-prompt");
        postBuildScript.push(msg("Installed Chromium"));
    }
    if (vscodeConfig.version) {
        const version = typeof vscodeConfig.version === "boolean" ? new SemVer("4.16.1") : vscodeConfig.version;
        postBuildScript.push(msg("Configuring VSCode"));
        postBuildScript.push("# download and install VS Code server");
        postBuildScript.push(`CODE_VERSION=${version}`);
        postBuildScript.push(kInstallVSCode);
        if (vscodeConfig.extensions) {
            postBuildScript.push("# install vscode extensions");
            for (const extension of vscodeConfig.extensions){
                postBuildScript.push(`code-server --install-extension ${extension}`);
            }
        }
        postBuildScript.push(msg("Configured VSCode"));
    }
    if (pythonConfig.pip) {
        postBuildScript.push("# install required python packages");
        for (const lib of pythonConfig.pip){
            postBuildScript.push(`python3 -m pip install ${lib}`);
        }
    }
    postBuildScript.push(msg("Completed"));
    return postBuildScript.join("\n");
};
const jupyterLabVersion = (context, env)=>{
    const envs = env.environments;
    const envMatchers = {};
    envMatchers["requirements.txt"] = /jupyterlab>*=*4.*./g;
    envMatchers["environment.yml"] = /jupyterlab *>*=*4.*./g;
    envMatchers["pipfile"] = /jupyterlab = "*>*=*4.*."/g;
    const hasJL4 = envs.some((env)=>{
        const matcher = envMatchers[env];
        if (!matcher) {
            return false;
        }
        const contents = Deno.readTextFileSync(join2(context.dir, env));
        return contents.match(matcher);
    });
    return hasJL4;
};
const msg = (text)=>{
    return `
echo
echo ${text}
echo`;
};
const kInstallQuarto = `
# download and install the deb file
curl -LO https://github.com/quarto-dev/quarto-cli/releases/download/v$QUARTO_VERSION/quarto-$QUARTO_VERSION-linux-amd64.deb
dpkg -x quarto-$QUARTO_VERSION-linux-amd64.deb .quarto
rm -rf quarto-$QUARTO_VERSION-linux-amd64.deb

# get quarto in the path
mkdir -p ~/.local/bin
ln -s ~/.quarto/opt/quarto/bin/quarto ~/.local/bin/quarto

# create the proper pandoc symlink to enable visual editor in Quarto extension
ln -s ~/.quarto/opt/quarto/bin/tools/x86_64/pandoc ~/.quarto/opt/quarto/bin/tools/pandoc
`;
const kInstallVSCode = `
# download and extract
wget -q -O code-server.tar.gz https://github.com/coder/code-server/releases/download/v$CODE_VERSION/code-server-$CODE_VERSION-linux-amd64.tar.gz
tar xzf code-server.tar.gz
rm -rf code-server.tar.gz

# place in hidden folder
mv "code-server-$CODE_VERSION-linux-amd64" .code-server

# get code-server in path
mkdir -p ./.local/bin
ln -s ~/.code-server/bin/code-server ~/.local/bin/code-server
`;
const kLookupQuartoVersion = `
# See whether we need to lookup a Quarto version
if [ $QUARTO_VERSION = "prerelease" ]; then
	QUARTO_JSON="_prerelease.json"
elif [ $QUARTO_VERSION = "release" ]; then
	QUARTO_JSON="_download.json"
fi

if [ $QUARTO_JSON != "" ]; then

# create a python script and run it
PYTHON_SCRIPT=_quarto_version.py
if [ -e $PYTHON_SCRIPT ]; then
	rm -rf $PYTHON_SCRIPT
fi

cat > $PYTHON_SCRIPT <<EOF
import urllib, json

import urllib.request, json
with urllib.request.urlopen("https://quarto.org/docs/download/\${QUARTO_JSON}") as url:
	data = json.load(url)
	print(data['version'])

EOF

QUARTO_VERSION=$(python $PYTHON_SCRIPT)
rm -rf $PYTHON_SCRIPT

fi
`;
async function binderFileOperations(projEnv, jupyterLab4, context, options, rConfig) {
    const operations = [];
    const quartoConfig = {
        version: projEnv.quarto,
        tinytex: projEnv.tools.includes("tinytex"),
        chromium: projEnv.tools.includes("chromium")
    };
    const vsCodeConfig = {
        version: projEnv.codeEnvironment === "vscode" ? new SemVer("4.16.1") : undefined,
        extensions: [
            "ms-python.python",
            "sumneko.lua",
            "quarto.quarto"
        ]
    };
    const pythonConfig = {
        pip: []
    };
    if (jupyterLab4) {
        if (projEnv.codeEnvironment === "vscode") {
            pythonConfig.pip?.push("git+https://github.com/trungleduc/jupyter-server-proxy@lab4");
        }
        pythonConfig.pip?.push("jupyterlab-quarto");
    } else {
        if (projEnv.codeEnvironment === "vscode") {
            pythonConfig.pip?.push("jupyter-server-proxy");
        }
        pythonConfig.pip?.push("jupyterlab-quarto==0.1.45");
    }
    const environmentConfig = {
        apt: [
            "zip"
        ]
    };
    const writeFile = safeFileWriter(context.dir, options.prompt);
    const renvPath = join2(context.dir, "renv.lock");
    if (existsSync(renvPath)) {
        const installRText = "install.packages('renv')\nrenv::restore()";
        operations.push({
            file: "install.R",
            desc: "Activates the R environment described in renv.lock",
            performOp: async ()=>{
                await writeFile("install.R", installRText);
            }
        });
    }
    const postBuildScriptText = createPostBuild(quartoConfig, vsCodeConfig, pythonConfig);
    operations.push({
        file: "postBuild",
        desc: "Configures Quarto and supporting tools",
        performOp: async ()=>{
            await writeFile("postBuild", postBuildScriptText);
        }
    });
    if (vsCodeConfig.version) {
        operations.push({
            file: ".jupyter",
            desc: "Configures JupyterLab with necessary extensions",
            performOp: async ()=>{
                const traitletsDir = ".jupyter";
                ensureDirSync(join2(context.dir, traitletsDir));
                const resDir = resourcePath("use/binder/");
                for (const file of [
                    "vscode.svg",
                    "jupyter_notebook_config.py"
                ]){
                    const textContents = Deno.readTextFileSync(join2(resDir, file));
                    await writeFile(join2(traitletsDir, file), textContents);
                }
            }
        });
    }
    if (environmentConfig.apt && environmentConfig.apt.length) {
        const aptText = environmentConfig.apt.join("\n");
        operations.push({
            file: "apt.txt",
            desc: "Installs Quarto required packages",
            performOp: async ()=>{
                await writeFile("apt.txt", aptText);
            }
        });
    }
    if (rConfig.version || rConfig.date) {
        const runtime = [
            "r"
        ];
        if (rConfig.version) {
            runtime.push(`-${rConfig.version}`);
        }
        if (rConfig.date) {
            runtime.push(`-${rConfig.date}`);
        }
        operations.push({
            file: "runtime.txt",
            desc: "Installs R and configures RStudio",
            performOp: async ()=>{
                await writeFile("runtime.txt", runtime.join(""));
            }
        });
    }
    return operations;
}
const projectHasR = (context, projEnv)=>{
    if (projEnv.engines.includes("knitr")) {
        return true;
    }
    if (existsSync(join2(context.dir, "renv.lock"))) {
        return true;
    }
    if (existsSync(join2(context.dir, "install.R"))) {
        return true;
    }
    if (context.config?.project?.[kProjectPreRender]) {
        if (asArray(context.config.project[kProjectPreRender]).some((file)=>{
            return extname2(file).toLowerCase() === ".r";
        })) {
            return true;
        }
    }
    if (context.config?.project?.[kProjectPostRender]) {
        if (asArray(context.config.project[kProjectPostRender]).some((file)=>{
            return extname2(file).toLowerCase() === ".r";
        })) {
            return true;
        }
    }
    return false;
};
const kUseCommands = [
    useTemplateCommand,
    useBinderCommand
];
const makeUseCommand = ()=>{
    const theCommand = new Command().name("use").arguments("<type:string> [target:string]").option("--no-prompt", "Do not prompt to confirm actions").description("Automate document or project setup tasks.").action((_options, type, _target)=>{
        const useCommand = kUseCommands.find((command)=>{
            return command.getName() === type;
        });
        if (!useCommand) {
            throw new ValidationError1(`Unknown type '${type}'- did you mean 'template'?`);
        }
    });
    kUseCommands.forEach((command)=>{
        theCommand.command(command.getName(), command);
    });
    return theCommand;
};
const addCommand1 = new Command().name("add").arguments("<extension:string>").option("--no-prompt", "Do not prompt to confirm actions").option("--embed <extensionId>", "Embed this extension within another extension (used when authoring extensions).").description("Add an extension to this folder or project").example("Install extension (Github)", "quarto add <gh-org>/<gh-repo>").example("Install extension (file)", "quarto add <path-to-zip>").example("Install extension (url)", "quarto add <url>").action(async (options, extension)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    const temp = createTempContext();
    try {
        if (extension) {
            await installExtension(extension, temp, options.prompt !== false, options.embed);
        } else {
            info("Please provide an extension name, url, or path.");
        }
    } finally{
        temp.cleanup();
    }
});
const uninstallCommand = new Command().name("uninstall").arguments("[tool]").option("--no-prompt", "Do not prompt to confirm actions").option("--update-path", "Update system path when a tool is installed").description("Removes an extension.").example("Remove extension using name", "quarto remove <extension-name>").action(async (options, tool)=>{
    await initYamlIntelligenceResourcesFromFilesystem();
    if (tool) {
        await removeTool(tool, options.prompt, options.updatePath);
    } else {
        const allTools = await loadTools();
        if (allTools.filter((tool)=>tool.installed).length === 0) {
            info("No tools are installed.");
        } else {
            const toolTarget = await selectTool(allTools, "remove");
            if (toolTarget) {
                info("");
                await removeTool(toolTarget);
            }
        }
    }
});
const keyRegExp = /(.*)qstart-(.*)-qend(.*)/;
function renderAndCopyArtifacts(target, artifactSrcDir, createDirective, data, quiet) {
    ensureDirSync(target);
    const copiedFiles = [];
    for (const artifact of walkSync(artifactSrcDir)){
        if (artifact.isFile) {
            keyRegExp.lastIndex = 0;
            let match = keyRegExp.exec(artifact.path);
            let resolvedPath = artifact.path;
            while(match){
                const prefix = match[1];
                const key = match[2];
                const suffix = match[3];
                if (data[key]) {
                    resolvedPath = `${prefix}${data[key]}${suffix}`;
                } else {
                    resolvedPath = `${prefix}${key}${suffix}`;
                }
                match = keyRegExp.exec(resolvedPath);
            }
            keyRegExp.lastIndex = 0;
            const targetRelativePath = relative2(artifactSrcDir, resolvedPath);
            const targetAbsolutePath = join2(createDirective.directory, targetRelativePath);
            copiedFiles.push(renderArtifact(artifact.path, targetAbsolutePath, data));
        }
    }
    if (!quiet) {
        info(`Creating ${createDirective.displayType} at `, {
            newline: false
        });
        info(`${createDirective.directory}`, {
            bold: true,
            newline: false
        });
        info(":");
        for (const copiedFile of copiedFiles){
            const relPath = relative2(createDirective.directory, copiedFile);
            info(`  - Created ${relPath}`);
        }
    }
    return copiedFiles;
}
const renderArtifact = (src, target, data)=>{
    const srcFileName = basename2(src);
    if (srcFileName.includes(".ejs.")) {
        const renderTarget = target.replace(/\.ejs\./, ".");
        if (safeExistsSync(renderTarget)) {
            throw new Error(`The file ${renderTarget} already exists.`);
        }
        const rendered = renderEjs(src, data, false);
        ensureDirSync(dirname2(renderTarget));
        Deno.writeTextFileSync(renderTarget, rendered);
        return renderTarget;
    } else {
        if (safeExistsSync(target)) {
            throw new Error(`The file ${target} already exists.`);
        }
        ensureDirSync(dirname2(target));
        Deno.copyFileSync(src, target);
        return target;
    }
};
async function ejsData(createDirective) {
    const title = capitalizeTitle(createDirective.name);
    const classname = title.replaceAll(/[^\w]/gm, "");
    const filesafename = gfmAutoIdentifier(createDirective.name, true);
    const version = "1.0.0";
    const author = await gitAuthor() || "First Last";
    const qVer = coerce(quartoConfig.version());
    const quartoversion = `${qVer?.major}.${qVer?.minor}.0`;
    return {
        name: createDirective.name,
        filesafename,
        title,
        classname,
        author: author.trim(),
        version,
        quartoversion
    };
}
async function gitAuthor() {
    const result1 = await execProcess({
        cmd: [
            "git",
            "config",
            "--global",
            "user.name"
        ],
        stdout: "piped",
        stderr: "piped"
    });
    if (result1.success) {
        return result1.stdout;
    } else {
        return undefined;
    }
}
const kType3 = "type";
const kSubType = "subtype";
const kName1 = "name";
const kTypeExtension = "extension";
const kExtensionTypes = [
    {
        name: "shortcode",
        value: "shortcode",
        openfiles: [
            "example.qmd"
        ]
    },
    {
        name: "filter",
        value: "filter",
        openfiles: [
            "example.qmd"
        ]
    },
    {
        name: "revealjs plugin",
        value: "revealjs-plugin",
        openfiles: [
            "example.qmd"
        ]
    },
    {
        name: "journal format",
        value: "journal",
        openfiles: [
            "template.qmd"
        ]
    },
    {
        name: "custom format",
        value: "format",
        openfiles: [
            "template.qmd"
        ]
    },
    {
        name: "metadata",
        value: "metadata",
        openfiles: []
    }
];
const kExtensionSubtypes = {
    "format": [
        "html",
        "pdf",
        "docx",
        "revealjs",
        "typst"
    ]
};
const kExtensionValues = kExtensionTypes.filter((t)=>typeof t === "object").map((t)=>t.value);
const extensionArtifactCreator = {
    displayName: "Extension",
    type: kTypeExtension,
    resolveOptions,
    finalizeOptions,
    nextPrompt,
    createArtifact
};
function resolveOptions(args) {
    const typeRaw = args.length > 0 ? args[0] : undefined;
    const nameRaw = args.length > 1 ? args[1] : undefined;
    const options = {};
    if (typeRaw) {
        const [type, template] = typeRaw.split(":");
        options[kType3] = type;
        options[kSubType] = template;
    }
    if (nameRaw) {
        options[kName1] = nameRaw;
    }
    return options;
}
function finalizeOptions(createOptions) {
    if (!createOptions.options.name) {
        throw new Error("Required property 'name' is missing.");
    }
    const type = createOptions.options[kType3];
    if (!kExtensionValues.includes(type)) {
        throw new Error(`The type ${type} isn't valid. Expected one of ${kExtensionValues.join(", ")}`);
    }
    const subType = createOptions.options[kSubType];
    const subTypes = kExtensionSubtypes[type];
    if (subTypes && !subTypes.includes(subType)) {
        throw new Error(`The sub type ${subType} isn't valid. Expected one of ${subTypes.join(", ")}`);
    }
    const template = createOptions.options[kSubType] ? `${createOptions.options[kType3]}:${createOptions.options[kSubType]}` : createOptions.options[kType3];
    return {
        displayType: "extension",
        name: createOptions.options[kName1],
        directory: join2(createOptions.cwd, createOptions.options[kName1]),
        template
    };
}
function nextPrompt(createOptions) {
    if (!createOptions.options[kType3]) {
        return {
            name: kType3,
            message: "Type",
            type: Select,
            options: kExtensionTypes.map((t)=>{
                if (t === "---") {
                    return Select.separator("--------");
                } else {
                    return t;
                }
            })
        };
    }
    const subTypes = kExtensionSubtypes[createOptions.options[kType3]];
    if (!createOptions.options[kSubType] && subTypes && subTypes.length > 0) {
        return {
            name: kSubType,
            message: "Base Format",
            type: Select,
            options: subTypes.map((t)=>{
                return {
                    name: t,
                    value: t
                };
            })
        };
    }
    if (!createOptions.options[kName1]) {
        return {
            name: kName1,
            message: "Extension Name",
            type: Input
        };
    }
}
function typeFromTemplate(template) {
    return template.split(":")[0];
}
async function createArtifact(createDirective, quiet) {
    const createType = typeFromTemplate(createDirective.template);
    const extType = kExtensionTypes.find((type)=>{
        if (typeof type === "object") {
            return type.value === createType;
        } else {
            return false;
        }
    });
    if (!extType) {
        throw new Error(`Unrecognized extension type ${createType}`);
    }
    const openfiles = extType ? extType.openfiles : [];
    await createExtension(createDirective, quiet);
    return {
        path: createDirective.directory,
        openfiles
    };
}
async function createExtension(createDirective, quiet) {
    const artifact = templateFolder(createDirective);
    const target = createDirective.directory;
    if (existsSync(target)) {
        throw new Error(`The directory ${target} already exists. Quarto extensions must have unique names - please modify the existing extension or use a unique name.`);
    }
    const data = await ejsData(createDirective);
    const filesCreated = renderAndCopyArtifacts(target, artifact, createDirective, data, quiet);
    return filesCreated[0];
}
function templateFolder(createDirective) {
    const basePath = resourcePath(join2("create", "extensions"));
    const artifactFolderName = createDirective.template.replace(":", "-");
    return join2(basePath, artifactFolderName);
}
const kProjectTypes1 = projectTypes();
const kProjectTypeAliases1 = projectTypeAliases();
const kProjectTypesAndAliases1 = [
    ...kProjectTypes1,
    ...kProjectTypeAliases1
];
const kType4 = "type";
const kSubdirectory = "subdirectory";
const kBlogTypeAlias = "blog";
const kConfluenceAlias = "confluence";
const kTypeProj = "project";
const kProjectCreateTypes = [
    ...kProjectTypes1,
    kBlogTypeAlias,
    kConfluenceAlias
];
const kProjectTypeOrder = [
    "default",
    "website",
    kBlogTypeAlias,
    "manuscript",
    "book",
    kConfluenceAlias
];
const projectArtifactCreator = {
    displayName: "Project",
    type: kTypeProj,
    resolveOptions: resolveOptions1,
    finalizeOptions: finalizeOptions1,
    nextPrompt: nextPrompt1,
    createArtifact: createArtifact1
};
function resolveOptions1(args) {
    const typeRaw = args.length > 0 ? args[0] : undefined;
    const directoryRaw = args.length > 1 ? args[1] : undefined;
    const titleRaw = args.length > 2 ? args[2] : undefined;
    const options = {};
    if (typeRaw) {
        if (kProjectCreateTypes.includes(typeRaw)) {
            options[kType4] = typeRaw;
        }
    }
    if (directoryRaw) {
        options[kSubdirectory] = directoryRaw;
    }
    if (titleRaw) {
        options.name = titleRaw;
    }
    return options;
}
function resolveTemplate(type) {
    if (type === "website") {
        return {
            type,
            template: "default"
        };
    } else if (type === kBlogTypeAlias) {
        return {
            type: "website",
            template: "blog"
        };
    } else if (type === "confluence") {
        return {
            type: "default",
            template: kConfluenceAlias
        };
    } else {
        return {
            type
        };
    }
}
function finalizeOptions1(createContext) {
    const typeStr = createContext.options[kType4] || "default";
    const resolved = resolveTemplate(typeStr);
    const subdirectory = createContext.options[kSubdirectory];
    if (!subdirectory) {
        throw new Error("A directory is required for project creation with \`quarto create project\`");
    }
    const directory = join2(createContext.cwd, subdirectory);
    let name = createContext.options.name;
    if (!name) {
        name = defaultName(subdirectory, typeStr);
        warn(`No 'title' for project provided in \`quarto create project\`. Using '${name}' as default.`);
    }
    const template = resolved.template ? `${resolved.type}:${resolved.template}` : resolved.type;
    return {
        displayType: "project",
        name,
        directory,
        template
    };
}
function nextPrompt1(createOptions) {
    if (!createOptions.options[kType4]) {
        const orderedTypes = kProjectCreateTypes.sort((t1, t2)=>{
            if (t1 === t2) {
                return 0;
            } else if (kProjectTypeOrder.indexOf(t1) === -1) {
                return 1;
            } else {
                return kProjectTypeOrder.indexOf(t1) - kProjectTypeOrder.indexOf(t2);
            }
        });
        return {
            name: kType4,
            message: "Type",
            type: Select,
            options: orderedTypes.map((t)=>{
                return {
                    name: t,
                    value: t
                };
            })
        };
    }
    if (!createOptions.options[kSubdirectory]) {
        return {
            name: kSubdirectory,
            message: "Directory",
            type: Input
        };
    }
    if (!createOptions.options.name) {
        return {
            name: "name",
            message: "Title",
            type: Input,
            default: defaultName(createOptions.options[kSubdirectory], createOptions.options[kType4])
        };
    }
}
async function createArtifact1(createDirective, quiet) {
    const dir = createDirective.directory;
    const projectTitle = createDirective.name;
    const directiveType = createDirective.template;
    const { type, template } = parseProjectType(directiveType);
    if (kProjectTypesAndAliases1.indexOf(type) === -1) {
        throw new Error(`Project type must be one of ${kProjectTypes1.join(", ")}, but got "${type}".`);
    }
    const projType = projectType(type);
    if (template && !projType.templates?.includes(template)) {
        if (projType.templates) {
            throw new Error(`Project template must be one of ${projType.templates.join(", ")}, but got "${template}".`);
        } else {
            throw new Error(`The project type ${type} does not support any templates.`);
        }
    }
    await projectCreate({
        dir,
        type: type,
        title: projectTitle,
        scaffold: true,
        engine: kMarkdownEngine,
        template: template,
        quiet
    });
    return {
        path: dir,
        openfiles: type !== "default" ? [
            "index.qmd",
            "_quarto.yml"
        ] : [
            "_quarto.yml"
        ]
    };
}
function defaultName(subdirectory, type) {
    return subdirectory !== "." ? subdirectory : type;
}
const kEditorInfos = [
    vscodeEditorInfo(),
    rstudioEditorInfo()
];
async function scanForEditors(editorInfos, createResult) {
    const editors = [];
    for (const editorInfo of editorInfos){
        const editorPath = await findEditorPath(editorInfo.actions);
        if (editorPath) {
            editors.push({
                id: editorInfo.id,
                name: editorInfo.name,
                open: editorInfo.open(editorPath, createResult),
                inEditor: editorInfo.inEditor
            });
        }
    }
    return editors;
}
function vscodeEditorInfo() {
    const editorInfo = {
        id: "vscode",
        name: "vscode",
        open: (path, createResult)=>{
            const artifactPath = createResult.path;
            const cwd = Deno.statSync(artifactPath).isDirectory ? artifactPath : dirname2(artifactPath);
            return async ()=>{
                const p = Deno.run({
                    cmd: [
                        path,
                        artifactPath
                    ],
                    cwd
                });
                await p.status();
            };
        },
        inEditor: isVSCodeTerminal(),
        actions: []
    };
    if (Deno.build.os === "windows") {
        editorInfo.actions.push({
            action: "which",
            arg: "code.exe"
        });
        const pathActions = windowsAppPaths("Microsoft VS Code", "code.exe").map((path)=>{
            return {
                action: "path",
                arg: path
            };
        });
        editorInfo.actions.push(...pathActions);
    } else if (Deno.build.os === "darwin") {
        editorInfo.actions.push({
            action: "which",
            arg: "code"
        });
        const pathActions = macosAppPaths("Visual Studio Code.app/Contents/Resources/app/bin/code").map((path)=>{
            return {
                action: "path",
                arg: path
            };
        });
        editorInfo.actions.push(...pathActions);
    } else {
        editorInfo.actions.push({
            action: "which",
            arg: "code"
        });
        editorInfo.actions.push({
            action: "path",
            arg: "/snap/bin/code"
        });
    }
    return editorInfo;
}
function rstudioEditorInfo() {
    const editorInfo = {
        id: "rstudio",
        name: "RStudio",
        open: (path, createResult)=>{
            return async ()=>{
                const artifactPath = createResult.path;
                const cwd = Deno.statSync(artifactPath).isDirectory ? artifactPath : dirname2(artifactPath);
                const artifactName = basename2(artifactPath);
                const rProjPath = join2(cwd, `${artifactName}.Rproj`);
                Deno.writeTextFileSync(rProjPath, kRProjContents);
                const cmd = path.endsWith(".app") && Deno.build.os === "darwin" ? [
                    "open",
                    "-na",
                    path,
                    "--args",
                    rProjPath
                ] : [
                    path,
                    rProjPath
                ];
                const p = Deno.run({
                    cmd,
                    cwd
                });
                await p.status();
            };
        },
        inEditor: isRStudioTerminal(),
        actions: []
    };
    const rstudioExe = "rstudio.exe";
    if (Deno.build.os === "windows") {
        editorInfo.actions.push({
            action: "env",
            arg: "RS_RPOSTBACK_PATH",
            filter: (path)=>{
                return join2(dirname2(path), rstudioExe);
            }
        });
        const paths = windowsAppPaths(join2("RStudio", "bin"), rstudioExe).map((path)=>{
            return {
                action: "path",
                arg: path
            };
        });
        editorInfo.actions.push(...paths);
    } else if (Deno.build.os === "darwin") {
        const paths = macosAppPaths("RStudio.app").map((path)=>{
            return {
                action: "path",
                arg: path
            };
        });
        editorInfo.actions.push(...paths);
    } else {
        editorInfo.actions.push({
            action: "env",
            arg: "RS_RPOSTBACK_PATH",
            filter: (path)=>{
                return join2(dirname2(path), rstudioExe);
            }
        });
        editorInfo.actions.push({
            action: "path",
            arg: "/usr/lib/rstudio/bin/rstudio"
        });
        editorInfo.actions.push({
            action: "which",
            arg: "rstudio"
        });
    }
    return editorInfo;
}
const kRProjContents = `Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Knitr
LaTeX: pdfLaTeX`;
async function findEditorPath(actions) {
    for (const action of actions){
        const filter = action.filter || ((path)=>{
            return path;
        });
        switch(action.action){
            case "which":
                {
                    const path = await which(action.arg);
                    if (path) {
                        return filter(path);
                    }
                    break;
                }
            case "path":
                if (existsSync(action.arg)) {
                    return filter(action.arg);
                }
                break;
            case "env":
                {
                    const envValue = Deno.env.get(action.arg);
                    if (envValue) {
                        return filter(envValue);
                    }
                }
        }
    }
    return undefined;
}
function windowsAppPaths(folderName, command) {
    const paths = [];
    const localAppData = Deno.env.get("LOCALAPPDATA");
    if (localAppData) {
        paths.push(join2(localAppData, "Programs", folderName, command));
    }
    const programFiles = Deno.env.get("PROGRAMFILES");
    if (programFiles) {
        paths.push(join2(programFiles, folderName, command));
    }
    const programFilesx86 = Deno.env.get("PROGRAMFILES(X86)");
    if (programFilesx86) {
        paths.push(join2(programFilesx86, folderName, command));
    }
    return paths;
}
function macosAppPaths(appName) {
    const paths = [];
    paths.push(join2("/Applications", appName));
    const home = Deno.env.get("HOME");
    if (home) {
        paths.push(join2(home, "Applications", appName));
    }
    return paths;
}
const kArtifactCreators = [
    projectArtifactCreator,
    extensionArtifactCreator
];
const createCommand = new Command().name("create").description("Create a Quarto project or extension").option("--open [editor:string]", `Open new artifact in this editor (${kEditorInfos.map((info)=>info.id).join(",")})`).option("--no-open", "Do not open in an editor").option("--no-prompt", "Do not prompt to confirm actions").option("--json", "Pass serialized creation options via stdin", {
    hidden: true
}).arguments("[type] [commands...]").action(async (options, type, ...commands)=>{
    if (options.json) {
        await createFromStdin();
    } else {
        const isInteractive = isInteractiveTerminal() && !runningInCI();
        const allowPrompt = isInteractive && !!options.prompt && !options.json;
        const resolved = await resolveArtifact(type, options.prompt);
        const resolvedArtifact = resolved.artifact;
        if (resolvedArtifact) {
            const args = commands;
            const commandOpts = resolvedArtifact.resolveOptions(args);
            const createOptions = {
                cwd: Deno.cwd(),
                options: commandOpts
            };
            if (allowPrompt) {
                let nextPrompt = resolvedArtifact.nextPrompt(createOptions);
                while(nextPrompt !== undefined){
                    if (nextPrompt) {
                        const result1 = await prompt([
                            nextPrompt
                        ]);
                        createOptions.options = {
                            ...createOptions.options,
                            ...result1
                        };
                    }
                    nextPrompt = resolvedArtifact.nextPrompt(createOptions);
                }
            }
            const createDirective = resolvedArtifact.finalizeOptions(createOptions);
            const createResult = await resolvedArtifact.createArtifact(createDirective);
            if (allowPrompt && options.open !== false) {
                const resolvedEditor = await resolveEditor(createResult, typeof options.open === "string" ? options.open : undefined);
                if (resolvedEditor) {
                    resolvedEditor.open();
                }
            }
        }
    }
});
const resolveArtifact = async (type, prompt)=>{
    const findArtifact = (type)=>{
        return kArtifactCreators.find((artifact)=>artifact.type === type && artifact.enabled !== false);
    };
    let artifact = type ? findArtifact(type) : undefined;
    while(artifact === undefined){
        if (!prompt) {
            if (type) {
                throw new Error(`Failed to create ${type} - the type isn't recognized`);
            } else {
                throw new Error(`Creation failed - you must provide a type to create when using '--no-prompt'`);
            }
        }
        if (type) {
            info(`Unknown type ${type} - please select from the following:`);
        }
        type = await promptForType();
        artifact = findArtifact(type);
    }
    return {
        artifact
    };
};
async function promptSelect(message, options) {
    return await Select.prompt({
        message,
        options
    });
}
const promptForType = async ()=>{
    return await promptSelect("Create", kArtifactCreators.map((artifact)=>{
        return {
            name: artifact.displayName.toLowerCase(),
            value: artifact.type
        };
    }));
};
const resolveEditor = async (createResult, editor)=>{
    const editors = await scanForEditors(kEditorInfos, createResult);
    const defaultEditor = editors.find((ed)=>{
        return ed.id === editor;
    });
    if (defaultEditor) {
        return defaultEditor;
    } else {
        const inEditor = editors.find((ed)=>ed.inEditor);
        if (inEditor) {
            return inEditor;
        } else if (editors.length > 0) {
            const editorOptions = editors.map((editor)=>{
                return {
                    name: editor.name.toLowerCase(),
                    value: editor.name
                };
            });
            const options = [
                ...editorOptions,
                {
                    name: "(don't open)",
                    value: "do not open"
                }
            ];
            const name = await promptSelect("Open With", options);
            const selectedEditor = editors.find((edit)=>edit.name === name);
            return selectedEditor;
        } else {
            return undefined;
        }
    }
};
async function createFromStdin() {
    const { value: input } = await readLines(Deno.stdin).next();
    Deno.stdin.close();
    const jsonOptions = JSON.parse(input);
    const type = jsonOptions.type;
    if (!type) {
        throw new Error("The provided json for create artifacts must include a valid type");
    }
    if (!jsonOptions.directive || !jsonOptions.directive.name || !jsonOptions.directive.directory || !jsonOptions.directive.template) {
        throw new Error("The provided json for create artifacts must include a directive with a name, directory, and template.");
    }
    const resolved = await resolveArtifact(type, false);
    const createDirective = jsonOptions.directive;
    const createResult = await resolved.artifact.createArtifact(createDirective, true);
    const resultJSON = JSON.stringify(createResult, undefined);
    Deno.stdout.writeSync(new TextEncoder().encode(resultJSON));
}
function parseCrossrefFlags(options, args) {
    let input, output;
    if (options.input && args[0]) {
        input = args.shift();
    } else if (options.output && args[0]) {
        output = args.shift();
    }
    const argsStack = [
        ...args
    ];
    let arg = argsStack.shift();
    while(arg !== undefined){
        switch(arg){
            case "-i":
            case "--input":
                arg = argsStack.shift();
                if (arg) {
                    input = arg;
                }
                break;
            case "-o":
            case "--output":
                arg = argsStack.shift();
                if (arg) {
                    output = arg;
                }
                break;
            default:
                arg = argsStack.shift();
                break;
        }
    }
    return {
        input,
        output
    };
}
const makeCrossrefCommand = ()=>{
    return new Command().description("Index cross references for content").stopEarly().arguments("[...args]").option("-i, --input", "Use FILE as input (default: stdin).").option("-o, --output", "Write output to FILE (default: stdout).").action(async (options, ...args)=>{
        const flags = parseCrossrefFlags(options, args);
        const getInput = async ()=>{
            if (flags.input) {
                return Deno.readTextFileSync(flags.input);
            } else {
                const stdinContent = await readAll(Deno.stdin);
                return new TextDecoder().decode(stdinContent);
            }
        };
        const getOutputFile = ()=>flags.output || "stdout";
        const input = await getInput();
        const indexingDir = globalTempContext().createDir();
        const indexFile = join2(indexingDir, "index.json");
        Deno.env.set("QUARTO_CROSSREF_INDEX_PATH", indexFile);
        Deno.env.set("QUARTO_CROSSREF_INPUT_TYPE", "qmd");
        const cmd = [
            pandocBinaryPath(),
            "+RTS",
            "-K512m",
            "-RTS"
        ];
        cmd.push(...[
            "--from",
            resourcePath("filters/qmd-reader.lua"),
            "--to",
            "native",
            "--data-dir",
            resourcePath("pandoc/datadir"),
            "--lua-filter",
            resourcePath("filters/quarto-init/quarto-init.lua"),
            "--lua-filter",
            resourcePath("filters/crossref/crossref.lua")
        ]);
        const filterParams = encodeBase64(JSON.stringify({
            ["crossref-index-file"]: "index.json",
            ["crossref-input-type"]: "qmd"
        }));
        const result1 = await execProcess({
            cmd,
            cwd: indexingDir,
            env: {
                "QUARTO_FILTER_PARAMS": filterParams,
                "QUARTO_SHARE_PATH": resourcePath()
            },
            stdout: "piped"
        }, input, undefined, undefined, undefined, 5000);
        if (!result1.success) {
            error("Error running Pandoc: " + result1.stderr);
            throw new Error(result1.stderr);
        }
        const outputFile = getOutputFile();
        if (outputFile === "stdout") {
            Deno.stdout.writeSync(Deno.readFileSync(indexFile));
        } else {
            Deno.writeTextFileSync(outputFile, Deno.readTextFileSync(indexFile));
        }
    });
};
const crossrefCommand = makeCrossrefCommand();
const editorSupportCommand = new Command().name("editor-support").description("Miscellaneous tools to support Quarto editor modes").hidden().command("crossref", crossrefCommand);
function commands() {
    return [
        renderCommand,
        previewCommand,
        serveCommand,
        createCommand,
        makeUseCommand(),
        addCommand1,
        updateCommand,
        removeCommand,
        createProjectCommand,
        convertCommand,
        pandocCommand,
        typstCommand,
        runCommand,
        listCommand,
        installCommand,
        uninstallCommand,
        toolsCommand,
        publishCommand,
        capabilitiesCommand,
        inspectCommand,
        checkCommand,
        buildJsCommand,
        editorSupportCommand
    ];
}
const kDevConfig = "dev-config";
function createDevConfig(deno, deno_dom, pandoc, dartsass, esbuild, typst, scriptDir) {
    const scriptPath = join2(scriptDir, "quarto" + (isWindows3() ? ".cmd" : ""));
    const srcDir = Deno.env.get("QUARTO_SRC_PATH") || join2(quartoConfig.sharePath(), "../../src");
    return {
        deno,
        deno_dom,
        pandoc,
        dartsass,
        esbuild,
        typst,
        script: md5Hash(Deno.readTextFileSync(scriptPath)),
        importMap: md5Hash(Deno.readTextFileSync(join2(srcDir, "import_map.json"))),
        bundleImportMap: md5Hash(Deno.readTextFileSync(join2(srcDir, "resources/vendor/import_map.json")))
    };
}
function readInstalledDevConfig() {
    const binPath = quartoConfig.binPath();
    const configPath = join2(binPath, "..", "config", kDevConfig);
    if (existsSync(configPath)) {
        return JSON.parse(Deno.readTextFileSync(configPath));
    } else {
        return null;
    }
}
function readSourceDevConfig() {
    const rootDir = Deno.env.get("QUARTO_ROOT") || join2(quartoConfig.sharePath(), "../..");
    const configurationScript = join2(rootDir, "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 "";
        }
    };
    return createDevConfig(readConfig("DENO"), readConfig("DENO_DOM"), readConfig("PANDOC"), readConfig("DARTSASS"), readConfig("ESBUILD"), readConfig("TYPST"), quartoConfig.binPath());
}
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.typst === b.typst && a.script == b.script && a.importMap === b.importMap && a.bundleImportMap === b.bundleImportMap;
}
async function reconfigureQuarto(installed, source) {
    if (isWindows3()) {
        error(`Quarto requires reconfiguration to ${reconfigureReason(installed, source)}. Please run \`./configure.cmd\` command.\n`);
        return;
    }
    const configureScript = isWindows3() ? [
        "cmd",
        "/c",
        ".\\configure.cmd"
    ] : [
        "./configure.sh"
    ];
    const quartoDir = normalizePath(join2(quartoConfig.sharePath(), "..", ".."));
    const process = Deno.run({
        cmd: configureScript,
        cwd: quartoDir
    });
    await process.status();
    info("");
    error(`Quarto required reconfiguration to ${reconfigureReason(installed, source)}. Please try command again.\n`);
}
function reconfigureReason(installed, source) {
    const versionMessage = (dep, version)=>{
        return `install ${dep} version ${version}`;
    };
    if (installed === null || installed.deno !== source.deno) {
        return versionMessage("Deno", source.deno);
    } else if (installed.deno_dom !== source.deno_dom) {
        return versionMessage("Deno Dom", source.deno_dom);
    } else if (installed.pandoc !== source.pandoc) {
        return versionMessage("Pandoc", source.pandoc);
    } else if (installed.dartsass !== source.dartsass) {
        return versionMessage("Dart Sass", source.dartsass);
    } else if (installed.esbuild !== source.esbuild) {
        return versionMessage("Esbuild", source.esbuild);
    } else if (installed.typst !== source.typst) {
        return versionMessage("Typst", source.typst);
    } else if (installed.script !== source.script) {
        return "update Quarto wrapper script";
    } else if (installed.importMap !== source.importMap || installed.bundleImportMap !== source.importMap) {
        return "update dev import map";
    }
}
const denoRunHandler = {
    canHandle: (script)=>{
        return [
            ".js",
            ".ts"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, stdin, options)=>{
        const denoDir = initDenoCache();
        options = {
            ...options,
            env: {
                ...options?.env,
                DENO_DIR: denoDir
            }
        };
        const importMap = normalize2(join2(denoDir, "../run_import_map.json"));
        return await execProcess({
            cmd: [
                architectureToolsPath("deno"),
                "run",
                "--import-map",
                importMap,
                "--cached-only",
                "--allow-all",
                "--unstable-ffi",
                script,
                ...args
            ],
            ...options
        }, stdin, undefined, undefined, true);
    }
};
function directoryListing(path) {
    return new Set([
        ...expandGlobSync(path + "/**")
    ].map((x)=>x.path.slice(path.length)));
}
function directoryListingsMatch(path1, path2) {
    const listing1 = directoryListing(path1), listing2 = directoryListing(path2);
    for (const path of listing1){
        if (!listing2.has(path)) {
            return false;
        }
    }
    return true;
}
function initDenoCache() {
    const distDenoStd = resourcePath("deno_std");
    const cacheDenoStd = quartoCacheDir("deno_std");
    const filesDiffer = (file)=>{
        const file1 = join2(distDenoStd, file);
        const file2 = join2(cacheDenoStd, file);
        if (!existsSync(file2)) {
            return true;
        }
        return Deno.readTextFileSync(file1) !== Deno.readTextFileSync(file2);
    };
    const fileList = [
        "deno_std.lock",
        "import_map.json",
        "run_import_map.json"
    ];
    if (fileList.some(filesDiffer) || !directoryListingsMatch(distDenoStd, cacheDenoStd)) {
        removeIfExists(cacheDenoStd);
        copyTo(distDenoStd, cacheDenoStd);
    }
    return join2(cacheDenoStd, "cache");
}
const luaRunHandler = {
    canHandle: (script)=>{
        return [
            ".lua"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, stdin, options)=>{
        if (typeof stdin === "string") {
            throw new Error("Lua run handlers cannot be passed stdin");
        }
        const cmd = [
            pandocBinaryPath(),
            "--from",
            "markdown",
            "--to",
            "plain"
        ];
        cmd.push("--lua-filter", script);
        cmd.push(...args);
        return await execProcess({
            cmd,
            ...options
        }, "");
    }
};
const pythonRunHandler = {
    canHandle: (script)=>{
        return [
            ".py"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, stdin, options)=>{
        return await execProcess({
            cmd: [
                ...await pythonExec(),
                script,
                ...args
            ],
            ...options
        }, stdin);
    }
};
const rRunHandler = {
    canHandle: (script)=>{
        return [
            ".r"
        ].includes(extname2(script).toLowerCase());
    },
    run: async (script, args, stdin, options)=>{
        return await execProcess({
            cmd: [
                await rBinaryPath("Rscript"),
                script,
                ...args
            ],
            ...options
        }, stdin);
    }
};
installRunHandler(denoRunHandler);
installRunHandler(luaRunHandler);
installRunHandler(pythonRunHandler);
installRunHandler(rRunHandler);
function layerQuartoScss(key, dependency, sassLayer, format, darkLayer, darkDefault, loadPaths) {
    const uses = quartoUses();
    const defaults = [
        quartoDefaults(format),
        quartoBootstrapDefaults(format.metadata),
        quartoCopyCodeDefaults()
    ].join("\n");
    const mixins = [
        quartoBootstrapMixins()
    ].join("\n");
    const functions = [
        quartoFunctions(),
        quartoBootstrapFunctions()
    ].join("\n");
    const rules = [
        quartoRules(),
        quartoCopyCodeRules(),
        quartoBootstrapRules(),
        quartoGlobalCssVariableRules(),
        quartoLinkExternalRules(),
        quartoCodeFilenameRules()
    ].join("\n");
    const quartoScss = {
        uses,
        defaults,
        functions,
        mixins,
        rules
    };
    const frameworkFunctions = [
        bootstrapFunctions(),
        sassUtilFunctions("color-contrast.scss")
    ].join("\n");
    const frameworkVariables = [
        bootstrapVariables(),
        pandocVariablesToThemeScss(format.metadata)
    ].join("\n");
    const frameworkMixins = [
        bootstrapMixins(),
        bslibComponentMixins()
    ].join("\n");
    const frameworkRules = [
        bootstrapRules(),
        bslibComponentRules(),
        htmlToolsRules()
    ].join("\n");
    const bootstrapScss = {
        uses: "",
        defaults: frameworkVariables,
        functions: frameworkFunctions,
        mixins: frameworkMixins,
        rules: frameworkRules
    };
    const resolvedLoadPaths = [
        ...loadPaths || [],
        bootstrapResourceDir(),
        bslibResourceDir()
    ];
    return {
        dependency,
        key,
        user: sassLayer,
        quarto: quartoScss,
        framework: bootstrapScss,
        loadPaths: resolvedLoadPaths,
        dark: darkLayer ? {
            user: darkLayer,
            default: darkDefault
        } : undefined,
        attribs: {
            id: "quarto-bootstrap"
        }
    };
}
function resolveBootstrapScss(input, format, sassLayers) {
    const quartoThemesDir = formatResourcePath("html", join2("bootstrap", "themes"));
    const theme = format.metadata[kTheme] || [];
    const [themeSassLayers, defaultDark, loadPaths] = resolveThemeLayer(format, input, theme, quartoThemesDir, sassLayers);
    const sassBundles = [];
    sassBundles.push(layerQuartoScss("quarto-theme", kBootstrapDependencyName, themeSassLayers.light, format, themeSassLayers.dark, defaultDark, loadPaths));
    return sassBundles;
}
function layerTheme(input, themes, quartoThemesDir) {
    let injectedCustomization = false;
    const loadPaths = [];
    const layers = themes.flatMap((theme)=>{
        const isAbs = isAbsolute2(theme);
        const isScssFile = [
            ".scss",
            ".css"
        ].includes(extname2(theme));
        if (isAbs && isScssFile) {
            if (existsSync(theme)) {
                const themeDir = dirname2(theme);
                loadPaths.push(themeDir);
                return sassLayer(theme);
            }
        } else if (isScssFile) {
            const themePath = join2(dirname2(input), theme);
            if (existsSync(themePath)) {
                const themeDir = dirname2(themePath);
                loadPaths.push(themeDir);
                return sassLayer(themePath);
            }
        } else {
            const resolvedThemePath = join2(quartoThemesDir, `${theme}.scss`);
            if (existsSync(resolvedThemePath)) {
                const themeLayer = sassLayer(resolvedThemePath);
                injectedCustomization = true;
                return [
                    themeLayer,
                    quartoBootstrapCustomizationLayer()
                ];
            }
        }
        return {
            uses: "",
            defaults: "",
            functions: "",
            mixins: "",
            rules: ""
        };
    });
    if (!injectedCustomization) {
        layers.unshift(quartoBootstrapCustomizationLayer());
    }
    return {
        layers,
        loadPaths
    };
}
function resolveTextHighlightingLayer(input, format, style) {
    const layer = {
        uses: "",
        defaults: "",
        functions: "",
        mixins: "",
        rules: ""
    };
    const themeDescriptor = readHighlightingTheme(dirname2(input), format.pandoc, style);
    if (format.metadata[kCodeBlockBackground] === undefined) {
        if (themeDescriptor && !themeDescriptor.isAdaptive) {
            const backgroundColor = ()=>{
                if (themeDescriptor.json["background-color"]) {
                    return themeDescriptor.json["background-color"];
                } else {
                    const editorColors = themeDescriptor.json["editor-colors"];
                    if (editorColors && editorColors["BackgroundColor"]) {
                        return editorColors["BackgroundColor"];
                    } else {
                        return undefined;
                    }
                }
            };
            const background = backgroundColor();
            if (background) {
                layer.defaults = outputVariable(sassVariable("code-block-bg", asCssColor(background)), true);
            }
            const textColor = themeDescriptor.json["text-color"];
            if (textColor) {
                layer.defaults = layer.defaults + "\n" + outputVariable(sassVariable("code-block-color", asCssColor(textColor)), true);
            }
        }
    }
    if (themeDescriptor) {
        const readTextColor = (name)=>{
            const textStyles = themeDescriptor.json["text-styles"];
            if (textStyles && typeof textStyles === "object") {
                const commentColor = textStyles[name];
                if (commentColor && typeof commentColor === "object") {
                    const textColor = commentColor["text-color"];
                    return textColor;
                } else {
                    return undefined;
                }
            } else {
                return undefined;
            }
        };
        const commentColor = readTextColor("Comment");
        if (commentColor) {
            layer.defaults = layer.defaults + "\n" + outputVariable(sassVariable("btn-code-copy-color", asCssColor(commentColor)), true);
        }
        const functionColor = readTextColor("Function");
        if (functionColor) {
            layer.defaults = layer.defaults + "\n" + outputVariable(sassVariable("btn-code-copy-color-active", asCssColor(functionColor)), true);
        }
    }
    return layer;
}
function resolveThemeLayer(format, input, themes, quartoThemesDir, sassLayers) {
    let theme = undefined;
    let defaultDark = false;
    if (typeof themes === "string") {
        theme = {
            light: [
                themes
            ]
        };
    } else if (Array.isArray(themes)) {
        theme = {
            light: themes
        };
    } else if (typeof themes === "object") {
        const themeArr = (theme)=>{
            const themes = [];
            if (theme) {
                if (typeof theme === "string") {
                    themes.push(theme);
                } else if (Array.isArray(theme)) {
                    themes.push(...theme);
                }
            }
            return themes;
        };
        const themeObj = themes;
        const keyList = Object.keys(themeObj);
        defaultDark = keyList.length > 1 && keyList[0] === "dark";
        theme = {
            light: themeArr(themeObj.light),
            dark: themeObj.dark ? themeArr(themeObj.dark) : undefined
        };
    } else {
        theme = {
            light: []
        };
    }
    const lightLayerContext = layerTheme(input, theme.light, quartoThemesDir);
    lightLayerContext.layers.unshift(...sassLayers);
    const highlightingLayer = resolveTextHighlightingLayer(input, format, "light");
    if (highlightingLayer) {
        lightLayerContext.layers.unshift(highlightingLayer);
    }
    const darkLayerContext = theme.dark ? layerTheme(input, theme.dark, quartoThemesDir) : undefined;
    if (darkLayerContext) {
        darkLayerContext.layers.push(...sassLayers);
        const darkHighlightingLayer = resolveTextHighlightingLayer(input, format, "dark");
        if (darkHighlightingLayer) {
            darkLayerContext.layers.unshift(darkHighlightingLayer);
        }
    }
    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, name, value, formatter)=>{
        if (value) {
            const sassVar = sassVariable(name, 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);
    });
    const gridObj = metadata[kGrid];
    if (gridObj) {
        add(explicitVars, "grid-sidebar-width", gridObj["sidebar-width"]);
        add(explicitVars, "grid-margin-width", gridObj["margin-width"]);
        add(explicitVars, "grid-body-width", gridObj["body-width"]);
        add(explicitVars, "grid-column-gutter-width", gridObj["gutter-width"]);
    }
    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 kTogglePosition = "toggle-position";
const kColor = "color";
const kBorder = "border";
const quartoBootstrapDefaults = (metadata)=>{
    const varFilePath = formatResourcePath("html", join2("bootstrap", "_bootstrap-variables.scss"));
    const variables = [
        Deno.readTextFileSync(varFilePath)
    ];
    const colorDefaults = [];
    const navbar = metadata[kWebsite]?.[kSiteNavbar];
    if (navbar && typeof navbar === "object") {
        const navbarBackground = navbar[kBackground];
        if (navbarBackground !== undefined) {
            resolveBootstrapColorDefault(navbarBackground, colorDefaults);
            variables.push(outputVariable(sassVariable("navbar-bg", navbarBackground, typeof navbarBackground === "string" ? asBootstrapColor : undefined)));
        }
        const navbarForeground = navbar[kForeground];
        if (navbarForeground !== undefined) {
            resolveBootstrapColorDefault(navbarForeground, colorDefaults);
            variables.push(outputVariable(sassVariable("navbar-fg", navbarForeground, typeof navbarForeground === "string" ? asBootstrapColor : undefined)));
        }
        const navbarTogglePosition = navbar[kTogglePosition];
        if (navbarTogglePosition !== undefined) {
            variables.push(outputVariable(sassVariable("navbar-toggle-position", navbarTogglePosition)));
        }
    }
    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) {
            resolveBootstrapColorDefault(sidebarBackground, colorDefaults);
            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) {
            resolveBootstrapColorDefault(sidebarForeground, colorDefaults);
            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) {
            resolveBootstrapColorDefault(footerBg, colorDefaults);
            variables.push(outputVariable(sassVariable("footer-bg", footerBg, typeof footerBg === "string" ? asBootstrapColor : undefined)));
        }
        const footerFg = footer[kForeground];
        if (footerFg !== undefined) {
            resolveBootstrapColorDefault(footerFg, colorDefaults);
            variables.push(outputVariable(sassVariable("footer-fg", footerFg, typeof footerFg === "string" ? asBootstrapColor : undefined)));
        }
        const footerBorder = footer[kBorder];
        const showBorder = footerBorder !== undefined ? footerBorder : sidebar?.style === "docked";
        if (showBorder) {
            variables.push(outputVariable(sassVariable("footer-border", true)));
        }
        if (footerBorder !== undefined && typeof footerBorder === "string") {
            resolveBootstrapColorDefault(footerBorder, colorDefaults);
            variables.push(outputVariable(sassVariable("footer-border-color", footerBorder, asBootstrapColor)));
        }
        const footerColor = footer[kColor];
        if (footerColor && typeof footerColor === "string") {
            resolveBootstrapColorDefault(footerColor, colorDefaults);
            variables.push(outputVariable(sassVariable("footer-color", footerColor, asBootstrapColor)));
        }
    }
    const codeblockLeftBorder = metadata[kCodeBorderLeft];
    const codeblockBackground = metadata[kCodeBlockBackground];
    if (codeblockLeftBorder !== undefined) {
        resolveBootstrapColorDefault(codeblockLeftBorder, colorDefaults);
        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)));
    }
    colorDefaults.forEach((colorDefault)=>{
        variables.push(colorDefault);
    });
    return variables.reverse().join("\n");
};
function resolveBootstrapColorDefault(value, variables) {
    if (value) {
        const variable = bootstrapColorDefault(value);
        if (variable && !variables.find((existingVar)=>{
            return existingVar === variable;
        })) {
            variables.unshift(variable);
        }
    }
}
function bootstrapColorDefault(value) {
    if (typeof value === "string") {
        return bootstrapColorVars[value];
    }
}
const bootstrapColorVars = {
    primary: "$primary: #0d6efd !default;",
    secondary: "$secondary: #6c757d !default;",
    success: "$success: #198754 !default;",
    info: "$info: #0dcaf0 !default;",
    warning: "$warning: #ffc107 !default;",
    danger: "$danger: #dc3545 !default;",
    light: "$light: #f8f9fa !default;",
    dark: "$dark: #212529 !default;"
};
const kAppendixCreativeCommonsLic = [
    "CC BY",
    "CC BY-SA",
    "CC BY-ND",
    "CC BY-NC",
    "CC BY-NC-SA",
    "CC BY-NC-ND"
];
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, inputTraits, format, flags, doc, offset) {
    if (format.metadata.book || format.metadata[kAppendixStyle] === false || format.metadata[kAppendixStyle] === "none") {
        return;
    }
    const appendixStyle = parseStyle(format.metadata[kAppendixStyle]);
    let mainEl = doc.querySelector("main.content");
    if (mainEl === null) {
        mainEl = doc.querySelector("#quarto-content");
    }
    if (mainEl === null) {
        mainEl = doc.querySelector(".page-layout-custom");
    }
    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, title)=>{
            const containerEl = doc.createElement("SECTION");
            containerEl.classList.add(kAppendixContentsClass);
            fn(containerEl);
            if (title) {
                insertTitle(doc, containerEl, title, 2, headingClasses);
            }
            appendixSections.push(containerEl);
        };
        if (!hasMarginCites(format) && !inputTraits[kPositionedRefs]) {
            const refsEl = doc.getElementById("refs");
            if (refsEl) {
                const findRefTitle = (refsEl)=>{
                    const parentEl = refsEl.parentElement;
                    if (parentEl && parentEl.tagName === "SECTION" && parentEl.childElementCount === 2) {
                        const headingEl = parentEl.querySelector("h1, h2, h3, h4, h5, h6");
                        if (headingEl) {
                            headingEl.remove();
                            return headingEl.innerText;
                        }
                    }
                };
                const existingTitle = findRefTitle(refsEl);
                addSection((sectionEl)=>{
                    sectionEl.setAttribute("role", "doc-bibliography");
                    sectionEl.id = "quarto-bibliography";
                    sectionEl.appendChild(refsEl);
                    if (existingTitle) {
                        insertTitle(doc, sectionEl, existingTitle, 2, headingClasses);
                    } else {
                        insertReferencesTitle(doc, sectionEl, format.language, 2, headingClasses);
                    }
                });
            }
        }
        if (!hasMarginRefs(format, flags)) {
            const footnoteEls = doc.querySelectorAll('section[role="doc-endnotes"]');
            if (footnoteEls && footnoteEls.length === 1) {
                const footnotesEl = footnoteEls.item(0);
                footnotesEl.tagName = "SECTION";
                insertFootnotesTitle(doc, footnotesEl, format.language, 2, headingClasses);
                appendixSections.push(footnotesEl);
            }
        }
        if (format.metadata[kLicense]) {
            addSection((sectionEl)=>{
                const contentsDiv = doc.createElement("DIV");
                sectionEl.id = "quarto-reuse";
                contentsDiv.classList.add(kAppendixContentsClass);
                const normalizedLicense = (license)=>{
                    if (typeof license === "string") {
                        const creativeCommons = creativeCommonsLicense(license);
                        if (creativeCommons) {
                            const licenseUrlInfo = creativeCommonsUrl(creativeCommons.base, format.metadata[kLang], creativeCommons.version);
                            return licenseUrlInfo;
                        } else {
                            return {
                                text: license
                            };
                        }
                    } else {
                        const licenseObj = license;
                        return {
                            text: licenseObj.text,
                            url: licenseObj.url,
                            type: licenseObj.type,
                            inlineLink: false
                        };
                    }
                };
                const normalizedLicenses = (licenses)=>{
                    if (Array.isArray(licenses)) {
                        return licenses.map((license)=>{
                            return normalizedLicense(license);
                        });
                    } else {
                        return [
                            normalizedLicense(licenses)
                        ];
                    }
                };
                const license = format.metadata[kLicense];
                const normalized = normalizedLicenses(license);
                for (const normalLicense of normalized){
                    const licenseEl = doc.createElement("DIV");
                    if (normalLicense.url && normalLicense.inlineLink) {
                        const linkEl = doc.createElement("A");
                        linkEl.innerText = normalLicense.text;
                        linkEl.setAttribute("rel", "license");
                        linkEl.setAttribute("href", normalLicense.url);
                        licenseEl.appendChild(linkEl);
                    } else {
                        licenseEl.innerText = normalLicense.text;
                        if (normalLicense.url) {
                            const linkEl = doc.createElement("A");
                            linkEl.innerText = `(${format.language[kAppendixViewLicense] || "View License"})`;
                            linkEl.setAttribute("rel", "license");
                            linkEl.setAttribute("href", normalLicense.url);
                            licenseEl.appendChild(linkEl);
                        }
                    }
                    contentsDiv.appendChild(licenseEl);
                }
                sectionEl.appendChild(contentsDiv);
            }, format.language[kSectionTitleReuse] || "Reuse");
        }
        if (format.metadata[kCopyright]) {
            const normalizedCopyright = (copyright)=>{
                if (typeof copyright === "string") {
                    return copyright;
                } else if (copyright) {
                    return copyright.statement;
                }
            };
            const copyrightRaw = format.metadata[kCopyright];
            const copyright = normalizedCopyright(copyrightRaw);
            if (copyright) {
                addSection((sectionEl)=>{
                    const contentsDiv = doc.createElement("DIV");
                    sectionEl.id = "quarto-copyright";
                    contentsDiv.classList.add(kAppendixContentsClass);
                    const licenseEl = doc.createElement("DIV");
                    licenseEl.innerText = copyright;
                    contentsDiv.appendChild(licenseEl);
                    sectionEl.appendChild(contentsDiv);
                }, format.language[kSectionTitleCopyright] || "Copyright");
            }
        }
        if (format.metadata[kCitation]) {
            const cite = await generateCite(input, format, offset);
            if (cite?.bibtex || cite?.html) {
                addSection((sectionEl)=>{
                    const contentsDiv = doc.createElement("DIV");
                    sectionEl.appendChild(contentsDiv);
                    sectionEl.id = "quarto-citation";
                    if (cite?.bibtex) {
                        const bibTexLabelEl = doc.createElement("DIV");
                        bibTexLabelEl.classList.add(kQuartoSecondaryLabelClass);
                        bibTexLabelEl.innerText = format.language[kAppendixAttributionBibTex] || "BibLaTeX citation";
                        contentsDiv.appendChild(bibTexLabelEl);
                        const bibTexDiv = createCodeBlock(doc, cite.bibtex, "bibtex");
                        bibTexDiv.classList.add(kQuartoCiteBibtexClass);
                        contentsDiv.appendChild(bibTexDiv);
                        const copyButton = createCodeCopyButton(doc, format);
                        bibTexDiv.appendChild(copyButton);
                    }
                    if (cite?.html) {
                        const citeLabelEl = doc.createElement("DIV");
                        citeLabelEl.classList.add(kQuartoSecondaryLabelClass);
                        citeLabelEl.innerText = format.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);
                        }
                    }
                }, format.language[kSectionTitleCitation] || "Citation");
            }
        }
        const appendixSectionNodes = doc.querySelectorAll("section.appendix");
        const appendixSectionEls = [];
        for (const appendixSectionNode of appendixSectionNodes){
            const appendSectionEl = appendixSectionNode;
            if (appendSectionEl) {
                if (appendSectionEl.id) {
                    const selector = `#TOC a[href="#${appendSectionEl.id}"]`;
                    const tocEl = doc.querySelector(selector);
                    if (tocEl && tocEl.parentElement) {
                        tocEl.parentElement.remove();
                    }
                }
                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;
                        if (appendSectionEl.id) {
                            h2.classList.add("anchored");
                        }
                        return h2;
                    } else {
                        const h2 = doc.createElement("h2");
                        return h2;
                    }
                };
                const headerEl = extractHeaderEl();
                headerEl.classList.add(kAppendixHeadingClass);
                const containerDivEl = doc.createElement("DIV");
                containerDivEl.classList.add(kAppendixContentsClass);
                while(appendSectionEl.childNodes.length > 0){
                    containerDivEl.appendChild(appendSectionEl.childNodes[0]);
                }
                appendSectionEl.appendChild(headerEl);
                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);
        }
    }
}
const kCiteAsStyleBibtex = "bibtex";
const kCiteAsStyleDisplay = "display";
function citeStyleTester(format) {
    const citeStyle = format.metadata[kAppendixCiteAs];
    const resolvedStyles = [];
    if (citeStyle === undefined || citeStyle === true) {
        resolvedStyles.push(...[
            kCiteAsStyleDisplay,
            kCiteAsStyleBibtex
        ]);
    } else {
        if (Array.isArray(citeStyle)) {
            resolvedStyles.push(...citeStyle);
        } else {
            resolvedStyles.push(citeStyle);
        }
    }
    return {
        hasCiteAs: ()=>{
            return resolvedStyles.length > 0;
        },
        hasCiteAsStyle: (style)=>{
            return resolvedStyles.includes(style);
        }
    };
}
function parseStyle(style) {
    switch(style){
        case "plain":
            return "plain";
        default:
            return kStyleDefault;
    }
}
const kCcPattern = /(CC BY[^\s]*)\s*(\S*)/;
function creativeCommonsLicense(license) {
    if (license) {
        const match = license.toUpperCase().match(kCcPattern);
        if (match) {
            const base = match[1];
            const version = match[2];
            if (kAppendixCreativeCommonsLic.includes(base)) {
                return {
                    base: base,
                    version: version || "4.0"
                };
            } else {
                return undefined;
            }
        } else {
            return undefined;
        }
    } else {
        return undefined;
    }
}
function creativeCommonsUrl(license, lang, version) {
    const licenseType = license.substring(3);
    if (lang && lang !== "en") {
        return {
            url: `https://creativecommons.org/licenses/${licenseType.toLowerCase()}/${version}/deed.${lang.toLowerCase().replace("-", "_")}`,
            text: `CC ${licenseType} ${version}`,
            inlineLink: true
        };
    } else {
        return {
            url: `https://creativecommons.org/licenses/${licenseType.toLowerCase()}/${version}/`,
            text: `CC ${licenseType} ${version}`,
            inlineLink: true
        };
    }
}
async function generateCite(input, format, offset) {
    const citeStyle = citeStyleTester(format);
    if (citeStyle.hasCiteAs()) {
        const { csl } = documentCSL(input, format.metadata, "webpage", format.pandoc["output-file"], offset);
        if (csl) {
            const cslPath = getCSLPath(input, format);
            return {
                html: citeStyle.hasCiteAsStyle(kCiteAsStyleDisplay) ? await renderHtml(csl, cslPath) : undefined,
                bibtex: citeStyle.hasCiteAsStyle(kCiteAsStyleBibtex) ? await renderBibTex(csl) : undefined
            };
        } else {
            return undefined;
        }
    } else {
        return {};
    }
}
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;
    }
}
const notebookPreviewer = (nbView, format, services, project)=>{
    const isBook = projectIsBook(project);
    const previewQueue = [];
    const outputDir = project?.config?.project["output-dir"];
    const nbDescriptors = {};
    if (nbView) {
        if (typeof nbView !== "boolean") {
            asArray(nbView).forEach((view)=>{
                const existingView = nbDescriptors[view.notebook];
                nbDescriptors[view.notebook] = {
                    ...existingView,
                    ...view
                };
            });
        }
    }
    const descriptor = (notebook)=>{
        return nbDescriptors[notebook];
    };
    const enQueuePreview = (input, nbAbsPath, title, order, callback)=>{
        if (!previewQueue.find((work)=>{
            return work.nbPath === nbAbsPath;
        })) {
            previewQueue.push({
                input,
                nbPath: nbAbsPath,
                title: title,
                callback,
                order
            });
        }
    };
    const renderPreviews = async (output, quiet)=>{
        const rendered = {};
        const nbOptions = format.metadata[kNotebookPreviewOptions];
        const notebookPaths = previewQueue.map((work)=>work.nbPath);
        const uniquePaths = __VIRTUAL_FILE181(notebookPaths);
        const toRenderPaths = uniquePaths.filter((nbPath)=>{
            return services.notebook.get(nbPath, project) === undefined;
        });
        const haveRenderedPaths = [];
        if (toRenderPaths.length > 0 && !quiet) {
            logProgress(`Rendering notebook previews`);
        }
        const total = previewQueue.length;
        let renderCount = 0;
        for(let i1 = 0; i1 < total; i1++){
            const work = previewQueue[i1];
            const { nbPath, input, title } = work;
            if (toRenderPaths.includes(nbPath) && !haveRenderedPaths.includes(nbPath) && !quiet) {
                logProgress(`[${++renderCount}/${toRenderPaths.length}] ${basename2(nbPath)}`);
                haveRenderedPaths.push(nbPath);
            }
            const nbDir = dirname2(nbPath);
            const filename = basename2(nbPath);
            const inputDir = dirname2(input);
            if (nbView !== false) {
                const descriptor = nbDescriptors[relative2(dirname2(input), nbPath)];
                const nbAbsPath = isAbsolute2(nbPath) ? nbPath : join2(inputDir, nbPath);
                const nbContext = services.notebook;
                const notebook = nbContext.get(nbAbsPath, project);
                const resolvedTitle = descriptor?.title || title || notebook?.metadata?.title || basename2(nbAbsPath);
                const notebookIsQmd = !nbAbsPath.endsWith(".ipynb");
                if (!notebook || !notebook[kHtmlPreview] || !notebook[kRenderedIPynb]) {
                    if ((!notebook || !notebook[kRenderedIPynb]) && !descriptor?.[kDownloadUrl] && !isBook && !notebookIsQmd) {
                        const renderedIpynb = await nbContext.render(nbAbsPath, format, kRenderedIPynb, services, {
                            title: resolvedTitle,
                            filename: basename2(nbAbsPath)
                        }, project);
                        if (renderedIpynb && (!project || !outputDir)) {
                            nbContext.preserve(nbAbsPath, kRenderedIPynb);
                        }
                    }
                    if (!notebook || !notebook[kHtmlPreview]) {
                        const backHref = nbOptions && nbOptions.back && output ? relative2(dirname2(nbAbsPath), output) : undefined;
                        let downloadHref = basename2(nbAbsPath);
                        let downloadFileName = basename2(nbAbsPath);
                        if (notebook && notebook[kRenderedIPynb] && !notebookIsQmd) {
                            downloadHref = relative2(dirname2(nbAbsPath), notebook[kRenderedIPynb].hrefPath);
                            downloadFileName = basename2(notebook[kRenderedIPynb].hrefPath);
                        }
                        const htmlPreview = await nbContext.render(nbAbsPath, format, kHtmlPreview, services, {
                            title: resolvedTitle,
                            filename: basename2(nbAbsPath),
                            backHref,
                            downloadHref,
                            downloadFile: downloadFileName
                        }, project);
                        if (htmlPreview && (!project || !outputDir)) {
                            nbContext.preserve(nbAbsPath, kHtmlPreview);
                        }
                    }
                }
                const renderedNotebook = nbContext.get(nbAbsPath, project);
                if (!renderedNotebook || !renderedNotebook[kHtmlPreview]) {
                    throw new InternalError("We just ensured that notebooks had rendered previews, but the preview then didn't exist.");
                }
                const supporting = [];
                const resources = [];
                if (renderedNotebook[kRenderedIPynb]) {
                    const renderedIpynb = renderedNotebook[kRenderedIPynb];
                    if (renderedIpynb) {
                        if (project) {
                            supporting.push(relative2(project.dir, renderedIpynb.hrefPath));
                        } else {
                            supporting.push(renderedIpynb.hrefPath);
                        }
                        supporting.push(...renderedIpynb.supporting);
                        resources.push(...renderedIpynb.resourceFiles.files);
                    }
                }
                if (renderedNotebook[kHtmlPreview]) {
                    const htmlPreview = renderedNotebook[kHtmlPreview];
                    if (htmlPreview) {
                        if (project) {
                            supporting.push(relative2(project.dir, htmlPreview.hrefPath));
                        } else {
                            supporting.push(htmlPreview.hrefPath);
                        }
                        supporting.push(...htmlPreview.supporting);
                        resources.push(...htmlPreview.resourceFiles.files);
                    }
                }
                const nbPreview = {
                    title: resolvedTitle,
                    href: relative2(inputDir, renderedNotebook[kHtmlPreview].hrefPath),
                    supporting,
                    resources,
                    order: work.order
                };
                rendered[work.nbPath] = nbPreview;
                if (work.callback) {
                    work.callback(nbPreview);
                }
            } else {
                const nbPreview = {
                    href: pathWithForwardSlashes(join2(nbDir, filename)),
                    title: title || filename,
                    filename,
                    order: work.order
                };
                rendered[work.nbPath] = nbPreview;
                if (work.callback) {
                    work.callback(nbPreview);
                }
            }
        }
        return rendered;
    };
    return {
        enQueuePreview,
        renderPreviews,
        descriptor
    };
};
const kQuartoNbClass = "quarto-notebook";
const kQuartoCellContainerClass = "cell-container";
const kQuartoCellDecoratorClass = "cell-decorator";
function notebookViewPostProcessor() {
    return (doc)=>{
        doc.body.classList.add(kQuartoNbClass);
        const cells = doc.querySelectorAll("div.cell");
        let cellCount = 0;
        for (const cell of cells){
            const cellEl = cell;
            const count = cellEl.getAttribute("data-execution_count") || ++cellCount;
            const isMarkdown = cellEl.classList.contains("markdown");
            const hasCodeFolding = cellEl.querySelector("details.code-fold") !== null;
            if (!isMarkdown) {
                const containerNode = doc.createElement("div");
                containerNode.classList.add(kQuartoCellContainerClass);
                containerNode.classList.add("column-page-left");
                if (hasCodeFolding) {
                    containerNode.classList.add("code-fold");
                }
                const decoratorNode = doc.createElement("div");
                decoratorNode.classList.add(kQuartoCellDecoratorClass);
                const contentsEl = doc.createElement("pre");
                contentsEl.appendChild(doc.createTextNode(`In [${count}]:`));
                decoratorNode.appendChild(contentsEl);
                containerNode.appendChild(decoratorNode);
                const prevSibling = cellEl.previousElementSibling;
                if (prevSibling && prevSibling.tagName === "DIV" && prevSibling.classList.contains("cell-code")) {
                    cell.parentElement?.insertBefore(containerNode, cell);
                    const wrapperDiv = doc.createElement("div");
                    containerNode.appendChild(wrapperDiv);
                    wrapperDiv.appendChild(prevSibling.cloneNode(true));
                    prevSibling.remove();
                    wrapperDiv.appendChild(cell);
                } else {
                    cell.parentElement?.insertBefore(containerNode, cell);
                    containerNode.appendChild(cell);
                }
            }
        }
        const resources = [];
        const supporting = [];
        return Promise.resolve({
            resources,
            supporting
        });
    };
}
async function emplaceNotebookPreviews(input, doc, format, services, project, output, quiet) {
    const notebookView = format.render[kNotebookView] ?? true;
    const notebookViewStyle = format.render[kNotebookViewStyle];
    if (notebookViewStyle === "notebook") {
        return {
            resources: [],
            supporting: []
        };
    }
    const isBook = projectIsBook(project);
    if (notebookView !== false && !isBook) {
        const inline = format.render[kNotebookLinks] === "inline" || format.render[kNotebookLinks] === true;
        const global1 = format.render[kNotebookLinks] === "global" || format.render[kNotebookLinks] === true;
        const addInlineLineNotebookLink = inlineLinkGenerator(doc, format);
        const previewer = notebookPreviewer(notebookView, format, services, project);
        const inputNbName = basename2(input);
        if (previewer.descriptor(inputNbName)) {
            const computationalNodes = doc.querySelectorAll("div.cell");
            for (const computationalNode of computationalNodes){
                const computeEl = computationalNode;
                const cellId = computeEl.getAttribute("id");
                previewer.enQueuePreview(input, input, undefined, undefined, (nbPreview)=>{
                    if (inline) {
                        if (!computeEl.parentElement?.classList.contains("quarto-embed-nb-cell")) {
                            addInlineLineNotebookLink(computeEl, nbPreview, cellId);
                        }
                    }
                });
            }
        }
        if (typeof notebookView !== "boolean") {
            const nbs = Array.isArray(notebookView) ? notebookView : [
                notebookView
            ];
            for (const nb of nbs){
                if (nb.url === undefined && inputNbName !== nb.notebook) {
                    const nbAbsPath = isAbsolute2(nb.notebook) ? nb.notebook : join2(dirname2(input), nb.notebook);
                    previewer.enQueuePreview(input, nbAbsPath, nb.title, nb.order);
                }
            }
        }
        const notebookDivNodes = doc.querySelectorAll("[data-notebook]");
        for (const nbDivNode of notebookDivNodes){
            const nbDivEl = nbDivNode;
            const notebookPath = nbDivEl.getAttribute("data-notebook");
            nbDivEl.removeAttribute("data-notebook");
            const notebookCellId = nbDivEl.getAttribute("data-notebook-cellId");
            nbDivEl.removeAttribute("data-notebook-cellId");
            const title = nbDivEl.getAttribute("data-notebook-title");
            nbDivEl.removeAttribute("data-notebook-title");
            if (notebookPath) {
                previewer.enQueuePreview(input, nbAbsPath(input, notebookPath), title === null ? undefined : title, undefined, (nbPreview)=>{
                    if (inline) {
                        addInlineLineNotebookLink(nbDivEl, nbPreview, notebookCellId);
                    }
                });
            }
        }
        const previews = await previewer.renderPreviews(output, quiet);
        const previewNotebooks = Object.values(previews).sort((a, b)=>{
            if (a.order !== undefined && b.order !== undefined) {
                return a.order - b.order;
            } else if (a.order !== undefined && b.order === undefined) {
                return -1;
            } else if (a.order === undefined && b.order !== undefined) {
                return 1;
            } else {
                return a.title.localeCompare(b.title);
            }
        });
        if (global1 && previewNotebooks.length > 0) {
            const containerEl = doc.createElement("div");
            containerEl.classList.add("quarto-alternate-notebooks");
            const heading = doc.createElement("h2");
            if (format.language[kRelatedNotebooksTitle]) {
                heading.innerText = format.language[kRelatedNotebooksTitle];
            }
            containerEl.appendChild(heading);
            const formatList = doc.createElement("ul");
            containerEl.appendChild(formatList);
            __VIRTUAL_FILE210(previewNotebooks, (nbPath)=>{
                return nbPath.href;
            }).forEach((nbPath)=>{
                const li = doc.createElement("li");
                const link = doc.createElement("a");
                link.setAttribute("href", nbPath.href);
                if (nbPath.filename) {
                    link.setAttribute("download", nbPath.filename);
                }
                const icon = doc.createElement("i");
                icon.classList.add("bi");
                icon.classList.add(`bi-journal-code`);
                link.appendChild(icon);
                link.appendChild(doc.createTextNode(nbPath.title));
                li.appendChild(link);
                formatList.appendChild(li);
            });
            let dlLinkTarget = doc.querySelector(`nav[role="doc-toc"]`);
            if (dlLinkTarget === null) {
                dlLinkTarget = doc.querySelector("#quarto-margin-sidebar");
            }
            if (dlLinkTarget) {
                dlLinkTarget.appendChild(containerEl);
            }
        }
        const supporting = [];
        const resources = [];
        for (const notebookPath of Object.keys(previews)){
            const nbPath = previews[notebookPath];
            if (nbPath.supporting) {
                supporting.push(...nbPath.supporting);
            }
            if (nbPath.resources) {
                resources.push(...nbPath.resources.map((file)=>{
                    return project ? relative2(project?.dir, file) : file;
                }));
            }
            resources.push(notebookPath);
        }
        return {
            resources,
            supporting
        };
    }
}
const nbAbsPath = (input, nbPath)=>{
    if (isAbsolute2(nbPath)) {
        return nbPath;
    }
    const inputAbsPath = isAbsolute2(input) ? input : join2(Deno.cwd(), input);
    return join2(dirname2(inputAbsPath), nbPath);
};
const inlineLinkGenerator = (doc, format)=>{
    let count = 1;
    return (nbDivEl, nbPreview, cellId)=>{
        const id = "nblink-" + count++;
        const nbLinkEl = doc.createElement("a");
        nbLinkEl.classList.add("quarto-notebook-link");
        nbLinkEl.setAttribute("id", `${id}`);
        if (nbPreview.filename) {
            nbLinkEl.setAttribute("download", nbPreview.filename);
            nbLinkEl.setAttribute("href", nbPreview.href);
        } else {
            if (cellId) {
                nbLinkEl.setAttribute("href", `${nbPreview.href}#${cellId}`);
            } else {
                nbLinkEl.setAttribute("href", `${nbPreview.href}`);
            }
        }
        nbLinkEl.appendChild(doc.createTextNode(`${format.language[kSourceNotebookPrefix]}: ${nbPreview.title}`));
        const nbParentEl = nbDivEl.parentElement;
        if (nbParentEl?.tagName.toLocaleLowerCase() === "figure") {
            const figCapEl = nbDivEl.parentElement?.querySelector("figcaption");
            if (figCapEl) {
                figCapEl.after(nbLinkEl);
            } else {
                nbDivEl.appendChild(nbLinkEl);
            }
        } else {
            nbDivEl.appendChild(nbLinkEl);
        }
    };
};
function otherFormatLinks(input, format, renderedFormats) {
    const normalizedFormatLinks = (unnormalizedLinks)=>{
        if (typeof unnormalizedLinks === "boolean") {
            return undefined;
        } else if (unnormalizedLinks !== undefined) {
            const linksArr = Array.isArray(unnormalizedLinks) ? unnormalizedLinks : [
                unnormalizedLinks
            ];
            return linksArr;
        } else {
            return undefined;
        }
    };
    const userLinks = normalizedFormatLinks(format.render[kFormatLinks]);
    const filteredFormats = renderedFormats.filter((renderedFormat)=>{
        return !isHtmlOutput(renderedFormat.format.pandoc, true);
    });
    return alternateLinks(input, filteredFormats, userLinks);
}
function alternateLinks(input, formats, userLinks) {
    const alternateLinks = [];
    const alternateLinkForFormat = (renderedFormat, order, title, icon)=>{
        const relPath = isAbsolute2(renderedFormat.path) ? relative2(dirname2(input), renderedFormat.path) : renderedFormat.path;
        return {
            title: `${title || renderedFormat.format.identifier[kDisplayName] || renderedFormat.format.pandoc.to}${renderedFormat.format.identifier[kExtensionName] ? ` (${renderedFormat.format.identifier[kExtensionName]})` : ""}`,
            href: relPath,
            icon: icon || fileBsIconName(renderedFormat.format),
            order,
            dlAttrValue: fileDownloadAttr(renderedFormat.format, renderedFormat.path)
        };
    };
    let count = 1;
    for (const userLink of userLinks || []){
        if (typeof userLink === "string") {
            const renderedFormat = formats.find((f)=>f.format.identifier[kTargetFormat] === userLink);
            if (renderedFormat) {
                alternateLinks.push(alternateLinkForFormat(renderedFormat, count));
            }
        } else {
            const linkObj = userLink;
            if ("format" in linkObj) {
                const thatLink = userLink;
                const rf = formats.find((f)=>f.format.identifier[kTargetFormat] === thatLink.format);
                if (rf) {
                    alternateLinks.push(alternateLinkForFormat(rf, count, thatLink.text, thatLink.icon));
                }
            } else {
                const thisLink = userLink;
                const alternate = {
                    title: thisLink.text,
                    href: thisLink.href,
                    icon: thisLink.icon || fileBsIconForExt(thisLink.href),
                    dlAttrValue: "",
                    order: thisLink.order || count,
                    attr: thisLink.attr
                };
                alternateLinks.push(alternate);
            }
        }
        count++;
    }
    const userLinksHasFormat = userLinks && userLinks.some((link)=>typeof link === "string");
    if (!userLinksHasFormat) {
        formats.forEach((renderedFormat)=>{
            const baseFormat = renderedFormat.format.identifier["base-format"];
            if (!kExcludeFormatUnlessExplicit.includes(baseFormat || "html")) {
                alternateLinks.push(alternateLinkForFormat(renderedFormat, count));
            }
            count++;
        });
    }
    return alternateLinks;
}
const fileBsIconName = (format)=>{
    if (isDocxOutput(format.pandoc)) {
        return "file-word";
    } else if (isPdfOutput(format.pandoc)) {
        return "file-pdf";
    } else if (isTypstOutput(format.pandoc)) {
        return "file-pdf";
    } else if (isIpynbOutput(format.pandoc)) {
        return "journal-code";
    } else if (isMarkdownOutput(format)) {
        return "file-code";
    } else if (isPresentationOutput(format.pandoc)) {
        return "file-slides";
    } else if (isJatsOutput(format.pandoc)) {
        return "filetype-xml";
    } else {
        return "file";
    }
};
const fileDownloadAttr = (format, path)=>{
    if (isIpynbOutput(format.pandoc)) {
        return basename2(path);
    } else if (isJatsOutput(format.pandoc)) {
        return basename2(path);
    } else {
        return undefined;
    }
};
const fileBsIconForExt = (path)=>{
    const ext = extname2(path);
    switch(ext.toLowerCase()){
        case ".docx":
            return "file-word";
        case ".pdf":
            return "file-pdf";
        case ".ipynb":
            return "journal-code";
        case ".md":
            return "file-code";
        case ".xml":
            return "filetype-xml";
        default:
            return "file";
    }
};
const kExcludeFormatUnlessExplicit = [
    "jats"
];
function bootstrapFormatDependency() {
    const boostrapResource = (resource)=>formatResourcePath("html", join2("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 bootstrapExtras(input, flags, format, services, offset, project, quiet) {
    const toc = hasTableOfContents(flags, format);
    const tocLocation = toc ? format.metadata[kTocLocation] || "right" : undefined;
    const renderTemplate = (template, pageLayout)=>{
        return renderEjs(formatResourcePath("html", `templates/${template}`), {
            toc,
            tocLocation,
            pageLayout
        });
    };
    const pageLayout = formatPageLayout(format);
    const bodyEnvelope = formatHasArticleLayout(format) ? {
        before: renderTemplate("before-body-article.ejs", pageLayout),
        afterPreamble: renderTemplate("after-body-article-preamble.ejs", pageLayout),
        afterPostamble: renderTemplate("after-body-article-postamble.ejs", pageLayout)
    } : {
        before: renderTemplate("before-body-custom.ejs", kPageLayoutCustom),
        afterPreamble: renderTemplate("after-body-custom-preamble.ejs", kPageLayoutCustom),
        afterPostamble: renderTemplate("after-body-custom-postamble.ejs", kPageLayoutCustom)
    };
    const { partials, templateParams } = documentTitlePartial(format);
    const sassLayers = [];
    const titleSassLayer = documentTitleScssLayer(format);
    if (titleSassLayer) {
        sassLayers.push(titleSassLayer);
    }
    const includeInHeader = [];
    const titleInclude = documentTitleIncludeInHeader(input, format, services.temp);
    if (titleInclude) {
        includeInHeader.push(titleInclude);
    }
    const titleMetadata = documentTitleMetadata(format);
    const scssBundles = resolveBootstrapScss(input, format, sassLayers);
    return {
        pandoc: {
            [kSectionDivs]: true,
            [kHtmlMathMethod]: "mathjax"
        },
        metadata: {
            [kDocumentCss]: false,
            [kLinkCitations]: true,
            [kTemplatePartials]: partials,
            [kQuartoTemplateParams]: templateParams,
            ...titleMetadata
        },
        [kIncludeInHeader]: includeInHeader,
        html: {
            [kSassBundles]: scssBundles,
            [kDependencies]: [
                bootstrapFormatDependency()
            ],
            [kBodyEnvelope]: bodyEnvelope,
            [kHtmlPostprocessors]: [
                bootstrapHtmlPostprocessor(input, format, flags, services, offset, project, quiet)
            ],
            [kHtmlFinalizers]: [
                bootstrapHtmlFinalizer(format, flags)
            ]
        }
    };
}
const getColumnLayoutElements = (doc)=>{
    return doc.querySelectorAll(kColumnSelector);
};
const removeColumnClasses = (el)=>{
    for (const cls of allColumnClz){
        el.classList.remove(cls);
    }
};
const removeNestedColumnLayouts = (doc)=>{
    const columnNodes = doc.querySelectorAll(kColumnSelector);
    columnNodes.forEach((columnNode)=>{
        const columnEl = columnNode;
        if (isInColumnLayout(columnEl, doc, nonScreenColumnClz)) {
            removeColumnClasses(columnEl);
        }
    });
};
const cleanNonsensicalMarginCaps = (doc)=>{
    const marginCapNodes = doc.querySelectorAll(".margin-caption,.margin-ref");
    marginCapNodes.forEach((capNode)=>{
        const capEl = capNode;
        if (isInColumnLayout(capEl, doc, removeMarginClz)) {
            capEl.classList.remove("margin-caption");
            capEl.classList.remove("margin-ref");
        }
    });
};
const isInColumnLayout = (el, doc, clzList)=>{
    const parent = el.parentElement;
    if (!parent) {
        return false;
    }
    for (const cls of parent.classList){
        if (clzList.includes(cls)) {
            return true;
        }
    }
    return isInColumnLayout(parent, doc, clzList);
};
const kColumnSelector = '[class^="column-"], [class*=" column-"], aside:not(.footnotes):not(.sidebar), [class*="margin-caption"], [class*=" margin-caption"], [class*="margin-ref"], [class*=" margin-ref"]';
function bootstrapHtmlPostprocessor(input, format, flags, services, offset, project, quiet) {
    return async (doc, options)=>{
        const resources = [];
        const supporting = [];
        const title = doc.querySelector("header > .title");
        if (title) {
            title.classList.add("display-7");
        }
        const subtitle = doc.querySelector("header > .subtitle");
        if (subtitle) {
            subtitle.classList.add("lead");
        }
        const blockquotes = doc.querySelectorAll("blockquote");
        for(let i1 = 0; i1 < blockquotes.length; i1++){
            const classList = blockquotes[i1].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 marginImgNodes = doc.querySelectorAll(".column-margin .cell-output-display img:not(.img-fluid)");
        for (const marginImgNode of marginImgNodes){
            const marginImgEl = marginImgNode;
            marginImgEl.classList.add("img-fluid");
        }
        const toc = doc.querySelector('nav[role="doc-toc"]');
        const tocTarget = doc.getElementById("quarto-toc-target");
        const useDoubleToc = format.metadata[kTocLocation]?.includes("-body") ?? false;
        if (toc && tocTarget) {
            if (useDoubleToc) {
                const clonedToc = toc.cloneNode(true);
                clonedToc.id = "TOC-body";
                const tocActionsEl = clonedToc.querySelector(".toc-actions");
                if (tocActionsEl) {
                    tocActionsEl.remove();
                }
                toc.parentElement?.insertBefore(clonedToc, toc);
            }
            toc.classList.add("toc-active");
            const expanded = format.metadata[kTocExpand];
            if (expanded !== undefined) {
                if (expanded === true) {
                    toc.setAttribute("data-toc-expanded", 99);
                } else if (expanded) {
                    toc.setAttribute("data-toc-expanded", expanded);
                } else {
                    toc.setAttribute("data-toc-expanded", -1);
                }
            }
            const tocLinks = doc.querySelectorAll('nav#TOC[role="doc-toc"] > ul a');
            for(let i1 = 0; i1 < tocLinks.length; i1++){
                const tocLink = tocLinks[i1];
                tocLink.classList.add("nav-link");
                if (i1 === 0) {
                    tocLink.classList.add("active");
                }
                if (!tocLink.hasAttribute("data-scroll-target")) {
                    tocLink.setAttribute("data-scroll-target", tocLink.getAttribute("href")?.replaceAll(":", "\\:"));
                }
            }
            const tocDepth = format.pandoc[kTocDepth] || 3;
            if (tocDepth > 1) {
                const ulSelector = "ul ".repeat(tocDepth - 1).trim();
                const nestedUls = toc.querySelectorAll(ulSelector);
                for(let i1 = 0; i1 < nestedUls.length; i1++){
                    const ul = nestedUls[i1];
                    ul.classList.add("collapse");
                }
            }
            toc.remove();
            tocTarget.replaceWith(toc);
        } else {
            tocTarget?.remove();
        }
        if (format.render[kFormatLinks] !== false) {
            processAlternateFormatLinks(input, options, doc, format, resources);
        }
        if (format.render[kNotebookLinks] !== false) {
            const renderedHtml = options.renderedFormats.find((renderedFormat)=>{
                return isHtmlOutput(renderedFormat.format.pandoc, true);
            });
            const notebookResults = await emplaceNotebookPreviews(input, doc, format, services, project, renderedHtml?.path, quiet);
            if (notebookResults) {
                resources.push(...notebookResults.resources);
                supporting.push(...notebookResults.supporting);
            }
        }
        await processOtherLinks(doc, format, project);
        const addTableClasses = (table, computational = false)=>{
            table.classList.add("table");
            if (computational) {
                table.classList.add("table-sm");
                table.classList.add("table-striped");
                table.classList.add("small");
            }
        };
        const tableHeaders = doc.querySelectorAll("tbody > tr:first-child.odd");
        for(let i1 = 0; i1 < tableHeaders.length; i1++){
            const th = tableHeaders[i1];
            if (th.parentNode?.parentNode) {
                const table = th.parentNode.parentNode;
                table.removeAttribute("style");
                addTableClasses(table, !!findParent(table, (el)=>el.classList.contains("cell") && !el.classList.contains("plain")));
            }
        }
        const pandasTables = doc.querySelectorAll("table.dataframe");
        for(let i1 = 0; i1 < pandasTables.length; i1++){
            const table = pandasTables[i1];
            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 dataFramesTables = doc.querySelectorAll("table.data-frame");
        for(let i1 = 0; i1 < dataFramesTables.length; i1++){
            const table = dataFramesTables[i1];
            addTableClasses(table, true);
        }
        const sections = doc.querySelectorAll('section[class^="level"]');
        for(let i1 = 0; i1 < sections.length; i1++){
            const section = sections[i1];
            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 titleResourceFiles = processDocumentTitle(input, format, flags, doc);
        resources.push(...titleResourceFiles);
        if (format.metadata[kAppendixStyle] !== false && format.metadata[kAppendixStyle] !== "none") {
            await processDocumentAppendix(input, options.inputTraits, format, flags, doc, offset);
        }
        return Promise.resolve({
            resources,
            supporting
        });
    };
}
function createLinkChild(formatLink, doc) {
    const link = doc.createElement("a");
    link.setAttribute("href", formatLink.href);
    if (formatLink.attr) {
        for (const key of Object.keys(formatLink.attr)){
            const value = formatLink.attr[key];
            link.setAttribute(key, value);
        }
    }
    if (formatLink.dlAttrValue) {
        link.setAttribute("download", formatLink.dlAttrValue);
    }
    const icon = doc.createElement("i");
    icon.classList.add("bi");
    icon.classList.add(`bi-${formatLink.icon}`);
    link.appendChild(icon);
    link.appendChild(doc.createTextNode(formatLink.title));
    return link;
}
async function processOtherLinks(doc, format, context) {
    const processLinks = (otherLinks, clz, title)=>{
        const dlLinkTarget = getLinkTarget(doc, kLinkProvidersOtherLinks);
        if (otherLinks.length > 0 && dlLinkTarget) {
            const containerEl = doc.createElement("div");
            containerEl.classList.add(clz);
            const heading = dlLinkTarget.makeHeadingEl(title);
            containerEl.appendChild(heading);
            const getAttrs = (otherLink)=>{
                if (otherLink.rel || otherLink.target) {
                    const attrs = {};
                    if (otherLink.rel) {
                        attrs.rel = otherLink.rel;
                    }
                    if (otherLink.target) {
                        attrs.target = otherLink.target;
                    }
                    return attrs;
                } else {
                    return undefined;
                }
            };
            const linkList = dlLinkTarget.makeContainerEl();
            let order = 0;
            for(let i1 = 0; i1 < otherLinks.length; i1++){
                const otherLink = otherLinks[i1];
                const alternateLink = {
                    icon: otherLink.icon || "link-45deg",
                    href: otherLink.href,
                    title: otherLink.text,
                    order: ++order,
                    attr: getAttrs(otherLink)
                };
                const li = dlLinkTarget.makeItemEl(createLinkChild(alternateLink, doc), i1, otherLinks.length);
                if (linkList) {
                    linkList.appendChild(li);
                } else {
                    containerEl.appendChild(li);
                }
            }
            if (linkList) {
                containerEl.appendChild(linkList);
            }
            dlLinkTarget.targetEl.appendChild(containerEl);
        }
    };
    const resolveCodeLinks = async (metadata, context)=>{
        const codeLinks = metadata[kCodeLinks];
        if (codeLinks !== undefined) {
            if (typeof codeLinks === "boolean") {
                return [];
            } else if (typeof codeLinks === "string") {
                if (!context) {
                    throw new Error(`The code-link value '${codeLinks}' is only supported from within a project.`);
                }
                const resolvedCodeLink = await resolveCodeLink(codeLinks, context);
                if (resolvedCodeLink) {
                    return [
                        resolvedCodeLink
                    ];
                } else {
                    throw new Error(`Unknown code-link value '${codeLinks}'`);
                }
            } else {
                const outputLinks = [];
                for (const codeLink of codeLinks){
                    if (typeof codeLink === "string") {
                        if (!context) {
                            throw new Error(`The code-link value '${codeLink}' is only supported from within a project.`);
                        }
                        const resolvedCodeLink = await resolveCodeLink(codeLink, context);
                        if (resolvedCodeLink) {
                            outputLinks.push(resolvedCodeLink);
                        } else {
                            throw new Error(`Unknown code-link value '${codeLink}'`);
                        }
                    } else {
                        outputLinks.push(codeLink);
                    }
                }
                return outputLinks;
            }
        }
        return [];
    };
    const resolveCodeLink = async (link, context)=>{
        if (link === "repo") {
            const env = await context.environment();
            if (env.github.repoUrl) {
                return {
                    icon: "github",
                    text: "GitHub Repo",
                    href: env.github.repoUrl,
                    target: "_blank"
                };
            } else {
                warn("The 'repo' code link is not able to be created as the project isn't a GitHub project.");
            }
        } else if (link === "devcontainer") {
            const env = await context.environment();
            if (env.github.organization && env.github.repository && env.github.repoUrl) {
                const containerUrl = codeSpacesUrl(env.github.repoUrl);
                return {
                    icon: "github",
                    text: format.language[kLaunchDevContainerTitle] || "Launch Dev Container",
                    href: containerUrl,
                    target: "_blank"
                };
            } else {
                warn("The 'devcontainer' code link is not able to be created as the project isn't a GitHub project.");
            }
        } else if (link === "binder") {
            const env = await context.environment();
            if (env.github.organization && env.github.repository) {
                const containerUrl = binderUrl(env.github.organization, env.github.repository, {
                    editor: env.codeEnvironment
                });
                return {
                    icon: "journals",
                    text: format.language[kLaunchBinderTitle] || "Launch Binder",
                    href: containerUrl,
                    target: "_blank"
                };
            } else {
                warn("The 'binder' code link is not able to be created as the project isn't a GitHub project.");
            }
        }
    };
    const codeLinks = await resolveCodeLinks(format.metadata, context);
    const otherLinkOptions = [
        {
            links: format.metadata[kOtherLinks] || [],
            clz: "quarto-other-links",
            title: format.language[kOtherLinksTitle] || "Other Links"
        },
        {
            links: codeLinks,
            clz: "quarto-code-links",
            title: format.language[kCodeLinksTitle] || "Code Links"
        }
    ];
    otherLinkOptions.forEach((linkDesc)=>{
        processLinks(linkDesc.links, linkDesc.clz, linkDesc.title);
    });
}
const bannerHeadingLinkProvider = {
    makeHeadingEl: (doc, text)=>{
        const headingEl = doc.createElement("div");
        headingEl.classList.add("quarto-title-meta-heading");
        if (text) {
            headingEl.innerText = text;
        }
        return headingEl;
    },
    makeContainerEl: (_doc)=>{
        return undefined;
    },
    makeItemEl: (doc, el)=>{
        const itemEl = doc.createElement("div");
        itemEl.classList.add("quarto-title-meta-contents");
        const pEl = doc.createElement("p");
        pEl.appendChild(el);
        itemEl.appendChild(pEl);
        return itemEl;
    }
};
const bannerTextLinkProvider = {
    makeHeadingEl: (doc, text)=>{
        const headingEl = doc.createElement("div");
        headingEl.classList.add("quarto-title-meta-heading");
        if (text) {
            headingEl.innerText = text;
        }
        return headingEl;
    },
    makeContainerEl: (doc)=>{
        const headingEl = doc.createElement("div");
        headingEl.classList.add("quarto-title-meta-contents");
        return headingEl;
    },
    makeItemEl: (doc, el, idx, len)=>{
        const itemEl = doc.createElement("span");
        itemEl.appendChild(el);
        if (idx < len - 1) {
            itemEl.append(doc.createTextNode(","));
            itemEl.setAttribute("style", "padding-right: 0.5em;");
        }
        return itemEl;
    }
};
const kLinkProvidersOtherLinks = {
    "quarto-other-links-target": bannerHeadingLinkProvider,
    "quarto-other-links-text-target": bannerTextLinkProvider
};
const kLinkProvidersOtherFormats = {
    "quarto-other-formats-target": bannerHeadingLinkProvider,
    "quarto-other-formats-text-target": bannerTextLinkProvider
};
function getLinkTarget(doc, linkProviders) {
    if (linkProviders) {
        for (const sel of Object.keys(linkProviders)){
            const explicitTarget = doc.querySelector(`.${sel}`);
            if (explicitTarget !== null) {
                const linkProvider = linkProviders[sel];
                return {
                    targetEl: explicitTarget,
                    makeHeadingEl: (text)=>{
                        return linkProvider.makeHeadingEl(doc, text);
                    },
                    makeContainerEl: ()=>{
                        return linkProvider.makeContainerEl(doc);
                    },
                    makeItemEl: (el, idx, len)=>{
                        return linkProvider.makeItemEl(doc, el, idx, len);
                    }
                };
            }
        }
    }
    let dlLinkTarget = doc.querySelector(`nav[role="doc-toc"]`);
    if (dlLinkTarget === null) {
        dlLinkTarget = doc.getElementById("quarto-sidebar-toc-left");
    }
    if (dlLinkTarget === null) {
        dlLinkTarget = doc.getElementById(kMarginSidebarId1);
    }
    if (dlLinkTarget !== null) {
        return {
            targetEl: dlLinkTarget,
            makeHeadingEl: (text)=>{
                const headingEl = doc.createElement("h2");
                if (text) {
                    headingEl.innerText = text;
                }
                return headingEl;
            },
            makeContainerEl: ()=>{
                return doc.createElement("ul");
            },
            makeItemEl: (el)=>{
                const liEl = doc.createElement("li");
                liEl.appendChild(el);
                return liEl;
            }
        };
    }
}
function processAlternateFormatLinks(input, options, doc, format, resources) {
    if (options.renderedFormats.length > 1) {
        const dlLinkTarget = getLinkTarget(doc, kLinkProvidersOtherFormats);
        if (dlLinkTarget) {
            const containerEl = doc.createElement("div");
            containerEl.classList.add("quarto-alternate-formats");
            const heading = dlLinkTarget.makeHeadingEl(format.language[kRelatedFormatsTitle]);
            containerEl.appendChild(heading);
            const otherLinks = otherFormatLinks(input, format, options.renderedFormats);
            const formatList = dlLinkTarget.makeContainerEl();
            const sortedLinks = otherLinks.sort(({ order: a }, { order: b })=>a - b);
            for(let i1 = 0; i1 < sortedLinks.length; i1++){
                const alternateLink = sortedLinks[i1];
                const link = doc.createElement("a");
                link.setAttribute("href", alternateLink.href);
                if (alternateLink.dlAttrValue) {
                    link.setAttribute("download", alternateLink.dlAttrValue);
                }
                if (alternateLink.attr) {
                    for (const key of Object.keys(alternateLink.attr)){
                        const value = alternateLink.attr[key];
                        link.setAttribute(key, value);
                    }
                }
                const icon = doc.createElement("i");
                icon.classList.add("bi");
                icon.classList.add(`bi-${alternateLink.icon}`);
                link.appendChild(icon);
                link.appendChild(doc.createTextNode(alternateLink.title));
                const li = dlLinkTarget.makeItemEl(link, i1, sortedLinks.length);
                if (formatList) {
                    formatList.appendChild(li);
                } else {
                    containerEl.appendChild(li);
                }
                resources.push(alternateLink.href);
            }
            if (otherLinks.length > 0) {
                if (formatList) {
                    containerEl.appendChild(formatList);
                }
                dlLinkTarget.targetEl.appendChild(containerEl);
            }
        }
    }
}
function bootstrapHtmlFinalizer(format, flags) {
    return (doc)=>{
        const { citesInMargin, refsInMargin } = processColumnElements(doc, format, flags);
        if (format.metadata[kDisableArticleLayout]) {
            const stripColumnClasses = (el)=>{
                const stripClz = [];
                el.classList.forEach((clz)=>{
                    if (clz === "margin-caption" || clz === "margin-ref" || clz.startsWith("column-") || clz === "page-columns" || clz === "page-full") {
                        stripClz.push(clz);
                    }
                });
                el.classList.remove(...stripClz);
                for (const childEl of el.children){
                    stripColumnClasses(childEl);
                }
            };
            const mainEl = doc.body.querySelector("main");
            if (mainEl) {
                stripColumnClasses(mainEl);
            }
        }
        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(format);
        if (fullLayout) {
            const leftSidebar = hasContents(kSidebarId, doc);
            if (!leftSidebar) {
                const sidebarEl = doc.getElementById(kSidebarId);
                sidebarEl?.remove();
            }
            const column = suggestColumn(doc);
            setMainColumn(doc, column);
        }
        const hasToc = !!format.pandoc.toc;
        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 && !hasToc) {
            rightSidebar.remove();
        }
        const gridObj = format.metadata[kGrid];
        let contentMode = "auto";
        if (gridObj) {
            contentMode = gridObj[kContentMode];
        }
        if (contentMode === undefined || contentMode === "auto") {
            const hasColumnElements = getColumnLayoutElements(doc).length > 0;
            if (hasColumnElements) {
                if (hasLeftContent && hasMarginContent) {
                    doc.body.classList.add("slimcontent");
                } else if (hasRightContent || hasMarginContent || fullLayout || hasToc) {} else {
                    doc.body.classList.add("fullcontent");
                }
            } else {
                if (!hasRightContent && !hasMarginContent && !hasToc) {
                    doc.body.classList.add("fullcontent");
                } else {}
            }
        } else {
            if (contentMode === "slim") {
                doc.body.classList.add("slimcontent");
            } else if (contentMode === "full") {
                doc.body.classList.add("fullcontent");
            }
        }
        const isFullLayout = format.metadata[kPageLayout] === "full";
        const marginSidebarEl = doc.getElementById("quarto-margin-sidebar");
        if (!hasMarginContent && isFullLayout && !hasRightContent || marginSidebarEl?.childElementCount === 0) {
            marginSidebarEl?.classList.add("zindex-bottom");
        }
        return Promise.resolve();
    };
}
function processColumnElements(doc, format, flags) {
    removeNestedColumnLayouts(doc);
    cleanNonsensicalMarginCaps(doc);
    if (!formatHasArticleLayout(format)) {
        return {
            citesInMargin: false,
            refsInMargin: false
        };
    }
    processMarginCaptions(doc);
    processMarginElsInCallouts(doc);
    processMarginElsInTabsets(doc);
    processFigureOutputs(doc);
    const marginProcessors = [
        simpleMarginProcessor
    ];
    if (hasMarginFigCaps(format)) {
        marginProcessors.push(figCapInCalloutMarginProcessor);
    }
    const refsInMargin = hasMarginRefs(format, flags);
    if (refsInMargin) {
        marginProcessors.unshift(footnoteMarginProcessor);
    }
    const citesInMargin = hasMarginCites(format);
    if (citesInMargin) {
        marginProcessors.push(referenceMarginProcessor);
    }
    processMarginNodes(doc, marginProcessors);
    if (refsInMargin) {
        const footnoteContainer = doc.getElementById("footnotes");
        if (footnoteContainer) {
            footnoteContainer.remove();
        }
    }
    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("quarto-layout-row") && !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") || el.classList.contains("quarto-layout-panel") || el.classList.contains("quarto-float")) {
        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 processTableMarginCaption = (captionContainer, doc)=>{
    const caption = captionContainer.querySelector("caption");
    if (caption) {
        const marginCapEl = doc.createElement("DIV");
        marginCapEl.classList.add("quarto-table-caption");
        marginCapEl.classList.add("margin-caption");
        marginCapEl.innerHTML = caption.innerHTML;
        captionContainer.parentElement?.insertBefore(marginCapEl, captionContainer.nextElementSibling);
        caption.remove();
        removeCaptionClass(captionContainer);
    }
};
const processMarginCaptions = (doc)=>{
    const captionsAlreadyInMargin = doc.querySelectorAll(".column-margin .margin-caption");
    captionsAlreadyInMargin.forEach((node)=>{
        const el = node;
        el.classList.remove("margin-caption");
    });
    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");
            const explicitCapLoc = captionContainer.getAttribute("data-cap-location");
            if (explicitCapLoc == null || explicitCapLoc == "margin") {
                if (isLayoutPanel) {
                    processLayoutPanelMarginCaption(captionContainer);
                } else {
                    processFigureMarginCaption(captionContainer, doc);
                }
            }
        } else {
            if (figureEl.classList.contains("tbl-parent")) {
                const capDivEl = figureEl.querySelector("div.panel-caption");
                if (capDivEl) {
                    capDivEl.classList.add("margin-caption");
                    capDivEl.remove();
                    figureEl.appendChild(capDivEl);
                }
            } else {
                const table = figureEl.querySelector("table");
                if (table) {
                    processTableMarginCaption(table, doc);
                }
            }
        }
        removeCaptionClass(figureEl);
    });
};
const processMarginElsInCallouts = (doc)=>{
    const calloutNodes = doc.querySelectorAll("div.callout");
    calloutNodes.forEach((calloutNode)=>{
        const calloutEl = calloutNode;
        const collapseEl = calloutEl.querySelector(".callout-collapse");
        const isSimple = calloutEl.classList.contains("callout-style-simple");
        const collapseClasses = [];
        if (collapseEl) {
            collapseEl.classList.forEach((clz)=>collapseClasses.push(clz));
        }
        const marginNodes = calloutEl.querySelectorAll(".callout-body-container .column-margin, .callout-body-container aside:not(.footnotes):not(.sidebar), .callout-body-container .aside:not(.footnotes)");
        if (marginNodes.length > 0) {
            const marginArr = Array.from(marginNodes);
            marginArr.reverse().forEach((marginNode)=>{
                const marginEl = marginNode;
                collapseClasses.forEach((clz)=>{
                    marginEl.classList.add(clz);
                });
                marginEl.classList.add("callout-margin-content");
                if (isSimple) {
                    marginEl.classList.add("callout-margin-content-simple");
                }
                calloutEl.after(marginEl);
            });
        }
    });
};
const figCapInCalloutMarginProcessor = {
    selector: ".callout",
    canProcess (el) {
        const hasFigCap = el.querySelector("figcaption");
        return hasFigCap !== null;
    },
    process (el, doc) {
        const collapseEl = el.querySelector(".callout-collapse");
        const isSimple = el.classList.contains("callout-style-simple");
        const collapseClasses = [];
        if (collapseEl) {
            collapseEl.classList.forEach((clz)=>collapseClasses.push(clz));
        }
        const figNodes = el.querySelectorAll("figure");
        for (const figNode of Array.from(figNodes).reverse()){
            const figEl = figNode;
            const figCaptionEl = figEl.querySelector("figcaption");
            let figureId = figEl.id;
            if (figureId === "") {
                figureId = figEl.parentElement?.id || "";
            }
            const captionId = figureId + "-caption";
            figEl.setAttribute("aria-labelledby", captionId);
            if (figCaptionEl !== null) {
                figCaptionEl.remove();
                const div = doc.createElement("DIV");
                div.id = captionId;
                div.classList.add("margin-figure-caption");
                div.classList.add("column-margin");
                collapseClasses.forEach((clz)=>{
                    div.classList.add(clz);
                });
                div.classList.add("callout-margin-content");
                if (isSimple) {
                    div.classList.add("callout-margin-content-simple");
                }
                figCaptionEl.childNodes.forEach((node)=>{
                    div.append(node);
                });
                el.parentElement?.insertBefore(div, el.nextElementSibling);
            }
        }
    }
};
const kPreviewFigColumnForwarding = [
    ".grid"
];
const isInsideAbout = (el)=>!!findParent(el, (parent)=>Array.from(parent.classList).some((x)=>x.startsWith("quarto-about-")));
const processFigureOutputs = (doc)=>{
    const columnEls = doc.querySelectorAll('[class^="column-"]:not(.column-margin), [class*=" column-"]:not(.column-margin)');
    const moveColumnClasses = (fromEl, toEl)=>{
        const clzList = [];
        for (const clz of fromEl.classList){
            if (clz.startsWith("column-")) {
                clzList.push(clz);
            }
        }
        fromEl.classList.remove(...clzList);
        toEl.classList.add(...clzList);
    };
    for (const columnNode of columnEls){
        const columnEl = columnNode;
        if (kPreviewFigColumnForwarding.some((sel)=>{
            return columnEl.querySelector(sel) !== null;
        })) {
            continue;
        }
        const figures = columnEl.querySelectorAll("figure img.figure-img");
        if (figures && figures.length === 1 && !isInsideAbout(figures[0])) {
            moveColumnClasses(columnEl, figures[0]);
        } else {
            const layoutFigures = columnEl.querySelectorAll(".quarto-layout-panel > figure.figure .quarto-layout-row");
            if (layoutFigures && layoutFigures.length === 1 && !isInsideAbout(layoutFigures[0])) {
                moveColumnClasses(columnEl, layoutFigures[0]);
            }
        }
    }
};
const processMarginElsInTabsets = (doc)=>{
    const tabSetNodes = doc.querySelectorAll("div.panel-tabset");
    tabSetNodes.forEach((tabsetNode)=>{
        const tabSetEl = tabsetNode;
        const tabNodes = tabSetEl.querySelectorAll("div.tab-pane");
        const marginEls = [];
        let count = 0;
        tabNodes.forEach((tabNode)=>{
            const tabEl = tabNode;
            const tabId = tabEl.id;
            const marginNodes = tabEl.querySelectorAll(".column-margin, aside:not(.footnotes):not(.sidebar), .aside:not(.footnotes)");
            if (tabId && marginNodes.length > 0) {
                const marginArr = Array.from(marginNodes);
                marginArr.forEach((marginNode)=>{
                    const marginEl = marginNode;
                    marginEl.classList.add("tabset-margin-content");
                    marginEl.classList.add(`${tabId}-tab-margin-content`);
                    if (count > 0) {
                        marginEl.classList.add("collapse");
                    }
                    marginEls.push(marginEl);
                });
            }
            count++;
        });
        if (marginEls) {
            const containerEl = doc.createElement("div");
            containerEl.classList.add("tabset-margin-container");
            marginEls.forEach((marginEl)=>{
                containerEl.appendChild(marginEl);
            });
            tabSetEl.before(containerEl);
        }
    });
};
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");
        const kPopMarginElOutOfTags = [
            "DD"
        ];
        if (el.parentElement && kPopMarginElOutOfTags.includes(el.parentElement?.tagName)) {
            const parentElement = el.parentElement;
            const marginContainer = doc.createElement("DIV");
            el.remove();
            marginContainer.appendChild(el);
            parentElement.parentElement?.insertBefore(marginContainer, parentElement.nextSibling);
            addContentToMarginContainerForEl(marginContainer, marginContainer, doc);
        } else {
            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();
                    }
                    const invalidParentTags = [
                        "SPAN",
                        "EM",
                        "STRONG",
                        "DEL",
                        "H1",
                        "H2",
                        "H3",
                        "H4",
                        "H5",
                        "H6"
                    ];
                    const findValidParentEl = (el)=>{
                        if (el.parentElement && !invalidParentTags.includes(el.parentElement.tagName)) {
                            return el.parentElement;
                        } else if (el.parentElement) {
                            return findValidParentEl(el.parentElement);
                        } else {
                            return undefined;
                        }
                    };
                    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);
                    }
                    const validParent = findValidParentEl(el);
                    if (refContentsEl.tagName === "LI") {
                        const containerEl = doc.createElement("DIV");
                        containerEl.id = refContentsEl.id;
                        containerEl.append(...refContentsEl.childNodes);
                        addContentToMarginContainerForEl(validParent || el, containerEl, doc);
                    } else {
                        addContentToMarginContainerForEl(validParent || el, refContentsEl, doc);
                    }
                }
            }
        }
    }
};
const referenceMarginProcessor = {
    selector: "a[role='doc-biblioref']",
    canProcess (el) {
        return el.hasAttribute("role") && el.getAttribute("role") === "doc-biblioref";
    },
    process (el, doc) {
        if (el.hasAttribute("href")) {
            const target = el.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 figureCaptionEl = findCaptionEl(el);
                if (refContentsEl && figureCaptionEl) {
                    if (figureCaptionEl.classList.contains("margin-caption")) {
                        figureCaptionEl.appendChild(refContentsEl.cloneNode(true));
                    } else {
                        addContentToMarginContainerForEl(figureCaptionEl, refContentsEl, doc);
                    }
                } else if (refContentsEl) {
                    const nonSpanParent = findNonSpanParentEl(el);
                    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("footnotes") || 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 findCalloutEl = (el)=>{
        if (el.parentElement?.classList.contains("callout")) {
            return el.parentElement;
        } else if (el.parentElement) {
            return findCalloutEl(el.parentElement);
        } else {
            return undefined;
        }
    };
    const calloutEl = findCalloutEl(el);
    if (calloutEl) {
        const container = createMarginContainer(doc);
        calloutEl.parentNode?.insertBefore(container, calloutEl.nextElementSibling);
        return container;
    }
    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",
        "BLOCKQUOTE"
    ];
    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;
    }
};
const hasContents = (id, doc)=>{
    const el = doc.getElementById(id);
    if (el === null) {
        return false;
    }
    if (el.children.length > 0) {
        return true;
    }
    return !!el.innerText.trim();
};
function suggestColumn(doc) {
    const leftSidebar = hasContents(kSidebarId, doc);
    const leftToc = hasContents(kTocLeftSidebarId, doc);
    const rightSidebar = hasContents(kMarginSidebarId1, doc);
    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 || leftToc;
    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 kMarginSidebarId1 = "quarto-margin-sidebar";
const kTocLeftSidebarId = "quarto-sidebar-toc-left";
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 allColumnClz = [
    "column-body-outset",
    "column-body-outset-left",
    "column-body-outset-right",
    "column-page-inset",
    "column-page-inset-left",
    "column-page-inset-right",
    "column-page",
    "column-page-left",
    "column-page-right",
    "column-screen-inset",
    "column-screen-inset-left",
    "column-screen-inset-right",
    "column-screen",
    "column-screen-left",
    "column-screen-right",
    "column-margin"
];
const removeMarginClz = [
    "column-body-outset",
    "column-body-outset-right",
    "column-page-inset",
    "column-page-inset-right",
    "column-page",
    "column-page-right",
    "column-screen-inset",
    "column-screen-inset-right",
    "column-screen",
    "column-screen-right",
    "column-margin"
];
const nonScreenColumnClz = [
    "column-body-outset",
    "column-body-outset-left",
    "column-body-outset-right",
    "column-page-inset",
    "column-page-inset-left",
    "column-page-inset-right",
    "column-page",
    "column-page-left",
    "column-page-right",
    "column-screen-inset",
    "column-screen-inset-left",
    "column-screen-inset-right",
    "column-screen-left",
    "column-screen-right",
    "column-margin"
];
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;
};
function htmlFormat(figwidth, figheight) {
    return mergeConfigs(createHtmlFormat("HTML", figwidth, figheight), {
        render: {
            [kNotebookLinks]: true
        },
        resolveFormat: (format)=>{
            if (format.metadata[kMinimal] === true) {
                if (format.metadata[kFigResponsive] === undefined) {
                    format.metadata[kFigResponsive] = false;
                }
                if (format.metadata[kTheme] === undefined) {
                    format.metadata[kTheme] = "none";
                }
            }
        },
        formatExtras: async (input, _markdown, flags, format, _libDir, services, offset, project, quiet)=>{
            if (!project && format.metadata[kListing]) {
                warn(`Quarto only supports listings within websites. Please ensure that the file ${input} is a part of a website project to enable listing rendering.`);
            }
            const htmlFilterParams = htmlFormatFilterParams(format);
            return mergeConfigs(await htmlFormatExtras(input, flags, offset, format, services.temp, project), themeFormatExtras(input, flags, format, services, offset, project, quiet), {
                [kFilterParams]: htmlFilterParams
            });
        },
        extensions: {
            book: {
                multiFile: true
            }
        }
    });
}
async function htmlFormatExtras(input, _flags, offset, format, temp, _project, featureDefaults, tippyOptions, scssOptions) {
    const bootstrap = formatHasBootstrap(format);
    if (!featureDefaults) {
        featureDefaults = htmlFormatFeatureDefaults(format);
    }
    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 = __VIRTUAL_FILE18(format.metadata[kComments]) ? {
        [kHypothesis]: format.metadata[kComments][kHypothesis] || false,
        [kUtterances]: format.metadata[kComments][kUtterances] || false,
        [kGiscus]: format.metadata[kComments][kGiscus] || false
    } : {};
    options.codeLink = format.metadata[kCodeLink] || false;
    if (featureDefaults.tabby) {
        options.tabby = format.metadata[kTabsets] !== false;
    } else {
        options.tabby = format.metadata[kTabsets] || false;
    }
    if (featureDefaults.copyCode) {
        options.copyCode = format.metadata[kCodeCopy] !== false;
    } else {
        options.copyCode = format.metadata[kCodeCopy] || false;
    }
    if (featureDefaults.anchors) {
        options.anchors = format.metadata[kAnchorSections] !== false;
    } else {
        options.anchors = format.metadata[kAnchorSections] || false;
    }
    if (featureDefaults.hoverCitations) {
        options.hoverCitations = format.metadata[kCitationsHover] !== false;
    } else {
        options.hoverCitations = format.metadata[kCitationsHover] || false;
    }
    if (featureDefaults.hoverFootnotes) {
        options.hoverFootnotes = format.metadata[kFootnotesHover] !== false;
    } else {
        options.hoverFootnotes = format.metadata[kFootnotesHover] || false;
    }
    if (featureDefaults.hoverXrefs) {
        options.hoverXrefs = format.metadata[kXrefsHover] !== false;
    } else {
        options.hoverXrefs = format.metadata[kXrefsHover] || false;
    }
    if (featureDefaults.figResponsive) {
        options.figResponsive = format.metadata[kFigResponsive] !== false;
    } else {
        options.figResponsive = format.metadata[kFigResponsive] || false;
    }
    if (featureDefaults.codeAnnotations) {
        options.codeAnnotations = format.metadata[kCodeAnnotations] || true;
    } else {
        options.codeAnnotations = format.metadata[kCodeAnnotations] || false;
    }
    options.zenscroll = format.metadata[kSmoothScroll];
    options.codeTools = formatHasCodeTools(format);
    options.darkMode = formatDarkMode(format);
    options.darkModeDefault = darkModeDefault(format.metadata);
    options.linkExternalIcon = format.render[kLinkExternalIcon];
    options.linkExternalNewwindow = format.render[kLinkExternalNewwindow];
    options.linkExternalFilter = format.render[kLinkExternalFilter];
    const siteMetadata = format.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", join2("tabby", "js", "tabby.js"))
        });
    }
    const includeInHeader = [];
    if (options.zenscroll) {
        scripts.push({
            name: "zenscroll-min.js",
            path: formatResourcePath("html", join2("zenscroll", "zenscroll-min.js")),
            afterBody: true
        });
        const zenscrollStyle = temp.createFile({
            suffix: "-zen.html"
        });
        Deno.writeTextFileSync(zenscrollStyle, "<style>html{ scroll-behavior: smooth; }</style>");
        includeInHeader.push(zenscrollStyle);
    }
    options.tippy = options.hoverCitations || options.hoverFootnotes || options.codeAnnotations || options.hoverXrefs;
    if (bootstrap || options.tippy) {
        scripts.push({
            name: "popper.min.js",
            path: formatResourcePath("html", join2("popper", "popper.min.js"))
        });
    }
    if (options.tippy) {
        scripts.push({
            name: "tippy.umd.min.js",
            path: formatResourcePath("html", join2("tippy", "tippy.umd.min.js"))
        });
        stylesheets.push({
            name: "tippy.css",
            path: formatResourcePath("html", join2("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", join2("tippy", "_tippy.scss")))
                    }
                });
            } else {
                tippyOptions.theme = "light-border";
                stylesheets.push({
                    name: "light-border.css",
                    path: formatResourcePath("html", join2("tippy", "light-border.css"))
                });
            }
        }
    }
    options.tippyOptions = tippyOptions;
    if (options.copyCode) {
        dependencies.push(clipboardDependency());
    }
    options.language = format.language;
    if (options.anchors) {
        scripts.push({
            name: "anchor.min.js",
            path: formatResourcePath("html", join2("anchor", "anchor.min.js"))
        });
        options.anchors = typeof options.anchors === "string" ? options.anchors : true;
    }
    const minimal = format.metadata[kMinimal] === true;
    if (!bootstrap && !minimal) {
        if (scssOptions.quartoBase) {
            sassBundles.push({
                dependency: kQuartoHtmlDependency,
                key: kQuartoHtmlDependency,
                quarto: quartoBaseLayer(format, !!options.copyCode, !!options.tabby, !!options.figResponsive)
            });
        }
        if (scssOptions.quartoCssVars) {
            sassBundles.push({
                dependency: kQuartoHtmlDependency,
                key: kQuartoHtmlDependency,
                quarto: {
                    uses: "",
                    defaults: "",
                    functions: "",
                    mixins: "",
                    rules: quartoGlobalCssVariableRules()
                }
            });
        }
    }
    if (options.hypothesis) {
        const hypothesisHeader = temp.createFile({
            suffix: "-hypoth.html"
        });
        Deno.writeTextFileSync(hypothesisHeader, renderEjs(formatResourcePath("html", join2("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();
        const renderedHtml = renderEjs(formatResourcePath("html", join2("templates", "quarto-html.ejs")), options);
        if (renderedHtml.trim() !== "") {
            Deno.writeTextFileSync(quartoHtmlScript, renderedHtml);
            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: "-utter.html"
        });
        Deno.writeTextFileSync(utterancesAfterBody, renderEjs(formatResourcePath("html", join2("utterances", "utterances.ejs")), {
            utterances
        }));
        includeAfterBody.push(utterancesAfterBody);
    }
    if (options.giscus) {
        const giscus = options.giscus;
        giscus.category = giscus.category || "General";
        giscus.theme = giscus.theme || "";
        const themeToggleRecord = buildGiscusThemeKeys(Boolean(options.darkModeDefault), giscus.theme);
        giscus.baseTheme = themeToggleRecord.baseTheme;
        giscus.altTheme = themeToggleRecord.altTheme;
        giscus.theme = giscus.baseTheme;
        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: "-giscus.html"
        });
        Deno.writeTextFileSync(giscusAfterBody, renderEjs(formatResourcePath("html", join2("giscus", "giscus.ejs")), {
            giscus
        }));
        includeAfterBody.push(giscusAfterBody);
    }
    dependencies.push({
        name: kQuartoHtmlDependency,
        scripts,
        stylesheets
    });
    const templateDir = formatResourcePath("html", "pandoc");
    const partials = [
        "metadata.html",
        "title-block.html",
        "toc.html",
        "styles.html"
    ];
    const templateContext = {
        template: join2(templateDir, "template.html"),
        partials: partials.map((partial)=>join2(templateDir, partial))
    };
    const htmlPostProcessors = [
        htmlFormatPostprocessor(format, featureDefaults),
        metadataPostProcessor(input, format, offset)
    ];
    const viewStyle = format.render[kNotebookViewStyle];
    if (viewStyle === kNotebookViewStyleNotebook) {
        htmlPostProcessors.push(notebookViewPostProcessor());
    }
    const metadata = {};
    return {
        [kIncludeInHeader]: includeInHeader,
        [kIncludeAfterBody]: includeAfterBody,
        metadata,
        templateContext,
        html: {
            [kDependencies]: dependencies,
            [kSassBundles]: sassBundles,
            [kHtmlPostprocessors]: htmlPostProcessors
        }
    };
}
const kFormatHasBootstrap = "has-bootstrap";
function htmlFormatFilterParams(format) {
    return {
        [kFormatHasBootstrap]: formatHasBootstrap(format)
    };
}
function htmlFormatFeatureDefaults(format) {
    const bootstrap = formatHasBootstrap(format);
    const minimal = format.metadata[kMinimal] === true;
    return {
        tabby: !minimal && !bootstrap,
        copyCode: !minimal,
        anchors: !minimal,
        hoverCitations: !minimal,
        hoverFootnotes: !minimal,
        figResponsive: !minimal,
        codeAnnotations: !minimal,
        hoverXrefs: !minimal
    };
}
function htmlFormatPostprocessor(format, featureDefaults) {
    const haveBootstrap = formatHasBootstrap(format);
    if (!featureDefaults) {
        featureDefaults = htmlFormatFeatureDefaults(format);
    }
    const codeCopy = featureDefaults.copyCode ? format.metadata[kCodeCopy] !== false : format.metadata[kCodeCopy] || false;
    const anchors = featureDefaults.anchors ? format.metadata[kAnchorSections] !== false : format.metadata[kAnchorSections] || false;
    return (doc)=>{
        if (format.render[kBodyClasses]) {
            const clz = format.render[kBodyClasses].split(" ");
            clz.forEach((cls)=>{
                doc.body.classList.add(cls);
            });
        }
        const codeBlocks = doc.querySelectorAll("pre.sourceCode");
        const EmbedSourceModal = doc.querySelector(`#${kEmbeddedSourceModalId}`);
        for(let i1 = 0; i1 < codeBlocks.length; i1++){
            const code = codeBlocks[i1];
            const parentHoist = (clz)=>{
                if (code.classList.contains(clz)) {
                    code.classList.remove(clz);
                    code.parentElement?.classList.add(clz);
                }
            };
            parentHoist("cell-code");
            parentHoist("hidden");
            if (code.classList.contains("hidden")) {
                code.classList.remove("hidden");
                code.parentElement?.classList.add("hidden");
            }
            if (codeCopy) {
                code.classList.add("code-with-copy");
                const copyButton = createCodeCopyButton(doc, format);
                if (EmbedSourceModal && EmbedSourceModal.contains(code)) {
                    copyButton.setAttribute("data-in-quarto-modal", "");
                }
                code.appendChild(copyButton);
            }
            if (code.parentElement?.getAttribute("data-code-preview")) {
                const codeExample = doc.createElement("iframe");
                for (const parentClass of code.classList){
                    codeExample.classList.add(parentClass);
                }
                codeExample.setAttribute("src", code.parentElement.getAttribute("data-code-preview").replace(/\.qmd$/, ".html"));
                code.parentElement.removeAttribute("data-code-preview");
                code.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 i1 = 0; i1 < headings.length; i1++){
                        const heading = headings[i1];
                        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")) {
                secNumber.remove();
            }
        }
        processCodeAnnotations(format, doc);
        const tables = doc.querySelectorAll('table[data-quarto-postprocess-tables="true"]');
        for(let i1 = 0; i1 < tables.length; ++i1){
            const table = tables[i1];
            if (table.getAttribute("data-quarto-disable-processing")) {
                continue;
            }
            table.removeAttribute("data-quarto-postprocess-tables");
            table.querySelectorAll("tr").forEach((tr)=>{
                const { children } = tr;
                for(let j = 0; j < children.length; ++j){
                    const child = children[j];
                    if (child.tagName === "TH" || child.tagName === "TD") {
                        const isTH = child.getAttribute("data-quarto-table-cell-role") === "th";
                        const newElement = doc.createElement(isTH ? "th" : "td");
                        while(child.firstChild){
                            newElement.appendChild(child.firstChild);
                        }
                        for(let k = 0; k < child.attributes.length; ++k){
                            const attr = child.attributes[k];
                            newElement.setAttribute(attr.name, attr.value);
                        }
                        child.parentNode?.replaceChild(newElement, child);
                    }
                }
            });
        }
        const metadraftEl = doc.querySelector("meta[name='quarto:status']");
        if (metadraftEl !== null) {
            const status = metadraftEl.getAttribute("content");
            if (status === "draft") {
                const draftDivEl = doc.createElement("DIV");
                const iconEl = doc.createElement("I");
                iconEl.classList.add("bi");
                iconEl.classList.add("bi-pencil-square");
                const textNode = doc.createTextNode(format.language.draft || "Draft");
                draftDivEl.appendChild(iconEl);
                draftDivEl.appendChild(textNode);
                draftDivEl.setAttribute("id", "quarto-draft-alert");
                draftDivEl.classList.add("alert");
                draftDivEl.classList.add("alert-warning");
                let targetEl = doc.body;
                const headerEl = doc.getElementById("quarto-header");
                if (headerEl !== null) {
                    targetEl = headerEl;
                }
                targetEl.insertBefore(draftDivEl, targetEl.firstChild);
            }
        }
        return Promise.resolve(kHtmlEmptyPostProcessResult);
    };
}
const kCodeCellAttr = "data-code-cell";
const kCodeLinesAttr = "data-code-lines";
const kCodeAnnotationAttr = "data-code-annotation";
const kCodeCellTargetAttr = "data-target-cell";
const kCodeAnnotationTargetAttr = "data-target-annotation";
const kCodeAnnotationHiddenClz = "code-annotation-container-hidden";
const kCodeAnnotationGridClz = "code-annotation-container-grid";
const kCodeAnnotationAnchorClz = "code-annotation-anchor";
const kCodeAnnotationTargetClz = "code-annotation-target";
const kCodeAnnotationParentClz = "code-annotated";
const kCodeAnnotationGutterClz = "code-annotation-gutter";
const kCodeAnnotationGutterBgClz = "code-annotation-gutter-bg";
function processCodeAnnotations(format, doc) {
    const annotationStyle = format.metadata[kCodeAnnotations];
    const replaceLineNumberWithAnnote = (annoteEl, dtEl)=>{
        const annotation = annoteEl.getAttribute(kCodeAnnotationAttr);
        if (annotation !== null) {
            const ddEl = dtEl.previousElementSibling;
            if (ddEl) {
                ddEl.innerHTML = "";
                ddEl.innerText = annotation;
                const codeCell = annoteEl.getAttribute(kCodeCellAttr);
                if (codeCell) {
                    ddEl.setAttribute(kCodeCellTargetAttr, codeCell);
                    ddEl.setAttribute(kCodeAnnotationTargetAttr, annotation);
                }
            }
        }
    };
    if (annotationStyle === false) {
        const annoteNodes = doc.querySelectorAll(`span[${kCodeCellAttr}]`);
        for (const annoteNode of annoteNodes){
            const annoteEl = annoteNode;
            const parentDL = annoteEl.parentElement?.parentElement;
            if (parentDL && !parentDL.classList.contains(kCodeAnnotationHiddenClz)) {
                parentDL.classList.add(kCodeAnnotationHiddenClz);
            }
        }
    } else if (annotationStyle === "hover" || annotationStyle === "select") {
        const definitionLists = processCodeBlockAnnotation(doc, true, "start", replaceLineNumberWithAnnote);
        Object.values(definitionLists).forEach((dl)=>{
            dl.classList.add(kCodeAnnotationHiddenClz);
            dl.classList.add(kCodeAnnotationGridClz);
        });
    } else {
        const definitionLists = processCodeBlockAnnotation(doc, false, "start", replaceLineNumberWithAnnote);
        Object.values(definitionLists).forEach((dl)=>{
            dl.classList.add(kCodeAnnotationGridClz);
        });
    }
}
function processCodeBlockAnnotation(doc, interactiveAnnotations, annotationPosition, processDt) {
    const definitionLists = {};
    const codeBlockParents = [];
    const annoteNodes = doc.querySelectorAll(`span[${kCodeCellAttr}]`);
    for (const annoteNode of annoteNodes){
        const annoteEl = annoteNode;
        const parentCodeBlock = processLineAnnotation(doc, annoteEl, interactiveAnnotations, annotationPosition);
        if (parentCodeBlock && !codeBlockParents.includes(parentCodeBlock)) {
            codeBlockParents.push(parentCodeBlock);
        }
        const parentDL = annoteEl.parentElement?.parentElement;
        const codeParentDivId = parentCodeBlock?.parentElement?.parentElement?.id;
        if (parentDL && codeParentDivId && !Object.keys(definitionLists).includes(codeParentDivId)) {
            definitionLists[codeParentDivId] = parentDL;
        }
        if (annoteEl.parentElement && processDt) {
            processDt(annoteEl, annoteEl.parentElement);
        }
    }
    for (const codeParentEl of codeBlockParents){
        if (codeParentEl.parentElement) {
            codeParentEl.parentElement.classList.add(kCodeAnnotationParentClz);
        }
        const gutterBgDivEl = doc.createElement("div");
        gutterBgDivEl.classList.add(kCodeAnnotationGutterBgClz);
        codeParentEl?.appendChild(gutterBgDivEl);
        const gutterDivEl = doc.createElement("div");
        gutterDivEl.classList.add(kCodeAnnotationGutterClz);
        codeParentEl?.appendChild(gutterDivEl);
    }
    return definitionLists;
}
function processLineAnnotation(doc, annoteEl, interactive, position) {
    const targetCell = annoteEl.getAttribute(kCodeCellAttr);
    const targetLines = annoteEl.getAttribute(kCodeLinesAttr);
    const targetAnnotation = annoteEl.getAttribute(kCodeAnnotationAttr);
    if (targetCell && targetLines) {
        const lineArr = targetLines?.split(",");
        const targetIndex = position === "start" ? 0 : Math.floor(lineArr.length / 2);
        const line = lineArr[targetIndex];
        const targetId = `${targetCell}-${line}`;
        const targetEl = doc.getElementById(targetId);
        if (targetEl) {
            const annoteAnchorEl = doc.createElement(interactive ? "button" : "a");
            annoteAnchorEl.classList.add(kCodeAnnotationAnchorClz);
            annoteAnchorEl.setAttribute(kCodeCellTargetAttr, `${targetCell}`);
            annoteAnchorEl.setAttribute(kCodeAnnotationTargetAttr, `${targetAnnotation}`);
            if (!interactive) {
                annoteAnchorEl.setAttribute("onclick", "event.preventDefault();");
            }
            annoteAnchorEl.innerText = targetAnnotation || "?";
            targetEl.parentElement?.insertBefore(annoteAnchorEl, targetEl);
            targetEl.classList.add(kCodeAnnotationTargetClz);
            return targetEl.parentElement;
        }
    }
}
function themeFormatExtras(input, flags, format, sevices, offset, project, quiet) {
    const theme = format.metadata[kTheme];
    if (theme === "none") {
        return {
            metadata: {
                [kDocumentCss]: false
            }
        };
    } else if (theme === "pandoc") {
        return pandocExtras(format);
    } else {
        return bootstrapExtras(input, flags, format, sevices, offset, project, quiet);
    }
}
function pandocExtras(format) {
    const maxWidth = format.metadata["max-width"];
    const headerIncludes = maxWidth ? `<style type="text/css">body { max-width: ${asCssSize(maxWidth)};}</style>` : undefined;
    return {
        metadata: {
            [kDocumentCss]: true,
            [kHeaderIncludes]: headerIncludes
        }
    };
}
registerWriterFormatHandler((format)=>{
    switch(format){
        case "html":
        case "html4":
        case "html5":
            return {
                format: htmlFormat(7, 5)
            };
    }
});
function optionsToKebab(options) {
    return options.reduce((options, option)=>{
        const kebab = camelToKebab(option);
        if (kebab !== option) {
            options.push(kebab);
        }
        return options;
    }, []);
}
function revealMetadataFilter(metadata, kebabOptions = kRevealKebabOptions) {
    const mappingExceptions = {
        "fragment-in-url": "fragmentInURL"
    };
    const filtered = {};
    Object.keys(metadata).forEach((key)=>{
        const value = metadata[key];
        if (kebabOptions.includes(key)) {
            const camel = mappingExceptions[key] || kebabToCamel(key);
            filtered[camel] = value;
        } else {
            filtered[key] = value;
        }
    });
    return filtered;
}
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",
    "pdfMaxPagesPerSlide",
    "pdfSeparateFragments",
    "pdfPageHeightOffset"
];
const kRevealKebabOptions = optionsToKebab(kRevealOptions);
const kRevealJsMultiplex = "multiplex";
function revealMultiplexPlugin(format) {
    if (format.metadata[kRevealJsMultiplex]) {
        return formatResourcePath("revealjs", join2("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(format, flags) {
    if (format.metadata[kRevealJsMultiplex]) {
        return {
            postprocessors: [
                async (output)=>{
                    const token = await revealMultiplexToken(format, 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);
                    const selfContained = isSelfContainedOutput(flags, format, speakerOutput);
                    if (selfContained) {
                        await pandocIngestSelfContainedContent(speakerOutput, format.pandoc[kResourcePath]);
                    }
                }
            ]
        };
    } else {
        return undefined;
    }
}
function revealSpeakerOutput(output) {
    const [dir, stem] = dirAndStem(output);
    return join2(dir, `${stem}-speaker.html`);
}
const kDefaultMultiplexUrl = "https://reveal-multiplex.glitch.me/";
async function revealMultiplexToken(format, output) {
    const multiplex = format.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(join2(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 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);
function isPluginBundle(plugin) {
    return plugin.plugin !== undefined;
}
async function revealPluginExtras(input, format, flags, temp, revealUrl, revealDestDir, extensionContext, project) {
    const pluginsDestDir = join2(revealDestDir, "plugin");
    const register = [];
    const scripts = [];
    const stylesheets = [];
    const config = {};
    const metadata = [];
    const dependencies = [];
    const pluginBundles = [
        {
            plugin: formatResourcePath("revealjs", join2("plugins", "line-highlight"))
        },
        {
            plugin: formatResourcePath("revealjs", join2("plugins", "pdfexport"))
        }
    ];
    const menuPlugin = revealMenuPlugin(format);
    if (menuPlugin) {
        pluginBundles.push(menuPlugin);
    }
    const chalkboardPlugiln = revealChalkboardPlugin(format);
    if (chalkboardPlugiln) {
        pluginBundles.push(chalkboardPlugiln);
    }
    const tonePlugin = revealTonePlugin(format);
    if (tonePlugin) {
        dependencies.push(toneDependency());
        pluginBundles.push(tonePlugin);
    }
    const multiplexPlugin = revealMultiplexPlugin(format);
    if (multiplexPlugin) {
        pluginBundles.push(multiplexPlugin);
    }
    const resolvePluginPath = async (plugin)=>{
        let extensions = await extensionContext?.find(plugin, input, kRevealJSPlugins, project?.config, project?.dir) || [];
        extensions = filterExtensions(extensions || [], plugin, "revealjs-plugins");
        if (extensions.length > 0) {
            return extensions[0].contributes[kRevealJSPlugins] || [];
        } else {
            return [
                plugin
            ];
        }
    };
    const resolvePlugin = async (plugin)=>{
        if (typeof plugin === "string") {
            if (existsSync(plugin)) {
                return [
                    plugin
                ];
            } else {
                return await resolvePluginPath(plugin);
            }
        } else {
            if (isPluginBundle(plugin)) {
                const path = plugin.plugin;
                const resolvedPlugins = await resolvePluginPath(path);
                const pluginBundles = resolvedPlugins.map((resolvedPlug)=>{
                    if (typeof resolvedPlug === "string") {
                        return {
                            plugin: resolvedPlug,
                            config: plugin.config
                        };
                    } else if (isPluginBundle(resolvedPlug)) {
                        return {
                            plugin: resolvedPlug.plugin,
                            config: mergeConfigs(plugin.config, resolvedPlug.config)
                        };
                    } else {
                        return plugin;
                    }
                });
                return pluginBundles;
            } else {
                return Promise.resolve([
                    plugin
                ]);
            }
        }
    };
    if (Array.isArray(format.metadata[kRevealjsPlugins])) {
        for (const plugin of format.metadata[kRevealJSPlugins]){
            const resolvedPlugins = await resolvePlugin(plugin);
            pluginBundles.push(...resolvedPlugins);
        }
    }
    pluginBundles.push({
        plugin: formatResourcePath("revealjs", join2("plugins", "support"))
    });
    for (let bundle of pluginBundles){
        if (typeof bundle === "string") {
            bundle = {
                plugin: bundle
            };
        }
        const plugin = isPluginBundle(bundle) ? await pluginFromBundle(bundle) : bundle;
        if (isSelfContained(flags, format)) {
            if (plugin[kSelfContained] === false) {
                throw new Error("Reveal plugin '" + plugin.name + " is not compatible with self-contained output");
            }
        }
        if (plugin.register !== false) {
            register.push(plugin.name);
        }
        const pluginUrl = pathWithForwardSlashes(join2(revealUrl, "plugin", camelToKebab(plugin.name)));
        const pluginDir = join2(pluginsDestDir, camelToKebab(plugin.name));
        if (isPluginBundle(bundle)) {
            copyMinimal(bundle.plugin, pluginDir);
        } else {
            ensureDirSync(pluginDir);
            plugin.script?.forEach((script)=>{
                Deno.copyFileSync(join2(plugin.path, script.path), join2(pluginDir, basename2(script.path)));
            });
            plugin.stylesheet?.forEach((style)=>{
                Deno.copyFileSync(join2(plugin.path, style), join2(pluginDir, basename2(style)));
            });
        }
        if (plugin.script) {
            for (const script of plugin.script){
                script.path = pathWithForwardSlashes(join2(pluginUrl, script.path));
                scripts.push(script);
            }
        }
        if (plugin.stylesheet) {
            for (const stylesheet of plugin.stylesheet){
                const pluginStylesheet = pathWithForwardSlashes(join2(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 format.metadata[kebabKey] === "object") {
                        config[key] = mergeConfigs(revealMetadataFilter(config[key], kRevealPluginKebabOptions), revealMetadataFilter(format.metadata[kebabKey], kRevealPluginKebabOptions));
                    }
                } else {
                    config[key] = plugin.config[key];
                    if (format.metadata[key] !== undefined) {
                        config[key] = format.metadata[key];
                    }
                }
            }
        }
        if (plugin.metadata) {
            metadata.push(...plugin.metadata);
        }
    }
    const extras = {
        [kIncludeInHeader]: [],
        html: {
            [kDependencies]: dependencies
        }
    };
    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);
    metadata.forEach((option)=>{
        if (format.metadata[option] !== undefined) {
            config[option] = format.metadata[option];
        }
    });
    const result1 = {
        pluginInit: {
            scripts,
            register,
            revealConfig: config
        },
        extras
    };
    return result1;
}
function revealMenuPlugin(format) {
    return {
        plugin: formatResourcePath("revealjs", join2("plugins", "menu")),
        config: {
            menu: {
                custom: [
                    {
                        title: "Tools",
                        icon: '<i class="fas fa-gear"></i>',
                        content: revealMenuTools(format)
                    }
                ],
                openButton: format.metadata[kRevealMenu] !== false
            }
        }
    };
}
function revealChalkboardPlugin(format) {
    if (format.metadata[kRevealChalkboard]) {
        return {
            plugin: formatResourcePath("revealjs", join2("plugins", "chalkboard"))
        };
    } else {
        return undefined;
    }
}
function revealMenuTools(format) {
    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: "togglePdfExport"
        }
    ];
    if (format.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 lines = [
        '<ul class="slide-menu-items">'
    ];
    lines.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>`;
    }));
    lines.push("</ul>");
    return lines.join("\n");
}
function revealTonePlugin(format) {
    if (format.metadata[kRevealSlideTone]) {
        return {
            plugin: formatResourcePath("revealjs", join2("plugins", "tone"))
        };
    } else {
        return undefined;
    }
}
function toneDependency() {
    const dependency = {
        name: "tone",
        scripts: [
            {
                name: "tone.js",
                path: formatResourcePath("revealjs", join2("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(join2(bundle.plugin, "plugin.yml"), revealPluginSchema, "Validation of reveal plugin object failed.");
        plugin.path = bundle.plugin;
    } catch (e) {
        error(`Validation of plugin configuration ${join2(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(join2(plugin.path, script.path))) {
            throw new Error("Reveal plugin script '" + script + "' not found.");
        }
    }
    if (plugin.stylesheet) {
        for (const stylesheet of plugin.stylesheet){
            if (!existsSync(join2(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.");
        }
    }
}
const kRevealJsUrl = "revealjs-url";
const kRevealJsConfig = "revealjs-config";
const kSlideLogo = "logo";
const kSlideFooter = "footer";
const kHashType = "hash-type";
const kScrollable = "scrollable";
const kCenter = "center";
const kCenterTitleSlide = "center-title-slide";
const kControlsAuto = "controlsAuto";
const kPreviewLinksAuto = "previewLinksAuto";
const kPdfMaxPagesPerSlide = "pdfMaxPagesPerSlide";
const kPdfSeparateFragments = "pdfSeparateFragments";
const kAutoAnimateEasing = "autoAnimateEasing";
const kAutoAnimateDuration = "autoAnimateDuration";
const kAutoAnimateUnmatched = "autoAnimateUnmatched";
const kAutoStretch = "auto-stretch";
const kCodeBlockHeight = "code-block-height";
const kStylePandoc = "pandoc";
function titleSlidePartial(format) {
    if (isLegacyTitleStyle(format)) {
        return "title-slide.html";
    } else {
        return "title-fancy/title-slide.html";
    }
}
function titleSlideScss(format) {
    if (isLegacyTitleStyle(format)) {
        return undefined;
    } else {
        const titleBlockScss = formatResourcePath("revealjs", join2("pandoc", "title-fancy/title-slide.scss"));
        return sassLayer(titleBlockScss);
    }
}
function isLegacyTitleStyle(format) {
    return format.metadata["title-slide-style"] === kStylePandoc;
}
const kRevealLightThemes = [
    "white",
    "beige",
    "sky",
    "serif",
    "simple",
    "solarized"
];
const kRevealDarkThemes = [
    "black",
    "league",
    "night",
    "blood",
    "moon"
];
[
    ...kRevealLightThemes,
    ...kRevealDarkThemes
];
async function revealTheme(format, input, libDir, temp) {
    const metadata = {};
    const revealDir = join2(libDir, "revealjs");
    const revealJsUrl = format.metadata[kRevealJsUrl];
    if (revealJsUrl && !isFileRef(revealJsUrl)) {
        throw new Error("Invalid revealjs-url: " + revealJsUrl + " (remote urls are not supported)");
    }
    const revealUrl = pathWithForwardSlashes(revealDir);
    metadata[kRevealJsUrl] = pandocNativeStr(revealUrl).mappedString().value;
    const revealSrcDir = revealJsUrl || formatResourcePath("revealjs", "reveal");
    const revealDestDir = join2(dirname2(input), libDir, "revealjs");
    [
        "dist",
        "plugin"
    ].forEach((dir)=>{
        copyMinimal(join2(revealSrcDir, dir), join2(revealDestDir, dir));
    });
    const cssThemeDir = join2(revealSrcDir, "css", "theme");
    const loadPaths = [
        join2(cssThemeDir, "source"),
        join2(cssThemeDir, "template")
    ];
    const themeConfig = format.metadata?.[kTheme] || "default";
    const themeLayers = (Array.isArray(themeConfig) ? themeConfig : [
        themeConfig
    ]).map((theme)=>{
        const themePath = join2(relative2(Deno.cwd(), dirname2(input)), theme);
        if (existsSync(themePath)) {
            loadPaths.unshift(join2(dirname2(input), dirname2(theme)));
            return themeLayer(themePath);
        } else {
            if (theme === "white") {
                theme = "default";
            } else if (theme === "black") {
                theme = "dark";
            }
            theme = formatResourcePath("revealjs", join2("themes", `${theme}.scss`));
            return themeLayer(theme);
        }
    });
    const yamlLayer = {
        uses: "",
        defaults: pandocVariablesToThemeScss1(format.metadata, true),
        functions: "",
        mixins: "",
        rules: ""
    };
    const highlightingLayer = !hasAdaptiveTheme(format.pandoc) ? resolveTextHighlightingLayer(input, format, "light") : undefined;
    const userLayers = [
        yamlLayer
    ];
    if (highlightingLayer) {
        userLayers.push(highlightingLayer);
    }
    userLayers.push(...themeLayers);
    const quartoLayers = [
        quartoBaseLayer(format, true, true, false, true),
        quartoLayer()
    ];
    const titleSlideLayer = titleSlideScss(format);
    if (titleSlideLayer) {
        userLayers.unshift(titleSlideLayer);
    }
    const bundleLayers = {
        key: "reveal-theme",
        user: mergeLayers(...userLayers),
        quarto: mergeLayers(...quartoLayers),
        framework: revealFrameworkLayer(revealSrcDir),
        loadPaths
    };
    const css = await compileSass([
        bundleLayers
    ], temp);
    copyTo(css, join2(revealDestDir, "dist", "theme", "quarto.css"));
    metadata[kTheme] = "quarto";
    const highlightingMode = cssHasDarkModeSentinel(Deno.readTextFileSync(css)) ? "dark" : "light";
    return {
        revealUrl,
        revealDestDir,
        metadata,
        [kTextHighlightingMode]: highlightingMode
    };
}
function revealFrameworkLayer(revealDir) {
    const readTemplate = (template)=>{
        return Deno.readTextFileSync(join2(revealDir, "css", "theme", "template", template));
    };
    return {
        uses: "",
        defaults: "",
        functions: "",
        mixins: readTemplate("mixins.scss"),
        rules: readTemplate("theme.scss")
    };
}
function pandocVariablesToThemeScss1(metadata, asDefaults = false) {
    return pandocVariablesToRevealDefaults(metadata).map((variable)=>{
        return outputVariable(variable, asDefaults);
    }).join("\n");
}
function pandocVariablesToRevealDefaults(metadata) {
    const explicitVars = [];
    const add = (defaults, name, value, formatter)=>{
        if (value) {
            const sassVar = sassVariable(name, value, formatter);
            defaults.push(sassVar);
        }
    };
    add(explicitVars, "font-family-sans-serif", metadata["mainfont"], asCssFont);
    add(explicitVars, "font-family-monospace", metadata["monofont"], asCssFont);
    add(explicitVars, "presentation-font-size-root", metadata["fontsize"]);
    add(explicitVars, "presentation-line-height", metadata["linestretch"], asCssNumber);
    add(explicitVars, "code-block-bg", metadata["monobackgroundcolor"]);
    add(explicitVars, "code-block-height", metadata[kCodeBlockHeight]);
    return explicitVars;
}
function quartoLayer() {
    return sassLayerFile(formatResourcePath("revealjs", "quarto.scss"));
}
function themeLayer(theme) {
    return sassLayerFile(theme);
}
function revealResolveFormat(format) {
    format.metadata = revealMetadataFilter(format.metadata);
    if (format.metadata["navigationMode"] === "vertical") {
        format.metadata["navigationMode"] = "default";
    }
}
function revealjsFormat() {
    return mergeConfigs(createHtmlPresentationFormat("RevealJS", 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, _markdown, flags, format, libDir, services, offset, project)=>{
            const stylesFile = services.temp.createFile({
                suffix: ".html"
            });
            const styles = renderEjs(formatResourcePath("revealjs", "styles.html"), {
                [kScrollable]: format.metadata[kScrollable]
            });
            Deno.writeTextFileSync(stylesFile, styles);
            const metadataOverride = {};
            const controlsAuto = typeof format.metadata["controls"] !== "boolean";
            if (controlsAuto) {
                metadataOverride.controls = false;
            }
            const previewLinksAuto = format.metadata["previewLinks"] === "auto";
            if (previewLinksAuto) {
                metadataOverride.previewLinks = false;
            }
            const extraConfig = {
                [kControlsAuto]: controlsAuto,
                [kPreviewLinksAuto]: previewLinksAuto,
                [kPdfSeparateFragments]: !!format.metadata[kPdfSeparateFragments],
                [kAutoAnimateEasing]: format.metadata[kAutoAnimateEasing] || "ease",
                [kAutoAnimateDuration]: format.metadata[kAutoAnimateDuration] || 1.0,
                [kAutoAnimateUnmatched]: format.metadata[kAutoAnimateUnmatched] !== undefined ? format.metadata[kAutoAnimateUnmatched] : true
            };
            if (format.metadata[kPdfMaxPagesPerSlide]) {
                extraConfig[kPdfMaxPagesPerSlide] = format.metadata[kPdfMaxPagesPerSlide];
            }
            const theme = await revealTheme(format, input, libDir, services.temp);
            const revealPluginData = await revealPluginExtras(input, format, flags, services.temp, theme.revealUrl, theme.revealDestDir, services.extension, project);
            const templateDir = formatResourcePath("revealjs", "pandoc");
            const partials = [
                "toc-slide.html",
                titleSlidePartial(format)
            ];
            const templateContext = {
                template: join2(templateDir, "template.html"),
                partials: partials.map((partial)=>join2(templateDir, partial))
            };
            let extras = mergeConfigs(await htmlFormatExtras(input, flags, offset, format, services.temp, project, {
                tabby: true,
                anchors: false,
                copyCode: true,
                hoverCitations: true,
                hoverFootnotes: true,
                hoverXrefs: false,
                figResponsive: false
            }, {
                parent: "section.slide",
                config: {
                    offset: [
                        0,
                        0
                    ],
                    maxWidth: 700
                }
            }, {
                quartoBase: false
            }), {
                args: [],
                pandoc: {},
                metadata: {
                    [kLinkCitations]: true,
                    [kRevealJsScripts]: revealPluginData.pluginInit.scripts.map((script)=>{
                        return pandocNativeStr(script.path).mappedString().value;
                    })
                },
                metadataOverride,
                templateContext,
                [kIncludeInHeader]: [
                    formatResourcePath("html", "styles-callout.html"),
                    stylesFile
                ],
                html: {
                    [kHtmlPostprocessors]: [
                        revealHtmlPostprocessor(format, extraConfig, revealPluginData.pluginInit, theme["text-highlighting-mode"])
                    ],
                    [kMarkdownAfterBody]: [
                        revealMarkdownAfterBody(format)
                    ]
                }
            });
            extras.metadataOverride = {
                ...extras.metadataOverride,
                ...theme.metadata
            };
            extras.html[kTextHighlightingMode] = theme[kTextHighlightingMode];
            extras = mergeConfigs(revealPluginData.extras, extras);
            const multiplexExtras = revealMultiplexExtras(format, flags);
            if (multiplexExtras) {
                extras = mergeConfigs(extras, multiplexExtras);
            }
            if (format.metadata[kRevealJsConfig] !== "default") {
                const navigationMode = format.metadata["navigationMode"];
                const verticalSlides = navigationMode === "default" || navigationMode === "grid";
                if (format.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 (format.metadata[kHashType] === "number") {
                extras.pandoc = {
                    ...extras.pandoc,
                    from: pandocFormatWith(format.pandoc[kFrom] || "markdown", "", "-auto_identifiers")
                };
            }
            return extras;
        }
    });
}
function revealMarkdownAfterBody(format) {
    const lines = [];
    lines.push("::: {.quarto-auto-generated-content}\n");
    if (format.metadata[kSlideLogo]) {
        lines.push(`<img src="${format.metadata[kSlideLogo]}" class="slide-logo" />`);
        lines.push("\n");
    }
    lines.push("::: {.footer .footer-default}");
    if (format.metadata[kSlideFooter]) {
        lines.push(String(format.metadata[kSlideFooter]));
    } else {
        lines.push("");
    }
    lines.push(":::");
    lines.push("\n");
    lines.push(":::");
    lines.push("\n");
    return lines.join("\n");
}
const handleOutputLocationSlide = (doc, slideHeadingTags)=>{
    const slideOutputs = doc.querySelectorAll(`.${kOutputLocationSlide}`);
    for (const slideOutput of slideOutputs){
        const slideOutputEl = slideOutput;
        const parentSlide = findParentSlide(slideOutputEl);
        if (parentSlide && parentSlide.parentElement) {
            const newSlide = doc.createElement("section");
            newSlide.setAttribute("id", parentSlide?.id ? parentSlide.id + "-output" : "");
            for (const clz of parentSlide.classList){
                newSlide.classList.add(clz);
            }
            newSlide.classList.add(kOutputLocationSlide);
            if (slideHeadingTags.includes(parentSlide.firstElementChild?.tagName || "")) {
                const headingEl = doc.createElement(parentSlide.firstElementChild?.tagName);
                headingEl.innerHTML = parentSlide.firstElementChild?.innerHTML || "";
                newSlide.appendChild(headingEl);
            }
            newSlide.appendChild(slideOutputEl);
            const nextSlide = parentSlide.nextElementSibling;
            parentSlide.parentElement.insertBefore(newSlide, nextSlide);
        }
    }
};
const handleHashTypeNumber = (doc, format)=>{
    if (format.metadata[kHashType] === "number") {
        const titleSlide = doc.getElementById("title-slide");
        if (titleSlide) {
            titleSlide.removeAttribute("id");
            titleSlide.classList.add("quarto-title-block");
        }
    }
};
const handleAutoGeneratedContent = (doc)=>{
    for (const slide of doc.querySelectorAll("section.slide")){
        const slideContentFromQuarto = slide.querySelector(".quarto-auto-generated-content");
        if (slideContentFromQuarto && slide.getAttribute("data-visibility") === "hidden") {
            if (slideContentFromQuarto.childElementCount === 0) {
                slideContentFromQuarto.remove();
            } else {
                for (const otherSlide of doc.querySelectorAll("section.slide")){
                    if (otherSlide.getAttribute("data-visibility") !== "hidden") {
                        otherSlide.appendChild(slideContentFromQuarto);
                        break;
                    }
                }
            }
        }
    }
};
const fixupRevealJsInitialization = (doc, extraConfig, pluginInit)=>{
    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'");
            scriptEl.innerText = scriptEl.innerText.replace(/width: (\d+(\.\d+)?%)/, "width: '$1'");
            scriptEl.innerText = scriptEl.innerText.replace(/height: (\d+(\.\d+)?%)/, "height: '$1'");
            if (pluginInit.register.length > 0) {
                const kRevealPluginArray = "plugins: [";
                scriptEl.innerText = scriptEl.innerText.replace(kRevealPluginArray, kRevealPluginArray + pluginInit.register.join(", ") + ",\n");
            }
            const configJs = [];
            Object.keys(extraConfig).forEach((key)=>{
                configJs.push(`'${key}': ${JSON.stringify(extraConfig[key])}`);
            });
            Object.keys(pluginInit.revealConfig).forEach((key)=>{
                configJs.push(`'${key}': ${JSON.stringify(pluginInit.revealConfig[key])}`);
            });
            const configStr = configJs.join(",\n");
            scriptEl.innerText = scriptEl.innerText.replace("Reveal.initialize({", `Reveal.initialize({\n${configStr},\n`);
        }
    }
};
const kOutputLocationSlide = "output-location-slide";
const handleInvisibleSlides = (doc)=>{
    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.parentElement?.remove();
            }
        }
        slide.parentNode?.removeChild(slide);
    }
};
const handleUntitledSlidesInToc = (doc)=>{
    const tocEntries = Array.from(doc.querySelectorAll('nav[role="doc-toc"] a[href^="#/"]'));
    for (const tocEntry of tocEntries){
        const tocEntryEl = tocEntry;
        if (tocEntryEl.textContent.trim() === "") {
            tocEntryEl.parentElement?.remove();
        }
    }
};
const handleSlideHeadingAttributes = (doc, slideHeadingTags)=>{
    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");
                            }
                        });
                    }
                }
            }
        }
    });
};
const handleCenteredSlides = (doc, format)=>{
    if (format.metadata[kCenterTitleSlide] !== false) {
        const titleSlide = doc.getElementById("title-slide") ?? doc.querySelector(".reveal .slides section.quarto-title-block");
        if (titleSlide) {
            titleSlide.classList.add("center");
        }
        const titleSlides = doc.querySelectorAll(".title-slide");
        for (const slide of titleSlides){
            slide.classList.add("center");
        }
    }
    if (format.metadata[kCenter] === true) {
        for (const slide of doc.querySelectorAll("section.slide")){
            const slideEl = slide;
            slideEl.classList.add("center");
        }
    }
};
const fixupAssistiveMmlInNotes = (doc)=>{
    const notes = doc.querySelectorAll("aside.notes");
    for (const note of notes){
        const style = doc.createElement("style");
        style.setAttribute("type", "text/css");
        style.innerHTML = `
        span.MJX_Assistive_MathML {
          position:absolute!important;
          clip: rect(1px, 1px, 1px, 1px);
          padding: 1px 0 0 0!important;
          border: 0!important;
          height: 1px!important;
          width: 1px!important;
          overflow: hidden!important;
          display:block!important;
      }`;
        note.appendChild(style);
    }
};
const coalesceAsides = (doc, slideFootnotes)=>{
    const slides = doc.querySelectorAll("section.slide");
    for (const slide of slides){
        const slideEl = slide;
        const asides = slideEl.querySelectorAll("aside:not(.notes)");
        const asideDivs = slideEl.querySelectorAll("div.aside");
        const footnotes = slideEl.querySelectorAll('a[role="doc-noteref"]');
        if (asides.length > 0 || asideDivs.length > 0 || footnotes.length > 0) {
            const aside = doc.createElement("aside");
            const collectAsides = (asideList)=>{
                asideList.forEach((asideEl)=>{
                    const asideDiv = doc.createElement("div");
                    asideDiv.innerHTML = asideEl.innerHTML;
                    aside.appendChild(asideDiv);
                });
                asideList.forEach((asideEl)=>{
                    asideEl.remove();
                });
            };
            collectAsides(asides);
            collectAsides(asideDivs);
            if (slideFootnotes && footnotes.length > 0) {
                const ol = doc.createElement("ol");
                ol.classList.add("aside-footnotes");
                footnotes.forEach((note, index)=>{
                    const noteEl = note;
                    const href = noteEl.getAttribute("href");
                    if (href) {
                        const noteLi = doc.getElementById(href.replace(/^#\//, ""));
                        if (noteLi) {
                            const footnoteBack = noteLi.querySelector(".footnote-back");
                            if (footnoteBack) {
                                footnoteBack.remove();
                            }
                            ol.appendChild(noteLi);
                        }
                    }
                    const sup = doc.createElement("sup");
                    sup.innerText = index + 1 + "";
                    noteEl.replaceWith(sup);
                });
                aside.appendChild(ol);
            }
            slide.appendChild(aside);
        }
    }
};
const handleSlideFootnotes = (doc, slideFootnotes, format, slideLevel)=>{
    const footnotes = doc.querySelectorAll('section[role="doc-endnotes"]');
    if (slideFootnotes) {
        for (const footnoteSection of footnotes){
            footnoteSection.remove();
        }
    } else {
        let footnotesId;
        const footnotes = doc.querySelectorAll('section[role="doc-endnotes"]');
        if (footnotes.length === 1) {
            const footnotesEl = footnotes[0];
            footnotesId = footnotesEl?.getAttribute("id") || "footnotes";
            footnotesEl.setAttribute("id", footnotesId);
            insertFootnotesTitle(doc, footnotesEl, format.language, slideLevel);
            footnotesEl.classList.add("smaller");
            footnotesEl.classList.add("scrollable");
            footnotesEl.classList.remove("center");
            removeFootnoteBacklinks(footnotesEl);
        }
        const notes = doc.querySelectorAll('a[role="doc-noteref"]');
        for (const note of notes){
            const noteEl = note;
            noteEl.setAttribute("data-footnote-href", noteEl.getAttribute("href"));
            noteEl.setAttribute("href", footnotesId ? `#/${footnotesId}` : "");
            noteEl.setAttribute("onclick", footnotesId ? "" : "return false;");
        }
    }
};
const handleRefs = (doc)=>{
    let refsId;
    const refs = doc.querySelector("#refs");
    if (refs) {
        const refsSlide = findParentSlide(refs);
        if (refsSlide) {
            refsId = refsSlide?.getAttribute("id") || "references";
            refsSlide.setAttribute("id", refsId);
        }
        applyClassesToParentSlide(refs, [
            "smaller",
            "scrollable"
        ]);
        removeClassesFromParentSlide(refs, [
            "center"
        ]);
    }
    return refsId;
};
const handleScrollable = (doc, format)=>{
    if (format.metadata[kScrollable] === true) {
        const ol = doc.querySelectorAll("ol");
        for (const olEl of ol){
            const olParent = findParent(olEl, (el)=>{
                return el.nodeName === "SECTION";
            });
            if (olParent) {
                olParent.classList.add("scrollable");
            }
        }
    }
};
const handleCitationLinks = (doc, refsId)=>{
    const cites = doc.querySelectorAll('a[role="doc-biblioref"]');
    for (const cite of cites){
        const citeEl = cite;
        citeEl.setAttribute("href", refsId ? `#/${refsId}` : "");
        citeEl.setAttribute("onclick", refsId ? "" : "return false;");
    }
};
const handleChalkboard = (result1, format)=>{
    const chalkboard = format.metadata["chalkboard"];
    if (typeof chalkboard === "object") {
        const chalkboardSrc = chalkboard["src"];
        if (typeof chalkboardSrc === "string") {
            result1.resources.push(chalkboardSrc);
        }
    }
};
const handleAnchors = (doc)=>{
    const codeLinesAnchors = doc.querySelectorAll("span[id^='cb'] > a[href^='#c']");
    codeLinesAnchors.forEach((codeLineAnchor)=>{
        const codeLineAnchorEl = codeLineAnchor;
        codeLineAnchorEl.removeAttribute("href");
    });
    const anchors = doc.querySelectorAll("a[href^='#/']");
    for (const anchor of anchors){
        const anchorEl = anchor;
        const href = anchorEl.getAttribute("href");
        if (href) {
            const target = doc.getElementById(href.replace(/^#\//, ""));
            if (target) {
                const slide = findParentSlide(target);
                if (slide && slide.getAttribute("id")) {
                    anchorEl.setAttribute("href", `#/${slide.getAttribute("id")}`);
                }
            }
        }
    }
};
const handleInterColumnDivSpaces = (doc)=>{
    for (const slide of doc.querySelectorAll("section.slide")){
        for (const column of slide.querySelectorAll("div.column")){
            const columnEl = column;
            let next = columnEl.nextSibling;
            while(next && next.nodeType === NodeType.TEXT_NODE && next.textContent?.trim() === ""){
                next.parentElement?.removeChild(next);
                next = columnEl.nextSibling;
            }
        }
    }
};
function revealHtmlPostprocessor(format, extraConfig, pluginInit, highlightingMode) {
    return (doc)=>{
        const result1 = {
            resources: [],
            supporting: []
        };
        doc.body.classList.add("quarto-" + highlightingMode);
        const slideFootnotes = format.pandoc[kReferenceLocation] !== "document";
        const slideLevel = format.pandoc[kSlideLevel] || 2;
        const slideHeadingTags = Array.from(Array(slideLevel)).map((_e, i1)=>"H" + (i1 + 1));
        handleOutputLocationSlide(doc, slideHeadingTags);
        handleHashTypeNumber(doc, format);
        fixupRevealJsInitialization(doc, extraConfig, pluginInit);
        handleAutoGeneratedContent(doc);
        handleInvisibleSlides(doc);
        handleUntitledSlidesInToc(doc);
        handleSlideHeadingAttributes(doc, slideHeadingTags);
        handleCenteredSlides(doc, format);
        fixupAssistiveMmlInNotes(doc);
        coalesceAsides(doc, slideFootnotes);
        handleSlideFootnotes(doc, slideFootnotes, format, slideLevel);
        const refsId = handleRefs(doc);
        handleScrollable(doc, format);
        handleCitationLinks(doc, refsId);
        applyStretch(doc, format.metadata[kAutoStretch]);
        handleChalkboard(result1, format);
        handleAnchors(doc);
        handleInterColumnDivSpaces(doc);
        return Promise.resolve(result1);
    };
}
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 image = images[0];
            const imageEl = image;
            if (imageEl.classList.contains("nostretch")) {
                imageEl.classList.remove("nostretch");
                continue;
            }
            if (findParent(imageEl, (el)=>{
                return el.classList.contains("column") || el.classList.contains("quarto-layout-panel") || el.classList.contains("fragment") || el.classList.contains(kOutputLocationSlide) || !!el.className.match(/panel-/);
            }) || slideEl.querySelectorAll("aside:not(.notes)").length !== 0) {
                continue;
            }
            let selNode;
            for (const node of slide.childNodes){
                if (node.contains(image)) {
                    selNode = node;
                    break;
                }
            }
            const nodeEl = selNode;
            if (!nodeEl || nodeEl.nodeName === "P" && nodeEl.childNodes.length > 1) {
                continue;
            }
            const hasStretchClass = function(el) {
                return el.classList.contains("stretch") || el.classList.contains("r-stretch");
            };
            if (nodeEl.nodeName === "P" || nodeEl.nodeName === "DIV" && nodeEl.classList.contains("quarto-figure") || nodeEl.nodeName === "DIV" && nodeEl.classList.contains("cell") || nodeEl.nodeName === "DIV" && hasStretchClass(nodeEl)) {
                if (nodeEl.nodeName === "DIV" && hasStretchClass(nodeEl)) {
                    nodeEl.classList.remove("r-stretch");
                    nodeEl.classList.remove("stretch");
                }
                if (autoStretch === true && !hasStretchClass(imageEl) && !imageEl.getAttribute("style")?.match("height:") && !imageEl.hasAttribute("height") && !imageEl.classList.contains("absolute") && imageEl.parentElement?.nodeName !== "A") {
                    imageEl.classList.add("r-stretch");
                }
                if (hasStretchClass(imageEl) && imageEl.parentNode?.nodeName !== "SECTION") {
                    const removeEmpty = function(el) {
                        const parentEl = el.parentElement;
                        parentEl?.removeChild(el);
                        if (parentEl?.innerText.trim() === "" && parentEl?.nodeName !== "SECTION") {
                            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) imageEl.classList.add(align[0]);
                        const figCaption = nodeEl.querySelector("figcaption");
                        if (figCaption) {
                            caption.classList.add("caption");
                            caption.innerHTML = figCaption.innerHTML;
                        }
                    }
                    const nextEl = nodeEl.nextElementSibling;
                    removeEmpty(imageEl);
                    slideEl.insertBefore(image, nextEl);
                    if (caption.classList.contains("caption")) {
                        slideEl.insertBefore(caption, imageEl.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(el, slideClass = "slide") {
    return findParent(el, (el)=>{
        return el.classList.contains(slideClass);
    });
}
registerWriterFormatHandler((format)=>{
    switch(format){
        case "revealjs":
            return {
                format: revealjsFormat()
            };
    }
});
function asciidocFormat() {
    return mergeConfigs(plaintextFormat("Asciidoc", "adoc"), {
        pandoc: {
            wrap: "none",
            template: formatResourcePath("asciidoc", join2("pandoc", "template.asciidoc")),
            to: "asciidoc"
        },
        extensions: {
            book: asciidocBookExtension
        }
    });
}
const kFormatOutputDir = "book-asciidoc";
const kAsciidocDocType = "asciidoc-doctype";
const kAtlasConfigFile = "atlas.json";
const kRefTargetIdentifier = "refs-target-identifier";
const kRefTargetIndentifierValue = "// quarto-refs-target-378736AB";
const kRefTargetIndentifierMatch = /\/\/ quarto-refs-target-378736AB/g;
const kUseAsciidocNativeCites = "use-asciidoc-native-cites";
const asciidocBookExtension = {
    multiFile: true,
    formatOutputDirectory () {
        return kFormatOutputDir;
    },
    filterParams: (_options)=>{
        return {
            [kUseAsciidocNativeCites]: true,
            [kRefTargetIdentifier]: kRefTargetIndentifierValue
        };
    },
    filterFormat: (source, format, project)=>{
        if (project) {
            const inputFile = relative2(project.dir, source);
            if (isBookIndexPage(inputFile) && !format.pandoc[kOutputFile]) {
                const title = bookOutputStem(project.dir, project.config);
                const adocOutputFile = title + ".adoc";
                format.pandoc[kOutputFile] = adocOutputFile;
            }
            return format;
        } else {
            return format;
        }
    },
    async onMultiFilePrePrender (isIndex, format, markdown, project) {
        if (isIndex) {
            const rootPageMd = await bookRootPageMarkdown(project);
            const completeMd = markdown + "\n" + rootPageMd;
            format.pandoc.variables = format.pandoc.variables || {};
            format.pandoc.variables[kAsciidocDocType] = "book";
            return {
                markdown: completeMd,
                format
            };
        } else {
            format.pandoc.toc = false;
            format.pandoc[kShiftHeadingLevelBy] = -1;
            return {
                format
            };
        }
    },
    async bookPostRender (format, context, _incremental, outputFiles) {
        const projDir = projectOutputDir(context);
        const outDir = join2(projDir, kFormatOutputDir);
        const atlasInFile = join2(context.dir, kAtlasConfigFile);
        const atlasOutFile = join2(outDir, kAtlasConfigFile);
        if (existsSync(atlasInFile)) {
            Deno.copyFileSync(atlasInFile, atlasOutFile);
        } else {
            Deno.writeTextFileSync(atlasOutFile, project2Atlas(projDir, context));
        }
        let refsTarget;
        let indexPage;
        for (const outputFile of outputFiles){
            const path = outputFile.file;
            if (existsSync(path)) {
                const contents = Deno.readTextFileSync(path);
                if (contents.match(kRefTargetIndentifierMatch)) {
                    refsTarget = path;
                }
            }
            const relativePath = relative2(outDir, outputFile.file);
            if (isBookIndexPage(relativePath)) {
                indexPage = outputFile.file;
            }
        }
        if (refsTarget || indexPage) {
            const cites = new Set();
            const citeIndexObj = citeIndex(context.dir);
            for (const key of Object.keys(citeIndexObj)){
                const citeArr = citeIndexObj[key];
                citeArr.forEach((cite)=>{
                    cites.add(cite);
                });
            }
            const biblio = await bookBibliography(outputFiles, context);
            if (biblio.nocite) {
                biblio.nocite.forEach((no)=>{
                    cites.add(no);
                });
            }
            let bibliographyContents = "";
            if (biblio.bibliographyPaths && cites.size) {
                bibliographyContents = await generateBibliography(context, biblio.bibliographyPaths, Array.from(cites), "asciidoc", biblio.csl);
            }
            const cleanedBibliography = lines(bibliographyContents).filter((line)=>{
                return line !== "[[refs]]";
            }).map((line)=>{
                if (line.startsWith("[[ref-")) {
                    return line.replace("[[ref-", "- [[");
                } else {
                    return `  ${line}`;
                }
            }).join("\n").trim();
            if (refsTarget) {
                const refTargetContents = Deno.readTextFileSync(refsTarget);
                const updatedContents = refTargetContents.replace(kRefTargetIndentifierMatch, cleanedBibliography);
                Deno.writeTextFileSync(refsTarget, updatedContents);
            } else if (indexPage) {
                const title = format.language[kSectionTitleReferences] || "References";
                const titleAdoc = `== ${title}`;
                const indexPageContents = Deno.readTextFileSync(indexPage);
                const updatedContents = `${indexPageContents}\n\n${titleAdoc}\n\n[[refs]]\n\n${cleanedBibliography}`;
                Deno.writeTextFileSync(indexPage, updatedContents);
            }
        }
    }
};
function project2Atlas(projDir, context) {
    const bookStem = bookOutputStem(projDir, context.config);
    const bookTitle = bookConfig("title", context.config);
    const atlasJson = {
        branch: "main",
        "files": [
            `${bookStem}.adoc`
        ],
        "formats": {
            "pdf": {
                "version": "web",
                "color_count": "1",
                "index": false,
                "toc": true,
                "syntaxhighlighting": true,
                "show_comments": false
            },
            "epub": {
                "index": false,
                "toc": true,
                "epubcheck": true,
                "syntaxhighlighting": true,
                "show_comments": false
            },
            "mobi": {
                "index": false,
                "toc": true,
                "syntaxhighlighting": true,
                "show_comments": false
            },
            "html": {
                "index": false,
                "toc": true,
                "syntaxhighlighting": true,
                "show_comments": false,
                "consolidated": false
            }
        },
        "title": bookTitle,
        "compat-mode": "false"
    };
    return JSON.stringify(atlasJson, undefined, 2);
}
async function bookRootPageMarkdown(project) {
    const chapters = await chapterInputs(project);
    const appendices = await appendixInputs(project);
    const fileContents = [
        "\n```{=asciidoc}\n\n",
        levelOffset("+1"),
        partsAndChapters(chapters, chapter),
        partsAndChapters(appendices, appendix),
        levelOffset("-1"),
        "```\n"
    ];
    return fileContents.join("\n");
}
function levelOffset(offset) {
    return `:leveloffset: ${offset}\n`;
}
function partsAndChapters(entries, include) {
    return entries.map((entry)=>{
        if (typeof entry === "string") {
            return include(entry);
        } else {
            const partOutput = [];
            if (entry.partPath) {
                partOutput.push(include(entry.partPath));
            } else {
                partOutput.push(levelOffset("-1"));
                partOutput.push(`= ${entry.part}`);
                partOutput.push(levelOffset("+1"));
            }
            for (const chap of entry.chapters){
                partOutput.push(include(chap));
            }
            return partOutput.join("\n");
        }
    }).join("\n");
}
function chapter(path) {
    return `include::${path}[]\n`;
}
function appendix(path) {
    return `[appendix]\n${chapter(path)}\n`;
}
async function chapterInputs(project) {
    const bookContents = bookConfig(kBookChapters, project.config);
    return await resolveBookInputs(bookContents, project, (input)=>{
        return !isBookIndexPage(input);
    });
}
async function appendixInputs(project) {
    const bookApps = bookConfig(kBookAppendix, project.config);
    return bookApps ? await resolveBookInputs(bookApps, project) : [];
}
async function resolveBookInputs(inputs, project, filter) {
    const resolveChapter = async (input)=>{
        if (filter && !filter(input)) {
            return undefined;
        } else {
            const target = await resolveInputTarget(project, input, false);
            if (target) {
                const [dir, stem] = dirAndStem(target?.outputHref);
                const outputFile = join2(dir, `${stem}.adoc`);
                return outputFile;
            } else {
                return undefined;
            }
        }
    };
    const outputs = [];
    for (const input of inputs){
        if (typeof input === "string") {
            const chapterOutput = await resolveChapter(input);
            if (chapterOutput) {
                outputs.push(chapterOutput);
            }
        } else {
            const entry = input;
            const resolvedPart = await resolveChapter(entry.part);
            const entryOutput = {
                partPath: resolvedPart,
                part: resolvedPart ? undefined : entry.part,
                chapters: []
            };
            for (const chapter of entry.chapters){
                const resolved = await resolveChapter(chapter);
                if (resolved) {
                    entryOutput.chapters.push(resolved);
                }
            }
            outputs.push(entryOutput);
        }
    }
    return outputs;
}
registerWriterFormatHandler((format)=>{
    switch(format){
        case "asciidoc":
        case "asciidoctor":
            return {
                format: asciidocFormat()
            };
    }
});
const kValueboxBodySelector = ".card-body > div";
const kValueboxShowcaseClass = ".value-box-showcase";
const kValueboxTitleClass = "value-box-title";
const kValueBoxValueClass = "value-box-value";
const kToParagraphsClz = [
    kValueboxTitleClass,
    kValueBoxValueClass
];
const kValueBoxColorAttr = "data-color";
const kValueBoxBgColorAttr = "data-bg-color";
const kValueBoxFgColorAttr = "data-fg-color";
const kValueBoxIconAttr = "data-icon";
const kValueBoxShowcasePositionAttr = "data-showcase-position";
const kDefaultShowcasePosition = "left-center";
const bsLibValueBoxClass = "bslib-value-box";
const bsLibValueBoxGridClass = "value-box-grid";
const kDefaultColors = [
    "secondary"
];
function isValueBox(el) {
    return el.classList.contains(kValueboxClass) || el.classList.contains(bsLibValueBoxClass);
}
function processValueBoxes(doc) {
    const valueboxNodes = doc.body.querySelectorAll(`.${kValueboxClass}`);
    let autoColorizeCount = 0;
    for (const valueboxNode of valueboxNodes){
        const valueboxEl = valueboxNode;
        applyClasses(valueboxEl, [
            bsLibValueBoxClass
        ]);
        const valueboxBodyEl = valueboxEl.querySelector(kValueboxBodySelector);
        if (valueboxBodyEl) {
            applyClasses(valueboxBodyEl, [
                bsLibValueBoxGridClass
            ]);
            kToParagraphsClz.forEach((cls)=>{
                const toParaEl = valueboxEl.querySelector(`.${cls}`);
                if (toParaEl && toParaEl.tagName !== "P") {
                    const paraEl = doc.createElement("P");
                    paraEl.childNodes = toParaEl.childNodes;
                    for (const toClass of toParaEl.classList){
                        paraEl.classList.add(toClass);
                    }
                    toParaEl.replaceWith(paraEl);
                }
            });
            let colorProcessed = false;
            processAndRemoveAttr(valueboxBodyEl, kValueBoxColorAttr, (_el, attrValue)=>{
                colorEl(valueboxEl, attrValue, "background");
                colorProcessed = true;
            });
            if (!colorProcessed) {
                processAndRemoveAttr(valueboxBodyEl, kValueBoxBgColorAttr, (_el, attrValue)=>{
                    colorEl(valueboxEl, attrValue, "background");
                    colorProcessed = true;
                });
                processAndRemoveAttr(valueboxBodyEl, kValueBoxFgColorAttr, (_el, attrValue)=>{
                    colorEl(valueboxEl, attrValue, "foreground");
                    colorProcessed = true;
                });
            }
            if (!colorProcessed) {
                const suggestedColorIndex = autoColorizeCount % kDefaultColors.length;
                colorEl(valueboxEl, kDefaultColors[suggestedColorIndex], "background");
                autoColorizeCount++;
            }
        }
        const showcaseEl = valueboxEl.querySelector(kValueboxShowcaseClass);
        if (showcaseEl) {
            processAndRemoveAttr(showcaseEl, kValueBoxIconAttr, (el, attrValue)=>{
                const iconEl = doc.createElement("I");
                iconEl.classList.add("bi");
                iconEl.classList.add(`bi-${attrValue}`);
                el.append(iconEl);
            });
            processAndRemoveAttr(showcaseEl, kValueBoxShowcasePositionAttr, (_el, attrValue)=>{
                valueboxEl.classList.add(`showcase-${attrValue}`);
            }, kDefaultShowcasePosition);
        }
    }
}
const isHtmlColor = (color)=>{
    return color.startsWith("#");
};
const colorEl = (el, color, type)=>{
    if (isHtmlColor(color)) {
        const styleName = type === "background" ? "background" : "color";
        const style = el.getAttribute("style");
        const currentStyle = style !== null ? style : "";
        el.setAttribute("style", currentStyle + ` ${styleName}: ${color};`);
    } else {
        const clsPrefix = type === "background" ? "bg-" : "text-";
        el.classList.add(`${clsPrefix}${color}`);
    }
};
const kExpandBtnHtml = `
<bslib-tooltip placement="auto" bsoptions="[]" data-require-bs-version="5" data-require-bs-caller="tooltip()">
    <template>Expand</template>
    <span class="bslib-full-screen-enter badge rounded-pill">
        <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 24 24" style="height:1em;width:1em;" aria-hidden="true" role="img"><path d="M20 5C20 4.4 19.6 4 19 4H13C12.4 4 12 3.6 12 3C12 2.4 12.4 2 13 2H21C21.6 2 22 2.4 22 3V11C22 11.6 21.6 12 21 12C20.4 12 20 11.6 20 11V5ZM4 19C4 19.6 4.4 20 5 20H11C11.6 20 12 20.4 12 21C12 21.6 11.6 22 11 22H3C2.4 22 2 21.6 2 21V13C2 12.4 2.4 12 3 12C3.6 12 4 12.4 4 13V19Z"></path></svg>
    </span>
</bslib-tooltip>
`;
const kRowsClass = "rows";
const kSidebarPanelClass = "sidebar-panel";
const kCardBodyClass = "card-body";
const kCardHeaderClass = "card-header";
const kCardFooterClass = "card-footer";
const kCardTitleClass = "card-title";
const kCardToolbarClass = "card-toolbar";
const kCardSidebarClass = "card-sidebar";
const kTabsetClass = "tabset";
const kTabsetIdPrefix = "card-tabset-";
const kAttrTitle = "data-title";
const kAttrExpandable = "data-expandable";
const kAttrMaxHeight = "data-max-height";
const kAttrMinHeight = "data-min-height";
const kAttrHeight = "data-height";
const kAttrPadding = "data-padding";
const kAttrFullScreen = "data-full-screen";
const kBsCardClasses = [
    "bslib-card",
    "html-fill-container"
];
const kBsCardScriptInitAttrs = {
    ["data-bslib-card-init"]: ""
};
const kBsTabsetCardHeaderClasses = [
    "bslib-navs-card-title"
];
const kQuartoHideTitleClass = "dashboard-card-no-title";
const kBsCardAttributes = {
    ["data-bslib-card-init"]: "",
    ["data-require-bs-caller"]: "card()"
};
const cardAttrHandlers = (doc, dashboardMeta)=>{
    return [
        {
            attr: kAttrExpandable,
            handle: (el, attrValue)=>{
                if (attrValue !== "false") {
                    const shellEl = doc.createElement("DIV");
                    shellEl.innerHTML = kExpandBtnHtml;
                    for (const childEl of shellEl.children){
                        el.appendChild(childEl);
                    }
                    el.setAttribute(kAttrFullScreen, "false");
                }
            },
            defaultValue: (el)=>{
                if (el.classList.contains(kValueboxClass) || hasFlowLayout(el)) {
                    return "false";
                } else {
                    return dashboardMeta.expandable ? "true" : "false";
                }
            }
        },
        {
            attr: kAttrMaxHeight,
            handle: ensureCssUnits(attrToStyle("max-height"))
        },
        {
            attr: kAttrMinHeight,
            handle: ensureCssUnits(attrToStyle("min-height"))
        },
        {
            attr: kAttrHeight,
            handle: ensureCssUnits(attrToStyle("height"))
        },
        {
            attr: kAttrPadding,
            handle: ensureCssUnits(attrToCardBodyStyle("padding"))
        }
    ];
};
const cardBodyAttrHandlers = ()=>{
    return [
        {
            attr: kAttrMaxHeight,
            handle: ensureCssUnits(attrToStyle("max-height"))
        },
        {
            attr: kAttrMinHeight,
            handle: ensureCssUnits(attrToStyle("min-height"))
        },
        {
            attr: kAttrHeight,
            handle: ensureCssUnits(attrToStyle("height"))
        }
    ];
};
const kColumnsClass = "columns";
const kHeightAttr = "data-height";
const kWidthAttr = "data-width";
const kBsLibGridClass = "bslib-grid";
const kHtmlFillItemClass = "html-fill-item";
const kHtmlFillContainerClass = "html-fill-container";
const kHiddenClass = "hidden";
const kNeverFillClasses = [
    "value-box-grid",
    "value-box-area",
    "value-box-title",
    "value-box-value",
    "nav-tabs",
    "card-header",
    "card-footer",
    "callout",
    "h1",
    "h2",
    "h3",
    "h4",
    "h5",
    "h6",
    "input-panel",
    "toolbar",
    "flow"
];
const kFillContentElements = {
    tags: [
        {
            name: "div",
            ignoreClasses: kNeverFillClasses
        }
    ],
    classes: [
        "card",
        "card-body",
        "tab-pane",
        "tab-content",
        "tabset",
        "bslib-grid",
        "bslib-grid-item",
        "sidebar-content",
        "main",
        "bslib-sidebar-layout",
        "cell-output-display",
        "quarto-float"
    ]
};
const kFillContainerElements = {
    tags: kFillContentElements.tags,
    classes: [
        ...kFillContentElements.classes,
        "bslib-page-fill"
    ]
};
const kFillDontRecurseInsideClasses = [
    "sidebar",
    "toolbar"
];
function processRows(doc) {
    const rowNodes = doc.querySelectorAll(`div.${kRowsClass}`);
    if (rowNodes !== null) {
        for (const rowNode of rowNodes){
            const rowEl = rowNode;
            rowEl.classList.add(kBsLibGridClass);
            rowEl.classList.remove(kRowsClass);
            const rowLayouts = computeRowLayouts(rowEl);
            const fillFr = computeFillFr(rowLayouts);
            const rowGridSizes = rowLayouts.map((layout)=>{
                return toGridSize(layout, fillFr);
            });
            const gridTemplRowsVal = `${rowGridSizes.join(" ")}`;
            const currentStyle = rowEl.getAttribute("style");
            const template = `display: grid; grid-template-rows: ${gridTemplRowsVal}; grid-auto-columns: minmax(0, 1fr);`;
            rowEl.setAttribute("style", currentStyle === null ? template : `${currentStyle}\n${template}`);
        }
    }
}
function processColumns(doc) {
    const colNodes = doc.querySelectorAll(`div.${kColumnsClass}`);
    if (colNodes !== null) {
        for (const colNode of colNodes){
            const colEl = colNode;
            colEl.classList.add(kBsLibGridClass);
            colEl.classList.remove(kColumnsClass);
            const colLayouts = computeColumnLayouts(colEl);
            const fillFr = computeFillFr(colLayouts);
            const gridTemplColVal = `${colLayouts.map((layout)=>{
                return toGridSize(layout, fillFr);
            }).join(" ")}`;
            const currentStyle = colEl.getAttribute("style");
            const template = `display: grid; grid-template-columns: ${gridTemplColVal};\ngrid-auto-rows: minmax(0, 1fr);`;
            colEl.setAttribute("style", currentStyle === null ? template : `${currentStyle}\n${template}`);
        }
    }
}
function computeColumnLayouts(colEl) {
    const layouts = [];
    for (const childEl of colEl.children){
        if (childEl.classList.contains(kHiddenClass) || childEl.classList.contains(kDashboardGridSkip)) {} else {
            const explicitWidth = childEl.getAttribute(kWidthAttr);
            if (explicitWidth !== null) {
                childEl.removeAttribute(kWidthAttr);
                layouts.push(explicitWidth);
            } else {
                layouts.push(kLayoutFill);
            }
        }
    }
    return layouts;
}
function isFlowCard(el) {
    const layouts = cardBodyLayouts(el);
    return layouts.every((layout)=>{
        return layout === kLayoutFlow;
    });
}
function computeRowLayouts(rowEl) {
    const parentFillRaw = rowEl.getAttribute(kFillAttr);
    const parentLayout = parentFillRaw !== null ? asLayout(parentFillRaw) : null;
    const layouts = [];
    for (const childEl of rowEl.children){
        const explicitHeight = childEl.getAttribute(kHeightAttr);
        if (childEl.classList.contains(kHiddenClass) || childEl.classList.contains(kDashboardGridSkip)) {} else if (explicitHeight !== null) {
            childEl.removeAttribute(kHeightAttr);
            layouts.push(explicitHeight);
        } else {
            const fill = childEl.getAttribute(kFillAttr);
            if (fill !== null) {
                layouts.push(asLayout(fill));
            } else {
                if (childEl.classList.contains(kRowsClass)) {
                    const rowLayouts = computeRowLayouts(childEl);
                    if (rowLayouts.some((layout)=>layout === kLayoutFill)) {
                        layouts.push(kLayoutFill);
                    } else {
                        layouts.push(kLayoutFlow);
                    }
                } else if (childEl.classList.contains(kColumnsClass)) {
                    const layout = rowLayoutForColumn(childEl, parentLayout);
                    layouts.push(layout);
                } else if (childEl.classList.contains(kCardClass)) {
                    const isFlow = isFlowCard(childEl);
                    layouts.push(isFlow ? kLayoutFlow : kLayoutFill);
                } else {
                    if (parentLayout !== null) {
                        layouts.push(parentLayout);
                    } else {
                        layouts.push(kLayoutFill);
                    }
                }
            }
        }
    }
    return layouts;
}
function toGridSize(layout, fillFr) {
    if (layout === kLayoutFill) {
        return `minmax(${kMinSizeRow}, ${fillFr}fr)`;
    } else if (layout === kLayoutFlow) {
        return `minmax(${kMinSizeRow}, max-content)`;
    } else {
        if (layout.endsWith("px")) {
            return layout;
        } else if (layout.match(kEndsWithNumber1)) {
            return `${layout}px`;
        } else if (layout.endsWith("%")) {
            const percentRaw = parseFloat(layout.slice(0, -1));
            const layoutSize = `minmax(${kMinSizeRow}, ${percentRaw}fr)`;
            return layoutSize;
        } else {
            return `minmax(${kMinSizeRow}, ${asCssSize(layout)})`;
        }
    }
}
const kEndsWithNumber1 = /[0-9]$/;
const kMinSizeRow = "3em";
function computeFillFr(layouts) {
    const percents = [];
    let unallocatedFills = 0;
    for (const layout of layouts){
        if (layout === kLayoutFill) {
            unallocatedFills++;
        } else if (layout.endsWith("%")) {
            const unitless = layout.slice(0, -1);
            percents.push(parseFloat(unitless));
        }
    }
    const allocatedPercent = percents.reduce((prev, current)=>{
        return prev + current;
    }, 0);
    let fillFr = 1;
    if (allocatedPercent > 0) {
        if (allocatedPercent < 100) {
            fillFr = (100 - allocatedPercent) / unallocatedFills;
        } else {
            fillFr = percents[percents.length - 1];
        }
    }
    return fillFr;
}
function asLayout(fill) {
    if (fill !== "false") {
        return kLayoutFill;
    } else {
        return kLayoutFlow;
    }
}
const kFlowLayoutDetectors = [
    isValueBox,
    isFlowCard
];
function suggestsFlowLayout(el) {
    return kFlowLayoutDetectors.some((detector)=>{
        return detector(el);
    });
}
function suggestLayout(el) {
    const explicitFill = el.getAttribute(kFillAttr);
    if (explicitFill !== null) {
        return explicitFill !== "false" ? kLayoutFill : kLayoutFlow;
    } else {
        if (suggestsFlowLayout(el)) {
            return kLayoutFlow;
        } else {
            return kLayoutFill;
        }
    }
}
function rowLayoutForColumn(colEl, defaultLayout) {
    const layouts = [];
    for (const childEl of colEl.children){
        layouts.push(suggestLayout(childEl));
    }
    return layouts.some((layout)=>layout === kLayoutFill) ? defaultLayout ? defaultLayout : kLayoutFill : kLayoutFlow;
}
const recursiveApplyFillClasses = (el)=>{
    applyFillItemClasses(el);
    applyFillContainerClasses(el);
    for (const childEl of el.children){
        const recurse = !kFillDontRecurseInsideClasses.some((cls)=>{
            return el.classList.contains(cls);
        });
        if (recurse) {
            recursiveApplyFillClasses(childEl);
        }
    }
};
const kSidebarClass = "sidebar";
const kSidebarContentClass = "sidebar-content";
const kSidebarAttrPosition = "data-position";
const kSidebarAttrPositionRight = "right";
const kBsLibSidebarRight = "sidebar-right";
function makeSidebar(id, sidebar, contents, doc) {
    const sidebarContainerEl = makeEl("div", {
        classes: [
            "bslib-sidebar-layout",
            "html-fill-item"
        ],
        attributes: {
            "data-bslib-sidebar-open": "desktop",
            "data-bslib-sidebar-init": "true"
        }
    }, doc);
    const sidebarMainEl = makeEl("div", {
        classes: [
            "main",
            "html-fill-container"
        ]
    }, doc);
    contents.forEach((content)=>{
        sidebarMainEl.appendChild(content);
    });
    processAndRemoveAttr(sidebar, kSidebarAttrPosition, (_el, value)=>{
        if (value === kSidebarAttrPositionRight) {
            sidebarContainerEl.classList.add(kBsLibSidebarRight);
        }
    });
    processAndRemoveAttr(sidebar, "data-width", (_el, value)=>{
        const size = asCssSize(value);
        const styleRaw = sidebarContainerEl.getAttribute("style");
        const styleVal = styleRaw !== null ? styleRaw : "";
        const newStyle = styleVal + " --bslib-sidebar-width: " + size;
        sidebarContainerEl.setAttribute("style", newStyle);
    });
    sidebar?.classList.remove(kSidebarClass);
    const sidebarAsideEl = makeEl("aside", {
        id,
        classes: [
            kSidebarClass,
            "html-fill-container",
            "html-fill-item"
        ]
    }, doc);
    if (sidebar !== null) {
        sidebar.classList.add("html-fill-container", "html-fill-item");
        sidebarAsideEl.appendChild(sidebar);
    }
    sidebarContainerEl.appendChild(sidebarMainEl);
    recursiveApplyFillClasses(sidebarContainerEl);
    sidebarContainerEl.appendChild(sidebarAsideEl);
    sidebarContainerEl.append(...sidebarToggle(id, doc));
    return sidebarContainerEl;
}
function processCards(doc, dashboardMeta) {
    const cardNodes = doc.body.querySelectorAll(`.${kCardClass}`);
    let cardCount = 0;
    for (const cardNode of cardNodes){
        cardCount++;
        const cardEl = cardNode;
        const cardBodyEls = [];
        let cardHeaderEl = undefined;
        let cardSidebarEl = undefined;
        for (const cardChildEl of cardEl.children){
            if (cardChildEl.classList.contains(kCardBodyClass)) {
                cardBodyEls.push(cardChildEl);
            } else if (cardChildEl.classList.contains(kCardHeaderClass)) {
                cardHeaderEl = cardChildEl;
            } else if (cardChildEl.classList.contains(kCardSidebarClass)) {
                cardSidebarEl = cardChildEl;
            }
        }
        if (cardHeaderEl) {
            const looseText = [];
            const cardToolbarEl = cardHeaderEl.querySelector(`.${kCardToolbarClass}`);
            for (const headerChildNode of cardHeaderEl.childNodes){
                if (headerChildNode.nodeType === Node.TEXT_NODE && headerChildNode.textContent.trim() !== "") {
                    looseText.push(headerChildNode.textContent.trim());
                    headerChildNode.parentNode?.removeChild(headerChildNode);
                }
            }
            if (looseText.length > 0) {
                const classes = [
                    kCardTitleClass
                ];
                const titleTextDiv = makeEl("DIV", {
                    classes
                }, doc);
                titleTextDiv.innerText = looseText.join(" ");
                if (cardToolbarEl) {
                    cardToolbarEl.insertBefore(titleTextDiv, cardToolbarEl.firstChild);
                } else {
                    cardHeaderEl.insertBefore(titleTextDiv, cardHeaderEl.firstChild);
                }
            } else {
                cardHeaderEl.classList.add(kQuartoHideTitleClass);
            }
        }
        applyClasses(cardEl, kBsCardClasses);
        applyAttributes(cardEl, kBsCardAttributes);
        const tabSetId = cardEl.classList.contains(kTabsetClass) ? `${kTabsetIdPrefix}${cardCount}` : undefined;
        if (tabSetId) {
            if (cardHeaderEl) {
                convertToTabsetHeader(tabSetId, cardHeaderEl, cardBodyEls, doc);
            }
            convertToTabs(tabSetId, cardEl, cardBodyEls, cardSidebarEl, doc);
        } else {
            if (cardSidebarEl) {
                cardBodyEls.forEach((el)=>el.remove);
                const sidebarId = `card-${cardCount}-card-sidebar`;
                const sidebarContainerEl = makeSidebar(sidebarId, cardSidebarEl, cardBodyEls, doc);
                cardEl.appendChild(sidebarContainerEl);
            }
        }
        for (const cardAttrHandler of cardAttrHandlers(doc, dashboardMeta)){
            const defaultValue = cardAttrHandler.defaultValue ? cardAttrHandler.defaultValue(cardEl) : undefined;
            processAndRemoveAttr(cardEl, cardAttrHandler.attr, cardAttrHandler.handle, defaultValue);
        }
        for (const cardBodyEl of cardBodyEls){
            const layout = cardBodyLayout(cardBodyEl);
            if (layout === kLayoutFlow) {
                cardBodyEl.classList.add(kLayoutFlow);
            }
            for (const cardBodyAttrHandler of cardBodyAttrHandlers()){
                processAndRemoveAttr(cardBodyEl, cardBodyAttrHandler.attr, cardBodyAttrHandler.handle);
                if (!tabSetId) {
                    recursiveApplyFillClasses(cardBodyEl);
                }
            }
        }
        cardEl.appendChild(initCardScript(doc));
    }
}
function cardBodyLayouts(el) {
    const cardBodyNodes = el.querySelectorAll(`.${kCardBodyClass}`);
    const layouts = [];
    for (const cardBodyNode of cardBodyNodes){
        layouts.push(cardBodyLayout(cardBodyNode));
    }
    return layouts;
}
function cardBodyLayout(cardBodyEl) {
    const explicitFill = cardBodyEl.getAttribute(kFillAttr);
    if (explicitFill !== null) {
        return explicitFill !== "false" ? kLayoutFill : kLayoutFlow;
    } else if (shinyInputs(cardBodyEl)) {
        return kLayoutFlow;
    } else {
        return kLayoutFill;
    }
}
function shinyInputs(cardBodyEl) {
    for (const childEl of cardBodyEl.children){
        if (!childEl.classList.contains("cell-output")) {
            return false;
        }
        if (childEl.childElementCount < 1) {
            return false;
        }
        const firstChildEl = childEl.children.item(0);
        if (!firstChildEl.classList.contains("shiny-input-container")) {
            return false;
        }
    }
    return true;
}
function initCardScript(doc) {
    const scriptInitEl = doc.createElement("SCRIPT");
    applyAttributes(scriptInitEl, kBsCardScriptInitAttrs);
    scriptInitEl.innerText = "bslib.Card.initializeAllCards();";
    return scriptInitEl;
}
function convertToTabsetHeader(tabSetId, cardHeaderEl, cardBodyEls, doc) {
    applyClasses(cardHeaderEl, kBsTabsetCardHeaderClasses);
    const ulEl = doc.createElement("UL");
    applyClasses(ulEl, [
        "nav",
        "nav-tabs",
        "card-header-tabs"
    ]);
    applyAttributes(ulEl, {
        role: "tablist",
        ["data-tabsetid"]: tabSetId
    });
    let cardBodyCount = 0;
    for (const cardBodyEl of cardBodyEls){
        cardBodyCount++;
        let cardBodyTitle = cardBodyEl.getAttribute(kAttrTitle);
        if (cardBodyTitle == null) {
            cardBodyTitle = `Tab ${cardBodyCount}`;
        }
        const liEl = doc.createElement("LI");
        applyClasses(liEl, [
            "nav-item"
        ]);
        applyAttributes(liEl, {
            role: "presentation"
        });
        const aEl = doc.createElement("A");
        applyAttributes(aEl, {
            href: `#${tabSetId}-${cardBodyCount}`,
            role: "tab",
            ["data-toggle"]: "tab",
            ["data-bs-toggle"]: "tab",
            ["data-value"]: cardBodyTitle,
            ["aria-selected"]: cardBodyCount === 1 ? "true" : "false"
        });
        const clz = [
            "nav-link"
        ];
        if (cardBodyCount === 1) {
            clz.push("active");
        }
        applyClasses(aEl, clz);
        aEl.innerText = cardBodyTitle;
        liEl.appendChild(aEl);
        ulEl.appendChild(liEl);
    }
    cardHeaderEl.appendChild(ulEl);
}
function findFooterEl(cardEl) {
    for (const childEl of cardEl.children){
        if (childEl.classList.contains(kCardFooterClass)) {
            return childEl;
        }
    }
}
function convertToTabs(tabSetId, cardEl, cardBodyEls, cardSidebarEl, doc) {
    const cardFooterEl = findFooterEl(cardEl);
    const tabContainerEl = tabSetId ? doc.createElement("DIV") : undefined;
    if (tabContainerEl) {
        tabContainerEl.classList.add("tab-content");
        tabContainerEl.setAttribute("data-tabset-id", tabSetId);
        if (cardFooterEl) {
            cardEl.insertBefore(tabContainerEl, cardFooterEl);
        } else {
            cardEl.appendChild(tabContainerEl);
        }
    }
    let cardBodyCount = 0;
    for (const cardBodyEl of cardBodyEls){
        cardBodyCount++;
        for (const cardBodyAttrHandler of cardBodyAttrHandlers()){
            processAndRemoveAttr(cardBodyEl, cardBodyAttrHandler.attr, cardBodyAttrHandler.handle);
        }
        if (tabContainerEl) {
            const tabPaneEl = doc.createElement("DIV");
            tabPaneEl.classList.add("tab-pane");
            if (cardBodyCount === 1) {
                tabPaneEl.classList.add("active");
                tabPaneEl.classList.add("show");
            }
            tabPaneEl.setAttribute("role", "tabpanel");
            tabPaneEl.id = `${tabSetId}-${cardBodyCount}`;
            tabPaneEl.appendChild(cardBodyEl);
            tabContainerEl.appendChild(tabPaneEl);
        }
    }
    if (tabContainerEl) {
        recursiveApplyFillClasses(tabContainerEl);
    }
    if (cardSidebarEl && tabContainerEl) {
        const sidebarId = `${tabSetId}-card-sidebar`;
        const sidebarContainerEl = makeSidebar(sidebarId, cardSidebarEl, [
            tabContainerEl
        ], doc);
        if (cardFooterEl) {
            cardEl.insertBefore(sidebarContainerEl, cardFooterEl);
        } else {
            cardEl.appendChild(sidebarContainerEl);
        }
    }
}
const shouldApplyClasses = (el, fillDescriptor)=>{
    if (kDontMutateTags.includes(el.tagName.toUpperCase())) {
        return false;
    }
    if (kNeverFillClasses.some((neverFillClass)=>{
        return el.classList.contains(neverFillClass);
    })) {
        return false;
    }
    if (el.tagName === "DIV" && el.children.length > 0) {
        let hasFillChild = false;
        for (const childNode of el.childNodes){
            const childEl = childNode;
            if (!childEl.classList?.contains(kLayoutFlow)) {
                hasFillChild = true;
                break;
            }
        }
        return hasFillChild;
    }
    const fillForClass = fillDescriptor.classes.some((clz)=>{
        if (el.classList.contains(clz)) {
            return true;
        }
    });
    if (fillForClass) {
        return true;
    }
    const fillForTagDesc = fillDescriptor.tags.some((tagDesc)=>{
        return tagDesc.name.toLowerCase() === el.tagName.toLowerCase() && !tagDesc.ignoreClasses.some((clz)=>{
            return el.classList.contains(clz);
        });
    });
    if (fillForTagDesc) {
        return true;
    }
    return false;
};
const applyFillItemClasses = (el)=>{
    if (shouldApplyClasses(el, kFillContentElements)) {
        el.classList.add(kHtmlFillItemClass);
    }
};
const applyFillContainerClasses = (el)=>{
    if (shouldApplyClasses(el, kFillContainerElements)) {
        el.classList.add(kHtmlFillContainerClass);
    }
};
function processSidebars(doc) {
    const sidebarNodes = doc.querySelectorAll(`.${kSidebarPanelClass}`);
    let sidebarCount = 1;
    for (const sidebarNode of sidebarNodes){
        const sidebarEl = sidebarNode;
        const sidebarId = sidebarEl.id !== "" ? sidebarEl.id : `bslib-sidebar-${sidebarCount++}`;
        const sidebarContentsEl = sidebarEl.querySelector(`.${kSidebarClass}`);
        const sidebarMainContentsEl = sidebarEl.querySelector(`.${kSidebarContentClass}`);
        let sidebarContainerEl = undefined;
        if (sidebarContentsEl !== null && sidebarMainContentsEl !== null) {
            sidebarContainerEl = makeSidebar(sidebarId, sidebarContentsEl, [
                sidebarMainContentsEl
            ], doc);
            sidebarEl.replaceWith(sidebarContainerEl);
            sidebarContainerEl.parentElement?.classList.add("dashboard-sidebar-container");
        }
    }
    const topLevelSidebar = doc.querySelector(".page-layout-custom > .bslib-sidebar-layout, .page-layout-custom .dashboard-page > .bslib-sidebar-layout");
    if (topLevelSidebar !== null) {
        topLevelSidebar.setAttribute("data-bslib-sidebar-border", "false");
        topLevelSidebar.setAttribute("data-bslib-sidebar-border-radius", "false");
        doc.body.classList.add("dashboard-sidebar");
    }
}
function sidebarToggle(id, doc) {
    const html = `
<button class="collapse-toggle" type="button" title="Toggle sidebar" aria-expanded="true" aria-controls="${id}">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" class="bi bi-chevron-left collapse-icon" style="fill:currentColor;" aria-hidden="true" role="img">
      <path fill-rule="evenodd" d="M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z"></path>
    </svg>
</button>
<script data-bslib-sidebar-init>
bslib.Sidebar.initCollapsibleAll()
</script>
`;
    const container = doc.createElement("DIV");
    container.innerHTML = html;
    return container.childNodes;
}
const kPageClass = "dashboard-page";
const kAttrTitle1 = "data-title";
const kAttrScrolling = "data-scrolling";
const kDashboardPagesClass = "quarto-dashboard-pages";
function processPages(doc, dashboardMeta) {
    const pageNodes = doc.querySelectorAll(`.${kPageClass}`);
    if (pageNodes.length === 0) {
        return;
    }
    const contentEl = doc.querySelector(".quarto-dashboard-content");
    if (contentEl !== null) {
        contentEl.classList.add(kDashboardPagesClass);
    }
    const navbarEl = doc.querySelector("#quarto-dashboard-header .navbar");
    if (!navbarEl) {
        throw new Error("Expected a navbar in the dashboard output since pages are specified.");
    }
    const navbarContainerEl = navbarEl.querySelector(".navbar-container");
    if (!navbarContainerEl) {
        throw new Error("Expected the navbar to have a container marked with `.navbar-container`.");
    }
    const navbarTogglerEl = navbarEl.querySelector(".navbar-toggler");
    if (navbarTogglerEl) {
        navbarTogglerEl.classList.remove("hidden");
    }
    if (dashboardMeta.hasDarkMode) {
        const toggleEl = makeEl("a", {
            classes: [
                "quarto-color-scheme-toggle"
            ],
            attributes: {
                href: "",
                onclick: "window.quartoToggleColorScheme(); return false;"
            }
        }, doc);
        const iEl = makeEl("i", {
            classes: [
                "bi"
            ]
        }, doc);
        toggleEl.append(iEl);
        navbarContainerEl.append(toggleEl);
    }
    const navItems = [];
    let counter = 1;
    for (const pageNode of pageNodes){
        const pageEl = pageNode;
        const scrolling = pageEl.getAttribute(kAttrScrolling) !== null ? pageEl.getAttribute(kAttrScrolling) === "true" : dashboardMeta.scrolling;
        const id = pageEl.id ? pageEl.id : "dashboard-page-" + counter;
        const text = pageEl.getAttribute(kAttrTitle1);
        pageEl.removeAttribute(kAttrTitle1);
        const active = counter === 1;
        pageEl.parentElement?.classList.add("tab-content");
        pageEl.id = id;
        pageEl.classList.add("tab-pane");
        pageEl.setAttribute("aria-labelledby", `tab-${id}`);
        if (active) {
            pageEl.classList.add("show");
            pageEl.classList.add("active");
        } else {
            pageEl.classList.add(kDashboardGridSkip);
        }
        recursiveApplyFillClasses(pageEl);
        navItems.push({
            id,
            text: text !== null ? text : "Page " + counter,
            active,
            scrolling
        });
        counter++;
    }
    const navUlEl = makeEl("ul", {
        classes: [
            "navbar-nav",
            "navbar-nav-scroll",
            "me-auto"
        ],
        attributes: {
            role: "tablist"
        }
    }, doc);
    for (const navItem of navItems){
        navUlEl.append(toNav(navItem, doc));
    }
    const collapseEl = makeEl("div", {
        id: "dashboard-collapse",
        classes: [
            "navbar-collapse",
            "collapse"
        ]
    }, doc);
    collapseEl.append(navUlEl);
    navbarContainerEl.append(collapseEl);
}
function toNav(navItem, doc) {
    const liEl = makeEl("li", {
        classes: [
            "nav-item"
        ],
        attributes: {
            role: "presentation"
        }
    }, doc);
    const classes = [
        "nav-link"
    ];
    if (navItem.active) {
        classes.push("active");
    }
    const aEl = makeEl("a", {
        id: `tab-${navItem.id}`,
        classes,
        attributes: {
            "data-bs-toggle": "tab",
            "role": "tab",
            "data-bs-target": `#${navItem.id}`,
            [kAttrScrolling]: navItem.scrolling.toString(),
            "href": `#${navItem.id}`,
            "aria-controls": navItem.id,
            "aria-selected": navItem.active.toString()
        }
    }, doc);
    const spanEl = makeEl("span", {
        classes: [
            "nav-link-text"
        ]
    }, doc);
    spanEl.innerText = navItem.text;
    aEl.append(spanEl);
    liEl.append(aEl);
    return liEl;
}
function processNavButtons(doc, dashboardMeta) {
    const buttons = dashboardMeta[kNavButtons];
    if (buttons === undefined || buttons.length === 0) {
        return;
    }
    const navbarEl = doc.querySelector(".navbar");
    if (!navbarEl) {
        throw new Error("Expected a navbar in the dashboard output since pages are specified.");
    }
    const navbarContainerEl = navbarEl.querySelector(".navbar-container");
    if (!navbarContainerEl) {
        throw new Error("Expected the navbar to have a container marked with `.navbar-container`.");
    }
    const containerEl = makeEl("DIV", {
        classes: [
            "quarto-dashboard-links"
        ]
    }, doc);
    buttons.forEach((btn)=>{
        const linkAttr = {
            href: btn.href
        };
        if (btn.rel) {
            linkAttr.rel = btn.rel;
        }
        if (btn.title) {
            linkAttr.title = btn.title;
        }
        if (btn.target) {
            linkAttr.target = btn.target;
        }
        if (btn["aria-label"]) {
            linkAttr["aria-label"] = btn["aria-label"];
        }
        const linkEl = makeEl("A", {
            classes: [
                "quarto-dashboard-link"
            ],
            attributes: linkAttr
        }, doc);
        if (btn.icon) {
            const iconEl = makeEl("I", {
                classes: [
                    "bi",
                    `bi-${btn.icon}`
                ]
            }, doc);
            linkEl.appendChild(iconEl);
        }
        if (btn.text) {
            const textEl = makeEl("SPAN", {
                classes: [
                    "quarto-dashboard-link-text"
                ]
            }, doc);
            textEl.innerText = btn.text;
            linkEl.appendChild(textEl);
        }
        containerEl.appendChild(linkEl);
    });
    const navbarCollapseEl = navbarEl.querySelector(`.navbar-collapse`);
    if (navbarCollapseEl) {
        navbarCollapseEl.appendChild(containerEl);
    } else {
        navbarContainerEl.appendChild(containerEl);
    }
}
function processNavigation(doc) {
    const websiteNavbarHeaderEl = doc.getElementById("quarto-header");
    if (websiteNavbarHeaderEl) {
        const dashboardHeaderEl = doc.getElementById("quarto-dashboard-header");
        if (dashboardHeaderEl) {
            websiteNavbarHeaderEl.appendChild(dashboardHeaderEl);
        }
    }
}
function processShinyComponents(doc) {
    const inputContainerNodes = doc.querySelectorAll(".shiny-input-container");
    for (const inputContainerNode of inputContainerNodes){
        const inputContainerEl = inputContainerNode;
        const sliderEl = inputContainerEl.querySelector("input.js-range-slider");
        if (sliderEl) {
            inputContainerEl.classList.add("no-baseline");
        }
    }
}
const kToolbarPanelClass = "toolbar-panel";
const kToolbarClass = "toolbar";
const kToolbarContentClass = "toolbar-content";
const kToolbarAttrHeight = "data-height";
const kToolbarAttrPosition = "data-position";
const kToolbarAttrPositionEnd = "end";
const kToolbarBottomClass = "toolbar-bottom";
const kToolbarTopLevelClass = "toolbar-toplevel";
const kDashboardToolbarClass = "dashboard-toolbar";
function processToolbars(doc) {
    const toolbarNodes = doc.querySelectorAll(`.${kToolbarPanelClass}`);
    for (const toolbarNode of toolbarNodes){
        const toolbarInputEl = toolbarNode;
        const toolbarContainerEl = makeEl("div", {
            classes: [
                "html-fill-item",
                "html-fill-container"
            ],
            attributes: {}
        }, doc);
        const toolbarEl = toolbarInputEl.querySelector(`.${kToolbarClass}`);
        if (toolbarEl) {
            processAndRemoveAttr(toolbarEl, kToolbarAttrPosition, (el, value)=>{
                if (value === kToolbarAttrPositionEnd) {
                    el.classList.add(kToolbarBottomClass);
                }
            });
            processAndRemoveAttr(toolbarEl, kToolbarAttrHeight, (_el, value)=>{
                const size = asCssSize(value);
                const styleRaw = toolbarInputEl.parentElement?.getAttribute("style");
                const styleVal = styleRaw !== null ? styleRaw : "";
                const newStyle = styleVal + " --bslib-sidebar-height: " + size;
                toolbarInputEl.parentElement?.setAttribute("style", newStyle);
            });
            toolbarEl.classList.add("html-fill-container");
            toolbarContainerEl.appendChild(toolbarEl);
        }
        const toolbarMainContentsEl = toolbarInputEl.querySelector(`.${kToolbarContentClass}`);
        if (toolbarMainContentsEl !== null) {
            toolbarContainerEl.appendChild(toolbarMainContentsEl);
        }
        recursiveApplyFillClasses(toolbarContainerEl);
        toolbarInputEl.replaceWith(toolbarContainerEl);
        toolbarContainerEl.classList.add("dashboard-toolbar-container");
        const topLevelToolbar = doc.querySelector(".page-layout-custom >  .dashboard-toolbar-container");
        if (topLevelToolbar !== null) {
            topLevelToolbar.classList.add(kToolbarTopLevelClass);
            doc.body.classList.add(kDashboardToolbarClass);
        }
    }
}
const kStripRegexes = [
    /\/\/ Import jquery and DataTable/,
    /^\s*import 'https:\/\/code\.jquery\.com\/jquery\-.*';$/,
    /^\s*import dt from 'https:\/\/cdn\.datatables\.net\/.*\.mjs';$/,
    /^\s*dt\(\$\);/
];
const kDatatableInit = /\$\(document\).ready\(function \(\) \{(?:\s|.)*?\$\('#(.*?)'\)\.DataTable\(dt_args\);(?:\s|.)*?\}\);.*/g;
const kDatatable16 = /.DataTable\(dt_args\)/g;
const kDtCssHrefRegex = /^\s*https:\/\/cdn\.datatables\.net\/.*?\/jquery\.dataTables\.min\.css$/;
function processDatatables(doc) {
    const resources = [];
    const supporting = [];
    const scriptNodes = doc.querySelectorAll(".cell-output script[type='module']");
    for (const scriptNode of scriptNodes){
        const scriptEl = scriptNode;
        const code = scriptEl.innerText;
        let hasConnectedDt = false;
        const codeFiltered = [];
        for (const line of lines(code)){
            if (kStripRegexes.some((regex)=>{
                return !!line.match(regex);
            })) {
                hasConnectedDt = true;
            } else {
                codeFiltered.push(line);
            }
        }
        if (hasConnectedDt) {
            const codeText = codeFiltered.join("\n");
            if (codeText.match(kDatatable16)) {
                const codeWithInit = codeText.replace(kDatatableInit, "let table = new DataTable('#$1', dt_args);");
                scriptEl.innerText = codeWithInit;
            } else {
                scriptEl.innerText = codeText;
            }
            const linkCssNodes = doc.querySelectorAll('link[rel="stylesheet"][type="text/css"][href]');
            for (const linkCssNode of linkCssNodes){
                const linkCssEl = linkCssNode;
                const href = linkCssEl.getAttribute("href");
                if (href?.match(kDtCssHrefRegex)) {
                    linkCssEl.remove();
                }
            }
            const dtNodes = doc.querySelectorAll(`[${kDTTableSentinel}="true"]`);
            dtNodes.forEach((node)=>{
                node.removeAttribute(kDTTableSentinel);
            });
        } else {
            const dtNodes = doc.querySelectorAll(`[${kDTTableSentinel}="true"]`);
            dtNodes.forEach((node)=>{
                node.remove();
            });
        }
    }
    return {
        resources,
        supporting
    };
}
const kDashboardClz = "quarto-dashboard";
function dashboardFormat() {
    const baseHtmlFormat = htmlFormat(8, 5);
    const dashboardFormat = mergeConfigs(baseHtmlFormat, {
        execute: {
            [kEcho]: false,
            [kWarning]: false,
            [kIpynbShellInteractivity]: "all",
            [kPlotlyConnected]: false
        },
        metadata: {
            [kPageLayout]: kPageLayoutCustom
        }
    });
    if (baseHtmlFormat.formatExtras) {
        const dashboardExtras = async (input, markdown, flags, format, libDir, services, offset, project, quiet)=>{
            if (baseHtmlFormat.formatExtras) {
                const dashboard = await dashboardMeta(format);
                const isWebsiteProject = projectIsWebsite(project);
                if (isWebsiteProject) {
                    const formats = format.metadata.format;
                    const htmlFormat = formats["html"];
                    if (htmlFormat && htmlFormat[kTheme]) {
                        format.metadata[kTheme] = htmlFormat[kTheme];
                    }
                }
                const extras = await baseHtmlFormat.formatExtras(input, markdown, flags, format, libDir, services, offset, project, quiet);
                extras.html = extras.html || {};
                extras.html[kHtmlPostprocessors] = extras.html[kHtmlPostprocessors] || [];
                extras.html[kHtmlPostprocessors].push(dashboardHtmlPostProcessor(dashboard));
                extras.metadata = extras.metadata || {};
                extras.metadata[kTemplatePartials] = [
                    "title-block.html",
                    "_nav-container.html"
                ].map((file)=>{
                    return formatResourcePath("dashboard", file);
                });
                extras.pandoc = extras.pandoc || {};
                extras.pandoc[kTemplate] = formatResourcePath("dashboard", "template.html");
                extras[kFilterParams] = extras[kFilterParams] || {};
                extras[kFilterParams][kDashboard] = {
                    orientation: dashboard.orientation,
                    scrolling: dashboard.scrolling
                };
                if (!isWebsiteProject) {
                    extras.html[kSassBundles] = extras.html[kSassBundles] || [];
                    extras.html[kSassBundles].unshift(dashboardScssLayer());
                }
                const scripts = [];
                const stylesheets = [];
                scripts.push({
                    name: "quarto-dashboard.js",
                    path: formatResourcePath("dashboard", "quarto-dashboard.js")
                });
                scripts.push({
                    name: "stickythead.js",
                    path: formatResourcePath("dashboard", join2("js", "stickythead.js"))
                });
                scripts.push({
                    name: "datatables.min.js",
                    path: formatResourcePath("dashboard", join2("js", "dt", "datatables.min.js")),
                    attribs: {
                        kDTTableSentinel: "true"
                    }
                });
                stylesheets.push({
                    name: "datatables.min.css",
                    path: formatResourcePath("dashboard", join2("js", "dt", "datatables.min.css")),
                    attribs: {
                        kDTTableSentinel: "true"
                    }
                });
                scripts.push({
                    name: "pdfmake.min.js",
                    path: formatResourcePath("dashboard", join2("js", "dt", "pdfmake.min.js")),
                    attribs: {
                        kDTTableSentinel: "true"
                    }
                });
                scripts.push({
                    name: "vfs_fonts.js",
                    path: formatResourcePath("dashboard", join2("js", "dt", "vfs_fonts.js")),
                    attribs: {
                        kDTTableSentinel: "true"
                    }
                });
                const componentDir = join2("bslib", "components", "dist");
                [
                    {
                        name: "web-components",
                        module: true
                    },
                    {
                        name: "components",
                        module: false
                    }
                ].forEach((dependency)=>{
                    const attribs = {};
                    if (dependency.module) {
                        attribs["type"] = "module";
                    }
                    scripts.push({
                        name: `${dependency.name}.js`,
                        path: formatResourcePath("html", join2(componentDir, `${dependency.name}.js`)),
                        attribs
                    });
                });
                extras.html[kDependencies] = extras.html[kDependencies] || [];
                extras.html[kDependencies].push({
                    name: "quarto-dashboard",
                    scripts,
                    stylesheets
                });
                extras[kIncludeAfterBody] = extras[kIncludeAfterBody] || [];
                return extras;
            } else {
                throw new InternalError("Dashboard superclass must provide a format extras");
            }
        };
        if (dashboardExtras) {
            dashboardFormat.formatExtras = dashboardExtras;
        }
    }
    return dashboardFormat;
}
registerWriterFormatHandler((format)=>{
    switch(format){
        case "dashboard":
            return {
                format: dashboardFormat(),
                pandocTo: "html"
            };
    }
});
function dashboardHtmlPostProcessor(dashboardMeta) {
    return (doc)=>{
        const result1 = {
            resources: [],
            supporting: []
        };
        doc.body.classList.add(kDashboardClz);
        if (!dashboardMeta.scrolling) {
            doc.body.classList.add("dashboard-fill");
        }
        const containerEl = doc.querySelector("div.page-layout-custom");
        if (containerEl) {
            const containerClz = [
                "quarto-dashboard-content",
                "bslib-gap-spacing",
                "html-fill-container"
            ];
            if (!dashboardMeta.scrolling) {
                containerClz.push("bslib-page-fill");
            } else {
                containerClz.push("dashboard-scrolling");
            }
            containerClz.forEach((clz)=>{
                containerEl.classList.add(clz);
            });
        }
        const children = containerEl?.children;
        if (children) {
            for (const childEl of children){
                if (!childEl.classList.contains("quarto-title-block") && !kDontMutateTags.includes(childEl.tagName.toUpperCase())) {
                    childEl.classList.add("bslib-grid-item");
                    applyFillItemClasses(childEl);
                }
            }
        }
        const addResults = (res)=>{
            if (res) {
                result1.resources.push(...res.resources);
                result1.supporting.push(...res.supporting);
            }
        };
        addResults(processDatatables(doc));
        processNavigation(doc);
        processPages(doc, dashboardMeta);
        processNavButtons(doc, dashboardMeta);
        processRows(doc);
        processColumns(doc);
        processCards(doc, dashboardMeta);
        processValueBoxes(doc);
        processSidebars(doc);
        processToolbars(doc);
        processTables(doc);
        processShinyComponents(doc);
        const imgFillSelectors = [
            "div.cell-output-display > div.quarto-figure > .quarto-float img",
            "div.cell-output-display > img"
        ];
        imgFillSelectors.forEach((selector)=>{
            const fillImgNodes = doc.body.querySelectorAll(selector);
            for (const fillImgNode of fillImgNodes){
                const fillImgEl = fillImgNode;
                fillImgEl.classList.add("quarto-dashboard-img-contain");
                fillImgEl.removeAttribute("height");
                fillImgEl.removeAttribute("width");
            }
        });
        return Promise.resolve(result1);
    };
}
function processTables(doc) {
    doc.querySelectorAll(".itables table").forEach((tableEl)=>{
        tableEl.setAttribute("style", "width:100%;");
    });
}
function emailFormat() {
    return mergeConfigs(htmlFormat(7, 5));
}
registerWriterFormatHandler((format)=>{
    switch(format){
        case "email":
            return {
                format: emailFormat(),
                pandocTo: "html"
            };
    }
});
const { hasOwn: hasOwn5 } = Object;
function get1(obj, key) {
    if (hasOwn5(obj, key)) {
        return obj[key];
    }
}
function getForce(obj, key) {
    const v = get1(obj, key);
    assertExists(v);
    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, keys) {
    let o = obj;
    keys.slice(0, -1).forEach((key)=>{
        o = get1(o, key) ?? {};
    });
    const key = keys.at(-1);
    return key !== undefined && hasOwn5(o, key);
}
function parse11(args, { "--": doubleDash = false, alias = {}, boolean: __boolean = false, default: defaults = {}, stopEarly = false, string = [], collect = [], negatable = [], unknown = (i1)=>i1 } = {}) {
    const aliases = {};
    const flags = {
        bools: {},
        strings: {},
        unknownFn: unknown,
        allBools: false,
        collect: {},
        negatable: {}
    };
    if (alias !== undefined) {
        for(const key in alias){
            const val = getForce(alias, key);
            if (typeof val === "string") {
                aliases[key] = [
                    val
                ];
            } else {
                aliases[key] = val;
            }
            const aliasesForKey = getForce(aliases, key);
            for (const alias of aliasesForKey){
                aliases[alias] = [
                    key
                ].concat(aliasesForKey.filter((y)=>alias !== y));
            }
        }
    }
    if (__boolean !== undefined) {
        if (typeof __boolean === "boolean") {
            flags.allBools = !!__boolean;
        } else {
            const booleanArgs = typeof __boolean === "string" ? [
                __boolean
            ] : __boolean;
            for (const key of booleanArgs.filter(Boolean)){
                flags.bools[key] = true;
                const alias = get1(aliases, key);
                if (alias) {
                    for (const al of alias){
                        flags.bools[al] = true;
                    }
                }
            }
        }
    }
    if (string !== undefined) {
        const stringArgs = typeof string === "string" ? [
            string
        ] : string;
        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;
                }
            }
        }
    }
    if (collect !== undefined) {
        const collectArgs = typeof collect === "string" ? [
            collect
        ] : collect;
        for (const key of collectArgs.filter(Boolean)){
            flags.collect[key] = true;
            const alias = get1(aliases, key);
            if (alias) {
                for (const al of alias){
                    flags.collect[al] = true;
                }
            }
        }
    }
    if (negatable !== undefined) {
        const negatableArgs = typeof negatable === "string" ? [
            negatable
        ] : negatable;
        for (const key of negatableArgs.filter(Boolean)){
            flags.negatable[key] = true;
            const alias = get1(aliases, key);
            if (alias) {
                for (const al of alias){
                    flags.negatable[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, name, value, collect = true) {
        let o = obj;
        const keys = name.split(".");
        keys.slice(0, -1).forEach(function(key) {
            if (get1(o, key) === undefined) {
                o[key] = {};
            }
            o = get1(o, key);
        });
        const key = keys.at(-1);
        const collectable = collect && !!get1(flags.collect, name);
        if (!collectable) {
            o[key] = value;
        } else if (get1(o, key) === undefined) {
            o[key] = [
                value
            ];
        } else if (Array.isArray(get1(o, key))) {
            o[key].push(value);
        } else {
            o[key] = [
                get1(o, key),
                value
            ];
        }
    }
    function setArg(key, val, arg = undefined, collect) {
        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, value, collect);
        const alias = get1(aliases, key);
        if (alias) {
            for (const x of alias){
                setKey(argv, x, value, collect);
            }
        }
    }
    function aliasIsBoolean(key) {
        return getForce(aliases, key).some((x)=>typeof get1(flags.bools, x) === "boolean");
    }
    let notFlags = [];
    if (args.includes("--")) {
        notFlags = args.slice(args.indexOf("--") + 1);
        args = args.slice(0, args.indexOf("--"));
    }
    for(let i1 = 0; i1 < args.length; i1++){
        const arg = args[i1];
        assertExists(arg);
        if (/^--.+=/.test(arg)) {
            const m = arg.match(/^--([^=]+)=(.*)$/s);
            assertExists(m);
            const [, key, value] = m;
            assertExists(key);
            if (flags.bools[key]) {
                const booleanValue = value !== "false";
                setArg(key, booleanValue, arg);
            } else {
                setArg(key, value, arg);
            }
        } else if (/^--no-.+/.test(arg) && get1(flags.negatable, arg.replace(/^--no-/, ""))) {
            const m = arg.match(/^--no-(.+)/);
            assertExists(m);
            assertExists(m[1]);
            setArg(m[1], false, arg, false);
        } else if (/^--.+/.test(arg)) {
            const m = arg.match(/^--(.+)/);
            assertExists(m);
            assertExists(m[1]);
            const [, key] = m;
            const next = args[i1 + 1];
            if (next !== undefined && !/^-/.test(next) && !get1(flags.bools, key) && !flags.allBools && (get1(aliases, key) ? !aliasIsBoolean(key) : true)) {
                setArg(key, next, arg);
                i1++;
            } else if (next !== undefined && (next === "true" || next === "false")) {
                setArg(key, next === "true", arg);
                i1++;
            } else {
                setArg(key, get1(flags.strings, key) ? "" : true, arg);
            }
        } else if (/^-[^-]+/.test(arg)) {
            const letters = arg.slice(1, -1).split("");
            let broken = false;
            for (const [j, letter] of letters.entries()){
                const next = arg.slice(j + 2);
                if (next === "-") {
                    setArg(letter, next, arg);
                    continue;
                }
                if (/[A-Za-z]/.test(letter) && next.includes("=")) {
                    setArg(letter, next.split(/=(.+)/)[1], arg);
                    broken = true;
                    break;
                }
                if (/[A-Za-z]/.test(letter) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
                    setArg(letter, next, arg);
                    broken = true;
                    break;
                }
                if (letters[j + 1]?.match(/\W/)) {
                    setArg(letter, arg.slice(j + 2), arg);
                    broken = true;
                    break;
                } else {
                    setArg(letter, get1(flags.strings, letter) ? "" : true, arg);
                }
            }
            const key = arg.at(-1);
            if (!broken && key !== "-") {
                const nextArg = args[i1 + 1];
                if (nextArg && !/^(-|--)[^-]/.test(nextArg) && !get1(flags.bools, key) && (get1(aliases, key) ? !aliasIsBoolean(key) : true)) {
                    setArg(key, nextArg, arg);
                    i1++;
                } else if (nextArg && (nextArg === "true" || nextArg === "false")) {
                    setArg(key, nextArg === "true", arg);
                    i1++;
                } 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(i1 + 1));
                break;
            }
        }
    }
    for (const [key, value] of Object.entries(defaults)){
        if (!hasKey(argv, key.split("."))) {
            setKey(argv, key, value, false);
            const alias = aliases[key];
            if (alias !== undefined) {
                for (const x of alias){
                    setKey(argv, x, value, false);
                }
            }
        }
    }
    for (const key of Object.keys(flags.bools)){
        if (!hasKey(argv, key.split("."))) {
            const value = get1(flags.collect, key) ? [] : false;
            setKey(argv, key, value, false);
        }
    }
    for (const key of Object.keys(flags.strings)){
        if (!hasKey(argv, key.split(".")) && get1(flags.collect, key)) {
            setKey(argv, key, [], false);
        }
    }
    if (doubleDash) {
        argv["--"] = [];
        for (const key of notFlags){
            argv["--"].push(key);
        }
    } else {
        for (const key of notFlags){
            argv._.push(key);
        }
    }
    return argv;
}
let fileReads = undefined;
function captureFileReads() {
    fileReads = [];
    const originalReadTextFileSync = Deno.readTextFileSync;
    Deno.readTextFileSync = function(path) {
        try {
            throw new Error("File read");
        } catch (e) {
            const stack = e.stack.split("\n").slice(2);
            fileReads.push({
                path: String(path),
                stack
            });
        }
        return originalReadTextFileSync(path);
    };
}
function quartoPerformanceMetrics() {
    return {
        inputTargetIndexCache: inputTargetIndexCacheMetrics,
        fileReads
    };
}
function reportPeformanceMetrics() {
    console.log("---");
    console.log("Performance metrics");
    console.log("Quarto:");
    console.log(JSON.stringify(quartoPerformanceMetrics(), null, 2));
    console.log();
    console.log("Deno:");
    const denoMetrics = JSON.parse(JSON.stringify(Deno.metrics()));
    denoMetrics.ops = Object.fromEntries(Object.entries(denoMetrics.ops).map(([key, opMetrics])=>{
        for (const key of Object.keys(opMetrics)){
            if (opMetrics[key] === 0) {
                delete opMetrics[key];
            }
        }
        return [
            key,
            opMetrics
        ];
    }).filter(([_key, opMetrics])=>Object.keys(opMetrics).length > 0).map(([key, opMetrics])=>{
        if (opMetrics.opsDispatched === opMetrics.opsDispatchedSync && opMetrics.opsDispatched === opMetrics.opsCompleted && opMetrics.opsDispatched === opMetrics.opsCompletedSync || opMetrics.opsDispatched === opMetrics.opsDispatchedAsync && opMetrics.opsDispatched === opMetrics.opsCompleted && opMetrics.opsDispatched === opMetrics.opsCompletedAsync) {
            return [
                key,
                opMetrics.opsDispatched
            ];
        } else {
            return [
                key,
                opMetrics
            ];
        }
    }));
    console.log(JSON.stringify(denoMetrics, null, 2));
}
async function mainRunner(runner) {
    try {
        const args = parse11(Deno.args);
        await initializeLogger(logOptions(args));
        if (Deno.build.os !== "windows") {
            Deno.addSignalListener("SIGINT", abend);
            Deno.addSignalListener("SIGTERM", abend);
        }
        if (Deno.env.get("QUARTO_REPORT_PERFORMANCE_METRICS") !== undefined) {
            captureFileReads();
        }
        await runner(args);
        if (Deno.env.get("QUARTO_TS_PROFILE") !== undefined) {
            console.log("Program finished. Turn off the Chrome profiler now!");
            console.log("Waiting for 10 seconds ...");
            await new Promise((resolve)=>setTimeout(resolve, 10000));
        }
        if (Deno.env.get("QUARTO_REPORT_PERFORMANCE_METRICS") !== undefined) {
            reportPeformanceMetrics();
        }
        exitWithCleanup(0);
    } catch (e) {
        if (e) {
            logError(e);
        }
    } finally{
        abend();
    }
}
function abend() {
    exitWithCleanup(1);
}
const importMeta1 = {
    url: "file:///home/runner/work/quarto-cli/quarto-cli/src/quarto.ts",
    main: import.meta.main
};
async function quarto(args, cmdHandler, env) {
    if (quartoConfig.isDebug()) {
        const installed = readInstalledDevConfig();
        const source = readSourceDevConfig();
        if (installed == null || !devConfigsEqual(installed, source)) {
            await reconfigureQuarto(installed, source);
            Deno.exit(1);
        }
    }
    if (args[0] === "pandoc" && args[1] !== "help") {
        const result1 = await execProcess({
            cmd: [
                pandocBinaryPath(),
                ...args.slice(1)
            ],
            env
        });
        Deno.exit(result1.code);
    }
    if (args[0] === "typst") {
        if (args[1] === "update") {
            error("The 'typst update' command is not supported.\n" + "Please install the latest version of Quarto from http://quarto.org to get the latest supported typst features.");
            Deno.exit(1);
        }
        const result1 = await execProcess({
            cmd: [
                typstBinaryPath(),
                ...args.slice(1)
            ],
            env
        });
        Deno.exit(result1.code);
    }
    if (args[0] === "run" && args[1] !== "help" && args[1] !== "--help") {
        const result1 = await runScript(args.slice(1));
        Deno.exit(result1.code);
    }
    if (args.length > 1 && (args[0] === "render" || args[0] === "preview") && args[1].startsWith("-")) {
        args = [
            args[0],
            kCliffyImplicitCwd,
            ...args.slice(1)
        ];
    }
    debug("Quarto version: " + quartoConfig.version());
    const oldEnv = {};
    for (const [key, value] of Object.entries(env || {})){
        const oldV = Deno.env.get(key);
        oldEnv[key] = oldV;
        Deno.env.set(key, value);
    }
    const quartoCommand = new Command().name("quarto").help({
        colors: false
    }).version(quartoConfig.version() + "\n").description("Quarto CLI").throwErrors();
    commands().forEach((command)=>{
        command.help({
            colors: false
        });
        quartoCommand.command(command.getName(), cmdHandler !== undefined ? cmdHandler(command) : command);
    });
    initSessionTempDir();
    onCleanup(cleanupSessionTempDir);
    const promise = quartoCommand.command("help", new HelpCommand().global()).command("completions", new CompletionsCommand()).hidden().parse(args);
    for (const [key, value] of Object.entries(oldEnv)){
        if (value === undefined) {
            Deno.env.delete(key);
        } else {
            Deno.env.set(key, value);
        }
    }
    try {
        await promise;
    } catch (e) {
        if (e instanceof CommandError) {
            logError(e, false);
            exitWithCleanup(1);
        } else {
            throw e;
        }
    }
}
if (importMeta1.main) {
    await mainRunner(async (args)=>{
        let quartoArgs = [
            ...Deno.args
        ];
        if (setProfileFromArg(args)) {
            const removeArgs = new Map();
            removeArgs.set("--profile", true);
            quartoArgs = removeFlags(quartoArgs, removeArgs);
        }
        await quarto(quartoArgs, (cmd)=>{
            cmd = appendLogOptions(cmd);
            return appendProfileArg(cmd);
        });
    });
}
export { quarto as quarto };
