import { require_url } from "./chunk-MPVQUUHK.js"; import { require_events, require_node_os, require_os, require_stream, require_util } from "./chunk-KPGLAEFU.js"; import { require_fs } from "./chunk-I5RSIQOR.js"; import { parseAst, parseAstAsync, require_native, require_node_fs, require_node_perf_hooks, require_promises, require_tty } from "./chunk-I6YKGN4K.js"; import { require_path } from "./chunk-4XRL7ZXG.js"; import { require_node_http } from "./chunk-X45QO7DX.js"; import { require_node_https } from "./chunk-OZBCPRVH.js"; import { require_node_module, require_node_url } from "./chunk-G2ZEZZAJ.js"; import { require_node_path } from "./chunk-M2MSWSHF.js"; import { __commonJS, __privateAdd, __privateGet, __privateMethod, __privateSet, __privateWrapper, __publicField, __require, __toESM } from "./chunk-ZSMWDLMK.js"; // browser-external:node:util var require_node_util = __commonJS({ "browser-external:node:util"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:util" has been externalized for browser compatibility. Cannot access "node:util.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:child_process var require_child_process = __commonJS({ "browser-external:child_process"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "child_process" has been externalized for browser compatibility. Cannot access "child_process.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:crypto var require_crypto = __commonJS({ "browser-external:crypto"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "crypto" has been externalized for browser compatibility. Cannot access "crypto.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:worker_threads var require_worker_threads = __commonJS({ "browser-external:worker_threads"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "worker_threads" has been externalized for browser compatibility. Cannot access "worker_threads.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // node_modules/esbuild/lib/main.js var require_main = __commonJS({ "node_modules/esbuild/lib/main.js"(exports2, module) { "use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name2 in all) __defProp(target, name2, { get: all[name2], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var node_exports = {}; __export(node_exports, { analyzeMetafile: () => analyzeMetafile, analyzeMetafileSync: () => analyzeMetafileSync, build: () => build2, buildSync: () => buildSync, context: () => context, default: () => node_default, formatMessages: () => formatMessages2, formatMessagesSync: () => formatMessagesSync, initialize: () => initialize, stop: () => stop, transform: () => transform2, transformSync: () => transformSync, version: () => version3 }); module.exports = __toCommonJS(node_exports); function encodePacket(packet) { let visit2 = (value2) => { if (value2 === null) { bb.write8(0); } else if (typeof value2 === "boolean") { bb.write8(1); bb.write8(+value2); } else if (typeof value2 === "number") { bb.write8(2); bb.write32(value2 | 0); } else if (typeof value2 === "string") { bb.write8(3); bb.write(encodeUTF8(value2)); } else if (value2 instanceof Uint8Array) { bb.write8(4); bb.write(value2); } else if (value2 instanceof Array) { bb.write8(5); bb.write32(value2.length); for (let item of value2) { visit2(item); } } else { let keys = Object.keys(value2); bb.write8(6); bb.write32(keys.length); for (let key of keys) { bb.write(encodeUTF8(key)); visit2(value2[key]); } } }; let bb = new ByteBuffer(); bb.write32(0); bb.write32(packet.id << 1 | +!packet.isRequest); visit2(packet.value); writeUInt32LE(bb.buf, bb.len - 4, 0); return bb.buf.subarray(0, bb.len); } function decodePacket(bytes) { let visit2 = () => { switch (bb.read8()) { case 0: return null; case 1: return !!bb.read8(); case 2: return bb.read32(); case 3: return decodeUTF8(bb.read()); case 4: return bb.read(); case 5: { let count = bb.read32(); let value22 = []; for (let i = 0; i < count; i++) { value22.push(visit2()); } return value22; } case 6: { let count = bb.read32(); let value22 = {}; for (let i = 0; i < count; i++) { value22[decodeUTF8(bb.read())] = visit2(); } return value22; } default: throw new Error("Invalid packet"); } }; let bb = new ByteBuffer(bytes); let id = bb.read32(); let isRequest = (id & 1) === 0; id >>>= 1; let value2 = visit2(); if (bb.ptr !== bytes.length) { throw new Error("Invalid packet"); } return { id, isRequest, value: value2 }; } var ByteBuffer = class { constructor(buf = new Uint8Array(1024)) { this.buf = buf; this.len = 0; this.ptr = 0; } _write(delta) { if (this.len + delta > this.buf.length) { let clone2 = new Uint8Array((this.len + delta) * 2); clone2.set(this.buf); this.buf = clone2; } this.len += delta; return this.len - delta; } write8(value2) { let offset2 = this._write(1); this.buf[offset2] = value2; } write32(value2) { let offset2 = this._write(4); writeUInt32LE(this.buf, value2, offset2); } write(bytes) { let offset2 = this._write(4 + bytes.length); writeUInt32LE(this.buf, bytes.length, offset2); this.buf.set(bytes, offset2 + 4); } _read(delta) { if (this.ptr + delta > this.buf.length) { throw new Error("Invalid packet"); } this.ptr += delta; return this.ptr - delta; } read8() { return this.buf[this._read(1)]; } read32() { return readUInt32LE(this.buf, this._read(4)); } read() { let length = this.read32(); let bytes = new Uint8Array(length); let ptr = this._read(bytes.length); bytes.set(this.buf.subarray(ptr, ptr + length)); return bytes; } }; var encodeUTF8; var decodeUTF8; var encodeInvariant; if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { let encoder = new TextEncoder(); let decoder2 = new TextDecoder(); encodeUTF8 = (text) => encoder.encode(text); decodeUTF8 = (bytes) => decoder2.decode(bytes); encodeInvariant = 'new TextEncoder().encode("")'; } else if (typeof Buffer !== "undefined") { encodeUTF8 = (text) => Buffer.from(text); decodeUTF8 = (bytes) => { let { buffer, byteOffset, byteLength } = bytes; return Buffer.from(buffer, byteOffset, byteLength).toString(); }; encodeInvariant = 'Buffer.from("")'; } else { throw new Error("No UTF-8 codec found"); } if (!(encodeUTF8("") instanceof Uint8Array)) throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false This indicates that your JavaScript environment is broken. You cannot use esbuild in this environment because esbuild relies on this invariant. This is not a problem with esbuild. You need to fix your environment instead. `); function readUInt32LE(buffer, offset2) { return buffer[offset2++] | buffer[offset2++] << 8 | buffer[offset2++] << 16 | buffer[offset2++] << 24; } function writeUInt32LE(buffer, value2, offset2) { buffer[offset2++] = value2; buffer[offset2++] = value2 >> 8; buffer[offset2++] = value2 >> 16; buffer[offset2++] = value2 >> 24; } var quote3 = JSON.stringify; var buildLogLevelDefault = "warning"; var transformLogLevelDefault = "silent"; function validateTarget(target) { validateStringValue(target, "target"); if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`); return target; } var canBeAnything = () => null; var mustBeBoolean = (value2) => typeof value2 === "boolean" ? null : "a boolean"; var mustBeString = (value2) => typeof value2 === "string" ? null : "a string"; var mustBeRegExp = (value2) => value2 instanceof RegExp ? null : "a RegExp object"; var mustBeInteger = (value2) => typeof value2 === "number" && value2 === (value2 | 0) ? null : "an integer"; var mustBeFunction = (value2) => typeof value2 === "function" ? null : "a function"; var mustBeArray = (value2) => Array.isArray(value2) ? null : "an array"; var mustBeObject = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2) ? null : "an object"; var mustBeEntryPoints = (value2) => typeof value2 === "object" && value2 !== null ? null : "an array or an object"; var mustBeWebAssemblyModule = (value2) => value2 instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; var mustBeObjectOrNull = (value2) => typeof value2 === "object" && !Array.isArray(value2) ? null : "an object or null"; var mustBeStringOrBoolean = (value2) => typeof value2 === "string" || typeof value2 === "boolean" ? null : "a string or a boolean"; var mustBeStringOrObject = (value2) => typeof value2 === "string" || typeof value2 === "object" && value2 !== null && !Array.isArray(value2) ? null : "a string or an object"; var mustBeStringOrArray = (value2) => typeof value2 === "string" || Array.isArray(value2) ? null : "a string or an array"; var mustBeStringOrUint8Array = (value2) => typeof value2 === "string" || value2 instanceof Uint8Array ? null : "a string or a Uint8Array"; var mustBeStringOrURL = (value2) => typeof value2 === "string" || value2 instanceof URL ? null : "a string or a URL"; function getFlag(object, keys, key, mustBeFn) { let value2 = object[key]; keys[key + ""] = true; if (value2 === void 0) return void 0; let mustBe = mustBeFn(value2); if (mustBe !== null) throw new Error(`${quote3(key)} must be ${mustBe}`); return value2; } function checkForInvalidFlags(object, keys, where) { for (let key in object) { if (!(key in keys)) { throw new Error(`Invalid option ${where}: ${quote3(key)}`); } } } function validateInitializeOptions(options2) { let keys = /* @__PURE__ */ Object.create(null); let wasmURL = getFlag(options2, keys, "wasmURL", mustBeStringOrURL); let wasmModule = getFlag(options2, keys, "wasmModule", mustBeWebAssemblyModule); let worker = getFlag(options2, keys, "worker", mustBeBoolean); checkForInvalidFlags(options2, keys, "in initialize() call"); return { wasmURL, wasmModule, worker }; } function validateMangleCache(mangleCache) { let validated; if (mangleCache !== void 0) { validated = /* @__PURE__ */ Object.create(null); for (let key in mangleCache) { let value2 = mangleCache[key]; if (typeof value2 === "string" || value2 === false) { validated[key] = value2; } else { throw new Error(`Expected ${quote3(key)} in mangle cache to map to either a string or false`); } } } return validated; } function pushLogFlags(flags, options2, keys, isTTY2, logLevelDefault) { let color = getFlag(options2, keys, "color", mustBeBoolean); let logLevel = getFlag(options2, keys, "logLevel", mustBeString); let logLimit = getFlag(options2, keys, "logLimit", mustBeInteger); if (color !== void 0) flags.push(`--color=${color}`); else if (isTTY2) flags.push(`--color=true`); flags.push(`--log-level=${logLevel || logLevelDefault}`); flags.push(`--log-limit=${logLimit || 0}`); } function validateStringValue(value2, what, key) { if (typeof value2 !== "string") { throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote3(key) : ""} to be a string, got ${typeof value2} instead`); } return value2; } function pushCommonFlags(flags, options2, keys) { let legalComments = getFlag(options2, keys, "legalComments", mustBeString); let sourceRoot = getFlag(options2, keys, "sourceRoot", mustBeString); let sourcesContent = getFlag(options2, keys, "sourcesContent", mustBeBoolean); let target = getFlag(options2, keys, "target", mustBeStringOrArray); let format2 = getFlag(options2, keys, "format", mustBeString); let globalName = getFlag(options2, keys, "globalName", mustBeString); let mangleProps = getFlag(options2, keys, "mangleProps", mustBeRegExp); let reserveProps = getFlag(options2, keys, "reserveProps", mustBeRegExp); let mangleQuoted = getFlag(options2, keys, "mangleQuoted", mustBeBoolean); let minify = getFlag(options2, keys, "minify", mustBeBoolean); let minifySyntax = getFlag(options2, keys, "minifySyntax", mustBeBoolean); let minifyWhitespace = getFlag(options2, keys, "minifyWhitespace", mustBeBoolean); let minifyIdentifiers = getFlag(options2, keys, "minifyIdentifiers", mustBeBoolean); let lineLimit = getFlag(options2, keys, "lineLimit", mustBeInteger); let drop = getFlag(options2, keys, "drop", mustBeArray); let dropLabels = getFlag(options2, keys, "dropLabels", mustBeArray); let charset = getFlag(options2, keys, "charset", mustBeString); let treeShaking = getFlag(options2, keys, "treeShaking", mustBeBoolean); let ignoreAnnotations = getFlag(options2, keys, "ignoreAnnotations", mustBeBoolean); let jsx = getFlag(options2, keys, "jsx", mustBeString); let jsxFactory = getFlag(options2, keys, "jsxFactory", mustBeString); let jsxFragment = getFlag(options2, keys, "jsxFragment", mustBeString); let jsxImportSource = getFlag(options2, keys, "jsxImportSource", mustBeString); let jsxDev = getFlag(options2, keys, "jsxDev", mustBeBoolean); let jsxSideEffects = getFlag(options2, keys, "jsxSideEffects", mustBeBoolean); let define = getFlag(options2, keys, "define", mustBeObject); let logOverride = getFlag(options2, keys, "logOverride", mustBeObject); let supported = getFlag(options2, keys, "supported", mustBeObject); let pure = getFlag(options2, keys, "pure", mustBeArray); let keepNames = getFlag(options2, keys, "keepNames", mustBeBoolean); let platform2 = getFlag(options2, keys, "platform", mustBeString); let tsconfigRaw = getFlag(options2, keys, "tsconfigRaw", mustBeStringOrObject); if (legalComments) flags.push(`--legal-comments=${legalComments}`); if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`); if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`); if (target) { if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`); else flags.push(`--target=${validateTarget(target)}`); } if (format2) flags.push(`--format=${format2}`); if (globalName) flags.push(`--global-name=${globalName}`); if (platform2) flags.push(`--platform=${platform2}`); if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); if (minify) flags.push("--minify"); if (minifySyntax) flags.push("--minify-syntax"); if (minifyWhitespace) flags.push("--minify-whitespace"); if (minifyIdentifiers) flags.push("--minify-identifiers"); if (lineLimit) flags.push(`--line-limit=${lineLimit}`); if (charset) flags.push(`--charset=${charset}`); if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`); if (ignoreAnnotations) flags.push(`--ignore-annotations`); if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`); if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`); if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`); if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`); if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`); if (jsx) flags.push(`--jsx=${jsx}`); if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`); if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`); if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`); if (jsxDev) flags.push(`--jsx-dev`); if (jsxSideEffects) flags.push(`--jsx-side-effects`); if (define) { for (let key in define) { if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`); flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); } } if (logOverride) { for (let key in logOverride) { if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`); flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); } } if (supported) { for (let key in supported) { if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`); const value2 = supported[key]; if (typeof value2 !== "boolean") throw new Error(`Expected value for supported ${quote3(key)} to be a boolean, got ${typeof value2} instead`); flags.push(`--supported:${key}=${value2}`); } } if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`); if (keepNames) flags.push(`--keep-names`); } function flagsForBuildOptions(callName, options2, isTTY2, logLevelDefault, writeDefault) { var _a22; let flags = []; let entries = []; let keys = /* @__PURE__ */ Object.create(null); let stdinContents = null; let stdinResolveDir = null; pushLogFlags(flags, options2, keys, isTTY2, logLevelDefault); pushCommonFlags(flags, options2, keys); let sourcemap = getFlag(options2, keys, "sourcemap", mustBeStringOrBoolean); let bundle = getFlag(options2, keys, "bundle", mustBeBoolean); let splitting = getFlag(options2, keys, "splitting", mustBeBoolean); let preserveSymlinks = getFlag(options2, keys, "preserveSymlinks", mustBeBoolean); let metafile = getFlag(options2, keys, "metafile", mustBeBoolean); let outfile = getFlag(options2, keys, "outfile", mustBeString); let outdir = getFlag(options2, keys, "outdir", mustBeString); let outbase = getFlag(options2, keys, "outbase", mustBeString); let tsconfig = getFlag(options2, keys, "tsconfig", mustBeString); let resolveExtensions2 = getFlag(options2, keys, "resolveExtensions", mustBeArray); let nodePathsInput = getFlag(options2, keys, "nodePaths", mustBeArray); let mainFields = getFlag(options2, keys, "mainFields", mustBeArray); let conditions = getFlag(options2, keys, "conditions", mustBeArray); let external = getFlag(options2, keys, "external", mustBeArray); let packages = getFlag(options2, keys, "packages", mustBeString); let alias2 = getFlag(options2, keys, "alias", mustBeObject); let loader = getFlag(options2, keys, "loader", mustBeObject); let outExtension = getFlag(options2, keys, "outExtension", mustBeObject); let publicPath = getFlag(options2, keys, "publicPath", mustBeString); let entryNames = getFlag(options2, keys, "entryNames", mustBeString); let chunkNames = getFlag(options2, keys, "chunkNames", mustBeString); let assetNames = getFlag(options2, keys, "assetNames", mustBeString); let inject = getFlag(options2, keys, "inject", mustBeArray); let banner = getFlag(options2, keys, "banner", mustBeObject); let footer = getFlag(options2, keys, "footer", mustBeObject); let entryPoints = getFlag(options2, keys, "entryPoints", mustBeEntryPoints); let absWorkingDir = getFlag(options2, keys, "absWorkingDir", mustBeString); let stdin = getFlag(options2, keys, "stdin", mustBeObject); let write = (_a22 = getFlag(options2, keys, "write", mustBeBoolean)) != null ? _a22 : writeDefault; let allowOverwrite = getFlag(options2, keys, "allowOverwrite", mustBeBoolean); let mangleCache = getFlag(options2, keys, "mangleCache", mustBeObject); keys.plugins = true; checkForInvalidFlags(options2, keys, `in ${callName}() call`); if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); if (bundle) flags.push("--bundle"); if (allowOverwrite) flags.push("--allow-overwrite"); if (splitting) flags.push("--splitting"); if (preserveSymlinks) flags.push("--preserve-symlinks"); if (metafile) flags.push(`--metafile`); if (outfile) flags.push(`--outfile=${outfile}`); if (outdir) flags.push(`--outdir=${outdir}`); if (outbase) flags.push(`--outbase=${outbase}`); if (tsconfig) flags.push(`--tsconfig=${tsconfig}`); if (packages) flags.push(`--packages=${packages}`); if (resolveExtensions2) { let values = []; for (let value2 of resolveExtensions2) { validateStringValue(value2, "resolve extension"); if (value2.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value2}`); values.push(value2); } flags.push(`--resolve-extensions=${values.join(",")}`); } if (publicPath) flags.push(`--public-path=${publicPath}`); if (entryNames) flags.push(`--entry-names=${entryNames}`); if (chunkNames) flags.push(`--chunk-names=${chunkNames}`); if (assetNames) flags.push(`--asset-names=${assetNames}`); if (mainFields) { let values = []; for (let value2 of mainFields) { validateStringValue(value2, "main field"); if (value2.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value2}`); values.push(value2); } flags.push(`--main-fields=${values.join(",")}`); } if (conditions) { let values = []; for (let value2 of conditions) { validateStringValue(value2, "condition"); if (value2.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value2}`); values.push(value2); } flags.push(`--conditions=${values.join(",")}`); } if (external) for (let name2 of external) flags.push(`--external:${validateStringValue(name2, "external")}`); if (alias2) { for (let old in alias2) { if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`); flags.push(`--alias:${old}=${validateStringValue(alias2[old], "alias", old)}`); } } if (banner) { for (let type in banner) { if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`); flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); } } if (footer) { for (let type in footer) { if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`); flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); } } if (inject) for (let path32 of inject) flags.push(`--inject:${validateStringValue(path32, "inject")}`); if (loader) { for (let ext2 in loader) { if (ext2.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext2}`); flags.push(`--loader:${ext2}=${validateStringValue(loader[ext2], "loader", ext2)}`); } } if (outExtension) { for (let ext2 in outExtension) { if (ext2.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext2}`); flags.push(`--out-extension:${ext2}=${validateStringValue(outExtension[ext2], "out extension", ext2)}`); } } if (entryPoints) { if (Array.isArray(entryPoints)) { for (let i = 0, n2 = entryPoints.length; i < n2; i++) { let entryPoint = entryPoints[i]; if (typeof entryPoint === "object" && entryPoint !== null) { let entryPointKeys = /* @__PURE__ */ Object.create(null); let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i); if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i); entries.push([output, input]); } else { entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); } } } else { for (let key in entryPoints) { entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); } } } if (stdin) { let stdinKeys = /* @__PURE__ */ Object.create(null); let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); if (loader2) flags.push(`--loader=${loader2}`); if (resolveDir) stdinResolveDir = resolveDir; if (typeof contents === "string") stdinContents = encodeUTF8(contents); else if (contents instanceof Uint8Array) stdinContents = contents; } let nodePaths = []; if (nodePathsInput) { for (let value2 of nodePathsInput) { value2 += ""; nodePaths.push(value2); } } return { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache: validateMangleCache(mangleCache) }; } function flagsForTransformOptions(callName, options2, isTTY2, logLevelDefault) { let flags = []; let keys = /* @__PURE__ */ Object.create(null); pushLogFlags(flags, options2, keys, isTTY2, logLevelDefault); pushCommonFlags(flags, options2, keys); let sourcemap = getFlag(options2, keys, "sourcemap", mustBeStringOrBoolean); let sourcefile = getFlag(options2, keys, "sourcefile", mustBeString); let loader = getFlag(options2, keys, "loader", mustBeString); let banner = getFlag(options2, keys, "banner", mustBeString); let footer = getFlag(options2, keys, "footer", mustBeString); let mangleCache = getFlag(options2, keys, "mangleCache", mustBeObject); checkForInvalidFlags(options2, keys, `in ${callName}() call`); if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); if (loader) flags.push(`--loader=${loader}`); if (banner) flags.push(`--banner=${banner}`); if (footer) flags.push(`--footer=${footer}`); return { flags, mangleCache: validateMangleCache(mangleCache) }; } function createChannel(streamIn) { const requestCallbacksByKey = {}; const closeData = { didClose: false, reason: "" }; let responseCallbacks = {}; let nextRequestID = 0; let nextBuildKey = 0; let stdout = new Uint8Array(16 * 1024); let stdoutUsed = 0; let readFromStdout = (chunk) => { let limit = stdoutUsed + chunk.length; if (limit > stdout.length) { let swap = new Uint8Array(limit * 2); swap.set(stdout); stdout = swap; } stdout.set(chunk, stdoutUsed); stdoutUsed += chunk.length; let offset2 = 0; while (offset2 + 4 <= stdoutUsed) { let length = readUInt32LE(stdout, offset2); if (offset2 + 4 + length > stdoutUsed) { break; } offset2 += 4; handleIncomingPacket(stdout.subarray(offset2, offset2 + length)); offset2 += length; } if (offset2 > 0) { stdout.copyWithin(0, offset2, stdoutUsed); stdoutUsed -= offset2; } }; let afterClose = (error2) => { closeData.didClose = true; if (error2) closeData.reason = ": " + (error2.message || error2); const text = "The service was stopped" + closeData.reason; for (let id in responseCallbacks) { responseCallbacks[id](text, null); } responseCallbacks = {}; }; let sendRequest = (refs, value2, callback) => { if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null); let id = nextRequestID++; responseCallbacks[id] = (error2, response) => { try { callback(error2, response); } finally { if (refs) refs.unref(); } }; if (refs) refs.ref(); streamIn.writeToStdin(encodePacket({ id, isRequest: true, value: value2 })); }; let sendResponse = (id, value2) => { if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason); streamIn.writeToStdin(encodePacket({ id, isRequest: false, value: value2 })); }; let handleRequest = async (id, request) => { try { if (request.command === "ping") { sendResponse(id, {}); return; } if (typeof request.key === "number") { const requestCallbacks = requestCallbacksByKey[request.key]; if (!requestCallbacks) { return; } const callback = requestCallbacks[request.command]; if (callback) { await callback(id, request); return; } } throw new Error(`Invalid command: ` + request.command); } catch (e2) { const errors = [extractErrorMessageV8(e2, streamIn, null, void 0, "")]; try { sendResponse(id, { errors }); } catch { } } }; let isFirstPacket = true; let handleIncomingPacket = (bytes) => { if (isFirstPacket) { isFirstPacket = false; let binaryVersion = String.fromCharCode(...bytes); if (binaryVersion !== "0.21.5") { throw new Error(`Cannot start service: Host version "${"0.21.5"}" does not match binary version ${quote3(binaryVersion)}`); } return; } let packet = decodePacket(bytes); if (packet.isRequest) { handleRequest(packet.id, packet.value); } else { let callback = responseCallbacks[packet.id]; delete responseCallbacks[packet.id]; if (packet.value.error) callback(packet.value.error, {}); else callback(null, packet.value); } }; let buildOrContext = ({ callName, refs, options: options2, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => { let refCount = 0; const buildKey = nextBuildKey++; const requestCallbacks = {}; const buildRefs = { ref() { if (++refCount === 1) { if (refs) refs.ref(); } }, unref() { if (--refCount === 0) { delete requestCallbacksByKey[buildKey]; if (refs) refs.unref(); } } }; requestCallbacksByKey[buildKey] = requestCallbacks; buildRefs.ref(); buildOrContextImpl( callName, buildKey, sendRequest, sendResponse, buildRefs, streamIn, requestCallbacks, options2, isTTY2, defaultWD2, (err2, res) => { try { callback(err2, res); } finally { buildRefs.unref(); } } ); }; let transform22 = ({ callName, refs, input, options: options2, isTTY: isTTY2, fs: fs3, callback }) => { const details = createObjectStash(); let start = (inputPath) => { try { if (typeof input !== "string" && !(input instanceof Uint8Array)) throw new Error('The input to "transform" must be a string or a Uint8Array'); let { flags, mangleCache } = flagsForTransformOptions(callName, options2, isTTY2, transformLogLevelDefault); let request = { command: "transform", flags, inputFS: inputPath !== null, input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input }; if (mangleCache) request.mangleCache = mangleCache; sendRequest(refs, request, (error2, response) => { if (error2) return callback(new Error(error2), null); let errors = replaceDetailsInMessages(response.errors, details); let warnings = replaceDetailsInMessages(response.warnings, details); let outstanding = 1; let next = () => { if (--outstanding === 0) { let result = { warnings, code: response.code, map: response.map, mangleCache: void 0, legalComments: void 0 }; if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments; if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache; callback(null, result); } }; if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null); if (response.codeFS) { outstanding++; fs3.readFile(response.code, (err2, contents) => { if (err2 !== null) { callback(err2, null); } else { response.code = contents; next(); } }); } if (response.mapFS) { outstanding++; fs3.readFile(response.map, (err2, contents) => { if (err2 !== null) { callback(err2, null); } else { response.map = contents; next(); } }); } next(); }); } catch (e2) { let flags = []; try { pushLogFlags(flags, options2, {}, isTTY2, transformLogLevelDefault); } catch { } const error2 = extractErrorMessageV8(e2, streamIn, details, void 0, ""); sendRequest(refs, { command: "error", flags, error: error2 }, () => { error2.detail = details.load(error2.detail); callback(failureErrorWithLog("Transform failed", [error2], []), null); }); } }; if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) { let next = start; start = () => fs3.writeFile(input, next); } start(null); }; let formatMessages22 = ({ callName, refs, messages: messages2, options: options2, callback }) => { if (!options2) throw new Error(`Missing second argument in ${callName}() call`); let keys = {}; let kind = getFlag(options2, keys, "kind", mustBeString); let color = getFlag(options2, keys, "color", mustBeBoolean); let terminalWidth = getFlag(options2, keys, "terminalWidth", mustBeInteger); checkForInvalidFlags(options2, keys, `in ${callName}() call`); if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`); if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`); let request = { command: "format-msgs", messages: sanitizeMessages(messages2, "messages", null, "", terminalWidth), isWarning: kind === "warning" }; if (color !== void 0) request.color = color; if (terminalWidth !== void 0) request.terminalWidth = terminalWidth; sendRequest(refs, request, (error2, response) => { if (error2) return callback(new Error(error2), null); callback(null, response.messages); }); }; let analyzeMetafile2 = ({ callName, refs, metafile, options: options2, callback }) => { if (options2 === void 0) options2 = {}; let keys = {}; let color = getFlag(options2, keys, "color", mustBeBoolean); let verbose = getFlag(options2, keys, "verbose", mustBeBoolean); checkForInvalidFlags(options2, keys, `in ${callName}() call`); let request = { command: "analyze-metafile", metafile }; if (color !== void 0) request.color = color; if (verbose !== void 0) request.verbose = verbose; sendRequest(refs, request, (error2, response) => { if (error2) return callback(new Error(error2), null); callback(null, response.result); }); }; return { readFromStdout, afterClose, service: { buildOrContext, transform: transform22, formatMessages: formatMessages22, analyzeMetafile: analyzeMetafile2 } }; } function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options2, isTTY2, defaultWD2, callback) { const details = createObjectStash(); const isContext = callName === "context"; const handleError = (e2, pluginName) => { const flags = []; try { pushLogFlags(flags, options2, {}, isTTY2, buildLogLevelDefault); } catch { } const message = extractErrorMessageV8(e2, streamIn, details, void 0, pluginName); sendRequest(refs, { command: "error", flags, error: message }, () => { message.detail = details.load(message.detail); callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null); }); }; let plugins2; if (typeof options2 === "object") { const value2 = options2.plugins; if (value2 !== void 0) { if (!Array.isArray(value2)) return handleError(new Error(`"plugins" must be an array`), ""); plugins2 = value2; } } if (plugins2 && plugins2.length > 0) { if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), ""); handlePlugins( buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options2, plugins2, details ).then( (result) => { if (!result.ok) return handleError(result.error, result.pluginName); try { buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks); } catch (e2) { handleError(e2, ""); } }, (e2) => handleError(e2, "") ); return; } try { buildOrContextContinue(null, (result, done) => done([], []), () => { }); } catch (e2) { handleError(e2, ""); } function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) { const writeDefault = streamIn.hasFS; const { entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir, nodePaths, mangleCache } = flagsForBuildOptions(callName, options2, isTTY2, buildLogLevelDefault, writeDefault); if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`); const request = { command: "build", key: buildKey, entries, flags, write, stdinContents, stdinResolveDir, absWorkingDir: absWorkingDir || defaultWD2, nodePaths, context: isContext }; if (requestPlugins) request.plugins = requestPlugins; if (mangleCache) request.mangleCache = mangleCache; const buildResponseToResult = (response, callback2) => { const result = { errors: replaceDetailsInMessages(response.errors, details), warnings: replaceDetailsInMessages(response.warnings, details), outputFiles: void 0, metafile: void 0, mangleCache: void 0 }; const originalErrors = result.errors.slice(); const originalWarnings = result.warnings.slice(); if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles); if (response.metafile) result.metafile = JSON.parse(response.metafile); if (response.mangleCache) result.mangleCache = response.mangleCache; if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { if (originalErrors.length > 0 || onEndErrors.length > 0) { const error2 = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)); return callback2(error2, null, onEndErrors, onEndWarnings); } callback2(null, result, onEndErrors, onEndWarnings); }); }; let latestResultPromise; let provideLatestResult; if (isContext) requestCallbacks["on-end"] = (id, request2) => new Promise((resolve3) => { buildResponseToResult(request2, (err2, result, onEndErrors, onEndWarnings) => { const response = { errors: onEndErrors, warnings: onEndWarnings }; if (provideLatestResult) provideLatestResult(err2, result); latestResultPromise = void 0; provideLatestResult = void 0; sendResponse(id, response); resolve3(); }); }); sendRequest(refs, request, (error2, response) => { if (error2) return callback(new Error(error2), null); if (!isContext) { return buildResponseToResult(response, (err2, res) => { scheduleOnDisposeCallbacks(); return callback(err2, res); }); } if (response.errors.length > 0) { return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null); } let didDispose = false; const result = { rebuild: () => { if (!latestResultPromise) latestResultPromise = new Promise((resolve3, reject) => { let settlePromise; provideLatestResult = (err2, result2) => { if (!settlePromise) settlePromise = () => err2 ? reject(err2) : resolve3(result2); }; const triggerAnotherBuild = () => { const request2 = { command: "rebuild", key: buildKey }; sendRequest(refs, request2, (error22, response2) => { if (error22) { reject(new Error(error22)); } else if (settlePromise) { settlePromise(); } else { triggerAnotherBuild(); } }); }; triggerAnotherBuild(); }); return latestResultPromise; }, watch: (options22 = {}) => new Promise((resolve3, reject) => { if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`); const keys = {}; checkForInvalidFlags(options22, keys, `in watch() call`); const request2 = { command: "watch", key: buildKey }; sendRequest(refs, request2, (error22) => { if (error22) reject(new Error(error22)); else resolve3(void 0); }); }), serve: (options22 = {}) => new Promise((resolve3, reject) => { if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`); const keys = {}; const port = getFlag(options22, keys, "port", mustBeInteger); const host = getFlag(options22, keys, "host", mustBeString); const servedir = getFlag(options22, keys, "servedir", mustBeString); const keyfile = getFlag(options22, keys, "keyfile", mustBeString); const certfile = getFlag(options22, keys, "certfile", mustBeString); const fallback = getFlag(options22, keys, "fallback", mustBeString); const onRequest = getFlag(options22, keys, "onRequest", mustBeFunction); checkForInvalidFlags(options22, keys, `in serve() call`); const request2 = { command: "serve", key: buildKey, onRequest: !!onRequest }; if (port !== void 0) request2.port = port; if (host !== void 0) request2.host = host; if (servedir !== void 0) request2.servedir = servedir; if (keyfile !== void 0) request2.keyfile = keyfile; if (certfile !== void 0) request2.certfile = certfile; if (fallback !== void 0) request2.fallback = fallback; sendRequest(refs, request2, (error22, response2) => { if (error22) return reject(new Error(error22)); if (onRequest) { requestCallbacks["serve-request"] = (id, request3) => { onRequest(request3.args); sendResponse(id, {}); }; } resolve3(response2); }); }), cancel: () => new Promise((resolve3) => { if (didDispose) return resolve3(); const request2 = { command: "cancel", key: buildKey }; sendRequest(refs, request2, () => { resolve3(); }); }), dispose: () => new Promise((resolve3) => { if (didDispose) return resolve3(); didDispose = true; const request2 = { command: "dispose", key: buildKey }; sendRequest(refs, request2, () => { resolve3(); scheduleOnDisposeCallbacks(); refs.unref(); }); }) }; refs.ref(); callback(null, result); }); } } var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins2, details) => { let onStartCallbacks = []; let onEndCallbacks = []; let onResolveCallbacks = {}; let onLoadCallbacks = {}; let onDisposeCallbacks = []; let nextCallbackID = 0; let i = 0; let requestPlugins = []; let isSetupDone = false; plugins2 = [...plugins2]; for (let item of plugins2) { let keys = {}; if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`); const name2 = getFlag(item, keys, "name", mustBeString); if (typeof name2 !== "string" || name2 === "") throw new Error(`Plugin at index ${i} is missing a name`); try { let setup = getFlag(item, keys, "setup", mustBeFunction); if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`); checkForInvalidFlags(item, keys, `on plugin ${quote3(name2)}`); let plugin = { name: name2, onStart: false, onEnd: false, onResolve: [], onLoad: [] }; i++; let resolve3 = (path32, options2 = {}) => { if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed'); if (typeof path32 !== "string") throw new Error(`The path to resolve must be a string`); let keys2 = /* @__PURE__ */ Object.create(null); let pluginName = getFlag(options2, keys2, "pluginName", mustBeString); let importer = getFlag(options2, keys2, "importer", mustBeString); let namespace = getFlag(options2, keys2, "namespace", mustBeString); let resolveDir = getFlag(options2, keys2, "resolveDir", mustBeString); let kind = getFlag(options2, keys2, "kind", mustBeString); let pluginData = getFlag(options2, keys2, "pluginData", canBeAnything); let importAttributes = getFlag(options2, keys2, "with", mustBeObject); checkForInvalidFlags(options2, keys2, "in resolve() call"); return new Promise((resolve22, reject) => { const request = { command: "resolve", path: path32, key: buildKey, pluginName: name2 }; if (pluginName != null) request.pluginName = pluginName; if (importer != null) request.importer = importer; if (namespace != null) request.namespace = namespace; if (resolveDir != null) request.resolveDir = resolveDir; if (kind != null) request.kind = kind; else throw new Error(`Must specify "kind" when calling "resolve"`); if (pluginData != null) request.pluginData = details.store(pluginData); if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with"); sendRequest(refs, request, (error2, response) => { if (error2 !== null) reject(new Error(error2)); else resolve22({ errors: replaceDetailsInMessages(response.errors, details), warnings: replaceDetailsInMessages(response.warnings, details), path: response.path, external: response.external, sideEffects: response.sideEffects, namespace: response.namespace, suffix: response.suffix, pluginData: details.load(response.pluginData) }); }); }); }; let promise2 = setup({ initialOptions, resolve: resolve3, onStart(callback) { let registeredText = `This error came from the "onStart" callback registered here:`; let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart"); onStartCallbacks.push({ name: name2, callback, note: registeredNote }); plugin.onStart = true; }, onEnd(callback) { let registeredText = `This error came from the "onEnd" callback registered here:`; let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd"); onEndCallbacks.push({ name: name2, callback, note: registeredNote }); plugin.onEnd = true; }, onResolve(options2, callback) { let registeredText = `This error came from the "onResolve" callback registered here:`; let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); let keys2 = {}; let filter2 = getFlag(options2, keys2, "filter", mustBeRegExp); let namespace = getFlag(options2, keys2, "namespace", mustBeString); checkForInvalidFlags(options2, keys2, `in onResolve() call for plugin ${quote3(name2)}`); if (filter2 == null) throw new Error(`onResolve() call is missing a filter`); let id = nextCallbackID++; onResolveCallbacks[id] = { name: name2, callback, note: registeredNote }; plugin.onResolve.push({ id, filter: filter2.source, namespace: namespace || "" }); }, onLoad(options2, callback) { let registeredText = `This error came from the "onLoad" callback registered here:`; let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); let keys2 = {}; let filter2 = getFlag(options2, keys2, "filter", mustBeRegExp); let namespace = getFlag(options2, keys2, "namespace", mustBeString); checkForInvalidFlags(options2, keys2, `in onLoad() call for plugin ${quote3(name2)}`); if (filter2 == null) throw new Error(`onLoad() call is missing a filter`); let id = nextCallbackID++; onLoadCallbacks[id] = { name: name2, callback, note: registeredNote }; plugin.onLoad.push({ id, filter: filter2.source, namespace: namespace || "" }); }, onDispose(callback) { onDisposeCallbacks.push(callback); }, esbuild: streamIn.esbuild }); if (promise2) await promise2; requestPlugins.push(plugin); } catch (e2) { return { ok: false, error: e2, pluginName: name2 }; } } requestCallbacks["on-start"] = async (id, request) => { let response = { errors: [], warnings: [] }; await Promise.all(onStartCallbacks.map(async ({ name: name2, callback, note }) => { try { let result = await callback(); if (result != null) { if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote3(name2)} to return an object`); let keys = {}; let errors = getFlag(result, keys, "errors", mustBeArray); let warnings = getFlag(result, keys, "warnings", mustBeArray); checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote3(name2)}`); if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name2, void 0)); if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name2, void 0)); } } catch (e2) { response.errors.push(extractErrorMessageV8(e2, streamIn, details, note && note(), name2)); } })); sendResponse(id, response); }; requestCallbacks["on-resolve"] = async (id, request) => { let response = {}, name2 = "", callback, note; for (let id2 of request.ids) { try { ({ name: name2, callback, note } = onResolveCallbacks[id2]); let result = await callback({ path: request.path, importer: request.importer, namespace: request.namespace, resolveDir: request.resolveDir, kind: request.kind, pluginData: details.load(request.pluginData), with: request.with }); if (result != null) { if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote3(name2)} to return an object`); let keys = {}; let pluginName = getFlag(result, keys, "pluginName", mustBeString); let path32 = getFlag(result, keys, "path", mustBeString); let namespace = getFlag(result, keys, "namespace", mustBeString); let suffix = getFlag(result, keys, "suffix", mustBeString); let external = getFlag(result, keys, "external", mustBeBoolean); let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean); let pluginData = getFlag(result, keys, "pluginData", canBeAnything); let errors = getFlag(result, keys, "errors", mustBeArray); let warnings = getFlag(result, keys, "warnings", mustBeArray); let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote3(name2)}`); response.id = id2; if (pluginName != null) response.pluginName = pluginName; if (path32 != null) response.path = path32; if (namespace != null) response.namespace = namespace; if (suffix != null) response.suffix = suffix; if (external != null) response.external = external; if (sideEffects != null) response.sideEffects = sideEffects; if (pluginData != null) response.pluginData = details.store(pluginData); if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name2, void 0); if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name2, void 0); if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); break; } } catch (e2) { response = { id: id2, errors: [extractErrorMessageV8(e2, streamIn, details, note && note(), name2)] }; break; } } sendResponse(id, response); }; requestCallbacks["on-load"] = async (id, request) => { let response = {}, name2 = "", callback, note; for (let id2 of request.ids) { try { ({ name: name2, callback, note } = onLoadCallbacks[id2]); let result = await callback({ path: request.path, namespace: request.namespace, suffix: request.suffix, pluginData: details.load(request.pluginData), with: request.with }); if (result != null) { if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote3(name2)} to return an object`); let keys = {}; let pluginName = getFlag(result, keys, "pluginName", mustBeString); let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); let pluginData = getFlag(result, keys, "pluginData", canBeAnything); let loader = getFlag(result, keys, "loader", mustBeString); let errors = getFlag(result, keys, "errors", mustBeArray); let warnings = getFlag(result, keys, "warnings", mustBeArray); let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote3(name2)}`); response.id = id2; if (pluginName != null) response.pluginName = pluginName; if (contents instanceof Uint8Array) response.contents = contents; else if (contents != null) response.contents = encodeUTF8(contents); if (resolveDir != null) response.resolveDir = resolveDir; if (pluginData != null) response.pluginData = details.store(pluginData); if (loader != null) response.loader = loader; if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name2, void 0); if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name2, void 0); if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); break; } } catch (e2) { response = { id: id2, errors: [extractErrorMessageV8(e2, streamIn, details, note && note(), name2)] }; break; } } sendResponse(id, response); }; let runOnEndCallbacks = (result, done) => done([], []); if (onEndCallbacks.length > 0) { runOnEndCallbacks = (result, done) => { (async () => { const onEndErrors = []; const onEndWarnings = []; for (const { name: name2, callback, note } of onEndCallbacks) { let newErrors; let newWarnings; try { const value2 = await callback(result); if (value2 != null) { if (typeof value2 !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote3(name2)} to return an object`); let keys = {}; let errors = getFlag(value2, keys, "errors", mustBeArray); let warnings = getFlag(value2, keys, "warnings", mustBeArray); checkForInvalidFlags(value2, keys, `from onEnd() callback in plugin ${quote3(name2)}`); if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name2, void 0); if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name2, void 0); } } catch (e2) { newErrors = [extractErrorMessageV8(e2, streamIn, details, note && note(), name2)]; } if (newErrors) { onEndErrors.push(...newErrors); try { result.errors.push(...newErrors); } catch { } } if (newWarnings) { onEndWarnings.push(...newWarnings); try { result.warnings.push(...newWarnings); } catch { } } } done(onEndErrors, onEndWarnings); })(); }; } let scheduleOnDisposeCallbacks = () => { for (const cb of onDisposeCallbacks) { setTimeout(() => cb(), 0); } }; isSetupDone = true; return { ok: true, requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks }; }; function createObjectStash() { const map2 = /* @__PURE__ */ new Map(); let nextID = 0; return { load(id) { return map2.get(id); }, store(value2) { if (value2 === void 0) return -1; const id = nextID++; map2.set(id, value2); return id; } }; } function extractCallerV8(e2, streamIn, ident) { let note; let tried = false; return () => { if (tried) return note; tried = true; try { let lines = (e2.stack + "").split("\n"); lines.splice(1, 1); let location2 = parseStackLinesV8(streamIn, lines, ident); if (location2) { note = { text: e2.message, location: location2 }; return note; } } catch { } }; } function extractErrorMessageV8(e2, streamIn, stash, note, pluginName) { let text = "Internal error"; let location2 = null; try { text = (e2 && e2.message || e2) + ""; } catch { } try { location2 = parseStackLinesV8(streamIn, (e2.stack + "").split("\n"), ""); } catch { } return { id: "", pluginName, text, location: location2, notes: note ? [note] : [], detail: stash ? stash.store(e2) : -1 }; } function parseStackLinesV8(streamIn, lines, ident) { let at = " at "; if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { for (let i = 1; i < lines.length; i++) { let line = lines[i]; if (!line.startsWith(at)) continue; line = line.slice(at.length); while (true) { let match2 = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); if (match2) { line = match2[1]; continue; } match2 = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); if (match2) { line = match2[1]; continue; } match2 = /^(\S+):(\d+):(\d+)$/.exec(line); if (match2) { let contents; try { contents = streamIn.readFileSync(match2[1], "utf8"); } catch { break; } let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match2[2] - 1] || ""; let column = +match2[3] - 1; let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; return { file: match2[1], namespace: "file", line: +match2[2], column: encodeUTF8(lineText.slice(0, column)).length, length: encodeUTF8(lineText.slice(column, column + length)).length, lineText: lineText + "\n" + lines.slice(1).join("\n"), suggestion: "" }; } break; } } } return null; } function failureErrorWithLog(text, errors, warnings) { let limit = 5; text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e2, i) => { if (i === limit) return "\n..."; if (!e2.location) return ` error: ${e2.text}`; let { file, line, column } = e2.location; let pluginText = e2.pluginName ? `[plugin: ${e2.pluginName}] ` : ""; return ` ${file}:${line}:${column}: ERROR: ${pluginText}${e2.text}`; }).join(""); let error2 = new Error(text); for (const [key, value2] of [["errors", errors], ["warnings", warnings]]) { Object.defineProperty(error2, key, { configurable: true, enumerable: true, get: () => value2, set: (value22) => Object.defineProperty(error2, key, { configurable: true, enumerable: true, value: value22 }) }); } return error2; } function replaceDetailsInMessages(messages2, stash) { for (const message of messages2) { message.detail = stash.load(message.detail); } return messages2; } function sanitizeLocation(location2, where, terminalWidth) { if (location2 == null) return null; let keys = {}; let file = getFlag(location2, keys, "file", mustBeString); let namespace = getFlag(location2, keys, "namespace", mustBeString); let line = getFlag(location2, keys, "line", mustBeInteger); let column = getFlag(location2, keys, "column", mustBeInteger); let length = getFlag(location2, keys, "length", mustBeInteger); let lineText = getFlag(location2, keys, "lineText", mustBeString); let suggestion = getFlag(location2, keys, "suggestion", mustBeString); checkForInvalidFlags(location2, keys, where); if (lineText) { const relevantASCII = lineText.slice( 0, (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80) ); if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { lineText = relevantASCII; } } return { file: file || "", namespace: namespace || "", line: line || 0, column: column || 0, length: length || 0, lineText: lineText || "", suggestion: suggestion || "" }; } function sanitizeMessages(messages2, property, stash, fallbackPluginName, terminalWidth) { let messagesClone = []; let index = 0; for (const message of messages2) { let keys = {}; let id = getFlag(message, keys, "id", mustBeString); let pluginName = getFlag(message, keys, "pluginName", mustBeString); let text = getFlag(message, keys, "text", mustBeString); let location2 = getFlag(message, keys, "location", mustBeObjectOrNull); let notes = getFlag(message, keys, "notes", mustBeArray); let detail = getFlag(message, keys, "detail", canBeAnything); let where = `in element ${index} of "${property}"`; checkForInvalidFlags(message, keys, where); let notesClone = []; if (notes) { for (const note of notes) { let noteKeys = {}; let noteText = getFlag(note, noteKeys, "text", mustBeString); let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); checkForInvalidFlags(note, noteKeys, where); notesClone.push({ text: noteText || "", location: sanitizeLocation(noteLocation, where, terminalWidth) }); } } messagesClone.push({ id: id || "", pluginName: pluginName || fallbackPluginName, text: text || "", location: sanitizeLocation(location2, where, terminalWidth), notes: notesClone, detail: stash ? stash.store(detail) : -1 }); index++; } return messagesClone; } function sanitizeStringArray(values, property) { const result = []; for (const value2 of values) { if (typeof value2 !== "string") throw new Error(`${quote3(property)} must be an array of strings`); result.push(value2); } return result; } function sanitizeStringMap(map2, property) { const result = /* @__PURE__ */ Object.create(null); for (const key in map2) { const value2 = map2[key]; if (typeof value2 !== "string") throw new Error(`key ${quote3(key)} in object ${quote3(property)} must be a string`); result[key] = value2; } return result; } function convertOutputFiles({ path: path32, contents, hash: hash2 }) { let text = null; return { path: path32, contents, hash: hash2, get text() { const binary2 = this.contents; if (text === null || binary2 !== contents) { contents = binary2; text = decodeUTF8(binary2); } return text; } }; } var fs2 = require_fs(); var os2 = require_os(); var path3 = require_path(); var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; var packageDarwin_arm64 = "@esbuild/darwin-arm64"; var packageDarwin_x64 = "@esbuild/darwin-x64"; var knownWindowsPackages = { "win32 arm64 LE": "@esbuild/win32-arm64", "win32 ia32 LE": "@esbuild/win32-ia32", "win32 x64 LE": "@esbuild/win32-x64" }; var knownUnixlikePackages = { "aix ppc64 BE": "@esbuild/aix-ppc64", "android arm64 LE": "@esbuild/android-arm64", "darwin arm64 LE": "@esbuild/darwin-arm64", "darwin x64 LE": "@esbuild/darwin-x64", "freebsd arm64 LE": "@esbuild/freebsd-arm64", "freebsd x64 LE": "@esbuild/freebsd-x64", "linux arm LE": "@esbuild/linux-arm", "linux arm64 LE": "@esbuild/linux-arm64", "linux ia32 LE": "@esbuild/linux-ia32", "linux mips64el LE": "@esbuild/linux-mips64el", "linux ppc64 LE": "@esbuild/linux-ppc64", "linux riscv64 LE": "@esbuild/linux-riscv64", "linux s390x BE": "@esbuild/linux-s390x", "linux x64 LE": "@esbuild/linux-x64", "linux loong64 LE": "@esbuild/linux-loong64", "netbsd x64 LE": "@esbuild/netbsd-x64", "openbsd x64 LE": "@esbuild/openbsd-x64", "sunos x64 LE": "@esbuild/sunos-x64" }; var knownWebAssemblyFallbackPackages = { "android arm LE": "@esbuild/android-arm", "android x64 LE": "@esbuild/android-x64" }; function pkgAndSubpathForCurrentPlatform() { let pkg; let subpath; let isWASM = false; let platformKey = `${process.platform} ${os2.arch()} ${os2.endianness()}`; if (platformKey in knownWindowsPackages) { pkg = knownWindowsPackages[platformKey]; subpath = "esbuild.exe"; } else if (platformKey in knownUnixlikePackages) { pkg = knownUnixlikePackages[platformKey]; subpath = "bin/esbuild"; } else if (platformKey in knownWebAssemblyFallbackPackages) { pkg = knownWebAssemblyFallbackPackages[platformKey]; subpath = "bin/esbuild"; isWASM = true; } else { throw new Error(`Unsupported platform: ${platformKey}`); } return { pkg, subpath, isWASM }; } function pkgForSomeOtherPlatform() { const libMainJS = __require.resolve("esbuild"); const nodeModulesDirectory = path3.dirname(path3.dirname(path3.dirname(libMainJS))); if (path3.basename(nodeModulesDirectory) === "node_modules") { for (const unixKey in knownUnixlikePackages) { try { const pkg = knownUnixlikePackages[unixKey]; if (fs2.existsSync(path3.join(nodeModulesDirectory, pkg))) return pkg; } catch { } } for (const windowsKey in knownWindowsPackages) { try { const pkg = knownWindowsPackages[windowsKey]; if (fs2.existsSync(path3.join(nodeModulesDirectory, pkg))) return pkg; } catch { } } } return null; } function downloadedBinPath(pkg, subpath) { const esbuildLibDir = path3.dirname(__require.resolve("esbuild")); return path3.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path3.basename(subpath)}`); } function generateBinPath() { if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { if (!fs2.existsSync(ESBUILD_BINARY_PATH)) { console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); } else { return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; } } const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); let binPath; try { binPath = __require.resolve(`${pkg}/${subpath}`); } catch (e2) { binPath = downloadedBinPath(pkg, subpath); if (!fs2.existsSync(binPath)) { try { __require.resolve(pkg); } catch { const otherPkg = pkgForSomeOtherPlatform(); if (otherPkg) { let suggestions = ` Specifically the "${otherPkg}" package is present but this platform needs the "${pkg}" package instead. People often get into this situation by installing esbuild on Windows or macOS and copying "node_modules" into a Docker image that runs Linux, or by copying "node_modules" between Windows and WSL environments. If you are installing with npm, you can try not copying the "node_modules" directory when you copy the files over, and running "npm ci" or "npm install" on the destination platform after the copy. Or you could consider using yarn instead of npm which has built-in support for installing a package on multiple platforms simultaneously. If you are installing with yarn, you can try listing both this platform and the other platform in your ".yarnrc.yml" file using the "supportedArchitectures" feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures Keep in mind that this means multiple copies of esbuild will be present. `; if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { suggestions = ` Specifically the "${otherPkg}" package is present but this platform needs the "${pkg}" package instead. People often get into this situation by installing esbuild with npm running inside of Rosetta 2 and then trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta 2 is Apple's on-the-fly x86_64-to-arm64 translation service). If you are installing with npm, you can try ensuring that both npm and node are not running under Rosetta 2 and then reinstalling esbuild. This likely involves changing how you installed npm and/or node. For example, installing node with the universal installer here should work: https://nodejs.org/en/download/. Or you could consider using yarn instead of npm which has built-in support for installing a package on multiple platforms simultaneously. If you are installing with yarn, you can try listing both "arm64" and "x64" in your ".yarnrc.yml" file using the "supportedArchitectures" feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures Keep in mind that this means multiple copies of esbuild will be present. `; } throw new Error(` You installed esbuild for another platform than the one you're currently using. This won't work because esbuild is written with native code and needs to install a platform-specific binary executable. ${suggestions} Another alternative is to use the "esbuild-wasm" package instead, which works the same way on all platforms. But it comes with a heavy performance cost and can sometimes be 10x slower than the "esbuild" package, so you may also not want to do that. `); } throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. If you are installing esbuild with npm, make sure that you don't specify the "--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature of "package.json" is used by esbuild to install the correct binary executable for your current platform.`); } throw e2; } } if (/\.zip\//.test(binPath)) { let pnpapi; try { pnpapi = __require("pnpapi"); } catch (e2) { } if (pnpapi) { const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; const binTargetPath = path3.join( root, "node_modules", ".cache", "esbuild", `pnpapi-${pkg.replace("/", "-")}-${"0.21.5"}-${path3.basename(subpath)}` ); if (!fs2.existsSync(binTargetPath)) { fs2.mkdirSync(path3.dirname(binTargetPath), { recursive: true }); fs2.copyFileSync(binPath, binTargetPath); fs2.chmodSync(binTargetPath, 493); } return { binPath: binTargetPath, isWASM }; } } return { binPath, isWASM }; } var child_process = require_child_process(); var crypto2 = require_crypto(); var path22 = require_path(); var fs22 = require_fs(); var os22 = require_os(); var tty = require_tty(); var worker_threads; if (process.env.ESBUILD_WORKER_THREADS !== "0") { try { worker_threads = require_worker_threads(); } catch { } let [major, minor] = process.versions.node.split("."); if ( // { if ((!ESBUILD_BINARY_PATH || false) && (path22.basename(__filename) !== "main.js" || path22.basename(__dirname) !== "lib")) { throw new Error( `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle. More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.` ); } if (false) { return ["node", [path22.join(__dirname, "..", "bin", "esbuild")]]; } else { const { binPath, isWASM } = generateBinPath(); if (isWASM) { return ["node", [binPath]]; } else { return [binPath, []]; } } }; var isTTY = () => tty.isatty(2); var fsSync = { readFile(tempFile, callback) { try { let contents = fs22.readFileSync(tempFile, "utf8"); try { fs22.unlinkSync(tempFile); } catch { } callback(null, contents); } catch (err2) { callback(err2, null); } }, writeFile(contents, callback) { try { let tempFile = randomFileName(); fs22.writeFileSync(tempFile, contents); callback(tempFile); } catch { callback(null); } } }; var fsAsync = { readFile(tempFile, callback) { try { fs22.readFile(tempFile, "utf8", (err2, contents) => { try { fs22.unlink(tempFile, () => callback(err2, contents)); } catch { callback(err2, contents); } }); } catch (err2) { callback(err2, null); } }, writeFile(contents, callback) { try { let tempFile = randomFileName(); fs22.writeFile(tempFile, contents, (err2) => err2 !== null ? callback(null) : callback(tempFile)); } catch { callback(null); } } }; var version3 = "0.21.5"; var build2 = (options2) => ensureServiceIsRunning().build(options2); var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions); var transform2 = (input, options2) => ensureServiceIsRunning().transform(input, options2); var formatMessages2 = (messages2, options2) => ensureServiceIsRunning().formatMessages(messages2, options2); var analyzeMetafile = (messages2, options2) => ensureServiceIsRunning().analyzeMetafile(messages2, options2); var buildSync = (options2) => { if (worker_threads && !isInternalWorkerThread) { if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); return workerThreadService.buildSync(options2); } let result; runServiceSync((service) => service.buildOrContext({ callName: "buildSync", refs: null, options: options2, isTTY: isTTY(), defaultWD, callback: (err2, res) => { if (err2) throw err2; result = res; } })); return result; }; var transformSync = (input, options2) => { if (worker_threads && !isInternalWorkerThread) { if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); return workerThreadService.transformSync(input, options2); } let result; runServiceSync((service) => service.transform({ callName: "transformSync", refs: null, input, options: options2 || {}, isTTY: isTTY(), fs: fsSync, callback: (err2, res) => { if (err2) throw err2; result = res; } })); return result; }; var formatMessagesSync = (messages2, options2) => { if (worker_threads && !isInternalWorkerThread) { if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); return workerThreadService.formatMessagesSync(messages2, options2); } let result; runServiceSync((service) => service.formatMessages({ callName: "formatMessagesSync", refs: null, messages: messages2, options: options2, callback: (err2, res) => { if (err2) throw err2; result = res; } })); return result; }; var analyzeMetafileSync = (metafile, options2) => { if (worker_threads && !isInternalWorkerThread) { if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); return workerThreadService.analyzeMetafileSync(metafile, options2); } let result; runServiceSync((service) => service.analyzeMetafile({ callName: "analyzeMetafileSync", refs: null, metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), options: options2, callback: (err2, res) => { if (err2) throw err2; result = res; } })); return result; }; var stop = () => { if (stopService) stopService(); if (workerThreadService) workerThreadService.stop(); return Promise.resolve(); }; var initializeWasCalled = false; var initialize = (options2) => { options2 = validateInitializeOptions(options2 || {}); if (options2.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`); if (options2.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`); if (options2.worker) throw new Error(`The "worker" option only works in the browser`); if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once'); ensureServiceIsRunning(); initializeWasCalled = true; return Promise.resolve(); }; var defaultWD = process.cwd(); var longLivedService; var stopService; var ensureServiceIsRunning = () => { if (longLivedService) return longLivedService; let [command, args] = esbuildCommandAndArgs(); let child = child_process.spawn(command, args.concat(`--service=${"0.21.5"}`, "--ping"), { windowsHide: true, stdio: ["pipe", "pipe", "inherit"], cwd: defaultWD }); let { readFromStdout, afterClose, service } = createChannel({ writeToStdin(bytes) { child.stdin.write(bytes, (err2) => { if (err2) afterClose(err2); }); }, readFileSync: fs22.readFileSync, isSync: false, hasFS: true, esbuild: node_exports }); child.stdin.on("error", afterClose); child.on("error", afterClose); const stdin = child.stdin; const stdout = child.stdout; stdout.on("data", readFromStdout); stdout.on("end", afterClose); stopService = () => { stdin.destroy(); stdout.destroy(); child.kill(); initializeWasCalled = false; longLivedService = void 0; stopService = void 0; }; let refCount = 0; child.unref(); if (stdin.unref) { stdin.unref(); } if (stdout.unref) { stdout.unref(); } const refs = { ref() { if (++refCount === 1) child.ref(); }, unref() { if (--refCount === 0) child.unref(); } }; longLivedService = { build: (options2) => new Promise((resolve3, reject) => { service.buildOrContext({ callName: "build", refs, options: options2, isTTY: isTTY(), defaultWD, callback: (err2, res) => err2 ? reject(err2) : resolve3(res) }); }), context: (options2) => new Promise((resolve3, reject) => service.buildOrContext({ callName: "context", refs, options: options2, isTTY: isTTY(), defaultWD, callback: (err2, res) => err2 ? reject(err2) : resolve3(res) })), transform: (input, options2) => new Promise((resolve3, reject) => service.transform({ callName: "transform", refs, input, options: options2 || {}, isTTY: isTTY(), fs: fsAsync, callback: (err2, res) => err2 ? reject(err2) : resolve3(res) })), formatMessages: (messages2, options2) => new Promise((resolve3, reject) => service.formatMessages({ callName: "formatMessages", refs, messages: messages2, options: options2, callback: (err2, res) => err2 ? reject(err2) : resolve3(res) })), analyzeMetafile: (metafile, options2) => new Promise((resolve3, reject) => service.analyzeMetafile({ callName: "analyzeMetafile", refs, metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), options: options2, callback: (err2, res) => err2 ? reject(err2) : resolve3(res) })) }; return longLivedService; }; var runServiceSync = (callback) => { let [command, args] = esbuildCommandAndArgs(); let stdin = new Uint8Array(); let { readFromStdout, afterClose, service } = createChannel({ writeToStdin(bytes) { if (stdin.length !== 0) throw new Error("Must run at most one command"); stdin = bytes; }, isSync: true, hasFS: true, esbuild: node_exports }); callback(service); let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.21.5"}`), { cwd: defaultWD, windowsHide: true, input: stdin, // We don't know how large the output could be. If it's too large, the // command will fail with ENOBUFS. Reserve 16mb for now since that feels // like it should be enough. Also allow overriding this with an environment // variable. maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 }); readFromStdout(stdout); afterClose(null); }; var randomFileName = () => { return path22.join(os22.tmpdir(), `esbuild-${crypto2.randomBytes(32).toString("hex")}`); }; var workerThreadService = null; var startWorkerThreadService = (worker_threads2) => { let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel(); let worker = new worker_threads2.Worker(__filename, { workerData: { workerPort, defaultWD, esbuildVersion: "0.21.5" }, transferList: [workerPort], // From node's documentation: https://nodejs.org/api/worker_threads.html // // Take care when launching worker threads from preload scripts (scripts loaded // and run using the `-r` command line flag). Unless the `execArgv` option is // explicitly set, new Worker threads automatically inherit the command line flags // from the running process and will preload the same preload scripts as the main // thread. If the preload script unconditionally launches a worker thread, every // thread spawned will spawn another until the application crashes. // execArgv: [] }); let nextID = 0; let fakeBuildError = (text) => { let error2 = new Error(`Build failed with 1 error: error: ${text}`); let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }]; error2.errors = errors; error2.warnings = []; return error2; }; let validateBuildSyncOptions = (options2) => { if (!options2) return; let plugins2 = options2.plugins; if (plugins2 && plugins2.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`); }; let applyProperties = (object, properties) => { for (let key in properties) { object[key] = properties[key]; } }; let runCallSync = (command, args) => { let id = nextID++; let sharedBuffer = new SharedArrayBuffer(8); let sharedBufferView = new Int32Array(sharedBuffer); let msg = { sharedBuffer, id, command, args }; worker.postMessage(msg); let status2 = Atomics.wait(sharedBufferView, 0, 0); if (status2 !== "ok" && status2 !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status2); let { message: { id: id2, resolve: resolve3, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort); if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); if (reject) { applyProperties(reject, properties); throw reject; } return resolve3; }; worker.unref(); return { buildSync(options2) { validateBuildSyncOptions(options2); return runCallSync("build", [options2]); }, transformSync(input, options2) { return runCallSync("transform", [input, options2]); }, formatMessagesSync(messages2, options2) { return runCallSync("formatMessages", [messages2, options2]); }, analyzeMetafileSync(metafile, options2) { return runCallSync("analyzeMetafile", [metafile, options2]); }, stop() { worker.terminate(); workerThreadService = null; } }; }; var startSyncServiceWorker = () => { let workerPort = worker_threads.workerData.workerPort; let parentPort = worker_threads.parentPort; let extractProperties = (object) => { let properties = {}; if (object && typeof object === "object") { for (let key in object) { properties[key] = object[key]; } } return properties; }; try { let service = ensureServiceIsRunning(); defaultWD = worker_threads.workerData.defaultWD; parentPort.on("message", (msg) => { (async () => { let { sharedBuffer, id, command, args } = msg; let sharedBufferView = new Int32Array(sharedBuffer); try { switch (command) { case "build": workerPort.postMessage({ id, resolve: await service.build(args[0]) }); break; case "transform": workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) }); break; case "formatMessages": workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) }); break; case "analyzeMetafile": workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) }); break; default: throw new Error(`Invalid command: ${command}`); } } catch (reject) { workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); } Atomics.add(sharedBufferView, 0, 1); Atomics.notify(sharedBufferView, 0, Infinity); })(); }); } catch (reject) { parentPort.on("message", (msg) => { let { sharedBuffer, id } = msg; let sharedBufferView = new Int32Array(sharedBuffer); workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); Atomics.add(sharedBufferView, 0, 1); Atomics.notify(sharedBufferView, 0, Infinity); }); } }; if (isInternalWorkerThread) { startSyncServiceWorker(); } var node_default = node_exports; } }); // browser-external:node:events var require_node_events = __commonJS({ "browser-external:node:events"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:events" has been externalized for browser compatibility. Cannot access "node:events.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:stream var require_node_stream = __commonJS({ "browser-external:node:stream"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:stream" has been externalized for browser compatibility. Cannot access "node:stream.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:string_decoder var require_node_string_decoder = __commonJS({ "browser-external:node:string_decoder"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:string_decoder" has been externalized for browser compatibility. Cannot access "node:string_decoder.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:child_process var require_node_child_process = __commonJS({ "browser-external:node:child_process"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:child_process" has been externalized for browser compatibility. Cannot access "node:child_process.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:net var require_net = __commonJS({ "browser-external:net"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "net" has been externalized for browser compatibility. Cannot access "net.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:http var require_http = __commonJS({ "browser-external:http"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "http" has been externalized for browser compatibility. Cannot access "http.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:crypto var require_node_crypto = __commonJS({ "browser-external:node:crypto"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:crypto" has been externalized for browser compatibility. Cannot access "node:crypto.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:dns var require_node_dns = __commonJS({ "browser-external:node:dns"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:dns" has been externalized for browser compatibility. Cannot access "node:dns.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:module var require_module = __commonJS({ "browser-external:module"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "module" has been externalized for browser compatibility. Cannot access "module.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:assert var require_node_assert = __commonJS({ "browser-external:node:assert"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:assert" has been externalized for browser compatibility. Cannot access "node:assert.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:v8 var require_node_v8 = __commonJS({ "browser-external:node:v8"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:v8" has been externalized for browser compatibility. Cannot access "node:v8.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:worker_threads var require_node_worker_threads = __commonJS({ "browser-external:node:worker_threads"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:worker_threads" has been externalized for browser compatibility. Cannot access "node:worker_threads.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:buffer var require_node_buffer = __commonJS({ "browser-external:node:buffer"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:buffer" has been externalized for browser compatibility. Cannot access "node:buffer.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:querystring var require_querystring = __commonJS({ "browser-external:querystring"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "querystring" has been externalized for browser compatibility. Cannot access "querystring.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:readline var require_node_readline = __commonJS({ "browser-external:node:readline"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:readline" has been externalized for browser compatibility. Cannot access "node:readline.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:zlib var require_zlib = __commonJS({ "browser-external:zlib"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "zlib" has been externalized for browser compatibility. Cannot access "zlib.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:buffer var require_buffer = __commonJS({ "browser-external:buffer"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "buffer" has been externalized for browser compatibility. Cannot access "buffer.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:https var require_https = __commonJS({ "browser-external:https"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "https" has been externalized for browser compatibility. Cannot access "https.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:tls var require_tls = __commonJS({ "browser-external:tls"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "tls" has been externalized for browser compatibility. Cannot access "tls.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:assert var require_assert = __commonJS({ "browser-external:assert"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "assert" has been externalized for browser compatibility. Cannot access "assert.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // browser-external:node:zlib var require_node_zlib = __commonJS({ "browser-external:node:zlib"(exports2, module) { module.exports = Object.create(new Proxy({}, { get(_, key) { if (key !== "__esModule" && key !== "__proto__" && key !== "constructor" && key !== "splice") { console.warn(`Module "node:zlib" has been externalized for browser compatibility. Cannot access "node:zlib.${key}" in client code. See https://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // node_modules/rollup/dist/es/parseAst.js var import_native = __toESM(require_native()); var import_node_path = __toESM(require_node_path()); // node_modules/vite/dist/node/constants.js var import_node_path2 = __toESM(require_node_path(), 1); var import_node_url = __toESM(require_node_url(), 1); var import_node_fs = __toESM(require_node_fs(), 1); var { version } = JSON.parse( (0, import_node_fs.readFileSync)(new URL("../../package.json", import.meta.url)).toString() ); var VERSION = version; var DEFAULT_MAIN_FIELDS = [ "browser", "module", "jsnext:main", // moment still uses this... "jsnext" ]; var ESBUILD_MODULES_TARGET = [ "es2020", // support import.meta.url "edge88", "firefox78", "chrome87", "safari14" ]; var DEFAULT_EXTENSIONS = [ ".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json" ]; var DEFAULT_CONFIG_FILES = [ "vite.config.js", "vite.config.mjs", "vite.config.ts", "vite.config.cjs", "vite.config.mts", "vite.config.cts" ]; var JS_TYPES_RE = /\.(?:j|t)sx?$|\.mjs$/; var CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/; var OPTIMIZABLE_ENTRY_RE = /\.[cm]?[jt]s$/; var SPECIAL_QUERY_RE = /[?&](?:worker|sharedworker|raw|url)\b/; var FS_PREFIX = `/@fs/`; var CLIENT_PUBLIC_PATH = `/@vite/client`; var ENV_PUBLIC_PATH = `/@vite/env`; var VITE_PACKAGE_DIR = (0, import_node_path2.resolve)( // import.meta.url is `dist/node/constants.js` after bundle (0, import_node_url.fileURLToPath)(import.meta.url), "../../.." ); var CLIENT_ENTRY = (0, import_node_path2.resolve)(VITE_PACKAGE_DIR, "dist/client/client.mjs"); var ENV_ENTRY = (0, import_node_path2.resolve)(VITE_PACKAGE_DIR, "dist/client/env.mjs"); var CLIENT_DIR = import_node_path2.default.dirname(CLIENT_ENTRY); var KNOWN_ASSET_TYPES = [ // images "apng", "bmp", "png", "jpe?g", "jfif", "pjpeg", "pjp", "gif", "svg", "ico", "webp", "avif", // media "mp4", "webm", "ogg", "mp3", "wav", "flac", "aac", "opus", "mov", "m4a", "vtt", // fonts "woff2?", "eot", "ttf", "otf", // other "webmanifest", "pdf", "txt" ]; var DEFAULT_ASSETS_RE = new RegExp( `\\.(` + KNOWN_ASSET_TYPES.join("|") + `)(\\?.*)?$` ); var DEP_VERSION_RE = /[?&](v=[\w.-]+)\b/; var loopbackHosts = /* @__PURE__ */ new Set([ "localhost", "127.0.0.1", "::1", "0000:0000:0000:0000:0000:0000:0000:0001" ]); var wildcardHosts = /* @__PURE__ */ new Set([ "0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000" ]); var DEFAULT_DEV_PORT = 5173; var DEFAULT_PREVIEW_PORT = 4173; var DEFAULT_ASSETS_INLINE_LIMIT = 4096; var METADATA_FILENAME = "_metadata.json"; // node_modules/vite/dist/node/chunks/dep-mCdpKltl.js var fs$j = __toESM(require_node_fs(), 1); var import_node_fs2 = __toESM(require_node_fs(), 1); var import_promises = __toESM(require_promises(), 1); var import_node_path3 = __toESM(require_node_path(), 1); var import_node_url2 = __toESM(require_node_url(), 1); var import_node_util = __toESM(require_node_util(), 1); var import_node_perf_hooks = __toESM(require_node_perf_hooks(), 1); var import_node_module = __toESM(require_node_module(), 1); var import_tty = __toESM(require_tty(), 1); var import_path = __toESM(require_path(), 1); var import_esbuild = __toESM(require_main(), 1); var require$$0$2 = __toESM(require_fs(), 1); var import_fs = __toESM(require_fs(), 1); var import_node_events = __toESM(require_node_events(), 1); var import_node_stream = __toESM(require_node_stream(), 1); var import_node_string_decoder = __toESM(require_node_string_decoder(), 1); var import_node_child_process = __toESM(require_node_child_process(), 1); var import_node_http = __toESM(require_node_http(), 1); var import_node_https = __toESM(require_node_https(), 1); var import_util = __toESM(require_util(), 1); var import_net = __toESM(require_net(), 1); var import_events = __toESM(require_events(), 1); var import_url = __toESM(require_url(), 1); var import_http = __toESM(require_http(), 1); var import_stream = __toESM(require_stream(), 1); var import_os = __toESM(require_os(), 1); var import_child_process = __toESM(require_child_process(), 1); var import_node_os = __toESM(require_node_os(), 1); var import_node_crypto = __toESM(require_node_crypto(), 1); var import_node_dns = __toESM(require_node_dns(), 1); var import_crypto = __toESM(require_crypto(), 1); var import_module = __toESM(require_module(), 1); var import_node_assert = __toESM(require_node_assert(), 1); var import_node_v8 = __toESM(require_node_v8(), 1); var import_node_worker_threads = __toESM(require_node_worker_threads(), 1); var import_node_buffer = __toESM(require_node_buffer(), 1); var qs = __toESM(require_querystring(), 1); var import_node_readline = __toESM(require_node_readline(), 1); var import_zlib = __toESM(require_zlib(), 1); var import_buffer = __toESM(require_buffer(), 1); var import_https = __toESM(require_https(), 1); var import_tls = __toESM(require_tls(), 1); var import_assert = __toESM(require_assert(), 1); var import_node_zlib = __toESM(require_node_zlib(), 1); var import_node_url3 = __toESM(require_node_url(), 1); var import_node_path4 = __toESM(require_node_path(), 1); var import_node_module2 = __toESM(require_node_module(), 1); var __filename2 = (0, import_node_url3.fileURLToPath)(import.meta.url); var __dirname2 = (0, import_node_path4.dirname)(__filename2); var require2 = (0, import_node_module2.createRequire)(import.meta.url); var __require2 = require2; var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } function getAugmentedNamespace(n2) { if (n2.__esModule) return n2; var f2 = n2.default; if (typeof f2 == "function") { var a = function a2() { if (this instanceof a2) { return Reflect.construct(f2, arguments, this.constructor); } return f2.apply(this, arguments); }; a.prototype = f2.prototype; } else a = {}; Object.defineProperty(a, "__esModule", { value: true }); Object.keys(n2).forEach(function(k) { var d = Object.getOwnPropertyDescriptor(n2, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function() { return n2[k]; } }); }); return a; } function commonjsRequire(path3) { throw new Error('Could not dynamically require "' + path3 + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); } var picocolors = { exports: {} }; var argv = process.argv || []; var env$1 = process.env; var isColorSupported = !("NO_COLOR" in env$1 || argv.includes("--no-color")) && ("FORCE_COLOR" in env$1 || argv.includes("--color") || process.platform === "win32" || commonjsRequire != null && import_tty.default.isatty(1) && env$1.TERM !== "dumb" || "CI" in env$1); var formatter = (open2, close2, replace = open2) => (input) => { let string2 = "" + input; let index = string2.indexOf(close2, open2.length); return ~index ? open2 + replaceClose(string2, close2, replace, index) + close2 : open2 + string2 + close2; }; var replaceClose = (string2, close2, replace, index) => { let result = ""; let cursor = 0; do { result += string2.substring(cursor, index) + replace; cursor = index + close2.length; index = string2.indexOf(close2, cursor); } while (~index); return result + string2.substring(cursor); }; var createColors = (enabled = isColorSupported) => { let init2 = enabled ? formatter : () => String; return { isColorSupported: enabled, reset: init2("\x1B[0m", "\x1B[0m"), bold: init2("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"), dim: init2("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"), italic: init2("\x1B[3m", "\x1B[23m"), underline: init2("\x1B[4m", "\x1B[24m"), inverse: init2("\x1B[7m", "\x1B[27m"), hidden: init2("\x1B[8m", "\x1B[28m"), strikethrough: init2("\x1B[9m", "\x1B[29m"), black: init2("\x1B[30m", "\x1B[39m"), red: init2("\x1B[31m", "\x1B[39m"), green: init2("\x1B[32m", "\x1B[39m"), yellow: init2("\x1B[33m", "\x1B[39m"), blue: init2("\x1B[34m", "\x1B[39m"), magenta: init2("\x1B[35m", "\x1B[39m"), cyan: init2("\x1B[36m", "\x1B[39m"), white: init2("\x1B[37m", "\x1B[39m"), gray: init2("\x1B[90m", "\x1B[39m"), bgBlack: init2("\x1B[40m", "\x1B[49m"), bgRed: init2("\x1B[41m", "\x1B[49m"), bgGreen: init2("\x1B[42m", "\x1B[49m"), bgYellow: init2("\x1B[43m", "\x1B[49m"), bgBlue: init2("\x1B[44m", "\x1B[49m"), bgMagenta: init2("\x1B[45m", "\x1B[49m"), bgCyan: init2("\x1B[46m", "\x1B[49m"), bgWhite: init2("\x1B[47m", "\x1B[49m") }; }; picocolors.exports = createColors(); picocolors.exports.createColors = createColors; var picocolorsExports = picocolors.exports; var colors$1 = getDefaultExportFromCjs(picocolorsExports); function matches$1(pattern2, importee) { if (pattern2 instanceof RegExp) { return pattern2.test(importee); } if (importee.length < pattern2.length) { return false; } if (importee === pattern2) { return true; } return importee.startsWith(pattern2 + "/"); } function getEntries({ entries, customResolver }) { if (!entries) { return []; } const resolverFunctionFromOptions = resolveCustomResolver(customResolver); if (Array.isArray(entries)) { return entries.map((entry2) => { return { find: entry2.find, replacement: entry2.replacement, resolverFunction: resolveCustomResolver(entry2.customResolver) || resolverFunctionFromOptions }; }); } return Object.entries(entries).map(([key, value2]) => { return { find: key, replacement: value2, resolverFunction: resolverFunctionFromOptions }; }); } function getHookFunction(hook) { if (typeof hook === "function") { return hook; } if (hook && "handler" in hook && typeof hook.handler === "function") { return hook.handler; } return null; } function resolveCustomResolver(customResolver) { if (typeof customResolver === "function") { return customResolver; } if (customResolver) { return getHookFunction(customResolver.resolveId); } return null; } function alias$1(options2 = {}) { const entries = getEntries(options2); if (entries.length === 0) { return { name: "alias", resolveId: () => null }; } return { name: "alias", async buildStart(inputOptions) { await Promise.all([...Array.isArray(options2.entries) ? options2.entries : [], options2].map(({ customResolver }) => { var _a4; return customResolver && ((_a4 = getHookFunction(customResolver.buildStart)) === null || _a4 === void 0 ? void 0 : _a4.call(this, inputOptions)); })); }, resolveId(importee, importer, resolveOptions) { const matchedEntry = entries.find((entry2) => matches$1(entry2.find, importee)); if (!matchedEntry) { return null; } const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement); if (matchedEntry.resolverFunction) { return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions); } return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => { if (resolved) return resolved; if (!import_path.default.isAbsolute(updatedId)) { this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. This will lead to duplicated modules for the same path. To avoid duplicating modules, you should resolve to an absolute path.`); } return { id: updatedId }; }); } }; } var VALID_ID_PREFIX = `/@id/`; var NULL_BYTE_PLACEHOLDER = `__x00__`; var SOURCEMAPPING_URL = "sourceMa"; SOURCEMAPPING_URL += "ppingURL"; var VITE_RUNTIME_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-runtime"; var isWindows$3 = typeof process !== "undefined" && process.platform === "win32"; function wrapId$1(id) { return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER); } function unwrapId$1(id) { return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id; } var windowsSlashRE = /\\/g; function slash$1(p) { return p.replace(windowsSlashRE, "/"); } var postfixRE = /[?#].*$/; function cleanUrl(url2) { return url2.replace(postfixRE, ""); } function withTrailingSlash(path3) { if (path3[path3.length - 1] !== "/") { return `${path3}/`; } return path3; } var AsyncFunction = (async function() { }).constructor; var asyncFunctionDeclarationPaddingLineCount = (() => { const body = "/*code*/"; const source = new AsyncFunction("a", "b", body).toString(); return source.slice(0, source.indexOf(body)).split("\n").length - 1; })(); var WalkerBase$1 = class WalkerBase { constructor() { this.should_skip = false; this.should_remove = false; this.replacement = null; this.context = { skip: () => this.should_skip = true, remove: () => this.should_remove = true, replace: (node2) => this.replacement = node2 }; } /** * * @param {any} parent * @param {string} prop * @param {number} index * @param {BaseNode} node */ replace(parent, prop, index, node2) { if (parent) { if (index !== null) { parent[prop][index] = node2; } else { parent[prop] = node2; } } } /** * * @param {any} parent * @param {string} prop * @param {number} index */ remove(parent, prop, index) { if (parent) { if (index !== null) { parent[prop].splice(index, 1); } else { delete parent[prop]; } } } }; var SyncWalker$1 = class SyncWalker extends WalkerBase$1 { /** * * @param {SyncHandler} enter * @param {SyncHandler} leave */ constructor(enter, leave) { super(); this.enter = enter; this.leave = leave; } /** * * @param {BaseNode} node * @param {BaseNode} parent * @param {string} [prop] * @param {number} [index] * @returns {BaseNode} */ visit(node2, parent, prop, index) { if (node2) { if (this.enter) { const _should_skip = this.should_skip; const _should_remove = this.should_remove; const _replacement = this.replacement; this.should_skip = false; this.should_remove = false; this.replacement = null; this.enter.call(this.context, node2, parent, prop, index); if (this.replacement) { node2 = this.replacement; this.replace(parent, prop, index, node2); } if (this.should_remove) { this.remove(parent, prop, index); } const skipped = this.should_skip; const removed = this.should_remove; this.should_skip = _should_skip; this.should_remove = _should_remove; this.replacement = _replacement; if (skipped) return node2; if (removed) return null; } for (const key in node2) { const value2 = node2[key]; if (typeof value2 !== "object") { continue; } else if (Array.isArray(value2)) { for (let i = 0; i < value2.length; i += 1) { if (value2[i] !== null && typeof value2[i].type === "string") { if (!this.visit(value2[i], node2, key, i)) { i--; } } } } else if (value2 !== null && typeof value2.type === "string") { this.visit(value2, node2, key, null); } } if (this.leave) { const _replacement = this.replacement; const _should_remove = this.should_remove; this.replacement = null; this.should_remove = false; this.leave.call(this.context, node2, parent, prop, index); if (this.replacement) { node2 = this.replacement; this.replace(parent, prop, index, node2); } if (this.should_remove) { this.remove(parent, prop, index); } const removed = this.should_remove; this.replacement = _replacement; this.should_remove = _should_remove; if (removed) return null; } } return node2; } }; function walk$3(ast, { enter, leave }) { const instance = new SyncWalker$1(enter, leave); return instance.visit(ast, null); } var utils$k = {}; var path$m = import_path.default; var WIN_SLASH = "\\\\/"; var WIN_NO_SLASH = `[^${WIN_SLASH}]`; var DOT_LITERAL = "\\."; var PLUS_LITERAL = "\\+"; var QMARK_LITERAL = "\\?"; var SLASH_LITERAL = "\\/"; var ONE_CHAR = "(?=.)"; var QMARK = "[^/]"; var END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; var START_ANCHOR = `(?:^|${SLASH_LITERAL})`; var DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; var NO_DOT = `(?!${DOT_LITERAL})`; var NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; var NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; var NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; var QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; var STAR$1 = `${QMARK}*?`; var POSIX_CHARS = { DOT_LITERAL, PLUS_LITERAL, QMARK_LITERAL, SLASH_LITERAL, ONE_CHAR, QMARK, END_ANCHOR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK_NO_DOT, STAR: STAR$1, START_ANCHOR }; var WINDOWS_CHARS = { ...POSIX_CHARS, SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` }; var POSIX_REGEX_SOURCE$1 = { alnum: "a-zA-Z0-9", alpha: "a-zA-Z", ascii: "\\x00-\\x7F", blank: " \\t", cntrl: "\\x00-\\x1F\\x7F", digit: "0-9", graph: "\\x21-\\x7E", lower: "a-z", print: "\\x20-\\x7E ", punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~", space: " \\t\\r\\n\\v\\f", upper: "A-Z", word: "A-Za-z0-9_", xdigit: "A-Fa-f0-9" }; var constants$6 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { "***": "*", "**/**": "**", "**/**/**": "**" }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ CHAR_ASTERISK: 42, /* * */ // Non-alphabetic chars. CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46, /* . */ CHAR_DOUBLE_QUOTE: 34, /* " */ CHAR_EQUAL: 61, /* = */ CHAR_EXCLAMATION_MARK: 33, /* ! */ CHAR_FORM_FEED: 12, /* \f */ CHAR_FORWARD_SLASH: 47, /* / */ CHAR_GRAVE_ACCENT: 96, /* ` */ CHAR_HASH: 35, /* # */ CHAR_HYPHEN_MINUS: 45, /* - */ CHAR_LEFT_ANGLE_BRACKET: 60, /* < */ CHAR_LEFT_CURLY_BRACE: 123, /* { */ CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */ CHAR_LINE_FEED: 10, /* \n */ CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */ CHAR_PERCENT: 37, /* % */ CHAR_PLUS: 43, /* + */ CHAR_QUESTION_MARK: 63, /* ? */ CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */ CHAR_RIGHT_CURLY_BRACE: 125, /* } */ CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */ CHAR_SEMICOLON: 59, /* ; */ CHAR_SINGLE_QUOTE: 39, /* ' */ CHAR_SPACE: 32, /* */ CHAR_TAB: 9, /* \t */ CHAR_UNDERSCORE: 95, /* _ */ CHAR_VERTICAL_LINE: 124, /* | */ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */ SEP: path$m.sep, /** * Create EXTGLOB_CHARS */ extglobChars(chars2) { return { "!": { type: "negate", open: "(?:(?!(?:", close: `))${chars2.STAR})` }, "?": { type: "qmark", open: "(?:", close: ")?" }, "+": { type: "plus", open: "(?:", close: ")+" }, "*": { type: "star", open: "(?:", close: ")*" }, "@": { type: "at", open: "(?:", close: ")" } }; }, /** * Create GLOB_CHARS */ globChars(win322) { return win322 === true ? WINDOWS_CHARS : POSIX_CHARS; } }; (function(exports2) { const path3 = import_path.default; const win322 = process.platform === "win32"; const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = constants$6; exports2.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val); exports2.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str); exports2.isRegexChar = (str) => str.length === 1 && exports2.hasRegexChars(str); exports2.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"); exports2.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"); exports2.removeBackslashes = (str) => { return str.replace(REGEX_REMOVE_BACKSLASH, (match2) => { return match2 === "\\" ? "" : match2; }); }; exports2.supportsLookbehinds = () => { const segs = process.version.slice(1).split(".").map(Number); if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { return true; } return false; }; exports2.isWindows = (options2) => { if (options2 && typeof options2.windows === "boolean") { return options2.windows; } return win322 === true || path3.sep === "\\"; }; exports2.escapeLast = (input, char, lastIdx) => { const idx = input.lastIndexOf(char, lastIdx); if (idx === -1) return input; if (input[idx - 1] === "\\") return exports2.escapeLast(input, char, idx - 1); return `${input.slice(0, idx)}\\${input.slice(idx)}`; }; exports2.removePrefix = (input, state = {}) => { let output = input; if (output.startsWith("./")) { output = output.slice(2); state.prefix = "./"; } return output; }; exports2.wrapOutput = (input, state = {}, options2 = {}) => { const prepend = options2.contains ? "" : "^"; const append2 = options2.contains ? "" : "$"; let output = `${prepend}(?:${input})${append2}`; if (state.negated === true) { output = `(?:^(?!${output}).*$)`; } return output; }; })(utils$k); var utils$j = utils$k; var { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$6; var isPathSeparator = (code) => { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; }; var depth = (token) => { if (token.isPrefix !== true) { token.depth = token.isGlobstar ? Infinity : 1; } }; var scan$2 = (input, options2) => { const opts = options2 || {}; const length = input.length - 1; const scanToEnd = opts.parts === true || opts.scanToEnd === true; const slashes = []; const tokens = []; const parts = []; let str = input; let index = -1; let start = 0; let lastIndex = 0; let isBrace = false; let isBracket = false; let isGlob3 = false; let isExtglob3 = false; let isGlobstar = false; let braceEscaped = false; let backslashes = false; let negated = false; let negatedExtglob = false; let finished = false; let braces2 = 0; let prev; let code; let token = { value: "", depth: 0, isGlob: false }; const eos = () => index >= length; const peek = () => str.charCodeAt(index + 1); const advance = () => { prev = code; return str.charCodeAt(++index); }; while (index < length) { code = advance(); let next; if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); if (code === CHAR_LEFT_CURLY_BRACE$1) { braceEscaped = true; } continue; } if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { braces2++; while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (code === CHAR_LEFT_CURLY_BRACE$1) { braces2++; continue; } if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { isBrace = token.isBrace = true; isGlob3 = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (braceEscaped !== true && code === CHAR_COMMA$1) { isBrace = token.isBrace = true; isGlob3 = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_RIGHT_CURLY_BRACE$1) { braces2--; if (braces2 === 0) { braceEscaped = false; isBrace = token.isBrace = true; finished = true; break; } } } if (scanToEnd === true) { continue; } break; } if (code === CHAR_FORWARD_SLASH) { slashes.push(index); tokens.push(token); token = { value: "", depth: 0, isGlob: false }; if (finished === true) continue; if (prev === CHAR_DOT$1 && index === start + 1) { start += 2; continue; } lastIndex = index + 1; continue; } if (opts.noext !== true) { const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) { isGlob3 = token.isGlob = true; isExtglob3 = token.isExtglob = true; finished = true; if (code === CHAR_EXCLAMATION_MARK && index === start) { negatedExtglob = true; } if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$1) { isGlob3 = token.isGlob = true; finished = true; break; } } continue; } break; } } if (code === CHAR_ASTERISK) { if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; isGlob3 = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_QUESTION_MARK) { isGlob3 = token.isGlob = true; finished = true; if (scanToEnd === true) { continue; } break; } if (code === CHAR_LEFT_SQUARE_BRACKET$1) { while (eos() !== true && (next = advance())) { if (next === CHAR_BACKWARD_SLASH) { backslashes = token.backslashes = true; advance(); continue; } if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { isBracket = token.isBracket = true; isGlob3 = token.isGlob = true; finished = true; break; } } if (scanToEnd === true) { continue; } break; } if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { negated = token.negated = true; start++; continue; } if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) { isGlob3 = token.isGlob = true; if (scanToEnd === true) { while (eos() !== true && (code = advance())) { if (code === CHAR_LEFT_PARENTHESES$1) { backslashes = token.backslashes = true; code = advance(); continue; } if (code === CHAR_RIGHT_PARENTHESES$1) { finished = true; break; } } continue; } break; } if (isGlob3 === true) { finished = true; if (scanToEnd === true) { continue; } break; } } if (opts.noext === true) { isExtglob3 = false; isGlob3 = false; } let base = str; let prefix = ""; let glob2 = ""; if (start > 0) { prefix = str.slice(0, start); str = str.slice(start); lastIndex -= start; } if (base && isGlob3 === true && lastIndex > 0) { base = str.slice(0, lastIndex); glob2 = str.slice(lastIndex); } else if (isGlob3 === true) { base = ""; glob2 = str; } else { base = str; } if (base && base !== "" && base !== "/" && base !== str) { if (isPathSeparator(base.charCodeAt(base.length - 1))) { base = base.slice(0, -1); } } if (opts.unescape === true) { if (glob2) glob2 = utils$j.removeBackslashes(glob2); if (base && backslashes === true) { base = utils$j.removeBackslashes(base); } } const state = { prefix, input, start, base, glob: glob2, isBrace, isBracket, isGlob: isGlob3, isExtglob: isExtglob3, isGlobstar, negated, negatedExtglob }; if (opts.tokens === true) { state.maxDepth = 0; if (!isPathSeparator(code)) { tokens.push(token); } state.tokens = tokens; } if (opts.parts === true || opts.tokens === true) { let prevIndex; for (let idx = 0; idx < slashes.length; idx++) { const n2 = prevIndex ? prevIndex + 1 : start; const i = slashes[idx]; const value2 = input.slice(n2, i); if (opts.tokens) { if (idx === 0 && start !== 0) { tokens[idx].isPrefix = true; tokens[idx].value = prefix; } else { tokens[idx].value = value2; } depth(tokens[idx]); state.maxDepth += tokens[idx].depth; } if (idx !== 0 || value2 !== "") { parts.push(value2); } prevIndex = i; } if (prevIndex && prevIndex + 1 < input.length) { const value2 = input.slice(prevIndex + 1); parts.push(value2); if (opts.tokens) { tokens[tokens.length - 1].value = value2; depth(tokens[tokens.length - 1]); state.maxDepth += tokens[tokens.length - 1].depth; } } state.slashes = slashes; state.parts = parts; } return state; }; var scan_1 = scan$2; var constants$5 = constants$6; var utils$i = utils$k; var { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$5; var expandRange = (args, options2) => { if (typeof options2.expandRange === "function") { return options2.expandRange(...args, options2); } args.sort(); const value2 = `[${args.join("-")}]`; return value2; }; var syntaxError = (type, char) => { return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; }; var parse$g = (input, options2) => { if (typeof input !== "string") { throw new TypeError("Expected a string"); } input = REPLACEMENTS[input] || input; const opts = { ...options2 }; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; let len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } const bos = { type: "bos", value: "", output: opts.prepend || "" }; const tokens = [bos]; const capture = opts.capture ? "" : "?:"; const win322 = utils$i.isWindows(options2); const PLATFORM_CHARS = constants$5.globChars(win322); const EXTGLOB_CHARS = constants$5.extglobChars(PLATFORM_CHARS); const { DOT_LITERAL: DOT_LITERAL2, PLUS_LITERAL: PLUS_LITERAL2, SLASH_LITERAL: SLASH_LITERAL2, ONE_CHAR: ONE_CHAR2, DOTS_SLASH: DOTS_SLASH2, NO_DOT: NO_DOT2, NO_DOT_SLASH: NO_DOT_SLASH2, NO_DOTS_SLASH: NO_DOTS_SLASH2, QMARK: QMARK2, QMARK_NO_DOT: QMARK_NO_DOT2, STAR: STAR2, START_ANCHOR: START_ANCHOR2 } = PLATFORM_CHARS; const globstar = (opts2) => { return `(${capture}(?:(?!${START_ANCHOR2}${opts2.dot ? DOTS_SLASH2 : DOT_LITERAL2}).)*?)`; }; const nodot = opts.dot ? "" : NO_DOT2; const qmarkNoDot = opts.dot ? QMARK2 : QMARK_NO_DOT2; let star2 = opts.bash === true ? globstar(opts) : STAR2; if (opts.capture) { star2 = `(${star2})`; } if (typeof opts.noext === "boolean") { opts.noextglob = opts.noext; } const state = { input, index: -1, start: 0, dot: opts.dot === true, consumed: "", output: "", prefix: "", backtrack: false, negated: false, brackets: 0, braces: 0, parens: 0, quotes: 0, globstar: false, tokens }; input = utils$i.removePrefix(input, state); len = input.length; const extglobs = []; const braces2 = []; const stack = []; let prev = bos; let value2; const eos = () => state.index === len - 1; const peek = state.peek = (n2 = 1) => input[state.index + n2]; const advance = state.advance = () => input[++state.index] || ""; const remaining = () => input.slice(state.index + 1); const consume = (value3 = "", num = 0) => { state.consumed += value3; state.index += num; }; const append2 = (token) => { state.output += token.output != null ? token.output : token.value; consume(token.value); }; const negate = () => { let count = 1; while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) { advance(); state.start++; count++; } if (count % 2 === 0) { return false; } state.negated = true; state.start++; return true; }; const increment = (type) => { state[type]++; stack.push(type); }; const decrement = (type) => { state[type]--; stack.pop(); }; const push2 = (tok) => { if (prev.type === "globstar") { const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"); const isExtglob3 = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren"); if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob3) { state.output = state.output.slice(0, -prev.output.length); prev.type = "star"; prev.value = "*"; prev.output = star2; state.output += prev.output; } } if (extglobs.length && tok.type !== "paren") { extglobs[extglobs.length - 1].inner += tok.value; } if (tok.value || tok.output) append2(tok); if (prev && prev.type === "text" && tok.type === "text") { prev.value += tok.value; prev.output = (prev.output || "") + tok.value; return; } tok.prev = prev; tokens.push(tok); prev = tok; }; const extglobOpen = (type, value3) => { const token = { ...EXTGLOB_CHARS[value3], conditions: 1, inner: "" }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? "(" : "") + token.open; increment("parens"); push2({ type, value: value3, output: state.output ? "" : ONE_CHAR2 }); push2({ type: "paren", extglob: true, value: advance(), output }); extglobs.push(token); }; const extglobClose = (token) => { let output = token.close + (opts.capture ? ")" : ""); let rest; if (token.type === "negate") { let extglobStar = star2; if (token.inner && token.inner.length > 1 && token.inner.includes("/")) { extglobStar = globstar(opts); } if (extglobStar !== star2 || eos() || /^\)+$/.test(remaining())) { output = token.close = `)$))${extglobStar}`; } if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) { const expression = parse$g(rest, { ...options2, fastpaths: false }).output; output = token.close = `)${expression})${extglobStar})`; } if (token.prev.type === "bos") { state.negatedExtglob = true; } } push2({ type: "paren", extglob: true, value: value2, output }); decrement("parens"); }; if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { let backslashes = false; let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars2, first2, rest, index) => { if (first2 === "\\") { backslashes = true; return m; } if (first2 === "?") { if (esc) { return esc + first2 + (rest ? QMARK2.repeat(rest.length) : ""); } if (index === 0) { return qmarkNoDot + (rest ? QMARK2.repeat(rest.length) : ""); } return QMARK2.repeat(chars2.length); } if (first2 === ".") { return DOT_LITERAL2.repeat(chars2.length); } if (first2 === "*") { if (esc) { return esc + first2 + (rest ? star2 : ""); } return star2; } return esc ? m : `\\${m}`; }); if (backslashes === true) { if (opts.unescape === true) { output = output.replace(/\\/g, ""); } else { output = output.replace(/\\+/g, (m) => { return m.length % 2 === 0 ? "\\\\" : m ? "\\" : ""; }); } } if (output === input && opts.contains === true) { state.output = input; return state; } state.output = utils$i.wrapOutput(output, state, options2); return state; } while (!eos()) { value2 = advance(); if (value2 === "\0") { continue; } if (value2 === "\\") { const next = peek(); if (next === "/" && opts.bash !== true) { continue; } if (next === "." || next === ";") { continue; } if (!next) { value2 += "\\"; push2({ type: "text", value: value2 }); continue; } const match2 = /^\\+/.exec(remaining()); let slashes = 0; if (match2 && match2[0].length > 2) { slashes = match2[0].length; state.index += slashes; if (slashes % 2 !== 0) { value2 += "\\"; } } if (opts.unescape === true) { value2 = advance(); } else { value2 += advance(); } if (state.brackets === 0) { push2({ type: "text", value: value2 }); continue; } } if (state.brackets > 0 && (value2 !== "]" || prev.value === "[" || prev.value === "[^")) { if (opts.posix !== false && value2 === ":") { const inner = prev.value.slice(1); if (inner.includes("[")) { prev.posix = true; if (inner.includes(":")) { const idx = prev.value.lastIndexOf("["); const pre = prev.value.slice(0, idx); const rest2 = prev.value.slice(idx + 2); const posix2 = POSIX_REGEX_SOURCE[rest2]; if (posix2) { prev.value = pre + posix2; state.backtrack = true; advance(); if (!bos.output && tokens.indexOf(prev) === 1) { bos.output = ONE_CHAR2; } continue; } } } } if (value2 === "[" && peek() !== ":" || value2 === "-" && peek() === "]") { value2 = `\\${value2}`; } if (value2 === "]" && (prev.value === "[" || prev.value === "[^")) { value2 = `\\${value2}`; } if (opts.posix === true && value2 === "!" && prev.value === "[") { value2 = "^"; } prev.value += value2; append2({ value: value2 }); continue; } if (state.quotes === 1 && value2 !== '"') { value2 = utils$i.escapeRegex(value2); prev.value += value2; append2({ value: value2 }); continue; } if (value2 === '"') { state.quotes = state.quotes === 1 ? 0 : 1; if (opts.keepQuotes === true) { push2({ type: "text", value: value2 }); } continue; } if (value2 === "(") { increment("parens"); push2({ type: "paren", value: value2 }); continue; } if (value2 === ")") { if (state.parens === 0 && opts.strictBrackets === true) { throw new SyntaxError(syntaxError("opening", "(")); } const extglob = extglobs[extglobs.length - 1]; if (extglob && state.parens === extglob.parens + 1) { extglobClose(extglobs.pop()); continue; } push2({ type: "paren", value: value2, output: state.parens ? ")" : "\\)" }); decrement("parens"); continue; } if (value2 === "[") { if (opts.nobracket === true || !remaining().includes("]")) { if (opts.nobracket !== true && opts.strictBrackets === true) { throw new SyntaxError(syntaxError("closing", "]")); } value2 = `\\${value2}`; } else { increment("brackets"); } push2({ type: "bracket", value: value2 }); continue; } if (value2 === "]") { if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) { push2({ type: "text", value: value2, output: `\\${value2}` }); continue; } if (state.brackets === 0) { if (opts.strictBrackets === true) { throw new SyntaxError(syntaxError("opening", "[")); } push2({ type: "text", value: value2, output: `\\${value2}` }); continue; } decrement("brackets"); const prevValue = prev.value.slice(1); if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) { value2 = `/${value2}`; } prev.value += value2; append2({ value: value2 }); if (opts.literalBrackets === false || utils$i.hasRegexChars(prevValue)) { continue; } const escaped2 = utils$i.escapeRegex(prev.value); state.output = state.output.slice(0, -prev.value.length); if (opts.literalBrackets === true) { state.output += escaped2; prev.value = escaped2; continue; } prev.value = `(${capture}${escaped2}|${prev.value})`; state.output += prev.value; continue; } if (value2 === "{" && opts.nobrace !== true) { increment("braces"); const open2 = { type: "brace", value: value2, output: "(", outputIndex: state.output.length, tokensIndex: state.tokens.length }; braces2.push(open2); push2(open2); continue; } if (value2 === "}") { const brace = braces2[braces2.length - 1]; if (opts.nobrace === true || !brace) { push2({ type: "text", value: value2, output: value2 }); continue; } let output = ")"; if (brace.dots === true) { const arr = tokens.slice(); const range2 = []; for (let i = arr.length - 1; i >= 0; i--) { tokens.pop(); if (arr[i].type === "brace") { break; } if (arr[i].type !== "dots") { range2.unshift(arr[i].value); } } output = expandRange(range2, opts); state.backtrack = true; } if (brace.comma !== true && brace.dots !== true) { const out2 = state.output.slice(0, brace.outputIndex); const toks = state.tokens.slice(brace.tokensIndex); brace.value = brace.output = "\\{"; value2 = output = "\\}"; state.output = out2; for (const t2 of toks) { state.output += t2.output || t2.value; } } push2({ type: "brace", value: value2, output }); decrement("braces"); braces2.pop(); continue; } if (value2 === "|") { if (extglobs.length > 0) { extglobs[extglobs.length - 1].conditions++; } push2({ type: "text", value: value2 }); continue; } if (value2 === ",") { let output = value2; const brace = braces2[braces2.length - 1]; if (brace && stack[stack.length - 1] === "braces") { brace.comma = true; output = "|"; } push2({ type: "comma", value: value2, output }); continue; } if (value2 === "/") { if (prev.type === "dot" && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ""; state.output = ""; tokens.pop(); prev = bos; continue; } push2({ type: "slash", value: value2, output: SLASH_LITERAL2 }); continue; } if (value2 === ".") { if (state.braces > 0 && prev.type === "dot") { if (prev.value === ".") prev.output = DOT_LITERAL2; const brace = braces2[braces2.length - 1]; prev.type = "dots"; prev.output += value2; prev.value += value2; brace.dots = true; continue; } if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") { push2({ type: "text", value: value2, output: DOT_LITERAL2 }); continue; } push2({ type: "dot", value: value2, output: DOT_LITERAL2 }); continue; } if (value2 === "?") { const isGroup = prev && prev.value === "("; if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { extglobOpen("qmark", value2); continue; } if (prev && prev.type === "paren") { const next = peek(); let output = value2; if (next === "<" && !utils$i.supportsLookbehinds()) { throw new Error("Node.js v10 or higher is required for regex lookbehinds"); } if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) { output = `\\${value2}`; } push2({ type: "text", value: value2, output }); continue; } if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) { push2({ type: "qmark", value: value2, output: QMARK_NO_DOT2 }); continue; } push2({ type: "qmark", value: value2, output: QMARK2 }); continue; } if (value2 === "!") { if (opts.noextglob !== true && peek() === "(") { if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) { extglobOpen("negate", value2); continue; } } if (opts.nonegate !== true && state.index === 0) { negate(); continue; } } if (value2 === "+") { if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { extglobOpen("plus", value2); continue; } if (prev && prev.value === "(" || opts.regex === false) { push2({ type: "plus", value: value2, output: PLUS_LITERAL2 }); continue; } if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) { push2({ type: "plus", value: value2 }); continue; } push2({ type: "plus", value: PLUS_LITERAL2 }); continue; } if (value2 === "@") { if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") { push2({ type: "at", extglob: true, value: value2, output: "" }); continue; } push2({ type: "text", value: value2 }); continue; } if (value2 !== "*") { if (value2 === "$" || value2 === "^") { value2 = `\\${value2}`; } const match2 = REGEX_NON_SPECIAL_CHARS.exec(remaining()); if (match2) { value2 += match2[0]; state.index += match2[0].length; } push2({ type: "text", value: value2 }); continue; } if (prev && (prev.type === "globstar" || prev.star === true)) { prev.type = "star"; prev.star = true; prev.value += value2; prev.output = star2; state.backtrack = true; state.globstar = true; consume(value2); continue; } let rest = remaining(); if (opts.noextglob !== true && /^\([^?]/.test(rest)) { extglobOpen("star", value2); continue; } if (prev.type === "star") { if (opts.noglobstar === true) { consume(value2); continue; } const prior = prev.prev; const before = prior.prev; const isStart = prior.type === "slash" || prior.type === "bos"; const afterStar = before && (before.type === "star" || before.type === "globstar"); if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) { push2({ type: "star", value: value2, output: "" }); continue; } const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"); const isExtglob3 = extglobs.length && (prior.type === "pipe" || prior.type === "paren"); if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob3) { push2({ type: "star", value: value2, output: "" }); continue; } while (rest.slice(0, 3) === "/**") { const after = input[state.index + 4]; if (after && after !== "/") { break; } rest = rest.slice(3); consume("/**", 3); } if (prior.type === "bos" && eos()) { prev.type = "globstar"; prev.value += value2; prev.output = globstar(opts); state.output = prev.output; state.globstar = true; consume(value2); continue; } if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) { state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = "globstar"; prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"); prev.value += value2; state.globstar = true; state.output += prior.output + prev.output; consume(value2); continue; } if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") { const end = rest[1] !== void 0 ? "|$" : ""; state.output = state.output.slice(0, -(prior.output + prev.output).length); prior.output = `(?:${prior.output}`; prev.type = "globstar"; prev.output = `${globstar(opts)}${SLASH_LITERAL2}|${SLASH_LITERAL2}${end})`; prev.value += value2; state.output += prior.output + prev.output; state.globstar = true; consume(value2 + advance()); push2({ type: "slash", value: "/", output: "" }); continue; } if (prior.type === "bos" && rest[0] === "/") { prev.type = "globstar"; prev.value += value2; prev.output = `(?:^|${SLASH_LITERAL2}|${globstar(opts)}${SLASH_LITERAL2})`; state.output = prev.output; state.globstar = true; consume(value2 + advance()); push2({ type: "slash", value: "/", output: "" }); continue; } state.output = state.output.slice(0, -prev.output.length); prev.type = "globstar"; prev.output = globstar(opts); prev.value += value2; state.output += prev.output; state.globstar = true; consume(value2); continue; } const token = { type: "star", value: value2, output: star2 }; if (opts.bash === true) { token.output = ".*?"; if (prev.type === "bos" || prev.type === "slash") { token.output = nodot + token.output; } push2(token); continue; } if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) { token.output = value2; push2(token); continue; } if (state.index === state.start || prev.type === "slash" || prev.type === "dot") { if (prev.type === "dot") { state.output += NO_DOT_SLASH2; prev.output += NO_DOT_SLASH2; } else if (opts.dot === true) { state.output += NO_DOTS_SLASH2; prev.output += NO_DOTS_SLASH2; } else { state.output += nodot; prev.output += nodot; } if (peek() !== "*") { state.output += ONE_CHAR2; prev.output += ONE_CHAR2; } } push2(token); } while (state.brackets > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]")); state.output = utils$i.escapeLast(state.output, "["); decrement("brackets"); } while (state.parens > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")")); state.output = utils$i.escapeLast(state.output, "("); decrement("parens"); } while (state.braces > 0) { if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}")); state.output = utils$i.escapeLast(state.output, "{"); decrement("braces"); } if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) { push2({ type: "maybe_slash", value: "", output: `${SLASH_LITERAL2}?` }); } if (state.backtrack === true) { state.output = ""; for (const token of state.tokens) { state.output += token.output != null ? token.output : token.value; if (token.suffix) { state.output += token.suffix; } } } return state; }; parse$g.fastpaths = (input, options2) => { const opts = { ...options2 }; const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; const len = input.length; if (len > max) { throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); } input = REPLACEMENTS[input] || input; const win322 = utils$i.isWindows(options2); const { DOT_LITERAL: DOT_LITERAL2, SLASH_LITERAL: SLASH_LITERAL2, ONE_CHAR: ONE_CHAR2, DOTS_SLASH: DOTS_SLASH2, NO_DOT: NO_DOT2, NO_DOTS: NO_DOTS2, NO_DOTS_SLASH: NO_DOTS_SLASH2, STAR: STAR2, START_ANCHOR: START_ANCHOR2 } = constants$5.globChars(win322); const nodot = opts.dot ? NO_DOTS2 : NO_DOT2; const slashDot = opts.dot ? NO_DOTS_SLASH2 : NO_DOT2; const capture = opts.capture ? "" : "?:"; const state = { negated: false, prefix: "" }; let star2 = opts.bash === true ? ".*?" : STAR2; if (opts.capture) { star2 = `(${star2})`; } const globstar = (opts2) => { if (opts2.noglobstar === true) return star2; return `(${capture}(?:(?!${START_ANCHOR2}${opts2.dot ? DOTS_SLASH2 : DOT_LITERAL2}).)*?)`; }; const create = (str) => { switch (str) { case "*": return `${nodot}${ONE_CHAR2}${star2}`; case ".*": return `${DOT_LITERAL2}${ONE_CHAR2}${star2}`; case "*.*": return `${nodot}${star2}${DOT_LITERAL2}${ONE_CHAR2}${star2}`; case "*/*": return `${nodot}${star2}${SLASH_LITERAL2}${ONE_CHAR2}${slashDot}${star2}`; case "**": return nodot + globstar(opts); case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${slashDot}${ONE_CHAR2}${star2}`; case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${slashDot}${star2}${DOT_LITERAL2}${ONE_CHAR2}${star2}`; case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL2})?${DOT_LITERAL2}${ONE_CHAR2}${star2}`; default: { const match2 = /^(.*?)\.(\w+)$/.exec(str); if (!match2) return; const source2 = create(match2[1]); if (!source2) return; return source2 + DOT_LITERAL2 + match2[2]; } } }; const output = utils$i.removePrefix(input, state); let source = create(output); if (source && opts.strictSlashes !== true) { source += `${SLASH_LITERAL2}?`; } return source; }; var parse_1$3 = parse$g; var path$l = import_path.default; var scan$1 = scan_1; var parse$f = parse_1$3; var utils$h = utils$k; var constants$4 = constants$6; var isObject$3 = (val) => val && typeof val === "object" && !Array.isArray(val); var picomatch$5 = (glob2, options2, returnState = false) => { if (Array.isArray(glob2)) { const fns = glob2.map((input) => picomatch$5(input, options2, returnState)); const arrayMatcher = (str) => { for (const isMatch2 of fns) { const state2 = isMatch2(str); if (state2) return state2; } return false; }; return arrayMatcher; } const isState = isObject$3(glob2) && glob2.tokens && glob2.input; if (glob2 === "" || typeof glob2 !== "string" && !isState) { throw new TypeError("Expected pattern to be a non-empty string"); } const opts = options2 || {}; const posix2 = utils$h.isWindows(options2); const regex2 = isState ? picomatch$5.compileRe(glob2, options2) : picomatch$5.makeRe(glob2, options2, false, true); const state = regex2.state; delete regex2.state; let isIgnored = () => false; if (opts.ignore) { const ignoreOpts = { ...options2, ignore: null, onMatch: null, onResult: null }; isIgnored = picomatch$5(opts.ignore, ignoreOpts, returnState); } const matcher2 = (input, returnObject = false) => { const { isMatch: isMatch2, match: match2, output } = picomatch$5.test(input, regex2, options2, { glob: glob2, posix: posix2 }); const result = { glob: glob2, state, regex: regex2, posix: posix2, input, output, match: match2, isMatch: isMatch2 }; if (typeof opts.onResult === "function") { opts.onResult(result); } if (isMatch2 === false) { result.isMatch = false; return returnObject ? result : false; } if (isIgnored(input)) { if (typeof opts.onIgnore === "function") { opts.onIgnore(result); } result.isMatch = false; return returnObject ? result : false; } if (typeof opts.onMatch === "function") { opts.onMatch(result); } return returnObject ? result : true; }; if (returnState) { matcher2.state = state; } return matcher2; }; picomatch$5.test = (input, regex2, options2, { glob: glob2, posix: posix2 } = {}) => { if (typeof input !== "string") { throw new TypeError("Expected input to be a string"); } if (input === "") { return { isMatch: false, output: "" }; } const opts = options2 || {}; const format2 = opts.format || (posix2 ? utils$h.toPosixSlashes : null); let match2 = input === glob2; let output = match2 && format2 ? format2(input) : input; if (match2 === false) { output = format2 ? format2(input) : input; match2 = output === glob2; } if (match2 === false || opts.capture === true) { if (opts.matchBase === true || opts.basename === true) { match2 = picomatch$5.matchBase(input, regex2, options2, posix2); } else { match2 = regex2.exec(output); } } return { isMatch: Boolean(match2), match: match2, output }; }; picomatch$5.matchBase = (input, glob2, options2, posix2 = utils$h.isWindows(options2)) => { const regex2 = glob2 instanceof RegExp ? glob2 : picomatch$5.makeRe(glob2, options2); return regex2.test(path$l.basename(input)); }; picomatch$5.isMatch = (str, patterns, options2) => picomatch$5(patterns, options2)(str); picomatch$5.parse = (pattern2, options2) => { if (Array.isArray(pattern2)) return pattern2.map((p) => picomatch$5.parse(p, options2)); return parse$f(pattern2, { ...options2, fastpaths: false }); }; picomatch$5.scan = (input, options2) => scan$1(input, options2); picomatch$5.compileRe = (state, options2, returnOutput = false, returnState = false) => { if (returnOutput === true) { return state.output; } const opts = options2 || {}; const prepend = opts.contains ? "" : "^"; const append2 = opts.contains ? "" : "$"; let source = `${prepend}(?:${state.output})${append2}`; if (state && state.negated === true) { source = `^(?!${source}).*$`; } const regex2 = picomatch$5.toRegex(source, options2); if (returnState === true) { regex2.state = state; } return regex2; }; picomatch$5.makeRe = (input, options2 = {}, returnOutput = false, returnState = false) => { if (!input || typeof input !== "string") { throw new TypeError("Expected a non-empty string"); } let parsed = { negated: false, fastpaths: true }; if (options2.fastpaths !== false && (input[0] === "." || input[0] === "*")) { parsed.output = parse$f.fastpaths(input, options2); } if (!parsed.output) { parsed = parse$f(input, options2); } return picomatch$5.compileRe(parsed, options2, returnOutput, returnState); }; picomatch$5.toRegex = (source, options2) => { try { const opts = options2 || {}; return new RegExp(source, opts.flags || (opts.nocase ? "i" : "")); } catch (err2) { if (options2 && options2.debug === true) throw err2; return /$^/; } }; picomatch$5.constants = constants$4; var picomatch_1 = picomatch$5; var picomatch$3 = picomatch_1; var picomatch$4 = getDefaultExportFromCjs(picomatch$3); var extractors = { ArrayPattern(names, param) { for (const element of param.elements) { if (element) extractors[element.type](names, element); } }, AssignmentPattern(names, param) { extractors[param.left.type](names, param.left); }, Identifier(names, param) { names.push(param.name); }, MemberExpression() { }, ObjectPattern(names, param) { for (const prop of param.properties) { if (prop.type === "RestElement") { extractors.RestElement(names, prop); } else { extractors[prop.value.type](names, prop.value); } } }, RestElement(names, param) { extractors[param.argument.type](names, param.argument); } }; var extractAssignedNames = function extractAssignedNames2(param) { const names = []; extractors[param.type](names, param); return names; }; var blockDeclarations = { const: true, let: true }; var Scope = class { constructor(options2 = {}) { this.parent = options2.parent; this.isBlockScope = !!options2.block; this.declarations = /* @__PURE__ */ Object.create(null); if (options2.params) { options2.params.forEach((param) => { extractAssignedNames(param).forEach((name2) => { this.declarations[name2] = true; }); }); } } addDeclaration(node2, isBlockDeclaration, isVar) { if (!isBlockDeclaration && this.isBlockScope) { this.parent.addDeclaration(node2, isBlockDeclaration, isVar); } else if (node2.id) { extractAssignedNames(node2.id).forEach((name2) => { this.declarations[name2] = true; }); } } contains(name2) { return this.declarations[name2] || (this.parent ? this.parent.contains(name2) : false); } }; var attachScopes = function attachScopes2(ast, propertyName = "scope") { let scope = new Scope(); walk$3(ast, { enter(n2, parent) { const node2 = n2; if (/(Function|Class)Declaration/.test(node2.type)) { scope.addDeclaration(node2, false, false); } if (node2.type === "VariableDeclaration") { const { kind } = node2; const isBlockDeclaration = blockDeclarations[kind]; node2.declarations.forEach((declaration) => { scope.addDeclaration(declaration, isBlockDeclaration, true); }); } let newScope; if (/Function/.test(node2.type)) { const func = node2; newScope = new Scope({ parent: scope, block: false, params: func.params }); if (func.type === "FunctionExpression" && func.id) { newScope.addDeclaration(func, false, false); } } if (/For(In|Of)?Statement/.test(node2.type)) { newScope = new Scope({ parent: scope, block: true }); } if (node2.type === "BlockStatement" && !/Function/.test(parent.type)) { newScope = new Scope({ parent: scope, block: true }); } if (node2.type === "CatchClause") { newScope = new Scope({ parent: scope, params: node2.param ? [node2.param] : [], block: true }); } if (newScope) { Object.defineProperty(node2, propertyName, { value: newScope, configurable: true }); scope = newScope; } }, leave(n2) { const node2 = n2; if (node2[propertyName]) scope = scope.parent; } }); return scope; }; function isArray(arg) { return Array.isArray(arg); } function ensureArray(thing) { if (isArray(thing)) return thing; if (thing == null) return []; return [thing]; } var normalizePath$5 = function normalizePath(filename) { return filename.split(import_path.win32.sep).join(import_path.posix.sep); }; function getMatcherString(id, resolutionBase) { if (resolutionBase === false || (0, import_path.isAbsolute)(id) || id.startsWith("**")) { return normalizePath$5(id); } const basePath = normalizePath$5((0, import_path.resolve)(resolutionBase || "")).replace(/[-^$*+?.()|[\]{}]/g, "\\$&"); return import_path.posix.join(basePath, normalizePath$5(id)); } var createFilter$1 = function createFilter(include, exclude, options2) { const resolutionBase = options2 && options2.resolve; const getMatcher = (id) => id instanceof RegExp ? id : { test: (what) => { const pattern2 = getMatcherString(id, resolutionBase); const fn = picomatch$4(pattern2, { dot: true }); const result = fn(what); return result; } }; const includeMatchers = ensureArray(include).map(getMatcher); const excludeMatchers = ensureArray(exclude).map(getMatcher); return function result(id) { if (typeof id !== "string") return false; if (/\0/.test(id)) return false; const pathId = normalizePath$5(id); for (let i = 0; i < excludeMatchers.length; ++i) { const matcher2 = excludeMatchers[i]; if (matcher2.test(pathId)) return false; } for (let i = 0; i < includeMatchers.length; ++i) { const matcher2 = includeMatchers[i]; if (matcher2.test(pathId)) return true; } return !includeMatchers.length; }; }; var reservedWords = "break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public"; var builtins = "arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl"; var forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(" ")); forbiddenIdentifiers.add(""); var makeLegalIdentifier = function makeLegalIdentifier2(str) { let identifier = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, "_"); if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) { identifier = `_${identifier}`; } return identifier || "_"; }; function stringify$8(obj) { return (JSON.stringify(obj) || "undefined").replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`); } function serializeArray(arr, indent, baseIndent) { let output = "["; const separator = indent ? ` ${baseIndent}${indent}` : ""; for (let i = 0; i < arr.length; i++) { const key = arr[i]; output += `${i > 0 ? "," : ""}${separator}${serialize(key, indent, baseIndent + indent)}`; } return `${output}${indent ? ` ${baseIndent}` : ""}]`; } function serializeObject(obj, indent, baseIndent) { let output = "{"; const separator = indent ? ` ${baseIndent}${indent}` : ""; const entries = Object.entries(obj); for (let i = 0; i < entries.length; i++) { const [key, value2] = entries[i]; const stringKey = makeLegalIdentifier(key) === key ? key : stringify$8(key); output += `${i > 0 ? "," : ""}${separator}${stringKey}:${indent ? " " : ""}${serialize(value2, indent, baseIndent + indent)}`; } return `${output}${indent ? ` ${baseIndent}` : ""}}`; } function serialize(obj, indent, baseIndent) { if (typeof obj === "object" && obj !== null) { if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent); if (obj instanceof Date) return `new Date(${obj.getTime()})`; if (obj instanceof RegExp) return obj.toString(); return serializeObject(obj, indent, baseIndent); } if (typeof obj === "number") { if (obj === Infinity) return "Infinity"; if (obj === -Infinity) return "-Infinity"; if (obj === 0) return 1 / obj === Infinity ? "0" : "-0"; if (obj !== obj) return "NaN"; } if (typeof obj === "symbol") { const key = Symbol.keyFor(obj); if (key !== void 0) return `Symbol.for(${stringify$8(key)})`; } if (typeof obj === "bigint") return `${obj}n`; return stringify$8(obj); } var hasStringIsWellFormed = "isWellFormed" in String.prototype; function isWellFormedString(input) { if (hasStringIsWellFormed) return input.isWellFormed(); return !new RegExp("\\p{Surrogate}", "u").test(input); } var dataToEsm = function dataToEsm2(data, options2 = {}) { var _a4, _b3; const t2 = options2.compact ? "" : "indent" in options2 ? options2.indent : " "; const _ = options2.compact ? "" : " "; const n2 = options2.compact ? "" : "\n"; const declarationType = options2.preferConst ? "const" : "var"; if (options2.namedExports === false || typeof data !== "object" || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) { const code = serialize(data, options2.compact ? null : t2, ""); const magic = _ || (/^[{[\-\/]/.test(code) ? "" : " "); return `export default${magic}${code};`; } let maxUnderbarPrefixLength = 0; for (const key of Object.keys(data)) { const underbarPrefixLength = (_b3 = (_a4 = key.match(/^(_+)/)) === null || _a4 === void 0 ? void 0 : _a4[0].length) !== null && _b3 !== void 0 ? _b3 : 0; if (underbarPrefixLength > maxUnderbarPrefixLength) { maxUnderbarPrefixLength = underbarPrefixLength; } } const arbitraryNamePrefix = `${"_".repeat(maxUnderbarPrefixLength + 1)}arbitrary`; let namedExportCode = ""; const defaultExportRows = []; const arbitraryNameExportRows = []; for (const [key, value2] of Object.entries(data)) { if (key === makeLegalIdentifier(key)) { if (options2.objectShorthand) defaultExportRows.push(key); else defaultExportRows.push(`${key}:${_}${key}`); namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value2, options2.compact ? null : t2, "")};${n2}`; } else { defaultExportRows.push(`${stringify$8(key)}:${_}${serialize(value2, options2.compact ? null : t2, "")}`); if (options2.includeArbitraryNames && isWellFormedString(key)) { const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`; namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value2, options2.compact ? null : t2, "")};${n2}`; arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`); } } } const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n2}${t2}${arbitraryNameExportRows.join(`,${n2}${t2}`)}${n2}};${n2}` : ""; const defaultExportCode = `export default${_}{${n2}${t2}${defaultExportRows.join(`,${n2}${t2}`)}${n2}};${n2}`; return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`; }; var path$k = import_path.default; var commondir = function(basedir, relfiles) { if (relfiles) { var files = relfiles.map(function(r2) { return path$k.resolve(basedir, r2); }); } else { var files = basedir; } var res = files.slice(1).reduce(function(ps, file) { if (!file.match(/^([A-Za-z]:)?\/|\\/)) { throw new Error("relative path without a basedir"); } var xs = file.split(/\/+|\\+/); for (var i = 0; ps[i] === xs[i] && i < Math.min(ps.length, xs.length); i++) ; return ps.slice(0, i); }, files[0].split(/\/+|\\+/)); return res.length > 1 ? res.join("/") : "/"; }; var getCommonDir = getDefaultExportFromCjs(commondir); var balancedMatch = balanced$1; function balanced$1(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r2 = range$1(a, b, str); return r2 && { start: r2[0], end: r2[1], pre: str.slice(0, r2[0]), body: str.slice(r2[0] + a.length, r2[1]), post: str.slice(r2[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced$1.range = range$1; function range$1(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { if (a === b) { return [ai, bi]; } begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [begs.pop(), bi]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [left, right]; } } return result; } var balanced = balancedMatch; var braceExpansion = expandTop; var escSlash = "\0SLASH" + Math.random() + "\0"; var escOpen = "\0OPEN" + Math.random() + "\0"; var escClose = "\0CLOSE" + Math.random() + "\0"; var escComma = "\0COMMA" + Math.random() + "\0"; var escPeriod = "\0PERIOD" + Math.random() + "\0"; function numeric(str) { return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); } function escapeBraces(str) { return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod); } function unescapeBraces(str) { return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join("."); } function parseCommaParts(str) { if (!str) return [""]; var parts = []; var m = balanced("{", "}", str); if (!m) return str.split(","); var pre = m.pre; var body = m.body; var post = m.post; var p = pre.split(","); p[p.length - 1] += "{" + body + "}"; var postParts = parseCommaParts(post); if (post.length) { p[p.length - 1] += postParts.shift(); p.push.apply(p, postParts); } parts.push.apply(parts, p); return parts; } function expandTop(str) { if (!str) return []; if (str.substr(0, 2) === "{}") { str = "\\{\\}" + str.substr(2); } return expand$3(escapeBraces(str), true).map(unescapeBraces); } function embrace(str) { return "{" + str + "}"; } function isPadded(el) { return /^-?0\d/.test(el); } function lte(i, y) { return i <= y; } function gte(i, y) { return i >= y; } function expand$3(str, isTop) { var expansions = []; var m = balanced("{", "}", str); if (!m) return [str]; var pre = m.pre; var post = m.post.length ? expand$3(m.post, false) : [""]; if (/\$$/.test(m.pre)) { for (var k = 0; k < post.length; k++) { var expansion = pre + "{" + m.body + "}" + post[k]; expansions.push(expansion); } } else { var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); var isSequence = isNumericSequence || isAlphaSequence; var isOptions = m.body.indexOf(",") >= 0; if (!isSequence && !isOptions) { if (m.post.match(/,.*\}/)) { str = m.pre + "{" + m.body + escClose + m.post; return expand$3(str); } return [str]; } var n2; if (isSequence) { n2 = m.body.split(/\.\./); } else { n2 = parseCommaParts(m.body); if (n2.length === 1) { n2 = expand$3(n2[0], false).map(embrace); if (n2.length === 1) { return post.map(function(p) { return m.pre + n2[0] + p; }); } } } var N; if (isSequence) { var x = numeric(n2[0]); var y = numeric(n2[1]); var width = Math.max(n2[0].length, n2[1].length); var incr = n2.length == 3 ? Math.abs(numeric(n2[2])) : 1; var test = lte; var reverse = y < x; if (reverse) { incr *= -1; test = gte; } var pad2 = n2.some(isPadded); N = []; for (var i = x; test(i, y); i += incr) { var c; if (isAlphaSequence) { c = String.fromCharCode(i); if (c === "\\") c = ""; } else { c = String(i); if (pad2) { var need = width - c.length; if (need > 0) { var z = new Array(need + 1).join("0"); if (i < 0) c = "-" + z + c.slice(1); else c = z + c; } } } N.push(c); } } else { N = []; for (var j = 0; j < n2.length; j++) { N.push.apply(N, expand$3(n2[j], false)); } } for (var j = 0; j < N.length; j++) { for (var k = 0; k < post.length; k++) { var expansion = pre + N[j] + post[k]; if (!isTop || isSequence || expansion) expansions.push(expansion); } } } return expansions; } var expand$4 = getDefaultExportFromCjs(braceExpansion); var MAX_PATTERN_LENGTH = 1024 * 64; var assertValidPattern = (pattern2) => { if (typeof pattern2 !== "string") { throw new TypeError("invalid pattern"); } if (pattern2.length > MAX_PATTERN_LENGTH) { throw new TypeError("pattern is too long"); } }; var posixClasses = { "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true], "[:alpha:]": ["\\p{L}\\p{Nl}", true], "[:ascii:]": ["\\x00-\\x7f", false], "[:blank:]": ["\\p{Zs}\\t", true], "[:cntrl:]": ["\\p{Cc}", true], "[:digit:]": ["\\p{Nd}", true], "[:graph:]": ["\\p{Z}\\p{C}", true, true], "[:lower:]": ["\\p{Ll}", true], "[:print:]": ["\\p{C}", true], "[:punct:]": ["\\p{P}", true], "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true], "[:upper:]": ["\\p{Lu}", true], "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true], "[:xdigit:]": ["A-Fa-f0-9", false] }; var braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&"); var regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); var rangesToString = (ranges) => ranges.join(""); var parseClass = (glob2, position) => { const pos = position; if (glob2.charAt(pos) !== "[") { throw new Error("not in a brace expression"); } const ranges = []; const negs = []; let i = pos + 1; let sawStart = false; let uflag = false; let escaping = false; let negate = false; let endPos = pos; let rangeStart = ""; WHILE: while (i < glob2.length) { const c = glob2.charAt(i); if ((c === "!" || c === "^") && i === pos + 1) { negate = true; i++; continue; } if (c === "]" && sawStart && !escaping) { endPos = i + 1; break; } sawStart = true; if (c === "\\") { if (!escaping) { escaping = true; i++; continue; } } if (c === "[" && !escaping) { for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) { if (glob2.startsWith(cls, i)) { if (rangeStart) { return ["$.", false, glob2.length - pos, true]; } i += cls.length; if (neg) negs.push(unip); else ranges.push(unip); uflag = uflag || u; continue WHILE; } } } escaping = false; if (rangeStart) { if (c > rangeStart) { ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c)); } else if (c === rangeStart) { ranges.push(braceEscape(c)); } rangeStart = ""; i++; continue; } if (glob2.startsWith("-]", i + 1)) { ranges.push(braceEscape(c + "-")); i += 2; continue; } if (glob2.startsWith("-", i + 1)) { rangeStart = c; i += 2; continue; } ranges.push(braceEscape(c)); i++; } if (endPos < i) { return ["", false, 0, false]; } if (!ranges.length && !negs.length) { return ["$.", false, glob2.length - pos, true]; } if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) { const r2 = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]; return [regexpEscape(r2), false, endPos - pos, false]; } const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]"; const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]"; const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs; return [comb, uflag, endPos - pos, true]; }; var unescape$1 = (s, { windowsPathsNoEscape = false } = {}) => { return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1"); }; var types$1 = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]); var isExtglobType = (c) => types$1.has(c); var startNoTraversal = "(?!(?:^|/)\\.\\.?(?:$|/))"; var startNoDot = "(?!\\.)"; var addPatternStart = /* @__PURE__ */ new Set(["[", "."]); var justDots = /* @__PURE__ */ new Set(["..", "."]); var reSpecials = new Set("().*{}+?[]^$\\!"); var regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); var qmark$1 = "[^/]"; var star$1 = qmark$1 + "*?"; var starNoEmpty = qmark$1 + "+?"; var _root, _hasMagic, _uflag, _parts, _parent, _parentIndex, _negs, _filledNegs, _options, _toString, _emptyExt, _AST_instances, fillNegs_fn, _AST_static, parseAST_fn, partsToRegExp_fn, parseGlob_fn; var _AST = class _AST { constructor(type, parent, options2 = {}) { __privateAdd(this, _AST_instances); __publicField(this, "type"); __privateAdd(this, _root); __privateAdd(this, _hasMagic); __privateAdd(this, _uflag, false); __privateAdd(this, _parts, []); __privateAdd(this, _parent); __privateAdd(this, _parentIndex); __privateAdd(this, _negs); __privateAdd(this, _filledNegs, false); __privateAdd(this, _options); __privateAdd(this, _toString); // set to true if it's an extglob with no children // (which really means one child of '') __privateAdd(this, _emptyExt, false); this.type = type; if (type) __privateSet(this, _hasMagic, true); __privateSet(this, _parent, parent); __privateSet(this, _root, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _root) : this); __privateSet(this, _options, __privateGet(this, _root) === this ? options2 : __privateGet(__privateGet(this, _root), _options)); __privateSet(this, _negs, __privateGet(this, _root) === this ? [] : __privateGet(__privateGet(this, _root), _negs)); if (type === "!" && !__privateGet(__privateGet(this, _root), _filledNegs)) __privateGet(this, _negs).push(this); __privateSet(this, _parentIndex, __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0); } get hasMagic() { if (__privateGet(this, _hasMagic) !== void 0) return __privateGet(this, _hasMagic); for (const p of __privateGet(this, _parts)) { if (typeof p === "string") continue; if (p.type || p.hasMagic) return __privateSet(this, _hasMagic, true); } return __privateGet(this, _hasMagic); } // reconstructs the pattern toString() { if (__privateGet(this, _toString) !== void 0) return __privateGet(this, _toString); if (!this.type) { return __privateSet(this, _toString, __privateGet(this, _parts).map((p) => String(p)).join("")); } else { return __privateSet(this, _toString, this.type + "(" + __privateGet(this, _parts).map((p) => String(p)).join("|") + ")"); } } push(...parts) { for (const p of parts) { if (p === "") continue; if (typeof p !== "string" && !(p instanceof _AST && __privateGet(p, _parent) === this)) { throw new Error("invalid part: " + p); } __privateGet(this, _parts).push(p); } } toJSON() { var _a4; const ret = this.type === null ? __privateGet(this, _parts).slice().map((p) => typeof p === "string" ? p : p.toJSON()) : [this.type, ...__privateGet(this, _parts).map((p) => p.toJSON())]; if (this.isStart() && !this.type) ret.unshift([]); if (this.isEnd() && (this === __privateGet(this, _root) || __privateGet(__privateGet(this, _root), _filledNegs) && ((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.type) === "!")) { ret.push({}); } return ret; } isStart() { var _a4; if (__privateGet(this, _root) === this) return true; if (!((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.isStart())) return false; if (__privateGet(this, _parentIndex) === 0) return true; const p = __privateGet(this, _parent); for (let i = 0; i < __privateGet(this, _parentIndex); i++) { const pp = __privateGet(p, _parts)[i]; if (!(pp instanceof _AST && pp.type === "!")) { return false; } } return true; } isEnd() { var _a4, _b3, _c2; if (__privateGet(this, _root) === this) return true; if (((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.type) === "!") return true; if (!((_b3 = __privateGet(this, _parent)) == null ? void 0 : _b3.isEnd())) return false; if (!this.type) return (_c2 = __privateGet(this, _parent)) == null ? void 0 : _c2.isEnd(); const pl = __privateGet(this, _parent) ? __privateGet(__privateGet(this, _parent), _parts).length : 0; return __privateGet(this, _parentIndex) === pl - 1; } copyIn(part) { if (typeof part === "string") this.push(part); else this.push(part.clone(this)); } clone(parent) { const c = new _AST(this.type, parent); for (const p of __privateGet(this, _parts)) { c.copyIn(p); } return c; } static fromGlob(pattern2, options2 = {}) { var _a4; const ast = new _AST(null, void 0, options2); __privateMethod(_a4 = _AST, _AST_static, parseAST_fn).call(_a4, pattern2, ast, 0, options2); return ast; } // returns the regular expression if there's magic, or the unescaped // string if not. toMMPattern() { if (this !== __privateGet(this, _root)) return __privateGet(this, _root).toMMPattern(); const glob2 = this.toString(); const [re, body, hasMagic2, uflag] = this.toRegExpSource(); const anyMagic = hasMagic2 || __privateGet(this, _hasMagic) || __privateGet(this, _options).nocase && !__privateGet(this, _options).nocaseMagicOnly && glob2.toUpperCase() !== glob2.toLowerCase(); if (!anyMagic) { return body; } const flags = (__privateGet(this, _options).nocase ? "i" : "") + (uflag ? "u" : ""); return Object.assign(new RegExp(`^${re}$`, flags), { _src: re, _glob: glob2 }); } get options() { return __privateGet(this, _options); } // returns the string match, the regexp source, whether there's magic // in the regexp (so a regular expression is required) and whether or // not the uflag is needed for the regular expression (for posix classes) // TODO: instead of injecting the start/end at this point, just return // the BODY of the regexp, along with the start/end portions suitable // for binding the start/end in either a joined full-path makeRe context // (where we bind to (^|/), or a standalone matchPart context (where // we bind to ^, and not /). Otherwise slashes get duped! // // In part-matching mode, the start is: // - if not isStart: nothing // - if traversal possible, but not allowed: ^(?!\.\.?$) // - if dots allowed or not possible: ^ // - if dots possible and not allowed: ^(?!\.) // end is: // - if not isEnd(): nothing // - else: $ // // In full-path matching mode, we put the slash at the START of the // pattern, so start is: // - if first pattern: same as part-matching mode // - if not isStart(): nothing // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/)) // - if dots allowed or not possible: / // - if dots possible and not allowed: /(?!\.) // end is: // - if last pattern, same as part-matching mode // - else nothing // // Always put the (?:$|/) on negated tails, though, because that has to be // there to bind the end of the negated pattern portion, and it's easier to // just stick it in now rather than try to inject it later in the middle of // the pattern. // // We can just always return the same end, and leave it up to the caller // to know whether it's going to be used joined or in parts. // And, if the start is adjusted slightly, can do the same there: // - if not isStart: nothing // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$) // - if dots allowed or not possible: (?:/|^) // - if dots possible and not allowed: (?:/|^)(?!\.) // // But it's better to have a simpler binding without a conditional, for // performance, so probably better to return both start options. // // Then the caller just ignores the end if it's not the first pattern, // and the start always gets applied. // // But that's always going to be $ if it's the ending pattern, or nothing, // so the caller can just attach $ at the end of the pattern when building. // // So the todo is: // - better detect what kind of start is needed // - return both flavors of starting pattern // - attach $ at the end of the pattern when creating the actual RegExp // // Ah, but wait, no, that all only applies to the root when the first pattern // is not an extglob. If the first pattern IS an extglob, then we need all // that dot prevention biz to live in the extglob portions, because eg // +(*|.x*) can match .xy but not .yx. // // So, return the two flavors if it's #root and the first child is not an // AST, otherwise leave it to the child AST to handle it, and there, // use the (?:^|/) style of start binding. // // Even simplified further: // - Since the start for a join is eg /(?!\.) and the start for a part // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root // or start or whatever) and prepend ^ or / at the Regexp construction. toRegExpSource(allowDot) { var _a4; const dot = allowDot ?? !!__privateGet(this, _options).dot; if (__privateGet(this, _root) === this) __privateMethod(this, _AST_instances, fillNegs_fn).call(this); if (!this.type) { const noEmpty = this.isStart() && this.isEnd(); const src2 = __privateGet(this, _parts).map((p) => { var _a5; const [re, _, hasMagic2, uflag] = typeof p === "string" ? __privateMethod(_a5 = _AST, _AST_static, parseGlob_fn).call(_a5, p, __privateGet(this, _hasMagic), noEmpty) : p.toRegExpSource(allowDot); __privateSet(this, _hasMagic, __privateGet(this, _hasMagic) || hasMagic2); __privateSet(this, _uflag, __privateGet(this, _uflag) || uflag); return re; }).join(""); let start2 = ""; if (this.isStart()) { if (typeof __privateGet(this, _parts)[0] === "string") { const dotTravAllowed = __privateGet(this, _parts).length === 1 && justDots.has(__privateGet(this, _parts)[0]); if (!dotTravAllowed) { const aps = addPatternStart; const needNoTrav = ( // dots are allowed, and the pattern starts with [ or . dot && aps.has(src2.charAt(0)) || // the pattern starts with \., and then [ or . src2.startsWith("\\.") && aps.has(src2.charAt(2)) || // the pattern starts with \.\., and then [ or . src2.startsWith("\\.\\.") && aps.has(src2.charAt(4)) ); const needNoDot = !dot && !allowDot && aps.has(src2.charAt(0)); start2 = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ""; } } } let end = ""; if (this.isEnd() && __privateGet(__privateGet(this, _root), _filledNegs) && ((_a4 = __privateGet(this, _parent)) == null ? void 0 : _a4.type) === "!") { end = "(?:$|\\/)"; } const final2 = start2 + src2 + end; return [ final2, unescape$1(src2), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ]; } const repeated = this.type === "*" || this.type === "+"; const start = this.type === "!" ? "(?:(?!(?:" : "(?:"; let body = __privateMethod(this, _AST_instances, partsToRegExp_fn).call(this, dot); if (this.isStart() && this.isEnd() && !body && this.type !== "!") { const s = this.toString(); __privateSet(this, _parts, [s]); this.type = null; __privateSet(this, _hasMagic, void 0); return [s, unescape$1(this.toString()), false, false]; } let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ? "" : __privateMethod(this, _AST_instances, partsToRegExp_fn).call(this, true); if (bodyDotAllowed === body) { bodyDotAllowed = ""; } if (bodyDotAllowed) { body = `(?:${body})(?:${bodyDotAllowed})*?`; } let final = ""; if (this.type === "!" && __privateGet(this, _emptyExt)) { final = (this.isStart() && !dot ? startNoDot : "") + starNoEmpty; } else { const close2 = this.type === "!" ? ( // !() must match something,but !(x) can match '' "))" + (this.isStart() && !dot && !allowDot ? startNoDot : "") + star$1 + ")" ) : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && bodyDotAllowed ? ")" : this.type === "*" && bodyDotAllowed ? `)?` : `)${this.type}`; final = start + body + close2; } return [ final, unescape$1(body), __privateSet(this, _hasMagic, !!__privateGet(this, _hasMagic)), __privateGet(this, _uflag) ]; } }; _root = new WeakMap(); _hasMagic = new WeakMap(); _uflag = new WeakMap(); _parts = new WeakMap(); _parent = new WeakMap(); _parentIndex = new WeakMap(); _negs = new WeakMap(); _filledNegs = new WeakMap(); _options = new WeakMap(); _toString = new WeakMap(); _emptyExt = new WeakMap(); _AST_instances = new WeakSet(); fillNegs_fn = function() { if (this !== __privateGet(this, _root)) throw new Error("should only call on root"); if (__privateGet(this, _filledNegs)) return this; this.toString(); __privateSet(this, _filledNegs, true); let n2; while (n2 = __privateGet(this, _negs).pop()) { if (n2.type !== "!") continue; let p = n2; let pp = __privateGet(p, _parent); while (pp) { for (let i = __privateGet(p, _parentIndex) + 1; !pp.type && i < __privateGet(pp, _parts).length; i++) { for (const part of __privateGet(n2, _parts)) { if (typeof part === "string") { throw new Error("string part in extglob AST??"); } part.copyIn(__privateGet(pp, _parts)[i]); } } p = pp; pp = __privateGet(p, _parent); } } return this; }; _AST_static = new WeakSet(); parseAST_fn = function(str, ast, pos, opt) { var _a4, _b3; let escaping = false; let inBrace = false; let braceStart = -1; let braceNeg = false; if (ast.type === null) { let i2 = pos; let acc2 = ""; while (i2 < str.length) { const c = str.charAt(i2++); if (escaping || c === "\\") { escaping = !escaping; acc2 += c; continue; } if (inBrace) { if (i2 === braceStart + 1) { if (c === "^" || c === "!") { braceNeg = true; } } else if (c === "]" && !(i2 === braceStart + 2 && braceNeg)) { inBrace = false; } acc2 += c; continue; } else if (c === "[") { inBrace = true; braceStart = i2; braceNeg = false; acc2 += c; continue; } if (!opt.noext && isExtglobType(c) && str.charAt(i2) === "(") { ast.push(acc2); acc2 = ""; const ext2 = new _AST(c, ast); i2 = __privateMethod(_a4 = _AST, _AST_static, parseAST_fn).call(_a4, str, ext2, i2, opt); ast.push(ext2); continue; } acc2 += c; } ast.push(acc2); return i2; } let i = pos + 1; let part = new _AST(null, ast); const parts = []; let acc = ""; while (i < str.length) { const c = str.charAt(i++); if (escaping || c === "\\") { escaping = !escaping; acc += c; continue; } if (inBrace) { if (i === braceStart + 1) { if (c === "^" || c === "!") { braceNeg = true; } } else if (c === "]" && !(i === braceStart + 2 && braceNeg)) { inBrace = false; } acc += c; continue; } else if (c === "[") { inBrace = true; braceStart = i; braceNeg = false; acc += c; continue; } if (isExtglobType(c) && str.charAt(i) === "(") { part.push(acc); acc = ""; const ext2 = new _AST(c, part); part.push(ext2); i = __privateMethod(_b3 = _AST, _AST_static, parseAST_fn).call(_b3, str, ext2, i, opt); continue; } if (c === "|") { part.push(acc); acc = ""; parts.push(part); part = new _AST(null, ast); continue; } if (c === ")") { if (acc === "" && __privateGet(ast, _parts).length === 0) { __privateSet(ast, _emptyExt, true); } part.push(acc); acc = ""; ast.push(...parts, part); return i; } acc += c; } ast.type = null; __privateSet(ast, _hasMagic, void 0); __privateSet(ast, _parts, [str.substring(pos - 1)]); return i; }; partsToRegExp_fn = function(dot) { return __privateGet(this, _parts).map((p) => { if (typeof p === "string") { throw new Error("string type in extglob ast??"); } const [re, _, _hasMagic2, uflag] = p.toRegExpSource(dot); __privateSet(this, _uflag, __privateGet(this, _uflag) || uflag); return re; }).filter((p) => !(this.isStart() && this.isEnd()) || !!p).join("|"); }; parseGlob_fn = function(glob2, hasMagic2, noEmpty = false) { let escaping = false; let re = ""; let uflag = false; for (let i = 0; i < glob2.length; i++) { const c = glob2.charAt(i); if (escaping) { escaping = false; re += (reSpecials.has(c) ? "\\" : "") + c; continue; } if (c === "\\") { if (i === glob2.length - 1) { re += "\\\\"; } else { escaping = true; } continue; } if (c === "[") { const [src2, needUflag, consumed, magic] = parseClass(glob2, i); if (consumed) { re += src2; uflag = uflag || needUflag; i += consumed - 1; hasMagic2 = hasMagic2 || magic; continue; } } if (c === "*") { if (noEmpty && glob2 === "*") re += starNoEmpty; else re += star$1; hasMagic2 = true; continue; } if (c === "?") { re += qmark$1; hasMagic2 = true; continue; } re += regExpEscape$1(c); } return [re, unescape$1(glob2), !!hasMagic2, uflag]; }; __privateAdd(_AST, _AST_static); var AST = _AST; var escape$2 = (s, { windowsPathsNoEscape = false } = {}) => { return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&"); }; var minimatch = (p, pattern2, options2 = {}) => { assertValidPattern(pattern2); if (!options2.nocomment && pattern2.charAt(0) === "#") { return false; } return new Minimatch(pattern2, options2).match(p); }; var starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/; var starDotExtTest = (ext2) => (f2) => !f2.startsWith(".") && f2.endsWith(ext2); var starDotExtTestDot = (ext2) => (f2) => f2.endsWith(ext2); var starDotExtTestNocase = (ext2) => { ext2 = ext2.toLowerCase(); return (f2) => !f2.startsWith(".") && f2.toLowerCase().endsWith(ext2); }; var starDotExtTestNocaseDot = (ext2) => { ext2 = ext2.toLowerCase(); return (f2) => f2.toLowerCase().endsWith(ext2); }; var starDotStarRE = /^\*+\.\*+$/; var starDotStarTest = (f2) => !f2.startsWith(".") && f2.includes("."); var starDotStarTestDot = (f2) => f2 !== "." && f2 !== ".." && f2.includes("."); var dotStarRE = /^\.\*+$/; var dotStarTest = (f2) => f2 !== "." && f2 !== ".." && f2.startsWith("."); var starRE = /^\*+$/; var starTest = (f2) => f2.length !== 0 && !f2.startsWith("."); var starTestDot = (f2) => f2.length !== 0 && f2 !== "." && f2 !== ".."; var qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/; var qmarksTestNocase = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExt([$0]); if (!ext2) return noext; ext2 = ext2.toLowerCase(); return (f2) => noext(f2) && f2.toLowerCase().endsWith(ext2); }; var qmarksTestNocaseDot = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExtDot([$0]); if (!ext2) return noext; ext2 = ext2.toLowerCase(); return (f2) => noext(f2) && f2.toLowerCase().endsWith(ext2); }; var qmarksTestDot = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExtDot([$0]); return !ext2 ? noext : (f2) => noext(f2) && f2.endsWith(ext2); }; var qmarksTest = ([$0, ext2 = ""]) => { const noext = qmarksTestNoExt([$0]); return !ext2 ? noext : (f2) => noext(f2) && f2.endsWith(ext2); }; var qmarksTestNoExt = ([$0]) => { const len = $0.length; return (f2) => f2.length === len && !f2.startsWith("."); }; var qmarksTestNoExtDot = ([$0]) => { const len = $0.length; return (f2) => f2.length === len && f2 !== "." && f2 !== ".."; }; var defaultPlatform$2 = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix"; var path$j = { win32: { sep: "\\" }, posix: { sep: "/" } }; var sep = defaultPlatform$2 === "win32" ? path$j.win32.sep : path$j.posix.sep; minimatch.sep = sep; var GLOBSTAR$2 = Symbol("globstar **"); minimatch.GLOBSTAR = GLOBSTAR$2; var qmark = "[^/]"; var star = qmark + "*?"; var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?"; var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?"; var filter$1 = (pattern2, options2 = {}) => (p) => minimatch(p, pattern2, options2); minimatch.filter = filter$1; var ext = (a, b = {}) => Object.assign({}, a, b); var defaults = (def) => { if (!def || typeof def !== "object" || !Object.keys(def).length) { return minimatch; } const orig = minimatch; const m = (p, pattern2, options2 = {}) => orig(p, pattern2, ext(def, options2)); return Object.assign(m, { Minimatch: class Minimatch extends orig.Minimatch { constructor(pattern2, options2 = {}) { super(pattern2, ext(def, options2)); } static defaults(options2) { return orig.defaults(ext(def, options2)).Minimatch; } }, AST: class AST extends orig.AST { /* c8 ignore start */ constructor(type, parent, options2 = {}) { super(type, parent, ext(def, options2)); } /* c8 ignore stop */ static fromGlob(pattern2, options2 = {}) { return orig.AST.fromGlob(pattern2, ext(def, options2)); } }, unescape: (s, options2 = {}) => orig.unescape(s, ext(def, options2)), escape: (s, options2 = {}) => orig.escape(s, ext(def, options2)), filter: (pattern2, options2 = {}) => orig.filter(pattern2, ext(def, options2)), defaults: (options2) => orig.defaults(ext(def, options2)), makeRe: (pattern2, options2 = {}) => orig.makeRe(pattern2, ext(def, options2)), braceExpand: (pattern2, options2 = {}) => orig.braceExpand(pattern2, ext(def, options2)), match: (list, pattern2, options2 = {}) => orig.match(list, pattern2, ext(def, options2)), sep: orig.sep, GLOBSTAR: GLOBSTAR$2 }); }; minimatch.defaults = defaults; var braceExpand = (pattern2, options2 = {}) => { assertValidPattern(pattern2); if (options2.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern2)) { return [pattern2]; } return expand$4(pattern2); }; minimatch.braceExpand = braceExpand; var makeRe$1 = (pattern2, options2 = {}) => new Minimatch(pattern2, options2).makeRe(); minimatch.makeRe = makeRe$1; var match = (list, pattern2, options2 = {}) => { const mm = new Minimatch(pattern2, options2); list = list.filter((f2) => mm.match(f2)); if (mm.options.nonull && !list.length) { list.push(pattern2); } return list; }; minimatch.match = match; var globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/; var regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); var Minimatch = class { constructor(pattern2, options2 = {}) { __publicField(this, "options"); __publicField(this, "set"); __publicField(this, "pattern"); __publicField(this, "windowsPathsNoEscape"); __publicField(this, "nonegate"); __publicField(this, "negate"); __publicField(this, "comment"); __publicField(this, "empty"); __publicField(this, "preserveMultipleSlashes"); __publicField(this, "partial"); __publicField(this, "globSet"); __publicField(this, "globParts"); __publicField(this, "nocase"); __publicField(this, "isWindows"); __publicField(this, "platform"); __publicField(this, "windowsNoMagicRoot"); __publicField(this, "regexp"); assertValidPattern(pattern2); options2 = options2 || {}; this.options = options2; this.pattern = pattern2; this.platform = options2.platform || defaultPlatform$2; this.isWindows = this.platform === "win32"; this.windowsPathsNoEscape = !!options2.windowsPathsNoEscape || options2.allowWindowsEscape === false; if (this.windowsPathsNoEscape) { this.pattern = this.pattern.replace(/\\/g, "/"); } this.preserveMultipleSlashes = !!options2.preserveMultipleSlashes; this.regexp = null; this.negate = false; this.nonegate = !!options2.nonegate; this.comment = false; this.empty = false; this.partial = !!options2.partial; this.nocase = !!this.options.nocase; this.windowsNoMagicRoot = options2.windowsNoMagicRoot !== void 0 ? options2.windowsNoMagicRoot : !!(this.isWindows && this.nocase); this.globSet = []; this.globParts = []; this.set = []; this.make(); } hasMagic() { if (this.options.magicalBraces && this.set.length > 1) { return true; } for (const pattern2 of this.set) { for (const part of pattern2) { if (typeof part !== "string") return true; } } return false; } debug(..._) { } make() { const pattern2 = this.pattern; const options2 = this.options; if (!options2.nocomment && pattern2.charAt(0) === "#") { this.comment = true; return; } if (!pattern2) { this.empty = true; return; } this.parseNegate(); this.globSet = [...new Set(this.braceExpand())]; if (options2.debug) { this.debug = (...args) => console.error(...args); } this.debug(this.pattern, this.globSet); const rawGlobParts = this.globSet.map((s) => this.slashSplit(s)); this.globParts = this.preprocess(rawGlobParts); this.debug(this.pattern, this.globParts); let set2 = this.globParts.map((s, _, __) => { if (this.isWindows && this.windowsNoMagicRoot) { const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]); const isDrive = /^[a-z]:/i.test(s[0]); if (isUNC) { return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))]; } else if (isDrive) { return [s[0], ...s.slice(1).map((ss) => this.parse(ss))]; } } return s.map((ss) => this.parse(ss)); }); this.debug(this.pattern, set2); this.set = set2.filter((s) => s.indexOf(false) === -1); if (this.isWindows) { for (let i = 0; i < this.set.length; i++) { const p = this.set[i]; if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) { p[2] = "?"; } } } this.debug(this.pattern, this.set); } // various transforms to equivalent pattern sets that are // faster to process in a filesystem walk. The goal is to // eliminate what we can, and push all ** patterns as far // to the right as possible, even if it increases the number // of patterns that we have to process. preprocess(globParts) { if (this.options.noglobstar) { for (let i = 0; i < globParts.length; i++) { for (let j = 0; j < globParts[i].length; j++) { if (globParts[i][j] === "**") { globParts[i][j] = "*"; } } } } const { optimizationLevel = 1 } = this.options; if (optimizationLevel >= 2) { globParts = this.firstPhasePreProcess(globParts); globParts = this.secondPhasePreProcess(globParts); } else if (optimizationLevel >= 1) { globParts = this.levelOneOptimize(globParts); } else { globParts = this.adjascentGlobstarOptimize(globParts); } return globParts; } // just get rid of adjascent ** portions adjascentGlobstarOptimize(globParts) { return globParts.map((parts) => { let gs = -1; while (-1 !== (gs = parts.indexOf("**", gs + 1))) { let i = gs; while (parts[i + 1] === "**") { i++; } if (i !== gs) { parts.splice(gs, i - gs); } } return parts; }); } // get rid of adjascent ** and resolve .. portions levelOneOptimize(globParts) { return globParts.map((parts) => { parts = parts.reduce((set2, part) => { const prev = set2[set2.length - 1]; if (part === "**" && prev === "**") { return set2; } if (part === "..") { if (prev && prev !== ".." && prev !== "." && prev !== "**") { set2.pop(); return set2; } } set2.push(part); return set2; }, []); return parts.length === 0 ? [""] : parts; }); } levelTwoFileOptimize(parts) { if (!Array.isArray(parts)) { parts = this.slashSplit(parts); } let didSomething = false; do { didSomething = false; if (!this.preserveMultipleSlashes) { for (let i = 1; i < parts.length - 1; i++) { const p = parts[i]; if (i === 1 && p === "" && parts[0] === "") continue; if (p === "." || p === "") { didSomething = true; parts.splice(i, 1); i--; } } if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) { didSomething = true; parts.pop(); } } let dd = 0; while (-1 !== (dd = parts.indexOf("..", dd + 1))) { const p = parts[dd - 1]; if (p && p !== "." && p !== ".." && p !== "**") { didSomething = true; parts.splice(dd - 1, 2); dd -= 2; } } } while (didSomething); return parts.length === 0 ? [""] : parts; } // First phase: single-pattern processing //
 is 1 or more portions
  //  is 1 or more portions
  // 

is any portion other than ., .., '', or ** // is . or '' // // **/.. is *brutal* for filesystem walking performance, because // it effectively resets the recursive walk each time it occurs, // and ** cannot be reduced out by a .. pattern part like a regexp // or most strings (other than .., ., and '') can be. // //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/} //

// -> 
/
  // 
/

/../ ->

/
  // **/**/ -> **/
  //
  // **/*/ -> */**/ <== not valid because ** doesn't follow
  // this WOULD be allowed if ** did follow symlinks, or * didn't
  firstPhasePreProcess(globParts) {
    let didSomething = false;
    do {
      didSomething = false;
      for (let parts of globParts) {
        let gs = -1;
        while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
          let gss = gs;
          while (parts[gss + 1] === "**") {
            gss++;
          }
          if (gss > gs) {
            parts.splice(gs + 1, gss - gs);
          }
          let next = parts[gs + 1];
          const p = parts[gs + 2];
          const p2 = parts[gs + 3];
          if (next !== "..")
            continue;
          if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
            continue;
          }
          didSomething = true;
          parts.splice(gs, 1);
          const other = parts.slice(0);
          other[gs] = "**";
          globParts.push(other);
          gs--;
        }
        if (!this.preserveMultipleSlashes) {
          for (let i = 1; i < parts.length - 1; i++) {
            const p = parts[i];
            if (i === 1 && p === "" && parts[0] === "")
              continue;
            if (p === "." || p === "") {
              didSomething = true;
              parts.splice(i, 1);
              i--;
            }
          }
          if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
            didSomething = true;
            parts.pop();
          }
        }
        let dd = 0;
        while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
          const p = parts[dd - 1];
          if (p && p !== "." && p !== ".." && p !== "**") {
            didSomething = true;
            const needDot = dd === 1 && parts[dd + 1] === "**";
            const splin = needDot ? ["."] : [];
            parts.splice(dd - 1, 2, ...splin);
            if (parts.length === 0)
              parts.push("");
            dd -= 2;
          }
        }
      }
    } while (didSomething);
    return globParts;
  }
  // second phase: multi-pattern dedupes
  // {
/*/,
/

/} ->

/*/
  // {
/,
/} -> 
/
  // {
/**/,
/} -> 
/**/
  //
  // {
/**/,
/**/

/} ->

/**/
  // ^-- not valid because ** doens't follow symlinks
  secondPhasePreProcess(globParts) {
    for (let i = 0; i < globParts.length - 1; i++) {
      for (let j = i + 1; j < globParts.length; j++) {
        const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
        if (matched) {
          globParts[i] = [];
          globParts[j] = matched;
          break;
        }
      }
    }
    return globParts.filter((gs) => gs.length);
  }
  partsMatch(a, b, emptyGSMatch = false) {
    let ai = 0;
    let bi = 0;
    let result = [];
    let which2 = "";
    while (ai < a.length && bi < b.length) {
      if (a[ai] === b[bi]) {
        result.push(which2 === "b" ? b[bi] : a[ai]);
        ai++;
        bi++;
      } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
        result.push(a[ai]);
        ai++;
      } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
        result.push(b[bi]);
        bi++;
      } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
        if (which2 === "b")
          return false;
        which2 = "a";
        result.push(a[ai]);
        ai++;
        bi++;
      } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
        if (which2 === "a")
          return false;
        which2 = "b";
        result.push(b[bi]);
        ai++;
        bi++;
      } else {
        return false;
      }
    }
    return a.length === b.length && result;
  }
  parseNegate() {
    if (this.nonegate)
      return;
    const pattern2 = this.pattern;
    let negate = false;
    let negateOffset = 0;
    for (let i = 0; i < pattern2.length && pattern2.charAt(i) === "!"; i++) {
      negate = !negate;
      negateOffset++;
    }
    if (negateOffset)
      this.pattern = pattern2.slice(negateOffset);
    this.negate = negate;
  }
  // set partial to true to test if, for example,
  // "/a/b" matches the start of "/*/b/*/d"
  // Partial means, if you run out of file before you run
  // out of pattern, then that's fine, as long as all
  // the parts match.
  matchOne(file, pattern2, partial2 = false) {
    const options2 = this.options;
    if (this.isWindows) {
      const fileDrive = typeof file[0] === "string" && /^[a-z]:$/i.test(file[0]);
      const fileUNC = !fileDrive && file[0] === "" && file[1] === "" && file[2] === "?" && /^[a-z]:$/i.test(file[3]);
      const patternDrive = typeof pattern2[0] === "string" && /^[a-z]:$/i.test(pattern2[0]);
      const patternUNC = !patternDrive && pattern2[0] === "" && pattern2[1] === "" && pattern2[2] === "?" && typeof pattern2[3] === "string" && /^[a-z]:$/i.test(pattern2[3]);
      const fdi = fileUNC ? 3 : fileDrive ? 0 : void 0;
      const pdi = patternUNC ? 3 : patternDrive ? 0 : void 0;
      if (typeof fdi === "number" && typeof pdi === "number") {
        const [fd, pd] = [file[fdi], pattern2[pdi]];
        if (fd.toLowerCase() === pd.toLowerCase()) {
          pattern2[pdi] = fd;
          if (pdi > fdi) {
            pattern2 = pattern2.slice(pdi);
          } else if (fdi > pdi) {
            file = file.slice(fdi);
          }
        }
      }
    }
    const { optimizationLevel = 1 } = this.options;
    if (optimizationLevel >= 2) {
      file = this.levelTwoFileOptimize(file);
    }
    this.debug("matchOne", this, { file, pattern: pattern2 });
    this.debug("matchOne", file.length, pattern2.length);
    for (var fi = 0, pi = 0, fl = file.length, pl = pattern2.length; fi < fl && pi < pl; fi++, pi++) {
      this.debug("matchOne loop");
      var p = pattern2[pi];
      var f2 = file[fi];
      this.debug(pattern2, p, f2);
      if (p === false) {
        return false;
      }
      if (p === GLOBSTAR$2) {
        this.debug("GLOBSTAR", [pattern2, p, f2]);
        var fr = fi;
        var pr = pi + 1;
        if (pr === pl) {
          this.debug("** at the end");
          for (; fi < fl; fi++) {
            if (file[fi] === "." || file[fi] === ".." || !options2.dot && file[fi].charAt(0) === ".")
              return false;
          }
          return true;
        }
        while (fr < fl) {
          var swallowee = file[fr];
          this.debug("\nglobstar while", file, fr, pattern2, pr, swallowee);
          if (this.matchOne(file.slice(fr), pattern2.slice(pr), partial2)) {
            this.debug("globstar found match!", fr, fl, swallowee);
            return true;
          } else {
            if (swallowee === "." || swallowee === ".." || !options2.dot && swallowee.charAt(0) === ".") {
              this.debug("dot detected!", file, fr, pattern2, pr);
              break;
            }
            this.debug("globstar swallow a segment, and continue");
            fr++;
          }
        }
        if (partial2) {
          this.debug("\n>>> no match, partial?", file, fr, pattern2, pr);
          if (fr === fl) {
            return true;
          }
        }
        return false;
      }
      let hit;
      if (typeof p === "string") {
        hit = f2 === p;
        this.debug("string match", p, f2, hit);
      } else {
        hit = p.test(f2);
        this.debug("pattern match", p, f2, hit);
      }
      if (!hit)
        return false;
    }
    if (fi === fl && pi === pl) {
      return true;
    } else if (fi === fl) {
      return partial2;
    } else if (pi === pl) {
      return fi === fl - 1 && file[fi] === "";
    } else {
      throw new Error("wtf?");
    }
  }
  braceExpand() {
    return braceExpand(this.pattern, this.options);
  }
  parse(pattern2) {
    assertValidPattern(pattern2);
    const options2 = this.options;
    if (pattern2 === "**")
      return GLOBSTAR$2;
    if (pattern2 === "")
      return "";
    let m;
    let fastTest = null;
    if (m = pattern2.match(starRE)) {
      fastTest = options2.dot ? starTestDot : starTest;
    } else if (m = pattern2.match(starDotExtRE)) {
      fastTest = (options2.nocase ? options2.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options2.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
    } else if (m = pattern2.match(qmarksRE)) {
      fastTest = (options2.nocase ? options2.dot ? qmarksTestNocaseDot : qmarksTestNocase : options2.dot ? qmarksTestDot : qmarksTest)(m);
    } else if (m = pattern2.match(starDotStarRE)) {
      fastTest = options2.dot ? starDotStarTestDot : starDotStarTest;
    } else if (m = pattern2.match(dotStarRE)) {
      fastTest = dotStarTest;
    }
    const re = AST.fromGlob(pattern2, this.options).toMMPattern();
    if (fastTest && typeof re === "object") {
      Reflect.defineProperty(re, "test", { value: fastTest });
    }
    return re;
  }
  makeRe() {
    if (this.regexp || this.regexp === false)
      return this.regexp;
    const set2 = this.set;
    if (!set2.length) {
      this.regexp = false;
      return this.regexp;
    }
    const options2 = this.options;
    const twoStar = options2.noglobstar ? star : options2.dot ? twoStarDot : twoStarNoDot;
    const flags = new Set(options2.nocase ? ["i"] : []);
    let re = set2.map((pattern2) => {
      const pp = pattern2.map((p) => {
        if (p instanceof RegExp) {
          for (const f2 of p.flags.split(""))
            flags.add(f2);
        }
        return typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR$2 ? GLOBSTAR$2 : p._src;
      });
      pp.forEach((p, i) => {
        const next = pp[i + 1];
        const prev = pp[i - 1];
        if (p !== GLOBSTAR$2 || prev === GLOBSTAR$2) {
          return;
        }
        if (prev === void 0) {
          if (next !== void 0 && next !== GLOBSTAR$2) {
            pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
          } else {
            pp[i] = twoStar;
          }
        } else if (next === void 0) {
          pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
        } else if (next !== GLOBSTAR$2) {
          pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
          pp[i + 1] = GLOBSTAR$2;
        }
      });
      return pp.filter((p) => p !== GLOBSTAR$2).join("/");
    }).join("|");
    const [open2, close2] = set2.length > 1 ? ["(?:", ")"] : ["", ""];
    re = "^" + open2 + re + close2 + "$";
    if (this.negate)
      re = "^(?!" + re + ").+$";
    try {
      this.regexp = new RegExp(re, [...flags].join(""));
    } catch (ex) {
      this.regexp = false;
    }
    return this.regexp;
  }
  slashSplit(p) {
    if (this.preserveMultipleSlashes) {
      return p.split("/");
    } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
      return ["", ...p.split(/\/+/)];
    } else {
      return p.split(/\/+/);
    }
  }
  match(f2, partial2 = this.partial) {
    this.debug("match", f2, this.pattern);
    if (this.comment) {
      return false;
    }
    if (this.empty) {
      return f2 === "";
    }
    if (f2 === "/" && partial2) {
      return true;
    }
    const options2 = this.options;
    if (this.isWindows) {
      f2 = f2.split("\\").join("/");
    }
    const ff = this.slashSplit(f2);
    this.debug(this.pattern, "split", ff);
    const set2 = this.set;
    this.debug(this.pattern, "set", set2);
    let filename = ff[ff.length - 1];
    if (!filename) {
      for (let i = ff.length - 2; !filename && i >= 0; i--) {
        filename = ff[i];
      }
    }
    for (let i = 0; i < set2.length; i++) {
      const pattern2 = set2[i];
      let file = ff;
      if (options2.matchBase && pattern2.length === 1) {
        file = [filename];
      }
      const hit = this.matchOne(file, pattern2, partial2);
      if (hit) {
        if (options2.flipNegate) {
          return true;
        }
        return !this.negate;
      }
    }
    if (options2.flipNegate) {
      return false;
    }
    return this.negate;
  }
  static defaults(def) {
    return minimatch.defaults(def).Minimatch;
  }
};
minimatch.AST = AST;
minimatch.Minimatch = Minimatch;
minimatch.escape = escape$2;
minimatch.unescape = unescape$1;
var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
var warned$1 = /* @__PURE__ */ new Set();
var PROCESS = typeof process === "object" && !!process ? process : {};
var emitWarning = (msg, type, code, fn) => {
  typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
};
var AC = globalThis.AbortController;
var AS = globalThis.AbortSignal;
var _a;
if (typeof AC === "undefined") {
  AS = class AbortSignal {
    constructor() {
      __publicField(this, "onabort");
      __publicField(this, "_onabort", []);
      __publicField(this, "reason");
      __publicField(this, "aborted", false);
    }
    addEventListener(_, fn) {
      this._onabort.push(fn);
    }
  };
  AC = class AbortController {
    constructor() {
      __publicField(this, "signal", new AS());
      warnACPolyfill();
    }
    abort(reason) {
      var _a4, _b3;
      if (this.signal.aborted)
        return;
      this.signal.reason = reason;
      this.signal.aborted = true;
      for (const fn of this.signal._onabort) {
        fn(reason);
      }
      (_b3 = (_a4 = this.signal).onabort) == null ? void 0 : _b3.call(_a4, reason);
    }
  };
  let printACPolyfillWarning = ((_a = PROCESS.env) == null ? void 0 : _a.LRU_CACHE_IGNORE_AC_WARNING) !== "1";
  const warnACPolyfill = () => {
    if (!printACPolyfillWarning)
      return;
    printACPolyfillWarning = false;
    emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
  };
}
var shouldWarn = (code) => !warned$1.has(code);
var isPosInt = (n2) => n2 && n2 === Math.floor(n2) && n2 > 0 && isFinite(n2);
var getUintArray = (max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null;
var ZeroArray = class extends Array {
  constructor(size) {
    super(size);
    this.fill(0);
  }
};
var _constructing;
var _Stack = class _Stack {
  constructor(max, HeapCls) {
    __publicField(this, "heap");
    __publicField(this, "length");
    if (!__privateGet(_Stack, _constructing)) {
      throw new TypeError("instantiate Stack using Stack.create(n)");
    }
    this.heap = new HeapCls(max);
    this.length = 0;
  }
  static create(max) {
    const HeapCls = getUintArray(max);
    if (!HeapCls)
      return [];
    __privateSet(_Stack, _constructing, true);
    const s = new _Stack(max, HeapCls);
    __privateSet(_Stack, _constructing, false);
    return s;
  }
  push(n2) {
    this.heap[this.length++] = n2;
  }
  pop() {
    return this.heap[--this.length];
  }
};
_constructing = new WeakMap();
// private constructor
__privateAdd(_Stack, _constructing, false);
var Stack = _Stack;
var _a2, _b, _max, _maxSize, _dispose, _disposeAfter, _fetchMethod, _memoMethod, _size, _calculatedSize, _keyMap, _keyList, _valList, _next, _prev, _head, _tail, _free, _disposed, _sizes, _starts, _ttls, _hasDispose, _hasFetchMethod, _hasDisposeAfter, _LRUCache_instances, initializeTTLTracking_fn, _updateItemAge, _statusTTL, _setItemTTL, _isStale, initializeSizeTracking_fn, _removeItemSize, _addItemSize, _requireSize, indexes_fn, rindexes_fn, isValidIndex_fn, evict_fn, backgroundFetch_fn, isBackgroundFetch_fn, connect_fn, moveToTail_fn, delete_fn, clear_fn;
var _LRUCache = class _LRUCache {
  constructor(options2) {
    __privateAdd(this, _LRUCache_instances);
    // options that cannot be changed without disaster
    __privateAdd(this, _max);
    __privateAdd(this, _maxSize);
    __privateAdd(this, _dispose);
    __privateAdd(this, _disposeAfter);
    __privateAdd(this, _fetchMethod);
    __privateAdd(this, _memoMethod);
    /**
     * {@link LRUCache.OptionsBase.ttl}
     */
    __publicField(this, "ttl");
    /**
     * {@link LRUCache.OptionsBase.ttlResolution}
     */
    __publicField(this, "ttlResolution");
    /**
     * {@link LRUCache.OptionsBase.ttlAutopurge}
     */
    __publicField(this, "ttlAutopurge");
    /**
     * {@link LRUCache.OptionsBase.updateAgeOnGet}
     */
    __publicField(this, "updateAgeOnGet");
    /**
     * {@link LRUCache.OptionsBase.updateAgeOnHas}
     */
    __publicField(this, "updateAgeOnHas");
    /**
     * {@link LRUCache.OptionsBase.allowStale}
     */
    __publicField(this, "allowStale");
    /**
     * {@link LRUCache.OptionsBase.noDisposeOnSet}
     */
    __publicField(this, "noDisposeOnSet");
    /**
     * {@link LRUCache.OptionsBase.noUpdateTTL}
     */
    __publicField(this, "noUpdateTTL");
    /**
     * {@link LRUCache.OptionsBase.maxEntrySize}
     */
    __publicField(this, "maxEntrySize");
    /**
     * {@link LRUCache.OptionsBase.sizeCalculation}
     */
    __publicField(this, "sizeCalculation");
    /**
     * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
     */
    __publicField(this, "noDeleteOnFetchRejection");
    /**
     * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
     */
    __publicField(this, "noDeleteOnStaleGet");
    /**
     * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
     */
    __publicField(this, "allowStaleOnFetchAbort");
    /**
     * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
     */
    __publicField(this, "allowStaleOnFetchRejection");
    /**
     * {@link LRUCache.OptionsBase.ignoreFetchAbort}
     */
    __publicField(this, "ignoreFetchAbort");
    // computed properties
    __privateAdd(this, _size);
    __privateAdd(this, _calculatedSize);
    __privateAdd(this, _keyMap);
    __privateAdd(this, _keyList);
    __privateAdd(this, _valList);
    __privateAdd(this, _next);
    __privateAdd(this, _prev);
    __privateAdd(this, _head);
    __privateAdd(this, _tail);
    __privateAdd(this, _free);
    __privateAdd(this, _disposed);
    __privateAdd(this, _sizes);
    __privateAdd(this, _starts);
    __privateAdd(this, _ttls);
    __privateAdd(this, _hasDispose);
    __privateAdd(this, _hasFetchMethod);
    __privateAdd(this, _hasDisposeAfter);
    // conditionally set private methods related to TTL
    __privateAdd(this, _updateItemAge, () => {
    });
    __privateAdd(this, _statusTTL, () => {
    });
    __privateAdd(this, _setItemTTL, () => {
    });
    /* c8 ignore stop */
    __privateAdd(this, _isStale, () => false);
    __privateAdd(this, _removeItemSize, (_i2) => {
    });
    __privateAdd(this, _addItemSize, (_i2, _s2, _st) => {
    });
    __privateAdd(this, _requireSize, (_k2, _v, size, sizeCalculation) => {
      if (size || sizeCalculation) {
        throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
      }
      return 0;
    });
    /**
     * A String value that is used in the creation of the default string
     * description of an object. Called by the built-in method
     * `Object.prototype.toString`.
     */
    __publicField(this, _a2, "LRUCache");
    const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options2;
    if (max !== 0 && !isPosInt(max)) {
      throw new TypeError("max option must be a nonnegative integer");
    }
    const UintArray = max ? getUintArray(max) : Array;
    if (!UintArray) {
      throw new Error("invalid max value: " + max);
    }
    __privateSet(this, _max, max);
    __privateSet(this, _maxSize, maxSize);
    this.maxEntrySize = maxEntrySize || __privateGet(this, _maxSize);
    this.sizeCalculation = sizeCalculation;
    if (this.sizeCalculation) {
      if (!__privateGet(this, _maxSize) && !this.maxEntrySize) {
        throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
      }
      if (typeof this.sizeCalculation !== "function") {
        throw new TypeError("sizeCalculation set to non-function");
      }
    }
    if (memoMethod !== void 0 && typeof memoMethod !== "function") {
      throw new TypeError("memoMethod must be a function if defined");
    }
    __privateSet(this, _memoMethod, memoMethod);
    if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
      throw new TypeError("fetchMethod must be a function if specified");
    }
    __privateSet(this, _fetchMethod, fetchMethod);
    __privateSet(this, _hasFetchMethod, !!fetchMethod);
    __privateSet(this, _keyMap, /* @__PURE__ */ new Map());
    __privateSet(this, _keyList, new Array(max).fill(void 0));
    __privateSet(this, _valList, new Array(max).fill(void 0));
    __privateSet(this, _next, new UintArray(max));
    __privateSet(this, _prev, new UintArray(max));
    __privateSet(this, _head, 0);
    __privateSet(this, _tail, 0);
    __privateSet(this, _free, Stack.create(max));
    __privateSet(this, _size, 0);
    __privateSet(this, _calculatedSize, 0);
    if (typeof dispose === "function") {
      __privateSet(this, _dispose, dispose);
    }
    if (typeof disposeAfter === "function") {
      __privateSet(this, _disposeAfter, disposeAfter);
      __privateSet(this, _disposed, []);
    } else {
      __privateSet(this, _disposeAfter, void 0);
      __privateSet(this, _disposed, void 0);
    }
    __privateSet(this, _hasDispose, !!__privateGet(this, _dispose));
    __privateSet(this, _hasDisposeAfter, !!__privateGet(this, _disposeAfter));
    this.noDisposeOnSet = !!noDisposeOnSet;
    this.noUpdateTTL = !!noUpdateTTL;
    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
    this.ignoreFetchAbort = !!ignoreFetchAbort;
    if (this.maxEntrySize !== 0) {
      if (__privateGet(this, _maxSize) !== 0) {
        if (!isPosInt(__privateGet(this, _maxSize))) {
          throw new TypeError("maxSize must be a positive integer if specified");
        }
      }
      if (!isPosInt(this.maxEntrySize)) {
        throw new TypeError("maxEntrySize must be a positive integer if specified");
      }
      __privateMethod(this, _LRUCache_instances, initializeSizeTracking_fn).call(this);
    }
    this.allowStale = !!allowStale;
    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
    this.updateAgeOnGet = !!updateAgeOnGet;
    this.updateAgeOnHas = !!updateAgeOnHas;
    this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
    this.ttlAutopurge = !!ttlAutopurge;
    this.ttl = ttl || 0;
    if (this.ttl) {
      if (!isPosInt(this.ttl)) {
        throw new TypeError("ttl must be a positive integer if specified");
      }
      __privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this);
    }
    if (__privateGet(this, _max) === 0 && this.ttl === 0 && __privateGet(this, _maxSize) === 0) {
      throw new TypeError("At least one of max, maxSize, or ttl is required");
    }
    if (!this.ttlAutopurge && !__privateGet(this, _max) && !__privateGet(this, _maxSize)) {
      const code = "LRU_CACHE_UNBOUNDED";
      if (shouldWarn(code)) {
        warned$1.add(code);
        const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
        emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
      }
    }
  }
  /**
   * Do not call this method unless you need to inspect the
   * inner workings of the cache.  If anything returned by this
   * object is modified in any way, strange breakage may occur.
   *
   * These fields are private for a reason!
   *
   * @internal
   */
  static unsafeExposeInternals(c) {
    return {
      // properties
      starts: __privateGet(c, _starts),
      ttls: __privateGet(c, _ttls),
      sizes: __privateGet(c, _sizes),
      keyMap: __privateGet(c, _keyMap),
      keyList: __privateGet(c, _keyList),
      valList: __privateGet(c, _valList),
      next: __privateGet(c, _next),
      prev: __privateGet(c, _prev),
      get head() {
        return __privateGet(c, _head);
      },
      get tail() {
        return __privateGet(c, _tail);
      },
      free: __privateGet(c, _free),
      // methods
      isBackgroundFetch: (p) => {
        var _a4;
        return __privateMethod(_a4 = c, _LRUCache_instances, isBackgroundFetch_fn).call(_a4, p);
      },
      backgroundFetch: (k, index, options2, context) => {
        var _a4;
        return __privateMethod(_a4 = c, _LRUCache_instances, backgroundFetch_fn).call(_a4, k, index, options2, context);
      },
      moveToTail: (index) => {
        var _a4;
        return __privateMethod(_a4 = c, _LRUCache_instances, moveToTail_fn).call(_a4, index);
      },
      indexes: (options2) => {
        var _a4;
        return __privateMethod(_a4 = c, _LRUCache_instances, indexes_fn).call(_a4, options2);
      },
      rindexes: (options2) => {
        var _a4;
        return __privateMethod(_a4 = c, _LRUCache_instances, rindexes_fn).call(_a4, options2);
      },
      isStale: (index) => {
        var _a4;
        return __privateGet(_a4 = c, _isStale).call(_a4, index);
      }
    };
  }
  // Protected read-only members
  /**
   * {@link LRUCache.OptionsBase.max} (read-only)
   */
  get max() {
    return __privateGet(this, _max);
  }
  /**
   * {@link LRUCache.OptionsBase.maxSize} (read-only)
   */
  get maxSize() {
    return __privateGet(this, _maxSize);
  }
  /**
   * The total computed size of items in the cache (read-only)
   */
  get calculatedSize() {
    return __privateGet(this, _calculatedSize);
  }
  /**
   * The number of items stored in the cache (read-only)
   */
  get size() {
    return __privateGet(this, _size);
  }
  /**
   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
   */
  get fetchMethod() {
    return __privateGet(this, _fetchMethod);
  }
  get memoMethod() {
    return __privateGet(this, _memoMethod);
  }
  /**
   * {@link LRUCache.OptionsBase.dispose} (read-only)
   */
  get dispose() {
    return __privateGet(this, _dispose);
  }
  /**
   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
   */
  get disposeAfter() {
    return __privateGet(this, _disposeAfter);
  }
  /**
   * Return the number of ms left in the item's TTL. If item is not in cache,
   * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
   */
  getRemainingTTL(key) {
    return __privateGet(this, _keyMap).has(key) ? Infinity : 0;
  }
  /**
   * Return a generator yielding `[key, value]` pairs,
   * in order from most recently used to least recently used.
   */
  *entries() {
    for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
      if (__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
        yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]];
      }
    }
  }
  /**
   * Inverse order version of {@link LRUCache.entries}
   *
   * Return a generator yielding `[key, value]` pairs,
   * in order from least recently used to most recently used.
   */
  *rentries() {
    for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
      if (__privateGet(this, _valList)[i] !== void 0 && __privateGet(this, _keyList)[i] !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
        yield [__privateGet(this, _keyList)[i], __privateGet(this, _valList)[i]];
      }
    }
  }
  /**
   * Return a generator yielding the keys in the cache,
   * in order from most recently used to least recently used.
   */
  *keys() {
    for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
      const k = __privateGet(this, _keyList)[i];
      if (k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
        yield k;
      }
    }
  }
  /**
   * Inverse order version of {@link LRUCache.keys}
   *
   * Return a generator yielding the keys in the cache,
   * in order from least recently used to most recently used.
   */
  *rkeys() {
    for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
      const k = __privateGet(this, _keyList)[i];
      if (k !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
        yield k;
      }
    }
  }
  /**
   * Return a generator yielding the values in the cache,
   * in order from most recently used to least recently used.
   */
  *values() {
    for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
      const v = __privateGet(this, _valList)[i];
      if (v !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
        yield __privateGet(this, _valList)[i];
      }
    }
  }
  /**
   * Inverse order version of {@link LRUCache.values}
   *
   * Return a generator yielding the values in the cache,
   * in order from least recently used to most recently used.
   */
  *rvalues() {
    for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
      const v = __privateGet(this, _valList)[i];
      if (v !== void 0 && !__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, __privateGet(this, _valList)[i])) {
        yield __privateGet(this, _valList)[i];
      }
    }
  }
  /**
   * Iterating over the cache itself yields the same results as
   * {@link LRUCache.entries}
   */
  [(_b = Symbol.iterator, _a2 = Symbol.toStringTag, _b)]() {
    return this.entries();
  }
  /**
   * Find a value for which the supplied fn method returns a truthy value,
   * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
   */
  find(fn, getOptions2 = {}) {
    for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
      const v = __privateGet(this, _valList)[i];
      const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
      if (value2 === void 0)
        continue;
      if (fn(value2, __privateGet(this, _keyList)[i], this)) {
        return this.get(__privateGet(this, _keyList)[i], getOptions2);
      }
    }
  }
  /**
   * Call the supplied function on each item in the cache, in order from most
   * recently used to least recently used.
   *
   * `fn` is called as `fn(value, key, cache)`.
   *
   * If `thisp` is provided, function will be called in the `this`-context of
   * the provided object, or the cache if no `thisp` object is provided.
   *
   * Does not update age or recenty of use, or iterate over stale values.
   */
  forEach(fn, thisp = this) {
    for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this)) {
      const v = __privateGet(this, _valList)[i];
      const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
      if (value2 === void 0)
        continue;
      fn.call(thisp, value2, __privateGet(this, _keyList)[i], this);
    }
  }
  /**
   * The same as {@link LRUCache.forEach} but items are iterated over in
   * reverse order.  (ie, less recently used items are iterated over first.)
   */
  rforEach(fn, thisp = this) {
    for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this)) {
      const v = __privateGet(this, _valList)[i];
      const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
      if (value2 === void 0)
        continue;
      fn.call(thisp, value2, __privateGet(this, _keyList)[i], this);
    }
  }
  /**
   * Delete any stale entries. Returns true if anything was removed,
   * false otherwise.
   */
  purgeStale() {
    let deleted = false;
    for (const i of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: true })) {
      if (__privateGet(this, _isStale).call(this, i)) {
        __privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[i], "expire");
        deleted = true;
      }
    }
    return deleted;
  }
  /**
   * Get the extended info about a given entry, to get its value, size, and
   * TTL info simultaneously. Returns `undefined` if the key is not present.
   *
   * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
   * serialization, the `start` value is always the current timestamp, and the
   * `ttl` is a calculated remaining time to live (negative if expired).
   *
   * Always returns stale values, if their info is found in the cache, so be
   * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
   * if relevant.
   */
  info(key) {
    const i = __privateGet(this, _keyMap).get(key);
    if (i === void 0)
      return void 0;
    const v = __privateGet(this, _valList)[i];
    const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
    if (value2 === void 0)
      return void 0;
    const entry2 = { value: value2 };
    if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {
      const ttl = __privateGet(this, _ttls)[i];
      const start = __privateGet(this, _starts)[i];
      if (ttl && start) {
        const remain = ttl - (perf.now() - start);
        entry2.ttl = remain;
        entry2.start = Date.now();
      }
    }
    if (__privateGet(this, _sizes)) {
      entry2.size = __privateGet(this, _sizes)[i];
    }
    return entry2;
  }
  /**
   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
   * passed to {@link LRLUCache#load}.
   *
   * The `start` fields are calculated relative to a portable `Date.now()`
   * timestamp, even if `performance.now()` is available.
   *
   * Stale entries are always included in the `dump`, even if
   * {@link LRUCache.OptionsBase.allowStale} is false.
   *
   * Note: this returns an actual array, not a generator, so it can be more
   * easily passed around.
   */
  dump() {
    const arr = [];
    for (const i of __privateMethod(this, _LRUCache_instances, indexes_fn).call(this, { allowStale: true })) {
      const key = __privateGet(this, _keyList)[i];
      const v = __privateGet(this, _valList)[i];
      const value2 = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
      if (value2 === void 0 || key === void 0)
        continue;
      const entry2 = { value: value2 };
      if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {
        entry2.ttl = __privateGet(this, _ttls)[i];
        const age = perf.now() - __privateGet(this, _starts)[i];
        entry2.start = Math.floor(Date.now() - age);
      }
      if (__privateGet(this, _sizes)) {
        entry2.size = __privateGet(this, _sizes)[i];
      }
      arr.unshift([key, entry2]);
    }
    return arr;
  }
  /**
   * Reset the cache and load in the items in entries in the order listed.
   *
   * The shape of the resulting cache may be different if the same options are
   * not used in both caches.
   *
   * The `start` fields are assumed to be calculated relative to a portable
   * `Date.now()` timestamp, even if `performance.now()` is available.
   */
  load(arr) {
    this.clear();
    for (const [key, entry2] of arr) {
      if (entry2.start) {
        const age = Date.now() - entry2.start;
        entry2.start = perf.now() - age;
      }
      this.set(key, entry2.value, entry2);
    }
  }
  /**
   * Add a value to the cache.
   *
   * Note: if `undefined` is specified as a value, this is an alias for
   * {@link LRUCache#delete}
   *
   * Fields on the {@link LRUCache.SetOptions} options param will override
   * their corresponding values in the constructor options for the scope
   * of this single `set()` operation.
   *
   * If `start` is provided, then that will set the effective start
   * time for the TTL calculation. Note that this must be a previous
   * value of `performance.now()` if supported, or a previous value of
   * `Date.now()` if not.
   *
   * Options object may also include `size`, which will prevent
   * calling the `sizeCalculation` function and just use the specified
   * number if it is a positive integer, and `noDisposeOnSet` which
   * will prevent calling a `dispose` function in the case of
   * overwrites.
   *
   * If the `size` (or return value of `sizeCalculation`) for a given
   * entry is greater than `maxEntrySize`, then the item will not be
   * added to the cache.
   *
   * Will update the recency of the entry.
   *
   * If the value is `undefined`, then this is an alias for
   * `cache.delete(key)`. `undefined` is never stored in the cache.
   */
  set(k, v, setOptions = {}) {
    var _a4, _b3, _c2, _d2, _e2;
    if (v === void 0) {
      this.delete(k);
      return this;
    }
    const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status: status2 } = setOptions;
    let { noUpdateTTL = this.noUpdateTTL } = setOptions;
    const size = __privateGet(this, _requireSize).call(this, k, v, setOptions.size || 0, sizeCalculation);
    if (this.maxEntrySize && size > this.maxEntrySize) {
      if (status2) {
        status2.set = "miss";
        status2.maxEntrySizeExceeded = true;
      }
      __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "set");
      return this;
    }
    let index = __privateGet(this, _size) === 0 ? void 0 : __privateGet(this, _keyMap).get(k);
    if (index === void 0) {
      index = __privateGet(this, _size) === 0 ? __privateGet(this, _tail) : __privateGet(this, _free).length !== 0 ? __privateGet(this, _free).pop() : __privateGet(this, _size) === __privateGet(this, _max) ? __privateMethod(this, _LRUCache_instances, evict_fn).call(this, false) : __privateGet(this, _size);
      __privateGet(this, _keyList)[index] = k;
      __privateGet(this, _valList)[index] = v;
      __privateGet(this, _keyMap).set(k, index);
      __privateGet(this, _next)[__privateGet(this, _tail)] = index;
      __privateGet(this, _prev)[index] = __privateGet(this, _tail);
      __privateSet(this, _tail, index);
      __privateWrapper(this, _size)._++;
      __privateGet(this, _addItemSize).call(this, index, size, status2);
      if (status2)
        status2.set = "add";
      noUpdateTTL = false;
    } else {
      __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);
      const oldVal = __privateGet(this, _valList)[index];
      if (v !== oldVal) {
        if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal)) {
          oldVal.__abortController.abort(new Error("replaced"));
          const { __staleWhileFetching: s } = oldVal;
          if (s !== void 0 && !noDisposeOnSet) {
            if (__privateGet(this, _hasDispose)) {
              (_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, s, k, "set");
            }
            if (__privateGet(this, _hasDisposeAfter)) {
              (_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([s, k, "set"]);
            }
          }
        } else if (!noDisposeOnSet) {
          if (__privateGet(this, _hasDispose)) {
            (_c2 = __privateGet(this, _dispose)) == null ? void 0 : _c2.call(this, oldVal, k, "set");
          }
          if (__privateGet(this, _hasDisposeAfter)) {
            (_d2 = __privateGet(this, _disposed)) == null ? void 0 : _d2.push([oldVal, k, "set"]);
          }
        }
        __privateGet(this, _removeItemSize).call(this, index);
        __privateGet(this, _addItemSize).call(this, index, size, status2);
        __privateGet(this, _valList)[index] = v;
        if (status2) {
          status2.set = "replace";
          const oldValue = oldVal && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, oldVal) ? oldVal.__staleWhileFetching : oldVal;
          if (oldValue !== void 0)
            status2.oldValue = oldValue;
        }
      } else if (status2) {
        status2.set = "update";
      }
    }
    if (ttl !== 0 && !__privateGet(this, _ttls)) {
      __privateMethod(this, _LRUCache_instances, initializeTTLTracking_fn).call(this);
    }
    if (__privateGet(this, _ttls)) {
      if (!noUpdateTTL) {
        __privateGet(this, _setItemTTL).call(this, index, ttl, start);
      }
      if (status2)
        __privateGet(this, _statusTTL).call(this, status2, index);
    }
    if (!noDisposeOnSet && __privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {
      const dt = __privateGet(this, _disposed);
      let task;
      while (task = dt == null ? void 0 : dt.shift()) {
        (_e2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _e2.call(this, ...task);
      }
    }
    return this;
  }
  /**
   * Evict the least recently used item, returning its value or
   * `undefined` if cache is empty.
   */
  pop() {
    var _a4;
    try {
      while (__privateGet(this, _size)) {
        const val = __privateGet(this, _valList)[__privateGet(this, _head)];
        __privateMethod(this, _LRUCache_instances, evict_fn).call(this, true);
        if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, val)) {
          if (val.__staleWhileFetching) {
            return val.__staleWhileFetching;
          }
        } else if (val !== void 0) {
          return val;
        }
      }
    } finally {
      if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {
        const dt = __privateGet(this, _disposed);
        let task;
        while (task = dt == null ? void 0 : dt.shift()) {
          (_a4 = __privateGet(this, _disposeAfter)) == null ? void 0 : _a4.call(this, ...task);
        }
      }
    }
  }
  /**
   * Check if a key is in the cache, without updating the recency of use.
   * Will return false if the item is stale, even though it is technically
   * in the cache.
   *
   * Check if a key is in the cache, without updating the recency of
   * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
   * to `true` in either the options or the constructor.
   *
   * Will return `false` if the item is stale, even though it is technically in
   * the cache. The difference can be determined (if it matters) by using a
   * `status` argument, and inspecting the `has` field.
   *
   * Will not update item age unless
   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
   */
  has(k, hasOptions = {}) {
    const { updateAgeOnHas = this.updateAgeOnHas, status: status2 } = hasOptions;
    const index = __privateGet(this, _keyMap).get(k);
    if (index !== void 0) {
      const v = __privateGet(this, _valList)[index];
      if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) && v.__staleWhileFetching === void 0) {
        return false;
      }
      if (!__privateGet(this, _isStale).call(this, index)) {
        if (updateAgeOnHas) {
          __privateGet(this, _updateItemAge).call(this, index);
        }
        if (status2) {
          status2.has = "hit";
          __privateGet(this, _statusTTL).call(this, status2, index);
        }
        return true;
      } else if (status2) {
        status2.has = "stale";
        __privateGet(this, _statusTTL).call(this, status2, index);
      }
    } else if (status2) {
      status2.has = "miss";
    }
    return false;
  }
  /**
   * Like {@link LRUCache#get} but doesn't update recency or delete stale
   * items.
   *
   * Returns `undefined` if the item is stale, unless
   * {@link LRUCache.OptionsBase.allowStale} is set.
   */
  peek(k, peekOptions = {}) {
    const { allowStale = this.allowStale } = peekOptions;
    const index = __privateGet(this, _keyMap).get(k);
    if (index === void 0 || !allowStale && __privateGet(this, _isStale).call(this, index)) {
      return;
    }
    const v = __privateGet(this, _valList)[index];
    return __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v) ? v.__staleWhileFetching : v;
  }
  async fetch(k, fetchOptions = {}) {
    const {
      // get options
      allowStale = this.allowStale,
      updateAgeOnGet = this.updateAgeOnGet,
      noDeleteOnStaleGet = this.noDeleteOnStaleGet,
      // set options
      ttl = this.ttl,
      noDisposeOnSet = this.noDisposeOnSet,
      size = 0,
      sizeCalculation = this.sizeCalculation,
      noUpdateTTL = this.noUpdateTTL,
      // fetch exclusive options
      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
      ignoreFetchAbort = this.ignoreFetchAbort,
      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
      context,
      forceRefresh = false,
      status: status2,
      signal
    } = fetchOptions;
    if (!__privateGet(this, _hasFetchMethod)) {
      if (status2)
        status2.fetch = "get";
      return this.get(k, {
        allowStale,
        updateAgeOnGet,
        noDeleteOnStaleGet,
        status: status2
      });
    }
    const options2 = {
      allowStale,
      updateAgeOnGet,
      noDeleteOnStaleGet,
      ttl,
      noDisposeOnSet,
      size,
      sizeCalculation,
      noUpdateTTL,
      noDeleteOnFetchRejection,
      allowStaleOnFetchRejection,
      allowStaleOnFetchAbort,
      ignoreFetchAbort,
      status: status2,
      signal
    };
    let index = __privateGet(this, _keyMap).get(k);
    if (index === void 0) {
      if (status2)
        status2.fetch = "miss";
      const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options2, context);
      return p.__returned = p;
    } else {
      const v = __privateGet(this, _valList)[index];
      if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
        const stale = allowStale && v.__staleWhileFetching !== void 0;
        if (status2) {
          status2.fetch = "inflight";
          if (stale)
            status2.returnedStale = true;
        }
        return stale ? v.__staleWhileFetching : v.__returned = v;
      }
      const isStale = __privateGet(this, _isStale).call(this, index);
      if (!forceRefresh && !isStale) {
        if (status2)
          status2.fetch = "hit";
        __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);
        if (updateAgeOnGet) {
          __privateGet(this, _updateItemAge).call(this, index);
        }
        if (status2)
          __privateGet(this, _statusTTL).call(this, status2, index);
        return v;
      }
      const p = __privateMethod(this, _LRUCache_instances, backgroundFetch_fn).call(this, k, index, options2, context);
      const hasStale = p.__staleWhileFetching !== void 0;
      const staleVal = hasStale && allowStale;
      if (status2) {
        status2.fetch = isStale ? "stale" : "refresh";
        if (staleVal && isStale)
          status2.returnedStale = true;
      }
      return staleVal ? p.__staleWhileFetching : p.__returned = p;
    }
  }
  async forceFetch(k, fetchOptions = {}) {
    const v = await this.fetch(k, fetchOptions);
    if (v === void 0)
      throw new Error("fetch() returned undefined");
    return v;
  }
  memo(k, memoOptions = {}) {
    const memoMethod = __privateGet(this, _memoMethod);
    if (!memoMethod) {
      throw new Error("no memoMethod provided to constructor");
    }
    const { context, forceRefresh, ...options2 } = memoOptions;
    const v = this.get(k, options2);
    if (!forceRefresh && v !== void 0)
      return v;
    const vv = memoMethod(k, v, {
      options: options2,
      context
    });
    this.set(k, vv, options2);
    return vv;
  }
  /**
   * Return a value from the cache. Will update the recency of the cache
   * entry found.
   *
   * If the key is not found, get() will return `undefined`.
   */
  get(k, getOptions2 = {}) {
    const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status: status2 } = getOptions2;
    const index = __privateGet(this, _keyMap).get(k);
    if (index !== void 0) {
      const value2 = __privateGet(this, _valList)[index];
      const fetching = __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, value2);
      if (status2)
        __privateGet(this, _statusTTL).call(this, status2, index);
      if (__privateGet(this, _isStale).call(this, index)) {
        if (status2)
          status2.get = "stale";
        if (!fetching) {
          if (!noDeleteOnStaleGet) {
            __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "expire");
          }
          if (status2 && allowStale)
            status2.returnedStale = true;
          return allowStale ? value2 : void 0;
        } else {
          if (status2 && allowStale && value2.__staleWhileFetching !== void 0) {
            status2.returnedStale = true;
          }
          return allowStale ? value2.__staleWhileFetching : void 0;
        }
      } else {
        if (status2)
          status2.get = "hit";
        if (fetching) {
          return value2.__staleWhileFetching;
        }
        __privateMethod(this, _LRUCache_instances, moveToTail_fn).call(this, index);
        if (updateAgeOnGet) {
          __privateGet(this, _updateItemAge).call(this, index);
        }
        return value2;
      }
    } else if (status2) {
      status2.get = "miss";
    }
  }
  /**
   * Deletes a key out of the cache.
   *
   * Returns true if the key was deleted, false otherwise.
   */
  delete(k) {
    return __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "delete");
  }
  /**
   * Clear the cache entirely, throwing away all values.
   */
  clear() {
    return __privateMethod(this, _LRUCache_instances, clear_fn).call(this, "delete");
  }
};
_max = new WeakMap();
_maxSize = new WeakMap();
_dispose = new WeakMap();
_disposeAfter = new WeakMap();
_fetchMethod = new WeakMap();
_memoMethod = new WeakMap();
_size = new WeakMap();
_calculatedSize = new WeakMap();
_keyMap = new WeakMap();
_keyList = new WeakMap();
_valList = new WeakMap();
_next = new WeakMap();
_prev = new WeakMap();
_head = new WeakMap();
_tail = new WeakMap();
_free = new WeakMap();
_disposed = new WeakMap();
_sizes = new WeakMap();
_starts = new WeakMap();
_ttls = new WeakMap();
_hasDispose = new WeakMap();
_hasFetchMethod = new WeakMap();
_hasDisposeAfter = new WeakMap();
_LRUCache_instances = new WeakSet();
initializeTTLTracking_fn = function() {
  const ttls = new ZeroArray(__privateGet(this, _max));
  const starts = new ZeroArray(__privateGet(this, _max));
  __privateSet(this, _ttls, ttls);
  __privateSet(this, _starts, starts);
  __privateSet(this, _setItemTTL, (index, ttl, start = perf.now()) => {
    starts[index] = ttl !== 0 ? start : 0;
    ttls[index] = ttl;
    if (ttl !== 0 && this.ttlAutopurge) {
      const t2 = setTimeout(() => {
        if (__privateGet(this, _isStale).call(this, index)) {
          __privateMethod(this, _LRUCache_instances, delete_fn).call(this, __privateGet(this, _keyList)[index], "expire");
        }
      }, ttl + 1);
      if (t2.unref) {
        t2.unref();
      }
    }
  });
  __privateSet(this, _updateItemAge, (index) => {
    starts[index] = ttls[index] !== 0 ? perf.now() : 0;
  });
  __privateSet(this, _statusTTL, (status2, index) => {
    if (ttls[index]) {
      const ttl = ttls[index];
      const start = starts[index];
      if (!ttl || !start)
        return;
      status2.ttl = ttl;
      status2.start = start;
      status2.now = cachedNow || getNow();
      const age = status2.now - start;
      status2.remainingTTL = ttl - age;
    }
  });
  let cachedNow = 0;
  const getNow = () => {
    const n2 = perf.now();
    if (this.ttlResolution > 0) {
      cachedNow = n2;
      const t2 = setTimeout(() => cachedNow = 0, this.ttlResolution);
      if (t2.unref) {
        t2.unref();
      }
    }
    return n2;
  };
  this.getRemainingTTL = (key) => {
    const index = __privateGet(this, _keyMap).get(key);
    if (index === void 0) {
      return 0;
    }
    const ttl = ttls[index];
    const start = starts[index];
    if (!ttl || !start) {
      return Infinity;
    }
    const age = (cachedNow || getNow()) - start;
    return ttl - age;
  };
  __privateSet(this, _isStale, (index) => {
    const s = starts[index];
    const t2 = ttls[index];
    return !!t2 && !!s && (cachedNow || getNow()) - s > t2;
  });
};
_updateItemAge = new WeakMap();
_statusTTL = new WeakMap();
_setItemTTL = new WeakMap();
_isStale = new WeakMap();
initializeSizeTracking_fn = function() {
  const sizes = new ZeroArray(__privateGet(this, _max));
  __privateSet(this, _calculatedSize, 0);
  __privateSet(this, _sizes, sizes);
  __privateSet(this, _removeItemSize, (index) => {
    __privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) - sizes[index]);
    sizes[index] = 0;
  });
  __privateSet(this, _requireSize, (k, v, size, sizeCalculation) => {
    if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
      return 0;
    }
    if (!isPosInt(size)) {
      if (sizeCalculation) {
        if (typeof sizeCalculation !== "function") {
          throw new TypeError("sizeCalculation must be a function");
        }
        size = sizeCalculation(v, k);
        if (!isPosInt(size)) {
          throw new TypeError("sizeCalculation return invalid (expect positive integer)");
        }
      } else {
        throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
      }
    }
    return size;
  });
  __privateSet(this, _addItemSize, (index, size, status2) => {
    sizes[index] = size;
    if (__privateGet(this, _maxSize)) {
      const maxSize = __privateGet(this, _maxSize) - sizes[index];
      while (__privateGet(this, _calculatedSize) > maxSize) {
        __privateMethod(this, _LRUCache_instances, evict_fn).call(this, true);
      }
    }
    __privateSet(this, _calculatedSize, __privateGet(this, _calculatedSize) + sizes[index]);
    if (status2) {
      status2.entrySize = size;
      status2.totalCalculatedSize = __privateGet(this, _calculatedSize);
    }
  });
};
_removeItemSize = new WeakMap();
_addItemSize = new WeakMap();
_requireSize = new WeakMap();
indexes_fn = function* ({ allowStale = this.allowStale } = {}) {
  if (__privateGet(this, _size)) {
    for (let i = __privateGet(this, _tail); true; ) {
      if (!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i)) {
        break;
      }
      if (allowStale || !__privateGet(this, _isStale).call(this, i)) {
        yield i;
      }
      if (i === __privateGet(this, _head)) {
        break;
      } else {
        i = __privateGet(this, _prev)[i];
      }
    }
  }
};
rindexes_fn = function* ({ allowStale = this.allowStale } = {}) {
  if (__privateGet(this, _size)) {
    for (let i = __privateGet(this, _head); true; ) {
      if (!__privateMethod(this, _LRUCache_instances, isValidIndex_fn).call(this, i)) {
        break;
      }
      if (allowStale || !__privateGet(this, _isStale).call(this, i)) {
        yield i;
      }
      if (i === __privateGet(this, _tail)) {
        break;
      } else {
        i = __privateGet(this, _next)[i];
      }
    }
  }
};
isValidIndex_fn = function(index) {
  return index !== void 0 && __privateGet(this, _keyMap).get(__privateGet(this, _keyList)[index]) === index;
};
evict_fn = function(free) {
  var _a4, _b3;
  const head = __privateGet(this, _head);
  const k = __privateGet(this, _keyList)[head];
  const v = __privateGet(this, _valList)[head];
  if (__privateGet(this, _hasFetchMethod) && __privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
    v.__abortController.abort(new Error("evicted"));
  } else if (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) {
    if (__privateGet(this, _hasDispose)) {
      (_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, v, k, "evict");
    }
    if (__privateGet(this, _hasDisposeAfter)) {
      (_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([v, k, "evict"]);
    }
  }
  __privateGet(this, _removeItemSize).call(this, head);
  if (free) {
    __privateGet(this, _keyList)[head] = void 0;
    __privateGet(this, _valList)[head] = void 0;
    __privateGet(this, _free).push(head);
  }
  if (__privateGet(this, _size) === 1) {
    __privateSet(this, _head, __privateSet(this, _tail, 0));
    __privateGet(this, _free).length = 0;
  } else {
    __privateSet(this, _head, __privateGet(this, _next)[head]);
  }
  __privateGet(this, _keyMap).delete(k);
  __privateWrapper(this, _size)._--;
  return head;
};
backgroundFetch_fn = function(k, index, options2, context) {
  const v = index === void 0 ? void 0 : __privateGet(this, _valList)[index];
  if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
    return v;
  }
  const ac = new AC();
  const { signal } = options2;
  signal == null ? void 0 : signal.addEventListener("abort", () => ac.abort(signal.reason), {
    signal: ac.signal
  });
  const fetchOpts = {
    signal: ac.signal,
    options: options2,
    context
  };
  const cb = (v2, updateCache = false) => {
    const { aborted } = ac.signal;
    const ignoreAbort = options2.ignoreFetchAbort && v2 !== void 0;
    if (options2.status) {
      if (aborted && !updateCache) {
        options2.status.fetchAborted = true;
        options2.status.fetchError = ac.signal.reason;
        if (ignoreAbort)
          options2.status.fetchAbortIgnored = true;
      } else {
        options2.status.fetchResolved = true;
      }
    }
    if (aborted && !ignoreAbort && !updateCache) {
      return fetchFail(ac.signal.reason);
    }
    const bf2 = p;
    if (__privateGet(this, _valList)[index] === p) {
      if (v2 === void 0) {
        if (bf2.__staleWhileFetching) {
          __privateGet(this, _valList)[index] = bf2.__staleWhileFetching;
        } else {
          __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch");
        }
      } else {
        if (options2.status)
          options2.status.fetchUpdated = true;
        this.set(k, v2, fetchOpts.options);
      }
    }
    return v2;
  };
  const eb = (er) => {
    if (options2.status) {
      options2.status.fetchRejected = true;
      options2.status.fetchError = er;
    }
    return fetchFail(er);
  };
  const fetchFail = (er) => {
    const { aborted } = ac.signal;
    const allowStaleAborted = aborted && options2.allowStaleOnFetchAbort;
    const allowStale = allowStaleAborted || options2.allowStaleOnFetchRejection;
    const noDelete = allowStale || options2.noDeleteOnFetchRejection;
    const bf2 = p;
    if (__privateGet(this, _valList)[index] === p) {
      const del = !noDelete || bf2.__staleWhileFetching === void 0;
      if (del) {
        __privateMethod(this, _LRUCache_instances, delete_fn).call(this, k, "fetch");
      } else if (!allowStaleAborted) {
        __privateGet(this, _valList)[index] = bf2.__staleWhileFetching;
      }
    }
    if (allowStale) {
      if (options2.status && bf2.__staleWhileFetching !== void 0) {
        options2.status.returnedStale = true;
      }
      return bf2.__staleWhileFetching;
    } else if (bf2.__returned === bf2) {
      throw er;
    }
  };
  const pcall = (res, rej) => {
    var _a4;
    const fmp = (_a4 = __privateGet(this, _fetchMethod)) == null ? void 0 : _a4.call(this, k, v, fetchOpts);
    if (fmp && fmp instanceof Promise) {
      fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
    }
    ac.signal.addEventListener("abort", () => {
      if (!options2.ignoreFetchAbort || options2.allowStaleOnFetchAbort) {
        res(void 0);
        if (options2.allowStaleOnFetchAbort) {
          res = (v2) => cb(v2, true);
        }
      }
    });
  };
  if (options2.status)
    options2.status.fetchDispatched = true;
  const p = new Promise(pcall).then(cb, eb);
  const bf = Object.assign(p, {
    __abortController: ac,
    __staleWhileFetching: v,
    __returned: void 0
  });
  if (index === void 0) {
    this.set(k, bf, { ...fetchOpts.options, status: void 0 });
    index = __privateGet(this, _keyMap).get(k);
  } else {
    __privateGet(this, _valList)[index] = bf;
  }
  return bf;
};
isBackgroundFetch_fn = function(p) {
  if (!__privateGet(this, _hasFetchMethod))
    return false;
  const b = p;
  return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
};
connect_fn = function(p, n2) {
  __privateGet(this, _prev)[n2] = p;
  __privateGet(this, _next)[p] = n2;
};
moveToTail_fn = function(index) {
  if (index !== __privateGet(this, _tail)) {
    if (index === __privateGet(this, _head)) {
      __privateSet(this, _head, __privateGet(this, _next)[index]);
    } else {
      __privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _prev)[index], __privateGet(this, _next)[index]);
    }
    __privateMethod(this, _LRUCache_instances, connect_fn).call(this, __privateGet(this, _tail), index);
    __privateSet(this, _tail, index);
  }
};
delete_fn = function(k, reason) {
  var _a4, _b3, _c2, _d2;
  let deleted = false;
  if (__privateGet(this, _size) !== 0) {
    const index = __privateGet(this, _keyMap).get(k);
    if (index !== void 0) {
      deleted = true;
      if (__privateGet(this, _size) === 1) {
        __privateMethod(this, _LRUCache_instances, clear_fn).call(this, reason);
      } else {
        __privateGet(this, _removeItemSize).call(this, index);
        const v = __privateGet(this, _valList)[index];
        if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
          v.__abortController.abort(new Error("deleted"));
        } else if (__privateGet(this, _hasDispose) || __privateGet(this, _hasDisposeAfter)) {
          if (__privateGet(this, _hasDispose)) {
            (_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, v, k, reason);
          }
          if (__privateGet(this, _hasDisposeAfter)) {
            (_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([v, k, reason]);
          }
        }
        __privateGet(this, _keyMap).delete(k);
        __privateGet(this, _keyList)[index] = void 0;
        __privateGet(this, _valList)[index] = void 0;
        if (index === __privateGet(this, _tail)) {
          __privateSet(this, _tail, __privateGet(this, _prev)[index]);
        } else if (index === __privateGet(this, _head)) {
          __privateSet(this, _head, __privateGet(this, _next)[index]);
        } else {
          const pi = __privateGet(this, _prev)[index];
          __privateGet(this, _next)[pi] = __privateGet(this, _next)[index];
          const ni = __privateGet(this, _next)[index];
          __privateGet(this, _prev)[ni] = __privateGet(this, _prev)[index];
        }
        __privateWrapper(this, _size)._--;
        __privateGet(this, _free).push(index);
      }
    }
  }
  if (__privateGet(this, _hasDisposeAfter) && ((_c2 = __privateGet(this, _disposed)) == null ? void 0 : _c2.length)) {
    const dt = __privateGet(this, _disposed);
    let task;
    while (task = dt == null ? void 0 : dt.shift()) {
      (_d2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _d2.call(this, ...task);
    }
  }
  return deleted;
};
clear_fn = function(reason) {
  var _a4, _b3, _c2;
  for (const index of __privateMethod(this, _LRUCache_instances, rindexes_fn).call(this, { allowStale: true })) {
    const v = __privateGet(this, _valList)[index];
    if (__privateMethod(this, _LRUCache_instances, isBackgroundFetch_fn).call(this, v)) {
      v.__abortController.abort(new Error("deleted"));
    } else {
      const k = __privateGet(this, _keyList)[index];
      if (__privateGet(this, _hasDispose)) {
        (_a4 = __privateGet(this, _dispose)) == null ? void 0 : _a4.call(this, v, k, reason);
      }
      if (__privateGet(this, _hasDisposeAfter)) {
        (_b3 = __privateGet(this, _disposed)) == null ? void 0 : _b3.push([v, k, reason]);
      }
    }
  }
  __privateGet(this, _keyMap).clear();
  __privateGet(this, _valList).fill(void 0);
  __privateGet(this, _keyList).fill(void 0);
  if (__privateGet(this, _ttls) && __privateGet(this, _starts)) {
    __privateGet(this, _ttls).fill(0);
    __privateGet(this, _starts).fill(0);
  }
  if (__privateGet(this, _sizes)) {
    __privateGet(this, _sizes).fill(0);
  }
  __privateSet(this, _head, 0);
  __privateSet(this, _tail, 0);
  __privateGet(this, _free).length = 0;
  __privateSet(this, _calculatedSize, 0);
  __privateSet(this, _size, 0);
  if (__privateGet(this, _hasDisposeAfter) && __privateGet(this, _disposed)) {
    const dt = __privateGet(this, _disposed);
    let task;
    while (task = dt == null ? void 0 : dt.shift()) {
      (_c2 = __privateGet(this, _disposeAfter)) == null ? void 0 : _c2.call(this, ...task);
    }
  }
};
var LRUCache = _LRUCache;
var proc = typeof process === "object" && process ? process : {
  stdout: null,
  stderr: null
};
var isStream = (s) => !!s && typeof s === "object" && (s instanceof Minipass || s instanceof import_node_stream.default || isReadable(s) || isWritable(s));
var isReadable = (s) => !!s && typeof s === "object" && s instanceof import_node_events.EventEmitter && typeof s.pipe === "function" && // node core Writable streams have a pipe() method, but it throws
s.pipe !== import_node_stream.default.Writable.prototype.pipe;
var isWritable = (s) => !!s && typeof s === "object" && s instanceof import_node_events.EventEmitter && typeof s.write === "function" && typeof s.end === "function";
var EOF = Symbol("EOF");
var MAYBE_EMIT_END = Symbol("maybeEmitEnd");
var EMITTED_END = Symbol("emittedEnd");
var EMITTING_END = Symbol("emittingEnd");
var EMITTED_ERROR = Symbol("emittedError");
var CLOSED$1 = Symbol("closed");
var READ = Symbol("read");
var FLUSH = Symbol("flush");
var FLUSHCHUNK = Symbol("flushChunk");
var ENCODING$1 = Symbol("encoding");
var DECODER = Symbol("decoder");
var FLOWING = Symbol("flowing");
var PAUSED = Symbol("paused");
var RESUME = Symbol("resume");
var BUFFER = Symbol("buffer");
var PIPES = Symbol("pipes");
var BUFFERLENGTH = Symbol("bufferLength");
var BUFFERPUSH = Symbol("bufferPush");
var BUFFERSHIFT = Symbol("bufferShift");
var OBJECTMODE = Symbol("objectMode");
var DESTROYED = Symbol("destroyed");
var ERROR = Symbol("error");
var EMITDATA = Symbol("emitData");
var EMITEND = Symbol("emitEnd");
var EMITEND2 = Symbol("emitEnd2");
var ASYNC = Symbol("async");
var ABORT = Symbol("abort");
var ABORTED = Symbol("aborted");
var SIGNAL = Symbol("signal");
var DATALISTENERS = Symbol("dataListeners");
var DISCARDED = Symbol("discarded");
var defer$3 = (fn) => Promise.resolve().then(fn);
var nodefer = (fn) => fn();
var isEndish = (ev) => ev === "end" || ev === "finish" || ev === "prefinish";
var isArrayBufferLike = (b) => b instanceof ArrayBuffer || !!b && typeof b === "object" && b.constructor && b.constructor.name === "ArrayBuffer" && b.byteLength >= 0;
var isArrayBufferView = (b) => !Buffer.isBuffer(b) && ArrayBuffer.isView(b);
var Pipe = class {
  constructor(src2, dest, opts) {
    __publicField(this, "src");
    __publicField(this, "dest");
    __publicField(this, "opts");
    __publicField(this, "ondrain");
    this.src = src2;
    this.dest = dest;
    this.opts = opts;
    this.ondrain = () => src2[RESUME]();
    this.dest.on("drain", this.ondrain);
  }
  unpipe() {
    this.dest.removeListener("drain", this.ondrain);
  }
  // only here for the prototype
  /* c8 ignore start */
  proxyErrors(_er) {
  }
  /* c8 ignore stop */
  end() {
    this.unpipe();
    if (this.opts.end)
      this.dest.end();
  }
};
var PipeProxyErrors = class extends Pipe {
  unpipe() {
    this.src.removeListener("error", this.proxyErrors);
    super.unpipe();
  }
  constructor(src2, dest, opts) {
    super(src2, dest, opts);
    this.proxyErrors = (er) => dest.emit("error", er);
    src2.on("error", this.proxyErrors);
  }
};
var isObjectModeOptions = (o2) => !!o2.objectMode;
var isEncodingOptions = (o2) => !o2.objectMode && !!o2.encoding && o2.encoding !== "buffer";
var _a3, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
var Minipass = class extends import_node_events.EventEmitter {
  /**
   * If `RType` is Buffer, then options do not need to be provided.
   * Otherwise, an options object must be provided to specify either
   * {@link Minipass.SharedOptions.objectMode} or
   * {@link Minipass.SharedOptions.encoding}, as appropriate.
   */
  constructor(...args) {
    const options2 = args[0] || {};
    super();
    __publicField(this, _s, false);
    __publicField(this, _r, false);
    __publicField(this, _q, []);
    __publicField(this, _p, []);
    __publicField(this, _o);
    __publicField(this, _n);
    __publicField(this, _m);
    __publicField(this, _l);
    __publicField(this, _k, false);
    __publicField(this, _j, false);
    __publicField(this, _i, false);
    __publicField(this, _h, false);
    __publicField(this, _g, null);
    __publicField(this, _f, 0);
    __publicField(this, _e, false);
    __publicField(this, _d);
    __publicField(this, _c, false);
    __publicField(this, _b2, 0);
    __publicField(this, _a3, false);
    /**
     * true if the stream can be written
     */
    __publicField(this, "writable", true);
    /**
     * true if the stream can be read
     */
    __publicField(this, "readable", true);
    if (options2.objectMode && typeof options2.encoding === "string") {
      throw new TypeError("Encoding and objectMode may not be used together");
    }
    if (isObjectModeOptions(options2)) {
      this[OBJECTMODE] = true;
      this[ENCODING$1] = null;
    } else if (isEncodingOptions(options2)) {
      this[ENCODING$1] = options2.encoding;
      this[OBJECTMODE] = false;
    } else {
      this[OBJECTMODE] = false;
      this[ENCODING$1] = null;
    }
    this[ASYNC] = !!options2.async;
    this[DECODER] = this[ENCODING$1] ? new import_node_string_decoder.StringDecoder(this[ENCODING$1]) : null;
    if (options2 && options2.debugExposeBuffer === true) {
      Object.defineProperty(this, "buffer", { get: () => this[BUFFER] });
    }
    if (options2 && options2.debugExposePipes === true) {
      Object.defineProperty(this, "pipes", { get: () => this[PIPES] });
    }
    const { signal } = options2;
    if (signal) {
      this[SIGNAL] = signal;
      if (signal.aborted) {
        this[ABORT]();
      } else {
        signal.addEventListener("abort", () => this[ABORT]());
      }
    }
  }
  /**
   * The amount of data stored in the buffer waiting to be read.
   *
   * For Buffer strings, this will be the total byte length.
   * For string encoding streams, this will be the string character length,
   * according to JavaScript's `string.length` logic.
   * For objectMode streams, this is a count of the items waiting to be
   * emitted.
   */
  get bufferLength() {
    return this[BUFFERLENGTH];
  }
  /**
   * The `BufferEncoding` currently in use, or `null`
   */
  get encoding() {
    return this[ENCODING$1];
  }
  /**
   * @deprecated - This is a read only property
   */
  set encoding(_enc) {
    throw new Error("Encoding must be set at instantiation time");
  }
  /**
   * @deprecated - Encoding may only be set at instantiation time
   */
  setEncoding(_enc) {
    throw new Error("Encoding must be set at instantiation time");
  }
  /**
   * True if this is an objectMode stream
   */
  get objectMode() {
    return this[OBJECTMODE];
  }
  /**
   * @deprecated - This is a read-only property
   */
  set objectMode(_om) {
    throw new Error("objectMode must be set at instantiation time");
  }
  /**
   * true if this is an async stream
   */
  get ["async"]() {
    return this[ASYNC];
  }
  /**
   * Set to true to make this stream async.
   *
   * Once set, it cannot be unset, as this would potentially cause incorrect
   * behavior.  Ie, a sync stream can be made async, but an async stream
   * cannot be safely made sync.
   */
  set ["async"](a) {
    this[ASYNC] = this[ASYNC] || !!a;
  }
  // drop everything and get out of the flow completely
  [(_s = FLOWING, _r = PAUSED, _q = PIPES, _p = BUFFER, _o = OBJECTMODE, _n = ENCODING$1, _m = ASYNC, _l = DECODER, _k = EOF, _j = EMITTED_END, _i = EMITTING_END, _h = CLOSED$1, _g = EMITTED_ERROR, _f = BUFFERLENGTH, _e = DESTROYED, _d = SIGNAL, _c = ABORTED, _b2 = DATALISTENERS, _a3 = DISCARDED, ABORT)]() {
    var _a4, _b3;
    this[ABORTED] = true;
    this.emit("abort", (_a4 = this[SIGNAL]) == null ? void 0 : _a4.reason);
    this.destroy((_b3 = this[SIGNAL]) == null ? void 0 : _b3.reason);
  }
  /**
   * True if the stream has been aborted.
   */
  get aborted() {
    return this[ABORTED];
  }
  /**
   * No-op setter. Stream aborted status is set via the AbortSignal provided
   * in the constructor options.
   */
  set aborted(_) {
  }
  write(chunk, encoding, cb) {
    var _a4;
    if (this[ABORTED])
      return false;
    if (this[EOF])
      throw new Error("write after end");
    if (this[DESTROYED]) {
      this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" }));
      return true;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = "utf8";
    }
    if (!encoding)
      encoding = "utf8";
    const fn = this[ASYNC] ? defer$3 : nodefer;
    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
      if (isArrayBufferView(chunk)) {
        chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
      } else if (isArrayBufferLike(chunk)) {
        chunk = Buffer.from(chunk);
      } else if (typeof chunk !== "string") {
        throw new Error("Non-contiguous data written to non-objectMode stream");
      }
    }
    if (this[OBJECTMODE]) {
      if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
        this[FLUSH](true);
      if (this[FLOWING])
        this.emit("data", chunk);
      else
        this[BUFFERPUSH](chunk);
      if (this[BUFFERLENGTH] !== 0)
        this.emit("readable");
      if (cb)
        fn(cb);
      return this[FLOWING];
    }
    if (!chunk.length) {
      if (this[BUFFERLENGTH] !== 0)
        this.emit("readable");
      if (cb)
        fn(cb);
      return this[FLOWING];
    }
    if (typeof chunk === "string" && // unless it is a string already ready for us to use
    !(encoding === this[ENCODING$1] && !((_a4 = this[DECODER]) == null ? void 0 : _a4.lastNeed))) {
      chunk = Buffer.from(chunk, encoding);
    }
    if (Buffer.isBuffer(chunk) && this[ENCODING$1]) {
      chunk = this[DECODER].write(chunk);
    }
    if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
      this[FLUSH](true);
    if (this[FLOWING])
      this.emit("data", chunk);
    else
      this[BUFFERPUSH](chunk);
    if (this[BUFFERLENGTH] !== 0)
      this.emit("readable");
    if (cb)
      fn(cb);
    return this[FLOWING];
  }
  /**
   * Low-level explicit read method.
   *
   * In objectMode, the argument is ignored, and one item is returned if
   * available.
   *
   * `n` is the number of bytes (or in the case of encoding streams,
   * characters) to consume. If `n` is not provided, then the entire buffer
   * is returned, or `null` is returned if no data is available.
   *
   * If `n` is greater that the amount of data in the internal buffer,
   * then `null` is returned.
   */
  read(n2) {
    if (this[DESTROYED])
      return null;
    this[DISCARDED] = false;
    if (this[BUFFERLENGTH] === 0 || n2 === 0 || n2 && n2 > this[BUFFERLENGTH]) {
      this[MAYBE_EMIT_END]();
      return null;
    }
    if (this[OBJECTMODE])
      n2 = null;
    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {
      this[BUFFER] = [
        this[ENCODING$1] ? this[BUFFER].join("") : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])
      ];
    }
    const ret = this[READ](n2 || null, this[BUFFER][0]);
    this[MAYBE_EMIT_END]();
    return ret;
  }
  [READ](n2, chunk) {
    if (this[OBJECTMODE])
      this[BUFFERSHIFT]();
    else {
      const c = chunk;
      if (n2 === c.length || n2 === null)
        this[BUFFERSHIFT]();
      else if (typeof c === "string") {
        this[BUFFER][0] = c.slice(n2);
        chunk = c.slice(0, n2);
        this[BUFFERLENGTH] -= n2;
      } else {
        this[BUFFER][0] = c.subarray(n2);
        chunk = c.subarray(0, n2);
        this[BUFFERLENGTH] -= n2;
      }
    }
    this.emit("data", chunk);
    if (!this[BUFFER].length && !this[EOF])
      this.emit("drain");
    return chunk;
  }
  end(chunk, encoding, cb) {
    if (typeof chunk === "function") {
      cb = chunk;
      chunk = void 0;
    }
    if (typeof encoding === "function") {
      cb = encoding;
      encoding = "utf8";
    }
    if (chunk !== void 0)
      this.write(chunk, encoding);
    if (cb)
      this.once("end", cb);
    this[EOF] = true;
    this.writable = false;
    if (this[FLOWING] || !this[PAUSED])
      this[MAYBE_EMIT_END]();
    return this;
  }
  // don't let the internal resume be overwritten
  [RESUME]() {
    if (this[DESTROYED])
      return;
    if (!this[DATALISTENERS] && !this[PIPES].length) {
      this[DISCARDED] = true;
    }
    this[PAUSED] = false;
    this[FLOWING] = true;
    this.emit("resume");
    if (this[BUFFER].length)
      this[FLUSH]();
    else if (this[EOF])
      this[MAYBE_EMIT_END]();
    else
      this.emit("drain");
  }
  /**
   * Resume the stream if it is currently in a paused state
   *
   * If called when there are no pipe destinations or `data` event listeners,
   * this will place the stream in a "discarded" state, where all data will
   * be thrown away. The discarded state is removed if a pipe destination or
   * data handler is added, if pause() is called, or if any synchronous or
   * asynchronous iteration is started.
   */
  resume() {
    return this[RESUME]();
  }
  /**
   * Pause the stream
   */
  pause() {
    this[FLOWING] = false;
    this[PAUSED] = true;
    this[DISCARDED] = false;
  }
  /**
   * true if the stream has been forcibly destroyed
   */
  get destroyed() {
    return this[DESTROYED];
  }
  /**
   * true if the stream is currently in a flowing state, meaning that
   * any writes will be immediately emitted.
   */
  get flowing() {
    return this[FLOWING];
  }
  /**
   * true if the stream is currently in a paused state
   */
  get paused() {
    return this[PAUSED];
  }
  [BUFFERPUSH](chunk) {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] += 1;
    else
      this[BUFFERLENGTH] += chunk.length;
    this[BUFFER].push(chunk);
  }
  [BUFFERSHIFT]() {
    if (this[OBJECTMODE])
      this[BUFFERLENGTH] -= 1;
    else
      this[BUFFERLENGTH] -= this[BUFFER][0].length;
    return this[BUFFER].shift();
  }
  [FLUSH](noDrain = false) {
    do {
    } while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
    if (!noDrain && !this[BUFFER].length && !this[EOF])
      this.emit("drain");
  }
  [FLUSHCHUNK](chunk) {
    this.emit("data", chunk);
    return this[FLOWING];
  }
  /**
   * Pipe all data emitted by this stream into the destination provided.
   *
   * Triggers the flow of data.
   */
  pipe(dest, opts) {
    if (this[DESTROYED])
      return dest;
    this[DISCARDED] = false;
    const ended = this[EMITTED_END];
    opts = opts || {};
    if (dest === proc.stdout || dest === proc.stderr)
      opts.end = false;
    else
      opts.end = opts.end !== false;
    opts.proxyErrors = !!opts.proxyErrors;
    if (ended) {
      if (opts.end)
        dest.end();
    } else {
      this[PIPES].push(!opts.proxyErrors ? new Pipe(this, dest, opts) : new PipeProxyErrors(this, dest, opts));
      if (this[ASYNC])
        defer$3(() => this[RESUME]());
      else
        this[RESUME]();
    }
    return dest;
  }
  /**
   * Fully unhook a piped destination stream.
   *
   * If the destination stream was the only consumer of this stream (ie,
   * there are no other piped destinations or `'data'` event listeners)
   * then the flow of data will stop until there is another consumer or
   * {@link Minipass#resume} is explicitly called.
   */
  unpipe(dest) {
    const p = this[PIPES].find((p2) => p2.dest === dest);
    if (p) {
      if (this[PIPES].length === 1) {
        if (this[FLOWING] && this[DATALISTENERS] === 0) {
          this[FLOWING] = false;
        }
        this[PIPES] = [];
      } else
        this[PIPES].splice(this[PIPES].indexOf(p), 1);
      p.unpipe();
    }
  }
  /**
   * Alias for {@link Minipass#on}
   */
  addListener(ev, handler) {
    return this.on(ev, handler);
  }
  /**
   * Mostly identical to `EventEmitter.on`, with the following
   * behavior differences to prevent data loss and unnecessary hangs:
   *
   * - Adding a 'data' event handler will trigger the flow of data
   *
   * - Adding a 'readable' event handler when there is data waiting to be read
   *   will cause 'readable' to be emitted immediately.
   *
   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has
   *   already passed will cause the event to be emitted immediately and all
   *   handlers removed.
   *
   * - Adding an 'error' event handler after an error has been emitted will
   *   cause the event to be re-emitted immediately with the error previously
   *   raised.
   */
  on(ev, handler) {
    const ret = super.on(ev, handler);
    if (ev === "data") {
      this[DISCARDED] = false;
      this[DATALISTENERS]++;
      if (!this[PIPES].length && !this[FLOWING]) {
        this[RESUME]();
      }
    } else if (ev === "readable" && this[BUFFERLENGTH] !== 0) {
      super.emit("readable");
    } else if (isEndish(ev) && this[EMITTED_END]) {
      super.emit(ev);
      this.removeAllListeners(ev);
    } else if (ev === "error" && this[EMITTED_ERROR]) {
      const h = handler;
      if (this[ASYNC])
        defer$3(() => h.call(this, this[EMITTED_ERROR]));
      else
        h.call(this, this[EMITTED_ERROR]);
    }
    return ret;
  }
  /**
   * Alias for {@link Minipass#off}
   */
  removeListener(ev, handler) {
    return this.off(ev, handler);
  }
  /**
   * Mostly identical to `EventEmitter.off`
   *
   * If a 'data' event handler is removed, and it was the last consumer
   * (ie, there are no pipe destinations or other 'data' event listeners),
   * then the flow of data will stop until there is another consumer or
   * {@link Minipass#resume} is explicitly called.
   */
  off(ev, handler) {
    const ret = super.off(ev, handler);
    if (ev === "data") {
      this[DATALISTENERS] = this.listeners("data").length;
      if (this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length) {
        this[FLOWING] = false;
      }
    }
    return ret;
  }
  /**
   * Mostly identical to `EventEmitter.removeAllListeners`
   *
   * If all 'data' event handlers are removed, and they were the last consumer
   * (ie, there are no pipe destinations), then the flow of data will stop
   * until there is another consumer or {@link Minipass#resume} is explicitly
   * called.
   */
  removeAllListeners(ev) {
    const ret = super.removeAllListeners(ev);
    if (ev === "data" || ev === void 0) {
      this[DATALISTENERS] = 0;
      if (!this[DISCARDED] && !this[PIPES].length) {
        this[FLOWING] = false;
      }
    }
    return ret;
  }
  /**
   * true if the 'end' event has been emitted
   */
  get emittedEnd() {
    return this[EMITTED_END];
  }
  [MAYBE_EMIT_END]() {
    if (!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF]) {
      this[EMITTING_END] = true;
      this.emit("end");
      this.emit("prefinish");
      this.emit("finish");
      if (this[CLOSED$1])
        this.emit("close");
      this[EMITTING_END] = false;
    }
  }
  /**
   * Mostly identical to `EventEmitter.emit`, with the following
   * behavior differences to prevent data loss and unnecessary hangs:
   *
   * If the stream has been destroyed, and the event is something other
   * than 'close' or 'error', then `false` is returned and no handlers
   * are called.
   *
   * If the event is 'end', and has already been emitted, then the event
   * is ignored. If the stream is in a paused or non-flowing state, then
   * the event will be deferred until data flow resumes. If the stream is
   * async, then handlers will be called on the next tick rather than
   * immediately.
   *
   * If the event is 'close', and 'end' has not yet been emitted, then
   * the event will be deferred until after 'end' is emitted.
   *
   * If the event is 'error', and an AbortSignal was provided for the stream,
   * and there are no listeners, then the event is ignored, matching the
   * behavior of node core streams in the presense of an AbortSignal.
   *
   * If the event is 'finish' or 'prefinish', then all listeners will be
   * removed after emitting the event, to prevent double-firing.
   */
  emit(ev, ...args) {
    const data = args[0];
    if (ev !== "error" && ev !== "close" && ev !== DESTROYED && this[DESTROYED]) {
      return false;
    } else if (ev === "data") {
      return !this[OBJECTMODE] && !data ? false : this[ASYNC] ? (defer$3(() => this[EMITDATA](data)), true) : this[EMITDATA](data);
    } else if (ev === "end") {
      return this[EMITEND]();
    } else if (ev === "close") {
      this[CLOSED$1] = true;
      if (!this[EMITTED_END] && !this[DESTROYED])
        return false;
      const ret2 = super.emit("close");
      this.removeAllListeners("close");
      return ret2;
    } else if (ev === "error") {
      this[EMITTED_ERROR] = data;
      super.emit(ERROR, data);
      const ret2 = !this[SIGNAL] || this.listeners("error").length ? super.emit("error", data) : false;
      this[MAYBE_EMIT_END]();
      return ret2;
    } else if (ev === "resume") {
      const ret2 = super.emit("resume");
      this[MAYBE_EMIT_END]();
      return ret2;
    } else if (ev === "finish" || ev === "prefinish") {
      const ret2 = super.emit(ev);
      this.removeAllListeners(ev);
      return ret2;
    }
    const ret = super.emit(ev, ...args);
    this[MAYBE_EMIT_END]();
    return ret;
  }
  [EMITDATA](data) {
    for (const p of this[PIPES]) {
      if (p.dest.write(data) === false)
        this.pause();
    }
    const ret = this[DISCARDED] ? false : super.emit("data", data);
    this[MAYBE_EMIT_END]();
    return ret;
  }
  [EMITEND]() {
    if (this[EMITTED_END])
      return false;
    this[EMITTED_END] = true;
    this.readable = false;
    return this[ASYNC] ? (defer$3(() => this[EMITEND2]()), true) : this[EMITEND2]();
  }
  [EMITEND2]() {
    if (this[DECODER]) {
      const data = this[DECODER].end();
      if (data) {
        for (const p of this[PIPES]) {
          p.dest.write(data);
        }
        if (!this[DISCARDED])
          super.emit("data", data);
      }
    }
    for (const p of this[PIPES]) {
      p.end();
    }
    const ret = super.emit("end");
    this.removeAllListeners("end");
    return ret;
  }
  /**
   * Return a Promise that resolves to an array of all emitted data once
   * the stream ends.
   */
  async collect() {
    const buf = Object.assign([], {
      dataLength: 0
    });
    if (!this[OBJECTMODE])
      buf.dataLength = 0;
    const p = this.promise();
    this.on("data", (c) => {
      buf.push(c);
      if (!this[OBJECTMODE])
        buf.dataLength += c.length;
    });
    await p;
    return buf;
  }
  /**
   * Return a Promise that resolves to the concatenation of all emitted data
   * once the stream ends.
   *
   * Not allowed on objectMode streams.
   */
  async concat() {
    if (this[OBJECTMODE]) {
      throw new Error("cannot concat in objectMode");
    }
    const buf = await this.collect();
    return this[ENCODING$1] ? buf.join("") : Buffer.concat(buf, buf.dataLength);
  }
  /**
   * Return a void Promise that resolves once the stream ends.
   */
  async promise() {
    return new Promise((resolve3, reject) => {
      this.on(DESTROYED, () => reject(new Error("stream destroyed")));
      this.on("error", (er) => reject(er));
      this.on("end", () => resolve3());
    });
  }
  /**
   * Asynchronous `for await of` iteration.
   *
   * This will continue emitting all chunks until the stream terminates.
   */
  [Symbol.asyncIterator]() {
    this[DISCARDED] = false;
    let stopped = false;
    const stop = async () => {
      this.pause();
      stopped = true;
      return { value: void 0, done: true };
    };
    const next = () => {
      if (stopped)
        return stop();
      const res = this.read();
      if (res !== null)
        return Promise.resolve({ done: false, value: res });
      if (this[EOF])
        return stop();
      let resolve3;
      let reject;
      const onerr = (er) => {
        this.off("data", ondata);
        this.off("end", onend);
        this.off(DESTROYED, ondestroy);
        stop();
        reject(er);
      };
      const ondata = (value2) => {
        this.off("error", onerr);
        this.off("end", onend);
        this.off(DESTROYED, ondestroy);
        this.pause();
        resolve3({ value: value2, done: !!this[EOF] });
      };
      const onend = () => {
        this.off("error", onerr);
        this.off("data", ondata);
        this.off(DESTROYED, ondestroy);
        stop();
        resolve3({ done: true, value: void 0 });
      };
      const ondestroy = () => onerr(new Error("stream destroyed"));
      return new Promise((res2, rej) => {
        reject = rej;
        resolve3 = res2;
        this.once(DESTROYED, ondestroy);
        this.once("error", onerr);
        this.once("end", onend);
        this.once("data", ondata);
      });
    };
    return {
      next,
      throw: stop,
      return: stop,
      [Symbol.asyncIterator]() {
        return this;
      }
    };
  }
  /**
   * Synchronous `for of` iteration.
   *
   * The iteration will terminate when the internal buffer runs out, even
   * if the stream has not yet terminated.
   */
  [Symbol.iterator]() {
    this[DISCARDED] = false;
    let stopped = false;
    const stop = () => {
      this.pause();
      this.off(ERROR, stop);
      this.off(DESTROYED, stop);
      this.off("end", stop);
      stopped = true;
      return { done: true, value: void 0 };
    };
    const next = () => {
      if (stopped)
        return stop();
      const value2 = this.read();
      return value2 === null ? stop() : { done: false, value: value2 };
    };
    this.once("end", stop);
    this.once(ERROR, stop);
    this.once(DESTROYED, stop);
    return {
      next,
      throw: stop,
      return: stop,
      [Symbol.iterator]() {
        return this;
      }
    };
  }
  /**
   * Destroy a stream, preventing it from being used for any further purpose.
   *
   * If the stream has a `close()` method, then it will be called on
   * destruction.
   *
   * After destruction, any attempt to write data, read data, or emit most
   * events will be ignored.
   *
   * If an error argument is provided, then it will be emitted in an
   * 'error' event.
   */
  destroy(er) {
    if (this[DESTROYED]) {
      if (er)
        this.emit("error", er);
      else
        this.emit(DESTROYED);
      return this;
    }
    this[DESTROYED] = true;
    this[DISCARDED] = true;
    this[BUFFER].length = 0;
    this[BUFFERLENGTH] = 0;
    const wc = this;
    if (typeof wc.close === "function" && !this[CLOSED$1])
      wc.close();
    if (er)
      this.emit("error", er);
    else
      this.emit(DESTROYED);
    return this;
  }
  /**
   * Alias for {@link isStream}
   *
   * Former export location, maintained for backwards compatibility.
   *
   * @deprecated
   */
  static get isStream() {
    return isStream;
  }
};
var realpathSync = import_fs.realpathSync.native;
var defaultFS = {
  lstatSync: import_fs.lstatSync,
  readdir: import_fs.readdir,
  readdirSync: import_fs.readdirSync,
  readlinkSync: import_fs.readlinkSync,
  realpathSync,
  promises: {
    lstat: import_promises.lstat,
    readdir: import_promises.readdir,
    readlink: import_promises.readlink,
    realpath: import_promises.realpath
  }
};
var fsFromOption = (fsOption) => !fsOption || fsOption === defaultFS || fsOption === fs$j ? defaultFS : {
  ...defaultFS,
  ...fsOption,
  promises: {
    ...defaultFS.promises,
    ...fsOption.promises || {}
  }
};
var uncDriveRegexp = /^\\\\\?\\([a-z]:)\\?$/i;
var uncToDrive = (rootPath) => rootPath.replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
var eitherSep = /[\\\/]/;
var UNKNOWN = 0;
var IFIFO = 1;
var IFCHR = 2;
var IFDIR = 4;
var IFBLK = 6;
var IFREG = 8;
var IFLNK = 10;
var IFSOCK = 12;
var IFMT = 15;
var IFMT_UNKNOWN = ~IFMT;
var READDIR_CALLED = 16;
var LSTAT_CALLED = 32;
var ENOTDIR = 64;
var ENOENT = 128;
var ENOREADLINK = 256;
var ENOREALPATH = 512;
var ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH;
var TYPEMASK = 1023;
var entToType = (s) => s.isFile() ? IFREG : s.isDirectory() ? IFDIR : s.isSymbolicLink() ? IFLNK : s.isCharacterDevice() ? IFCHR : s.isBlockDevice() ? IFBLK : s.isSocket() ? IFSOCK : s.isFIFO() ? IFIFO : UNKNOWN;
var normalizeCache = /* @__PURE__ */ new Map();
var normalize = (s) => {
  const c = normalizeCache.get(s);
  if (c)
    return c;
  const n2 = s.normalize("NFKD");
  normalizeCache.set(s, n2);
  return n2;
};
var normalizeNocaseCache = /* @__PURE__ */ new Map();
var normalizeNocase = (s) => {
  const c = normalizeNocaseCache.get(s);
  if (c)
    return c;
  const n2 = normalize(s.toLowerCase());
  normalizeNocaseCache.set(s, n2);
  return n2;
};
var ResolveCache = class extends LRUCache {
  constructor() {
    super({ max: 256 });
  }
};
var ChildrenCache = class extends LRUCache {
  constructor(maxSize = 16 * 1024) {
    super({
      maxSize,
      // parent + children
      sizeCalculation: (a) => a.length + 1
    });
  }
};
var setAsCwd = Symbol("PathScurry setAsCwd");
var _fs, _dev, _mode, _nlink, _uid, _gid, _rdev, _blksize, _ino, _size2, _blocks, _atimeMs, _mtimeMs, _ctimeMs, _birthtimeMs, _atime, _mtime, _ctime, _birthtime, _matchName, _depth, _fullpath, _fullpathPosix, _relative, _relativePosix, _type, _children, _linkTarget, _realpath, _PathBase_instances, resolveParts_fn, readdirSuccess_fn, markENOENT_fn, markChildrenENOENT_fn, markENOREALPATH_fn, markENOTDIR_fn, readdirFail_fn, lstatFail_fn, readlinkFail_fn, readdirAddChild_fn, readdirAddNewChild_fn, readdirMaybePromoteChild_fn, readdirPromoteChild_fn, applyStat_fn, _onReaddirCB, _readdirCBInFlight, callOnReaddirCB_fn, _asyncReaddirInFlight;
var PathBase = class {
  /**
   * Do not create new Path objects directly.  They should always be accessed
   * via the PathScurry class or other methods on the Path class.
   *
   * @internal
   */
  constructor(name2, type = UNKNOWN, root, roots, nocase, children, opts) {
    __privateAdd(this, _PathBase_instances);
    /**
     * the basename of this path
     *
     * **Important**: *always* test the path name against any test string
     * usingthe {@link isNamed} method, and not by directly comparing this
     * string. Otherwise, unicode path strings that the system sees as identical
     * will not be properly treated as the same path, leading to incorrect
     * behavior and possible security issues.
     */
    __publicField(this, "name");
    /**
     * the Path entry corresponding to the path root.
     *
     * @internal
     */
    __publicField(this, "root");
    /**
     * All roots found within the current PathScurry family
     *
     * @internal
     */
    __publicField(this, "roots");
    /**
     * a reference to the parent path, or undefined in the case of root entries
     *
     * @internal
     */
    __publicField(this, "parent");
    /**
     * boolean indicating whether paths are compared case-insensitively
     * @internal
     */
    __publicField(this, "nocase");
    /**
     * boolean indicating that this path is the current working directory
     * of the PathScurry collection that contains it.
     */
    __publicField(this, "isCWD", false);
    // potential default fs override
    __privateAdd(this, _fs);
    // Stats fields
    __privateAdd(this, _dev);
    __privateAdd(this, _mode);
    __privateAdd(this, _nlink);
    __privateAdd(this, _uid);
    __privateAdd(this, _gid);
    __privateAdd(this, _rdev);
    __privateAdd(this, _blksize);
    __privateAdd(this, _ino);
    __privateAdd(this, _size2);
    __privateAdd(this, _blocks);
    __privateAdd(this, _atimeMs);
    __privateAdd(this, _mtimeMs);
    __privateAdd(this, _ctimeMs);
    __privateAdd(this, _birthtimeMs);
    __privateAdd(this, _atime);
    __privateAdd(this, _mtime);
    __privateAdd(this, _ctime);
    __privateAdd(this, _birthtime);
    __privateAdd(this, _matchName);
    __privateAdd(this, _depth);
    __privateAdd(this, _fullpath);
    __privateAdd(this, _fullpathPosix);
    __privateAdd(this, _relative);
    __privateAdd(this, _relativePosix);
    __privateAdd(this, _type);
    __privateAdd(this, _children);
    __privateAdd(this, _linkTarget);
    __privateAdd(this, _realpath);
    __privateAdd(this, _onReaddirCB, []);
    __privateAdd(this, _readdirCBInFlight, false);
    __privateAdd(this, _asyncReaddirInFlight);
    this.name = name2;
    __privateSet(this, _matchName, nocase ? normalizeNocase(name2) : normalize(name2));
    __privateSet(this, _type, type & TYPEMASK);
    this.nocase = nocase;
    this.roots = roots;
    this.root = root || this;
    __privateSet(this, _children, children);
    __privateSet(this, _fullpath, opts.fullpath);
    __privateSet(this, _relative, opts.relative);
    __privateSet(this, _relativePosix, opts.relativePosix);
    this.parent = opts.parent;
    if (this.parent) {
      __privateSet(this, _fs, __privateGet(this.parent, _fs));
    } else {
      __privateSet(this, _fs, fsFromOption(opts.fs));
    }
  }
  get dev() {
    return __privateGet(this, _dev);
  }
  get mode() {
    return __privateGet(this, _mode);
  }
  get nlink() {
    return __privateGet(this, _nlink);
  }
  get uid() {
    return __privateGet(this, _uid);
  }
  get gid() {
    return __privateGet(this, _gid);
  }
  get rdev() {
    return __privateGet(this, _rdev);
  }
  get blksize() {
    return __privateGet(this, _blksize);
  }
  get ino() {
    return __privateGet(this, _ino);
  }
  get size() {
    return __privateGet(this, _size2);
  }
  get blocks() {
    return __privateGet(this, _blocks);
  }
  get atimeMs() {
    return __privateGet(this, _atimeMs);
  }
  get mtimeMs() {
    return __privateGet(this, _mtimeMs);
  }
  get ctimeMs() {
    return __privateGet(this, _ctimeMs);
  }
  get birthtimeMs() {
    return __privateGet(this, _birthtimeMs);
  }
  get atime() {
    return __privateGet(this, _atime);
  }
  get mtime() {
    return __privateGet(this, _mtime);
  }
  get ctime() {
    return __privateGet(this, _ctime);
  }
  get birthtime() {
    return __privateGet(this, _birthtime);
  }
  /**
   * This property is for compatibility with the Dirent class as of
   * Node v20, where Dirent['parentPath'] refers to the path of the
   * directory that was passed to readdir. For root entries, it's the path
   * to the entry itself.
   */
  get parentPath() {
    return (this.parent || this).fullpath();
  }
  /**
   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,
   * this property refers to the *parent* path, not the path object itself.
   */
  get path() {
    return this.parentPath;
  }
  /**
   * Returns the depth of the Path object from its root.
   *
   * For example, a path at `/foo/bar` would have a depth of 2.
   */
  depth() {
    if (__privateGet(this, _depth) !== void 0)
      return __privateGet(this, _depth);
    if (!this.parent)
      return __privateSet(this, _depth, 0);
    return __privateSet(this, _depth, this.parent.depth() + 1);
  }
  /**
   * @internal
   */
  childrenCache() {
    return __privateGet(this, _children);
  }
  /**
   * Get the Path object referenced by the string path, resolved from this Path
   */
  resolve(path3) {
    var _a4;
    if (!path3) {
      return this;
    }
    const rootPath = this.getRootString(path3);
    const dir = path3.substring(rootPath.length);
    const dirParts = dir.split(this.splitSep);
    const result = rootPath ? __privateMethod(_a4 = this.getRoot(rootPath), _PathBase_instances, resolveParts_fn).call(_a4, dirParts) : __privateMethod(this, _PathBase_instances, resolveParts_fn).call(this, dirParts);
    return result;
  }
  /**
   * Returns the cached children Path objects, if still available.  If they
   * have fallen out of the cache, then returns an empty array, and resets the
   * READDIR_CALLED bit, so that future calls to readdir() will require an fs
   * lookup.
   *
   * @internal
   */
  children() {
    const cached = __privateGet(this, _children).get(this);
    if (cached) {
      return cached;
    }
    const children = Object.assign([], { provisional: 0 });
    __privateGet(this, _children).set(this, children);
    __privateSet(this, _type, __privateGet(this, _type) & ~READDIR_CALLED);
    return children;
  }
  /**
   * Resolves a path portion and returns or creates the child Path.
   *
   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is
   * `'..'`.
   *
   * This should not be called directly.  If `pathPart` contains any path
   * separators, it will lead to unsafe undefined behavior.
   *
   * Use `Path.resolve()` instead.
   *
   * @internal
   */
  child(pathPart, opts) {
    if (pathPart === "" || pathPart === ".") {
      return this;
    }
    if (pathPart === "..") {
      return this.parent || this;
    }
    const children = this.children();
    const name2 = this.nocase ? normalizeNocase(pathPart) : normalize(pathPart);
    for (const p of children) {
      if (__privateGet(p, _matchName) === name2) {
        return p;
      }
    }
    const s = this.parent ? this.sep : "";
    const fullpath = __privateGet(this, _fullpath) ? __privateGet(this, _fullpath) + s + pathPart : void 0;
    const pchild = this.newChild(pathPart, UNKNOWN, {
      ...opts,
      parent: this,
      fullpath
    });
    if (!this.canReaddir()) {
      __privateSet(pchild, _type, __privateGet(pchild, _type) | ENOENT);
    }
    children.push(pchild);
    return pchild;
  }
  /**
   * The relative path from the cwd. If it does not share an ancestor with
   * the cwd, then this ends up being equivalent to the fullpath()
   */
  relative() {
    if (this.isCWD)
      return "";
    if (__privateGet(this, _relative) !== void 0) {
      return __privateGet(this, _relative);
    }
    const name2 = this.name;
    const p = this.parent;
    if (!p) {
      return __privateSet(this, _relative, this.name);
    }
    const pv = p.relative();
    return pv + (!pv || !p.parent ? "" : this.sep) + name2;
  }
  /**
   * The relative path from the cwd, using / as the path separator.
   * If it does not share an ancestor with
   * the cwd, then this ends up being equivalent to the fullpathPosix()
   * On posix systems, this is identical to relative().
   */
  relativePosix() {
    if (this.sep === "/")
      return this.relative();
    if (this.isCWD)
      return "";
    if (__privateGet(this, _relativePosix) !== void 0)
      return __privateGet(this, _relativePosix);
    const name2 = this.name;
    const p = this.parent;
    if (!p) {
      return __privateSet(this, _relativePosix, this.fullpathPosix());
    }
    const pv = p.relativePosix();
    return pv + (!pv || !p.parent ? "" : "/") + name2;
  }
  /**
   * The fully resolved path string for this Path entry
   */
  fullpath() {
    if (__privateGet(this, _fullpath) !== void 0) {
      return __privateGet(this, _fullpath);
    }
    const name2 = this.name;
    const p = this.parent;
    if (!p) {
      return __privateSet(this, _fullpath, this.name);
    }
    const pv = p.fullpath();
    const fp = pv + (!p.parent ? "" : this.sep) + name2;
    return __privateSet(this, _fullpath, fp);
  }
  /**
   * On platforms other than windows, this is identical to fullpath.
   *
   * On windows, this is overridden to return the forward-slash form of the
   * full UNC path.
   */
  fullpathPosix() {
    if (__privateGet(this, _fullpathPosix) !== void 0)
      return __privateGet(this, _fullpathPosix);
    if (this.sep === "/")
      return __privateSet(this, _fullpathPosix, this.fullpath());
    if (!this.parent) {
      const p2 = this.fullpath().replace(/\\/g, "/");
      if (/^[a-z]:\//i.test(p2)) {
        return __privateSet(this, _fullpathPosix, `//?/${p2}`);
      } else {
        return __privateSet(this, _fullpathPosix, p2);
      }
    }
    const p = this.parent;
    const pfpp = p.fullpathPosix();
    const fpp = pfpp + (!pfpp || !p.parent ? "" : "/") + this.name;
    return __privateSet(this, _fullpathPosix, fpp);
  }
  /**
   * Is the Path of an unknown type?
   *
   * Note that we might know *something* about it if there has been a previous
   * filesystem operation, for example that it does not exist, or is not a
   * link, or whether it has child entries.
   */
  isUnknown() {
    return (__privateGet(this, _type) & IFMT) === UNKNOWN;
  }
  isType(type) {
    return this[`is${type}`]();
  }
  getType() {
    return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : (
      /* c8 ignore start */
      this.isSocket() ? "Socket" : "Unknown"
    );
  }
  /**
   * Is the Path a regular file?
   */
  isFile() {
    return (__privateGet(this, _type) & IFMT) === IFREG;
  }
  /**
   * Is the Path a directory?
   */
  isDirectory() {
    return (__privateGet(this, _type) & IFMT) === IFDIR;
  }
  /**
   * Is the path a character device?
   */
  isCharacterDevice() {
    return (__privateGet(this, _type) & IFMT) === IFCHR;
  }
  /**
   * Is the path a block device?
   */
  isBlockDevice() {
    return (__privateGet(this, _type) & IFMT) === IFBLK;
  }
  /**
   * Is the path a FIFO pipe?
   */
  isFIFO() {
    return (__privateGet(this, _type) & IFMT) === IFIFO;
  }
  /**
   * Is the path a socket?
   */
  isSocket() {
    return (__privateGet(this, _type) & IFMT) === IFSOCK;
  }
  /**
   * Is the path a symbolic link?
   */
  isSymbolicLink() {
    return (__privateGet(this, _type) & IFLNK) === IFLNK;
  }
  /**
   * Return the entry if it has been subject of a successful lstat, or
   * undefined otherwise.
   *
   * Does not read the filesystem, so an undefined result *could* simply
   * mean that we haven't called lstat on it.
   */
  lstatCached() {
    return __privateGet(this, _type) & LSTAT_CALLED ? this : void 0;
  }
  /**
   * Return the cached link target if the entry has been the subject of a
   * successful readlink, or undefined otherwise.
   *
   * Does not read the filesystem, so an undefined result *could* just mean we
   * don't have any cached data. Only use it if you are very sure that a
   * readlink() has been called at some point.
   */
  readlinkCached() {
    return __privateGet(this, _linkTarget);
  }
  /**
   * Returns the cached realpath target if the entry has been the subject
   * of a successful realpath, or undefined otherwise.
   *
   * Does not read the filesystem, so an undefined result *could* just mean we
   * don't have any cached data. Only use it if you are very sure that a
   * realpath() has been called at some point.
   */
  realpathCached() {
    return __privateGet(this, _realpath);
  }
  /**
   * Returns the cached child Path entries array if the entry has been the
   * subject of a successful readdir(), or [] otherwise.
   *
   * Does not read the filesystem, so an empty array *could* just mean we
   * don't have any cached data. Only use it if you are very sure that a
   * readdir() has been called recently enough to still be valid.
   */
  readdirCached() {
    const children = this.children();
    return children.slice(0, children.provisional);
  }
  /**
   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have
   * any indication that readlink will definitely fail.
   *
   * Returns false if the path is known to not be a symlink, if a previous
   * readlink failed, or if the entry does not exist.
   */
  canReadlink() {
    if (__privateGet(this, _linkTarget))
      return true;
    if (!this.parent)
      return false;
    const ifmt = __privateGet(this, _type) & IFMT;
    return !(ifmt !== UNKNOWN && ifmt !== IFLNK || __privateGet(this, _type) & ENOREADLINK || __privateGet(this, _type) & ENOENT);
  }
  /**
   * Return true if readdir has previously been successfully called on this
   * path, indicating that cachedReaddir() is likely valid.
   */
  calledReaddir() {
    return !!(__privateGet(this, _type) & READDIR_CALLED);
  }
  /**
   * Returns true if the path is known to not exist. That is, a previous lstat
   * or readdir failed to verify its existence when that would have been
   * expected, or a parent entry was marked either enoent or enotdir.
   */
  isENOENT() {
    return !!(__privateGet(this, _type) & ENOENT);
  }
  /**
   * Return true if the path is a match for the given path name.  This handles
   * case sensitivity and unicode normalization.
   *
   * Note: even on case-sensitive systems, it is **not** safe to test the
   * equality of the `.name` property to determine whether a given pathname
   * matches, due to unicode normalization mismatches.
   *
   * Always use this method instead of testing the `path.name` property
   * directly.
   */
  isNamed(n2) {
    return !this.nocase ? __privateGet(this, _matchName) === normalize(n2) : __privateGet(this, _matchName) === normalizeNocase(n2);
  }
  /**
   * Return the Path object corresponding to the target of a symbolic link.
   *
   * If the Path is not a symbolic link, or if the readlink call fails for any
   * reason, `undefined` is returned.
   *
   * Result is cached, and thus may be outdated if the filesystem is mutated.
   */
  async readlink() {
    var _a4;
    const target = __privateGet(this, _linkTarget);
    if (target) {
      return target;
    }
    if (!this.canReadlink()) {
      return void 0;
    }
    if (!this.parent) {
      return void 0;
    }
    try {
      const read2 = await __privateGet(this, _fs).promises.readlink(this.fullpath());
      const linkTarget = (_a4 = await this.parent.realpath()) == null ? void 0 : _a4.resolve(read2);
      if (linkTarget) {
        return __privateSet(this, _linkTarget, linkTarget);
      }
    } catch (er) {
      __privateMethod(this, _PathBase_instances, readlinkFail_fn).call(this, er.code);
      return void 0;
    }
  }
  /**
   * Synchronous {@link PathBase.readlink}
   */
  readlinkSync() {
    var _a4;
    const target = __privateGet(this, _linkTarget);
    if (target) {
      return target;
    }
    if (!this.canReadlink()) {
      return void 0;
    }
    if (!this.parent) {
      return void 0;
    }
    try {
      const read2 = __privateGet(this, _fs).readlinkSync(this.fullpath());
      const linkTarget = (_a4 = this.parent.realpathSync()) == null ? void 0 : _a4.resolve(read2);
      if (linkTarget) {
        return __privateSet(this, _linkTarget, linkTarget);
      }
    } catch (er) {
      __privateMethod(this, _PathBase_instances, readlinkFail_fn).call(this, er.code);
      return void 0;
    }
  }
  /**
   * Call lstat() on this Path, and update all known information that can be
   * determined.
   *
   * Note that unlike `fs.lstat()`, the returned value does not contain some
   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
   * information is required, you will need to call `fs.lstat` yourself.
   *
   * If the Path refers to a nonexistent file, or if the lstat call fails for
   * any reason, `undefined` is returned.  Otherwise the updated Path object is
   * returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   */
  async lstat() {
    if ((__privateGet(this, _type) & ENOENT) === 0) {
      try {
        __privateMethod(this, _PathBase_instances, applyStat_fn).call(this, await __privateGet(this, _fs).promises.lstat(this.fullpath()));
        return this;
      } catch (er) {
        __privateMethod(this, _PathBase_instances, lstatFail_fn).call(this, er.code);
      }
    }
  }
  /**
   * synchronous {@link PathBase.lstat}
   */
  lstatSync() {
    if ((__privateGet(this, _type) & ENOENT) === 0) {
      try {
        __privateMethod(this, _PathBase_instances, applyStat_fn).call(this, __privateGet(this, _fs).lstatSync(this.fullpath()));
        return this;
      } catch (er) {
        __privateMethod(this, _PathBase_instances, lstatFail_fn).call(this, er.code);
      }
    }
  }
  /**
   * Standard node-style callback interface to get list of directory entries.
   *
   * If the Path cannot or does not contain any children, then an empty array
   * is returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   *
   * @param cb The callback called with (er, entries).  Note that the `er`
   * param is somewhat extraneous, as all readdir() errors are handled and
   * simply result in an empty set of entries being returned.
   * @param allowZalgo Boolean indicating that immediately known results should
   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release
   * zalgo at your peril, the dark pony lord is devious and unforgiving.
   */
  readdirCB(cb, allowZalgo = false) {
    if (!this.canReaddir()) {
      if (allowZalgo)
        cb(null, []);
      else
        queueMicrotask(() => cb(null, []));
      return;
    }
    const children = this.children();
    if (this.calledReaddir()) {
      const c = children.slice(0, children.provisional);
      if (allowZalgo)
        cb(null, c);
      else
        queueMicrotask(() => cb(null, c));
      return;
    }
    __privateGet(this, _onReaddirCB).push(cb);
    if (__privateGet(this, _readdirCBInFlight)) {
      return;
    }
    __privateSet(this, _readdirCBInFlight, true);
    const fullpath = this.fullpath();
    __privateGet(this, _fs).readdir(fullpath, { withFileTypes: true }, (er, entries) => {
      if (er) {
        __privateMethod(this, _PathBase_instances, readdirFail_fn).call(this, er.code);
        children.provisional = 0;
      } else {
        for (const e2 of entries) {
          __privateMethod(this, _PathBase_instances, readdirAddChild_fn).call(this, e2, children);
        }
        __privateMethod(this, _PathBase_instances, readdirSuccess_fn).call(this, children);
      }
      __privateMethod(this, _PathBase_instances, callOnReaddirCB_fn).call(this, children.slice(0, children.provisional));
      return;
    });
  }
  /**
   * Return an array of known child entries.
   *
   * If the Path cannot or does not contain any children, then an empty array
   * is returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   */
  async readdir() {
    if (!this.canReaddir()) {
      return [];
    }
    const children = this.children();
    if (this.calledReaddir()) {
      return children.slice(0, children.provisional);
    }
    const fullpath = this.fullpath();
    if (__privateGet(this, _asyncReaddirInFlight)) {
      await __privateGet(this, _asyncReaddirInFlight);
    } else {
      let resolve3 = () => {
      };
      __privateSet(this, _asyncReaddirInFlight, new Promise((res) => resolve3 = res));
      try {
        for (const e2 of await __privateGet(this, _fs).promises.readdir(fullpath, {
          withFileTypes: true
        })) {
          __privateMethod(this, _PathBase_instances, readdirAddChild_fn).call(this, e2, children);
        }
        __privateMethod(this, _PathBase_instances, readdirSuccess_fn).call(this, children);
      } catch (er) {
        __privateMethod(this, _PathBase_instances, readdirFail_fn).call(this, er.code);
        children.provisional = 0;
      }
      __privateSet(this, _asyncReaddirInFlight, void 0);
      resolve3();
    }
    return children.slice(0, children.provisional);
  }
  /**
   * synchronous {@link PathBase.readdir}
   */
  readdirSync() {
    if (!this.canReaddir()) {
      return [];
    }
    const children = this.children();
    if (this.calledReaddir()) {
      return children.slice(0, children.provisional);
    }
    const fullpath = this.fullpath();
    try {
      for (const e2 of __privateGet(this, _fs).readdirSync(fullpath, {
        withFileTypes: true
      })) {
        __privateMethod(this, _PathBase_instances, readdirAddChild_fn).call(this, e2, children);
      }
      __privateMethod(this, _PathBase_instances, readdirSuccess_fn).call(this, children);
    } catch (er) {
      __privateMethod(this, _PathBase_instances, readdirFail_fn).call(this, er.code);
      children.provisional = 0;
    }
    return children.slice(0, children.provisional);
  }
  canReaddir() {
    if (__privateGet(this, _type) & ENOCHILD)
      return false;
    const ifmt = IFMT & __privateGet(this, _type);
    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {
      return false;
    }
    return true;
  }
  shouldWalk(dirs, walkFilter) {
    return (__privateGet(this, _type) & IFDIR) === IFDIR && !(__privateGet(this, _type) & ENOCHILD) && !dirs.has(this) && (!walkFilter || walkFilter(this));
  }
  /**
   * Return the Path object corresponding to path as resolved
   * by realpath(3).
   *
   * If the realpath call fails for any reason, `undefined` is returned.
   *
   * Result is cached, and thus may be outdated if the filesystem is mutated.
   * On success, returns a Path object.
   */
  async realpath() {
    if (__privateGet(this, _realpath))
      return __privateGet(this, _realpath);
    if ((ENOREALPATH | ENOREADLINK | ENOENT) & __privateGet(this, _type))
      return void 0;
    try {
      const rp = await __privateGet(this, _fs).promises.realpath(this.fullpath());
      return __privateSet(this, _realpath, this.resolve(rp));
    } catch (_) {
      __privateMethod(this, _PathBase_instances, markENOREALPATH_fn).call(this);
    }
  }
  /**
   * Synchronous {@link realpath}
   */
  realpathSync() {
    if (__privateGet(this, _realpath))
      return __privateGet(this, _realpath);
    if ((ENOREALPATH | ENOREADLINK | ENOENT) & __privateGet(this, _type))
      return void 0;
    try {
      const rp = __privateGet(this, _fs).realpathSync(this.fullpath());
      return __privateSet(this, _realpath, this.resolve(rp));
    } catch (_) {
      __privateMethod(this, _PathBase_instances, markENOREALPATH_fn).call(this);
    }
  }
  /**
   * Internal method to mark this Path object as the scurry cwd,
   * called by {@link PathScurry#chdir}
   *
   * @internal
   */
  [setAsCwd](oldCwd) {
    if (oldCwd === this)
      return;
    oldCwd.isCWD = false;
    this.isCWD = true;
    const changed = /* @__PURE__ */ new Set([]);
    let rp = [];
    let p = this;
    while (p && p.parent) {
      changed.add(p);
      __privateSet(p, _relative, rp.join(this.sep));
      __privateSet(p, _relativePosix, rp.join("/"));
      p = p.parent;
      rp.push("..");
    }
    p = oldCwd;
    while (p && p.parent && !changed.has(p)) {
      __privateSet(p, _relative, void 0);
      __privateSet(p, _relativePosix, void 0);
      p = p.parent;
    }
  }
};
_fs = new WeakMap();
_dev = new WeakMap();
_mode = new WeakMap();
_nlink = new WeakMap();
_uid = new WeakMap();
_gid = new WeakMap();
_rdev = new WeakMap();
_blksize = new WeakMap();
_ino = new WeakMap();
_size2 = new WeakMap();
_blocks = new WeakMap();
_atimeMs = new WeakMap();
_mtimeMs = new WeakMap();
_ctimeMs = new WeakMap();
_birthtimeMs = new WeakMap();
_atime = new WeakMap();
_mtime = new WeakMap();
_ctime = new WeakMap();
_birthtime = new WeakMap();
_matchName = new WeakMap();
_depth = new WeakMap();
_fullpath = new WeakMap();
_fullpathPosix = new WeakMap();
_relative = new WeakMap();
_relativePosix = new WeakMap();
_type = new WeakMap();
_children = new WeakMap();
_linkTarget = new WeakMap();
_realpath = new WeakMap();
_PathBase_instances = new WeakSet();
resolveParts_fn = function(dirParts) {
  let p = this;
  for (const part of dirParts) {
    p = p.child(part);
  }
  return p;
};
readdirSuccess_fn = function(children) {
  var _a4;
  __privateSet(this, _type, __privateGet(this, _type) | READDIR_CALLED);
  for (let p = children.provisional; p < children.length; p++) {
    const c = children[p];
    if (c)
      __privateMethod(_a4 = c, _PathBase_instances, markENOENT_fn).call(_a4);
  }
};
markENOENT_fn = function() {
  if (__privateGet(this, _type) & ENOENT)
    return;
  __privateSet(this, _type, (__privateGet(this, _type) | ENOENT) & IFMT_UNKNOWN);
  __privateMethod(this, _PathBase_instances, markChildrenENOENT_fn).call(this);
};
markChildrenENOENT_fn = function() {
  var _a4;
  const children = this.children();
  children.provisional = 0;
  for (const p of children) {
    __privateMethod(_a4 = p, _PathBase_instances, markENOENT_fn).call(_a4);
  }
};
markENOREALPATH_fn = function() {
  __privateSet(this, _type, __privateGet(this, _type) | ENOREALPATH);
  __privateMethod(this, _PathBase_instances, markENOTDIR_fn).call(this);
};
// save the information when we know the entry is not a dir
markENOTDIR_fn = function() {
  if (__privateGet(this, _type) & ENOTDIR)
    return;
  let t2 = __privateGet(this, _type);
  if ((t2 & IFMT) === IFDIR)
    t2 &= IFMT_UNKNOWN;
  __privateSet(this, _type, t2 | ENOTDIR);
  __privateMethod(this, _PathBase_instances, markChildrenENOENT_fn).call(this);
};
readdirFail_fn = function(code = "") {
  if (code === "ENOTDIR" || code === "EPERM") {
    __privateMethod(this, _PathBase_instances, markENOTDIR_fn).call(this);
  } else if (code === "ENOENT") {
    __privateMethod(this, _PathBase_instances, markENOENT_fn).call(this);
  } else {
    this.children().provisional = 0;
  }
};
lstatFail_fn = function(code = "") {
  var _a4;
  if (code === "ENOTDIR") {
    const p = this.parent;
    __privateMethod(_a4 = p, _PathBase_instances, markENOTDIR_fn).call(_a4);
  } else if (code === "ENOENT") {
    __privateMethod(this, _PathBase_instances, markENOENT_fn).call(this);
  }
};
readlinkFail_fn = function(code = "") {
  var _a4;
  let ter = __privateGet(this, _type);
  ter |= ENOREADLINK;
  if (code === "ENOENT")
    ter |= ENOENT;
  if (code === "EINVAL" || code === "UNKNOWN") {
    ter &= IFMT_UNKNOWN;
  }
  __privateSet(this, _type, ter);
  if (code === "ENOTDIR" && this.parent) {
    __privateMethod(_a4 = this.parent, _PathBase_instances, markENOTDIR_fn).call(_a4);
  }
};
readdirAddChild_fn = function(e2, c) {
  return __privateMethod(this, _PathBase_instances, readdirMaybePromoteChild_fn).call(this, e2, c) || __privateMethod(this, _PathBase_instances, readdirAddNewChild_fn).call(this, e2, c);
};
readdirAddNewChild_fn = function(e2, c) {
  const type = entToType(e2);
  const child = this.newChild(e2.name, type, { parent: this });
  const ifmt = __privateGet(child, _type) & IFMT;
  if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {
    __privateSet(child, _type, __privateGet(child, _type) | ENOTDIR);
  }
  c.unshift(child);
  c.provisional++;
  return child;
};
readdirMaybePromoteChild_fn = function(e2, c) {
  for (let p = c.provisional; p < c.length; p++) {
    const pchild = c[p];
    const name2 = this.nocase ? normalizeNocase(e2.name) : normalize(e2.name);
    if (name2 !== __privateGet(pchild, _matchName)) {
      continue;
    }
    return __privateMethod(this, _PathBase_instances, readdirPromoteChild_fn).call(this, e2, pchild, p, c);
  }
};
readdirPromoteChild_fn = function(e2, p, index, c) {
  const v = p.name;
  __privateSet(p, _type, __privateGet(p, _type) & IFMT_UNKNOWN | entToType(e2));
  if (v !== e2.name)
    p.name = e2.name;
  if (index !== c.provisional) {
    if (index === c.length - 1)
      c.pop();
    else
      c.splice(index, 1);
    c.unshift(p);
  }
  c.provisional++;
  return p;
};
applyStat_fn = function(st) {
  const { atime, atimeMs, birthtime, birthtimeMs, blksize, blocks, ctime, ctimeMs, dev, gid, ino, mode: mode2, mtime, mtimeMs, nlink, rdev, size, uid } = st;
  __privateSet(this, _atime, atime);
  __privateSet(this, _atimeMs, atimeMs);
  __privateSet(this, _birthtime, birthtime);
  __privateSet(this, _birthtimeMs, birthtimeMs);
  __privateSet(this, _blksize, blksize);
  __privateSet(this, _blocks, blocks);
  __privateSet(this, _ctime, ctime);
  __privateSet(this, _ctimeMs, ctimeMs);
  __privateSet(this, _dev, dev);
  __privateSet(this, _gid, gid);
  __privateSet(this, _ino, ino);
  __privateSet(this, _mode, mode2);
  __privateSet(this, _mtime, mtime);
  __privateSet(this, _mtimeMs, mtimeMs);
  __privateSet(this, _nlink, nlink);
  __privateSet(this, _rdev, rdev);
  __privateSet(this, _size2, size);
  __privateSet(this, _uid, uid);
  const ifmt = entToType(st);
  __privateSet(this, _type, __privateGet(this, _type) & IFMT_UNKNOWN | ifmt | LSTAT_CALLED);
  if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {
    __privateSet(this, _type, __privateGet(this, _type) | ENOTDIR);
  }
};
_onReaddirCB = new WeakMap();
_readdirCBInFlight = new WeakMap();
callOnReaddirCB_fn = function(children) {
  __privateSet(this, _readdirCBInFlight, false);
  const cbs = __privateGet(this, _onReaddirCB).slice();
  __privateGet(this, _onReaddirCB).length = 0;
  cbs.forEach((cb) => cb(null, children));
};
_asyncReaddirInFlight = new WeakMap();
var PathWin32 = class _PathWin32 extends PathBase {
  /**
   * Do not create new Path objects directly.  They should always be accessed
   * via the PathScurry class or other methods on the Path class.
   *
   * @internal
   */
  constructor(name2, type = UNKNOWN, root, roots, nocase, children, opts) {
    super(name2, type, root, roots, nocase, children, opts);
    /**
     * Separator for generating path strings.
     */
    __publicField(this, "sep", "\\");
    /**
     * Separator for parsing path strings.
     */
    __publicField(this, "splitSep", eitherSep);
  }
  /**
   * @internal
   */
  newChild(name2, type = UNKNOWN, opts = {}) {
    return new _PathWin32(name2, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
  }
  /**
   * @internal
   */
  getRootString(path3) {
    return import_node_path3.win32.parse(path3).root;
  }
  /**
   * @internal
   */
  getRoot(rootPath) {
    rootPath = uncToDrive(rootPath.toUpperCase());
    if (rootPath === this.root.name) {
      return this.root;
    }
    for (const [compare2, root] of Object.entries(this.roots)) {
      if (this.sameRoot(rootPath, compare2)) {
        return this.roots[rootPath] = root;
      }
    }
    return this.roots[rootPath] = new PathScurryWin32(rootPath, this).root;
  }
  /**
   * @internal
   */
  sameRoot(rootPath, compare2 = this.root.name) {
    rootPath = rootPath.toUpperCase().replace(/\//g, "\\").replace(uncDriveRegexp, "$1\\");
    return rootPath === compare2;
  }
};
var PathPosix = class _PathPosix extends PathBase {
  /**
   * Do not create new Path objects directly.  They should always be accessed
   * via the PathScurry class or other methods on the Path class.
   *
   * @internal
   */
  constructor(name2, type = UNKNOWN, root, roots, nocase, children, opts) {
    super(name2, type, root, roots, nocase, children, opts);
    /**
     * separator for parsing path strings
     */
    __publicField(this, "splitSep", "/");
    /**
     * separator for generating path strings
     */
    __publicField(this, "sep", "/");
  }
  /**
   * @internal
   */
  getRootString(path3) {
    return path3.startsWith("/") ? "/" : "";
  }
  /**
   * @internal
   */
  getRoot(_rootPath) {
    return this.root;
  }
  /**
   * @internal
   */
  newChild(name2, type = UNKNOWN, opts = {}) {
    return new _PathPosix(name2, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
  }
};
var _resolveCache, _resolvePosixCache, _children2, _fs2;
var PathScurryBase = class {
  /**
   * This class should not be instantiated directly.
   *
   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry
   *
   * @internal
   */
  constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs2 = defaultFS } = {}) {
    /**
     * The root Path entry for the current working directory of this Scurry
     */
    __publicField(this, "root");
    /**
     * The string path for the root of this Scurry's current working directory
     */
    __publicField(this, "rootPath");
    /**
     * A collection of all roots encountered, referenced by rootPath
     */
    __publicField(this, "roots");
    /**
     * The Path entry corresponding to this PathScurry's current working directory.
     */
    __publicField(this, "cwd");
    __privateAdd(this, _resolveCache);
    __privateAdd(this, _resolvePosixCache);
    __privateAdd(this, _children2);
    /**
     * Perform path comparisons case-insensitively.
     *
     * Defaults true on Darwin and Windows systems, false elsewhere.
     */
    __publicField(this, "nocase");
    __privateAdd(this, _fs2);
    __privateSet(this, _fs2, fsFromOption(fs2));
    if (cwd instanceof URL || cwd.startsWith("file://")) {
      cwd = (0, import_node_url2.fileURLToPath)(cwd);
    }
    const cwdPath = pathImpl.resolve(cwd);
    this.roots = /* @__PURE__ */ Object.create(null);
    this.rootPath = this.parseRootPath(cwdPath);
    __privateSet(this, _resolveCache, new ResolveCache());
    __privateSet(this, _resolvePosixCache, new ResolveCache());
    __privateSet(this, _children2, new ChildrenCache(childrenCacheSize));
    const split = cwdPath.substring(this.rootPath.length).split(sep2);
    if (split.length === 1 && !split[0]) {
      split.pop();
    }
    if (nocase === void 0) {
      throw new TypeError("must provide nocase setting to PathScurryBase ctor");
    }
    this.nocase = nocase;
    this.root = this.newRoot(__privateGet(this, _fs2));
    this.roots[this.rootPath] = this.root;
    let prev = this.root;
    let len = split.length - 1;
    const joinSep = pathImpl.sep;
    let abs = this.rootPath;
    let sawFirst = false;
    for (const part of split) {
      const l = len--;
      prev = prev.child(part, {
        relative: new Array(l).fill("..").join(joinSep),
        relativePosix: new Array(l).fill("..").join("/"),
        fullpath: abs += (sawFirst ? "" : joinSep) + part
      });
      sawFirst = true;
    }
    this.cwd = prev;
  }
  /**
   * Get the depth of a provided path, string, or the cwd
   */
  depth(path3 = this.cwd) {
    if (typeof path3 === "string") {
      path3 = this.cwd.resolve(path3);
    }
    return path3.depth();
  }
  /**
   * Return the cache of child entries.  Exposed so subclasses can create
   * child Path objects in a platform-specific way.
   *
   * @internal
   */
  childrenCache() {
    return __privateGet(this, _children2);
  }
  /**
   * Resolve one or more path strings to a resolved string
   *
   * Same interface as require('path').resolve.
   *
   * Much faster than path.resolve() when called multiple times for the same
   * path, because the resolved Path objects are cached.  Much slower
   * otherwise.
   */
  resolve(...paths) {
    let r2 = "";
    for (let i = paths.length - 1; i >= 0; i--) {
      const p = paths[i];
      if (!p || p === ".")
        continue;
      r2 = r2 ? `${p}/${r2}` : p;
      if (this.isAbsolute(p)) {
        break;
      }
    }
    const cached = __privateGet(this, _resolveCache).get(r2);
    if (cached !== void 0) {
      return cached;
    }
    const result = this.cwd.resolve(r2).fullpath();
    __privateGet(this, _resolveCache).set(r2, result);
    return result;
  }
  /**
   * Resolve one or more path strings to a resolved string, returning
   * the posix path.  Identical to .resolve() on posix systems, but on
   * windows will return a forward-slash separated UNC path.
   *
   * Same interface as require('path').resolve.
   *
   * Much faster than path.resolve() when called multiple times for the same
   * path, because the resolved Path objects are cached.  Much slower
   * otherwise.
   */
  resolvePosix(...paths) {
    let r2 = "";
    for (let i = paths.length - 1; i >= 0; i--) {
      const p = paths[i];
      if (!p || p === ".")
        continue;
      r2 = r2 ? `${p}/${r2}` : p;
      if (this.isAbsolute(p)) {
        break;
      }
    }
    const cached = __privateGet(this, _resolvePosixCache).get(r2);
    if (cached !== void 0) {
      return cached;
    }
    const result = this.cwd.resolve(r2).fullpathPosix();
    __privateGet(this, _resolvePosixCache).set(r2, result);
    return result;
  }
  /**
   * find the relative path from the cwd to the supplied path string or entry
   */
  relative(entry2 = this.cwd) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    }
    return entry2.relative();
  }
  /**
   * find the relative path from the cwd to the supplied path string or
   * entry, using / as the path delimiter, even on Windows.
   */
  relativePosix(entry2 = this.cwd) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    }
    return entry2.relativePosix();
  }
  /**
   * Return the basename for the provided string or Path object
   */
  basename(entry2 = this.cwd) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    }
    return entry2.name;
  }
  /**
   * Return the dirname for the provided string or Path object
   */
  dirname(entry2 = this.cwd) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    }
    return (entry2.parent || entry2).fullpath();
  }
  async readdir(entry2 = this.cwd, opts = {
    withFileTypes: true
  }) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes } = opts;
    if (!entry2.canReaddir()) {
      return [];
    } else {
      const p = await entry2.readdir();
      return withFileTypes ? p : p.map((e2) => e2.name);
    }
  }
  readdirSync(entry2 = this.cwd, opts = {
    withFileTypes: true
  }) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes = true } = opts;
    if (!entry2.canReaddir()) {
      return [];
    } else if (withFileTypes) {
      return entry2.readdirSync();
    } else {
      return entry2.readdirSync().map((e2) => e2.name);
    }
  }
  /**
   * Call lstat() on the string or Path object, and update all known
   * information that can be determined.
   *
   * Note that unlike `fs.lstat()`, the returned value does not contain some
   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that
   * information is required, you will need to call `fs.lstat` yourself.
   *
   * If the Path refers to a nonexistent file, or if the lstat call fails for
   * any reason, `undefined` is returned.  Otherwise the updated Path object is
   * returned.
   *
   * Results are cached, and thus may be out of date if the filesystem is
   * mutated.
   */
  async lstat(entry2 = this.cwd) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    }
    return entry2.lstat();
  }
  /**
   * synchronous {@link PathScurryBase.lstat}
   */
  lstatSync(entry2 = this.cwd) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    }
    return entry2.lstatSync();
  }
  async readlink(entry2 = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      withFileTypes = entry2.withFileTypes;
      entry2 = this.cwd;
    }
    const e2 = await entry2.readlink();
    return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
  }
  readlinkSync(entry2 = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      withFileTypes = entry2.withFileTypes;
      entry2 = this.cwd;
    }
    const e2 = entry2.readlinkSync();
    return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
  }
  async realpath(entry2 = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      withFileTypes = entry2.withFileTypes;
      entry2 = this.cwd;
    }
    const e2 = await entry2.realpath();
    return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
  }
  realpathSync(entry2 = this.cwd, { withFileTypes } = {
    withFileTypes: false
  }) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      withFileTypes = entry2.withFileTypes;
      entry2 = this.cwd;
    }
    const e2 = entry2.realpathSync();
    return withFileTypes ? e2 : e2 == null ? void 0 : e2.fullpath();
  }
  async walk(entry2 = this.cwd, opts = {}) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = [];
    if (!filter2 || filter2(entry2)) {
      results.push(withFileTypes ? entry2 : entry2.fullpath());
    }
    const dirs = /* @__PURE__ */ new Set();
    const walk2 = (dir, cb) => {
      dirs.add(dir);
      dir.readdirCB((er, entries) => {
        if (er) {
          return cb(er);
        }
        let len = entries.length;
        if (!len)
          return cb();
        const next = () => {
          if (--len === 0) {
            cb();
          }
        };
        for (const e2 of entries) {
          if (!filter2 || filter2(e2)) {
            results.push(withFileTypes ? e2 : e2.fullpath());
          }
          if (follow && e2.isSymbolicLink()) {
            e2.realpath().then((r2) => (r2 == null ? void 0 : r2.isUnknown()) ? r2.lstat() : r2).then((r2) => (r2 == null ? void 0 : r2.shouldWalk(dirs, walkFilter)) ? walk2(r2, next) : next());
          } else {
            if (e2.shouldWalk(dirs, walkFilter)) {
              walk2(e2, next);
            } else {
              next();
            }
          }
        }
      }, true);
    };
    const start = entry2;
    return new Promise((res, rej) => {
      walk2(start, (er) => {
        if (er)
          return rej(er);
        res(results);
      });
    });
  }
  walkSync(entry2 = this.cwd, opts = {}) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = [];
    if (!filter2 || filter2(entry2)) {
      results.push(withFileTypes ? entry2 : entry2.fullpath());
    }
    const dirs = /* @__PURE__ */ new Set([entry2]);
    for (const dir of dirs) {
      const entries = dir.readdirSync();
      for (const e2 of entries) {
        if (!filter2 || filter2(e2)) {
          results.push(withFileTypes ? e2 : e2.fullpath());
        }
        let r2 = e2;
        if (e2.isSymbolicLink()) {
          if (!(follow && (r2 = e2.realpathSync())))
            continue;
          if (r2.isUnknown())
            r2.lstatSync();
        }
        if (r2.shouldWalk(dirs, walkFilter)) {
          dirs.add(r2);
        }
      }
    }
    return results;
  }
  /**
   * Support for `for await`
   *
   * Alias for {@link PathScurryBase.iterate}
   *
   * Note: As of Node 19, this is very slow, compared to other methods of
   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead
   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.
   */
  [Symbol.asyncIterator]() {
    return this.iterate();
  }
  iterate(entry2 = this.cwd, options2 = {}) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      options2 = entry2;
      entry2 = this.cwd;
    }
    return this.stream(entry2, options2)[Symbol.asyncIterator]();
  }
  /**
   * Iterating over a PathScurry performs a synchronous walk.
   *
   * Alias for {@link PathScurryBase.iterateSync}
   */
  [Symbol.iterator]() {
    return this.iterateSync();
  }
  *iterateSync(entry2 = this.cwd, opts = {}) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    if (!filter2 || filter2(entry2)) {
      yield withFileTypes ? entry2 : entry2.fullpath();
    }
    const dirs = /* @__PURE__ */ new Set([entry2]);
    for (const dir of dirs) {
      const entries = dir.readdirSync();
      for (const e2 of entries) {
        if (!filter2 || filter2(e2)) {
          yield withFileTypes ? e2 : e2.fullpath();
        }
        let r2 = e2;
        if (e2.isSymbolicLink()) {
          if (!(follow && (r2 = e2.realpathSync())))
            continue;
          if (r2.isUnknown())
            r2.lstatSync();
        }
        if (r2.shouldWalk(dirs, walkFilter)) {
          dirs.add(r2);
        }
      }
    }
  }
  stream(entry2 = this.cwd, opts = {}) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = new Minipass({ objectMode: true });
    if (!filter2 || filter2(entry2)) {
      results.write(withFileTypes ? entry2 : entry2.fullpath());
    }
    const dirs = /* @__PURE__ */ new Set();
    const queue2 = [entry2];
    let processing = 0;
    const process2 = () => {
      let paused = false;
      while (!paused) {
        const dir = queue2.shift();
        if (!dir) {
          if (processing === 0)
            results.end();
          return;
        }
        processing++;
        dirs.add(dir);
        const onReaddir = (er, entries, didRealpaths = false) => {
          if (er)
            return results.emit("error", er);
          if (follow && !didRealpaths) {
            const promises2 = [];
            for (const e2 of entries) {
              if (e2.isSymbolicLink()) {
                promises2.push(e2.realpath().then((r2) => (r2 == null ? void 0 : r2.isUnknown()) ? r2.lstat() : r2));
              }
            }
            if (promises2.length) {
              Promise.all(promises2).then(() => onReaddir(null, entries, true));
              return;
            }
          }
          for (const e2 of entries) {
            if (e2 && (!filter2 || filter2(e2))) {
              if (!results.write(withFileTypes ? e2 : e2.fullpath())) {
                paused = true;
              }
            }
          }
          processing--;
          for (const e2 of entries) {
            const r2 = e2.realpathCached() || e2;
            if (r2.shouldWalk(dirs, walkFilter)) {
              queue2.push(r2);
            }
          }
          if (paused && !results.flowing) {
            results.once("drain", process2);
          } else if (!sync2) {
            process2();
          }
        };
        let sync2 = true;
        dir.readdirCB(onReaddir, true);
        sync2 = false;
      }
    };
    process2();
    return results;
  }
  streamSync(entry2 = this.cwd, opts = {}) {
    if (typeof entry2 === "string") {
      entry2 = this.cwd.resolve(entry2);
    } else if (!(entry2 instanceof PathBase)) {
      opts = entry2;
      entry2 = this.cwd;
    }
    const { withFileTypes = true, follow = false, filter: filter2, walkFilter } = opts;
    const results = new Minipass({ objectMode: true });
    const dirs = /* @__PURE__ */ new Set();
    if (!filter2 || filter2(entry2)) {
      results.write(withFileTypes ? entry2 : entry2.fullpath());
    }
    const queue2 = [entry2];
    let processing = 0;
    const process2 = () => {
      let paused = false;
      while (!paused) {
        const dir = queue2.shift();
        if (!dir) {
          if (processing === 0)
            results.end();
          return;
        }
        processing++;
        dirs.add(dir);
        const entries = dir.readdirSync();
        for (const e2 of entries) {
          if (!filter2 || filter2(e2)) {
            if (!results.write(withFileTypes ? e2 : e2.fullpath())) {
              paused = true;
            }
          }
        }
        processing--;
        for (const e2 of entries) {
          let r2 = e2;
          if (e2.isSymbolicLink()) {
            if (!(follow && (r2 = e2.realpathSync())))
              continue;
            if (r2.isUnknown())
              r2.lstatSync();
          }
          if (r2.shouldWalk(dirs, walkFilter)) {
            queue2.push(r2);
          }
        }
      }
      if (paused && !results.flowing)
        results.once("drain", process2);
    };
    process2();
    return results;
  }
  chdir(path3 = this.cwd) {
    const oldCwd = this.cwd;
    this.cwd = typeof path3 === "string" ? this.cwd.resolve(path3) : path3;
    this.cwd[setAsCwd](oldCwd);
  }
};
_resolveCache = new WeakMap();
_resolvePosixCache = new WeakMap();
_children2 = new WeakMap();
_fs2 = new WeakMap();
var PathScurryWin32 = class extends PathScurryBase {
  constructor(cwd = process.cwd(), opts = {}) {
    const { nocase = true } = opts;
    super(cwd, import_node_path3.win32, "\\", { ...opts, nocase });
    /**
     * separator for generating path strings
     */
    __publicField(this, "sep", "\\");
    this.nocase = nocase;
    for (let p = this.cwd; p; p = p.parent) {
      p.nocase = this.nocase;
    }
  }
  /**
   * @internal
   */
  parseRootPath(dir) {
    return import_node_path3.win32.parse(dir).root.toUpperCase();
  }
  /**
   * @internal
   */
  newRoot(fs2) {
    return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
  }
  /**
   * Return true if the provided path string is an absolute path
   */
  isAbsolute(p) {
    return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
  }
};
var PathScurryPosix = class extends PathScurryBase {
  constructor(cwd = process.cwd(), opts = {}) {
    const { nocase = false } = opts;
    super(cwd, import_node_path3.posix, "/", { ...opts, nocase });
    /**
     * separator for generating path strings
     */
    __publicField(this, "sep", "/");
    this.nocase = nocase;
  }
  /**
   * @internal
   */
  parseRootPath(_dir) {
    return "/";
  }
  /**
   * @internal
   */
  newRoot(fs2) {
    return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs2 });
  }
  /**
   * Return true if the provided path string is an absolute path
   */
  isAbsolute(p) {
    return p.startsWith("/");
  }
};
var PathScurryDarwin = class extends PathScurryPosix {
  constructor(cwd = process.cwd(), opts = {}) {
    const { nocase = true } = opts;
    super(cwd, { ...opts, nocase });
  }
};
process.platform === "win32" ? PathWin32 : PathPosix;
var PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
var isPatternList = (pl) => pl.length >= 1;
var isGlobList = (gl) => gl.length >= 1;
var _patternList, _globList, _index, _platform, _rest, _globString, _isDrive, _isUNC, _isAbsolute, _followGlobstar;
var _Pattern = class _Pattern {
  constructor(patternList, globList, index, platform2) {
    __privateAdd(this, _patternList);
    __privateAdd(this, _globList);
    __privateAdd(this, _index);
    __publicField(this, "length");
    __privateAdd(this, _platform);
    __privateAdd(this, _rest);
    __privateAdd(this, _globString);
    __privateAdd(this, _isDrive);
    __privateAdd(this, _isUNC);
    __privateAdd(this, _isAbsolute);
    __privateAdd(this, _followGlobstar, true);
    if (!isPatternList(patternList)) {
      throw new TypeError("empty pattern list");
    }
    if (!isGlobList(globList)) {
      throw new TypeError("empty glob list");
    }
    if (globList.length !== patternList.length) {
      throw new TypeError("mismatched pattern list and glob list lengths");
    }
    this.length = patternList.length;
    if (index < 0 || index >= this.length) {
      throw new TypeError("index out of range");
    }
    __privateSet(this, _patternList, patternList);
    __privateSet(this, _globList, globList);
    __privateSet(this, _index, index);
    __privateSet(this, _platform, platform2);
    if (__privateGet(this, _index) === 0) {
      if (this.isUNC()) {
        const [p0, p1, p2, p3, ...prest] = __privateGet(this, _patternList);
        const [g0, g1, g2, g3, ...grest] = __privateGet(this, _globList);
        if (prest[0] === "") {
          prest.shift();
          grest.shift();
        }
        const p = [p0, p1, p2, p3, ""].join("/");
        const g = [g0, g1, g2, g3, ""].join("/");
        __privateSet(this, _patternList, [p, ...prest]);
        __privateSet(this, _globList, [g, ...grest]);
        this.length = __privateGet(this, _patternList).length;
      } else if (this.isDrive() || this.isAbsolute()) {
        const [p1, ...prest] = __privateGet(this, _patternList);
        const [g1, ...grest] = __privateGet(this, _globList);
        if (prest[0] === "") {
          prest.shift();
          grest.shift();
        }
        const p = p1 + "/";
        const g = g1 + "/";
        __privateSet(this, _patternList, [p, ...prest]);
        __privateSet(this, _globList, [g, ...grest]);
        this.length = __privateGet(this, _patternList).length;
      }
    }
  }
  /**
   * The first entry in the parsed list of patterns
   */
  pattern() {
    return __privateGet(this, _patternList)[__privateGet(this, _index)];
  }
  /**
   * true of if pattern() returns a string
   */
  isString() {
    return typeof __privateGet(this, _patternList)[__privateGet(this, _index)] === "string";
  }
  /**
   * true of if pattern() returns GLOBSTAR
   */
  isGlobstar() {
    return __privateGet(this, _patternList)[__privateGet(this, _index)] === GLOBSTAR$2;
  }
  /**
   * true if pattern() returns a regexp
   */
  isRegExp() {
    return __privateGet(this, _patternList)[__privateGet(this, _index)] instanceof RegExp;
  }
  /**
   * The /-joined set of glob parts that make up this pattern
   */
  globString() {
    return __privateSet(this, _globString, __privateGet(this, _globString) || (__privateGet(this, _index) === 0 ? this.isAbsolute() ? __privateGet(this, _globList)[0] + __privateGet(this, _globList).slice(1).join("/") : __privateGet(this, _globList).join("/") : __privateGet(this, _globList).slice(__privateGet(this, _index)).join("/")));
  }
  /**
   * true if there are more pattern parts after this one
   */
  hasMore() {
    return this.length > __privateGet(this, _index) + 1;
  }
  /**
   * The rest of the pattern after this part, or null if this is the end
   */
  rest() {
    if (__privateGet(this, _rest) !== void 0)
      return __privateGet(this, _rest);
    if (!this.hasMore())
      return __privateSet(this, _rest, null);
    __privateSet(this, _rest, new _Pattern(__privateGet(this, _patternList), __privateGet(this, _globList), __privateGet(this, _index) + 1, __privateGet(this, _platform)));
    __privateSet(__privateGet(this, _rest), _isAbsolute, __privateGet(this, _isAbsolute));
    __privateSet(__privateGet(this, _rest), _isUNC, __privateGet(this, _isUNC));
    __privateSet(__privateGet(this, _rest), _isDrive, __privateGet(this, _isDrive));
    return __privateGet(this, _rest);
  }
  /**
   * true if the pattern represents a //unc/path/ on windows
   */
  isUNC() {
    const pl = __privateGet(this, _patternList);
    return __privateGet(this, _isUNC) !== void 0 ? __privateGet(this, _isUNC) : __privateSet(this, _isUNC, __privateGet(this, _platform) === "win32" && __privateGet(this, _index) === 0 && pl[0] === "" && pl[1] === "" && typeof pl[2] === "string" && !!pl[2] && typeof pl[3] === "string" && !!pl[3]);
  }
  // pattern like C:/...
  // split = ['C:', ...]
  // XXX: would be nice to handle patterns like `c:*` to test the cwd
  // in c: for *, but I don't know of a way to even figure out what that
  // cwd is without actually chdir'ing into it?
  /**
   * True if the pattern starts with a drive letter on Windows
   */
  isDrive() {
    const pl = __privateGet(this, _patternList);
    return __privateGet(this, _isDrive) !== void 0 ? __privateGet(this, _isDrive) : __privateSet(this, _isDrive, __privateGet(this, _platform) === "win32" && __privateGet(this, _index) === 0 && this.length > 1 && typeof pl[0] === "string" && /^[a-z]:$/i.test(pl[0]));
  }
  // pattern = '/' or '/...' or '/x/...'
  // split = ['', ''] or ['', ...] or ['', 'x', ...]
  // Drive and UNC both considered absolute on windows
  /**
   * True if the pattern is rooted on an absolute path
   */
  isAbsolute() {
    const pl = __privateGet(this, _patternList);
    return __privateGet(this, _isAbsolute) !== void 0 ? __privateGet(this, _isAbsolute) : __privateSet(this, _isAbsolute, pl[0] === "" && pl.length > 1 || this.isDrive() || this.isUNC());
  }
  /**
   * consume the root of the pattern, and return it
   */
  root() {
    const p = __privateGet(this, _patternList)[0];
    return typeof p === "string" && this.isAbsolute() && __privateGet(this, _index) === 0 ? p : "";
  }
  /**
   * Check to see if the current globstar pattern is allowed to follow
   * a symbolic link.
   */
  checkFollowGlobstar() {
    return !(__privateGet(this, _index) === 0 || !this.isGlobstar() || !__privateGet(this, _followGlobstar));
  }
  /**
   * Mark that the current globstar pattern is following a symbolic link
   */
  markFollowGlobstar() {
    if (__privateGet(this, _index) === 0 || !this.isGlobstar() || !__privateGet(this, _followGlobstar))
      return false;
    __privateSet(this, _followGlobstar, false);
    return true;
  }
};
_patternList = new WeakMap();
_globList = new WeakMap();
_index = new WeakMap();
_platform = new WeakMap();
_rest = new WeakMap();
_globString = new WeakMap();
_isDrive = new WeakMap();
_isUNC = new WeakMap();
_isAbsolute = new WeakMap();
_followGlobstar = new WeakMap();
var Pattern = _Pattern;
var defaultPlatform$1 = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
var Ignore = class {
  constructor(ignored, { nobrace, nocase, noext, noglobstar, platform: platform2 = defaultPlatform$1 }) {
    __publicField(this, "relative");
    __publicField(this, "relativeChildren");
    __publicField(this, "absolute");
    __publicField(this, "absoluteChildren");
    __publicField(this, "platform");
    __publicField(this, "mmopts");
    this.relative = [];
    this.absolute = [];
    this.relativeChildren = [];
    this.absoluteChildren = [];
    this.platform = platform2;
    this.mmopts = {
      dot: true,
      nobrace,
      nocase,
      noext,
      noglobstar,
      optimizationLevel: 2,
      platform: platform2,
      nocomment: true,
      nonegate: true
    };
    for (const ign of ignored)
      this.add(ign);
  }
  add(ign) {
    const mm = new Minimatch(ign, this.mmopts);
    for (let i = 0; i < mm.set.length; i++) {
      const parsed = mm.set[i];
      const globParts = mm.globParts[i];
      if (!parsed || !globParts) {
        throw new Error("invalid pattern object");
      }
      while (parsed[0] === "." && globParts[0] === ".") {
        parsed.shift();
        globParts.shift();
      }
      const p = new Pattern(parsed, globParts, 0, this.platform);
      const m = new Minimatch(p.globString(), this.mmopts);
      const children = globParts[globParts.length - 1] === "**";
      const absolute = p.isAbsolute();
      if (absolute)
        this.absolute.push(m);
      else
        this.relative.push(m);
      if (children) {
        if (absolute)
          this.absoluteChildren.push(m);
        else
          this.relativeChildren.push(m);
      }
    }
  }
  ignored(p) {
    const fullpath = p.fullpath();
    const fullpaths = `${fullpath}/`;
    const relative2 = p.relative() || ".";
    const relatives = `${relative2}/`;
    for (const m of this.relative) {
      if (m.match(relative2) || m.match(relatives))
        return true;
    }
    for (const m of this.absolute) {
      if (m.match(fullpath) || m.match(fullpaths))
        return true;
    }
    return false;
  }
  childrenIgnored(p) {
    const fullpath = p.fullpath() + "/";
    const relative2 = (p.relative() || ".") + "/";
    for (const m of this.relativeChildren) {
      if (m.match(relative2))
        return true;
    }
    for (const m of this.absoluteChildren) {
      if (m.match(fullpath))
        return true;
    }
    return false;
  }
};
var HasWalkedCache = class _HasWalkedCache {
  constructor(store = /* @__PURE__ */ new Map()) {
    __publicField(this, "store");
    this.store = store;
  }
  copy() {
    return new _HasWalkedCache(new Map(this.store));
  }
  hasWalked(target, pattern2) {
    var _a4;
    return (_a4 = this.store.get(target.fullpath())) == null ? void 0 : _a4.has(pattern2.globString());
  }
  storeWalked(target, pattern2) {
    const fullpath = target.fullpath();
    const cached = this.store.get(fullpath);
    if (cached)
      cached.add(pattern2.globString());
    else
      this.store.set(fullpath, /* @__PURE__ */ new Set([pattern2.globString()]));
  }
};
var MatchRecord = class {
  constructor() {
    __publicField(this, "store", /* @__PURE__ */ new Map());
  }
  add(target, absolute, ifDir) {
    const n2 = (absolute ? 2 : 0) | (ifDir ? 1 : 0);
    const current = this.store.get(target);
    this.store.set(target, current === void 0 ? n2 : n2 & current);
  }
  // match, absolute, ifdir
  entries() {
    return [...this.store.entries()].map(([path3, n2]) => [
      path3,
      !!(n2 & 2),
      !!(n2 & 1)
    ]);
  }
};
var SubWalks = class {
  constructor() {
    __publicField(this, "store", /* @__PURE__ */ new Map());
  }
  add(target, pattern2) {
    if (!target.canReaddir()) {
      return;
    }
    const subs = this.store.get(target);
    if (subs) {
      if (!subs.find((p) => p.globString() === pattern2.globString())) {
        subs.push(pattern2);
      }
    } else
      this.store.set(target, [pattern2]);
  }
  get(target) {
    const subs = this.store.get(target);
    if (!subs) {
      throw new Error("attempting to walk unknown path");
    }
    return subs;
  }
  entries() {
    return this.keys().map((k) => [k, this.store.get(k)]);
  }
  keys() {
    return [...this.store.keys()].filter((t2) => t2.canReaddir());
  }
};
var Processor = class _Processor {
  constructor(opts, hasWalkedCache) {
    __publicField(this, "hasWalkedCache");
    __publicField(this, "matches", new MatchRecord());
    __publicField(this, "subwalks", new SubWalks());
    __publicField(this, "patterns");
    __publicField(this, "follow");
    __publicField(this, "dot");
    __publicField(this, "opts");
    this.opts = opts;
    this.follow = !!opts.follow;
    this.dot = !!opts.dot;
    this.hasWalkedCache = hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache();
  }
  processPatterns(target, patterns) {
    this.patterns = patterns;
    const processingSet = patterns.map((p) => [target, p]);
    for (let [t2, pattern2] of processingSet) {
      this.hasWalkedCache.storeWalked(t2, pattern2);
      const root = pattern2.root();
      const absolute = pattern2.isAbsolute() && this.opts.absolute !== false;
      if (root) {
        t2 = t2.resolve(root === "/" && this.opts.root !== void 0 ? this.opts.root : root);
        const rest2 = pattern2.rest();
        if (!rest2) {
          this.matches.add(t2, true, false);
          continue;
        } else {
          pattern2 = rest2;
        }
      }
      if (t2.isENOENT())
        continue;
      let p;
      let rest;
      let changed = false;
      while (typeof (p = pattern2.pattern()) === "string" && (rest = pattern2.rest())) {
        const c = t2.resolve(p);
        t2 = c;
        pattern2 = rest;
        changed = true;
      }
      p = pattern2.pattern();
      rest = pattern2.rest();
      if (changed) {
        if (this.hasWalkedCache.hasWalked(t2, pattern2))
          continue;
        this.hasWalkedCache.storeWalked(t2, pattern2);
      }
      if (typeof p === "string") {
        const ifDir = p === ".." || p === "" || p === ".";
        this.matches.add(t2.resolve(p), absolute, ifDir);
        continue;
      } else if (p === GLOBSTAR$2) {
        if (!t2.isSymbolicLink() || this.follow || pattern2.checkFollowGlobstar()) {
          this.subwalks.add(t2, pattern2);
        }
        const rp = rest == null ? void 0 : rest.pattern();
        const rrest = rest == null ? void 0 : rest.rest();
        if (!rest || (rp === "" || rp === ".") && !rrest) {
          this.matches.add(t2, absolute, rp === "" || rp === ".");
        } else {
          if (rp === "..") {
            const tp = t2.parent || t2;
            if (!rrest)
              this.matches.add(tp, absolute, true);
            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {
              this.subwalks.add(tp, rrest);
            }
          }
        }
      } else if (p instanceof RegExp) {
        this.subwalks.add(t2, pattern2);
      }
    }
    return this;
  }
  subwalkTargets() {
    return this.subwalks.keys();
  }
  child() {
    return new _Processor(this.opts, this.hasWalkedCache);
  }
  // return a new Processor containing the subwalks for each
  // child entry, and a set of matches, and
  // a hasWalkedCache that's a copy of this one
  // then we're going to call
  filterEntries(parent, entries) {
    const patterns = this.subwalks.get(parent);
    const results = this.child();
    for (const e2 of entries) {
      for (const pattern2 of patterns) {
        const absolute = pattern2.isAbsolute();
        const p = pattern2.pattern();
        const rest = pattern2.rest();
        if (p === GLOBSTAR$2) {
          results.testGlobstar(e2, pattern2, rest, absolute);
        } else if (p instanceof RegExp) {
          results.testRegExp(e2, p, rest, absolute);
        } else {
          results.testString(e2, p, rest, absolute);
        }
      }
    }
    return results;
  }
  testGlobstar(e2, pattern2, rest, absolute) {
    if (this.dot || !e2.name.startsWith(".")) {
      if (!pattern2.hasMore()) {
        this.matches.add(e2, absolute, false);
      }
      if (e2.canReaddir()) {
        if (this.follow || !e2.isSymbolicLink()) {
          this.subwalks.add(e2, pattern2);
        } else if (e2.isSymbolicLink()) {
          if (rest && pattern2.checkFollowGlobstar()) {
            this.subwalks.add(e2, rest);
          } else if (pattern2.markFollowGlobstar()) {
            this.subwalks.add(e2, pattern2);
          }
        }
      }
    }
    if (rest) {
      const rp = rest.pattern();
      if (typeof rp === "string" && // dots and empty were handled already
      rp !== ".." && rp !== "" && rp !== ".") {
        this.testString(e2, rp, rest.rest(), absolute);
      } else if (rp === "..") {
        const ep = e2.parent || e2;
        this.subwalks.add(ep, rest);
      } else if (rp instanceof RegExp) {
        this.testRegExp(e2, rp, rest.rest(), absolute);
      }
    }
  }
  testRegExp(e2, p, rest, absolute) {
    if (!p.test(e2.name))
      return;
    if (!rest) {
      this.matches.add(e2, absolute, false);
    } else {
      this.subwalks.add(e2, rest);
    }
  }
  testString(e2, p, rest, absolute) {
    if (!e2.isNamed(p))
      return;
    if (!rest) {
      this.matches.add(e2, absolute, false);
    } else {
      this.subwalks.add(e2, rest);
    }
  }
};
var makeIgnore = (ignore, opts) => typeof ignore === "string" ? new Ignore([ignore], opts) : Array.isArray(ignore) ? new Ignore(ignore, opts) : ignore;
var _onResume, _ignore, _sep, _GlobUtil_instances, ignored_fn, childrenIgnored_fn;
var GlobUtil = class {
  constructor(patterns, path3, opts) {
    __privateAdd(this, _GlobUtil_instances);
    __publicField(this, "path");
    __publicField(this, "patterns");
    __publicField(this, "opts");
    __publicField(this, "seen", /* @__PURE__ */ new Set());
    __publicField(this, "paused", false);
    __publicField(this, "aborted", false);
    __privateAdd(this, _onResume, []);
    __privateAdd(this, _ignore);
    __privateAdd(this, _sep);
    __publicField(this, "signal");
    __publicField(this, "maxDepth");
    __publicField(this, "includeChildMatches");
    this.patterns = patterns;
    this.path = path3;
    this.opts = opts;
    __privateSet(this, _sep, !opts.posix && opts.platform === "win32" ? "\\" : "/");
    this.includeChildMatches = opts.includeChildMatches !== false;
    if (opts.ignore || !this.includeChildMatches) {
      __privateSet(this, _ignore, makeIgnore(opts.ignore ?? [], opts));
      if (!this.includeChildMatches && typeof __privateGet(this, _ignore).add !== "function") {
        const m = "cannot ignore child matches, ignore lacks add() method.";
        throw new Error(m);
      }
    }
    this.maxDepth = opts.maxDepth || Infinity;
    if (opts.signal) {
      this.signal = opts.signal;
      this.signal.addEventListener("abort", () => {
        __privateGet(this, _onResume).length = 0;
      });
    }
  }
  // backpressure mechanism
  pause() {
    this.paused = true;
  }
  resume() {
    var _a4;
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      return;
    this.paused = false;
    let fn = void 0;
    while (!this.paused && (fn = __privateGet(this, _onResume).shift())) {
      fn();
    }
  }
  onResume(fn) {
    var _a4;
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      return;
    if (!this.paused) {
      fn();
    } else {
      __privateGet(this, _onResume).push(fn);
    }
  }
  // do the requisite realpath/stat checking, and return the path
  // to add or undefined to filter it out.
  async matchCheck(e2, ifDir) {
    if (ifDir && this.opts.nodir)
      return void 0;
    let rpc;
    if (this.opts.realpath) {
      rpc = e2.realpathCached() || await e2.realpath();
      if (!rpc)
        return void 0;
      e2 = rpc;
    }
    const needStat = e2.isUnknown() || this.opts.stat;
    const s = needStat ? await e2.lstat() : e2;
    if (this.opts.follow && this.opts.nodir && (s == null ? void 0 : s.isSymbolicLink())) {
      const target = await s.realpath();
      if (target && (target.isUnknown() || this.opts.stat)) {
        await target.lstat();
      }
    }
    return this.matchCheckTest(s, ifDir);
  }
  matchCheckTest(e2, ifDir) {
    var _a4;
    return e2 && (this.maxDepth === Infinity || e2.depth() <= this.maxDepth) && (!ifDir || e2.canReaddir()) && (!this.opts.nodir || !e2.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !e2.isSymbolicLink() || !((_a4 = e2.realpathCached()) == null ? void 0 : _a4.isDirectory())) && !__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, e2) ? e2 : void 0;
  }
  matchCheckSync(e2, ifDir) {
    if (ifDir && this.opts.nodir)
      return void 0;
    let rpc;
    if (this.opts.realpath) {
      rpc = e2.realpathCached() || e2.realpathSync();
      if (!rpc)
        return void 0;
      e2 = rpc;
    }
    const needStat = e2.isUnknown() || this.opts.stat;
    const s = needStat ? e2.lstatSync() : e2;
    if (this.opts.follow && this.opts.nodir && (s == null ? void 0 : s.isSymbolicLink())) {
      const target = s.realpathSync();
      if (target && ((target == null ? void 0 : target.isUnknown()) || this.opts.stat)) {
        target.lstatSync();
      }
    }
    return this.matchCheckTest(s, ifDir);
  }
  matchFinish(e2, absolute) {
    var _a4;
    if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, e2))
      return;
    if (!this.includeChildMatches && ((_a4 = __privateGet(this, _ignore)) == null ? void 0 : _a4.add)) {
      const ign = `${e2.relativePosix()}/**`;
      __privateGet(this, _ignore).add(ign);
    }
    const abs = this.opts.absolute === void 0 ? absolute : this.opts.absolute;
    this.seen.add(e2);
    const mark = this.opts.mark && e2.isDirectory() ? __privateGet(this, _sep) : "";
    if (this.opts.withFileTypes) {
      this.matchEmit(e2);
    } else if (abs) {
      const abs2 = this.opts.posix ? e2.fullpathPosix() : e2.fullpath();
      this.matchEmit(abs2 + mark);
    } else {
      const rel = this.opts.posix ? e2.relativePosix() : e2.relative();
      const pre = this.opts.dotRelative && !rel.startsWith(".." + __privateGet(this, _sep)) ? "." + __privateGet(this, _sep) : "";
      this.matchEmit(!rel ? "." + mark : pre + rel + mark);
    }
  }
  async match(e2, absolute, ifDir) {
    const p = await this.matchCheck(e2, ifDir);
    if (p)
      this.matchFinish(p, absolute);
  }
  matchSync(e2, absolute, ifDir) {
    const p = this.matchCheckSync(e2, ifDir);
    if (p)
      this.matchFinish(p, absolute);
  }
  walkCB(target, patterns, cb) {
    var _a4;
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      cb();
    this.walkCB2(target, patterns, new Processor(this.opts), cb);
  }
  walkCB2(target, patterns, processor, cb) {
    var _a4;
    if (__privateMethod(this, _GlobUtil_instances, childrenIgnored_fn).call(this, target))
      return cb();
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      cb();
    if (this.paused) {
      this.onResume(() => this.walkCB2(target, patterns, processor, cb));
      return;
    }
    processor.processPatterns(target, patterns);
    let tasks2 = 1;
    const next = () => {
      if (--tasks2 === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
        continue;
      tasks2++;
      this.match(m, absolute, ifDir).then(() => next());
    }
    for (const t2 of processor.subwalkTargets()) {
      if (this.maxDepth !== Infinity && t2.depth() >= this.maxDepth) {
        continue;
      }
      tasks2++;
      const childrenCached = t2.readdirCached();
      if (t2.calledReaddir())
        this.walkCB3(t2, childrenCached, processor, next);
      else {
        t2.readdirCB((_, entries) => this.walkCB3(t2, entries, processor, next), true);
      }
    }
    next();
  }
  walkCB3(target, entries, processor, cb) {
    processor = processor.filterEntries(target, entries);
    let tasks2 = 1;
    const next = () => {
      if (--tasks2 === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
        continue;
      tasks2++;
      this.match(m, absolute, ifDir).then(() => next());
    }
    for (const [target2, patterns] of processor.subwalks.entries()) {
      tasks2++;
      this.walkCB2(target2, patterns, processor.child(), next);
    }
    next();
  }
  walkCBSync(target, patterns, cb) {
    var _a4;
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      cb();
    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb);
  }
  walkCB2Sync(target, patterns, processor, cb) {
    var _a4;
    if (__privateMethod(this, _GlobUtil_instances, childrenIgnored_fn).call(this, target))
      return cb();
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      cb();
    if (this.paused) {
      this.onResume(() => this.walkCB2Sync(target, patterns, processor, cb));
      return;
    }
    processor.processPatterns(target, patterns);
    let tasks2 = 1;
    const next = () => {
      if (--tasks2 === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
        continue;
      this.matchSync(m, absolute, ifDir);
    }
    for (const t2 of processor.subwalkTargets()) {
      if (this.maxDepth !== Infinity && t2.depth() >= this.maxDepth) {
        continue;
      }
      tasks2++;
      const children = t2.readdirSync();
      this.walkCB3Sync(t2, children, processor, next);
    }
    next();
  }
  walkCB3Sync(target, entries, processor, cb) {
    processor = processor.filterEntries(target, entries);
    let tasks2 = 1;
    const next = () => {
      if (--tasks2 === 0)
        cb();
    };
    for (const [m, absolute, ifDir] of processor.matches.entries()) {
      if (__privateMethod(this, _GlobUtil_instances, ignored_fn).call(this, m))
        continue;
      this.matchSync(m, absolute, ifDir);
    }
    for (const [target2, patterns] of processor.subwalks.entries()) {
      tasks2++;
      this.walkCB2Sync(target2, patterns, processor.child(), next);
    }
    next();
  }
};
_onResume = new WeakMap();
_ignore = new WeakMap();
_sep = new WeakMap();
_GlobUtil_instances = new WeakSet();
ignored_fn = function(path3) {
  var _a4, _b3;
  return this.seen.has(path3) || !!((_b3 = (_a4 = __privateGet(this, _ignore)) == null ? void 0 : _a4.ignored) == null ? void 0 : _b3.call(_a4, path3));
};
childrenIgnored_fn = function(path3) {
  var _a4, _b3;
  return !!((_b3 = (_a4 = __privateGet(this, _ignore)) == null ? void 0 : _a4.childrenIgnored) == null ? void 0 : _b3.call(_a4, path3));
};
var GlobWalker = class extends GlobUtil {
  constructor(patterns, path3, opts) {
    super(patterns, path3, opts);
    __publicField(this, "matches", /* @__PURE__ */ new Set());
  }
  matchEmit(e2) {
    this.matches.add(e2);
  }
  async walk() {
    var _a4;
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      throw this.signal.reason;
    if (this.path.isUnknown()) {
      await this.path.lstat();
    }
    await new Promise((res, rej) => {
      this.walkCB(this.path, this.patterns, () => {
        var _a5;
        if ((_a5 = this.signal) == null ? void 0 : _a5.aborted) {
          rej(this.signal.reason);
        } else {
          res(this.matches);
        }
      });
    });
    return this.matches;
  }
  walkSync() {
    var _a4;
    if ((_a4 = this.signal) == null ? void 0 : _a4.aborted)
      throw this.signal.reason;
    if (this.path.isUnknown()) {
      this.path.lstatSync();
    }
    this.walkCBSync(this.path, this.patterns, () => {
      var _a5;
      if ((_a5 = this.signal) == null ? void 0 : _a5.aborted)
        throw this.signal.reason;
    });
    return this.matches;
  }
};
var GlobStream = class extends GlobUtil {
  constructor(patterns, path3, opts) {
    super(patterns, path3, opts);
    __publicField(this, "results");
    this.results = new Minipass({
      signal: this.signal,
      objectMode: true
    });
    this.results.on("drain", () => this.resume());
    this.results.on("resume", () => this.resume());
  }
  matchEmit(e2) {
    this.results.write(e2);
    if (!this.results.flowing)
      this.pause();
  }
  stream() {
    const target = this.path;
    if (target.isUnknown()) {
      target.lstat().then(() => {
        this.walkCB(target, this.patterns, () => this.results.end());
      });
    } else {
      this.walkCB(target, this.patterns, () => this.results.end());
    }
    return this.results;
  }
  streamSync() {
    if (this.path.isUnknown()) {
      this.path.lstatSync();
    }
    this.walkCBSync(this.path, this.patterns, () => this.results.end());
    return this.results;
  }
};
var defaultPlatform = typeof process === "object" && process && typeof process.platform === "string" ? process.platform : "linux";
var Glob = class {
  /**
   * All options are stored as properties on the `Glob` object.
   *
   * See {@link GlobOptions} for full options descriptions.
   *
   * Note that a previous `Glob` object can be passed as the
   * `GlobOptions` to another `Glob` instantiation to re-use settings
   * and caches with a new pattern.
   *
   * Traversal functions can be called multiple times to run the walk
   * again.
   */
  constructor(pattern2, opts) {
    __publicField(this, "absolute");
    __publicField(this, "cwd");
    __publicField(this, "root");
    __publicField(this, "dot");
    __publicField(this, "dotRelative");
    __publicField(this, "follow");
    __publicField(this, "ignore");
    __publicField(this, "magicalBraces");
    __publicField(this, "mark");
    __publicField(this, "matchBase");
    __publicField(this, "maxDepth");
    __publicField(this, "nobrace");
    __publicField(this, "nocase");
    __publicField(this, "nodir");
    __publicField(this, "noext");
    __publicField(this, "noglobstar");
    __publicField(this, "pattern");
    __publicField(this, "platform");
    __publicField(this, "realpath");
    __publicField(this, "scurry");
    __publicField(this, "stat");
    __publicField(this, "signal");
    __publicField(this, "windowsPathsNoEscape");
    __publicField(this, "withFileTypes");
    __publicField(this, "includeChildMatches");
    /**
     * The options provided to the constructor.
     */
    __publicField(this, "opts");
    /**
     * An array of parsed immutable {@link Pattern} objects.
     */
    __publicField(this, "patterns");
    if (!opts)
      throw new TypeError("glob options required");
    this.withFileTypes = !!opts.withFileTypes;
    this.signal = opts.signal;
    this.follow = !!opts.follow;
    this.dot = !!opts.dot;
    this.dotRelative = !!opts.dotRelative;
    this.nodir = !!opts.nodir;
    this.mark = !!opts.mark;
    if (!opts.cwd) {
      this.cwd = "";
    } else if (opts.cwd instanceof URL || opts.cwd.startsWith("file://")) {
      opts.cwd = (0, import_node_url2.fileURLToPath)(opts.cwd);
    }
    this.cwd = opts.cwd || "";
    this.root = opts.root;
    this.magicalBraces = !!opts.magicalBraces;
    this.nobrace = !!opts.nobrace;
    this.noext = !!opts.noext;
    this.realpath = !!opts.realpath;
    this.absolute = opts.absolute;
    this.includeChildMatches = opts.includeChildMatches !== false;
    this.noglobstar = !!opts.noglobstar;
    this.matchBase = !!opts.matchBase;
    this.maxDepth = typeof opts.maxDepth === "number" ? opts.maxDepth : Infinity;
    this.stat = !!opts.stat;
    this.ignore = opts.ignore;
    if (this.withFileTypes && this.absolute !== void 0) {
      throw new Error("cannot set absolute and withFileTypes:true");
    }
    if (typeof pattern2 === "string") {
      pattern2 = [pattern2];
    }
    this.windowsPathsNoEscape = !!opts.windowsPathsNoEscape || opts.allowWindowsEscape === false;
    if (this.windowsPathsNoEscape) {
      pattern2 = pattern2.map((p) => p.replace(/\\/g, "/"));
    }
    if (this.matchBase) {
      if (opts.noglobstar) {
        throw new TypeError("base matching requires globstar");
      }
      pattern2 = pattern2.map((p) => p.includes("/") ? p : `./**/${p}`);
    }
    this.pattern = pattern2;
    this.platform = opts.platform || defaultPlatform;
    this.opts = { ...opts, platform: this.platform };
    if (opts.scurry) {
      this.scurry = opts.scurry;
      if (opts.nocase !== void 0 && opts.nocase !== opts.scurry.nocase) {
        throw new Error("nocase option contradicts provided scurry option");
      }
    } else {
      const Scurry = opts.platform === "win32" ? PathScurryWin32 : opts.platform === "darwin" ? PathScurryDarwin : opts.platform ? PathScurryPosix : PathScurry;
      this.scurry = new Scurry(this.cwd, {
        nocase: opts.nocase,
        fs: opts.fs
      });
    }
    this.nocase = this.scurry.nocase;
    const nocaseMagicOnly = this.platform === "darwin" || this.platform === "win32";
    const mmo = {
      // default nocase based on platform
      ...opts,
      dot: this.dot,
      matchBase: this.matchBase,
      nobrace: this.nobrace,
      nocase: this.nocase,
      nocaseMagicOnly,
      nocomment: true,
      noext: this.noext,
      nonegate: true,
      optimizationLevel: 2,
      platform: this.platform,
      windowsPathsNoEscape: this.windowsPathsNoEscape,
      debug: !!this.opts.debug
    };
    const mms = this.pattern.map((p) => new Minimatch(p, mmo));
    const [matchSet, globParts] = mms.reduce((set2, m) => {
      set2[0].push(...m.set);
      set2[1].push(...m.globParts);
      return set2;
    }, [[], []]);
    this.patterns = matchSet.map((set2, i) => {
      const g = globParts[i];
      if (!g)
        throw new Error("invalid pattern object");
      return new Pattern(set2, g, 0, this.platform);
    });
  }
  async walk() {
    return [
      ...await new GlobWalker(this.patterns, this.scurry.cwd, {
        ...this.opts,
        maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
        platform: this.platform,
        nocase: this.nocase,
        includeChildMatches: this.includeChildMatches
      }).walk()
    ];
  }
  walkSync() {
    return [
      ...new GlobWalker(this.patterns, this.scurry.cwd, {
        ...this.opts,
        maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
        platform: this.platform,
        nocase: this.nocase,
        includeChildMatches: this.includeChildMatches
      }).walkSync()
    ];
  }
  stream() {
    return new GlobStream(this.patterns, this.scurry.cwd, {
      ...this.opts,
      maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
      platform: this.platform,
      nocase: this.nocase,
      includeChildMatches: this.includeChildMatches
    }).stream();
  }
  streamSync() {
    return new GlobStream(this.patterns, this.scurry.cwd, {
      ...this.opts,
      maxDepth: this.maxDepth !== Infinity ? this.maxDepth + this.scurry.cwd.depth() : Infinity,
      platform: this.platform,
      nocase: this.nocase,
      includeChildMatches: this.includeChildMatches
    }).streamSync();
  }
  /**
   * Default sync iteration function. Returns a Generator that
   * iterates over the results.
   */
  iterateSync() {
    return this.streamSync()[Symbol.iterator]();
  }
  [Symbol.iterator]() {
    return this.iterateSync();
  }
  /**
   * Default async iteration function. Returns an AsyncGenerator that
   * iterates over the results.
   */
  iterate() {
    return this.stream()[Symbol.asyncIterator]();
  }
  [Symbol.asyncIterator]() {
    return this.iterate();
  }
};
var hasMagic = (pattern2, options2 = {}) => {
  if (!Array.isArray(pattern2)) {
    pattern2 = [pattern2];
  }
  for (const p of pattern2) {
    if (new Minimatch(p, options2).hasMagic())
      return true;
  }
  return false;
};
function globStreamSync(pattern2, options2 = {}) {
  return new Glob(pattern2, options2).streamSync();
}
function globStream(pattern2, options2 = {}) {
  return new Glob(pattern2, options2).stream();
}
function globSync(pattern2, options2 = {}) {
  return new Glob(pattern2, options2).walkSync();
}
async function glob_(pattern2, options2 = {}) {
  return new Glob(pattern2, options2).walk();
}
function globIterateSync(pattern2, options2 = {}) {
  return new Glob(pattern2, options2).iterateSync();
}
function globIterate(pattern2, options2 = {}) {
  return new Glob(pattern2, options2).iterate();
}
var streamSync = globStreamSync;
var stream$5 = Object.assign(globStream, { sync: globStreamSync });
var iterateSync = globIterateSync;
var iterate = Object.assign(globIterate, {
  sync: globIterateSync
});
var sync$9 = Object.assign(globSync, {
  stream: globStreamSync,
  iterate: globIterateSync
});
var glob$1 = Object.assign(glob_, {
  glob: glob_,
  globSync,
  sync: sync$9,
  globStream,
  stream: stream$5,
  globStreamSync,
  streamSync,
  globIterate,
  iterate,
  globIterateSync,
  iterateSync,
  Glob,
  hasMagic,
  escape: escape$2,
  unescape: unescape$1
});
glob$1.glob = glob$1;
var comma = ",".charCodeAt(0);
var semicolon = ";".charCodeAt(0);
var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var intToChar = new Uint8Array(64);
var charToInt = new Uint8Array(128);
for (let i = 0; i < chars$1.length; i++) {
  const c = chars$1.charCodeAt(i);
  intToChar[i] = c;
  charToInt[c] = i;
}
var td = typeof TextDecoder !== "undefined" ? new TextDecoder() : typeof Buffer !== "undefined" ? {
  decode(buf) {
    const out2 = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
    return out2.toString();
  }
} : {
  decode(buf) {
    let out2 = "";
    for (let i = 0; i < buf.length; i++) {
      out2 += String.fromCharCode(buf[i]);
    }
    return out2;
  }
};
function decode(mappings) {
  const state = new Int32Array(5);
  const decoded = [];
  let index = 0;
  do {
    const semi = indexOf(mappings, index);
    const line = [];
    let sorted = true;
    let lastCol = 0;
    state[0] = 0;
    for (let i = index; i < semi; i++) {
      let seg;
      i = decodeInteger(mappings, i, state, 0);
      const col = state[0];
      if (col < lastCol)
        sorted = false;
      lastCol = col;
      if (hasMoreVlq(mappings, i, semi)) {
        i = decodeInteger(mappings, i, state, 1);
        i = decodeInteger(mappings, i, state, 2);
        i = decodeInteger(mappings, i, state, 3);
        if (hasMoreVlq(mappings, i, semi)) {
          i = decodeInteger(mappings, i, state, 4);
          seg = [col, state[1], state[2], state[3], state[4]];
        } else {
          seg = [col, state[1], state[2], state[3]];
        }
      } else {
        seg = [col];
      }
      line.push(seg);
    }
    if (!sorted)
      sort(line);
    decoded.push(line);
    index = semi + 1;
  } while (index <= mappings.length);
  return decoded;
}
function indexOf(mappings, index) {
  const idx = mappings.indexOf(";", index);
  return idx === -1 ? mappings.length : idx;
}
function decodeInteger(mappings, pos, state, j) {
  let value2 = 0;
  let shift = 0;
  let integer = 0;
  do {
    const c = mappings.charCodeAt(pos++);
    integer = charToInt[c];
    value2 |= (integer & 31) << shift;
    shift += 5;
  } while (integer & 32);
  const shouldNegate = value2 & 1;
  value2 >>>= 1;
  if (shouldNegate) {
    value2 = -2147483648 | -value2;
  }
  state[j] += value2;
  return pos;
}
function hasMoreVlq(mappings, i, length) {
  if (i >= length)
    return false;
  return mappings.charCodeAt(i) !== comma;
}
function sort(line) {
  line.sort(sortComparator$1);
}
function sortComparator$1(a, b) {
  return a[0] - b[0];
}
function encode$1(decoded) {
  const state = new Int32Array(5);
  const bufLength = 1024 * 16;
  const subLength = bufLength - 36;
  const buf = new Uint8Array(bufLength);
  const sub = buf.subarray(0, subLength);
  let pos = 0;
  let out2 = "";
  for (let i = 0; i < decoded.length; i++) {
    const line = decoded[i];
    if (i > 0) {
      if (pos === bufLength) {
        out2 += td.decode(buf);
        pos = 0;
      }
      buf[pos++] = semicolon;
    }
    if (line.length === 0)
      continue;
    state[0] = 0;
    for (let j = 0; j < line.length; j++) {
      const segment = line[j];
      if (pos > subLength) {
        out2 += td.decode(sub);
        buf.copyWithin(0, subLength, pos);
        pos -= subLength;
      }
      if (j > 0)
        buf[pos++] = comma;
      pos = encodeInteger(buf, pos, state, segment, 0);
      if (segment.length === 1)
        continue;
      pos = encodeInteger(buf, pos, state, segment, 1);
      pos = encodeInteger(buf, pos, state, segment, 2);
      pos = encodeInteger(buf, pos, state, segment, 3);
      if (segment.length === 4)
        continue;
      pos = encodeInteger(buf, pos, state, segment, 4);
    }
  }
  return out2 + td.decode(buf.subarray(0, pos));
}
function encodeInteger(buf, pos, state, segment, j) {
  const next = segment[j];
  let num = next - state[j];
  state[j] = next;
  num = num < 0 ? -num << 1 | 1 : num << 1;
  do {
    let clamped = num & 31;
    num >>>= 5;
    if (num > 0)
      clamped |= 32;
    buf[pos++] = intToChar[clamped];
  } while (num > 0);
  return pos;
}
var BitSet = class _BitSet {
  constructor(arg) {
    this.bits = arg instanceof _BitSet ? arg.bits.slice() : [];
  }
  add(n2) {
    this.bits[n2 >> 5] |= 1 << (n2 & 31);
  }
  has(n2) {
    return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
  }
};
var Chunk = class _Chunk {
  constructor(start, end, content) {
    this.start = start;
    this.end = end;
    this.original = content;
    this.intro = "";
    this.outro = "";
    this.content = content;
    this.storeName = false;
    this.edited = false;
    {
      this.previous = null;
      this.next = null;
    }
  }
  appendLeft(content) {
    this.outro += content;
  }
  appendRight(content) {
    this.intro = this.intro + content;
  }
  clone() {
    const chunk = new _Chunk(this.start, this.end, this.original);
    chunk.intro = this.intro;
    chunk.outro = this.outro;
    chunk.content = this.content;
    chunk.storeName = this.storeName;
    chunk.edited = this.edited;
    return chunk;
  }
  contains(index) {
    return this.start < index && index < this.end;
  }
  eachNext(fn) {
    let chunk = this;
    while (chunk) {
      fn(chunk);
      chunk = chunk.next;
    }
  }
  eachPrevious(fn) {
    let chunk = this;
    while (chunk) {
      fn(chunk);
      chunk = chunk.previous;
    }
  }
  edit(content, storeName, contentOnly) {
    this.content = content;
    if (!contentOnly) {
      this.intro = "";
      this.outro = "";
    }
    this.storeName = storeName;
    this.edited = true;
    return this;
  }
  prependLeft(content) {
    this.outro = content + this.outro;
  }
  prependRight(content) {
    this.intro = content + this.intro;
  }
  reset() {
    this.intro = "";
    this.outro = "";
    if (this.edited) {
      this.content = this.original;
      this.storeName = false;
      this.edited = false;
    }
  }
  split(index) {
    const sliceIndex = index - this.start;
    const originalBefore = this.original.slice(0, sliceIndex);
    const originalAfter = this.original.slice(sliceIndex);
    this.original = originalBefore;
    const newChunk = new _Chunk(index, this.end, originalAfter);
    newChunk.outro = this.outro;
    this.outro = "";
    this.end = index;
    if (this.edited) {
      newChunk.edit("", false);
      this.content = "";
    } else {
      this.content = originalBefore;
    }
    newChunk.next = this.next;
    if (newChunk.next) newChunk.next.previous = newChunk;
    newChunk.previous = this;
    this.next = newChunk;
    return newChunk;
  }
  toString() {
    return this.intro + this.content + this.outro;
  }
  trimEnd(rx) {
    this.outro = this.outro.replace(rx, "");
    if (this.outro.length) return true;
    const trimmed = this.content.replace(rx, "");
    if (trimmed.length) {
      if (trimmed !== this.content) {
        this.split(this.start + trimmed.length).edit("", void 0, true);
        if (this.edited) {
          this.edit(trimmed, this.storeName, true);
        }
      }
      return true;
    } else {
      this.edit("", void 0, true);
      this.intro = this.intro.replace(rx, "");
      if (this.intro.length) return true;
    }
  }
  trimStart(rx) {
    this.intro = this.intro.replace(rx, "");
    if (this.intro.length) return true;
    const trimmed = this.content.replace(rx, "");
    if (trimmed.length) {
      if (trimmed !== this.content) {
        const newChunk = this.split(this.end - trimmed.length);
        if (this.edited) {
          newChunk.edit(trimmed, this.storeName, true);
        }
        this.edit("", void 0, true);
      }
      return true;
    } else {
      this.edit("", void 0, true);
      this.outro = this.outro.replace(rx, "");
      if (this.outro.length) return true;
    }
  }
};
function getBtoa() {
  if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
    return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  } else if (typeof Buffer === "function") {
    return (str) => Buffer.from(str, "utf-8").toString("base64");
  } else {
    return () => {
      throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
    };
  }
}
var btoa$1 = getBtoa();
var SourceMap$1 = class SourceMap {
  constructor(properties) {
    this.version = 3;
    this.file = properties.file;
    this.sources = properties.sources;
    this.sourcesContent = properties.sourcesContent;
    this.names = properties.names;
    this.mappings = encode$1(properties.mappings);
    if (typeof properties.x_google_ignoreList !== "undefined") {
      this.x_google_ignoreList = properties.x_google_ignoreList;
    }
  }
  toString() {
    return JSON.stringify(this);
  }
  toUrl() {
    return "data:application/json;charset=utf-8;base64," + btoa$1(this.toString());
  }
};
function guessIndent(code) {
  const lines = code.split("\n");
  const tabbed = lines.filter((line) => /^\t+/.test(line));
  const spaced = lines.filter((line) => /^ {2,}/.test(line));
  if (tabbed.length === 0 && spaced.length === 0) {
    return null;
  }
  if (tabbed.length >= spaced.length) {
    return "	";
  }
  const min2 = spaced.reduce((previous, current) => {
    const numSpaces = /^ +/.exec(current)[0].length;
    return Math.min(numSpaces, previous);
  }, Infinity);
  return new Array(min2 + 1).join(" ");
}
function getRelativePath(from, to) {
  const fromParts = from.split(/[/\\]/);
  const toParts = to.split(/[/\\]/);
  fromParts.pop();
  while (fromParts[0] === toParts[0]) {
    fromParts.shift();
    toParts.shift();
  }
  if (fromParts.length) {
    let i = fromParts.length;
    while (i--) fromParts[i] = "..";
  }
  return fromParts.concat(toParts).join("/");
}
var toString$1 = Object.prototype.toString;
function isObject$2(thing) {
  return toString$1.call(thing) === "[object Object]";
}
function getLocator(source) {
  const originalLines = source.split("\n");
  const lineOffsets = [];
  for (let i = 0, pos = 0; i < originalLines.length; i++) {
    lineOffsets.push(pos);
    pos += originalLines[i].length + 1;
  }
  return function locate(index) {
    let i = 0;
    let j = lineOffsets.length;
    while (i < j) {
      const m = i + j >> 1;
      if (index < lineOffsets[m]) {
        j = m;
      } else {
        i = m + 1;
      }
    }
    const line = i - 1;
    const column = index - lineOffsets[line];
    return { line, column };
  };
}
var wordRegex = /\w/;
var Mappings = class {
  constructor(hires) {
    this.hires = hires;
    this.generatedCodeLine = 0;
    this.generatedCodeColumn = 0;
    this.raw = [];
    this.rawSegments = this.raw[this.generatedCodeLine] = [];
    this.pending = null;
  }
  addEdit(sourceIndex, content, loc, nameIndex) {
    if (content.length) {
      const contentLengthMinusOne = content.length - 1;
      let contentLineEnd = content.indexOf("\n", 0);
      let previousContentLineEnd = -1;
      while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
        const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
        if (nameIndex >= 0) {
          segment2.push(nameIndex);
        }
        this.rawSegments.push(segment2);
        this.generatedCodeLine += 1;
        this.raw[this.generatedCodeLine] = this.rawSegments = [];
        this.generatedCodeColumn = 0;
        previousContentLineEnd = contentLineEnd;
        contentLineEnd = content.indexOf("\n", contentLineEnd + 1);
      }
      const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
      if (nameIndex >= 0) {
        segment.push(nameIndex);
      }
      this.rawSegments.push(segment);
      this.advance(content.slice(previousContentLineEnd + 1));
    } else if (this.pending) {
      this.rawSegments.push(this.pending);
      this.advance(content);
    }
    this.pending = null;
  }
  addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
    let originalCharIndex = chunk.start;
    let first2 = true;
    let charInHiresBoundary = false;
    while (originalCharIndex < chunk.end) {
      if (this.hires || first2 || sourcemapLocations.has(originalCharIndex)) {
        const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
        if (this.hires === "boundary") {
          if (wordRegex.test(original[originalCharIndex])) {
            if (!charInHiresBoundary) {
              this.rawSegments.push(segment);
              charInHiresBoundary = true;
            }
          } else {
            this.rawSegments.push(segment);
            charInHiresBoundary = false;
          }
        } else {
          this.rawSegments.push(segment);
        }
      }
      if (original[originalCharIndex] === "\n") {
        loc.line += 1;
        loc.column = 0;
        this.generatedCodeLine += 1;
        this.raw[this.generatedCodeLine] = this.rawSegments = [];
        this.generatedCodeColumn = 0;
        first2 = true;
      } else {
        loc.column += 1;
        this.generatedCodeColumn += 1;
        first2 = false;
      }
      originalCharIndex += 1;
    }
    this.pending = null;
  }
  advance(str) {
    if (!str) return;
    const lines = str.split("\n");
    if (lines.length > 1) {
      for (let i = 0; i < lines.length - 1; i++) {
        this.generatedCodeLine++;
        this.raw[this.generatedCodeLine] = this.rawSegments = [];
      }
      this.generatedCodeColumn = 0;
    }
    this.generatedCodeColumn += lines[lines.length - 1].length;
  }
};
var n$1 = "\n";
var warned = {
  insertLeft: false,
  insertRight: false,
  storeName: false
};
var MagicString = class _MagicString {
  constructor(string2, options2 = {}) {
    const chunk = new Chunk(0, string2.length, string2);
    Object.defineProperties(this, {
      original: { writable: true, value: string2 },
      outro: { writable: true, value: "" },
      intro: { writable: true, value: "" },
      firstChunk: { writable: true, value: chunk },
      lastChunk: { writable: true, value: chunk },
      lastSearchedChunk: { writable: true, value: chunk },
      byStart: { writable: true, value: {} },
      byEnd: { writable: true, value: {} },
      filename: { writable: true, value: options2.filename },
      indentExclusionRanges: { writable: true, value: options2.indentExclusionRanges },
      sourcemapLocations: { writable: true, value: new BitSet() },
      storedNames: { writable: true, value: {} },
      indentStr: { writable: true, value: void 0 },
      ignoreList: { writable: true, value: options2.ignoreList }
    });
    this.byStart[0] = chunk;
    this.byEnd[string2.length] = chunk;
  }
  addSourcemapLocation(char) {
    this.sourcemapLocations.add(char);
  }
  append(content) {
    if (typeof content !== "string") throw new TypeError("outro content must be a string");
    this.outro += content;
    return this;
  }
  appendLeft(index, content) {
    if (typeof content !== "string") throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byEnd[index];
    if (chunk) {
      chunk.appendLeft(content);
    } else {
      this.intro += content;
    }
    return this;
  }
  appendRight(index, content) {
    if (typeof content !== "string") throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byStart[index];
    if (chunk) {
      chunk.appendRight(content);
    } else {
      this.outro += content;
    }
    return this;
  }
  clone() {
    const cloned = new _MagicString(this.original, { filename: this.filename });
    let originalChunk = this.firstChunk;
    let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
    while (originalChunk) {
      cloned.byStart[clonedChunk.start] = clonedChunk;
      cloned.byEnd[clonedChunk.end] = clonedChunk;
      const nextOriginalChunk = originalChunk.next;
      const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
      if (nextClonedChunk) {
        clonedChunk.next = nextClonedChunk;
        nextClonedChunk.previous = clonedChunk;
        clonedChunk = nextClonedChunk;
      }
      originalChunk = nextOriginalChunk;
    }
    cloned.lastChunk = clonedChunk;
    if (this.indentExclusionRanges) {
      cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
    }
    cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
    cloned.intro = this.intro;
    cloned.outro = this.outro;
    return cloned;
  }
  generateDecodedMap(options2) {
    options2 = options2 || {};
    const sourceIndex = 0;
    const names = Object.keys(this.storedNames);
    const mappings = new Mappings(options2.hires);
    const locate = getLocator(this.original);
    if (this.intro) {
      mappings.advance(this.intro);
    }
    this.firstChunk.eachNext((chunk) => {
      const loc = locate(chunk.start);
      if (chunk.intro.length) mappings.advance(chunk.intro);
      if (chunk.edited) {
        mappings.addEdit(
          sourceIndex,
          chunk.content,
          loc,
          chunk.storeName ? names.indexOf(chunk.original) : -1
        );
      } else {
        mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
      }
      if (chunk.outro.length) mappings.advance(chunk.outro);
    });
    return {
      file: options2.file ? options2.file.split(/[/\\]/).pop() : void 0,
      sources: [
        options2.source ? getRelativePath(options2.file || "", options2.source) : options2.file || ""
      ],
      sourcesContent: options2.includeContent ? [this.original] : void 0,
      names,
      mappings: mappings.raw,
      x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
    };
  }
  generateMap(options2) {
    return new SourceMap$1(this.generateDecodedMap(options2));
  }
  _ensureindentStr() {
    if (this.indentStr === void 0) {
      this.indentStr = guessIndent(this.original);
    }
  }
  _getRawIndentString() {
    this._ensureindentStr();
    return this.indentStr;
  }
  getIndentString() {
    this._ensureindentStr();
    return this.indentStr === null ? "	" : this.indentStr;
  }
  indent(indentStr, options2) {
    const pattern2 = /^[^\r\n]/gm;
    if (isObject$2(indentStr)) {
      options2 = indentStr;
      indentStr = void 0;
    }
    if (indentStr === void 0) {
      this._ensureindentStr();
      indentStr = this.indentStr || "	";
    }
    if (indentStr === "") return this;
    options2 = options2 || {};
    const isExcluded = {};
    if (options2.exclude) {
      const exclusions = typeof options2.exclude[0] === "number" ? [options2.exclude] : options2.exclude;
      exclusions.forEach((exclusion) => {
        for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
          isExcluded[i] = true;
        }
      });
    }
    let shouldIndentNextCharacter = options2.indentStart !== false;
    const replacer = (match2) => {
      if (shouldIndentNextCharacter) return `${indentStr}${match2}`;
      shouldIndentNextCharacter = true;
      return match2;
    };
    this.intro = this.intro.replace(pattern2, replacer);
    let charIndex = 0;
    let chunk = this.firstChunk;
    while (chunk) {
      const end = chunk.end;
      if (chunk.edited) {
        if (!isExcluded[charIndex]) {
          chunk.content = chunk.content.replace(pattern2, replacer);
          if (chunk.content.length) {
            shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
          }
        }
      } else {
        charIndex = chunk.start;
        while (charIndex < end) {
          if (!isExcluded[charIndex]) {
            const char = this.original[charIndex];
            if (char === "\n") {
              shouldIndentNextCharacter = true;
            } else if (char !== "\r" && shouldIndentNextCharacter) {
              shouldIndentNextCharacter = false;
              if (charIndex === chunk.start) {
                chunk.prependRight(indentStr);
              } else {
                this._splitChunk(chunk, charIndex);
                chunk = chunk.next;
                chunk.prependRight(indentStr);
              }
            }
          }
          charIndex += 1;
        }
      }
      charIndex = chunk.end;
      chunk = chunk.next;
    }
    this.outro = this.outro.replace(pattern2, replacer);
    return this;
  }
  insert() {
    throw new Error(
      "magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
    );
  }
  insertLeft(index, content) {
    if (!warned.insertLeft) {
      console.warn(
        "magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
      );
      warned.insertLeft = true;
    }
    return this.appendLeft(index, content);
  }
  insertRight(index, content) {
    if (!warned.insertRight) {
      console.warn(
        "magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
      );
      warned.insertRight = true;
    }
    return this.prependRight(index, content);
  }
  move(start, end, index) {
    if (index >= start && index <= end) throw new Error("Cannot move a selection inside itself");
    this._split(start);
    this._split(end);
    this._split(index);
    const first2 = this.byStart[start];
    const last = this.byEnd[end];
    const oldLeft = first2.previous;
    const oldRight = last.next;
    const newRight = this.byStart[index];
    if (!newRight && last === this.lastChunk) return this;
    const newLeft = newRight ? newRight.previous : this.lastChunk;
    if (oldLeft) oldLeft.next = oldRight;
    if (oldRight) oldRight.previous = oldLeft;
    if (newLeft) newLeft.next = first2;
    if (newRight) newRight.previous = last;
    if (!first2.previous) this.firstChunk = last.next;
    if (!last.next) {
      this.lastChunk = first2.previous;
      this.lastChunk.next = null;
    }
    first2.previous = newLeft;
    last.next = newRight || null;
    if (!newLeft) this.firstChunk = first2;
    if (!newRight) this.lastChunk = last;
    return this;
  }
  overwrite(start, end, content, options2) {
    options2 = options2 || {};
    return this.update(start, end, content, { ...options2, overwrite: !options2.contentOnly });
  }
  update(start, end, content, options2) {
    if (typeof content !== "string") throw new TypeError("replacement content must be a string");
    while (start < 0) start += this.original.length;
    while (end < 0) end += this.original.length;
    if (end > this.original.length) throw new Error("end is out of bounds");
    if (start === end)
      throw new Error(
        "Cannot overwrite a zero-length range – use appendLeft or prependRight instead"
      );
    this._split(start);
    this._split(end);
    if (options2 === true) {
      if (!warned.storeName) {
        console.warn(
          "The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
        );
        warned.storeName = true;
      }
      options2 = { storeName: true };
    }
    const storeName = options2 !== void 0 ? options2.storeName : false;
    const overwrite = options2 !== void 0 ? options2.overwrite : false;
    if (storeName) {
      const original = this.original.slice(start, end);
      Object.defineProperty(this.storedNames, original, {
        writable: true,
        value: true,
        enumerable: true
      });
    }
    const first2 = this.byStart[start];
    const last = this.byEnd[end];
    if (first2) {
      let chunk = first2;
      while (chunk !== last) {
        if (chunk.next !== this.byStart[chunk.end]) {
          throw new Error("Cannot overwrite across a split point");
        }
        chunk = chunk.next;
        chunk.edit("", false);
      }
      first2.edit(content, storeName, !overwrite);
    } else {
      const newChunk = new Chunk(start, end, "").edit(content, storeName);
      last.next = newChunk;
      newChunk.previous = last;
    }
    return this;
  }
  prepend(content) {
    if (typeof content !== "string") throw new TypeError("outro content must be a string");
    this.intro = content + this.intro;
    return this;
  }
  prependLeft(index, content) {
    if (typeof content !== "string") throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byEnd[index];
    if (chunk) {
      chunk.prependLeft(content);
    } else {
      this.intro = content + this.intro;
    }
    return this;
  }
  prependRight(index, content) {
    if (typeof content !== "string") throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byStart[index];
    if (chunk) {
      chunk.prependRight(content);
    } else {
      this.outro = content + this.outro;
    }
    return this;
  }
  remove(start, end) {
    while (start < 0) start += this.original.length;
    while (end < 0) end += this.original.length;
    if (start === end) return this;
    if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
    if (start > end) throw new Error("end must be greater than start");
    this._split(start);
    this._split(end);
    let chunk = this.byStart[start];
    while (chunk) {
      chunk.intro = "";
      chunk.outro = "";
      chunk.edit("");
      chunk = end > chunk.end ? this.byStart[chunk.end] : null;
    }
    return this;
  }
  reset(start, end) {
    while (start < 0) start += this.original.length;
    while (end < 0) end += this.original.length;
    if (start === end) return this;
    if (start < 0 || end > this.original.length) throw new Error("Character is out of bounds");
    if (start > end) throw new Error("end must be greater than start");
    this._split(start);
    this._split(end);
    let chunk = this.byStart[start];
    while (chunk) {
      chunk.reset();
      chunk = end > chunk.end ? this.byStart[chunk.end] : null;
    }
    return this;
  }
  lastChar() {
    if (this.outro.length) return this.outro[this.outro.length - 1];
    let chunk = this.lastChunk;
    do {
      if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
      if (chunk.content.length) return chunk.content[chunk.content.length - 1];
      if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
    } while (chunk = chunk.previous);
    if (this.intro.length) return this.intro[this.intro.length - 1];
    return "";
  }
  lastLine() {
    let lineIndex = this.outro.lastIndexOf(n$1);
    if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
    let lineStr = this.outro;
    let chunk = this.lastChunk;
    do {
      if (chunk.outro.length > 0) {
        lineIndex = chunk.outro.lastIndexOf(n$1);
        if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
        lineStr = chunk.outro + lineStr;
      }
      if (chunk.content.length > 0) {
        lineIndex = chunk.content.lastIndexOf(n$1);
        if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
        lineStr = chunk.content + lineStr;
      }
      if (chunk.intro.length > 0) {
        lineIndex = chunk.intro.lastIndexOf(n$1);
        if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
        lineStr = chunk.intro + lineStr;
      }
    } while (chunk = chunk.previous);
    lineIndex = this.intro.lastIndexOf(n$1);
    if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
    return this.intro + lineStr;
  }
  slice(start = 0, end = this.original.length) {
    while (start < 0) start += this.original.length;
    while (end < 0) end += this.original.length;
    let result = "";
    let chunk = this.firstChunk;
    while (chunk && (chunk.start > start || chunk.end <= start)) {
      if (chunk.start < end && chunk.end >= end) {
        return result;
      }
      chunk = chunk.next;
    }
    if (chunk && chunk.edited && chunk.start !== start)
      throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
    const startChunk = chunk;
    while (chunk) {
      if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
        result += chunk.intro;
      }
      const containsEnd = chunk.start < end && chunk.end >= end;
      if (containsEnd && chunk.edited && chunk.end !== end)
        throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
      const sliceStart = startChunk === chunk ? start - chunk.start : 0;
      const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
      result += chunk.content.slice(sliceStart, sliceEnd);
      if (chunk.outro && (!containsEnd || chunk.end === end)) {
        result += chunk.outro;
      }
      if (containsEnd) {
        break;
      }
      chunk = chunk.next;
    }
    return result;
  }
  // TODO deprecate this? not really very useful
  snip(start, end) {
    const clone2 = this.clone();
    clone2.remove(0, start);
    clone2.remove(end, clone2.original.length);
    return clone2;
  }
  _split(index) {
    if (this.byStart[index] || this.byEnd[index]) return;
    let chunk = this.lastSearchedChunk;
    const searchForward = index > chunk.end;
    while (chunk) {
      if (chunk.contains(index)) return this._splitChunk(chunk, index);
      chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
    }
  }
  _splitChunk(chunk, index) {
    if (chunk.edited && chunk.content.length) {
      const loc = getLocator(this.original)(index);
      throw new Error(
        `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
      );
    }
    const newChunk = chunk.split(index);
    this.byEnd[index] = chunk;
    this.byStart[index] = newChunk;
    this.byEnd[newChunk.end] = newChunk;
    if (chunk === this.lastChunk) this.lastChunk = newChunk;
    this.lastSearchedChunk = chunk;
    return true;
  }
  toString() {
    let str = this.intro;
    let chunk = this.firstChunk;
    while (chunk) {
      str += chunk.toString();
      chunk = chunk.next;
    }
    return str + this.outro;
  }
  isEmpty() {
    let chunk = this.firstChunk;
    do {
      if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
        return false;
    } while (chunk = chunk.next);
    return true;
  }
  length() {
    let chunk = this.firstChunk;
    let length = 0;
    do {
      length += chunk.intro.length + chunk.content.length + chunk.outro.length;
    } while (chunk = chunk.next);
    return length;
  }
  trimLines() {
    return this.trim("[\\r\\n]");
  }
  trim(charType) {
    return this.trimStart(charType).trimEnd(charType);
  }
  trimEndAborted(charType) {
    const rx = new RegExp((charType || "\\s") + "+$");
    this.outro = this.outro.replace(rx, "");
    if (this.outro.length) return true;
    let chunk = this.lastChunk;
    do {
      const end = chunk.end;
      const aborted = chunk.trimEnd(rx);
      if (chunk.end !== end) {
        if (this.lastChunk === chunk) {
          this.lastChunk = chunk.next;
        }
        this.byEnd[chunk.end] = chunk;
        this.byStart[chunk.next.start] = chunk.next;
        this.byEnd[chunk.next.end] = chunk.next;
      }
      if (aborted) return true;
      chunk = chunk.previous;
    } while (chunk);
    return false;
  }
  trimEnd(charType) {
    this.trimEndAborted(charType);
    return this;
  }
  trimStartAborted(charType) {
    const rx = new RegExp("^" + (charType || "\\s") + "+");
    this.intro = this.intro.replace(rx, "");
    if (this.intro.length) return true;
    let chunk = this.firstChunk;
    do {
      const end = chunk.end;
      const aborted = chunk.trimStart(rx);
      if (chunk.end !== end) {
        if (chunk === this.lastChunk) this.lastChunk = chunk.next;
        this.byEnd[chunk.end] = chunk;
        this.byStart[chunk.next.start] = chunk.next;
        this.byEnd[chunk.next.end] = chunk.next;
      }
      if (aborted) return true;
      chunk = chunk.next;
    } while (chunk);
    return false;
  }
  trimStart(charType) {
    this.trimStartAborted(charType);
    return this;
  }
  hasChanged() {
    return this.original !== this.toString();
  }
  _replaceRegexp(searchValue, replacement) {
    function getReplacement(match2, str) {
      if (typeof replacement === "string") {
        return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
          if (i === "$") return "$";
          if (i === "&") return match2[0];
          const num = +i;
          if (num < match2.length) return match2[+i];
          return `$${i}`;
        });
      } else {
        return replacement(...match2, match2.index, str, match2.groups);
      }
    }
    function matchAll2(re, str) {
      let match2;
      const matches2 = [];
      while (match2 = re.exec(str)) {
        matches2.push(match2);
      }
      return matches2;
    }
    if (searchValue.global) {
      const matches2 = matchAll2(searchValue, this.original);
      matches2.forEach((match2) => {
        if (match2.index != null) {
          const replacement2 = getReplacement(match2, this.original);
          if (replacement2 !== match2[0]) {
            this.overwrite(
              match2.index,
              match2.index + match2[0].length,
              replacement2
            );
          }
        }
      });
    } else {
      const match2 = this.original.match(searchValue);
      if (match2 && match2.index != null) {
        const replacement2 = getReplacement(match2, this.original);
        if (replacement2 !== match2[0]) {
          this.overwrite(
            match2.index,
            match2.index + match2[0].length,
            replacement2
          );
        }
      }
    }
    return this;
  }
  _replaceString(string2, replacement) {
    const { original } = this;
    const index = original.indexOf(string2);
    if (index !== -1) {
      this.overwrite(index, index + string2.length, replacement);
    }
    return this;
  }
  replace(searchValue, replacement) {
    if (typeof searchValue === "string") {
      return this._replaceString(searchValue, replacement);
    }
    return this._replaceRegexp(searchValue, replacement);
  }
  _replaceAllString(string2, replacement) {
    const { original } = this;
    const stringLength = string2.length;
    for (let index = original.indexOf(string2); index !== -1; index = original.indexOf(string2, index + stringLength)) {
      const previous = original.slice(index, index + stringLength);
      if (previous !== replacement)
        this.overwrite(index, index + stringLength, replacement);
    }
    return this;
  }
  replaceAll(searchValue, replacement) {
    if (typeof searchValue === "string") {
      return this._replaceAllString(searchValue, replacement);
    }
    if (!searchValue.global) {
      throw new TypeError(
        "MagicString.prototype.replaceAll called with a non-global RegExp argument"
      );
    }
    return this._replaceRegexp(searchValue, replacement);
  }
};
function isReference(node2, parent) {
  if (node2.type === "MemberExpression") {
    return !node2.computed && isReference(node2.object, node2);
  }
  if (node2.type === "Identifier") {
    if (!parent)
      return true;
    switch (parent.type) {
      case "MemberExpression":
        return parent.computed || node2 === parent.object;
      case "MethodDefinition":
        return parent.computed;
      case "FieldDefinition":
        return parent.computed || node2 === parent.value;
      case "Property":
        return parent.computed || node2 === parent.value;
      case "ExportSpecifier":
      case "ImportSpecifier":
        return node2 === parent.local;
      case "LabeledStatement":
      case "BreakStatement":
      case "ContinueStatement":
        return false;
      default:
        return true;
    }
  }
  return false;
}
var version$2 = "26.0.1";
var peerDependencies = {
  rollup: "^2.68.0||^3.0.0||^4.0.0"
};
function tryParse(parse4, code, id) {
  try {
    return parse4(code, { allowReturnOutsideFunction: true });
  } catch (err2) {
    err2.message += ` in ${id}`;
    throw err2;
  }
}
var firstpassGlobal = /\b(?:require|module|exports|global)\b/;
var firstpassNoGlobal = /\b(?:require|module|exports)\b/;
function hasCjsKeywords(code, ignoreGlobal) {
  const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
  return firstpass.test(code);
}
function analyzeTopLevelStatements(parse4, code, id) {
  const ast = tryParse(parse4, code, id);
  let isEsModule = false;
  let hasDefaultExport = false;
  let hasNamedExports = false;
  for (const node2 of ast.body) {
    switch (node2.type) {
      case "ExportDefaultDeclaration":
        isEsModule = true;
        hasDefaultExport = true;
        break;
      case "ExportNamedDeclaration":
        isEsModule = true;
        if (node2.declaration) {
          hasNamedExports = true;
        } else {
          for (const specifier of node2.specifiers) {
            if (specifier.exported.name === "default") {
              hasDefaultExport = true;
            } else {
              hasNamedExports = true;
            }
          }
        }
        break;
      case "ExportAllDeclaration":
        isEsModule = true;
        if (node2.exported && node2.exported.name === "default") {
          hasDefaultExport = true;
        } else {
          hasNamedExports = true;
        }
        break;
      case "ImportDeclaration":
        isEsModule = true;
        break;
    }
  }
  return { isEsModule, hasDefaultExport, hasNamedExports, ast };
}
function deconflict(scopes, globals, identifier) {
  let i = 1;
  let deconflicted = makeLegalIdentifier(identifier);
  const hasConflicts = () => scopes.some((scope) => scope.contains(deconflicted)) || globals.has(deconflicted);
  while (hasConflicts()) {
    deconflicted = makeLegalIdentifier(`${identifier}_${i}`);
    i += 1;
  }
  for (const scope of scopes) {
    scope.declarations[deconflicted] = true;
  }
  return deconflicted;
}
function getName(id) {
  const name2 = makeLegalIdentifier((0, import_path.basename)(id, (0, import_path.extname)(id)));
  if (name2 !== "index") {
    return name2;
  }
  return makeLegalIdentifier((0, import_path.basename)((0, import_path.dirname)(id)));
}
function normalizePathSlashes(path3) {
  return path3.replace(/\\/g, "/");
}
var getVirtualPathForDynamicRequirePath = (path3, commonDir) => `/${normalizePathSlashes((0, import_path.relative)(commonDir, path3))}`;
function capitalize(name2) {
  return name2[0].toUpperCase() + name2.slice(1);
}
function getStrictRequiresFilter({ strictRequires }) {
  switch (strictRequires) {
    case true:
      return { strictRequiresFilter: () => true, detectCyclesAndConditional: false };
    case void 0:
    case "auto":
    case "debug":
    case null:
      return { strictRequiresFilter: () => false, detectCyclesAndConditional: true };
    case false:
      return { strictRequiresFilter: () => false, detectCyclesAndConditional: false };
    default:
      if (typeof strictRequires === "string" || Array.isArray(strictRequires)) {
        return {
          strictRequiresFilter: createFilter$1(strictRequires),
          detectCyclesAndConditional: false
        };
      }
      throw new Error('Unexpected value for "strictRequires" option.');
  }
}
function getPackageEntryPoint(dirPath) {
  let entryPoint = "index.js";
  try {
    if ((0, import_fs.existsSync)((0, import_path.join)(dirPath, "package.json"))) {
      entryPoint = JSON.parse((0, import_fs.readFileSync)((0, import_path.join)(dirPath, "package.json"), { encoding: "utf8" })).main || entryPoint;
    }
  } catch (ignored) {
  }
  return entryPoint;
}
function isDirectory$1(path3) {
  try {
    if ((0, import_fs.statSync)(path3).isDirectory()) return true;
  } catch (ignored) {
  }
  return false;
}
function getDynamicRequireModules(patterns, dynamicRequireRoot) {
  const dynamicRequireModules = /* @__PURE__ */ new Map();
  const dirNames = /* @__PURE__ */ new Set();
  for (const pattern2 of !patterns || Array.isArray(patterns) ? patterns || [] : [patterns]) {
    const isNegated = pattern2.startsWith("!");
    const modifyMap = (targetPath, resolvedPath) => isNegated ? dynamicRequireModules.delete(targetPath) : dynamicRequireModules.set(targetPath, resolvedPath);
    for (const path3 of glob$1.sync(isNegated ? pattern2.substr(1) : pattern2).sort((a, b) => a.localeCompare(b, "en"))) {
      const resolvedPath = (0, import_path.resolve)(path3);
      const requirePath = normalizePathSlashes(resolvedPath);
      if (isDirectory$1(resolvedPath)) {
        dirNames.add(resolvedPath);
        const modulePath = (0, import_path.resolve)((0, import_path.join)(resolvedPath, getPackageEntryPoint(path3)));
        modifyMap(requirePath, modulePath);
        modifyMap(normalizePathSlashes(modulePath), modulePath);
      } else {
        dirNames.add((0, import_path.dirname)(resolvedPath));
        modifyMap(requirePath, resolvedPath);
      }
    }
  }
  return {
    commonDir: dirNames.size ? getCommonDir([...dirNames, dynamicRequireRoot]) : null,
    dynamicRequireModules
  };
}
var FAILED_REQUIRE_ERROR = `throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');`;
var COMMONJS_REQUIRE_EXPORT = "commonjsRequire";
var CREATE_COMMONJS_REQUIRE_EXPORT = "createCommonjsRequire";
function getDynamicModuleRegistry(isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, ignoreDynamicRequires) {
  if (!isDynamicRequireModulesEnabled) {
    return `export function ${COMMONJS_REQUIRE_EXPORT}(path) {
	${FAILED_REQUIRE_ERROR}
}`;
  }
  const dynamicModuleImports = [...dynamicRequireModules.values()].map(
    (id, index) => `import ${id.endsWith(".json") ? `json${index}` : `{ __require as require${index} }`} from ${JSON.stringify(id)};`
  ).join("\n");
  const dynamicModuleProps = [...dynamicRequireModules.keys()].map(
    (id, index) => `		${JSON.stringify(getVirtualPathForDynamicRequirePath(id, commonDir))}: ${id.endsWith(".json") ? `function () { return json${index}; }` : `require${index}`}`
  ).join(",\n");
  return `${dynamicModuleImports}

var dynamicModules;

function getDynamicModules() {
	return dynamicModules || (dynamicModules = {
${dynamicModuleProps}
	});
}

export function ${CREATE_COMMONJS_REQUIRE_EXPORT}(originalModuleDir) {
	function handleRequire(path) {
		var resolvedPath = commonjsResolve(path, originalModuleDir);
		if (resolvedPath !== null) {
			return getDynamicModules()[resolvedPath]();
		}
		${ignoreDynamicRequires ? "return require(path);" : FAILED_REQUIRE_ERROR}
	}
	handleRequire.resolve = function (path) {
		var resolvedPath = commonjsResolve(path, originalModuleDir);
		if (resolvedPath !== null) {
			return resolvedPath;
		}
		return require.resolve(path);
	}
	return handleRequire;
}

function commonjsResolve (path, originalModuleDir) {
	var shouldTryNodeModules = isPossibleNodeModulesPath(path);
	path = normalize(path);
	var relPath;
	if (path[0] === '/') {
		originalModuleDir = '';
	}
	var modules = getDynamicModules();
	var checkedExtensions = ['', '.js', '.json'];
	while (true) {
		if (!shouldTryNodeModules) {
			relPath = normalize(originalModuleDir + '/' + path);
		} else {
			relPath = normalize(originalModuleDir + '/node_modules/' + path);
		}

		if (relPath.endsWith('/..')) {
			break; // Travelled too far up, avoid infinite loop
		}

		for (var extensionIndex = 0; extensionIndex < checkedExtensions.length; extensionIndex++) {
			var resolvedPath = relPath + checkedExtensions[extensionIndex];
			if (modules[resolvedPath]) {
				return resolvedPath;
			}
		}
		if (!shouldTryNodeModules) break;
		var nextDir = normalize(originalModuleDir + '/..');
		if (nextDir === originalModuleDir) break;
		originalModuleDir = nextDir;
	}
	return null;
}

function isPossibleNodeModulesPath (modulePath) {
	var c0 = modulePath[0];
	if (c0 === '/' || c0 === '\\\\') return false;
	var c1 = modulePath[1], c2 = modulePath[2];
	if ((c0 === '.' && (!c1 || c1 === '/' || c1 === '\\\\')) ||
		(c0 === '.' && c1 === '.' && (!c2 || c2 === '/' || c2 === '\\\\'))) return false;
	if (c1 === ':' && (c2 === '/' || c2 === '\\\\')) return false;
	return true;
}

function normalize (path) {
	path = path.replace(/\\\\/g, '/');
	var parts = path.split('/');
	var slashed = parts[0] === '';
	for (var i = 1; i < parts.length; i++) {
		if (parts[i] === '.' || parts[i] === '') {
			parts.splice(i--, 1);
		}
	}
	for (var i = 1; i < parts.length; i++) {
		if (parts[i] !== '..') continue;
		if (i > 0 && parts[i - 1] !== '..' && parts[i - 1] !== '.') {
			parts.splice(--i, 2);
			i--;
		}
	}
	path = parts.join('/');
	if (slashed && path[0] !== '/') path = '/' + path;
	else if (path.length === 0) path = '.';
	return path;
}`;
}
var isWrappedId = (id, suffix) => id.endsWith(suffix);
var wrapId = (id, suffix) => `\0${id}${suffix}`;
var unwrapId = (wrappedId, suffix) => wrappedId.slice(1, -suffix.length);
var PROXY_SUFFIX = "?commonjs-proxy";
var WRAPPED_SUFFIX = "?commonjs-wrapped";
var EXTERNAL_SUFFIX = "?commonjs-external";
var EXPORTS_SUFFIX = "?commonjs-exports";
var MODULE_SUFFIX = "?commonjs-module";
var ENTRY_SUFFIX = "?commonjs-entry";
var ES_IMPORT_SUFFIX = "?commonjs-es-import";
var DYNAMIC_MODULES_ID = "\0commonjs-dynamic-modules";
var HELPERS_ID = "\0commonjsHelpers.js";
var IS_WRAPPED_COMMONJS = "withRequireFunction";
var HELPERS = `
export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

export function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

export function getDefaultExportFromNamespaceIfPresent (n) {
	return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
}

export function getDefaultExportFromNamespaceIfNotNamed (n) {
	return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
}

export function getAugmentedNamespace(n) {
  if (n.__esModule) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			if (this instanceof a) {
        return Reflect.construct(f, arguments, this.constructor);
			}
			return f.apply(this, arguments);
		};
		a.prototype = f.prototype;
  } else a = {};
  Object.defineProperty(a, '__esModule', {value: true});
	Object.keys(n).forEach(function (k) {
		var d = Object.getOwnPropertyDescriptor(n, k);
		Object.defineProperty(a, k, d.get ? d : {
			enumerable: true,
			get: function () {
				return n[k];
			}
		});
	});
	return a;
}
`;
function getHelpersModule() {
  return HELPERS;
}
function getUnknownRequireProxy(id, requireReturnsDefault) {
  if (requireReturnsDefault === true || id.endsWith(".json")) {
    return `export { default } from ${JSON.stringify(id)};`;
  }
  const name2 = getName(id);
  const exported = requireReturnsDefault === "auto" ? `import { getDefaultExportFromNamespaceIfNotNamed } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfNotNamed(${name2});` : requireReturnsDefault === "preferred" ? `import { getDefaultExportFromNamespaceIfPresent } from "${HELPERS_ID}"; export default /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(${name2});` : !requireReturnsDefault ? `import { getAugmentedNamespace } from "${HELPERS_ID}"; export default /*@__PURE__*/getAugmentedNamespace(${name2});` : `export default ${name2};`;
  return `import * as ${name2} from ${JSON.stringify(id)}; ${exported}`;
}
async function getStaticRequireProxy(id, requireReturnsDefault, loadModule) {
  const name2 = getName(id);
  const {
    meta: { commonjs: commonjsMeta }
  } = await loadModule({ id });
  if (!commonjsMeta) {
    return getUnknownRequireProxy(id, requireReturnsDefault);
  }
  if (commonjsMeta.isCommonJS) {
    return `export { __moduleExports as default } from ${JSON.stringify(id)};`;
  }
  if (!requireReturnsDefault) {
    return `import { getAugmentedNamespace } from "${HELPERS_ID}"; import * as ${name2} from ${JSON.stringify(
      id
    )}; export default /*@__PURE__*/getAugmentedNamespace(${name2});`;
  }
  if (requireReturnsDefault !== true && (requireReturnsDefault === "namespace" || !commonjsMeta.hasDefaultExport || requireReturnsDefault === "auto" && commonjsMeta.hasNamedExports)) {
    return `import * as ${name2} from ${JSON.stringify(id)}; export default ${name2};`;
  }
  return `export { default } from ${JSON.stringify(id)};`;
}
function getEntryProxy(id, defaultIsModuleExports, getModuleInfo, shebang) {
  const {
    meta: { commonjs: commonjsMeta },
    hasDefaultExport
  } = getModuleInfo(id);
  if (!commonjsMeta || commonjsMeta.isCommonJS !== IS_WRAPPED_COMMONJS) {
    const stringifiedId = JSON.stringify(id);
    let code = `export * from ${stringifiedId};`;
    if (hasDefaultExport) {
      code += `export { default } from ${stringifiedId};`;
    }
    return shebang + code;
  }
  const result = getEsImportProxy(id, defaultIsModuleExports);
  return {
    ...result,
    code: shebang + result.code
  };
}
function getEsImportProxy(id, defaultIsModuleExports) {
  const name2 = getName(id);
  const exportsName = `${name2}Exports`;
  const requireModule = `require${capitalize(name2)}`;
  let code = `import { getDefaultExportFromCjs } from "${HELPERS_ID}";
import { __require as ${requireModule} } from ${JSON.stringify(id)};
var ${exportsName} = ${requireModule}();
export { ${exportsName} as __moduleExports };`;
  if (defaultIsModuleExports === true) {
    code += `
export { ${exportsName} as default };`;
  } else {
    code += `export default /*@__PURE__*/getDefaultExportFromCjs(${exportsName});`;
  }
  return {
    code,
    syntheticNamedExports: "__moduleExports"
  };
}
function getCandidatesForExtension(resolved, extension2) {
  return [resolved + extension2, `${resolved}${import_path.sep}index${extension2}`];
}
function getCandidates(resolved, extensions2) {
  return extensions2.reduce(
    (paths, extension2) => paths.concat(getCandidatesForExtension(resolved, extension2)),
    [resolved]
  );
}
function resolveExtensions(importee, importer, extensions2) {
  if (importee[0] !== "." || !importer) return void 0;
  const resolved = (0, import_path.resolve)((0, import_path.dirname)(importer), importee);
  const candidates = getCandidates(resolved, extensions2);
  for (let i = 0; i < candidates.length; i += 1) {
    try {
      const stats = (0, import_fs.statSync)(candidates[i]);
      if (stats.isFile()) return { id: candidates[i] };
    } catch (err2) {
    }
  }
  return void 0;
}
function getResolveId(extensions2, isPossibleCjsId) {
  const currentlyResolving = /* @__PURE__ */ new Map();
  return {
    /**
     * This is a Maps of importers to Sets of require sources being resolved at
     * the moment by resolveRequireSourcesAndUpdateMeta
     */
    currentlyResolving,
    async resolveId(importee, importer, resolveOptions) {
      const customOptions = resolveOptions.custom;
      if (customOptions && customOptions["node-resolve"] && customOptions["node-resolve"].isRequire) {
        return null;
      }
      const currentlyResolvingForParent = currentlyResolving.get(importer);
      if (currentlyResolvingForParent && currentlyResolvingForParent.has(importee)) {
        this.warn({
          code: "THIS_RESOLVE_WITHOUT_OPTIONS",
          message: 'It appears a plugin has implemented a "resolveId" hook that uses "this.resolve" without forwarding the third "options" parameter of "resolveId". This is problematic as it can lead to wrong module resolutions especially for the node-resolve plugin and in certain cases cause early exit errors for the commonjs plugin.\nIn rare cases, this warning can appear if the same file is both imported and required from the same mixed ES/CommonJS module, in which case it can be ignored.',
          url: "https://rollupjs.org/guide/en/#resolveid"
        });
        return null;
      }
      if (isWrappedId(importee, WRAPPED_SUFFIX)) {
        return unwrapId(importee, WRAPPED_SUFFIX);
      }
      if (importee.endsWith(ENTRY_SUFFIX) || isWrappedId(importee, MODULE_SUFFIX) || isWrappedId(importee, EXPORTS_SUFFIX) || isWrappedId(importee, PROXY_SUFFIX) || isWrappedId(importee, ES_IMPORT_SUFFIX) || isWrappedId(importee, EXTERNAL_SUFFIX) || importee.startsWith(HELPERS_ID) || importee === DYNAMIC_MODULES_ID) {
        return importee;
      }
      if (importer) {
        if (importer === DYNAMIC_MODULES_ID || // Proxies are only importing resolved ids, no need to resolve again
        isWrappedId(importer, PROXY_SUFFIX) || isWrappedId(importer, ES_IMPORT_SUFFIX) || importer.endsWith(ENTRY_SUFFIX)) {
          return importee;
        }
        if (isWrappedId(importer, EXTERNAL_SUFFIX)) {
          if (!await this.resolve(
            importee,
            importer,
            Object.assign({ skipSelf: true }, resolveOptions)
          )) {
            return null;
          }
          return { id: importee, external: true };
        }
      }
      if (importee.startsWith("\0")) {
        return null;
      }
      const resolved = await this.resolve(
        importee,
        importer,
        Object.assign({ skipSelf: true }, resolveOptions)
      ) || resolveExtensions(importee, importer, extensions2);
      if (!resolved || resolved.external || resolved.id.endsWith(ENTRY_SUFFIX) || isWrappedId(resolved.id, ES_IMPORT_SUFFIX) || !isPossibleCjsId(resolved.id)) {
        return resolved;
      }
      const moduleInfo = await this.load(resolved);
      const {
        meta: { commonjs: commonjsMeta }
      } = moduleInfo;
      if (commonjsMeta) {
        const { isCommonJS } = commonjsMeta;
        if (isCommonJS) {
          if (resolveOptions.isEntry) {
            moduleInfo.moduleSideEffects = true;
            return resolved.id + ENTRY_SUFFIX;
          }
          if (isCommonJS === IS_WRAPPED_COMMONJS) {
            return { id: wrapId(resolved.id, ES_IMPORT_SUFFIX), meta: { commonjs: { resolved } } };
          }
        }
      }
      return resolved;
    }
  };
}
function getRequireResolver(extensions2, detectCyclesAndConditional, currentlyResolving) {
  const knownCjsModuleTypes = /* @__PURE__ */ Object.create(null);
  const requiredIds = /* @__PURE__ */ Object.create(null);
  const unconditionallyRequiredIds = /* @__PURE__ */ Object.create(null);
  const dependencies = /* @__PURE__ */ Object.create(null);
  const getDependencies = (id) => dependencies[id] || (dependencies[id] = /* @__PURE__ */ new Set());
  const isCyclic = (id) => {
    const dependenciesToCheck = new Set(getDependencies(id));
    for (const dependency of dependenciesToCheck) {
      if (dependency === id) {
        return true;
      }
      for (const childDependency of getDependencies(dependency)) {
        dependenciesToCheck.add(childDependency);
      }
    }
    return false;
  };
  const fullyAnalyzedModules = /* @__PURE__ */ Object.create(null);
  const getTypeForFullyAnalyzedModule = (id) => {
    const knownType = knownCjsModuleTypes[id];
    if (knownType !== true || !detectCyclesAndConditional || fullyAnalyzedModules[id]) {
      return knownType;
    }
    if (isCyclic(id)) {
      return knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
    }
    return knownType;
  };
  const setInitialParentType = (id, initialCommonJSType) => {
    if (fullyAnalyzedModules[id]) {
      return;
    }
    knownCjsModuleTypes[id] = initialCommonJSType;
    if (detectCyclesAndConditional && knownCjsModuleTypes[id] === true && requiredIds[id] && !unconditionallyRequiredIds[id]) {
      knownCjsModuleTypes[id] = IS_WRAPPED_COMMONJS;
    }
  };
  const analyzeRequiredModule = async (parentId, resolved, isConditional, loadModule) => {
    const childId = resolved.id;
    requiredIds[childId] = true;
    if (!(isConditional || knownCjsModuleTypes[parentId] === IS_WRAPPED_COMMONJS)) {
      unconditionallyRequiredIds[childId] = true;
    }
    getDependencies(parentId).add(childId);
    if (!isCyclic(childId)) {
      await loadModule(resolved);
    }
  };
  const getTypeForImportedModule = async (resolved, loadModule) => {
    if (resolved.id in knownCjsModuleTypes) {
      return knownCjsModuleTypes[resolved.id];
    }
    const {
      meta: { commonjs: commonjs2 }
    } = await loadModule(resolved);
    return commonjs2 && commonjs2.isCommonJS || false;
  };
  return {
    getWrappedIds: () => Object.keys(knownCjsModuleTypes).filter(
      (id) => knownCjsModuleTypes[id] === IS_WRAPPED_COMMONJS
    ),
    isRequiredId: (id) => requiredIds[id],
    async shouldTransformCachedModule({
      id: parentId,
      resolvedSources,
      meta: { commonjs: parentMeta }
    }) {
      if (!(parentMeta && parentMeta.isCommonJS)) knownCjsModuleTypes[parentId] = false;
      if (isWrappedId(parentId, ES_IMPORT_SUFFIX)) return false;
      const parentRequires = parentMeta && parentMeta.requires;
      if (parentRequires) {
        setInitialParentType(parentId, parentMeta.initialCommonJSType);
        await Promise.all(
          parentRequires.map(
            ({ resolved, isConditional }) => analyzeRequiredModule(parentId, resolved, isConditional, this.load)
          )
        );
        if (getTypeForFullyAnalyzedModule(parentId) !== parentMeta.isCommonJS) {
          return true;
        }
        for (const {
          resolved: { id }
        } of parentRequires) {
          if (getTypeForFullyAnalyzedModule(id) !== parentMeta.isRequiredCommonJS[id]) {
            return true;
          }
        }
        fullyAnalyzedModules[parentId] = true;
        for (const {
          resolved: { id }
        } of parentRequires) {
          fullyAnalyzedModules[id] = true;
        }
      }
      const parentRequireSet = new Set((parentRequires || []).map(({ resolved: { id } }) => id));
      return (await Promise.all(
        Object.keys(resolvedSources).map((source) => resolvedSources[source]).filter(({ id, external }) => !(external || parentRequireSet.has(id))).map(async (resolved) => {
          if (isWrappedId(resolved.id, ES_IMPORT_SUFFIX)) {
            return await getTypeForImportedModule(
              (await this.load({ id: resolved.id })).meta.commonjs.resolved,
              this.load
            ) !== IS_WRAPPED_COMMONJS;
          }
          return await getTypeForImportedModule(resolved, this.load) === IS_WRAPPED_COMMONJS;
        })
      )).some((shouldTransform) => shouldTransform);
    },
    /* eslint-disable no-param-reassign */
    resolveRequireSourcesAndUpdateMeta: (rollupContext) => async (parentId, isParentCommonJS, parentMeta, sources) => {
      parentMeta.initialCommonJSType = isParentCommonJS;
      parentMeta.requires = [];
      parentMeta.isRequiredCommonJS = /* @__PURE__ */ Object.create(null);
      setInitialParentType(parentId, isParentCommonJS);
      const currentlyResolvingForParent = currentlyResolving.get(parentId) || /* @__PURE__ */ new Set();
      currentlyResolving.set(parentId, currentlyResolvingForParent);
      const requireTargets = await Promise.all(
        sources.map(async ({ source, isConditional }) => {
          if (source.startsWith("\0")) {
            return { id: source, allowProxy: false };
          }
          currentlyResolvingForParent.add(source);
          const resolved = await rollupContext.resolve(source, parentId, {
            skipSelf: false,
            custom: { "node-resolve": { isRequire: true } }
          }) || resolveExtensions(source, parentId, extensions2);
          currentlyResolvingForParent.delete(source);
          if (!resolved) {
            return { id: wrapId(source, EXTERNAL_SUFFIX), allowProxy: false };
          }
          const childId = resolved.id;
          if (resolved.external) {
            return { id: wrapId(childId, EXTERNAL_SUFFIX), allowProxy: false };
          }
          parentMeta.requires.push({ resolved, isConditional });
          await analyzeRequiredModule(parentId, resolved, isConditional, rollupContext.load);
          return { id: childId, allowProxy: true };
        })
      );
      parentMeta.isCommonJS = getTypeForFullyAnalyzedModule(parentId);
      fullyAnalyzedModules[parentId] = true;
      return requireTargets.map(({ id: dependencyId, allowProxy }, index) => {
        const isCommonJS = parentMeta.isRequiredCommonJS[dependencyId] = getTypeForFullyAnalyzedModule(dependencyId);
        fullyAnalyzedModules[dependencyId] = true;
        return {
          source: sources[index].source,
          id: allowProxy ? isCommonJS === IS_WRAPPED_COMMONJS ? wrapId(dependencyId, WRAPPED_SUFFIX) : wrapId(dependencyId, PROXY_SUFFIX) : dependencyId,
          isCommonJS
        };
      });
    },
    isCurrentlyResolving(source, parentId) {
      const currentlyResolvingForParent = currentlyResolving.get(parentId);
      return currentlyResolvingForParent && currentlyResolvingForParent.has(source);
    }
  };
}
function validateVersion(actualVersion, peerDependencyVersion, name2) {
  const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
  let minMajor = Infinity;
  let minMinor = Infinity;
  let minPatch = Infinity;
  let foundVersion;
  while (foundVersion = versionRegexp.exec(peerDependencyVersion)) {
    const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split(".").map(Number);
    if (foundMajor < minMajor) {
      minMajor = foundMajor;
      minMinor = foundMinor;
      minPatch = foundPatch;
    }
  }
  if (!actualVersion) {
    throw new Error(
      `Insufficient ${name2} version: "@rollup/plugin-commonjs" requires at least ${name2}@${minMajor}.${minMinor}.${minPatch}.`
    );
  }
  const [major, minor, patch] = actualVersion.split(".").map(Number);
  if (major < minMajor || major === minMajor && (minor < minMinor || minor === minMinor && patch < minPatch)) {
    throw new Error(
      `Insufficient ${name2} version: "@rollup/plugin-commonjs" requires at least ${name2}@${minMajor}.${minMinor}.${minPatch} but found ${name2}@${actualVersion}.`
    );
  }
}
var operators = {
  "==": (x) => equals(x.left, x.right, false),
  "!=": (x) => not(operators["=="](x)),
  "===": (x) => equals(x.left, x.right, true),
  "!==": (x) => not(operators["==="](x)),
  "!": (x) => isFalsy(x.argument),
  "&&": (x) => isTruthy(x.left) && isTruthy(x.right),
  "||": (x) => isTruthy(x.left) || isTruthy(x.right)
};
function not(value2) {
  return value2 === null ? value2 : !value2;
}
function equals(a, b, strict) {
  if (a.type !== b.type) return null;
  if (a.type === "Literal") return strict ? a.value === b.value : a.value == b.value;
  return null;
}
function isTruthy(node2) {
  if (!node2) return false;
  if (node2.type === "Literal") return !!node2.value;
  if (node2.type === "ParenthesizedExpression") return isTruthy(node2.expression);
  if (node2.operator in operators) return operators[node2.operator](node2);
  return null;
}
function isFalsy(node2) {
  return not(isTruthy(node2));
}
function getKeypath(node2) {
  const parts = [];
  while (node2.type === "MemberExpression") {
    if (node2.computed) return null;
    parts.unshift(node2.property.name);
    node2 = node2.object;
  }
  if (node2.type !== "Identifier") return null;
  const { name: name2 } = node2;
  parts.unshift(name2);
  return { name: name2, keypath: parts.join(".") };
}
var KEY_COMPILED_ESM = "__esModule";
function getDefineCompiledEsmType(node2) {
  const definedPropertyWithExports = getDefinePropertyCallName(node2, "exports");
  const definedProperty = definedPropertyWithExports || getDefinePropertyCallName(node2, "module.exports");
  if (definedProperty && definedProperty.key === KEY_COMPILED_ESM) {
    return isTruthy(definedProperty.value) ? definedPropertyWithExports ? "exports" : "module" : false;
  }
  return false;
}
function getDefinePropertyCallName(node2, targetName) {
  const {
    callee: { object, property }
  } = node2;
  if (!object || object.type !== "Identifier" || object.name !== "Object") return;
  if (!property || property.type !== "Identifier" || property.name !== "defineProperty") return;
  if (node2.arguments.length !== 3) return;
  const targetNames = targetName.split(".");
  const [target, key, value2] = node2.arguments;
  if (targetNames.length === 1) {
    if (target.type !== "Identifier" || target.name !== targetNames[0]) {
      return;
    }
  }
  if (targetNames.length === 2) {
    if (target.type !== "MemberExpression" || target.object.name !== targetNames[0] || target.property.name !== targetNames[1]) {
      return;
    }
  }
  if (value2.type !== "ObjectExpression" || !value2.properties) return;
  const valueProperty = value2.properties.find((p) => p.key && p.key.name === "value");
  if (!valueProperty || !valueProperty.value) return;
  return { key: key.value, value: valueProperty.value };
}
function isShorthandProperty(parent) {
  return parent && parent.type === "Property" && parent.shorthand;
}
function wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges) {
  const args = [];
  const passedArgs = [];
  if (uses.module) {
    args.push("module");
    passedArgs.push(moduleName);
  }
  if (uses.exports) {
    args.push("exports");
    passedArgs.push(uses.module ? `${moduleName}.exports` : exportsName);
  }
  magicString.trim().indent("	", { exclude: indentExclusionRanges }).prepend(`(function (${args.join(", ")}) {
`).append(` 
} (${passedArgs.join(", ")}));`);
}
function rewriteExportsAndGetExportsBlock(magicString, moduleName, exportsName, exportedExportsName, wrapped, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsAssignmentsByName, topLevelAssignments, defineCompiledEsmExpressions, deconflictedExportNames, code, HELPERS_NAME, exportMode, defaultIsModuleExports, usesRequireWrapper, requireName) {
  const exports2 = [];
  const exportDeclarations = [];
  if (usesRequireWrapper) {
    getExportsWhenUsingRequireWrapper(
      magicString,
      wrapped,
      exportMode,
      exports2,
      moduleExportsAssignments,
      exportsAssignmentsByName,
      moduleName,
      exportsName,
      requireName,
      defineCompiledEsmExpressions
    );
  } else if (exportMode === "replace") {
    getExportsForReplacedModuleExports(
      magicString,
      exports2,
      exportDeclarations,
      moduleExportsAssignments,
      firstTopLevelModuleExportsAssignment,
      exportsName,
      defaultIsModuleExports,
      HELPERS_NAME
    );
  } else {
    if (exportMode === "module") {
      exportDeclarations.push(`var ${exportedExportsName} = ${moduleName}.exports`);
      exports2.push(`${exportedExportsName} as __moduleExports`);
    } else {
      exports2.push(`${exportsName} as __moduleExports`);
    }
    if (wrapped) {
      exportDeclarations.push(
        getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
      );
    } else {
      getExports(
        magicString,
        exports2,
        exportDeclarations,
        moduleExportsAssignments,
        exportsAssignmentsByName,
        deconflictedExportNames,
        topLevelAssignments,
        moduleName,
        exportsName,
        exportedExportsName,
        defineCompiledEsmExpressions,
        HELPERS_NAME,
        defaultIsModuleExports,
        exportMode
      );
    }
  }
  if (exports2.length) {
    exportDeclarations.push(`export { ${exports2.join(", ")} }`);
  }
  return `

${exportDeclarations.join(";\n")};`;
}
function getExportsWhenUsingRequireWrapper(magicString, wrapped, exportMode, exports2, moduleExportsAssignments, exportsAssignmentsByName, moduleName, exportsName, requireName, defineCompiledEsmExpressions) {
  exports2.push(`${requireName} as __require`);
  if (wrapped) return;
  if (exportMode === "replace") {
    rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName);
  } else {
    rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, `${moduleName}.exports`);
    for (const [exportName, { nodes }] of exportsAssignmentsByName) {
      for (const { node: node2, type } of nodes) {
        magicString.overwrite(
          node2.start,
          node2.left.end,
          `${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`
        );
      }
    }
    replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
      defineCompiledEsmExpressions,
      magicString,
      exportMode,
      moduleName,
      exportsName
    );
  }
}
function getExportsForReplacedModuleExports(magicString, exports2, exportDeclarations, moduleExportsAssignments, firstTopLevelModuleExportsAssignment, exportsName, defaultIsModuleExports, HELPERS_NAME) {
  for (const { left } of moduleExportsAssignments) {
    magicString.overwrite(left.start, left.end, exportsName);
  }
  magicString.prependRight(firstTopLevelModuleExportsAssignment.left.start, "var ");
  exports2.push(`${exportsName} as __moduleExports`);
  exportDeclarations.push(
    getDefaultExportDeclaration(exportsName, defaultIsModuleExports, HELPERS_NAME)
  );
}
function getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME) {
  return `export default ${defaultIsModuleExports === true ? exportedExportsName : defaultIsModuleExports === false ? `${exportedExportsName}.default` : `/*@__PURE__*/${HELPERS_NAME}.getDefaultExportFromCjs(${exportedExportsName})`}`;
}
function getExports(magicString, exports2, exportDeclarations, moduleExportsAssignments, exportsAssignmentsByName, deconflictedExportNames, topLevelAssignments, moduleName, exportsName, exportedExportsName, defineCompiledEsmExpressions, HELPERS_NAME, defaultIsModuleExports, exportMode) {
  let deconflictedDefaultExportName;
  for (const { left } of moduleExportsAssignments) {
    magicString.overwrite(left.start, left.end, `${moduleName}.exports`);
  }
  for (const [exportName, { nodes }] of exportsAssignmentsByName) {
    const deconflicted = deconflictedExportNames[exportName];
    let needsDeclaration = true;
    for (const { node: node2, type } of nodes) {
      let replacement = `${deconflicted} = ${exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName}.${exportName}`;
      if (needsDeclaration && topLevelAssignments.has(node2)) {
        replacement = `var ${replacement}`;
        needsDeclaration = false;
      }
      magicString.overwrite(node2.start, node2.left.end, replacement);
    }
    if (needsDeclaration) {
      magicString.prepend(`var ${deconflicted};
`);
    }
    if (exportName === "default") {
      deconflictedDefaultExportName = deconflicted;
    } else {
      exports2.push(exportName === deconflicted ? exportName : `${deconflicted} as ${exportName}`);
    }
  }
  const isRestorableCompiledEsm = replaceDefineCompiledEsmExpressionsAndGetIfRestorable(
    defineCompiledEsmExpressions,
    magicString,
    exportMode,
    moduleName,
    exportsName
  );
  if (defaultIsModuleExports === false || defaultIsModuleExports === "auto" && isRestorableCompiledEsm && moduleExportsAssignments.length === 0) {
    exports2.push(`${deconflictedDefaultExportName || exportedExportsName} as default`);
  } else if (defaultIsModuleExports === true || !isRestorableCompiledEsm && moduleExportsAssignments.length === 0) {
    exports2.push(`${exportedExportsName} as default`);
  } else {
    exportDeclarations.push(
      getDefaultExportDeclaration(exportedExportsName, defaultIsModuleExports, HELPERS_NAME)
    );
  }
}
function rewriteModuleExportsAssignments(magicString, moduleExportsAssignments, exportsName) {
  for (const { left } of moduleExportsAssignments) {
    magicString.overwrite(left.start, left.end, exportsName);
  }
}
function replaceDefineCompiledEsmExpressionsAndGetIfRestorable(defineCompiledEsmExpressions, magicString, exportMode, moduleName, exportsName) {
  let isRestorableCompiledEsm = false;
  for (const { node: node2, type } of defineCompiledEsmExpressions) {
    isRestorableCompiledEsm = true;
    const moduleExportsExpression = node2.type === "CallExpression" ? node2.arguments[0] : node2.left.object;
    magicString.overwrite(
      moduleExportsExpression.start,
      moduleExportsExpression.end,
      exportMode === "module" && type === "module" ? `${moduleName}.exports` : exportsName
    );
  }
  return isRestorableCompiledEsm;
}
function isRequireExpression(node2, scope) {
  if (!node2) return false;
  if (node2.type !== "CallExpression") return false;
  if (node2.arguments.length === 0) return false;
  return isRequire(node2.callee, scope);
}
function isRequire(node2, scope) {
  return node2.type === "Identifier" && node2.name === "require" && !scope.contains("require") || node2.type === "MemberExpression" && isModuleRequire(node2, scope);
}
function isModuleRequire({ object, property }, scope) {
  return object.type === "Identifier" && object.name === "module" && property.type === "Identifier" && property.name === "require" && !scope.contains("module");
}
function hasDynamicArguments(node2) {
  return node2.arguments.length > 1 || node2.arguments[0].type !== "Literal" && (node2.arguments[0].type !== "TemplateLiteral" || node2.arguments[0].expressions.length > 0);
}
var reservedMethod = { resolve: true, cache: true, main: true };
function isNodeRequirePropertyAccess(parent) {
  return parent && parent.property && reservedMethod[parent.property.name];
}
function getRequireStringArg(node2) {
  return node2.arguments[0].type === "Literal" ? node2.arguments[0].value : node2.arguments[0].quasis[0].value.cooked;
}
function getRequireHandlers() {
  const requireExpressions = [];
  function addRequireExpression(sourceId, node2, scope, usesReturnValue, isInsideTryBlock, isInsideConditional, toBeRemoved) {
    requireExpressions.push({
      sourceId,
      node: node2,
      scope,
      usesReturnValue,
      isInsideTryBlock,
      isInsideConditional,
      toBeRemoved
    });
  }
  async function rewriteRequireExpressionsAndGetImportBlock(magicString, topLevelDeclarations, reassignedNames, helpersName, dynamicRequireName, moduleName, exportsName, id, exportMode, resolveRequireSourcesAndUpdateMeta, needsRequireWrapper, isEsModule, isDynamicRequireModulesEnabled, getIgnoreTryCatchRequireStatementMode, commonjsMeta) {
    const imports = [];
    imports.push(`import * as ${helpersName} from "${HELPERS_ID}"`);
    if (dynamicRequireName) {
      imports.push(
        `import { ${isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT} as ${dynamicRequireName} } from "${DYNAMIC_MODULES_ID}"`
      );
    }
    if (exportMode === "module") {
      imports.push(
        `import { __module as ${moduleName} } from ${JSON.stringify(wrapId(id, MODULE_SUFFIX))}`,
        `var ${exportsName} = ${moduleName}.exports`
      );
    } else if (exportMode === "exports") {
      imports.push(
        `import { __exports as ${exportsName} } from ${JSON.stringify(wrapId(id, EXPORTS_SUFFIX))}`
      );
    }
    const requiresBySource = collectSources(requireExpressions);
    const requireTargets = await resolveRequireSourcesAndUpdateMeta(
      id,
      needsRequireWrapper ? IS_WRAPPED_COMMONJS : !isEsModule,
      commonjsMeta,
      Object.keys(requiresBySource).map((source) => {
        return {
          source,
          isConditional: requiresBySource[source].every((require3) => require3.isInsideConditional)
        };
      })
    );
    processRequireExpressions(
      imports,
      requireTargets,
      requiresBySource,
      getIgnoreTryCatchRequireStatementMode,
      magicString
    );
    return imports.length ? `${imports.join(";\n")};

` : "";
  }
  return {
    addRequireExpression,
    rewriteRequireExpressionsAndGetImportBlock
  };
}
function collectSources(requireExpressions) {
  const requiresBySource = /* @__PURE__ */ Object.create(null);
  for (const requireExpression of requireExpressions) {
    const { sourceId } = requireExpression;
    if (!requiresBySource[sourceId]) {
      requiresBySource[sourceId] = [];
    }
    const requires = requiresBySource[sourceId];
    requires.push(requireExpression);
  }
  return requiresBySource;
}
function processRequireExpressions(imports, requireTargets, requiresBySource, getIgnoreTryCatchRequireStatementMode, magicString) {
  const generateRequireName = getGenerateRequireName();
  for (const { source, id: resolvedId, isCommonJS } of requireTargets) {
    const requires = requiresBySource[source];
    const name2 = generateRequireName(requires);
    let usesRequired = false;
    let needsImport = false;
    for (const { node: node2, usesReturnValue, toBeRemoved, isInsideTryBlock } of requires) {
      const { canConvertRequire, shouldRemoveRequire } = isInsideTryBlock && isWrappedId(resolvedId, EXTERNAL_SUFFIX) ? getIgnoreTryCatchRequireStatementMode(source) : { canConvertRequire: true, shouldRemoveRequire: false };
      if (shouldRemoveRequire) {
        if (usesReturnValue) {
          magicString.overwrite(node2.start, node2.end, "undefined");
        } else {
          magicString.remove(toBeRemoved.start, toBeRemoved.end);
        }
      } else if (canConvertRequire) {
        needsImport = true;
        if (isCommonJS === IS_WRAPPED_COMMONJS) {
          magicString.overwrite(node2.start, node2.end, `${name2}()`);
        } else if (usesReturnValue) {
          usesRequired = true;
          magicString.overwrite(node2.start, node2.end, name2);
        } else {
          magicString.remove(toBeRemoved.start, toBeRemoved.end);
        }
      }
    }
    if (needsImport) {
      if (isCommonJS === IS_WRAPPED_COMMONJS) {
        imports.push(`import { __require as ${name2} } from ${JSON.stringify(resolvedId)}`);
      } else {
        imports.push(`import ${usesRequired ? `${name2} from ` : ""}${JSON.stringify(resolvedId)}`);
      }
    }
  }
}
function getGenerateRequireName() {
  let uid = 0;
  return (requires) => {
    let name2;
    const hasNameConflict = ({ scope }) => scope.contains(name2);
    do {
      name2 = `require$$${uid}`;
      uid += 1;
    } while (requires.some(hasNameConflict));
    return name2;
  };
}
var exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
var functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
async function transformCommonjs(parse4, code, id, isEsModule, ignoreGlobal, ignoreRequire, ignoreDynamicRequires, getIgnoreTryCatchRequireStatementMode, sourceMap, isDynamicRequireModulesEnabled, dynamicRequireModules, commonDir, astCache, defaultIsModuleExports, needsRequireWrapper, resolveRequireSourcesAndUpdateMeta, isRequired, checkDynamicRequire, commonjsMeta) {
  const ast = astCache || tryParse(parse4, code, id);
  const magicString = new MagicString(code);
  const uses = {
    module: false,
    exports: false,
    global: false,
    require: false
  };
  const virtualDynamicRequirePath = isDynamicRequireModulesEnabled && getVirtualPathForDynamicRequirePath((0, import_path.dirname)(id), commonDir);
  let scope = attachScopes(ast, "scope");
  let lexicalDepth = 0;
  let programDepth = 0;
  let classBodyDepth = 0;
  let currentTryBlockEnd = null;
  let shouldWrap = false;
  const globals = /* @__PURE__ */ new Set();
  let currentConditionalNodeEnd = null;
  const conditionalNodes = /* @__PURE__ */ new Set();
  const { addRequireExpression, rewriteRequireExpressionsAndGetImportBlock } = getRequireHandlers();
  const reassignedNames = /* @__PURE__ */ new Set();
  const topLevelDeclarations = [];
  const skippedNodes = /* @__PURE__ */ new Set();
  const moduleAccessScopes = /* @__PURE__ */ new Set([scope]);
  const exportsAccessScopes = /* @__PURE__ */ new Set([scope]);
  const moduleExportsAssignments = [];
  let firstTopLevelModuleExportsAssignment = null;
  const exportsAssignmentsByName = /* @__PURE__ */ new Map();
  const topLevelAssignments = /* @__PURE__ */ new Set();
  const topLevelDefineCompiledEsmExpressions = [];
  const replacedGlobal = [];
  const replacedDynamicRequires = [];
  const importedVariables = /* @__PURE__ */ new Set();
  const indentExclusionRanges = [];
  walk$3(ast, {
    enter(node2, parent) {
      if (skippedNodes.has(node2)) {
        this.skip();
        return;
      }
      if (currentTryBlockEnd !== null && node2.start > currentTryBlockEnd) {
        currentTryBlockEnd = null;
      }
      if (currentConditionalNodeEnd !== null && node2.start > currentConditionalNodeEnd) {
        currentConditionalNodeEnd = null;
      }
      if (currentConditionalNodeEnd === null && conditionalNodes.has(node2)) {
        currentConditionalNodeEnd = node2.end;
      }
      programDepth += 1;
      if (node2.scope) ({ scope } = node2);
      if (functionType.test(node2.type)) lexicalDepth += 1;
      if (sourceMap) {
        magicString.addSourcemapLocation(node2.start);
        magicString.addSourcemapLocation(node2.end);
      }
      switch (node2.type) {
        case "AssignmentExpression":
          if (node2.left.type === "MemberExpression") {
            const flattened = getKeypath(node2.left);
            if (!flattened || scope.contains(flattened.name)) return;
            const exportsPatternMatch = exportsPattern.exec(flattened.keypath);
            if (!exportsPatternMatch || flattened.keypath === "exports") return;
            const [, exportName] = exportsPatternMatch;
            uses[flattened.name] = true;
            if (flattened.keypath === "module.exports") {
              moduleExportsAssignments.push(node2);
              if (programDepth > 3) {
                moduleAccessScopes.add(scope);
              } else if (!firstTopLevelModuleExportsAssignment) {
                firstTopLevelModuleExportsAssignment = node2;
              }
            } else if (exportName === KEY_COMPILED_ESM) {
              if (programDepth > 3) {
                shouldWrap = true;
              } else {
                topLevelDefineCompiledEsmExpressions.push({ node: node2, type: flattened.name });
              }
            } else {
              const exportsAssignments = exportsAssignmentsByName.get(exportName) || {
                nodes: [],
                scopes: /* @__PURE__ */ new Set()
              };
              exportsAssignments.nodes.push({ node: node2, type: flattened.name });
              exportsAssignments.scopes.add(scope);
              exportsAccessScopes.add(scope);
              exportsAssignmentsByName.set(exportName, exportsAssignments);
              if (programDepth <= 3) {
                topLevelAssignments.add(node2);
              }
            }
            skippedNodes.add(node2.left);
          } else {
            for (const name2 of extractAssignedNames(node2.left)) {
              reassignedNames.add(name2);
            }
          }
          return;
        case "CallExpression": {
          const defineCompiledEsmType = getDefineCompiledEsmType(node2);
          if (defineCompiledEsmType) {
            if (programDepth === 3 && parent.type === "ExpressionStatement") {
              skippedNodes.add(node2.arguments[0]);
              topLevelDefineCompiledEsmExpressions.push({ node: node2, type: defineCompiledEsmType });
            } else {
              shouldWrap = true;
            }
            return;
          }
          if (isDynamicRequireModulesEnabled && node2.callee.object && isRequire(node2.callee.object, scope) && node2.callee.property.name === "resolve") {
            checkDynamicRequire(node2.start);
            uses.require = true;
            const requireNode2 = node2.callee.object;
            replacedDynamicRequires.push(requireNode2);
            skippedNodes.add(node2.callee);
            return;
          }
          if (!isRequireExpression(node2, scope)) {
            const keypath = getKeypath(node2.callee);
            if (keypath && importedVariables.has(keypath.name)) {
              currentConditionalNodeEnd = Infinity;
            }
            return;
          }
          skippedNodes.add(node2.callee);
          uses.require = true;
          if (hasDynamicArguments(node2)) {
            if (isDynamicRequireModulesEnabled) {
              checkDynamicRequire(node2.start);
            }
            if (!ignoreDynamicRequires) {
              replacedDynamicRequires.push(node2.callee);
            }
            return;
          }
          const requireStringArg = getRequireStringArg(node2);
          if (!ignoreRequire(requireStringArg)) {
            const usesReturnValue = parent.type !== "ExpressionStatement";
            const toBeRemoved = parent.type === "ExpressionStatement" && (!currentConditionalNodeEnd || // We should completely remove requires directly in a try-catch
            // so that Rollup can remove up the try-catch
            currentTryBlockEnd !== null && currentTryBlockEnd < currentConditionalNodeEnd) ? parent : node2;
            addRequireExpression(
              requireStringArg,
              node2,
              scope,
              usesReturnValue,
              currentTryBlockEnd !== null,
              currentConditionalNodeEnd !== null,
              toBeRemoved
            );
            if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") {
              for (const name2 of extractAssignedNames(parent.id)) {
                importedVariables.add(name2);
              }
            }
          }
          return;
        }
        case "ClassBody":
          classBodyDepth += 1;
          return;
        case "ConditionalExpression":
        case "IfStatement":
          if (isFalsy(node2.test)) {
            skippedNodes.add(node2.consequent);
          } else if (isTruthy(node2.test)) {
            if (node2.alternate) {
              skippedNodes.add(node2.alternate);
            }
          } else {
            conditionalNodes.add(node2.consequent);
            if (node2.alternate) {
              conditionalNodes.add(node2.alternate);
            }
          }
          return;
        case "ArrowFunctionExpression":
        case "FunctionDeclaration":
        case "FunctionExpression":
          if (currentConditionalNodeEnd === null && !(parent.type === "CallExpression" && parent.callee === node2)) {
            currentConditionalNodeEnd = node2.end;
          }
          return;
        case "Identifier": {
          const { name: name2 } = node2;
          if (!isReference(node2, parent) || scope.contains(name2) || parent.type === "PropertyDefinition" && parent.key === node2)
            return;
          switch (name2) {
            case "require":
              uses.require = true;
              if (isNodeRequirePropertyAccess(parent)) {
                return;
              }
              if (!ignoreDynamicRequires) {
                if (isShorthandProperty(parent)) {
                  skippedNodes.add(parent.value);
                  magicString.prependRight(node2.start, "require: ");
                }
                replacedDynamicRequires.push(node2);
              }
              return;
            case "module":
            case "exports":
              shouldWrap = true;
              uses[name2] = true;
              return;
            case "global":
              uses.global = true;
              if (!ignoreGlobal) {
                replacedGlobal.push(node2);
              }
              return;
            case "define":
              magicString.overwrite(node2.start, node2.end, "undefined", {
                storeName: true
              });
              return;
            default:
              globals.add(name2);
              return;
          }
        }
        case "LogicalExpression":
          if (node2.operator === "&&") {
            if (isFalsy(node2.left)) {
              skippedNodes.add(node2.right);
            } else if (!isTruthy(node2.left)) {
              conditionalNodes.add(node2.right);
            }
          } else if (node2.operator === "||") {
            if (isTruthy(node2.left)) {
              skippedNodes.add(node2.right);
            } else if (!isFalsy(node2.left)) {
              conditionalNodes.add(node2.right);
            }
          }
          return;
        case "MemberExpression":
          if (!isDynamicRequireModulesEnabled && isModuleRequire(node2, scope)) {
            uses.require = true;
            replacedDynamicRequires.push(node2);
            skippedNodes.add(node2.object);
            skippedNodes.add(node2.property);
          }
          return;
        case "ReturnStatement":
          if (lexicalDepth === 0) {
            shouldWrap = true;
          }
          return;
        case "ThisExpression":
          if (lexicalDepth === 0 && !classBodyDepth) {
            uses.global = true;
            if (!ignoreGlobal) {
              replacedGlobal.push(node2);
            }
          }
          return;
        case "TryStatement":
          if (currentTryBlockEnd === null) {
            currentTryBlockEnd = node2.block.end;
          }
          if (currentConditionalNodeEnd === null) {
            currentConditionalNodeEnd = node2.end;
          }
          return;
        case "UnaryExpression":
          if (node2.operator === "typeof") {
            const flattened = getKeypath(node2.argument);
            if (!flattened) return;
            if (scope.contains(flattened.name)) return;
            if (!isEsModule && (flattened.keypath === "module.exports" || flattened.keypath === "module" || flattened.keypath === "exports")) {
              magicString.overwrite(node2.start, node2.end, `'object'`, {
                storeName: false
              });
            }
          }
          return;
        case "VariableDeclaration":
          if (!scope.parent) {
            topLevelDeclarations.push(node2);
          }
          return;
        case "TemplateElement":
          if (node2.value.raw.includes("\n")) {
            indentExclusionRanges.push([node2.start, node2.end]);
          }
      }
    },
    leave(node2) {
      programDepth -= 1;
      if (node2.scope) scope = scope.parent;
      if (functionType.test(node2.type)) lexicalDepth -= 1;
      if (node2.type === "ClassBody") classBodyDepth -= 1;
    }
  });
  const nameBase = getName(id);
  const exportsName = deconflict([...exportsAccessScopes], globals, nameBase);
  const moduleName = deconflict([...moduleAccessScopes], globals, `${nameBase}Module`);
  const requireName = deconflict([scope], globals, `require${capitalize(nameBase)}`);
  const isRequiredName = deconflict([scope], globals, `hasRequired${capitalize(nameBase)}`);
  const helpersName = deconflict([scope], globals, "commonjsHelpers");
  const dynamicRequireName = replacedDynamicRequires.length > 0 && deconflict(
    [scope],
    globals,
    isDynamicRequireModulesEnabled ? CREATE_COMMONJS_REQUIRE_EXPORT : COMMONJS_REQUIRE_EXPORT
  );
  const deconflictedExportNames = /* @__PURE__ */ Object.create(null);
  for (const [exportName, { scopes }] of exportsAssignmentsByName) {
    deconflictedExportNames[exportName] = deconflict([...scopes], globals, exportName);
  }
  for (const node2 of replacedGlobal) {
    magicString.overwrite(node2.start, node2.end, `${helpersName}.commonjsGlobal`, {
      storeName: true
    });
  }
  for (const node2 of replacedDynamicRequires) {
    magicString.overwrite(
      node2.start,
      node2.end,
      isDynamicRequireModulesEnabled ? `${dynamicRequireName}(${JSON.stringify(virtualDynamicRequirePath)})` : dynamicRequireName,
      {
        contentOnly: true,
        storeName: true
      }
    );
  }
  shouldWrap = !isEsModule && (shouldWrap || uses.exports && moduleExportsAssignments.length > 0);
  if (!(shouldWrap || isRequired || needsRequireWrapper || uses.module || uses.exports || uses.require || topLevelDefineCompiledEsmExpressions.length > 0) && (ignoreGlobal || !uses.global)) {
    return { meta: { commonjs: { isCommonJS: false } } };
  }
  let leadingComment = "";
  if (code.startsWith("/*")) {
    const commentEnd = code.indexOf("*/", 2) + 2;
    leadingComment = `${code.slice(0, commentEnd)}
`;
    magicString.remove(0, commentEnd).trim();
  }
  let shebang = "";
  if (code.startsWith("#!")) {
    const shebangEndPosition = code.indexOf("\n") + 1;
    shebang = code.slice(0, shebangEndPosition);
    magicString.remove(0, shebangEndPosition).trim();
  }
  const exportMode = isEsModule ? "none" : shouldWrap ? uses.module ? "module" : "exports" : firstTopLevelModuleExportsAssignment ? exportsAssignmentsByName.size === 0 && topLevelDefineCompiledEsmExpressions.length === 0 ? "replace" : "module" : moduleExportsAssignments.length === 0 ? "exports" : "module";
  const exportedExportsName = exportMode === "module" ? deconflict([], globals, `${nameBase}Exports`) : exportsName;
  const importBlock = await rewriteRequireExpressionsAndGetImportBlock(
    magicString,
    topLevelDeclarations,
    reassignedNames,
    helpersName,
    dynamicRequireName,
    moduleName,
    exportsName,
    id,
    exportMode,
    resolveRequireSourcesAndUpdateMeta,
    needsRequireWrapper,
    isEsModule,
    isDynamicRequireModulesEnabled,
    getIgnoreTryCatchRequireStatementMode,
    commonjsMeta
  );
  const usesRequireWrapper = commonjsMeta.isCommonJS === IS_WRAPPED_COMMONJS;
  const exportBlock = isEsModule ? "" : rewriteExportsAndGetExportsBlock(
    magicString,
    moduleName,
    exportsName,
    exportedExportsName,
    shouldWrap,
    moduleExportsAssignments,
    firstTopLevelModuleExportsAssignment,
    exportsAssignmentsByName,
    topLevelAssignments,
    topLevelDefineCompiledEsmExpressions,
    deconflictedExportNames,
    code,
    helpersName,
    exportMode,
    defaultIsModuleExports,
    usesRequireWrapper,
    requireName
  );
  if (shouldWrap) {
    wrapCode(magicString, uses, moduleName, exportsName, indentExclusionRanges);
  }
  if (usesRequireWrapper) {
    magicString.trim().indent("	", {
      exclude: indentExclusionRanges
    });
    const exported = exportMode === "module" ? `${moduleName}.exports` : exportsName;
    magicString.prepend(
      `var ${isRequiredName};

function ${requireName} () {
	if (${isRequiredName}) return ${exported};
	${isRequiredName} = 1;
`
    ).append(`
	return ${exported};
}`);
    if (exportMode === "replace") {
      magicString.prepend(`var ${exportsName};
`);
    }
  }
  magicString.trim().prepend(shebang + leadingComment + importBlock).append(exportBlock);
  return {
    code: magicString.toString(),
    map: sourceMap ? magicString.generateMap() : null,
    syntheticNamedExports: isEsModule || usesRequireWrapper ? false : "__moduleExports",
    meta: { commonjs: { ...commonjsMeta, shebang } }
  };
}
var PLUGIN_NAME = "commonjs";
function commonjs(options2 = {}) {
  const {
    ignoreGlobal,
    ignoreDynamicRequires,
    requireReturnsDefault: requireReturnsDefaultOption,
    defaultIsModuleExports: defaultIsModuleExportsOption,
    esmExternals
  } = options2;
  const extensions2 = options2.extensions || [".js"];
  const filter2 = createFilter$1(options2.include, options2.exclude);
  const isPossibleCjsId = (id) => {
    const extName = (0, import_path.extname)(id);
    return extName === ".cjs" || extensions2.includes(extName) && filter2(id);
  };
  const { strictRequiresFilter, detectCyclesAndConditional } = getStrictRequiresFilter(options2);
  const getRequireReturnsDefault = typeof requireReturnsDefaultOption === "function" ? requireReturnsDefaultOption : () => requireReturnsDefaultOption;
  let esmExternalIds;
  const isEsmExternal = typeof esmExternals === "function" ? esmExternals : Array.isArray(esmExternals) ? (esmExternalIds = new Set(esmExternals), (id) => esmExternalIds.has(id)) : () => esmExternals;
  const getDefaultIsModuleExports = typeof defaultIsModuleExportsOption === "function" ? defaultIsModuleExportsOption : () => typeof defaultIsModuleExportsOption === "boolean" ? defaultIsModuleExportsOption : "auto";
  const dynamicRequireRoot = typeof options2.dynamicRequireRoot === "string" ? (0, import_path.resolve)(options2.dynamicRequireRoot) : process.cwd();
  const { commonDir, dynamicRequireModules } = getDynamicRequireModules(
    options2.dynamicRequireTargets,
    dynamicRequireRoot
  );
  const isDynamicRequireModulesEnabled = dynamicRequireModules.size > 0;
  const ignoreRequire = typeof options2.ignore === "function" ? options2.ignore : Array.isArray(options2.ignore) ? (id) => options2.ignore.includes(id) : () => false;
  const getIgnoreTryCatchRequireStatementMode = (id) => {
    const mode2 = typeof options2.ignoreTryCatch === "function" ? options2.ignoreTryCatch(id) : Array.isArray(options2.ignoreTryCatch) ? options2.ignoreTryCatch.includes(id) : typeof options2.ignoreTryCatch !== "undefined" ? options2.ignoreTryCatch : true;
    return {
      canConvertRequire: mode2 !== "remove" && mode2 !== true,
      shouldRemoveRequire: mode2 === "remove"
    };
  };
  const { currentlyResolving, resolveId } = getResolveId(extensions2, isPossibleCjsId);
  const sourceMap = options2.sourceMap !== false;
  let requireResolver;
  function transformAndCheckExports(code, id) {
    const normalizedId = normalizePathSlashes(id);
    const { isEsModule, hasDefaultExport, hasNamedExports, ast } = analyzeTopLevelStatements(
      this.parse,
      code,
      id
    );
    const commonjsMeta = this.getModuleInfo(id).meta.commonjs || {};
    if (hasDefaultExport) {
      commonjsMeta.hasDefaultExport = true;
    }
    if (hasNamedExports) {
      commonjsMeta.hasNamedExports = true;
    }
    if (!dynamicRequireModules.has(normalizedId) && (!(hasCjsKeywords(code, ignoreGlobal) || requireResolver.isRequiredId(id)) || isEsModule && !options2.transformMixedEsModules)) {
      commonjsMeta.isCommonJS = false;
      return { meta: { commonjs: commonjsMeta } };
    }
    const needsRequireWrapper = !isEsModule && (dynamicRequireModules.has(normalizedId) || strictRequiresFilter(id));
    const checkDynamicRequire = (position) => {
      const normalizedDynamicRequireRoot = normalizePathSlashes(dynamicRequireRoot);
      if (normalizedId.indexOf(normalizedDynamicRequireRoot) !== 0) {
        this.error(
          {
            code: "DYNAMIC_REQUIRE_OUTSIDE_ROOT",
            normalizedId,
            normalizedDynamicRequireRoot,
            message: `"${normalizedId}" contains dynamic require statements but it is not within the current dynamicRequireRoot "${normalizedDynamicRequireRoot}". You should set dynamicRequireRoot to "${(0, import_path.dirname)(
              normalizedId
            )}" or one of its parent directories.`
          },
          position
        );
      }
    };
    return transformCommonjs(
      this.parse,
      code,
      id,
      isEsModule,
      ignoreGlobal || isEsModule,
      ignoreRequire,
      ignoreDynamicRequires && !isDynamicRequireModulesEnabled,
      getIgnoreTryCatchRequireStatementMode,
      sourceMap,
      isDynamicRequireModulesEnabled,
      dynamicRequireModules,
      commonDir,
      ast,
      getDefaultIsModuleExports(id),
      needsRequireWrapper,
      requireResolver.resolveRequireSourcesAndUpdateMeta(this),
      requireResolver.isRequiredId(id),
      checkDynamicRequire,
      commonjsMeta
    );
  }
  return {
    name: PLUGIN_NAME,
    version: version$2,
    options(rawOptions) {
      const plugins2 = Array.isArray(rawOptions.plugins) ? [...rawOptions.plugins] : rawOptions.plugins ? [rawOptions.plugins] : [];
      plugins2.unshift({
        name: "commonjs--resolver",
        resolveId
      });
      return { ...rawOptions, plugins: plugins2 };
    },
    buildStart({ plugins: plugins2 }) {
      validateVersion(this.meta.rollupVersion, peerDependencies.rollup, "rollup");
      const nodeResolve = plugins2.find(({ name: name2 }) => name2 === "node-resolve");
      if (nodeResolve) {
        validateVersion(nodeResolve.version, "^13.0.6", "@rollup/plugin-node-resolve");
      }
      if (options2.namedExports != null) {
        this.warn(
          'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
        );
      }
      requireResolver = getRequireResolver(
        extensions2,
        detectCyclesAndConditional,
        currentlyResolving
      );
    },
    buildEnd() {
      if (options2.strictRequires === "debug") {
        const wrappedIds = requireResolver.getWrappedIds();
        if (wrappedIds.length) {
          this.warn({
            code: "WRAPPED_IDS",
            ids: wrappedIds,
            message: `The commonjs plugin automatically wrapped the following files:
[
${wrappedIds.map((id) => `	${JSON.stringify((0, import_path.relative)(process.cwd(), id))}`).join(",\n")}
]`
          });
        } else {
          this.warn({
            code: "WRAPPED_IDS",
            ids: wrappedIds,
            message: "The commonjs plugin did not wrap any files."
          });
        }
      }
    },
    load(id) {
      if (id === HELPERS_ID) {
        return getHelpersModule();
      }
      if (isWrappedId(id, MODULE_SUFFIX)) {
        const name2 = getName(unwrapId(id, MODULE_SUFFIX));
        return {
          code: `var ${name2} = {exports: {}}; export {${name2} as __module}`,
          meta: { commonjs: { isCommonJS: false } }
        };
      }
      if (isWrappedId(id, EXPORTS_SUFFIX)) {
        const name2 = getName(unwrapId(id, EXPORTS_SUFFIX));
        return {
          code: `var ${name2} = {}; export {${name2} as __exports}`,
          meta: { commonjs: { isCommonJS: false } }
        };
      }
      if (isWrappedId(id, EXTERNAL_SUFFIX)) {
        const actualId = unwrapId(id, EXTERNAL_SUFFIX);
        return getUnknownRequireProxy(
          actualId,
          isEsmExternal(actualId) ? getRequireReturnsDefault(actualId) : true
        );
      }
      if (id.endsWith(ENTRY_SUFFIX)) {
        const acutalId = id.slice(0, -ENTRY_SUFFIX.length);
        const {
          meta: { commonjs: commonjsMeta }
        } = this.getModuleInfo(acutalId);
        const shebang = (commonjsMeta == null ? void 0 : commonjsMeta.shebang) ?? "";
        return getEntryProxy(
          acutalId,
          getDefaultIsModuleExports(acutalId),
          this.getModuleInfo,
          shebang
        );
      }
      if (isWrappedId(id, ES_IMPORT_SUFFIX)) {
        const actualId = unwrapId(id, ES_IMPORT_SUFFIX);
        return getEsImportProxy(actualId, getDefaultIsModuleExports(actualId));
      }
      if (id === DYNAMIC_MODULES_ID) {
        return getDynamicModuleRegistry(
          isDynamicRequireModulesEnabled,
          dynamicRequireModules,
          commonDir,
          ignoreDynamicRequires
        );
      }
      if (isWrappedId(id, PROXY_SUFFIX)) {
        const actualId = unwrapId(id, PROXY_SUFFIX);
        return getStaticRequireProxy(actualId, getRequireReturnsDefault(actualId), this.load);
      }
      return null;
    },
    shouldTransformCachedModule(...args) {
      return requireResolver.shouldTransformCachedModule.call(this, ...args);
    },
    transform(code, id) {
      if (!isPossibleCjsId(id)) return null;
      try {
        return transformAndCheckExports.call(this, code, id);
      } catch (err2) {
        return this.error(err2, err2.pos);
      }
    }
  };
}
var schemeRegex = /^[\w+.-]+:\/\//;
var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
function isAbsoluteUrl(input) {
  return schemeRegex.test(input);
}
function isSchemeRelativeUrl(input) {
  return input.startsWith("//");
}
function isAbsolutePath(input) {
  return input.startsWith("/");
}
function isFileUrl(input) {
  return input.startsWith("file:");
}
function isRelative(input) {
  return /^[.?#]/.test(input);
}
function parseAbsoluteUrl(input) {
  const match2 = urlRegex.exec(input);
  return makeUrl(match2[1], match2[2] || "", match2[3], match2[4] || "", match2[5] || "/", match2[6] || "", match2[7] || "");
}
function parseFileUrl(input) {
  const match2 = fileRegex.exec(input);
  const path3 = match2[2];
  return makeUrl("file:", "", match2[1] || "", "", isAbsolutePath(path3) ? path3 : "/" + path3, match2[3] || "", match2[4] || "");
}
function makeUrl(scheme, user, host, port, path3, query, hash2) {
  return {
    scheme,
    user,
    host,
    port,
    path: path3,
    query,
    hash: hash2,
    type: 7
  };
}
function parseUrl$3(input) {
  if (isSchemeRelativeUrl(input)) {
    const url3 = parseAbsoluteUrl("http:" + input);
    url3.scheme = "";
    url3.type = 6;
    return url3;
  }
  if (isAbsolutePath(input)) {
    const url3 = parseAbsoluteUrl("http://foo.com" + input);
    url3.scheme = "";
    url3.host = "";
    url3.type = 5;
    return url3;
  }
  if (isFileUrl(input))
    return parseFileUrl(input);
  if (isAbsoluteUrl(input))
    return parseAbsoluteUrl(input);
  const url2 = parseAbsoluteUrl("http://foo.com/" + input);
  url2.scheme = "";
  url2.host = "";
  url2.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
  return url2;
}
function stripPathFilename(path3) {
  if (path3.endsWith("/.."))
    return path3;
  const index = path3.lastIndexOf("/");
  return path3.slice(0, index + 1);
}
function mergePaths(url2, base) {
  normalizePath$4(base, base.type);
  if (url2.path === "/") {
    url2.path = base.path;
  } else {
    url2.path = stripPathFilename(base.path) + url2.path;
  }
}
function normalizePath$4(url2, type) {
  const rel = type <= 4;
  const pieces = url2.path.split("/");
  let pointer = 1;
  let positive = 0;
  let addTrailingSlash = false;
  for (let i = 1; i < pieces.length; i++) {
    const piece = pieces[i];
    if (!piece) {
      addTrailingSlash = true;
      continue;
    }
    addTrailingSlash = false;
    if (piece === ".")
      continue;
    if (piece === "..") {
      if (positive) {
        addTrailingSlash = true;
        positive--;
        pointer--;
      } else if (rel) {
        pieces[pointer++] = piece;
      }
      continue;
    }
    pieces[pointer++] = piece;
    positive++;
  }
  let path3 = "";
  for (let i = 1; i < pointer; i++) {
    path3 += "/" + pieces[i];
  }
  if (!path3 || addTrailingSlash && !path3.endsWith("/..")) {
    path3 += "/";
  }
  url2.path = path3;
}
function resolve$2(input, base) {
  if (!input && !base)
    return "";
  const url2 = parseUrl$3(input);
  let inputType = url2.type;
  if (base && inputType !== 7) {
    const baseUrl = parseUrl$3(base);
    const baseType = baseUrl.type;
    switch (inputType) {
      case 1:
        url2.hash = baseUrl.hash;
      case 2:
        url2.query = baseUrl.query;
      case 3:
      case 4:
        mergePaths(url2, baseUrl);
      case 5:
        url2.user = baseUrl.user;
        url2.host = baseUrl.host;
        url2.port = baseUrl.port;
      case 6:
        url2.scheme = baseUrl.scheme;
    }
    if (baseType > inputType)
      inputType = baseType;
  }
  normalizePath$4(url2, inputType);
  const queryHash = url2.query + url2.hash;
  switch (inputType) {
    case 2:
    case 3:
      return queryHash;
    case 4: {
      const path3 = url2.path.slice(1);
      if (!path3)
        return queryHash || ".";
      if (isRelative(base || input) && !isRelative(path3)) {
        return "./" + path3 + queryHash;
      }
      return path3 + queryHash;
    }
    case 5:
      return url2.path + queryHash;
    default:
      return url2.scheme + "//" + url2.user + url2.host + url2.port + url2.path + queryHash;
  }
}
function resolve$1(input, base) {
  if (base && !base.endsWith("/"))
    base += "/";
  return resolve$2(input, base);
}
function stripFilename(path3) {
  if (!path3)
    return "";
  const index = path3.lastIndexOf("/");
  return path3.slice(0, index + 1);
}
var COLUMN$1 = 0;
var SOURCES_INDEX$1 = 1;
var SOURCE_LINE$1 = 2;
var SOURCE_COLUMN$1 = 3;
var NAMES_INDEX$1 = 4;
function maybeSort(mappings, owned) {
  const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  if (unsortedIndex === mappings.length)
    return mappings;
  if (!owned)
    mappings = mappings.slice();
  for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
    mappings[i] = sortSegments(mappings[i], owned);
  }
  return mappings;
}
function nextUnsortedSegmentLine(mappings, start) {
  for (let i = start; i < mappings.length; i++) {
    if (!isSorted(mappings[i]))
      return i;
  }
  return mappings.length;
}
function isSorted(line) {
  for (let j = 1; j < line.length; j++) {
    if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
      return false;
    }
  }
  return true;
}
function sortSegments(line, owned) {
  if (!owned)
    line = line.slice();
  return line.sort(sortComparator);
}
function sortComparator(a, b) {
  return a[COLUMN$1] - b[COLUMN$1];
}
var found = false;
function binarySearch(haystack, needle, low, high) {
  while (low <= high) {
    const mid = low + (high - low >> 1);
    const cmp = haystack[mid][COLUMN$1] - needle;
    if (cmp === 0) {
      found = true;
      return mid;
    }
    if (cmp < 0) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  found = false;
  return low - 1;
}
function upperBound(haystack, needle, index) {
  for (let i = index + 1; i < haystack.length; index = i++) {
    if (haystack[i][COLUMN$1] !== needle)
      break;
  }
  return index;
}
function lowerBound(haystack, needle, index) {
  for (let i = index - 1; i >= 0; index = i--) {
    if (haystack[i][COLUMN$1] !== needle)
      break;
  }
  return index;
}
function memoizedState() {
  return {
    lastKey: -1,
    lastNeedle: -1,
    lastIndex: -1
  };
}
function memoizedBinarySearch(haystack, needle, state, key) {
  const { lastKey, lastNeedle, lastIndex } = state;
  let low = 0;
  let high = haystack.length - 1;
  if (key === lastKey) {
    if (needle === lastNeedle) {
      found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
      return lastIndex;
    }
    if (needle >= lastNeedle) {
      low = lastIndex === -1 ? 0 : lastIndex;
    } else {
      high = lastIndex;
    }
  }
  state.lastKey = key;
  state.lastNeedle = needle;
  return state.lastIndex = binarySearch(haystack, needle, low, high);
}
var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
var LEAST_UPPER_BOUND = -1;
var GREATEST_LOWER_BOUND = 1;
var TraceMap = class {
  constructor(map2, mapUrl) {
    const isString2 = typeof map2 === "string";
    if (!isString2 && map2._decodedMemo)
      return map2;
    const parsed = isString2 ? JSON.parse(map2) : map2;
    const { version: version3, file, names, sourceRoot, sources, sourcesContent } = parsed;
    this.version = version3;
    this.file = file;
    this.names = names || [];
    this.sourceRoot = sourceRoot;
    this.sources = sources;
    this.sourcesContent = sourcesContent;
    this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
    const from = resolve$1(sourceRoot || "", stripFilename(mapUrl));
    this.resolvedSources = sources.map((s) => resolve$1(s || "", from));
    const { mappings } = parsed;
    if (typeof mappings === "string") {
      this._encoded = mappings;
      this._decoded = void 0;
    } else {
      this._encoded = void 0;
      this._decoded = maybeSort(mappings, isString2);
    }
    this._decodedMemo = memoizedState();
    this._bySources = void 0;
    this._bySourceMemos = void 0;
  }
};
function cast$2(map2) {
  return map2;
}
function encodedMappings(map2) {
  var _a4;
  var _b3;
  return (_a4 = (_b3 = cast$2(map2))._encoded) !== null && _a4 !== void 0 ? _a4 : _b3._encoded = encode$1(cast$2(map2)._decoded);
}
function decodedMappings(map2) {
  var _a4;
  return (_a4 = cast$2(map2))._decoded || (_a4._decoded = decode(cast$2(map2)._encoded));
}
function traceSegment(map2, line, column) {
  const decoded = decodedMappings(map2);
  if (line >= decoded.length)
    return null;
  const segments = decoded[line];
  const index = traceSegmentInternal(segments, cast$2(map2)._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  return index === -1 ? null : segments[index];
}
function originalPositionFor$1(map2, needle) {
  let { line, column, bias } = needle;
  line--;
  if (line < 0)
    throw new Error(LINE_GTR_ZERO);
  if (column < 0)
    throw new Error(COL_GTR_EQ_ZERO);
  const decoded = decodedMappings(map2);
  if (line >= decoded.length)
    return OMapping(null, null, null, null);
  const segments = decoded[line];
  const index = traceSegmentInternal(segments, cast$2(map2)._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  if (index === -1)
    return OMapping(null, null, null, null);
  const segment = segments[index];
  if (segment.length === 1)
    return OMapping(null, null, null, null);
  const { names, resolvedSources } = map2;
  return OMapping(resolvedSources[segment[SOURCES_INDEX$1]], segment[SOURCE_LINE$1] + 1, segment[SOURCE_COLUMN$1], segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null);
}
function decodedMap(map2) {
  return clone(map2, decodedMappings(map2));
}
function encodedMap(map2) {
  return clone(map2, encodedMappings(map2));
}
function clone(map2, mappings) {
  return {
    version: map2.version,
    file: map2.file,
    names: map2.names,
    sourceRoot: map2.sourceRoot,
    sources: map2.sources,
    sourcesContent: map2.sourcesContent,
    mappings,
    ignoreList: map2.ignoreList || map2.x_google_ignoreList
  };
}
function OMapping(source, line, column, name2) {
  return { source, line, column, name: name2 };
}
function traceSegmentInternal(segments, memo, line, column, bias) {
  let index = memoizedBinarySearch(segments, column, memo, line);
  if (found) {
    index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  } else if (bias === LEAST_UPPER_BOUND)
    index++;
  if (index === -1 || index === segments.length)
    return -1;
  return index;
}
var SetArray = class {
  constructor() {
    this._indexes = { __proto__: null };
    this.array = [];
  }
};
function cast$1(set2) {
  return set2;
}
function get(setarr, key) {
  return cast$1(setarr)._indexes[key];
}
function put(setarr, key) {
  const index = get(setarr, key);
  if (index !== void 0)
    return index;
  const { array: array2, _indexes: indexes } = cast$1(setarr);
  const length = array2.push(key);
  return indexes[key] = length - 1;
}
function remove(setarr, key) {
  const index = get(setarr, key);
  if (index === void 0)
    return;
  const { array: array2, _indexes: indexes } = cast$1(setarr);
  for (let i = index + 1; i < array2.length; i++) {
    const k = array2[i];
    array2[i - 1] = k;
    indexes[k]--;
  }
  indexes[key] = void 0;
  array2.pop();
}
var COLUMN = 0;
var SOURCES_INDEX = 1;
var SOURCE_LINE = 2;
var SOURCE_COLUMN = 3;
var NAMES_INDEX = 4;
var NO_NAME = -1;
var GenMapping = class {
  constructor({ file, sourceRoot } = {}) {
    this._names = new SetArray();
    this._sources = new SetArray();
    this._sourcesContent = [];
    this._mappings = [];
    this.file = file;
    this.sourceRoot = sourceRoot;
    this._ignoreList = new SetArray();
  }
};
function cast(map2) {
  return map2;
}
var maybeAddSegment = (map2, genLine, genColumn, source, sourceLine, sourceColumn, name2, content) => {
  return addSegmentInternal(true, map2, genLine, genColumn, source, sourceLine, sourceColumn, name2);
};
function setSourceContent(map2, source, content) {
  const { _sources: sources, _sourcesContent: sourcesContent } = cast(map2);
  const index = put(sources, source);
  sourcesContent[index] = content;
}
function setIgnore(map2, source, ignore = true) {
  const { _sources: sources, _sourcesContent: sourcesContent, _ignoreList: ignoreList } = cast(map2);
  const index = put(sources, source);
  if (index === sourcesContent.length)
    sourcesContent[index] = null;
  if (ignore)
    put(ignoreList, index);
  else
    remove(ignoreList, index);
}
function toDecodedMap(map2) {
  const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, _ignoreList: ignoreList } = cast(map2);
  removeEmptyFinalLines(mappings);
  return {
    version: 3,
    file: map2.file || void 0,
    names: names.array,
    sourceRoot: map2.sourceRoot || void 0,
    sources: sources.array,
    sourcesContent,
    mappings,
    ignoreList: ignoreList.array
  };
}
function toEncodedMap(map2) {
  const decoded = toDecodedMap(map2);
  return Object.assign(Object.assign({}, decoded), { mappings: encode$1(decoded.mappings) });
}
function addSegmentInternal(skipable, map2, genLine, genColumn, source, sourceLine, sourceColumn, name2, content) {
  const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names } = cast(map2);
  const line = getLine(mappings, genLine);
  const index = getColumnIndex(line, genColumn);
  if (!source) {
    if (skipSourceless(line, index))
      return;
    return insert(line, index, [genColumn]);
  }
  const sourcesIndex = put(sources, source);
  const namesIndex = name2 ? put(names, name2) : NO_NAME;
  if (sourcesIndex === sourcesContent.length)
    sourcesContent[sourcesIndex] = null;
  if (skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
    return;
  }
  return insert(line, index, name2 ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
}
function getLine(mappings, index) {
  for (let i = mappings.length; i <= index; i++) {
    mappings[i] = [];
  }
  return mappings[index];
}
function getColumnIndex(line, genColumn) {
  let index = line.length;
  for (let i = index - 1; i >= 0; index = i--) {
    const current = line[i];
    if (genColumn >= current[COLUMN])
      break;
  }
  return index;
}
function insert(array2, index, value2) {
  for (let i = array2.length; i > index; i--) {
    array2[i] = array2[i - 1];
  }
  array2[index] = value2;
}
function removeEmptyFinalLines(mappings) {
  const { length } = mappings;
  let len = length;
  for (let i = len - 1; i >= 0; len = i, i--) {
    if (mappings[i].length > 0)
      break;
  }
  if (len < length)
    mappings.length = len;
}
function skipSourceless(line, index) {
  if (index === 0)
    return true;
  const prev = line[index - 1];
  return prev.length === 1;
}
function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  if (index === 0)
    return false;
  const prev = line[index - 1];
  if (prev.length === 1)
    return false;
  return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME);
}
var SOURCELESS_MAPPING = SegmentObject("", -1, -1, "", null, false);
var EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name2, content, ignore) {
  return { source, line, column, name: name2, content, ignore };
}
function Source(map2, sources, source, content, ignore) {
  return {
    map: map2,
    sources,
    source,
    content,
    ignore
  };
}
function MapSource(map2, sources) {
  return Source(map2, sources, "", null, false);
}
function OriginalSource(source, content, ignore) {
  return Source(null, EMPTY_SOURCES, source, content, ignore);
}
function traceMappings(tree) {
  const gen = new GenMapping({ file: tree.map.file });
  const { sources: rootSources, map: map2 } = tree;
  const rootNames = map2.names;
  const rootMappings = decodedMappings(map2);
  for (let i = 0; i < rootMappings.length; i++) {
    const segments = rootMappings[i];
    for (let j = 0; j < segments.length; j++) {
      const segment = segments[j];
      const genCol = segment[0];
      let traced = SOURCELESS_MAPPING;
      if (segment.length !== 1) {
        const source2 = rootSources[segment[1]];
        traced = originalPositionFor(source2, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : "");
        if (traced == null)
          continue;
      }
      const { column, line, name: name2, content, source, ignore } = traced;
      maybeAddSegment(gen, i, genCol, source, line, column, name2);
      if (source && content != null)
        setSourceContent(gen, source, content);
      if (ignore)
        setIgnore(gen, source, true);
    }
  }
  return gen;
}
function originalPositionFor(source, line, column, name2) {
  if (!source.map) {
    return SegmentObject(source.source, line, column, name2, source.content, source.ignore);
  }
  const segment = traceSegment(source.map, line, column);
  if (segment == null)
    return null;
  if (segment.length === 1)
    return SOURCELESS_MAPPING;
  return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name2);
}
function asArray(value2) {
  if (Array.isArray(value2))
    return value2;
  return [value2];
}
function buildSourceMapTree(input, loader) {
  const maps = asArray(input).map((m) => new TraceMap(m, ""));
  const map2 = maps.pop();
  for (let i = 0; i < maps.length; i++) {
    if (maps[i].sources.length > 1) {
      throw new Error(`Transformation map ${i} must have exactly one source file.
Did you specify these with the most recent transformation maps first?`);
    }
  }
  let tree = build$2(map2, loader, "", 0);
  for (let i = maps.length - 1; i >= 0; i--) {
    tree = MapSource(maps[i], [tree]);
  }
  return tree;
}
function build$2(map2, loader, importer, importerDepth) {
  const { resolvedSources, sourcesContent, ignoreList } = map2;
  const depth2 = importerDepth + 1;
  const children = resolvedSources.map((sourceFile, i) => {
    const ctx = {
      importer,
      depth: depth2,
      source: sourceFile || "",
      content: void 0,
      ignore: void 0
    };
    const sourceMap = loader(ctx.source, ctx);
    const { source, content, ignore } = ctx;
    if (sourceMap)
      return build$2(new TraceMap(sourceMap, source), loader, source, depth2);
    const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null;
    const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false;
    return OriginalSource(source, sourceContent, ignored);
  });
  return MapSource(map2, children);
}
var SourceMap2 = class {
  constructor(map2, options2) {
    const out2 = options2.decodedMappings ? toDecodedMap(map2) : toEncodedMap(map2);
    this.version = out2.version;
    this.file = out2.file;
    this.mappings = out2.mappings;
    this.names = out2.names;
    this.ignoreList = out2.ignoreList;
    this.sourceRoot = out2.sourceRoot;
    this.sources = out2.sources;
    if (!options2.excludeContent) {
      this.sourcesContent = out2.sourcesContent;
    }
  }
  toString() {
    return JSON.stringify(this);
  }
};
function remapping(input, loader, options2) {
  const opts = { excludeContent: !!options2, decodedMappings: false };
  const tree = buildSourceMapTree(input, loader);
  return new SourceMap2(traceMappings(tree), opts);
}
var src$3 = { exports: {} };
var browser$3 = { exports: {} };
var ms$1;
var hasRequiredMs$1;
function requireMs$1() {
  if (hasRequiredMs$1) return ms$1;
  hasRequiredMs$1 = 1;
  var s = 1e3;
  var m = s * 60;
  var h = m * 60;
  var d = h * 24;
  var w = d * 7;
  var y = d * 365.25;
  ms$1 = function(val, options2) {
    options2 = options2 || {};
    var type = typeof val;
    if (type === "string" && val.length > 0) {
      return parse4(val);
    } else if (type === "number" && isFinite(val)) {
      return options2.long ? fmtLong(val) : fmtShort(val);
    }
    throw new Error(
      "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
    );
  };
  function parse4(str) {
    str = String(str);
    if (str.length > 100) {
      return;
    }
    var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
      str
    );
    if (!match2) {
      return;
    }
    var n2 = parseFloat(match2[1]);
    var type = (match2[2] || "ms").toLowerCase();
    switch (type) {
      case "years":
      case "year":
      case "yrs":
      case "yr":
      case "y":
        return n2 * y;
      case "weeks":
      case "week":
      case "w":
        return n2 * w;
      case "days":
      case "day":
      case "d":
        return n2 * d;
      case "hours":
      case "hour":
      case "hrs":
      case "hr":
      case "h":
        return n2 * h;
      case "minutes":
      case "minute":
      case "mins":
      case "min":
      case "m":
        return n2 * m;
      case "seconds":
      case "second":
      case "secs":
      case "sec":
      case "s":
        return n2 * s;
      case "milliseconds":
      case "millisecond":
      case "msecs":
      case "msec":
      case "ms":
        return n2;
      default:
        return void 0;
    }
  }
  function fmtShort(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d) {
      return Math.round(ms2 / d) + "d";
    }
    if (msAbs >= h) {
      return Math.round(ms2 / h) + "h";
    }
    if (msAbs >= m) {
      return Math.round(ms2 / m) + "m";
    }
    if (msAbs >= s) {
      return Math.round(ms2 / s) + "s";
    }
    return ms2 + "ms";
  }
  function fmtLong(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d) {
      return plural(ms2, msAbs, d, "day");
    }
    if (msAbs >= h) {
      return plural(ms2, msAbs, h, "hour");
    }
    if (msAbs >= m) {
      return plural(ms2, msAbs, m, "minute");
    }
    if (msAbs >= s) {
      return plural(ms2, msAbs, s, "second");
    }
    return ms2 + " ms";
  }
  function plural(ms2, msAbs, n2, name2) {
    var isPlural = msAbs >= n2 * 1.5;
    return Math.round(ms2 / n2) + " " + name2 + (isPlural ? "s" : "");
  }
  return ms$1;
}
var common$b;
var hasRequiredCommon;
function requireCommon() {
  if (hasRequiredCommon) return common$b;
  hasRequiredCommon = 1;
  function setup(env2) {
    createDebug.debug = createDebug;
    createDebug.default = createDebug;
    createDebug.coerce = coerce;
    createDebug.disable = disable;
    createDebug.enable = enable;
    createDebug.enabled = enabled;
    createDebug.humanize = requireMs$1();
    createDebug.destroy = destroy2;
    Object.keys(env2).forEach((key) => {
      createDebug[key] = env2[key];
    });
    createDebug.names = [];
    createDebug.skips = [];
    createDebug.formatters = {};
    function selectColor(namespace) {
      let hash2 = 0;
      for (let i = 0; i < namespace.length; i++) {
        hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i);
        hash2 |= 0;
      }
      return createDebug.colors[Math.abs(hash2) % createDebug.colors.length];
    }
    createDebug.selectColor = selectColor;
    function createDebug(namespace) {
      let prevTime;
      let enableOverride = null;
      let namespacesCache;
      let enabledCache;
      function debug2(...args) {
        if (!debug2.enabled) {
          return;
        }
        const self2 = debug2;
        const curr = Number(/* @__PURE__ */ new Date());
        const ms2 = curr - (prevTime || curr);
        self2.diff = ms2;
        self2.prev = prevTime;
        self2.curr = curr;
        prevTime = curr;
        args[0] = createDebug.coerce(args[0]);
        if (typeof args[0] !== "string") {
          args.unshift("%O");
        }
        let index = 0;
        args[0] = args[0].replace(/%([a-zA-Z%])/g, (match2, format2) => {
          if (match2 === "%%") {
            return "%";
          }
          index++;
          const formatter2 = createDebug.formatters[format2];
          if (typeof formatter2 === "function") {
            const val = args[index];
            match2 = formatter2.call(self2, val);
            args.splice(index, 1);
            index--;
          }
          return match2;
        });
        createDebug.formatArgs.call(self2, args);
        const logFn = self2.log || createDebug.log;
        logFn.apply(self2, args);
      }
      debug2.namespace = namespace;
      debug2.useColors = createDebug.useColors();
      debug2.color = createDebug.selectColor(namespace);
      debug2.extend = extend;
      debug2.destroy = createDebug.destroy;
      Object.defineProperty(debug2, "enabled", {
        enumerable: true,
        configurable: false,
        get: () => {
          if (enableOverride !== null) {
            return enableOverride;
          }
          if (namespacesCache !== createDebug.namespaces) {
            namespacesCache = createDebug.namespaces;
            enabledCache = createDebug.enabled(namespace);
          }
          return enabledCache;
        },
        set: (v) => {
          enableOverride = v;
        }
      });
      if (typeof createDebug.init === "function") {
        createDebug.init(debug2);
      }
      return debug2;
    }
    function extend(namespace, delimiter) {
      const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
      newDebug.log = this.log;
      return newDebug;
    }
    function enable(namespaces) {
      createDebug.save(namespaces);
      createDebug.namespaces = namespaces;
      createDebug.names = [];
      createDebug.skips = [];
      let i;
      const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/);
      const len = split.length;
      for (i = 0; i < len; i++) {
        if (!split[i]) {
          continue;
        }
        namespaces = split[i].replace(/\*/g, ".*?");
        if (namespaces[0] === "-") {
          createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$"));
        } else {
          createDebug.names.push(new RegExp("^" + namespaces + "$"));
        }
      }
    }
    function disable() {
      const namespaces = [
        ...createDebug.names.map(toNamespace),
        ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace)
      ].join(",");
      createDebug.enable("");
      return namespaces;
    }
    function enabled(name2) {
      if (name2[name2.length - 1] === "*") {
        return true;
      }
      let i;
      let len;
      for (i = 0, len = createDebug.skips.length; i < len; i++) {
        if (createDebug.skips[i].test(name2)) {
          return false;
        }
      }
      for (i = 0, len = createDebug.names.length; i < len; i++) {
        if (createDebug.names[i].test(name2)) {
          return true;
        }
      }
      return false;
    }
    function toNamespace(regexp) {
      return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*");
    }
    function coerce(val) {
      if (val instanceof Error) {
        return val.stack || val.message;
      }
      return val;
    }
    function destroy2() {
      console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
    }
    createDebug.enable(createDebug.load());
    return createDebug;
  }
  common$b = setup;
  return common$b;
}
var hasRequiredBrowser$1;
function requireBrowser$1() {
  if (hasRequiredBrowser$1) return browser$3.exports;
  hasRequiredBrowser$1 = 1;
  (function(module, exports2) {
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load2;
    exports2.useColors = useColors;
    exports2.storage = localstorage();
    exports2.destroy = /* @__PURE__ */ (() => {
      let warned2 = false;
      return () => {
        if (!warned2) {
          warned2 = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports2.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c = "color: " + this.color;
      args.splice(1, 0, c, "color: inherit");
      let index = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match2) => {
        if (match2 === "%%") {
          return;
        }
        index++;
        if (match2 === "%c") {
          lastC = index;
        }
      });
      args.splice(lastC, 0, c);
    }
    exports2.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports2.storage.setItem("debug", namespaces);
        } else {
          exports2.storage.removeItem("debug");
        }
      } catch (error2) {
      }
    }
    function load2() {
      let r2;
      try {
        r2 = exports2.storage.getItem("debug");
      } catch (error2) {
      }
      if (!r2 && typeof process !== "undefined" && "env" in process) {
        r2 = process.env.DEBUG;
      }
      return r2;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error2) {
      }
    }
    module.exports = requireCommon()(exports2);
    const { formatters } = module.exports;
    formatters.j = function(v) {
      try {
        return JSON.stringify(v);
      } catch (error2) {
        return "[UnexpectedJSONParseError]: " + error2.message;
      }
    };
  })(browser$3, browser$3.exports);
  return browser$3.exports;
}
var node$1 = { exports: {} };
var hasRequiredNode$1;
function requireNode$1() {
  if (hasRequiredNode$1) return node$1.exports;
  hasRequiredNode$1 = 1;
  (function(module, exports2) {
    const tty = import_tty.default;
    const util2 = import_util.default;
    exports2.init = init2;
    exports2.log = log;
    exports2.formatArgs = formatArgs;
    exports2.save = save;
    exports2.load = load2;
    exports2.useColors = useColors;
    exports2.destroy = util2.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports2.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor = require2("supports-color");
      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
        exports2.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error2) {
    }
    exports2.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
        return k.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports2.inspectOpts ? Boolean(exports2.inspectOpts.colors) : tty.isatty(process.stderr.fd);
    }
    function formatArgs(args) {
      const { namespace: name2, useColors: useColors2 } = this;
      if (useColors2) {
        const c = this.color;
        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
        const prefix = `  ${colorCode};1m${name2} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name2 + " " + args[0];
      }
    }
    function getDate() {
      if (exports2.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log(...args) {
      return process.stderr.write(util2.formatWithOptions(exports2.inspectOpts, ...args) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load2() {
      return process.env.DEBUG;
    }
    function init2(debug2) {
      debug2.inspectOpts = {};
      const keys = Object.keys(exports2.inspectOpts);
      for (let i = 0; i < keys.length; i++) {
        debug2.inspectOpts[keys[i]] = exports2.inspectOpts[keys[i]];
      }
    }
    module.exports = requireCommon()(exports2);
    const { formatters } = module.exports;
    formatters.o = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util2.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v) {
      this.inspectOpts.colors = this.useColors;
      return util2.inspect(v, this.inspectOpts);
    };
  })(node$1, node$1.exports);
  return node$1.exports;
}
if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
  src$3.exports = requireBrowser$1();
} else {
  src$3.exports = requireNode$1();
}
var srcExports$1 = src$3.exports;
var debug$i = getDefaultExportFromCjs(srcExports$1);
var pnp;
if (process.versions.pnp) {
  try {
    pnp = (0, import_node_module.createRequire)(import.meta.url)("pnpapi");
  } catch {
  }
}
function invalidatePackageData(packageCache, pkgPath) {
  const pkgDir = normalizePath$3(import_node_path3.default.dirname(pkgPath));
  packageCache.forEach((pkg, cacheKey) => {
    if (pkg.dir === pkgDir) {
      packageCache.delete(cacheKey);
    }
  });
}
function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
  if (pnp) {
    const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
    if (packageCache == null ? void 0 : packageCache.has(cacheKey)) return packageCache.get(cacheKey);
    try {
      const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
        considerBuiltins: false
      });
      if (!pkg) return null;
      const pkgData = loadPackageData(import_node_path3.default.join(pkg, "package.json"));
      packageCache == null ? void 0 : packageCache.set(cacheKey, pkgData);
      return pkgData;
    } catch {
      return null;
    }
  }
  const originalBasedir = basedir;
  while (basedir) {
    if (packageCache) {
      const cached = getRpdCache(
        packageCache,
        pkgName,
        basedir,
        originalBasedir,
        preserveSymlinks
      );
      if (cached) return cached;
    }
    const pkg = import_node_path3.default.join(basedir, "node_modules", pkgName, "package.json");
    try {
      if (import_node_fs2.default.existsSync(pkg)) {
        const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
        const pkgData = loadPackageData(pkgPath);
        if (packageCache) {
          setRpdCache(
            packageCache,
            pkgData,
            pkgName,
            basedir,
            originalBasedir,
            preserveSymlinks
          );
        }
        return pkgData;
      }
    } catch {
    }
    const nextBasedir = import_node_path3.default.dirname(basedir);
    if (nextBasedir === basedir) break;
    basedir = nextBasedir;
  }
  return null;
}
function findNearestPackageData(basedir, packageCache) {
  var _a4;
  const originalBasedir = basedir;
  while (basedir) {
    if (packageCache) {
      const cached = getFnpdCache(packageCache, basedir, originalBasedir);
      if (cached) return cached;
    }
    const pkgPath = import_node_path3.default.join(basedir, "package.json");
    if ((_a4 = tryStatSync(pkgPath)) == null ? void 0 : _a4.isFile()) {
      try {
        const pkgData = loadPackageData(pkgPath);
        if (packageCache) {
          setFnpdCache(packageCache, pkgData, basedir, originalBasedir);
        }
        return pkgData;
      } catch {
      }
    }
    const nextBasedir = import_node_path3.default.dirname(basedir);
    if (nextBasedir === basedir) break;
    basedir = nextBasedir;
  }
  return null;
}
function findNearestMainPackageData(basedir, packageCache) {
  const nearestPackage = findNearestPackageData(basedir, packageCache);
  return nearestPackage && (nearestPackage.data.name ? nearestPackage : findNearestMainPackageData(
    import_node_path3.default.dirname(nearestPackage.dir),
    packageCache
  ));
}
function loadPackageData(pkgPath) {
  const data = JSON.parse(import_node_fs2.default.readFileSync(pkgPath, "utf-8"));
  const pkgDir = normalizePath$3(import_node_path3.default.dirname(pkgPath));
  const { sideEffects } = data;
  let hasSideEffects;
  if (typeof sideEffects === "boolean") {
    hasSideEffects = () => sideEffects;
  } else if (Array.isArray(sideEffects)) {
    if (sideEffects.length <= 0) {
      hasSideEffects = () => false;
    } else {
      const finalPackageSideEffects = sideEffects.map((sideEffect) => {
        if (sideEffect.includes("/")) {
          return sideEffect;
        }
        return `**/${sideEffect}`;
      });
      hasSideEffects = createFilter2(finalPackageSideEffects, null, {
        resolve: pkgDir
      });
    }
  } else {
    hasSideEffects = () => null;
  }
  const pkg = {
    dir: pkgDir,
    data,
    hasSideEffects,
    webResolvedImports: {},
    nodeResolvedImports: {},
    setResolvedCache(key, entry2, targetWeb) {
      if (targetWeb) {
        pkg.webResolvedImports[key] = entry2;
      } else {
        pkg.nodeResolvedImports[key] = entry2;
      }
    },
    getResolvedCache(key, targetWeb) {
      if (targetWeb) {
        return pkg.webResolvedImports[key];
      } else {
        return pkg.nodeResolvedImports[key];
      }
    }
  };
  return pkg;
}
function watchPackageDataPlugin(packageCache) {
  const watchQueue = /* @__PURE__ */ new Set();
  const watchedDirs = /* @__PURE__ */ new Set();
  const watchFileStub = (id) => {
    watchQueue.add(id);
  };
  let watchFile = watchFileStub;
  const setPackageData = packageCache.set.bind(packageCache);
  packageCache.set = (id, pkg) => {
    if (!isInNodeModules$1(pkg.dir) && !watchedDirs.has(pkg.dir)) {
      watchedDirs.add(pkg.dir);
      watchFile(import_node_path3.default.join(pkg.dir, "package.json"));
    }
    return setPackageData(id, pkg);
  };
  return {
    name: "vite:watch-package-data",
    buildStart() {
      watchFile = this.addWatchFile.bind(this);
      watchQueue.forEach(watchFile);
      watchQueue.clear();
    },
    buildEnd() {
      watchFile = watchFileStub;
    },
    watchChange(id) {
      if (id.endsWith("/package.json")) {
        invalidatePackageData(packageCache, import_node_path3.default.normalize(id));
      }
    },
    handleHotUpdate({ file }) {
      if (file.endsWith("/package.json")) {
        invalidatePackageData(packageCache, import_node_path3.default.normalize(file));
      }
    }
  };
}
function getRpdCache(packageCache, pkgName, basedir, originalBasedir, preserveSymlinks) {
  const cacheKey = getRpdCacheKey(pkgName, basedir, preserveSymlinks);
  const pkgData = packageCache.get(cacheKey);
  if (pkgData) {
    traverseBetweenDirs(originalBasedir, basedir, (dir) => {
      packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
    });
    return pkgData;
  }
}
function setRpdCache(packageCache, pkgData, pkgName, basedir, originalBasedir, preserveSymlinks) {
  packageCache.set(getRpdCacheKey(pkgName, basedir, preserveSymlinks), pkgData);
  traverseBetweenDirs(originalBasedir, basedir, (dir) => {
    packageCache.set(getRpdCacheKey(pkgName, dir, preserveSymlinks), pkgData);
  });
}
function getRpdCacheKey(pkgName, basedir, preserveSymlinks) {
  return `rpd_${pkgName}_${basedir}_${preserveSymlinks}`;
}
function getFnpdCache(packageCache, basedir, originalBasedir) {
  const cacheKey = getFnpdCacheKey(basedir);
  const pkgData = packageCache.get(cacheKey);
  if (pkgData) {
    traverseBetweenDirs(originalBasedir, basedir, (dir) => {
      packageCache.set(getFnpdCacheKey(dir), pkgData);
    });
    return pkgData;
  }
}
function setFnpdCache(packageCache, pkgData, basedir, originalBasedir) {
  packageCache.set(getFnpdCacheKey(basedir), pkgData);
  traverseBetweenDirs(originalBasedir, basedir, (dir) => {
    packageCache.set(getFnpdCacheKey(dir), pkgData);
  });
}
function getFnpdCacheKey(basedir) {
  return `fnpd_${basedir}`;
}
function traverseBetweenDirs(longerDir, shorterDir, cb) {
  while (longerDir !== shorterDir) {
    cb(longerDir);
    longerDir = import_node_path3.default.dirname(longerDir);
  }
}
var createFilter2 = createFilter$1;
var replaceSlashOrColonRE = /[/:]/g;
var replaceDotRE = /\./g;
var replaceNestedIdRE = /(\s*>\s*)/g;
var replaceHashRE = /#/g;
var flattenId = (id) => {
  const flatId = limitFlattenIdLength(
    id.replace(replaceSlashOrColonRE, "_").replace(replaceDotRE, "__").replace(replaceNestedIdRE, "___").replace(replaceHashRE, "____")
  );
  return flatId;
};
var FLATTEN_ID_HASH_LENGTH = 8;
var FLATTEN_ID_MAX_FILE_LENGTH = 170;
var limitFlattenIdLength = (id, limit = FLATTEN_ID_MAX_FILE_LENGTH) => {
  if (id.length <= limit) {
    return id;
  }
  return id.slice(0, limit - (FLATTEN_ID_HASH_LENGTH + 1)) + "_" + getHash(id);
};
var normalizeId = (id) => id.replace(replaceNestedIdRE, " > ");
var NODE_BUILTIN_NAMESPACE = "node:";
var NPM_BUILTIN_NAMESPACE = "npm:";
var BUN_BUILTIN_NAMESPACE = "bun:";
var nodeBuiltins = import_node_module.builtinModules.filter((id) => !id.includes(":"));
function isBuiltin(id) {
  if (process.versions.deno && id.startsWith(NPM_BUILTIN_NAMESPACE)) return true;
  if (process.versions.bun && id.startsWith(BUN_BUILTIN_NAMESPACE)) return true;
  return isNodeBuiltin(id);
}
function isNodeBuiltin(id) {
  if (id.startsWith(NODE_BUILTIN_NAMESPACE)) return true;
  return nodeBuiltins.includes(id);
}
function isInNodeModules$1(id) {
  return id.includes("node_modules");
}
function moduleListContains(moduleList, id) {
  return moduleList == null ? void 0 : moduleList.some(
    (m) => m === id || id.startsWith(withTrailingSlash(m))
  );
}
function isOptimizable(id, optimizeDeps2) {
  const { extensions: extensions2 } = optimizeDeps2;
  return OPTIMIZABLE_ENTRY_RE.test(id) || ((extensions2 == null ? void 0 : extensions2.some((ext2) => id.endsWith(ext2))) ?? false);
}
var bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;
var _require$1 = (0, import_node_module.createRequire)(import.meta.url);
function resolveDependencyVersion(dep, pkgRelativePath = "../../package.json") {
  const pkgPath = import_node_path3.default.resolve(_require$1.resolve(dep), pkgRelativePath);
  return JSON.parse(import_node_fs2.default.readFileSync(pkgPath, "utf-8")).version;
}
var rollupVersion = resolveDependencyVersion("rollup");
var filter = process.env.VITE_DEBUG_FILTER;
var DEBUG = process.env.DEBUG;
function createDebugger(namespace, options2 = {}) {
  const log = debug$i(namespace);
  const { onlyWhenFocused } = options2;
  let enabled = log.enabled;
  if (enabled && onlyWhenFocused) {
    const ns = typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace;
    enabled = !!(DEBUG == null ? void 0 : DEBUG.includes(ns));
  }
  if (enabled) {
    return (...args) => {
      if (!filter || args.some((a) => {
        var _a4;
        return (_a4 = a == null ? void 0 : a.includes) == null ? void 0 : _a4.call(a, filter);
      })) {
        log(...args);
      }
    };
  }
}
function testCaseInsensitiveFS() {
  if (!CLIENT_ENTRY.endsWith("client.mjs")) {
    throw new Error(
      `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
    );
  }
  if (!import_node_fs2.default.existsSync(CLIENT_ENTRY)) {
    throw new Error(
      "cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY
    );
  }
  return import_node_fs2.default.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
}
var urlCanParse = (
  // eslint-disable-next-line n/no-unsupported-features/node-builtins
  import_node_url2.URL.canParse ?? // URL.canParse is supported from Node.js 18.17.0+, 20.0.0+
  ((path22, base) => {
    try {
      new import_node_url2.URL(path22, base);
      return true;
    } catch {
      return false;
    }
  })
);
var isCaseInsensitiveFS = testCaseInsensitiveFS();
var VOLUME_RE = /^[A-Z]:/i;
function normalizePath$3(id) {
  return import_node_path3.default.posix.normalize(isWindows$3 ? slash$1(id) : id);
}
function fsPathFromId(id) {
  const fsPath = normalizePath$3(
    id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
  );
  return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
}
function fsPathFromUrl(url2) {
  return fsPathFromId(cleanUrl(url2));
}
function isParentDirectory(dir, file) {
  dir = withTrailingSlash(dir);
  return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
}
function isSameFileUri(file1, file2) {
  return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
}
var externalRE = /^(https?:)?\/\//;
var isExternalUrl = (url2) => externalRE.test(url2);
var dataUrlRE = /^\s*data:/i;
var isDataUrl = (url2) => dataUrlRE.test(url2);
var virtualModuleRE = /^virtual-module:.*/;
var virtualModulePrefix = "virtual-module:";
var knownJsSrcRE = /\.(?:[jt]sx?|m[jt]s|vue|marko|svelte|astro|imba|mdx)(?:$|\?)/;
var isJSRequest = (url2) => {
  url2 = cleanUrl(url2);
  if (knownJsSrcRE.test(url2)) {
    return true;
  }
  if (!import_node_path3.default.extname(url2) && url2[url2.length - 1] !== "/") {
    return true;
  }
  return false;
};
var knownTsRE = /\.(?:ts|mts|cts|tsx)(?:$|\?)/;
var isTsRequest = (url2) => knownTsRE.test(url2);
var importQueryRE = /(\?|&)import=?(?:&|$)/;
var directRequestRE$1 = /(\?|&)direct=?(?:&|$)/;
var internalPrefixes = [
  FS_PREFIX,
  VALID_ID_PREFIX,
  CLIENT_PUBLIC_PATH,
  ENV_PUBLIC_PATH
];
var InternalPrefixRE = new RegExp(`^(?:${internalPrefixes.join("|")})`);
var trailingSeparatorRE = /[?&]$/;
var isImportRequest = (url2) => importQueryRE.test(url2);
var isInternalRequest = (url2) => InternalPrefixRE.test(url2);
function removeImportQuery(url2) {
  return url2.replace(importQueryRE, "$1").replace(trailingSeparatorRE, "");
}
function removeDirectQuery(url2) {
  return url2.replace(directRequestRE$1, "$1").replace(trailingSeparatorRE, "");
}
var urlRE = /(\?|&)url(?:&|$)/;
var rawRE = /(\?|&)raw(?:&|$)/;
function removeUrlQuery(url2) {
  return url2.replace(urlRE, "$1").replace(trailingSeparatorRE, "");
}
var replacePercentageRE = /%/g;
function injectQuery(url2, queryToInject) {
  const resolvedUrl = new import_node_url2.URL(
    url2.replace(replacePercentageRE, "%25"),
    "relative:///"
  );
  const { search, hash: hash2 } = resolvedUrl;
  let pathname = cleanUrl(url2);
  pathname = isWindows$3 ? slash$1(pathname) : pathname;
  return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${hash2 ?? ""}`;
}
var timestampRE = /\bt=\d{13}&?\b/;
function removeTimestampQuery(url2) {
  return url2.replace(timestampRE, "").replace(trailingSeparatorRE, "");
}
async function asyncReplace(input, re, replacer) {
  let match2;
  let remaining = input;
  let rewritten = "";
  while (match2 = re.exec(remaining)) {
    rewritten += remaining.slice(0, match2.index);
    rewritten += await replacer(match2);
    remaining = remaining.slice(match2.index + match2[0].length);
  }
  rewritten += remaining;
  return rewritten;
}
function timeFrom(start, subtract = 0) {
  const time = import_node_perf_hooks.performance.now() - start - subtract;
  const timeString = (time.toFixed(2) + `ms`).padEnd(5, " ");
  if (time < 10) {
    return colors$1.green(timeString);
  } else if (time < 50) {
    return colors$1.yellow(timeString);
  } else {
    return colors$1.red(timeString);
  }
}
function prettifyUrl(url2, root) {
  url2 = removeTimestampQuery(url2);
  const isAbsoluteFile = url2.startsWith(root);
  if (isAbsoluteFile || url2.startsWith(FS_PREFIX)) {
    const file = import_node_path3.default.posix.relative(
      root,
      isAbsoluteFile ? url2 : fsPathFromId(url2)
    );
    return colors$1.dim(file);
  } else {
    return colors$1.dim(url2);
  }
}
function isObject$1(value2) {
  return Object.prototype.toString.call(value2) === "[object Object]";
}
function isDefined(value2) {
  return value2 != null;
}
function tryStatSync(file) {
  try {
    return import_node_fs2.default.statSync(file, { throwIfNoEntry: false });
  } catch {
  }
}
function lookupFile(dir, fileNames) {
  var _a4;
  while (dir) {
    for (const fileName of fileNames) {
      const fullPath = import_node_path3.default.join(dir, fileName);
      if ((_a4 = tryStatSync(fullPath)) == null ? void 0 : _a4.isFile()) return fullPath;
    }
    const parentDir2 = import_node_path3.default.dirname(dir);
    if (parentDir2 === dir) return;
    dir = parentDir2;
  }
}
function isFilePathESM(filePath, packageCache) {
  if (/\.m[jt]s$/.test(filePath)) {
    return true;
  } else if (/\.c[jt]s$/.test(filePath)) {
    return false;
  } else {
    try {
      const pkg = findNearestPackageData(import_node_path3.default.dirname(filePath), packageCache);
      return (pkg == null ? void 0 : pkg.data.type) === "module";
    } catch {
      return false;
    }
  }
}
var splitRE = /\r?\n/g;
var range = 2;
function pad$1(source, n2 = 2) {
  const lines = source.split(splitRE);
  return lines.map((l) => ` `.repeat(n2) + l).join(`
`);
}
function posToNumber(source, pos) {
  if (typeof pos === "number") return pos;
  const lines = source.split(splitRE);
  const { line, column } = pos;
  let start = 0;
  for (let i = 0; i < line - 1 && i < lines.length; i++) {
    start += lines[i].length + 1;
  }
  return start + column;
}
function numberToPos(source, offset2) {
  if (typeof offset2 !== "number") return offset2;
  if (offset2 > source.length) {
    throw new Error(
      `offset is longer than source length! offset ${offset2} > length ${source.length}`
    );
  }
  const lines = source.split(splitRE);
  let counted = 0;
  let line = 0;
  let column = 0;
  for (; line < lines.length; line++) {
    const lineLength = lines[line].length + 1;
    if (counted + lineLength >= offset2) {
      column = offset2 - counted + 1;
      break;
    }
    counted += lineLength;
  }
  return { line: line + 1, column };
}
function generateCodeFrame(source, start = 0, end) {
  start = Math.max(posToNumber(source, start), 0);
  end = Math.min(
    end !== void 0 ? posToNumber(source, end) : start,
    source.length
  );
  const lines = source.split(splitRE);
  let count = 0;
  const res = [];
  for (let i = 0; i < lines.length; i++) {
    count += lines[i].length;
    if (count >= start) {
      for (let j = i - range; j <= i + range || end > count; j++) {
        if (j < 0 || j >= lines.length) continue;
        const line = j + 1;
        res.push(
          `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}|  ${lines[j]}`
        );
        const lineLength = lines[j].length;
        if (j === i) {
          const pad2 = Math.max(start - (count - lineLength), 0);
          const length = Math.max(
            1,
            end > count ? lineLength - pad2 : end - start
          );
          res.push(`   |  ` + " ".repeat(pad2) + "^".repeat(length));
        } else if (j > i) {
          if (end > count) {
            const length = Math.max(Math.min(end - count, lineLength), 1);
            res.push(`   |  ` + "^".repeat(length));
          }
          count += lineLength + 1;
        }
      }
      break;
    }
    count++;
  }
  return res.join("\n");
}
function isFileReadable(filename) {
  if (!tryStatSync(filename)) {
    return false;
  }
  try {
    import_node_fs2.default.accessSync(filename, import_node_fs2.default.constants.R_OK);
    return true;
  } catch {
    return false;
  }
}
var splitFirstDirRE = /(.+?)[\\/](.+)/;
function emptyDir(dir, skip) {
  const skipInDir = [];
  let nested = null;
  if (skip == null ? void 0 : skip.length) {
    for (const file of skip) {
      if (import_node_path3.default.dirname(file) !== ".") {
        const matched = file.match(splitFirstDirRE);
        if (matched) {
          nested ?? (nested = /* @__PURE__ */ new Map());
          const [, nestedDir, skipPath] = matched;
          let nestedSkip = nested.get(nestedDir);
          if (!nestedSkip) {
            nestedSkip = [];
            nested.set(nestedDir, nestedSkip);
          }
          if (!nestedSkip.includes(skipPath)) {
            nestedSkip.push(skipPath);
          }
        }
      } else {
        skipInDir.push(file);
      }
    }
  }
  for (const file of import_node_fs2.default.readdirSync(dir)) {
    if (skipInDir.includes(file)) {
      continue;
    }
    if (nested == null ? void 0 : nested.has(file)) {
      emptyDir(import_node_path3.default.resolve(dir, file), nested.get(file));
    } else {
      import_node_fs2.default.rmSync(import_node_path3.default.resolve(dir, file), { recursive: true, force: true });
    }
  }
}
function copyDir(srcDir, destDir) {
  import_node_fs2.default.mkdirSync(destDir, { recursive: true });
  for (const file of import_node_fs2.default.readdirSync(srcDir)) {
    const srcFile = import_node_path3.default.resolve(srcDir, file);
    if (srcFile === destDir) {
      continue;
    }
    const destFile = import_node_path3.default.resolve(destDir, file);
    const stat2 = import_node_fs2.default.statSync(srcFile);
    if (stat2.isDirectory()) {
      copyDir(srcFile, destFile);
    } else {
      import_node_fs2.default.copyFileSync(srcFile, destFile);
    }
  }
}
var ERR_SYMLINK_IN_RECURSIVE_READDIR = "ERR_SYMLINK_IN_RECURSIVE_READDIR";
async function recursiveReaddir(dir) {
  if (!import_node_fs2.default.existsSync(dir)) {
    return [];
  }
  let dirents;
  try {
    dirents = await import_promises.default.readdir(dir, { withFileTypes: true });
  } catch (e2) {
    if (e2.code === "EACCES") {
      return [];
    }
    throw e2;
  }
  if (dirents.some((dirent) => dirent.isSymbolicLink())) {
    const err2 = new Error(
      "Symbolic links are not supported in recursiveReaddir"
    );
    err2.code = ERR_SYMLINK_IN_RECURSIVE_READDIR;
    throw err2;
  }
  const files = await Promise.all(
    dirents.map((dirent) => {
      const res = import_node_path3.default.resolve(dir, dirent.name);
      return dirent.isDirectory() ? recursiveReaddir(res) : normalizePath$3(res);
    })
  );
  return files.flat(1);
}
var safeRealpathSync = isWindows$3 ? windowsSafeRealPathSync : import_node_fs2.default.realpathSync.native;
var windowsNetworkMap = /* @__PURE__ */ new Map();
function windowsMappedRealpathSync(path22) {
  const realPath = import_node_fs2.default.realpathSync.native(path22);
  if (realPath.startsWith("\\\\")) {
    for (const [network, volume] of windowsNetworkMap) {
      if (realPath.startsWith(network)) return realPath.replace(network, volume);
    }
  }
  return realPath;
}
var parseNetUseRE = /^(\w+)? +(\w:) +([^ ]+)\s/;
var firstSafeRealPathSyncRun = false;
function windowsSafeRealPathSync(path22) {
  if (!firstSafeRealPathSyncRun) {
    optimizeSafeRealPathSync();
    firstSafeRealPathSyncRun = true;
  }
  return import_node_fs2.default.realpathSync(path22);
}
function optimizeSafeRealPathSync() {
  const nodeVersion = process.versions.node.split(".").map(Number);
  if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
    safeRealpathSync = import_node_fs2.default.realpathSync;
    return;
  }
  try {
    import_node_fs2.default.realpathSync.native(import_node_path3.default.resolve("./"));
  } catch (error2) {
    if (error2.message.includes("EISDIR: illegal operation on a directory")) {
      safeRealpathSync = import_node_fs2.default.realpathSync;
      return;
    }
  }
  (0, import_node_child_process.exec)("net use", (error2, stdout) => {
    if (error2) return;
    const lines = stdout.split("\n");
    for (const line of lines) {
      const m = line.match(parseNetUseRE);
      if (m) windowsNetworkMap.set(m[3], m[2]);
    }
    if (windowsNetworkMap.size === 0) {
      safeRealpathSync = import_node_fs2.default.realpathSync.native;
    } else {
      safeRealpathSync = windowsMappedRealpathSync;
    }
  });
}
function ensureWatchedFile(watcher, file, root) {
  if (file && // only need to watch if out of root
  !file.startsWith(withTrailingSlash(root)) && // some rollup plugins use null bytes for private resolved Ids
  !file.includes("\0") && import_node_fs2.default.existsSync(file)) {
    watcher.add(import_node_path3.default.resolve(file));
  }
}
var escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
var imageSetUrlRE = /^(?:[\w\-]+\(.*?\)|'.*?'|".*?"|\S*)/;
function joinSrcset(ret) {
  return ret.map(({ url: url2, descriptor }) => url2 + (descriptor ? ` ${descriptor}` : "")).join(", ");
}
function splitSrcSetDescriptor(srcs) {
  return splitSrcSet(srcs).map((s) => {
    var _a4;
    const src2 = s.replace(escapedSpaceCharacters, " ").trim();
    const url2 = ((_a4 = imageSetUrlRE.exec(src2)) == null ? void 0 : _a4[0]) ?? "";
    return {
      url: url2,
      descriptor: src2.slice(url2.length).trim()
    };
  }).filter(({ url: url2 }) => !!url2);
}
function processSrcSet(srcs, replacer) {
  return Promise.all(
    splitSrcSetDescriptor(srcs).map(async ({ url: url2, descriptor }) => ({
      url: await replacer({ url: url2, descriptor }),
      descriptor
    }))
  ).then(joinSrcset);
}
function processSrcSetSync(srcs, replacer) {
  return joinSrcset(
    splitSrcSetDescriptor(srcs).map(({ url: url2, descriptor }) => ({
      url: replacer({ url: url2, descriptor }),
      descriptor
    }))
  );
}
var cleanSrcSetRE = new RegExp(`(?:url|image|gradient|cross-fade)\\([^)]*\\)|"([^"]|(?<=\\\\)")*"|'([^']|(?<=\\\\)')*'|data:\\w+\\/[\\w.+\\-]+;base64,[\\w+/=]+|\\?\\S+,`, "g");
function splitSrcSet(srcs) {
  const parts = [];
  const cleanedSrcs = srcs.replace(cleanSrcSetRE, blankReplacer);
  let startIndex = 0;
  let splitIndex;
  do {
    splitIndex = cleanedSrcs.indexOf(",", startIndex);
    parts.push(
      srcs.slice(startIndex, splitIndex !== -1 ? splitIndex : void 0)
    );
    startIndex = splitIndex + 1;
  } while (splitIndex !== -1);
  return parts;
}
var windowsDriveRE = /^[A-Z]:/;
var replaceWindowsDriveRE = /^([A-Z]):\//;
var linuxAbsolutePathRE = /^\/[^/]/;
function escapeToLinuxLikePath(path22) {
  if (windowsDriveRE.test(path22)) {
    return path22.replace(replaceWindowsDriveRE, "/windows/$1/");
  }
  if (linuxAbsolutePathRE.test(path22)) {
    return `/linux${path22}`;
  }
  return path22;
}
var revertWindowsDriveRE = /^\/windows\/([A-Z])\//;
function unescapeToLinuxLikePath(path22) {
  if (path22.startsWith("/linux/")) {
    return path22.slice("/linux".length);
  }
  if (path22.startsWith("/windows/")) {
    return path22.replace(revertWindowsDriveRE, "$1:/");
  }
  return path22;
}
var nullSourceMap = {
  names: [],
  sources: [],
  mappings: "",
  version: 3
};
function combineSourcemaps(filename, sourcemapList) {
  if (sourcemapList.length === 0 || sourcemapList.every((m) => m.sources.length === 0)) {
    return { ...nullSourceMap };
  }
  sourcemapList = sourcemapList.map((sourcemap) => {
    const newSourcemaps = { ...sourcemap };
    newSourcemaps.sources = sourcemap.sources.map(
      (source) => source ? escapeToLinuxLikePath(source) : null
    );
    if (sourcemap.sourceRoot) {
      newSourcemaps.sourceRoot = escapeToLinuxLikePath(sourcemap.sourceRoot);
    }
    return newSourcemaps;
  });
  let map2;
  let mapIndex = 1;
  const useArrayInterface = sourcemapList.slice(0, -1).find((m) => m.sources.length !== 1) === void 0;
  if (useArrayInterface) {
    map2 = remapping(sourcemapList, () => null);
  } else {
    map2 = remapping(sourcemapList[0], function loader(sourcefile) {
      const mapForSources = sourcemapList.slice(mapIndex).find((s) => s.sources.includes(sourcefile));
      if (mapForSources) {
        mapIndex++;
        return mapForSources;
      }
      return null;
    });
  }
  if (!map2.file) {
    delete map2.file;
  }
  map2.sources = map2.sources.map(
    (source) => source ? unescapeToLinuxLikePath(source) : source
  );
  map2.file = filename;
  return map2;
}
function unique(arr) {
  return Array.from(new Set(arr));
}
async function getLocalhostAddressIfDiffersFromDNS() {
  const [nodeResult, dnsResult] = await Promise.all([
    import_node_dns.promises.lookup("localhost"),
    import_node_dns.promises.lookup("localhost", { verbatim: true })
  ]);
  const isSame = nodeResult.family === dnsResult.family && nodeResult.address === dnsResult.address;
  return isSame ? void 0 : nodeResult.address;
}
function diffDnsOrderChange(oldUrls, newUrls) {
  return !(oldUrls === newUrls || oldUrls && newUrls && arrayEqual(oldUrls.local, newUrls.local) && arrayEqual(oldUrls.network, newUrls.network));
}
async function resolveHostname(optionsHost) {
  let host;
  if (optionsHost === void 0 || optionsHost === false) {
    host = "localhost";
  } else if (optionsHost === true) {
    host = void 0;
  } else {
    host = optionsHost;
  }
  let name2 = host === void 0 || wildcardHosts.has(host) ? "localhost" : host;
  if (host === "localhost") {
    const localhostAddr = await getLocalhostAddressIfDiffersFromDNS();
    if (localhostAddr) {
      name2 = localhostAddr;
    }
  }
  return { host, name: name2 };
}
async function resolveServerUrls(server2, options2, config2) {
  const address = server2.address();
  const isAddressInfo = (x) => x == null ? void 0 : x.address;
  if (!isAddressInfo(address)) {
    return { local: [], network: [] };
  }
  const local = [];
  const network = [];
  const hostname = await resolveHostname(options2.host);
  const protocol = options2.https ? "https" : "http";
  const port = address.port;
  const base = config2.rawBase === "./" || config2.rawBase === "" ? "/" : config2.rawBase;
  if (hostname.host !== void 0 && !wildcardHosts.has(hostname.host)) {
    let hostnameName = hostname.name;
    if (hostnameName.includes(":")) {
      hostnameName = `[${hostnameName}]`;
    }
    const address2 = `${protocol}://${hostnameName}:${port}${base}`;
    if (loopbackHosts.has(hostname.host)) {
      local.push(address2);
    } else {
      network.push(address2);
    }
  } else {
    Object.values(import_node_os.default.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter(
      (detail) => detail && detail.address && (detail.family === "IPv4" || // @ts-expect-error Node 18.0 - 18.3 returns number
      detail.family === 4)
    ).forEach((detail) => {
      let host = detail.address.replace("127.0.0.1", hostname.name);
      if (host.includes(":")) {
        host = `[${host}]`;
      }
      const url2 = `${protocol}://${host}:${port}${base}`;
      if (detail.address.includes("127.0.0.1")) {
        local.push(url2);
      } else {
        network.push(url2);
      }
    });
  }
  return { local, network };
}
function arraify(target) {
  return Array.isArray(target) ? target : [target];
}
var multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g;
var singlelineCommentsRE = /\/\/.*/g;
var requestQuerySplitRE = /\?(?!.*[/|}])/;
var requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/;
var blankReplacer = (match2) => " ".repeat(match2.length);
function getHash(text, length = 8) {
  const h = (0, import_node_crypto.createHash)("sha256").update(text).digest("hex").substring(0, length);
  if (length <= 64) return h;
  return h.padEnd(length, "_");
}
var _dirname = import_node_path3.default.dirname((0, import_node_url2.fileURLToPath)(import.meta.url));
var requireResolveFromRootWithFallback = (root, id) => {
  const found2 = resolvePackageData(id, root) || resolvePackageData(id, _dirname);
  if (!found2) {
    const error2 = new Error(`${JSON.stringify(id)} not found.`);
    error2.code = "MODULE_NOT_FOUND";
    throw error2;
  }
  return _require$1.resolve(id, { paths: [root, _dirname] });
};
function emptyCssComments(raw) {
  return raw.replace(multilineCommentsRE, blankReplacer);
}
function backwardCompatibleWorkerPlugins(plugins2) {
  if (Array.isArray(plugins2)) {
    return plugins2;
  }
  if (typeof plugins2 === "function") {
    return plugins2();
  }
  return [];
}
function mergeConfigRecursively(defaults2, overrides, rootPath) {
  const merged = { ...defaults2 };
  for (const key in overrides) {
    const value2 = overrides[key];
    if (value2 == null) {
      continue;
    }
    const existing = merged[key];
    if (existing == null) {
      merged[key] = value2;
      continue;
    }
    if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
      merged[key] = mergeAlias(existing, value2);
      continue;
    } else if (key === "assetsInclude" && rootPath === "") {
      merged[key] = [].concat(existing, value2);
      continue;
    } else if (key === "noExternal" && rootPath === "ssr" && (existing === true || value2 === true)) {
      merged[key] = true;
      continue;
    } else if (key === "plugins" && rootPath === "worker") {
      merged[key] = () => [
        ...backwardCompatibleWorkerPlugins(existing),
        ...backwardCompatibleWorkerPlugins(value2)
      ];
      continue;
    }
    if (Array.isArray(existing) || Array.isArray(value2)) {
      merged[key] = [...arraify(existing), ...arraify(value2)];
      continue;
    }
    if (isObject$1(existing) && isObject$1(value2)) {
      merged[key] = mergeConfigRecursively(
        existing,
        value2,
        rootPath ? `${rootPath}.${key}` : key
      );
      continue;
    }
    merged[key] = value2;
  }
  return merged;
}
function mergeConfig(defaults2, overrides, isRoot = true) {
  if (typeof defaults2 === "function" || typeof overrides === "function") {
    throw new Error(`Cannot merge config in form of callback`);
  }
  return mergeConfigRecursively(defaults2, overrides, isRoot ? "" : ".");
}
function mergeAlias(a, b) {
  if (!a) return b;
  if (!b) return a;
  if (isObject$1(a) && isObject$1(b)) {
    return { ...a, ...b };
  }
  return [...normalizeAlias(b), ...normalizeAlias(a)];
}
function normalizeAlias(o2 = []) {
  return Array.isArray(o2) ? o2.map(normalizeSingleAlias) : Object.keys(o2).map(
    (find2) => normalizeSingleAlias({
      find: find2,
      replacement: o2[find2]
    })
  );
}
function normalizeSingleAlias({
  find: find2,
  replacement,
  customResolver
}) {
  if (typeof find2 === "string" && find2[find2.length - 1] === "/" && replacement[replacement.length - 1] === "/") {
    find2 = find2.slice(0, find2.length - 1);
    replacement = replacement.slice(0, replacement.length - 1);
  }
  const alias2 = {
    find: find2,
    replacement
  };
  if (customResolver) {
    alias2.customResolver = customResolver;
  }
  return alias2;
}
function transformStableResult(s, id, config2) {
  return {
    code: s.toString(),
    map: config2.command === "build" && config2.build.sourcemap ? s.generateMap({ hires: "boundary", source: id }) : null
  };
}
async function asyncFlatten(arr) {
  do {
    arr = (await Promise.all(arr)).flat(Infinity);
  } while (arr.some((v) => v == null ? void 0 : v.then));
  return arr;
}
function stripBomTag(content) {
  if (content.charCodeAt(0) === 65279) {
    return content.slice(1);
  }
  return content;
}
var windowsDrivePathPrefixRE = /^[A-Za-z]:[/\\]/;
var isNonDriveRelativeAbsolutePath = (p) => {
  if (!isWindows$3) return p[0] === "/";
  return windowsDrivePathPrefixRE.test(p);
};
function shouldServeFile(filePath, root) {
  if (!isCaseInsensitiveFS) return true;
  return hasCorrectCase(filePath, root);
}
function hasCorrectCase(file, assets) {
  if (file === assets) return true;
  const parent = import_node_path3.default.dirname(file);
  if (import_node_fs2.default.readdirSync(parent).includes(import_node_path3.default.basename(file))) {
    return hasCorrectCase(parent, assets);
  }
  return false;
}
function joinUrlSegments(a, b) {
  if (!a || !b) {
    return a || b || "";
  }
  if (a[a.length - 1] === "/") {
    a = a.substring(0, a.length - 1);
  }
  if (b[0] !== "/") {
    b = "/" + b;
  }
  return a + b;
}
function removeLeadingSlash(str) {
  return str[0] === "/" ? str.slice(1) : str;
}
function stripBase(path22, base) {
  if (path22 === base) {
    return "/";
  }
  const devBase = withTrailingSlash(base);
  return path22.startsWith(devBase) ? path22.slice(devBase.length - 1) : path22;
}
function arrayEqual(a, b) {
  if (a === b) return true;
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}
function evalValue(rawValue) {
  const fn = new Function(`
    var console, exports, global, module, process, require
    return (
${rawValue}
)
  `);
  return fn();
}
function getNpmPackageName(importPath) {
  const parts = importPath.split("/");
  if (parts[0][0] === "@") {
    if (!parts[1]) return null;
    return `${parts[0]}/${parts[1]}`;
  } else {
    return parts[0];
  }
}
var escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
  return str.replace(escapeRegexRE, "\\$&");
}
function getPackageManagerCommand(type = "install") {
  var _a4;
  const packageManager = ((_a4 = process.env.npm_config_user_agent) == null ? void 0 : _a4.split(" ")[0].split("/")[0]) || "npm";
  switch (type) {
    case "install":
      return packageManager === "npm" ? "npm install" : `${packageManager} add`;
    case "uninstall":
      return packageManager === "npm" ? "npm uninstall" : `${packageManager} remove`;
    case "update":
      return packageManager === "yarn" ? "yarn upgrade" : `${packageManager} update`;
    default:
      throw new TypeError(`Unknown command type: ${type}`);
  }
}
function isDevServer(server2) {
  return "pluginContainer" in server2;
}
function promiseWithResolvers() {
  let resolve3;
  let reject;
  const promise2 = new Promise((_resolve, _reject) => {
    resolve3 = _resolve;
    reject = _reject;
  });
  return { promise: promise2, resolve: resolve3, reject };
}
function createSerialPromiseQueue() {
  let previousTask;
  return {
    async run(f2) {
      const thisTask = f2();
      const depTasks = Promise.all([previousTask, thisTask]);
      previousTask = depTasks;
      const [, result] = await depTasks;
      if (previousTask === depTasks) {
        previousTask = void 0;
      }
      return result;
    }
  };
}
function sortObjectKeys(obj) {
  const sorted = {};
  for (const key of Object.keys(obj).sort()) {
    sorted[key] = obj[key];
  }
  return sorted;
}
function displayTime(time) {
  if (time < 1e3) {
    return `${time}ms`;
  }
  time = time / 1e3;
  if (time < 60) {
    return `${time.toFixed(2)}s`;
  }
  const mins = parseInt((time / 60).toString());
  const seconds = time % 60;
  return `${mins}m${seconds < 1 ? "" : ` ${seconds.toFixed(0)}s`}`;
}
function encodeURIPath(uri) {
  if (uri.startsWith("data:")) return uri;
  const filePath = cleanUrl(uri);
  const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  return encodeURI(filePath) + postfix;
}
function partialEncodeURIPath(uri) {
  if (uri.startsWith("data:")) return uri;
  const filePath = cleanUrl(uri);
  const postfix = filePath !== uri ? uri.slice(filePath.length) : "";
  return filePath.replaceAll("%", "%25") + postfix;
}
var setupSIGTERMListener = (callback) => {
  process.once("SIGTERM", callback);
  if (process.env.CI !== "true") {
    process.stdin.on("end", callback);
  }
};
var teardownSIGTERMListener = (callback) => {
  process.off("SIGTERM", callback);
  if (process.env.CI !== "true") {
    process.stdin.off("end", callback);
  }
};
var LogLevels = {
  silent: 0,
  error: 1,
  warn: 2,
  info: 3
};
var lastType;
var lastMsg;
var sameCount = 0;
function clearScreen() {
  const repeatCount = process.stdout.rows - 2;
  const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
  console.log(blank);
  import_node_readline.default.cursorTo(process.stdout, 0, 0);
  import_node_readline.default.clearScreenDown(process.stdout);
}
var timeFormatter;
function getTimeFormatter() {
  timeFormatter ?? (timeFormatter = new Intl.DateTimeFormat(void 0, {
    hour: "numeric",
    minute: "numeric",
    second: "numeric"
  }));
  return timeFormatter;
}
function createLogger(level = "info", options2 = {}) {
  if (options2.customLogger) {
    return options2.customLogger;
  }
  const loggedErrors = /* @__PURE__ */ new WeakSet();
  const { prefix = "[vite]", allowClearScreen = true } = options2;
  const thresh = LogLevels[level];
  const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
  const clear = canClearScreen ? clearScreen : () => {
  };
  function format2(type, msg, options22 = {}) {
    if (options22.timestamp) {
      let tag = "";
      if (type === "info") {
        tag = colors$1.cyan(colors$1.bold(prefix));
      } else if (type === "warn") {
        tag = colors$1.yellow(colors$1.bold(prefix));
      } else {
        tag = colors$1.red(colors$1.bold(prefix));
      }
      return `${colors$1.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${msg}`;
    } else {
      return msg;
    }
  }
  function output(type, msg, options22 = {}) {
    if (thresh >= LogLevels[type]) {
      const method = type === "info" ? "log" : type;
      if (options22.error) {
        loggedErrors.add(options22.error);
      }
      if (canClearScreen) {
        if (type === lastType && msg === lastMsg) {
          sameCount++;
          clear();
          console[method](
            format2(type, msg, options22),
            colors$1.yellow(`(x${sameCount + 1})`)
          );
        } else {
          sameCount = 0;
          lastMsg = msg;
          lastType = type;
          if (options22.clear) {
            clear();
          }
          console[method](format2(type, msg, options22));
        }
      } else {
        console[method](format2(type, msg, options22));
      }
    }
  }
  const warnedMessages = /* @__PURE__ */ new Set();
  const logger = {
    hasWarned: false,
    info(msg, opts) {
      output("info", msg, opts);
    },
    warn(msg, opts) {
      logger.hasWarned = true;
      output("warn", msg, opts);
    },
    warnOnce(msg, opts) {
      if (warnedMessages.has(msg)) return;
      logger.hasWarned = true;
      output("warn", msg, opts);
      warnedMessages.add(msg);
    },
    error(msg, opts) {
      logger.hasWarned = true;
      output("error", msg, opts);
    },
    clearScreen(type) {
      if (thresh >= LogLevels[type]) {
        clear();
      }
    },
    hasErrorLogged(error2) {
      return loggedErrors.has(error2);
    }
  };
  return logger;
}
function printServerUrls(urls, optionsHost, info) {
  const colorUrl = (url2) => colors$1.cyan(url2.replace(/:(\d+)\//, (_, port) => `:${colors$1.bold(port)}/`));
  for (const url2 of urls.local) {
    info(`  ${colors$1.green("➜")}  ${colors$1.bold("Local")}:   ${colorUrl(url2)}`);
  }
  for (const url2 of urls.network) {
    info(`  ${colors$1.green("➜")}  ${colors$1.bold("Network")}: ${colorUrl(url2)}`);
  }
  if (urls.network.length === 0 && optionsHost === void 0) {
    info(
      colors$1.dim(`  ${colors$1.green("➜")}  ${colors$1.bold("Network")}: use `) + colors$1.bold("--host") + colors$1.dim(" to expose")
    );
  }
}
var groups = [
  { name: "Assets", color: colors$1.green },
  { name: "CSS", color: colors$1.magenta },
  { name: "JS", color: colors$1.cyan }
];
var COMPRESSIBLE_ASSETS_RE = /\.(?:html|json|svg|txt|xml|xhtml)$/;
function buildReporterPlugin(config2) {
  const compress = (0, import_node_util.promisify)(import_node_zlib.gzip);
  const chunkLimit = config2.build.chunkSizeWarningLimit;
  const numberFormatter = new Intl.NumberFormat("en", {
    maximumFractionDigits: 2,
    minimumFractionDigits: 2
  });
  const displaySize = (bytes) => {
    return `${numberFormatter.format(bytes / 1e3)} kB`;
  };
  const tty = process.stdout.isTTY && !process.env.CI;
  const shouldLogInfo = LogLevels[config2.logLevel || "info"] >= LogLevels.info;
  let hasTransformed = false;
  let hasRenderedChunk = false;
  let hasCompressChunk = false;
  let transformedCount = 0;
  let chunkCount = 0;
  let compressedCount = 0;
  async function getCompressedSize(code) {
    if (config2.build.ssr || !config2.build.reportCompressedSize) {
      return null;
    }
    if (shouldLogInfo && !hasCompressChunk) {
      if (!tty) {
        config2.logger.info("computing gzip size...");
      } else {
        writeLine("computing gzip size (0)...");
      }
      hasCompressChunk = true;
    }
    const compressed = await compress(
      typeof code === "string" ? code : Buffer.from(code)
    );
    compressedCount++;
    if (shouldLogInfo && tty) {
      writeLine(`computing gzip size (${compressedCount})...`);
    }
    return compressed.length;
  }
  const logTransform = throttle((id) => {
    writeLine(
      `transforming (${transformedCount}) ${colors$1.dim(
        import_node_path3.default.relative(config2.root, id)
      )}`
    );
  });
  return {
    name: "vite:reporter",
    transform(_, id) {
      transformedCount++;
      if (shouldLogInfo) {
        if (!tty) {
          if (!hasTransformed) {
            config2.logger.info(`transforming...`);
          }
        } else {
          if (id.includes(`?`)) return;
          logTransform(id);
        }
        hasTransformed = true;
      }
      return null;
    },
    buildStart() {
      transformedCount = 0;
    },
    buildEnd() {
      if (shouldLogInfo) {
        if (tty) {
          clearLine$1();
        }
        config2.logger.info(
          `${colors$1.green(`✓`)} ${transformedCount} modules transformed.`
        );
      }
    },
    renderStart() {
      chunkCount = 0;
      compressedCount = 0;
    },
    renderChunk(code, chunk, options2) {
      if (!options2.inlineDynamicImports) {
        for (const id of chunk.moduleIds) {
          const module = this.getModuleInfo(id);
          if (!module) continue;
          if (module.importers.length && module.dynamicImporters.length) {
            const detectedIneffectiveDynamicImport = module.dynamicImporters.some(
              (id2) => !isInNodeModules$1(id2) && chunk.moduleIds.includes(id2)
            );
            if (detectedIneffectiveDynamicImport) {
              this.warn(
                `
(!) ${module.id} is dynamically imported by ${module.dynamicImporters.join(
                  ", "
                )} but also statically imported by ${module.importers.join(
                  ", "
                )}, dynamic import will not move module into another chunk.
`
              );
            }
          }
        }
      }
      chunkCount++;
      if (shouldLogInfo) {
        if (!tty) {
          if (!hasRenderedChunk) {
            config2.logger.info("rendering chunks...");
          }
        } else {
          writeLine(`rendering chunks (${chunkCount})...`);
        }
        hasRenderedChunk = true;
      }
      return null;
    },
    generateBundle() {
      if (shouldLogInfo && tty) clearLine$1();
    },
    async writeBundle({ dir: outDir }, output) {
      let hasLargeChunks = false;
      if (shouldLogInfo) {
        const entries = (await Promise.all(
          Object.values(output).map(
            async (chunk) => {
              if (chunk.type === "chunk") {
                return {
                  name: chunk.fileName,
                  group: "JS",
                  size: chunk.code.length,
                  compressedSize: await getCompressedSize(chunk.code),
                  mapSize: chunk.map ? chunk.map.toString().length : null
                };
              } else {
                if (chunk.fileName.endsWith(".map")) return null;
                const isCSS = chunk.fileName.endsWith(".css");
                const isCompressible = isCSS || COMPRESSIBLE_ASSETS_RE.test(chunk.fileName);
                return {
                  name: chunk.fileName,
                  group: isCSS ? "CSS" : "Assets",
                  size: chunk.source.length,
                  mapSize: null,
                  // Rollup doesn't support CSS maps?
                  compressedSize: isCompressible ? await getCompressedSize(chunk.source) : null
                };
              }
            }
          )
        )).filter(isDefined);
        if (tty) clearLine$1();
        let longest = 0;
        let biggestSize = 0;
        let biggestMap = 0;
        let biggestCompressSize = 0;
        for (const entry2 of entries) {
          if (entry2.name.length > longest) longest = entry2.name.length;
          if (entry2.size > biggestSize) biggestSize = entry2.size;
          if (entry2.mapSize && entry2.mapSize > biggestMap) {
            biggestMap = entry2.mapSize;
          }
          if (entry2.compressedSize && entry2.compressedSize > biggestCompressSize) {
            biggestCompressSize = entry2.compressedSize;
          }
        }
        const sizePad = displaySize(biggestSize).length;
        const mapPad = displaySize(biggestMap).length;
        const compressPad = displaySize(biggestCompressSize).length;
        const relativeOutDir = normalizePath$3(
          import_node_path3.default.relative(
            config2.root,
            import_node_path3.default.resolve(config2.root, outDir ?? config2.build.outDir)
          )
        );
        const assetsDir = import_node_path3.default.join(config2.build.assetsDir, "/");
        for (const group of groups) {
          const filtered = entries.filter((e2) => e2.group === group.name);
          if (!filtered.length) continue;
          for (const entry2 of filtered.sort((a, z) => a.size - z.size)) {
            const isLarge = group.name === "JS" && entry2.size / 1e3 > chunkLimit;
            if (isLarge) hasLargeChunks = true;
            const sizeColor = isLarge ? colors$1.yellow : colors$1.dim;
            let log = colors$1.dim(withTrailingSlash(relativeOutDir));
            log += !config2.build.lib && entry2.name.startsWith(withTrailingSlash(assetsDir)) ? colors$1.dim(assetsDir) + group.color(
              entry2.name.slice(assetsDir.length).padEnd(longest + 2 - assetsDir.length)
            ) : group.color(entry2.name.padEnd(longest + 2));
            log += colors$1.bold(
              sizeColor(displaySize(entry2.size).padStart(sizePad))
            );
            if (entry2.compressedSize) {
              log += colors$1.dim(
                ` │ gzip: ${displaySize(entry2.compressedSize).padStart(
                  compressPad
                )}`
              );
            }
            if (entry2.mapSize) {
              log += colors$1.dim(
                ` │ map: ${displaySize(entry2.mapSize).padStart(mapPad)}`
              );
            }
            config2.logger.info(log);
          }
        }
      } else {
        hasLargeChunks = Object.values(output).some((chunk) => {
          return chunk.type === "chunk" && chunk.code.length / 1e3 > chunkLimit;
        });
      }
      if (hasLargeChunks && config2.build.minify && !config2.build.lib && !config2.build.ssr) {
        config2.logger.warn(
          colors$1.yellow(
            `
(!) Some chunks are larger than ${chunkLimit} kB after minification. Consider:
- Using dynamic import() to code-split the application
- Use build.rollupOptions.output.manualChunks to improve chunking: https://rollupjs.org/configuration-options/#output-manualchunks
- Adjust chunk size limit for this warning via build.chunkSizeWarningLimit.`
          )
        );
      }
    }
  };
}
function writeLine(output) {
  clearLine$1();
  if (output.length < process.stdout.columns) {
    process.stdout.write(output);
  } else {
    process.stdout.write(output.substring(0, process.stdout.columns - 1));
  }
}
function clearLine$1() {
  process.stdout.clearLine(0);
  process.stdout.cursorTo(0);
}
function throttle(fn) {
  let timerHandle = null;
  return (...args) => {
    if (timerHandle) return;
    fn(...args);
    timerHandle = setTimeout(() => {
      timerHandle = null;
    }, 100);
  };
}
var POSIX_SEP_RE = new RegExp("\\" + import_node_path3.default.posix.sep, "g");
var NATIVE_SEP_RE = new RegExp("\\" + import_node_path3.default.sep, "g");
var PATTERN_REGEX_CACHE = /* @__PURE__ */ new Map();
var GLOB_ALL_PATTERN = `**/*`;
var TS_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
var JS_EXTENSIONS = [".js", ".jsx", ".mjs", ".cjs"];
var TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS);
var TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext2) => ext2.substring(1)).join("|")})`;
var TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext2) => ext2.substring(1)).join(
  "|"
)})`;
var IS_POSIX = import_node_path3.default.posix.sep === import_node_path3.default.sep;
function makePromise() {
  let resolve3, reject;
  const promise2 = new Promise((res, rej) => {
    resolve3 = res;
    reject = rej;
  });
  return { promise: promise2, resolve: resolve3, reject };
}
async function resolveTSConfigJson(filename, cache) {
  if (import_node_path3.default.extname(filename) !== ".json") {
    return;
  }
  const tsconfig = import_node_path3.default.resolve(filename);
  if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) {
    return tsconfig;
  }
  return import_node_fs2.promises.stat(tsconfig).then((stat2) => {
    if (stat2.isFile() || stat2.isFIFO()) {
      return tsconfig;
    } else {
      throw new Error(`${filename} exists but is not a regular file.`);
    }
  });
}
var isInNodeModules = IS_POSIX ? (dir) => dir.includes("/node_modules/") : (dir) => dir.match(/[/\\]node_modules[/\\]/);
var posix2native = IS_POSIX ? (filename) => filename : (filename) => filename.replace(POSIX_SEP_RE, import_node_path3.default.sep);
var native2posix = IS_POSIX ? (filename) => filename : (filename) => filename.replace(NATIVE_SEP_RE, import_node_path3.default.posix.sep);
var resolve2posix = IS_POSIX ? (dir, filename) => dir ? import_node_path3.default.resolve(dir, filename) : import_node_path3.default.resolve(filename) : (dir, filename) => native2posix(
  dir ? import_node_path3.default.resolve(posix2native(dir), posix2native(filename)) : import_node_path3.default.resolve(posix2native(filename))
);
function resolveReferencedTSConfigFiles(result, options2) {
  const dir = import_node_path3.default.dirname(result.tsconfigFile);
  return result.tsconfig.references.map((ref) => {
    const refPath = ref.path.endsWith(".json") ? ref.path : import_node_path3.default.join(ref.path, (options2 == null ? void 0 : options2.configName) ?? "tsconfig.json");
    return resolve2posix(dir, refPath);
  });
}
function resolveSolutionTSConfig(filename, result) {
  var _a4;
  const allowJs = (_a4 = result.tsconfig.compilerOptions) == null ? void 0 : _a4.allowJs;
  const extensions2 = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
  if (result.referenced && extensions2.some((ext2) => filename.endsWith(ext2)) && !isIncluded(filename, result)) {
    const solutionTSConfig = result.referenced.find(
      (referenced) => isIncluded(filename, referenced)
    );
    if (solutionTSConfig) {
      return solutionTSConfig;
    }
  }
  return result;
}
function isIncluded(filename, result) {
  var _a4;
  const dir = native2posix(import_node_path3.default.dirname(result.tsconfigFile));
  const files = (result.tsconfig.files || []).map((file) => resolve2posix(dir, file));
  const absoluteFilename = resolve2posix(null, filename);
  if (files.includes(filename)) {
    return true;
  }
  const allowJs = (_a4 = result.tsconfig.compilerOptions) == null ? void 0 : _a4.allowJs;
  const isIncluded2 = isGlobMatch(
    absoluteFilename,
    dir,
    result.tsconfig.include || (result.tsconfig.files ? [] : [GLOB_ALL_PATTERN]),
    allowJs
  );
  if (isIncluded2) {
    const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
    return !isExcluded;
  }
  return false;
}
function isGlobMatch(filename, dir, patterns, allowJs) {
  const extensions2 = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
  return patterns.some((pattern2) => {
    let lastWildcardIndex = pattern2.length;
    let hasWildcard = false;
    for (let i = pattern2.length - 1; i > -1; i--) {
      if (pattern2[i] === "*" || pattern2[i] === "?") {
        lastWildcardIndex = i;
        hasWildcard = true;
        break;
      }
    }
    if (lastWildcardIndex < pattern2.length - 1 && !filename.endsWith(pattern2.slice(lastWildcardIndex + 1))) {
      return false;
    }
    if (pattern2.endsWith("*") && !extensions2.some((ext2) => filename.endsWith(ext2))) {
      return false;
    }
    if (pattern2 === GLOB_ALL_PATTERN) {
      return filename.startsWith(`${dir}/`);
    }
    const resolvedPattern = resolve2posix(dir, pattern2);
    let firstWildcardIndex = -1;
    for (let i = 0; i < resolvedPattern.length; i++) {
      if (resolvedPattern[i] === "*" || resolvedPattern[i] === "?") {
        firstWildcardIndex = i;
        hasWildcard = true;
        break;
      }
    }
    if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) {
      return false;
    }
    if (!hasWildcard) {
      return filename === resolvedPattern;
    }
    if (PATTERN_REGEX_CACHE.has(resolvedPattern)) {
      return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
    }
    const regex2 = pattern2regex(resolvedPattern, allowJs);
    PATTERN_REGEX_CACHE.set(resolvedPattern, regex2);
    return regex2.test(filename);
  });
}
function pattern2regex(resolvedPattern, allowJs) {
  let regexStr = "^";
  for (let i = 0; i < resolvedPattern.length; i++) {
    const char = resolvedPattern[i];
    if (char === "?") {
      regexStr += "[^\\/]";
      continue;
    }
    if (char === "*") {
      if (resolvedPattern[i + 1] === "*" && resolvedPattern[i + 2] === "/") {
        i += 2;
        regexStr += "(?:[^\\/]*\\/)*";
        continue;
      }
      regexStr += "[^\\/]*";
      continue;
    }
    if ("/.+^${}()|[]\\".includes(char)) {
      regexStr += `\\`;
    }
    regexStr += char;
  }
  if (resolvedPattern.endsWith("*")) {
    regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
  }
  regexStr += "$";
  return new RegExp(regexStr);
}
function replaceTokens(tsconfig, configDir) {
  return JSON.parse(
    JSON.stringify(tsconfig).replaceAll(/"(?:\.\.\/)*\${configDir}/g, `"${native2posix(configDir)}`)
  );
}
async function find(filename, options2) {
  let dir = import_node_path3.default.dirname(import_node_path3.default.resolve(filename));
  if ((options2 == null ? void 0 : options2.ignoreNodeModules) && isInNodeModules(dir)) {
    return null;
  }
  const cache = options2 == null ? void 0 : options2.cache;
  const configName = (options2 == null ? void 0 : options2.configName) ?? "tsconfig.json";
  if (cache == null ? void 0 : cache.hasConfigPath(dir, configName)) {
    return cache.getConfigPath(dir, configName);
  }
  const {
    /** @type {Promise} */
    promise: promise2,
    resolve: resolve3,
    reject
  } = makePromise();
  if ((options2 == null ? void 0 : options2.root) && !import_node_path3.default.isAbsolute(options2.root)) {
    options2.root = import_node_path3.default.resolve(options2.root);
  }
  findUp(dir, { promise: promise2, resolve: resolve3, reject }, options2);
  return promise2;
}
function findUp(dir, { resolve: resolve3, reject, promise: promise2 }, options2) {
  const { cache, root, configName } = options2 ?? {};
  if (cache) {
    if (cache.hasConfigPath(dir, configName)) {
      let cached;
      try {
        cached = cache.getConfigPath(dir, configName);
      } catch (e2) {
        reject(e2);
        return;
      }
      if (cached == null ? void 0 : cached.then) {
        cached.then(resolve3).catch(reject);
      } else {
        resolve3(cached);
      }
    } else {
      cache.setConfigPath(dir, promise2, configName);
    }
  }
  const tsconfig = import_node_path3.default.join(dir, (options2 == null ? void 0 : options2.configName) ?? "tsconfig.json");
  import_node_fs2.default.stat(tsconfig, (err2, stats) => {
    if (stats && (stats.isFile() || stats.isFIFO())) {
      resolve3(tsconfig);
    } else if ((err2 == null ? void 0 : err2.code) !== "ENOENT") {
      reject(err2);
    } else {
      let parent;
      if (root === dir || (parent = import_node_path3.default.dirname(dir)) === dir) {
        resolve3(null);
      } else {
        findUp(parent, { promise: promise2, resolve: resolve3, reject }, options2);
      }
    }
  });
}
function toJson(tsconfigJson) {
  const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
  if (stripped.trim() === "") {
    return "{}";
  } else {
    return stripped;
  }
}
function stripDanglingComma(pseudoJson) {
  let insideString = false;
  let offset2 = 0;
  let result = "";
  let danglingCommaPos = null;
  for (let i = 0; i < pseudoJson.length; i++) {
    const currentCharacter = pseudoJson[i];
    if (currentCharacter === '"') {
      const escaped2 = isEscaped(pseudoJson, i);
      if (!escaped2) {
        insideString = !insideString;
      }
    }
    if (insideString) {
      danglingCommaPos = null;
      continue;
    }
    if (currentCharacter === ",") {
      danglingCommaPos = i;
      continue;
    }
    if (danglingCommaPos) {
      if (currentCharacter === "}" || currentCharacter === "]") {
        result += pseudoJson.slice(offset2, danglingCommaPos) + " ";
        offset2 = danglingCommaPos + 1;
        danglingCommaPos = null;
      } else if (!currentCharacter.match(/\s/)) {
        danglingCommaPos = null;
      }
    }
  }
  return result + pseudoJson.substring(offset2);
}
function isEscaped(jsonString, quotePosition) {
  let index = quotePosition - 1;
  let backslashCount = 0;
  while (jsonString[index] === "\\") {
    index -= 1;
    backslashCount += 1;
  }
  return Boolean(backslashCount % 2);
}
function strip(string2, start, end) {
  return string2.slice(start, end).replace(/\S/g, " ");
}
var singleComment = Symbol("singleComment");
var multiComment = Symbol("multiComment");
function stripJsonComments(jsonString) {
  let isInsideString = false;
  let isInsideComment = false;
  let offset2 = 0;
  let result = "";
  for (let index = 0; index < jsonString.length; index++) {
    const currentCharacter = jsonString[index];
    const nextCharacter = jsonString[index + 1];
    if (!isInsideComment && currentCharacter === '"') {
      const escaped2 = isEscaped(jsonString, index);
      if (!escaped2) {
        isInsideString = !isInsideString;
      }
    }
    if (isInsideString) {
      continue;
    }
    if (!isInsideComment && currentCharacter + nextCharacter === "//") {
      result += jsonString.slice(offset2, index);
      offset2 = index;
      isInsideComment = singleComment;
      index++;
    } else if (isInsideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
      index++;
      isInsideComment = false;
      result += strip(jsonString, offset2, index);
      offset2 = index;
    } else if (isInsideComment === singleComment && currentCharacter === "\n") {
      isInsideComment = false;
      result += strip(jsonString, offset2, index);
      offset2 = index;
    } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") {
      result += jsonString.slice(offset2, index);
      offset2 = index;
      isInsideComment = multiComment;
      index++;
    } else if (isInsideComment === multiComment && currentCharacter + nextCharacter === "*/") {
      index++;
      isInsideComment = false;
      result += strip(jsonString, offset2, index + 1);
      offset2 = index + 1;
    }
  }
  return result + (isInsideComment ? strip(jsonString.slice(offset2)) : jsonString.slice(offset2));
}
function stripBom(string2) {
  if (string2.charCodeAt(0) === 65279) {
    return string2.slice(1);
  }
  return string2;
}
var not_found_result = {
  tsconfigFile: null,
  tsconfig: {}
};
async function parse$e(filename, options2) {
  const cache = options2 == null ? void 0 : options2.cache;
  if (cache == null ? void 0 : cache.hasParseResult(filename)) {
    return getParsedDeep(filename, cache, options2);
  }
  const {
    resolve: resolve3,
    reject,
    /** @type {Promise}*/
    promise: promise2
  } = makePromise();
  cache == null ? void 0 : cache.setParseResult(filename, promise2, true);
  try {
    let tsconfigFile = await resolveTSConfigJson(filename, cache) || await find(filename, options2);
    if (!tsconfigFile) {
      resolve3(not_found_result);
      return promise2;
    }
    let result;
    if (filename !== tsconfigFile && (cache == null ? void 0 : cache.hasParseResult(tsconfigFile))) {
      result = await getParsedDeep(tsconfigFile, cache, options2);
    } else {
      result = await parseFile$1(tsconfigFile, cache, filename === tsconfigFile);
      await Promise.all([parseExtends(result, cache), parseReferences(result, options2)]);
    }
    result.tsconfig = replaceTokens(result.tsconfig, import_node_path3.default.dirname(tsconfigFile));
    resolve3(resolveSolutionTSConfig(filename, result));
  } catch (e2) {
    reject(e2);
  }
  return promise2;
}
async function getParsedDeep(filename, cache, options2) {
  const result = await cache.getParseResult(filename);
  if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
    const promise2 = Promise.all([
      parseExtends(result, cache),
      parseReferences(result, options2)
    ]).then(() => result);
    cache.setParseResult(filename, promise2, true);
    return promise2;
  }
  return result;
}
async function parseFile$1(tsconfigFile, cache, skipCache) {
  if (!skipCache && (cache == null ? void 0 : cache.hasParseResult(tsconfigFile)) && !cache.getParseResult(tsconfigFile)._isRootFile_) {
    return cache.getParseResult(tsconfigFile);
  }
  const promise2 = import_node_fs2.promises.readFile(tsconfigFile, "utf-8").then(toJson).then((json) => {
    const parsed = JSON.parse(json);
    applyDefaults(parsed, tsconfigFile);
    return {
      tsconfigFile,
      tsconfig: normalizeTSConfig(parsed, import_node_path3.default.dirname(tsconfigFile))
    };
  }).catch((e2) => {
    throw new TSConfckParseError(
      `parsing ${tsconfigFile} failed: ${e2}`,
      "PARSE_FILE",
      tsconfigFile,
      e2
    );
  });
  if (!skipCache && (!(cache == null ? void 0 : cache.hasParseResult(tsconfigFile)) || !cache.getParseResult(tsconfigFile)._isRootFile_)) {
    cache == null ? void 0 : cache.setParseResult(tsconfigFile, promise2);
  }
  return promise2;
}
function normalizeTSConfig(tsconfig, dir) {
  var _a4;
  const baseUrl = (_a4 = tsconfig.compilerOptions) == null ? void 0 : _a4.baseUrl;
  if (baseUrl && !baseUrl.startsWith("${") && !import_node_path3.default.isAbsolute(baseUrl)) {
    tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
  }
  return tsconfig;
}
async function parseReferences(result, options2) {
  if (!result.tsconfig.references) {
    return;
  }
  const referencedFiles = resolveReferencedTSConfigFiles(result, options2);
  const referenced = await Promise.all(
    referencedFiles.map((file) => parseFile$1(file, options2 == null ? void 0 : options2.cache))
  );
  await Promise.all(referenced.map((ref) => parseExtends(ref, options2 == null ? void 0 : options2.cache)));
  referenced.forEach((ref) => {
    ref.solution = result;
  });
  result.referenced = referenced;
}
async function parseExtends(result, cache) {
  if (!result.tsconfig.extends) {
    return;
  }
  const extended = [
    { tsconfigFile: result.tsconfigFile, tsconfig: JSON.parse(JSON.stringify(result.tsconfig)) }
  ];
  let pos = 0;
  const extendsPath = [];
  let currentBranchDepth = 0;
  while (pos < extended.length) {
    const extending = extended[pos];
    extendsPath.push(extending.tsconfigFile);
    if (extending.tsconfig.extends) {
      currentBranchDepth += 1;
      let resolvedExtends;
      if (!Array.isArray(extending.tsconfig.extends)) {
        resolvedExtends = [resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)];
      } else {
        resolvedExtends = extending.tsconfig.extends.reverse().map((ex) => resolveExtends(ex, extending.tsconfigFile));
      }
      const circularExtends = resolvedExtends.find(
        (tsconfigFile) => extendsPath.includes(tsconfigFile)
      );
      if (circularExtends) {
        const circle = extendsPath.concat([circularExtends]).join(" -> ");
        throw new TSConfckParseError(
          `Circular dependency in "extends": ${circle}`,
          "EXTENDS_CIRCULAR",
          result.tsconfigFile
        );
      }
      extended.splice(
        pos + 1,
        0,
        ...await Promise.all(resolvedExtends.map((file) => parseFile$1(file, cache)))
      );
    } else {
      extendsPath.splice(-currentBranchDepth);
      currentBranchDepth = 0;
    }
    pos = pos + 1;
  }
  result.extended = extended;
  for (const ext2 of result.extended.slice(1)) {
    extendTSConfig(result, ext2);
  }
}
function resolveExtends(extended, from) {
  if (extended === "..") {
    extended = "../tsconfig.json";
  }
  const req2 = (0, import_module.createRequire)(from);
  let error2;
  try {
    return req2.resolve(extended);
  } catch (e2) {
    error2 = e2;
  }
  if (extended[0] !== "." && !import_node_path3.default.isAbsolute(extended)) {
    try {
      return req2.resolve(`${extended}/tsconfig.json`);
    } catch (e2) {
      error2 = e2;
    }
  }
  throw new TSConfckParseError(
    `failed to resolve "extends":"${extended}" in ${from}`,
    "EXTENDS_RESOLVE",
    from,
    error2
  );
}
var EXTENDABLE_KEYS = [
  "compilerOptions",
  "files",
  "include",
  "exclude",
  "watchOptions",
  "compileOnSave",
  "typeAcquisition",
  "buildOptions"
];
function extendTSConfig(extending, extended) {
  const extendingConfig = extending.tsconfig;
  const extendedConfig = extended.tsconfig;
  const relativePath = native2posix(
    import_node_path3.default.relative(import_node_path3.default.dirname(extending.tsconfigFile), import_node_path3.default.dirname(extended.tsconfigFile))
  );
  for (const key of Object.keys(extendedConfig).filter((key2) => EXTENDABLE_KEYS.includes(key2))) {
    if (key === "compilerOptions") {
      if (!extendingConfig.compilerOptions) {
        extendingConfig.compilerOptions = {};
      }
      for (const option of Object.keys(extendedConfig.compilerOptions)) {
        if (Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) {
          continue;
        }
        extendingConfig.compilerOptions[option] = rebaseRelative(
          option,
          extendedConfig.compilerOptions[option],
          relativePath
        );
      }
    } else if (extendingConfig[key] === void 0) {
      if (key === "watchOptions") {
        extendingConfig.watchOptions = {};
        for (const option of Object.keys(extendedConfig.watchOptions)) {
          extendingConfig.watchOptions[option] = rebaseRelative(
            option,
            extendedConfig.watchOptions[option],
            relativePath
          );
        }
      } else {
        extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
      }
    }
  }
}
var REBASE_KEYS = [
  // root
  "files",
  "include",
  "exclude",
  // compilerOptions
  "baseUrl",
  "rootDir",
  "rootDirs",
  "typeRoots",
  "outDir",
  "outFile",
  "declarationDir",
  // watchOptions
  "excludeDirectories",
  "excludeFiles"
];
function rebaseRelative(key, value2, prependPath) {
  if (!REBASE_KEYS.includes(key)) {
    return value2;
  }
  if (Array.isArray(value2)) {
    return value2.map((x) => rebasePath(x, prependPath));
  } else {
    return rebasePath(value2, prependPath);
  }
}
function rebasePath(value2, prependPath) {
  if (import_node_path3.default.isAbsolute(value2)) {
    return value2;
  } else {
    return import_node_path3.default.posix.normalize(import_node_path3.default.posix.join(prependPath, value2));
  }
}
var TSConfckParseError = class _TSConfckParseError extends Error {
  /**
   *
   * @param {string} message - error message
   * @param {string} code - error code
   * @param {string} tsconfigFile - path to tsconfig file
   * @param {Error?} cause - cause of this error
   */
  constructor(message, code, tsconfigFile, cause) {
    super(message);
    /**
     * error code
     * @type {string}
     */
    __publicField(this, "code");
    /**
     * error cause
     * @type { Error | undefined}
     */
    __publicField(this, "cause");
    /**
     * absolute path of tsconfig file where the error happened
     * @type {string}
     */
    __publicField(this, "tsconfigFile");
    Object.setPrototypeOf(this, _TSConfckParseError.prototype);
    this.name = _TSConfckParseError.name;
    this.code = code;
    this.cause = cause;
    this.tsconfigFile = tsconfigFile;
  }
};
function applyDefaults(tsconfig, tsconfigFile) {
  if (isJSConfig(tsconfigFile)) {
    tsconfig.compilerOptions = {
      ...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
      ...tsconfig.compilerOptions
    };
  }
}
var DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
  allowJs: true,
  maxNodeModuleJsDepth: 2,
  allowSyntheticDefaultImports: true,
  skipLibCheck: true,
  noEmit: true
};
function isJSConfig(configFileName) {
  return import_node_path3.default.basename(configFileName) === "jsconfig.json";
}
var _configPaths, _parsed;
var TSConfckCache = class {
  constructor() {
    /**
     * map directories to their closest tsconfig.json
     * @internal
     * @private
     * @type{Map|string|null)>}
     */
    __privateAdd(this, _configPaths, /* @__PURE__ */ new Map());
    /**
     * map files to their parsed tsconfig result
     * @internal
     * @private
     * @type {Map|T)> }
     */
    __privateAdd(this, _parsed, /* @__PURE__ */ new Map());
  }
  /**
   * clear cache, use this if you have a long running process and tsconfig files have been added,changed or deleted
   */
  clear() {
    __privateGet(this, _configPaths).clear();
    __privateGet(this, _parsed).clear();
  }
  /**
   * has cached closest config for files in dir
   * @param {string} dir
   * @param {string} [configName=tsconfig.json]
   * @returns {boolean}
   */
  hasConfigPath(dir, configName = "tsconfig.json") {
    return __privateGet(this, _configPaths).has(`${dir}/${configName}`);
  }
  /**
   * get cached closest tsconfig for files in dir
   * @param {string} dir
   * @param {string} [configName=tsconfig.json]
   * @returns {Promise|string|null}
   * @throws {unknown} if cached value is an error
   */
  getConfigPath(dir, configName = "tsconfig.json") {
    const key = `${dir}/${configName}`;
    const value2 = __privateGet(this, _configPaths).get(key);
    if (value2 == null || value2.length || value2.then) {
      return value2;
    } else {
      throw value2;
    }
  }
  /**
   * has parsed tsconfig for file
   * @param {string} file
   * @returns {boolean}
   */
  hasParseResult(file) {
    return __privateGet(this, _parsed).has(file);
  }
  /**
   * get parsed tsconfig for file
   * @param {string} file
   * @returns {Promise|T}
   * @throws {unknown} if cached value is an error
   */
  getParseResult(file) {
    const value2 = __privateGet(this, _parsed).get(file);
    if (value2.then || value2.tsconfig) {
      return value2;
    } else {
      throw value2;
    }
  }
  /**
   * @internal
   * @private
   * @param file
   * @param {boolean} isRootFile a flag to check if current file which involking the parse() api, used to distinguish the normal cache which only parsed by parseFile()
   * @param {Promise} result
   */
  setParseResult(file, result, isRootFile = false) {
    Object.defineProperty(result, "_isRootFile_", {
      value: isRootFile,
      writable: false,
      enumerable: false,
      configurable: false
    });
    __privateGet(this, _parsed).set(file, result);
    result.then((parsed) => {
      if (__privateGet(this, _parsed).get(file) === result) {
        __privateGet(this, _parsed).set(file, parsed);
      }
    }).catch((e2) => {
      if (__privateGet(this, _parsed).get(file) === result) {
        __privateGet(this, _parsed).set(file, e2);
      }
    });
  }
  /**
   * @internal
   * @private
   * @param {string} dir
   * @param {Promise} configPath
   * @param {string} [configName=tsconfig.json]
   */
  setConfigPath(dir, configPath, configName = "tsconfig.json") {
    const key = `${dir}/${configName}`;
    __privateGet(this, _configPaths).set(key, configPath);
    configPath.then((path3) => {
      if (__privateGet(this, _configPaths).get(key) === configPath) {
        __privateGet(this, _configPaths).set(key, path3);
      }
    }).catch((e2) => {
      if (__privateGet(this, _configPaths).get(key) === configPath) {
        __privateGet(this, _configPaths).set(key, e2);
      }
    });
  }
};
_configPaths = new WeakMap();
_parsed = new WeakMap();
var debug$h = createDebugger("vite:esbuild");
var IIFE_BEGIN_RE = /(const|var)\s+\S+\s*=\s*function\([^()]*\)\s*\{\s*"use strict";/;
var validExtensionRE = /\.\w+$/;
var jsxExtensionsRE = /\.(?:j|t)sx\b/;
var defaultEsbuildSupported = {
  "dynamic-import": true,
  "import-meta": true
};
var server;
async function transformWithEsbuild(code, filename, options2, inMap) {
  let loader = options2 == null ? void 0 : options2.loader;
  if (!loader) {
    const ext2 = import_node_path3.default.extname(validExtensionRE.test(filename) ? filename : cleanUrl(filename)).slice(1);
    if (ext2 === "cjs" || ext2 === "mjs") {
      loader = "js";
    } else if (ext2 === "cts" || ext2 === "mts") {
      loader = "ts";
    } else {
      loader = ext2;
    }
  }
  let tsconfigRaw = options2 == null ? void 0 : options2.tsconfigRaw;
  if (typeof tsconfigRaw !== "string") {
    const meaningfulFields = [
      "alwaysStrict",
      "experimentalDecorators",
      "importsNotUsedAsValues",
      "jsx",
      "jsxFactory",
      "jsxFragmentFactory",
      "jsxImportSource",
      "preserveValueImports",
      "target",
      "useDefineForClassFields",
      "verbatimModuleSyntax"
    ];
    const compilerOptionsForFile = {};
    if (loader === "ts" || loader === "tsx") {
      const loadedTsconfig = await loadTsconfigJsonForFile(filename);
      const loadedCompilerOptions = loadedTsconfig.compilerOptions ?? {};
      for (const field of meaningfulFields) {
        if (field in loadedCompilerOptions) {
          compilerOptionsForFile[field] = loadedCompilerOptions[field];
        }
      }
    }
    const compilerOptions = {
      ...compilerOptionsForFile,
      ...tsconfigRaw == null ? void 0 : tsconfigRaw.compilerOptions
    };
    if (compilerOptions.useDefineForClassFields === void 0 && compilerOptions.target === void 0) {
      compilerOptions.useDefineForClassFields = false;
    }
    if (options2) {
      options2.jsx && (compilerOptions.jsx = void 0);
      options2.jsxFactory && (compilerOptions.jsxFactory = void 0);
      options2.jsxFragment && (compilerOptions.jsxFragmentFactory = void 0);
      options2.jsxImportSource && (compilerOptions.jsxImportSource = void 0);
    }
    tsconfigRaw = {
      ...tsconfigRaw,
      compilerOptions
    };
  }
  const resolvedOptions = {
    sourcemap: true,
    // ensure source file name contains full query
    sourcefile: filename,
    ...options2,
    loader,
    tsconfigRaw
  };
  delete resolvedOptions.include;
  delete resolvedOptions.exclude;
  delete resolvedOptions.jsxInject;
  try {
    const result = await (0, import_esbuild.transform)(code, resolvedOptions);
    let map2;
    if (inMap && resolvedOptions.sourcemap) {
      const nextMap = JSON.parse(result.map);
      nextMap.sourcesContent = [];
      map2 = combineSourcemaps(filename, [
        nextMap,
        inMap
      ]);
    } else {
      map2 = resolvedOptions.sourcemap && resolvedOptions.sourcemap !== "inline" ? JSON.parse(result.map) : { mappings: "" };
    }
    return {
      ...result,
      map: map2
    };
  } catch (e2) {
    debug$h == null ? void 0 : debug$h(`esbuild error with options used: `, resolvedOptions);
    if (e2.errors) {
      e2.frame = "";
      e2.errors.forEach((m) => {
        if (m.text === "Experimental decorators are not currently enabled" || m.text === "Parameter decorators only work when experimental decorators are enabled") {
          m.text += '. Vite 5 now uses esbuild 0.18 and you need to enable them by adding "experimentalDecorators": true in your "tsconfig.json" file.';
        }
        e2.frame += `
` + prettifyMessage(m, code);
      });
      e2.loc = e2.errors[0].location;
    }
    throw e2;
  }
}
function esbuildPlugin(config2) {
  const options2 = config2.esbuild;
  const { jsxInject, include, exclude, ...esbuildTransformOptions } = options2;
  const filter2 = createFilter2(include || /\.(m?ts|[jt]sx)$/, exclude || /\.js$/);
  const transformOptions = {
    target: "esnext",
    charset: "utf8",
    ...esbuildTransformOptions,
    minify: false,
    minifyIdentifiers: false,
    minifySyntax: false,
    minifyWhitespace: false,
    treeShaking: false,
    // keepNames is not needed when minify is disabled.
    // Also transforming multiple times with keepNames enabled breaks
    // tree-shaking. (#9164)
    keepNames: false,
    supported: {
      ...defaultEsbuildSupported,
      ...esbuildTransformOptions.supported
    }
  };
  return {
    name: "vite:esbuild",
    configureServer(_server) {
      server = _server;
      server.watcher.on("add", reloadOnTsconfigChange).on("change", reloadOnTsconfigChange).on("unlink", reloadOnTsconfigChange);
    },
    buildEnd() {
      server = null;
    },
    async transform(code, id) {
      if (filter2(id) || filter2(cleanUrl(id))) {
        const result = await transformWithEsbuild(code, id, transformOptions);
        if (result.warnings.length) {
          result.warnings.forEach((m) => {
            this.warn(prettifyMessage(m, code));
          });
        }
        if (jsxInject && jsxExtensionsRE.test(id)) {
          result.code = jsxInject + ";" + result.code;
        }
        return {
          code: result.code,
          map: result.map
        };
      }
    }
  };
}
var rollupToEsbuildFormatMap = {
  es: "esm",
  cjs: "cjs",
  // passing `var Lib = (() => {})()` to esbuild with format = "iife"
  // will turn it to `(() => { var Lib = (() => {})() })()`,
  // so we remove the format config to tell esbuild not doing this
  //
  // although esbuild doesn't change format, there is still possibility
  // that `{ treeShaking: true }` removes a top-level no-side-effect variable
  // like: `var Lib = 1`, which becomes `` after esbuild transforming,
  // but thankfully rollup does not do this optimization now
  iife: void 0
};
var buildEsbuildPlugin = (config2) => {
  return {
    name: "vite:esbuild-transpile",
    async renderChunk(code, chunk, opts) {
      if (opts.__vite_skip_esbuild__) {
        return null;
      }
      const options2 = resolveEsbuildTranspileOptions(config2, opts.format);
      if (!options2) {
        return null;
      }
      const res = await transformWithEsbuild(code, chunk.fileName, options2);
      if (config2.build.lib) {
        const esbuildCode = res.code;
        const contentIndex = opts.format === "iife" ? Math.max(esbuildCode.search(IIFE_BEGIN_RE), 0) : opts.format === "umd" ? esbuildCode.indexOf(`(function(`) : 0;
        if (contentIndex > 0) {
          const esbuildHelpers = esbuildCode.slice(0, contentIndex);
          res.code = esbuildCode.slice(contentIndex).replace(`"use strict";`, `"use strict";` + esbuildHelpers);
        }
      }
      return res;
    }
  };
};
function resolveEsbuildTranspileOptions(config2, format2) {
  const target = config2.build.target;
  const minify = config2.build.minify === "esbuild";
  if ((!target || target === "esnext") && !minify) {
    return null;
  }
  const isEsLibBuild = config2.build.lib && format2 === "es";
  const esbuildOptions = config2.esbuild || {};
  const options2 = {
    charset: "utf8",
    ...esbuildOptions,
    loader: "js",
    target: target || void 0,
    format: rollupToEsbuildFormatMap[format2],
    supported: {
      ...defaultEsbuildSupported,
      ...esbuildOptions.supported
    }
  };
  if (!minify) {
    return {
      ...options2,
      minify: false,
      minifyIdentifiers: false,
      minifySyntax: false,
      minifyWhitespace: false,
      treeShaking: false
    };
  }
  if (options2.minifyIdentifiers != null || options2.minifySyntax != null || options2.minifyWhitespace != null) {
    if (isEsLibBuild) {
      return {
        ...options2,
        minify: false,
        minifyIdentifiers: options2.minifyIdentifiers ?? true,
        minifySyntax: options2.minifySyntax ?? true,
        minifyWhitespace: false,
        treeShaking: true
      };
    } else {
      return {
        ...options2,
        minify: false,
        minifyIdentifiers: options2.minifyIdentifiers ?? true,
        minifySyntax: options2.minifySyntax ?? true,
        minifyWhitespace: options2.minifyWhitespace ?? true,
        treeShaking: true
      };
    }
  }
  if (isEsLibBuild) {
    return {
      ...options2,
      minify: false,
      minifyIdentifiers: true,
      minifySyntax: true,
      minifyWhitespace: false,
      treeShaking: true
    };
  } else {
    return {
      ...options2,
      minify: true,
      treeShaking: true
    };
  }
}
function prettifyMessage(m, code) {
  let res = colors$1.yellow(m.text);
  if (m.location) {
    res += `
` + generateCodeFrame(code, m.location);
  }
  return res + `
`;
}
var tsconfckCache;
async function loadTsconfigJsonForFile(filename) {
  try {
    if (!tsconfckCache) {
      tsconfckCache = new TSConfckCache();
    }
    const result = await parse$e(filename, {
      cache: tsconfckCache,
      ignoreNodeModules: true
    });
    if (server && result.tsconfigFile) {
      ensureWatchedFile(server.watcher, result.tsconfigFile, server.config.root);
    }
    return result.tsconfig;
  } catch (e2) {
    if (e2 instanceof TSConfckParseError) {
      if (server && e2.tsconfigFile) {
        ensureWatchedFile(server.watcher, e2.tsconfigFile, server.config.root);
      }
    }
    throw e2;
  }
}
async function reloadOnTsconfigChange(changedFile) {
  if (!server) return;
  if (import_node_path3.default.basename(changedFile) === "tsconfig.json" || changedFile.endsWith(".json") && (tsconfckCache == null ? void 0 : tsconfckCache.hasParseResult(changedFile))) {
    server.config.logger.info(
      `changed tsconfig file detected: ${changedFile} - Clearing cache and forcing full-reload to ensure TypeScript is compiled with updated config values.`,
      { clear: server.config.clearScreen, timestamp: true }
    );
    server.moduleGraph.invalidateAll();
    tsconfckCache == null ? void 0 : tsconfckCache.clear();
    if (server) {
      server.hot.send({
        type: "full-reload",
        path: "*"
      });
    }
  }
}
var Worker = class {
  constructor(fn, options2 = {}) {
    /** @internal */
    __publicField(this, "_code");
    /** @internal */
    __publicField(this, "_parentFunctions");
    /** @internal */
    __publicField(this, "_max");
    /** @internal */
    __publicField(this, "_pool");
    /** @internal */
    __publicField(this, "_idlePool");
    /** @internal */
    __publicField(this, "_queue");
    var _a4, _b3;
    this._code = genWorkerCode(fn, options2.parentFunctions ?? {});
    this._parentFunctions = options2.parentFunctions ?? {};
    const defaultMax = Math.max(
      1,
      // os.availableParallelism is available from Node.js 18.14.0
      (((_b3 = (_a4 = import_node_os.default).availableParallelism) == null ? void 0 : _b3.call(_a4)) ?? import_node_os.default.cpus().length) - 1
    );
    this._max = options2.max || defaultMax;
    this._pool = [];
    this._idlePool = [];
    this._queue = [];
  }
  async run(...args) {
    const worker = await this._getAvailableWorker();
    return new Promise((resolve3, reject) => {
      worker.currentResolve = resolve3;
      worker.currentReject = reject;
      worker.postMessage({ type: "run", args });
    });
  }
  stop() {
    this._pool.forEach((w) => w.unref());
    this._queue.forEach(
      ([, reject]) => reject(
        new Error("Main worker pool stopped before a worker was available.")
      )
    );
    this._pool = [];
    this._idlePool = [];
    this._queue = [];
  }
  /** @internal */
  async _getAvailableWorker() {
    if (this._idlePool.length) {
      return this._idlePool.shift();
    }
    if (this._pool.length < this._max) {
      const worker = new import_node_worker_threads.Worker(this._code, { eval: true });
      worker.on("message", async (args) => {
        if (args.type === "run") {
          if ("result" in args) {
            worker.currentResolve && worker.currentResolve(args.result);
            worker.currentResolve = null;
          } else {
            if (args.error instanceof ReferenceError) {
              args.error.message += ". Maybe you forgot to pass the function to parentFunction?";
            }
            worker.currentReject && worker.currentReject(args.error);
            worker.currentReject = null;
          }
          this._assignDoneWorker(worker);
        } else if (args.type === "parentFunction") {
          try {
            const result = await this._parentFunctions[args.name](...args.args);
            worker.postMessage({ type: "parentFunction", id: args.id, result });
          } catch (e2) {
            worker.postMessage({
              type: "parentFunction",
              id: args.id,
              error: e2
            });
          }
        }
      });
      worker.on("error", (err2) => {
        worker.currentReject && worker.currentReject(err2);
        worker.currentReject = null;
      });
      worker.on("exit", (code) => {
        const i = this._pool.indexOf(worker);
        if (i > -1)
          this._pool.splice(i, 1);
        if (code !== 0 && worker.currentReject) {
          worker.currentReject(
            new Error(`Worker stopped with non-0 exit code ${code}`)
          );
          worker.currentReject = null;
        }
      });
      this._pool.push(worker);
      return worker;
    }
    let resolve3;
    let reject;
    const onWorkerAvailablePromise = new Promise((r2, rj) => {
      resolve3 = r2;
      reject = rj;
    });
    this._queue.push([resolve3, reject]);
    return onWorkerAvailablePromise;
  }
  /** @internal */
  _assignDoneWorker(worker) {
    if (this._queue.length) {
      const [resolve3] = this._queue.shift();
      resolve3(worker);
      return;
    }
    this._idlePool.push(worker);
  }
};
function genWorkerCode(fn, parentFunctions) {
  const createParentFunctionCaller = (parentPort) => {
    let id = 0;
    const resolvers = /* @__PURE__ */ new Map();
    const call2 = (key) => async (...args) => {
      id++;
      let resolve3, reject;
      const promise2 = new Promise((res, rej) => {
        resolve3 = res;
        reject = rej;
      });
      resolvers.set(id, { resolve: resolve3, reject });
      parentPort.postMessage({ type: "parentFunction", id, name: key, args });
      return await promise2;
    };
    const receive = (id2, args) => {
      if (resolvers.has(id2)) {
        const { resolve: resolve3, reject } = resolvers.get(id2);
        resolvers.delete(id2);
        if ("result" in args) {
          resolve3(args.result);
        } else {
          reject(args.error);
        }
      }
    };
    return { call: call2, receive };
  };
  return `
const { parentPort } = require('worker_threads')
const parentFunctionCaller = (${createParentFunctionCaller.toString()})(parentPort)

const doWork = (() => {
  ${Object.keys(parentFunctions).map(
    (key) => `const ${key} = parentFunctionCaller.call(${JSON.stringify(key)});`
  ).join("\n")}
  return (${fn.toString()})()
})()

parentPort.on('message', async (args) => {
  if (args.type === 'run') {
    try {
      const res = await doWork(...args.args)
      parentPort.postMessage({ type: 'run', result: res })
    } catch (e) {
      parentPort.postMessage({ type: 'run', error: e })
    }
  } else if (args.type === 'parentFunction') {
    parentFunctionCaller.receive(args.id, args)
  }
})
  `;
}
var FakeWorker = class {
  constructor(fn, options2 = {}) {
    /** @internal */
    __publicField(this, "_fn");
    const argsAndCode = genFakeWorkerArgsAndCode(
      fn,
      options2.parentFunctions ?? {}
    );
    const require22 = (0, import_node_module.createRequire)(import.meta.url);
    this._fn = new Function(...argsAndCode)(require22, options2.parentFunctions);
  }
  async run(...args) {
    try {
      return await this._fn(...args);
    } catch (err2) {
      if (err2 instanceof ReferenceError) {
        err2.message += ". Maybe you forgot to pass the function to parentFunction?";
      }
      throw err2;
    }
  }
  stop() {
  }
};
function genFakeWorkerArgsAndCode(fn, parentFunctions) {
  return [
    "require",
    "parentFunctions",
    `
${Object.keys(parentFunctions).map((key) => `const ${key} = parentFunctions[${JSON.stringify(key)}];`).join("\n")}
return (${fn.toString()})()
  `
  ];
}
var WorkerWithFallback = class {
  constructor(fn, options2) {
    /** @internal */
    __publicField(this, "_disableReal");
    /** @internal */
    __publicField(this, "_realWorker");
    /** @internal */
    __publicField(this, "_fakeWorker");
    /** @internal */
    __publicField(this, "_shouldUseFake");
    this._disableReal = options2.max !== void 0 && options2.max <= 0;
    this._realWorker = new Worker(fn, options2);
    this._fakeWorker = new FakeWorker(fn, options2);
    this._shouldUseFake = options2.shouldUseFake;
  }
  async run(...args) {
    const useFake = this._disableReal || this._shouldUseFake(...args);
    return this[useFake ? "_fakeWorker" : "_realWorker"].run(...args);
  }
  stop() {
    this._realWorker.stop();
    this._fakeWorker.stop();
  }
};
var terserPath;
var loadTerserPath = (root) => {
  if (terserPath) return terserPath;
  try {
    terserPath = requireResolveFromRootWithFallback(root, "terser");
  } catch (e2) {
    if (e2.code === "MODULE_NOT_FOUND") {
      throw new Error(
        "terser not found. Since Vite v3, terser has become an optional dependency. You need to install it."
      );
    } else {
      const message = new Error(`terser failed to load:
${e2.message}`);
      message.stack = e2.stack + "\n" + message.stack;
      throw message;
    }
  }
  return terserPath;
};
function terserPlugin(config2) {
  const { maxWorkers, ...terserOptions } = config2.build.terserOptions;
  const makeWorker = () => new Worker(
    () => async (terserPath2, code, options2) => {
      const terser = require2(terserPath2);
      return terser.minify(code, options2);
    },
    {
      max: maxWorkers
    }
  );
  let worker;
  return {
    name: "vite:terser",
    async renderChunk(code, _chunk, outputOptions) {
      if (config2.build.minify !== "terser" && // @ts-expect-error injected by @vitejs/plugin-legacy
      !outputOptions.__vite_force_terser__) {
        return null;
      }
      if (config2.build.lib && outputOptions.format === "es") {
        return null;
      }
      worker || (worker = makeWorker());
      const terserPath2 = loadTerserPath(config2.root);
      const res = await worker.run(terserPath2, code, {
        safari10: true,
        ...terserOptions,
        sourceMap: !!outputOptions.sourcemap,
        module: outputOptions.format.startsWith("es"),
        toplevel: outputOptions.format === "cjs"
      });
      return {
        code: res.code,
        map: res.map
      };
    },
    closeBundle() {
      worker == null ? void 0 : worker.stop();
    }
  };
}
var mimes = {
  "3g2": "video/3gpp2",
  "3gp": "video/3gpp",
  "3gpp": "video/3gpp",
  "3mf": "model/3mf",
  "aac": "audio/aac",
  "ac": "application/pkix-attr-cert",
  "adp": "audio/adpcm",
  "adts": "audio/aac",
  "ai": "application/postscript",
  "aml": "application/automationml-aml+xml",
  "amlx": "application/automationml-amlx+zip",
  "amr": "audio/amr",
  "apng": "image/apng",
  "appcache": "text/cache-manifest",
  "appinstaller": "application/appinstaller",
  "appx": "application/appx",
  "appxbundle": "application/appxbundle",
  "asc": "application/pgp-keys",
  "atom": "application/atom+xml",
  "atomcat": "application/atomcat+xml",
  "atomdeleted": "application/atomdeleted+xml",
  "atomsvc": "application/atomsvc+xml",
  "au": "audio/basic",
  "avci": "image/avci",
  "avcs": "image/avcs",
  "avif": "image/avif",
  "aw": "application/applixware",
  "bdoc": "application/bdoc",
  "bin": "application/octet-stream",
  "bmp": "image/bmp",
  "bpk": "application/octet-stream",
  "btf": "image/prs.btif",
  "btif": "image/prs.btif",
  "buffer": "application/octet-stream",
  "ccxml": "application/ccxml+xml",
  "cdfx": "application/cdfx+xml",
  "cdmia": "application/cdmi-capability",
  "cdmic": "application/cdmi-container",
  "cdmid": "application/cdmi-domain",
  "cdmio": "application/cdmi-object",
  "cdmiq": "application/cdmi-queue",
  "cer": "application/pkix-cert",
  "cgm": "image/cgm",
  "cjs": "application/node",
  "class": "application/java-vm",
  "coffee": "text/coffeescript",
  "conf": "text/plain",
  "cpl": "application/cpl+xml",
  "cpt": "application/mac-compactpro",
  "crl": "application/pkix-crl",
  "css": "text/css",
  "csv": "text/csv",
  "cu": "application/cu-seeme",
  "cwl": "application/cwl",
  "cww": "application/prs.cww",
  "davmount": "application/davmount+xml",
  "dbk": "application/docbook+xml",
  "deb": "application/octet-stream",
  "def": "text/plain",
  "deploy": "application/octet-stream",
  "dib": "image/bmp",
  "disposition-notification": "message/disposition-notification",
  "dist": "application/octet-stream",
  "distz": "application/octet-stream",
  "dll": "application/octet-stream",
  "dmg": "application/octet-stream",
  "dms": "application/octet-stream",
  "doc": "application/msword",
  "dot": "application/msword",
  "dpx": "image/dpx",
  "drle": "image/dicom-rle",
  "dsc": "text/prs.lines.tag",
  "dssc": "application/dssc+der",
  "dtd": "application/xml-dtd",
  "dump": "application/octet-stream",
  "dwd": "application/atsc-dwd+xml",
  "ear": "application/java-archive",
  "ecma": "application/ecmascript",
  "elc": "application/octet-stream",
  "emf": "image/emf",
  "eml": "message/rfc822",
  "emma": "application/emma+xml",
  "emotionml": "application/emotionml+xml",
  "eps": "application/postscript",
  "epub": "application/epub+zip",
  "exe": "application/octet-stream",
  "exi": "application/exi",
  "exp": "application/express",
  "exr": "image/aces",
  "ez": "application/andrew-inset",
  "fdf": "application/fdf",
  "fdt": "application/fdt+xml",
  "fits": "image/fits",
  "g3": "image/g3fax",
  "gbr": "application/rpki-ghostbusters",
  "geojson": "application/geo+json",
  "gif": "image/gif",
  "glb": "model/gltf-binary",
  "gltf": "model/gltf+json",
  "gml": "application/gml+xml",
  "gpx": "application/gpx+xml",
  "gram": "application/srgs",
  "grxml": "application/srgs+xml",
  "gxf": "application/gxf",
  "gz": "application/gzip",
  "h261": "video/h261",
  "h263": "video/h263",
  "h264": "video/h264",
  "heic": "image/heic",
  "heics": "image/heic-sequence",
  "heif": "image/heif",
  "heifs": "image/heif-sequence",
  "hej2": "image/hej2k",
  "held": "application/atsc-held+xml",
  "hjson": "application/hjson",
  "hlp": "application/winhlp",
  "hqx": "application/mac-binhex40",
  "hsj2": "image/hsj2",
  "htm": "text/html",
  "html": "text/html",
  "ics": "text/calendar",
  "ief": "image/ief",
  "ifb": "text/calendar",
  "iges": "model/iges",
  "igs": "model/iges",
  "img": "application/octet-stream",
  "in": "text/plain",
  "ini": "text/plain",
  "ink": "application/inkml+xml",
  "inkml": "application/inkml+xml",
  "ipfix": "application/ipfix",
  "iso": "application/octet-stream",
  "its": "application/its+xml",
  "jade": "text/jade",
  "jar": "application/java-archive",
  "jhc": "image/jphc",
  "jls": "image/jls",
  "jp2": "image/jp2",
  "jpe": "image/jpeg",
  "jpeg": "image/jpeg",
  "jpf": "image/jpx",
  "jpg": "image/jpeg",
  "jpg2": "image/jp2",
  "jpgm": "image/jpm",
  "jpgv": "video/jpeg",
  "jph": "image/jph",
  "jpm": "image/jpm",
  "jpx": "image/jpx",
  "js": "text/javascript",
  "json": "application/json",
  "json5": "application/json5",
  "jsonld": "application/ld+json",
  "jsonml": "application/jsonml+json",
  "jsx": "text/jsx",
  "jt": "model/jt",
  "jxr": "image/jxr",
  "jxra": "image/jxra",
  "jxrs": "image/jxrs",
  "jxs": "image/jxs",
  "jxsc": "image/jxsc",
  "jxsi": "image/jxsi",
  "jxss": "image/jxss",
  "kar": "audio/midi",
  "ktx": "image/ktx",
  "ktx2": "image/ktx2",
  "less": "text/less",
  "lgr": "application/lgr+xml",
  "list": "text/plain",
  "litcoffee": "text/coffeescript",
  "log": "text/plain",
  "lostxml": "application/lost+xml",
  "lrf": "application/octet-stream",
  "m1v": "video/mpeg",
  "m21": "application/mp21",
  "m2a": "audio/mpeg",
  "m2v": "video/mpeg",
  "m3a": "audio/mpeg",
  "m4a": "audio/mp4",
  "m4p": "application/mp4",
  "m4s": "video/iso.segment",
  "ma": "application/mathematica",
  "mads": "application/mads+xml",
  "maei": "application/mmt-aei+xml",
  "man": "text/troff",
  "manifest": "text/cache-manifest",
  "map": "application/json",
  "mar": "application/octet-stream",
  "markdown": "text/markdown",
  "mathml": "application/mathml+xml",
  "mb": "application/mathematica",
  "mbox": "application/mbox",
  "md": "text/markdown",
  "mdx": "text/mdx",
  "me": "text/troff",
  "mesh": "model/mesh",
  "meta4": "application/metalink4+xml",
  "metalink": "application/metalink+xml",
  "mets": "application/mets+xml",
  "mft": "application/rpki-manifest",
  "mid": "audio/midi",
  "midi": "audio/midi",
  "mime": "message/rfc822",
  "mj2": "video/mj2",
  "mjp2": "video/mj2",
  "mjs": "text/javascript",
  "mml": "text/mathml",
  "mods": "application/mods+xml",
  "mov": "video/quicktime",
  "mp2": "audio/mpeg",
  "mp21": "application/mp21",
  "mp2a": "audio/mpeg",
  "mp3": "audio/mpeg",
  "mp4": "video/mp4",
  "mp4a": "audio/mp4",
  "mp4s": "application/mp4",
  "mp4v": "video/mp4",
  "mpd": "application/dash+xml",
  "mpe": "video/mpeg",
  "mpeg": "video/mpeg",
  "mpf": "application/media-policy-dataset+xml",
  "mpg": "video/mpeg",
  "mpg4": "video/mp4",
  "mpga": "audio/mpeg",
  "mpp": "application/dash-patch+xml",
  "mrc": "application/marc",
  "mrcx": "application/marcxml+xml",
  "ms": "text/troff",
  "mscml": "application/mediaservercontrol+xml",
  "msh": "model/mesh",
  "msi": "application/octet-stream",
  "msix": "application/msix",
  "msixbundle": "application/msixbundle",
  "msm": "application/octet-stream",
  "msp": "application/octet-stream",
  "mtl": "model/mtl",
  "musd": "application/mmt-usd+xml",
  "mxf": "application/mxf",
  "mxmf": "audio/mobile-xmf",
  "mxml": "application/xv+xml",
  "n3": "text/n3",
  "nb": "application/mathematica",
  "nq": "application/n-quads",
  "nt": "application/n-triples",
  "obj": "model/obj",
  "oda": "application/oda",
  "oga": "audio/ogg",
  "ogg": "audio/ogg",
  "ogv": "video/ogg",
  "ogx": "application/ogg",
  "omdoc": "application/omdoc+xml",
  "onepkg": "application/onenote",
  "onetmp": "application/onenote",
  "onetoc": "application/onenote",
  "onetoc2": "application/onenote",
  "opf": "application/oebps-package+xml",
  "opus": "audio/ogg",
  "otf": "font/otf",
  "owl": "application/rdf+xml",
  "oxps": "application/oxps",
  "p10": "application/pkcs10",
  "p7c": "application/pkcs7-mime",
  "p7m": "application/pkcs7-mime",
  "p7s": "application/pkcs7-signature",
  "p8": "application/pkcs8",
  "pdf": "application/pdf",
  "pfr": "application/font-tdpfr",
  "pgp": "application/pgp-encrypted",
  "pkg": "application/octet-stream",
  "pki": "application/pkixcmp",
  "pkipath": "application/pkix-pkipath",
  "pls": "application/pls+xml",
  "png": "image/png",
  "prc": "model/prc",
  "prf": "application/pics-rules",
  "provx": "application/provenance+xml",
  "ps": "application/postscript",
  "pskcxml": "application/pskc+xml",
  "pti": "image/prs.pti",
  "qt": "video/quicktime",
  "raml": "application/raml+yaml",
  "rapd": "application/route-apd+xml",
  "rdf": "application/rdf+xml",
  "relo": "application/p2p-overlay+xml",
  "rif": "application/reginfo+xml",
  "rl": "application/resource-lists+xml",
  "rld": "application/resource-lists-diff+xml",
  "rmi": "audio/midi",
  "rnc": "application/relax-ng-compact-syntax",
  "rng": "application/xml",
  "roa": "application/rpki-roa",
  "roff": "text/troff",
  "rq": "application/sparql-query",
  "rs": "application/rls-services+xml",
  "rsat": "application/atsc-rsat+xml",
  "rsd": "application/rsd+xml",
  "rsheet": "application/urc-ressheet+xml",
  "rss": "application/rss+xml",
  "rtf": "text/rtf",
  "rtx": "text/richtext",
  "rusd": "application/route-usd+xml",
  "s3m": "audio/s3m",
  "sbml": "application/sbml+xml",
  "scq": "application/scvp-cv-request",
  "scs": "application/scvp-cv-response",
  "sdp": "application/sdp",
  "senmlx": "application/senml+xml",
  "sensmlx": "application/sensml+xml",
  "ser": "application/java-serialized-object",
  "setpay": "application/set-payment-initiation",
  "setreg": "application/set-registration-initiation",
  "sgi": "image/sgi",
  "sgm": "text/sgml",
  "sgml": "text/sgml",
  "shex": "text/shex",
  "shf": "application/shf+xml",
  "shtml": "text/html",
  "sieve": "application/sieve",
  "sig": "application/pgp-signature",
  "sil": "audio/silk",
  "silo": "model/mesh",
  "siv": "application/sieve",
  "slim": "text/slim",
  "slm": "text/slim",
  "sls": "application/route-s-tsid+xml",
  "smi": "application/smil+xml",
  "smil": "application/smil+xml",
  "snd": "audio/basic",
  "so": "application/octet-stream",
  "spdx": "text/spdx",
  "spp": "application/scvp-vp-response",
  "spq": "application/scvp-vp-request",
  "spx": "audio/ogg",
  "sql": "application/sql",
  "sru": "application/sru+xml",
  "srx": "application/sparql-results+xml",
  "ssdl": "application/ssdl+xml",
  "ssml": "application/ssml+xml",
  "stk": "application/hyperstudio",
  "stl": "model/stl",
  "stpx": "model/step+xml",
  "stpxz": "model/step-xml+zip",
  "stpz": "model/step+zip",
  "styl": "text/stylus",
  "stylus": "text/stylus",
  "svg": "image/svg+xml",
  "svgz": "image/svg+xml",
  "swidtag": "application/swid+xml",
  "t": "text/troff",
  "t38": "image/t38",
  "td": "application/urc-targetdesc+xml",
  "tei": "application/tei+xml",
  "teicorpus": "application/tei+xml",
  "text": "text/plain",
  "tfi": "application/thraud+xml",
  "tfx": "image/tiff-fx",
  "tif": "image/tiff",
  "tiff": "image/tiff",
  "toml": "application/toml",
  "tr": "text/troff",
  "trig": "application/trig",
  "ts": "video/mp2t",
  "tsd": "application/timestamped-data",
  "tsv": "text/tab-separated-values",
  "ttc": "font/collection",
  "ttf": "font/ttf",
  "ttl": "text/turtle",
  "ttml": "application/ttml+xml",
  "txt": "text/plain",
  "u3d": "model/u3d",
  "u8dsn": "message/global-delivery-status",
  "u8hdr": "message/global-headers",
  "u8mdn": "message/global-disposition-notification",
  "u8msg": "message/global",
  "ubj": "application/ubjson",
  "uri": "text/uri-list",
  "uris": "text/uri-list",
  "urls": "text/uri-list",
  "vcard": "text/vcard",
  "vrml": "model/vrml",
  "vtt": "text/vtt",
  "vxml": "application/voicexml+xml",
  "war": "application/java-archive",
  "wasm": "application/wasm",
  "wav": "audio/wav",
  "weba": "audio/webm",
  "webm": "video/webm",
  "webmanifest": "application/manifest+json",
  "webp": "image/webp",
  "wgsl": "text/wgsl",
  "wgt": "application/widget",
  "wif": "application/watcherinfo+xml",
  "wmf": "image/wmf",
  "woff": "font/woff",
  "woff2": "font/woff2",
  "wrl": "model/vrml",
  "wsdl": "application/wsdl+xml",
  "wspolicy": "application/wspolicy+xml",
  "x3d": "model/x3d+xml",
  "x3db": "model/x3d+fastinfoset",
  "x3dbz": "model/x3d+binary",
  "x3dv": "model/x3d-vrml",
  "x3dvz": "model/x3d+vrml",
  "x3dz": "model/x3d+xml",
  "xaml": "application/xaml+xml",
  "xav": "application/xcap-att+xml",
  "xca": "application/xcap-caps+xml",
  "xcs": "application/calendar+xml",
  "xdf": "application/xcap-diff+xml",
  "xdssc": "application/dssc+xml",
  "xel": "application/xcap-el+xml",
  "xenc": "application/xenc+xml",
  "xer": "application/patch-ops-error+xml",
  "xfdf": "application/xfdf",
  "xht": "application/xhtml+xml",
  "xhtml": "application/xhtml+xml",
  "xhvml": "application/xv+xml",
  "xlf": "application/xliff+xml",
  "xm": "audio/xm",
  "xml": "text/xml",
  "xns": "application/xcap-ns+xml",
  "xop": "application/xop+xml",
  "xpl": "application/xproc+xml",
  "xsd": "application/xml",
  "xsf": "application/prs.xsf+xml",
  "xsl": "application/xml",
  "xslt": "application/xml",
  "xspf": "application/xspf+xml",
  "xvm": "application/xv+xml",
  "xvml": "application/xv+xml",
  "yaml": "text/yaml",
  "yang": "application/yang",
  "yin": "application/yin+xml",
  "yml": "text/yaml",
  "zip": "application/zip"
};
function lookup(extn) {
  let tmp = ("" + extn).trim().toLowerCase();
  let idx = tmp.lastIndexOf(".");
  return mimes[!~idx ? tmp : tmp.substring(++idx)];
}
var publicFilesMap = /* @__PURE__ */ new WeakMap();
async function initPublicFiles(config2) {
  let fileNames;
  try {
    fileNames = await recursiveReaddir(config2.publicDir);
  } catch (e2) {
    if (e2.code === ERR_SYMLINK_IN_RECURSIVE_READDIR) {
      return;
    }
    throw e2;
  }
  const publicFiles = new Set(
    fileNames.map((fileName) => fileName.slice(config2.publicDir.length))
  );
  publicFilesMap.set(config2, publicFiles);
  return publicFiles;
}
function getPublicFiles(config2) {
  return publicFilesMap.get(config2);
}
function checkPublicFile(url2, config2) {
  const { publicDir } = config2;
  if (!publicDir || url2[0] !== "/") {
    return;
  }
  const fileName = cleanUrl(url2);
  const publicFiles = getPublicFiles(config2);
  if (publicFiles) {
    return publicFiles.has(fileName) ? normalizePath$3(import_node_path3.default.join(publicDir, fileName)) : void 0;
  }
  const publicFile = normalizePath$3(import_node_path3.default.join(publicDir, fileName));
  if (!publicFile.startsWith(withTrailingSlash(publicDir))) {
    return;
  }
  return import_node_fs2.default.existsSync(publicFile) ? publicFile : void 0;
}
var assetUrlRE = /__VITE_ASSET__([\w$]+)__(?:\$_(.*?)__)?/g;
var jsSourceMapRE = /\.[cm]?js\.map$/;
var assetCache = /* @__PURE__ */ new WeakMap();
var generatedAssets = /* @__PURE__ */ new WeakMap();
function registerCustomMime() {
  mimes["ico"] = "image/x-icon";
  mimes["flac"] = "audio/flac";
  mimes["eot"] = "application/vnd.ms-fontobject";
}
function renderAssetUrlInJS(ctx, config2, chunk, opts, code) {
  const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(
    opts.format,
    config2.isWorker
  );
  let match2;
  let s;
  assetUrlRE.lastIndex = 0;
  while (match2 = assetUrlRE.exec(code)) {
    s || (s = new MagicString(code));
    const [full, referenceId, postfix = ""] = match2;
    const file = ctx.getFileName(referenceId);
    chunk.viteMetadata.importedAssets.add(cleanUrl(file));
    const filename = file + postfix;
    const replacement = toOutputFilePathInJS(
      filename,
      "asset",
      chunk.fileName,
      "js",
      config2,
      toRelativeRuntime
    );
    const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
    s.update(match2.index, match2.index + full.length, replacementString);
  }
  const publicAssetUrlMap = publicAssetUrlCache.get(config2);
  publicAssetUrlRE.lastIndex = 0;
  while (match2 = publicAssetUrlRE.exec(code)) {
    s || (s = new MagicString(code));
    const [full, hash2] = match2;
    const publicUrl = publicAssetUrlMap.get(hash2).slice(1);
    const replacement = toOutputFilePathInJS(
      publicUrl,
      "public",
      chunk.fileName,
      "js",
      config2,
      toRelativeRuntime
    );
    const replacementString = typeof replacement === "string" ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1) : `"+${replacement.runtime}+"`;
    s.update(match2.index, match2.index + full.length, replacementString);
  }
  return s;
}
function assetPlugin(config2) {
  registerCustomMime();
  let moduleGraph;
  return {
    name: "vite:asset",
    buildStart() {
      assetCache.set(config2, /* @__PURE__ */ new Map());
      generatedAssets.set(config2, /* @__PURE__ */ new Map());
    },
    configureServer(server2) {
      moduleGraph = server2.moduleGraph;
    },
    resolveId(id) {
      if (!config2.assetsInclude(cleanUrl(id)) && !urlRE.test(id)) {
        return;
      }
      const publicFile = checkPublicFile(id, config2);
      if (publicFile) {
        return id;
      }
    },
    async load(id) {
      var _a4;
      if (id[0] === "\0") {
        return;
      }
      if (rawRE.test(id)) {
        const file = checkPublicFile(id, config2) || cleanUrl(id);
        this.addWatchFile(file);
        return `export default ${JSON.stringify(
          await import_promises.default.readFile(file, "utf-8")
        )}`;
      }
      if (!urlRE.test(id) && !config2.assetsInclude(cleanUrl(id))) {
        return;
      }
      id = removeUrlQuery(id);
      let url2 = await fileToUrl$1(id, config2, this);
      if (moduleGraph) {
        const mod = moduleGraph.getModuleById(id);
        if (mod && mod.lastHMRTimestamp > 0) {
          url2 = injectQuery(url2, `t=${mod.lastHMRTimestamp}`);
        }
      }
      return {
        code: `export default ${JSON.stringify(encodeURIPath(url2))}`,
        // Force rollup to keep this module from being shared between other entry points if it's an entrypoint.
        // If the resulting chunk is empty, it will be removed in generateBundle.
        moduleSideEffects: config2.command === "build" && ((_a4 = this.getModuleInfo(id)) == null ? void 0 : _a4.isEntry) ? "no-treeshake" : false
      };
    },
    renderChunk(code, chunk, opts) {
      const s = renderAssetUrlInJS(this, config2, chunk, opts, code);
      if (s) {
        return {
          code: s.toString(),
          map: config2.build.sourcemap ? s.generateMap({ hires: "boundary" }) : null
        };
      } else {
        return null;
      }
    },
    generateBundle(_, bundle) {
      for (const file in bundle) {
        const chunk = bundle[file];
        if (chunk.type === "chunk" && chunk.isEntry && chunk.moduleIds.length === 1 && config2.assetsInclude(chunk.moduleIds[0])) {
          delete bundle[file];
        }
      }
      if (config2.command === "build" && config2.build.ssr && !config2.build.ssrEmitAssets) {
        for (const file in bundle) {
          if (bundle[file].type === "asset" && !file.endsWith("ssr-manifest.json") && !jsSourceMapRE.test(file)) {
            delete bundle[file];
          }
        }
      }
    }
  };
}
async function fileToUrl$1(id, config2, ctx) {
  if (config2.command === "serve") {
    return fileToDevUrl(id, config2);
  } else {
    return fileToBuiltUrl(id, config2, ctx);
  }
}
function fileToDevUrl(id, config2) {
  var _a4;
  let rtn;
  if (checkPublicFile(id, config2)) {
    rtn = id;
  } else if (id.startsWith(withTrailingSlash(config2.root))) {
    rtn = "/" + import_node_path3.default.posix.relative(config2.root, id);
  } else {
    rtn = import_node_path3.default.posix.join(FS_PREFIX, id);
  }
  const base = joinUrlSegments(((_a4 = config2.server) == null ? void 0 : _a4.origin) ?? "", config2.base);
  return joinUrlSegments(base, removeLeadingSlash(rtn));
}
function getPublicAssetFilename(hash2, config2) {
  var _a4;
  return (_a4 = publicAssetUrlCache.get(config2)) == null ? void 0 : _a4.get(hash2);
}
var publicAssetUrlCache = /* @__PURE__ */ new WeakMap();
var publicAssetUrlRE = /__VITE_PUBLIC_ASSET__([a-z\d]{8})__/g;
function publicFileToBuiltUrl(url2, config2) {
  if (config2.command !== "build") {
    return joinUrlSegments(config2.base, url2);
  }
  const hash2 = getHash(url2);
  let cache = publicAssetUrlCache.get(config2);
  if (!cache) {
    cache = /* @__PURE__ */ new Map();
    publicAssetUrlCache.set(config2, cache);
  }
  if (!cache.get(hash2)) {
    cache.set(hash2, url2);
  }
  return `__VITE_PUBLIC_ASSET__${hash2}__`;
}
var GIT_LFS_PREFIX = import_node_buffer.Buffer.from("version https://git-lfs.github.com");
function isGitLfsPlaceholder(content) {
  if (content.length < GIT_LFS_PREFIX.length) return false;
  return GIT_LFS_PREFIX.compare(content, 0, GIT_LFS_PREFIX.length) === 0;
}
async function fileToBuiltUrl(id, config2, pluginContext, skipPublicCheck = false, forceInline) {
  if (!skipPublicCheck && checkPublicFile(id, config2)) {
    return publicFileToBuiltUrl(id, config2);
  }
  const cache = assetCache.get(config2);
  const cached = cache.get(id);
  if (cached) {
    return cached;
  }
  const file = cleanUrl(id);
  const content = await import_promises.default.readFile(file);
  let url2;
  if (shouldInline(config2, file, id, content, pluginContext, forceInline)) {
    if (config2.build.lib && isGitLfsPlaceholder(content)) {
      config2.logger.warn(
        colors$1.yellow(`Inlined file ${id} was not downloaded via Git LFS`)
      );
    }
    if (file.endsWith(".svg")) {
      url2 = svgToDataURL(content);
    } else {
      const mimeType = lookup(file) ?? "application/octet-stream";
      url2 = `data:${mimeType};base64,${content.toString("base64")}`;
    }
  } else {
    const { search, hash: hash2 } = (0, import_node_url2.parse)(id);
    const postfix = (search || "") + (hash2 || "");
    const referenceId = pluginContext.emitFile({
      // Ignore directory structure for asset file names
      name: import_node_path3.default.basename(file),
      type: "asset",
      source: content
    });
    const originalName = normalizePath$3(import_node_path3.default.relative(config2.root, file));
    generatedAssets.get(config2).set(referenceId, { originalName });
    url2 = `__VITE_ASSET__${referenceId}__${postfix ? `$_${postfix}__` : ``}`;
  }
  cache.set(id, url2);
  return url2;
}
async function urlToBuiltUrl(url2, importer, config2, pluginContext, forceInline) {
  if (checkPublicFile(url2, config2)) {
    return publicFileToBuiltUrl(url2, config2);
  }
  const file = url2[0] === "/" ? import_node_path3.default.join(config2.root, url2) : import_node_path3.default.join(import_node_path3.default.dirname(importer), url2);
  return fileToBuiltUrl(
    file,
    config2,
    pluginContext,
    // skip public check since we just did it above
    true,
    forceInline
  );
}
var shouldInline = (config2, file, id, content, pluginContext, forceInline) => {
  var _a4;
  if (config2.build.lib) return true;
  if ((_a4 = pluginContext.getModuleInfo(id)) == null ? void 0 : _a4.isEntry) return false;
  if (forceInline !== void 0) return forceInline;
  let limit;
  if (typeof config2.build.assetsInlineLimit === "function") {
    const userShouldInline = config2.build.assetsInlineLimit(file, content);
    if (userShouldInline != null) return userShouldInline;
    limit = DEFAULT_ASSETS_INLINE_LIMIT;
  } else {
    limit = Number(config2.build.assetsInlineLimit);
  }
  if (file.endsWith(".html")) return false;
  if (file.endsWith(".svg") && id.includes("#")) return false;
  return content.length < limit && !isGitLfsPlaceholder(content);
};
var nestedQuotesRE = /"[^"']*'[^"]*"|'[^'"]*"[^']*'/;
function svgToDataURL(content) {
  const stringContent = content.toString();
  if (stringContent.includes("\s+<").replaceAll('"', "'").replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("<", "%3c").replaceAll(">", "%3e").replaceAll(/\s+/g, "%20");
  }
}
var endsWithJSRE = /\.[cm]?js$/;
function manifestPlugin(config2) {
  const manifest = {};
  let outputCount;
  return {
    name: "vite:manifest",
    buildStart() {
      outputCount = 0;
    },
    generateBundle({ format: format2 }, bundle) {
      var _a4, _b3;
      function getChunkName(chunk) {
        return getChunkOriginalFileName(chunk, config2.root, format2);
      }
      function getInternalImports(imports) {
        const filteredImports = [];
        for (const file of imports) {
          if (bundle[file] === void 0) {
            continue;
          }
          filteredImports.push(getChunkName(bundle[file]));
        }
        return filteredImports;
      }
      function createChunk(chunk) {
        var _a5, _b4;
        const manifestChunk = {
          file: chunk.fileName,
          name: chunk.name
        };
        if (chunk.facadeModuleId) {
          manifestChunk.src = getChunkName(chunk);
        }
        if (chunk.isEntry) {
          manifestChunk.isEntry = true;
        }
        if (chunk.isDynamicEntry) {
          manifestChunk.isDynamicEntry = true;
        }
        if (chunk.imports.length) {
          const internalImports = getInternalImports(chunk.imports);
          if (internalImports.length > 0) {
            manifestChunk.imports = internalImports;
          }
        }
        if (chunk.dynamicImports.length) {
          const internalImports = getInternalImports(chunk.dynamicImports);
          if (internalImports.length > 0) {
            manifestChunk.dynamicImports = internalImports;
          }
        }
        if ((_a5 = chunk.viteMetadata) == null ? void 0 : _a5.importedCss.size) {
          manifestChunk.css = [...chunk.viteMetadata.importedCss];
        }
        if ((_b4 = chunk.viteMetadata) == null ? void 0 : _b4.importedAssets.size) {
          manifestChunk.assets = [...chunk.viteMetadata.importedAssets];
        }
        return manifestChunk;
      }
      function createAsset(asset, src2, isEntry) {
        const manifestChunk = {
          file: asset.fileName,
          src: src2
        };
        if (isEntry) manifestChunk.isEntry = true;
        return manifestChunk;
      }
      const fileNameToAssetMeta = /* @__PURE__ */ new Map();
      const assets = generatedAssets.get(config2);
      assets.forEach((asset, referenceId) => {
        try {
          const fileName = this.getFileName(referenceId);
          fileNameToAssetMeta.set(fileName, asset);
        } catch (error2) {
          assets.delete(referenceId);
        }
      });
      const fileNameToAsset = /* @__PURE__ */ new Map();
      for (const file in bundle) {
        const chunk = bundle[file];
        if (chunk.type === "chunk") {
          manifest[getChunkName(chunk)] = createChunk(chunk);
        } else if (chunk.type === "asset" && typeof chunk.name === "string") {
          const assetMeta = fileNameToAssetMeta.get(chunk.fileName);
          const src2 = (assetMeta == null ? void 0 : assetMeta.originalName) ?? chunk.name;
          const asset = createAsset(chunk, src2, assetMeta == null ? void 0 : assetMeta.isEntry);
          const file2 = (_a4 = manifest[src2]) == null ? void 0 : _a4.file;
          if (file2 && endsWithJSRE.test(file2)) continue;
          manifest[src2] = asset;
          fileNameToAsset.set(chunk.fileName, asset);
        }
      }
      assets.forEach(({ originalName }, referenceId) => {
        if (!manifest[originalName]) {
          const fileName = this.getFileName(referenceId);
          const asset = fileNameToAsset.get(fileName);
          if (asset) {
            manifest[originalName] = asset;
          }
        }
      });
      outputCount++;
      const output = (_b3 = config2.build.rollupOptions) == null ? void 0 : _b3.output;
      const outputLength = Array.isArray(output) ? output.length : 1;
      if (outputCount >= outputLength) {
        this.emitFile({
          fileName: typeof config2.build.manifest === "string" ? config2.build.manifest : ".vite/manifest.json",
          type: "asset",
          source: JSON.stringify(sortObjectKeys(manifest), void 0, 2)
        });
      }
    }
  };
}
function getChunkOriginalFileName(chunk, root, format2) {
  if (chunk.facadeModuleId) {
    let name2 = normalizePath$3(import_node_path3.default.relative(root, chunk.facadeModuleId));
    if (format2 === "system" && !chunk.name.includes("-legacy")) {
      const ext2 = import_node_path3.default.extname(name2);
      const endPos = ext2.length !== 0 ? -ext2.length : void 0;
      name2 = name2.slice(0, endPos) + `-legacy` + ext2;
    }
    return name2.replace(/\0/g, "");
  } else {
    return `_` + import_node_path3.default.basename(chunk.fileName);
  }
}
var dataUriRE = /^([^/]+\/[^;,]+)(;base64)?,([\s\S]*)$/;
var base64RE = /base64/i;
var dataUriPrefix = `\0/@data-uri/`;
function dataURIPlugin() {
  let resolved;
  return {
    name: "vite:data-uri",
    buildStart() {
      resolved = /* @__PURE__ */ new Map();
    },
    resolveId(id) {
      if (!dataUriRE.test(id)) {
        return;
      }
      const uri = new import_node_url2.URL(id);
      if (uri.protocol !== "data:") {
        return;
      }
      const match2 = uri.pathname.match(dataUriRE);
      if (!match2) {
        return;
      }
      const [, mime, format2, data] = match2;
      if (mime !== "text/javascript") {
        throw new Error(
          `data URI with non-JavaScript mime type is not supported. If you're using legacy JavaScript MIME types (such as 'application/javascript'), please use 'text/javascript' instead.`
        );
      }
      const base64 = format2 && base64RE.test(format2.substring(1));
      const content = base64 ? Buffer.from(data, "base64").toString("utf-8") : data;
      resolved.set(id, content);
      return dataUriPrefix + id;
    },
    load(id) {
      if (id.startsWith(dataUriPrefix)) {
        return resolved.get(id.slice(dataUriPrefix.length));
      }
    }
  };
}
var ImportType;
!function(A2) {
  A2[A2.Static = 1] = "Static", A2[A2.Dynamic = 2] = "Dynamic", A2[A2.ImportMeta = 3] = "ImportMeta", A2[A2.StaticSourcePhase = 4] = "StaticSourcePhase", A2[A2.DynamicSourcePhase = 5] = "DynamicSourcePhase";
}(ImportType || (ImportType = {}));
var A = 1 === new Uint8Array(new Uint16Array([1]).buffer)[0];
function parse$d(E2, g = "@") {
  if (!C) return init.then(() => parse$d(E2));
  const I = E2.length + 1, w = (C.__heap_base.value || C.__heap_base) + 4 * I - C.memory.buffer.byteLength;
  w > 0 && C.memory.grow(Math.ceil(w / 65536));
  const K = C.sa(I - 1);
  if ((A ? B : Q)(E2, new Uint16Array(C.memory.buffer, K, I)), !C.parse()) throw Object.assign(new Error(`Parse error ${g}:${E2.slice(0, C.e()).split("\n").length}:${C.e() - E2.lastIndexOf("\n", C.e() - 1)}`), { idx: C.e() });
  const D = [], o2 = [];
  for (; C.ri(); ) {
    const A2 = C.is(), Q2 = C.ie(), B2 = C.it(), g2 = C.ai(), I2 = C.id(), w2 = C.ss(), K2 = C.se();
    let o3;
    C.ip() && (o3 = k(E2.slice(-1 === I2 ? A2 - 1 : A2, -1 === I2 ? Q2 + 1 : Q2))), D.push({ n: o3, t: B2, s: A2, e: Q2, ss: w2, se: K2, d: I2, a: g2 });
  }
  for (; C.re(); ) {
    const A2 = C.es(), Q2 = C.ee(), B2 = C.els(), g2 = C.ele(), I2 = E2.slice(A2, Q2), w2 = I2[0], K2 = B2 < 0 ? void 0 : E2.slice(B2, g2), D2 = K2 ? K2[0] : "";
    o2.push({ s: A2, e: Q2, ls: B2, le: g2, n: '"' === w2 || "'" === w2 ? k(I2) : I2, ln: '"' === D2 || "'" === D2 ? k(K2) : K2 });
  }
  function k(A2) {
    try {
      return (0, eval)(A2);
    } catch (A3) {
    }
  }
  return [D, o2, !!C.f(), !!C.ms()];
}
function Q(A2, Q2) {
  const B2 = A2.length;
  let C2 = 0;
  for (; C2 < B2; ) {
    const B3 = A2.charCodeAt(C2);
    Q2[C2++] = (255 & B3) << 8 | B3 >>> 8;
  }
}
function B(A2, Q2) {
  const B2 = A2.length;
  let C2 = 0;
  for (; C2 < B2; ) Q2[C2] = A2.charCodeAt(C2++);
}
var C;
var init = WebAssembly.compile((E = "AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKm0EwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQvcCAEGf0EAIQBBAEEAKAKwCiIBQQxqIgI2ArAKQQEQKSEDQQAoArAKIQQCQAJAAkACQAJAAkACQAJAIANBLkcNAEEAIARBAmo2ArAKAkBBARApIgNB8wBGDQAgA0HtAEcNB0EAKAKwCiIDQQJqQZwIQQYQLw0HAkBBACgCnAoiBBAqDQAgBC8BAEEuRg0ICyABIAEgA0EIakEAKALUCRABDwtBACgCsAoiA0ECakGiCEEKEC8NBgJAQQAoApwKIgQQKg0AIAQvAQBBLkYNBwsgA0EMaiEDDAELIANB8wBHDQEgBCACTQ0BQQYhAEEAIQIgBEECakGiCEEKEC8NAiAEQQxqIQMCQCAELwEMIgVBd2oiBEEXSw0AQQEgBHRBn4CABHENAQsgBUGgAUcNAgtBACADNgKwCkEBIQBBARApIQMLAkACQAJAAkAgA0H7AEYNACADQShHDQFBACgCpApBAC8BmAoiA0EDdGoiBEEAKAKwCjYCBEEAIANBAWo7AZgKIARBBTYCAEEAKAKcCi8BAEEuRg0HQQBBACgCsAoiBEECajYCsApBARApIQMgAUEAKAKwCkEAIAQQAQJAAkAgAA0AQQAoAvAJIQQMAQtBACgC8AkiBEEFNgIcC0EAQQAvAZYKIgBBAWo7AZYKQQAoAqgKIABBAnRqIAQ2AgACQCADQSJGDQAgA0EnRg0AQQBBACgCsApBfmo2ArAKDwsgAxAaQQBBACgCsApBAmoiAzYCsAoCQAJAAkBBARApQVdqDgQBAgIAAgtBAEEAKAKwCkECajYCsApBARApGkEAKALwCSIEIAM2AgQgBEEBOgAYIARBACgCsAoiAzYCEEEAIANBfmo2ArAKDwtBACgC8AkiBCADNgIEIARBAToAGEEAQQAvAZgKQX9qOwGYCiAEQQAoArAKQQJqNgIMQQBBAC8BlgpBf2o7AZYKDwtBAEEAKAKwCkF+ajYCsAoPCyAADQJBACgCsAohA0EALwGYCg0BA0ACQAJAAkAgA0EAKAK0Ck8NAEEBECkiA0EiRg0BIANBJ0YNASADQf0ARw0CQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0JC0EAIANBCGo2ArAKAkBBARApIgNBIkYNACADQSdHDQkLIAEgA0EAECsPCyADEBoLQQBBACgCsApBAmoiAzYCsAoMAAsLIAANAUEGIQBBACECAkAgA0FZag4EBAMDBAALIANBIkYNAwwCC0EAIANBfmo2ArAKDwtBDCEAQQEhAgtBACgCsAoiAyABIABBAXRqRw0AQQAgA0F+ajYCsAoPC0EALwGYCg0CQQAoArAKIQNBACgCtAohAANAIAMgAE8NAQJAAkAgAy8BACIEQSdGDQAgBEEiRw0BCyABIAQgAhArDwtBACADQQJqIgM2ArAKDAALCxAlCw8LQQBBACgCsApBfmo2ArAKC0cBA39BACgCsApBAmohAEEAKAK0CiEBAkADQCAAIgJBfmogAU8NASACQQJqIQAgAi8BAEF2ag4EAQAAAQALC0EAIAI2ArAKC5gBAQN/QQBBACgCsAoiAUECajYCsAogAUEGaiEBQQAoArQKIQIDQAJAAkACQCABQXxqIAJPDQAgAUF+ai8BACEDAkACQCAADQAgA0EqRg0BIANBdmoOBAIEBAIECyADQSpHDQMLIAEvAQBBL0cNAkEAIAFBfmo2ArAKDAELIAFBfmohAQtBACABNgKwCg8LIAFBAmohAQwACwuIAQEEf0EAKAKwCiEBQQAoArQKIQICQAJAA0AgASIDQQJqIQEgAyACTw0BIAEvAQAiBCAARg0CAkAgBEHcAEYNACAEQXZqDgQCAQECAQsgA0EEaiEBIAMvAQRBDUcNACADQQZqIAEgAy8BBkEKRhshAQwACwtBACABNgKwChAlDwtBACABNgKwCgtsAQF/AkACQCAAQV9qIgFBBUsNAEEBIAF0QTFxDQELIABBRmpB//8DcUEGSQ0AIABBKUcgAEFYakH//wNxQQdJcQ0AAkAgAEGlf2oOBAEAAAEACyAAQf0ARyAAQYV/akH//wNxQQRJcQ8LQQELLgEBf0EBIQECQCAAQaYJQQUQHQ0AIABBlghBAxAdDQAgAEGwCUECEB0hAQsgAQtGAQN/QQAhAwJAIAAgAkEBdCICayIEQQJqIgBBACgC3AkiBUkNACAAIAEgAhAvDQACQCAAIAVHDQBBAQ8LIAQQJiEDCyADC4MBAQJ/QQEhAQJAAkACQAJAAkACQCAALwEAIgJBRWoOBAUEBAEACwJAIAJBm39qDgQDBAQCAAsgAkEpRg0EIAJB+QBHDQMgAEF+akG8CUEGEB0PCyAAQX5qLwEAQT1GDwsgAEF+akG0CUEEEB0PCyAAQX5qQcgJQQMQHQ8LQQAhAQsgAQu0AwECf0EAIQECQAJAAkACQAJAAkACQAJAAkACQCAALwEAQZx/ag4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEF+ai8BAEGXf2oOBAAKCgEKCyAAQXxqQcoIQQIQHQ8LIABBfGpBzghBAxAdDwsCQAJAAkAgAEF+ai8BAEGNf2oOAwABAgoLAkAgAEF8ai8BACICQeEARg0AIAJB7ABHDQogAEF6akHlABAnDwsgAEF6akHjABAnDwsgAEF8akHUCEEEEB0PCyAAQXxqQdwIQQYQHQ8LIABBfmovAQBB7wBHDQYgAEF8ai8BAEHlAEcNBgJAIABBemovAQAiAkHwAEYNACACQeMARw0HIABBeGpB6AhBBhAdDwsgAEF4akH0CEECEB0PCyAAQX5qQfgIQQQQHQ8LQQEhASAAQX5qIgBB6QAQJw0EIABBgAlBBRAdDwsgAEF+akHkABAnDwsgAEF+akGKCUEHEB0PCyAAQX5qQZgJQQQQHQ8LAkAgAEF+ai8BACICQe8ARg0AIAJB5QBHDQEgAEF8akHuABAnDwsgAEF8akGgCUEDEB0hAQsgAQs0AQF/QQEhAQJAIABBd2pB//8DcUEFSQ0AIABBgAFyQaABRg0AIABBLkcgABAocSEBCyABCzABAX8CQAJAIABBd2oiAUEXSw0AQQEgAXRBjYCABHENAQsgAEGgAUYNAEEADwtBAQtOAQJ/QQAhAQJAAkAgAC8BACICQeUARg0AIAJB6wBHDQEgAEF+akH4CEEEEB0PCyAAQX5qLwEAQfUARw0AIABBfGpB3AhBBhAdIQELIAEL3gEBBH9BACgCsAohAEEAKAK0CiEBAkACQAJAA0AgACICQQJqIQAgAiABTw0BAkACQAJAIAAvAQAiA0Gkf2oOBQIDAwMBAAsgA0EkRw0CIAIvAQRB+wBHDQJBACACQQRqIgA2ArAKQQBBAC8BmAoiAkEBajsBmApBACgCpAogAkEDdGoiAkEENgIAIAIgADYCBA8LQQAgADYCsApBAEEALwGYCkF/aiIAOwGYCkEAKAKkCiAAQf//A3FBA3RqKAIAQQNHDQMMBAsgAkEEaiEADAALC0EAIAA2ArAKCxAlCwtwAQJ/AkACQANAQQBBACgCsAoiAEECaiIBNgKwCiAAQQAoArQKTw0BAkACQAJAIAEvAQAiAUGlf2oOAgECAAsCQCABQXZqDgQEAwMEAAsgAUEvRw0CDAQLEC4aDAELQQAgAEEEajYCsAoMAAsLECULCzUBAX9BAEEBOgD8CUEAKAKwCiEAQQBBACgCtApBAmo2ArAKQQAgAEEAKALcCWtBAXU2ApAKC0MBAn9BASEBAkAgAC8BACICQXdqQf//A3FBBUkNACACQYABckGgAUYNAEEAIQEgAhAoRQ0AIAJBLkcgABAqcg8LIAELPQECf0EAIQICQEEAKALcCSIDIABLDQAgAC8BACABRw0AAkAgAyAARw0AQQEPCyAAQX5qLwEAECAhAgsgAgtoAQJ/QQEhAQJAAkAgAEFfaiICQQVLDQBBASACdEExcQ0BCyAAQfj/A3FBKEYNACAAQUZqQf//A3FBBkkNAAJAIABBpX9qIgJBA0sNACACQQFHDQELIABBhX9qQf//A3FBBEkhAQsgAQucAQEDf0EAKAKwCiEBAkADQAJAAkAgAS8BACICQS9HDQACQCABLwECIgFBKkYNACABQS9HDQQQGAwCCyAAEBkMAQsCQAJAIABFDQAgAkF3aiIBQRdLDQFBASABdEGfgIAEcUUNAQwCCyACECFFDQMMAQsgAkGgAUcNAgtBAEEAKAKwCiIDQQJqIgE2ArAKIANBACgCtApJDQALCyACCzEBAX9BACEBAkAgAC8BAEEuRw0AIABBfmovAQBBLkcNACAAQXxqLwEAQS5GIQELIAELnAQBAX8CQCABQSJGDQAgAUEnRg0AECUPC0EAKAKwCiEDIAEQGiAAIANBAmpBACgCsApBACgC0AkQAQJAIAJFDQBBACgC8AlBBDYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQAMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhACABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIABBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiAiEAA0BBACAAQQJqNgKwCgJAAkACQEEBECkiAEEiRg0AIABBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQAMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSEADAELIAAQLCEACwJAIABBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAEEiRg0AIABBJ0YNAEEAIAE2ArAKDwsgABAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAEEsRg0AIABB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiEADAELC0EAKALwCSIBIAI2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=", "undefined" != typeof Buffer ? Buffer.from(E, "base64") : Uint8Array.from(atob(E), (A2) => A2.charCodeAt(0)))).then(WebAssembly.instantiate).then(({ exports: A2 }) => {
  C = A2;
});
var E;
var convertSourceMap$1 = {};
(function(exports2) {
  Object.defineProperty(exports2, "commentRegex", {
    get: function getCommentRegex() {
      return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
    }
  });
  Object.defineProperty(exports2, "mapFileCommentRegex", {
    get: function getMapFileCommentRegex() {
      return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
    }
  });
  var decodeBase64;
  if (typeof Buffer !== "undefined") {
    if (typeof Buffer.from === "function") {
      decodeBase64 = decodeBase64WithBufferFrom;
    } else {
      decodeBase64 = decodeBase64WithNewBuffer;
    }
  } else {
    decodeBase64 = decodeBase64WithAtob;
  }
  function decodeBase64WithBufferFrom(base64) {
    return Buffer.from(base64, "base64").toString();
  }
  function decodeBase64WithNewBuffer(base64) {
    if (typeof value === "number") {
      throw new TypeError("The value to decode must not be of type number.");
    }
    return new Buffer(base64, "base64").toString();
  }
  function decodeBase64WithAtob(base64) {
    return decodeURIComponent(escape(atob(base64)));
  }
  function stripComment(sm) {
    return sm.split(",").pop();
  }
  function readFromFileMap(sm, read2) {
    var r2 = exports2.mapFileCommentRegex.exec(sm);
    var filename = r2[1] || r2[2];
    try {
      var sm = read2(filename);
      if (sm != null && typeof sm.catch === "function") {
        return sm.catch(throwError);
      } else {
        return sm;
      }
    } catch (e2) {
      throwError(e2);
    }
    function throwError(e2) {
      throw new Error("An error occurred while trying to read the map file at " + filename + "\n" + e2.stack);
    }
  }
  function Converter(sm, opts) {
    opts = opts || {};
    if (opts.hasComment) {
      sm = stripComment(sm);
    }
    if (opts.encoding === "base64") {
      sm = decodeBase64(sm);
    } else if (opts.encoding === "uri") {
      sm = decodeURIComponent(sm);
    }
    if (opts.isJSON || opts.encoding) {
      sm = JSON.parse(sm);
    }
    this.sourcemap = sm;
  }
  Converter.prototype.toJSON = function(space) {
    return JSON.stringify(this.sourcemap, null, space);
  };
  if (typeof Buffer !== "undefined") {
    if (typeof Buffer.from === "function") {
      Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
    } else {
      Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
    }
  } else {
    Converter.prototype.toBase64 = encodeBase64WithBtoa;
  }
  function encodeBase64WithBufferFrom() {
    var json = this.toJSON();
    return Buffer.from(json, "utf8").toString("base64");
  }
  function encodeBase64WithNewBuffer() {
    var json = this.toJSON();
    if (typeof json === "number") {
      throw new TypeError("The json to encode must not be of type number.");
    }
    return new Buffer(json, "utf8").toString("base64");
  }
  function encodeBase64WithBtoa() {
    var json = this.toJSON();
    return btoa(unescape(encodeURIComponent(json)));
  }
  Converter.prototype.toURI = function() {
    var json = this.toJSON();
    return encodeURIComponent(json);
  };
  Converter.prototype.toComment = function(options2) {
    var encoding, content, data;
    if (options2 != null && options2.encoding === "uri") {
      encoding = "";
      content = this.toURI();
    } else {
      encoding = ";base64";
      content = this.toBase64();
    }
    data = "sourceMappingURL=data:application/json;charset=utf-8" + encoding + "," + content;
    return options2 != null && options2.multiline ? "/*# " + data + " */" : "//# " + data;
  };
  Converter.prototype.toObject = function() {
    return JSON.parse(this.toJSON());
  };
  Converter.prototype.addProperty = function(key, value2) {
    if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
    return this.setProperty(key, value2);
  };
  Converter.prototype.setProperty = function(key, value2) {
    this.sourcemap[key] = value2;
    return this;
  };
  Converter.prototype.getProperty = function(key) {
    return this.sourcemap[key];
  };
  exports2.fromObject = function(obj) {
    return new Converter(obj);
  };
  exports2.fromJSON = function(json) {
    return new Converter(json, { isJSON: true });
  };
  exports2.fromURI = function(uri) {
    return new Converter(uri, { encoding: "uri" });
  };
  exports2.fromBase64 = function(base64) {
    return new Converter(base64, { encoding: "base64" });
  };
  exports2.fromComment = function(comment) {
    var m, encoding;
    comment = comment.replace(/^\/\*/g, "//").replace(/\*\/$/g, "");
    m = exports2.commentRegex.exec(comment);
    encoding = m && m[4] || "uri";
    return new Converter(comment, { encoding, hasComment: true });
  };
  function makeConverter(sm) {
    return new Converter(sm, { isJSON: true });
  }
  exports2.fromMapFileComment = function(comment, read2) {
    if (typeof read2 === "string") {
      throw new Error(
        "String directory paths are no longer supported with `fromMapFileComment`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"
      );
    }
    var sm = readFromFileMap(comment, read2);
    if (sm != null && typeof sm.then === "function") {
      return sm.then(makeConverter);
    } else {
      return makeConverter(sm);
    }
  };
  exports2.fromSource = function(content) {
    var m = content.match(exports2.commentRegex);
    return m ? exports2.fromComment(m.pop()) : null;
  };
  exports2.fromMapFileSource = function(content, read2) {
    if (typeof read2 === "string") {
      throw new Error(
        "String directory paths are no longer supported with `fromMapFileSource`\nPlease review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading"
      );
    }
    var m = content.match(exports2.mapFileCommentRegex);
    return m ? exports2.fromMapFileComment(m.pop(), read2) : null;
  };
  exports2.removeComments = function(src2) {
    return src2.replace(exports2.commentRegex, "");
  };
  exports2.removeMapFileComments = function(src2) {
    return src2.replace(exports2.mapFileCommentRegex, "");
  };
  exports2.generateMapFileComment = function(file, options2) {
    var data = "sourceMappingURL=" + file;
    return options2 && options2.multiline ? "/*# " + data + " */" : "//# " + data;
  };
})(convertSourceMap$1);
var convertSourceMap = getDefaultExportFromCjs(convertSourceMap$1);
var debug$g = createDebugger("vite:sourcemap", {
  onlyWhenFocused: true
});
var virtualSourceRE = /^(?:dep:|browser-external:|virtual:)|\0/;
async function computeSourceRoute(map2, file) {
  let sourceRoot;
  try {
    sourceRoot = await import_promises.default.realpath(
      import_node_path3.default.resolve(import_node_path3.default.dirname(file), map2.sourceRoot || "")
    );
  } catch {
  }
  return sourceRoot;
}
async function injectSourcesContent(map2, file, logger) {
  let sourceRootPromise;
  const missingSources = [];
  const sourcesContent = map2.sourcesContent || [];
  const sourcesContentPromises = [];
  for (let index = 0; index < map2.sources.length; index++) {
    const sourcePath = map2.sources[index];
    if (sourcesContent[index] == null && sourcePath && !virtualSourceRE.test(sourcePath)) {
      sourcesContentPromises.push(
        (async () => {
          sourceRootPromise ?? (sourceRootPromise = computeSourceRoute(map2, file));
          const sourceRoot = await sourceRootPromise;
          let resolvedSourcePath = cleanUrl(decodeURI(sourcePath));
          if (sourceRoot) {
            resolvedSourcePath = import_node_path3.default.resolve(sourceRoot, resolvedSourcePath);
          }
          sourcesContent[index] = await import_promises.default.readFile(resolvedSourcePath, "utf-8").catch(() => {
            missingSources.push(resolvedSourcePath);
            return null;
          });
        })()
      );
    }
  }
  await Promise.all(sourcesContentPromises);
  map2.sourcesContent = sourcesContent;
  if (missingSources.length) {
    logger.warnOnce(`Sourcemap for "${file}" points to missing source files`);
    debug$g == null ? void 0 : debug$g(`Missing sources:
  ` + missingSources.join(`
  `));
  }
}
function genSourceMapUrl(map2) {
  if (typeof map2 !== "string") {
    map2 = JSON.stringify(map2);
  }
  return `data:application/json;base64,${Buffer.from(map2).toString("base64")}`;
}
function getCodeWithSourcemap(type, code, map2) {
  if (debug$g) {
    code += `
/*${JSON.stringify(map2, null, 2).replace(/\*\//g, "*\\/")}*/
`;
  }
  if (type === "js") {
    code += `
//# sourceMappingURL=${genSourceMapUrl(map2)}`;
  } else if (type === "css") {
    code += `
/*# sourceMappingURL=${genSourceMapUrl(map2)} */`;
  }
  return code;
}
function applySourcemapIgnoreList(map2, sourcemapPath, sourcemapIgnoreList, logger) {
  let { x_google_ignoreList } = map2;
  if (x_google_ignoreList === void 0) {
    x_google_ignoreList = [];
  }
  for (let sourcesIndex = 0; sourcesIndex < map2.sources.length; ++sourcesIndex) {
    const sourcePath = map2.sources[sourcesIndex];
    if (!sourcePath) continue;
    const ignoreList = sourcemapIgnoreList(
      import_node_path3.default.isAbsolute(sourcePath) ? sourcePath : import_node_path3.default.resolve(import_node_path3.default.dirname(sourcemapPath), sourcePath),
      sourcemapPath
    );
    if (logger && typeof ignoreList !== "boolean") {
      logger.warn("sourcemapIgnoreList function must return a boolean.");
    }
    if (ignoreList && !x_google_ignoreList.includes(sourcesIndex)) {
      x_google_ignoreList.push(sourcesIndex);
    }
  }
  if (x_google_ignoreList.length > 0) {
    if (!map2.x_google_ignoreList) map2.x_google_ignoreList = x_google_ignoreList;
  }
}
async function extractSourcemapFromFile(code, filePath) {
  var _a4;
  const map2 = (_a4 = convertSourceMap.fromSource(code) || await convertSourceMap.fromMapFileSource(
    code,
    createConvertSourceMapReadMap(filePath)
  )) == null ? void 0 : _a4.toObject();
  if (map2) {
    return {
      code: code.replace(convertSourceMap.mapFileCommentRegex, blankReplacer),
      map: map2
    };
  }
}
function createConvertSourceMapReadMap(originalFileName) {
  return (filename) => {
    return import_promises.default.readFile(
      import_node_path3.default.resolve(import_node_path3.default.dirname(originalFileName), filename),
      "utf-8"
    );
  };
}
var tasks = {};
var utils$g = {};
var array$1 = {};
Object.defineProperty(array$1, "__esModule", { value: true });
array$1.splitWhen = array$1.flatten = void 0;
function flatten$1(items) {
  return items.reduce((collection, item) => [].concat(collection, item), []);
}
array$1.flatten = flatten$1;
function splitWhen(items, predicate) {
  const result = [[]];
  let groupIndex = 0;
  for (const item of items) {
    if (predicate(item)) {
      groupIndex++;
      result[groupIndex] = [];
    } else {
      result[groupIndex].push(item);
    }
  }
  return result;
}
array$1.splitWhen = splitWhen;
var errno$1 = {};
Object.defineProperty(errno$1, "__esModule", { value: true });
errno$1.isEnoentCodeError = void 0;
function isEnoentCodeError(error2) {
  return error2.code === "ENOENT";
}
errno$1.isEnoentCodeError = isEnoentCodeError;
var fs$i = {};
Object.defineProperty(fs$i, "__esModule", { value: true });
fs$i.createDirentFromStats = void 0;
var DirentFromStats$1 = class DirentFromStats {
  constructor(name2, stats) {
    this.name = name2;
    this.isBlockDevice = stats.isBlockDevice.bind(stats);
    this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
    this.isDirectory = stats.isDirectory.bind(stats);
    this.isFIFO = stats.isFIFO.bind(stats);
    this.isFile = stats.isFile.bind(stats);
    this.isSocket = stats.isSocket.bind(stats);
    this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  }
};
function createDirentFromStats$1(name2, stats) {
  return new DirentFromStats$1(name2, stats);
}
fs$i.createDirentFromStats = createDirentFromStats$1;
var path$i = {};
Object.defineProperty(path$i, "__esModule", { value: true });
path$i.convertPosixPathToPattern = path$i.convertWindowsPathToPattern = path$i.convertPathToPattern = path$i.escapePosixPath = path$i.escapeWindowsPath = path$i.escape = path$i.removeLeadingDotSegment = path$i.makeAbsolute = path$i.unixify = void 0;
var os$4 = import_os.default;
var path$h = import_path.default;
var IS_WINDOWS_PLATFORM = os$4.platform() === "win32";
var LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2;
var POSIX_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g;
var WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()[\]{}]|^!|[!+@](?=\())/g;
var DOS_DEVICE_PATH_RE = /^\\\\([.?])/;
var WINDOWS_BACKSLASHES_RE = /\\(?![!()+@[\]{}])/g;
function unixify(filepath) {
  return filepath.replace(/\\/g, "/");
}
path$i.unixify = unixify;
function makeAbsolute(cwd, filepath) {
  return path$h.resolve(cwd, filepath);
}
path$i.makeAbsolute = makeAbsolute;
function removeLeadingDotSegment(entry2) {
  if (entry2.charAt(0) === ".") {
    const secondCharactery = entry2.charAt(1);
    if (secondCharactery === "/" || secondCharactery === "\\") {
      return entry2.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
    }
  }
  return entry2;
}
path$i.removeLeadingDotSegment = removeLeadingDotSegment;
path$i.escape = IS_WINDOWS_PLATFORM ? escapeWindowsPath : escapePosixPath;
function escapeWindowsPath(pattern2) {
  return pattern2.replace(WINDOWS_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2");
}
path$i.escapeWindowsPath = escapeWindowsPath;
function escapePosixPath(pattern2) {
  return pattern2.replace(POSIX_UNESCAPED_GLOB_SYMBOLS_RE, "\\$2");
}
path$i.escapePosixPath = escapePosixPath;
path$i.convertPathToPattern = IS_WINDOWS_PLATFORM ? convertWindowsPathToPattern : convertPosixPathToPattern;
function convertWindowsPathToPattern(filepath) {
  return escapeWindowsPath(filepath).replace(DOS_DEVICE_PATH_RE, "//$1").replace(WINDOWS_BACKSLASHES_RE, "/");
}
path$i.convertWindowsPathToPattern = convertWindowsPathToPattern;
function convertPosixPathToPattern(filepath) {
  return escapePosixPath(filepath);
}
path$i.convertPosixPathToPattern = convertPosixPathToPattern;
var pattern$1 = {};
var isExtglob$1 = function isExtglob(str) {
  if (typeof str !== "string" || str === "") {
    return false;
  }
  var match2;
  while (match2 = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
    if (match2[2]) return true;
    str = str.slice(match2.index + match2[0].length);
  }
  return false;
};
var isExtglob2 = isExtglob$1;
var chars = { "{": "}", "(": ")", "[": "]" };
var strictCheck = function(str) {
  if (str[0] === "!") {
    return true;
  }
  var index = 0;
  var pipeIndex = -2;
  var closeSquareIndex = -2;
  var closeCurlyIndex = -2;
  var closeParenIndex = -2;
  var backSlashIndex = -2;
  while (index < str.length) {
    if (str[index] === "*") {
      return true;
    }
    if (str[index + 1] === "?" && /[\].+)]/.test(str[index])) {
      return true;
    }
    if (closeSquareIndex !== -1 && str[index] === "[" && str[index + 1] !== "]") {
      if (closeSquareIndex < index) {
        closeSquareIndex = str.indexOf("]", index);
      }
      if (closeSquareIndex > index) {
        if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
          return true;
        }
        backSlashIndex = str.indexOf("\\", index);
        if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
          return true;
        }
      }
    }
    if (closeCurlyIndex !== -1 && str[index] === "{" && str[index + 1] !== "}") {
      closeCurlyIndex = str.indexOf("}", index);
      if (closeCurlyIndex > index) {
        backSlashIndex = str.indexOf("\\", index);
        if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
          return true;
        }
      }
    }
    if (closeParenIndex !== -1 && str[index] === "(" && str[index + 1] === "?" && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ")") {
      closeParenIndex = str.indexOf(")", index);
      if (closeParenIndex > index) {
        backSlashIndex = str.indexOf("\\", index);
        if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
          return true;
        }
      }
    }
    if (pipeIndex !== -1 && str[index] === "(" && str[index + 1] !== "|") {
      if (pipeIndex < index) {
        pipeIndex = str.indexOf("|", index);
      }
      if (pipeIndex !== -1 && str[pipeIndex + 1] !== ")") {
        closeParenIndex = str.indexOf(")", pipeIndex);
        if (closeParenIndex > pipeIndex) {
          backSlashIndex = str.indexOf("\\", pipeIndex);
          if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
            return true;
          }
        }
      }
    }
    if (str[index] === "\\") {
      var open2 = str[index + 1];
      index += 2;
      var close2 = chars[open2];
      if (close2) {
        var n2 = str.indexOf(close2, index);
        if (n2 !== -1) {
          index = n2 + 1;
        }
      }
      if (str[index] === "!") {
        return true;
      }
    } else {
      index++;
    }
  }
  return false;
};
var relaxedCheck = function(str) {
  if (str[0] === "!") {
    return true;
  }
  var index = 0;
  while (index < str.length) {
    if (/[*?{}()[\]]/.test(str[index])) {
      return true;
    }
    if (str[index] === "\\") {
      var open2 = str[index + 1];
      index += 2;
      var close2 = chars[open2];
      if (close2) {
        var n2 = str.indexOf(close2, index);
        if (n2 !== -1) {
          index = n2 + 1;
        }
      }
      if (str[index] === "!") {
        return true;
      }
    } else {
      index++;
    }
  }
  return false;
};
var isGlob$2 = function isGlob(str, options2) {
  if (typeof str !== "string" || str === "") {
    return false;
  }
  if (isExtglob2(str)) {
    return true;
  }
  var check = strictCheck;
  if (options2 && options2.strict === false) {
    check = relaxedCheck;
  }
  return check(str);
};
var isGlob$1 = isGlob$2;
var pathPosixDirname = import_path.default.posix.dirname;
var isWin32 = import_os.default.platform() === "win32";
var slash = "/";
var backslash = /\\/g;
var enclosure = /[\{\[].*[\}\]]$/;
var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
var globParent$2 = function globParent(str, opts) {
  var options2 = Object.assign({ flipBackslashes: true }, opts);
  if (options2.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
    str = str.replace(backslash, slash);
  }
  if (enclosure.test(str)) {
    str += slash;
  }
  str += "a";
  do {
    str = pathPosixDirname(str);
  } while (isGlob$1(str) || globby.test(str));
  return str.replace(escaped, "$1");
};
var utils$f = {};
(function(exports2) {
  exports2.isInteger = (num) => {
    if (typeof num === "number") {
      return Number.isInteger(num);
    }
    if (typeof num === "string" && num.trim() !== "") {
      return Number.isInteger(Number(num));
    }
    return false;
  };
  exports2.find = (node2, type) => node2.nodes.find((node3) => node3.type === type);
  exports2.exceedsLimit = (min2, max, step = 1, limit) => {
    if (limit === false) return false;
    if (!exports2.isInteger(min2) || !exports2.isInteger(max)) return false;
    return (Number(max) - Number(min2)) / Number(step) >= limit;
  };
  exports2.escapeNode = (block, n2 = 0, type) => {
    const node2 = block.nodes[n2];
    if (!node2) return;
    if (type && node2.type === type || node2.type === "open" || node2.type === "close") {
      if (node2.escaped !== true) {
        node2.value = "\\" + node2.value;
        node2.escaped = true;
      }
    }
  };
  exports2.encloseBrace = (node2) => {
    if (node2.type !== "brace") return false;
    if (node2.commas >> 0 + node2.ranges >> 0 === 0) {
      node2.invalid = true;
      return true;
    }
    return false;
  };
  exports2.isInvalidBrace = (block) => {
    if (block.type !== "brace") return false;
    if (block.invalid === true || block.dollar) return true;
    if (block.commas >> 0 + block.ranges >> 0 === 0) {
      block.invalid = true;
      return true;
    }
    if (block.open !== true || block.close !== true) {
      block.invalid = true;
      return true;
    }
    return false;
  };
  exports2.isOpenOrClose = (node2) => {
    if (node2.type === "open" || node2.type === "close") {
      return true;
    }
    return node2.open === true || node2.close === true;
  };
  exports2.reduce = (nodes) => nodes.reduce((acc, node2) => {
    if (node2.type === "text") acc.push(node2.value);
    if (node2.type === "range") node2.type = "text";
    return acc;
  }, []);
  exports2.flatten = (...args) => {
    const result = [];
    const flat = (arr) => {
      for (let i = 0; i < arr.length; i++) {
        const ele = arr[i];
        if (Array.isArray(ele)) {
          flat(ele);
          continue;
        }
        if (ele !== void 0) {
          result.push(ele);
        }
      }
      return result;
    };
    flat(args);
    return result;
  };
})(utils$f);
var utils$e = utils$f;
var stringify$7 = (ast, options2 = {}) => {
  const stringify2 = (node2, parent = {}) => {
    const invalidBlock = options2.escapeInvalid && utils$e.isInvalidBrace(parent);
    const invalidNode = node2.invalid === true && options2.escapeInvalid === true;
    let output = "";
    if (node2.value) {
      if ((invalidBlock || invalidNode) && utils$e.isOpenOrClose(node2)) {
        return "\\" + node2.value;
      }
      return node2.value;
    }
    if (node2.value) {
      return node2.value;
    }
    if (node2.nodes) {
      for (const child of node2.nodes) {
        output += stringify2(child);
      }
    }
    return output;
  };
  return stringify2(ast);
};
var isNumber$2 = function(num) {
  if (typeof num === "number") {
    return num - num === 0;
  }
  if (typeof num === "string" && num.trim() !== "") {
    return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
  }
  return false;
};
var isNumber$1 = isNumber$2;
var toRegexRange$1 = (min2, max, options2) => {
  if (isNumber$1(min2) === false) {
    throw new TypeError("toRegexRange: expected the first argument to be a number");
  }
  if (max === void 0 || min2 === max) {
    return String(min2);
  }
  if (isNumber$1(max) === false) {
    throw new TypeError("toRegexRange: expected the second argument to be a number.");
  }
  let opts = { relaxZeros: true, ...options2 };
  if (typeof opts.strictZeros === "boolean") {
    opts.relaxZeros = opts.strictZeros === false;
  }
  let relax = String(opts.relaxZeros);
  let shorthand = String(opts.shorthand);
  let capture = String(opts.capture);
  let wrap2 = String(opts.wrap);
  let cacheKey = min2 + ":" + max + "=" + relax + shorthand + capture + wrap2;
  if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
    return toRegexRange$1.cache[cacheKey].result;
  }
  let a = Math.min(min2, max);
  let b = Math.max(min2, max);
  if (Math.abs(a - b) === 1) {
    let result = min2 + "|" + max;
    if (opts.capture) {
      return `(${result})`;
    }
    if (opts.wrap === false) {
      return result;
    }
    return `(?:${result})`;
  }
  let isPadded2 = hasPadding(min2) || hasPadding(max);
  let state = { min: min2, max, a, b };
  let positives = [];
  let negatives = [];
  if (isPadded2) {
    state.isPadded = isPadded2;
    state.maxLen = String(state.max).length;
  }
  if (a < 0) {
    let newMin = b < 0 ? Math.abs(b) : 1;
    negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
    a = state.a = 0;
  }
  if (b >= 0) {
    positives = splitToPatterns(a, b, state, opts);
  }
  state.negatives = negatives;
  state.positives = positives;
  state.result = collatePatterns(negatives, positives);
  if (opts.capture === true) {
    state.result = `(${state.result})`;
  } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
    state.result = `(?:${state.result})`;
  }
  toRegexRange$1.cache[cacheKey] = state;
  return state.result;
};
function collatePatterns(neg, pos, options2) {
  let onlyNegative = filterPatterns(neg, pos, "-", false) || [];
  let onlyPositive = filterPatterns(pos, neg, "", false) || [];
  let intersected = filterPatterns(neg, pos, "-?", true) || [];
  let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
  return subpatterns.join("|");
}
function splitToRanges(min2, max) {
  let nines = 1;
  let zeros2 = 1;
  let stop = countNines(min2, nines);
  let stops = /* @__PURE__ */ new Set([max]);
  while (min2 <= stop && stop <= max) {
    stops.add(stop);
    nines += 1;
    stop = countNines(min2, nines);
  }
  stop = countZeros(max + 1, zeros2) - 1;
  while (min2 < stop && stop <= max) {
    stops.add(stop);
    zeros2 += 1;
    stop = countZeros(max + 1, zeros2) - 1;
  }
  stops = [...stops];
  stops.sort(compare);
  return stops;
}
function rangeToPattern(start, stop, options2) {
  if (start === stop) {
    return { pattern: start, count: [], digits: 0 };
  }
  let zipped = zip(start, stop);
  let digits = zipped.length;
  let pattern2 = "";
  let count = 0;
  for (let i = 0; i < digits; i++) {
    let [startDigit, stopDigit] = zipped[i];
    if (startDigit === stopDigit) {
      pattern2 += startDigit;
    } else if (startDigit !== "0" || stopDigit !== "9") {
      pattern2 += toCharacterClass(startDigit, stopDigit);
    } else {
      count++;
    }
  }
  if (count) {
    pattern2 += options2.shorthand === true ? "\\d" : "[0-9]";
  }
  return { pattern: pattern2, count: [count], digits };
}
function splitToPatterns(min2, max, tok, options2) {
  let ranges = splitToRanges(min2, max);
  let tokens = [];
  let start = min2;
  let prev;
  for (let i = 0; i < ranges.length; i++) {
    let max2 = ranges[i];
    let obj = rangeToPattern(String(start), String(max2), options2);
    let zeros2 = "";
    if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
      if (prev.count.length > 1) {
        prev.count.pop();
      }
      prev.count.push(obj.count[0]);
      prev.string = prev.pattern + toQuantifier(prev.count);
      start = max2 + 1;
      continue;
    }
    if (tok.isPadded) {
      zeros2 = padZeros(max2, tok, options2);
    }
    obj.string = zeros2 + obj.pattern + toQuantifier(obj.count);
    tokens.push(obj);
    start = max2 + 1;
    prev = obj;
  }
  return tokens;
}
function filterPatterns(arr, comparison, prefix, intersection, options2) {
  let result = [];
  for (let ele of arr) {
    let { string: string2 } = ele;
    if (!intersection && !contains(comparison, "string", string2)) {
      result.push(prefix + string2);
    }
    if (intersection && contains(comparison, "string", string2)) {
      result.push(prefix + string2);
    }
  }
  return result;
}
function zip(a, b) {
  let arr = [];
  for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
  return arr;
}
function compare(a, b) {
  return a > b ? 1 : b > a ? -1 : 0;
}
function contains(arr, key, val) {
  return arr.some((ele) => ele[key] === val);
}
function countNines(min2, len) {
  return Number(String(min2).slice(0, -len) + "9".repeat(len));
}
function countZeros(integer, zeros2) {
  return integer - integer % Math.pow(10, zeros2);
}
function toQuantifier(digits) {
  let [start = 0, stop = ""] = digits;
  if (stop || start > 1) {
    return `{${start + (stop ? "," + stop : "")}}`;
  }
  return "";
}
function toCharacterClass(a, b, options2) {
  return `[${a}${b - a === 1 ? "" : "-"}${b}]`;
}
function hasPadding(str) {
  return /^-?(0+)\d/.test(str);
}
function padZeros(value2, tok, options2) {
  if (!tok.isPadded) {
    return value2;
  }
  let diff = Math.abs(tok.maxLen - String(value2).length);
  let relax = options2.relaxZeros !== false;
  switch (diff) {
    case 0:
      return "";
    case 1:
      return relax ? "0?" : "0";
    case 2:
      return relax ? "0{0,2}" : "00";
    default: {
      return relax ? `0{0,${diff}}` : `0{${diff}}`;
    }
  }
}
toRegexRange$1.cache = {};
toRegexRange$1.clearCache = () => toRegexRange$1.cache = {};
var toRegexRange_1 = toRegexRange$1;
var util$1 = import_util.default;
var toRegexRange = toRegexRange_1;
var isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
var transform = (toNumber) => {
  return (value2) => toNumber === true ? Number(value2) : String(value2);
};
var isValidValue = (value2) => {
  return typeof value2 === "number" || typeof value2 === "string" && value2 !== "";
};
var isNumber = (num) => Number.isInteger(+num);
var zeros = (input) => {
  let value2 = `${input}`;
  let index = -1;
  if (value2[0] === "-") value2 = value2.slice(1);
  if (value2 === "0") return false;
  while (value2[++index] === "0") ;
  return index > 0;
};
var stringify$6 = (start, end, options2) => {
  if (typeof start === "string" || typeof end === "string") {
    return true;
  }
  return options2.stringify === true;
};
var pad = (input, maxLength, toNumber) => {
  if (maxLength > 0) {
    let dash = input[0] === "-" ? "-" : "";
    if (dash) input = input.slice(1);
    input = dash + input.padStart(dash ? maxLength - 1 : maxLength, "0");
  }
  if (toNumber === false) {
    return String(input);
  }
  return input;
};
var toMaxLen = (input, maxLength) => {
  let negative = input[0] === "-" ? "-" : "";
  if (negative) {
    input = input.slice(1);
    maxLength--;
  }
  while (input.length < maxLength) input = "0" + input;
  return negative ? "-" + input : input;
};
var toSequence = (parts, options2, maxLen) => {
  parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
  let prefix = options2.capture ? "" : "?:";
  let positives = "";
  let negatives = "";
  let result;
  if (parts.positives.length) {
    positives = parts.positives.map((v) => toMaxLen(String(v), maxLen)).join("|");
  }
  if (parts.negatives.length) {
    negatives = `-(${prefix}${parts.negatives.map((v) => toMaxLen(String(v), maxLen)).join("|")})`;
  }
  if (positives && negatives) {
    result = `${positives}|${negatives}`;
  } else {
    result = positives || negatives;
  }
  if (options2.wrap) {
    return `(${prefix}${result})`;
  }
  return result;
};
var toRange = (a, b, isNumbers, options2) => {
  if (isNumbers) {
    return toRegexRange(a, b, { wrap: false, ...options2 });
  }
  let start = String.fromCharCode(a);
  if (a === b) return start;
  let stop = String.fromCharCode(b);
  return `[${start}-${stop}]`;
};
var toRegex = (start, end, options2) => {
  if (Array.isArray(start)) {
    let wrap2 = options2.wrap === true;
    let prefix = options2.capture ? "" : "?:";
    return wrap2 ? `(${prefix}${start.join("|")})` : start.join("|");
  }
  return toRegexRange(start, end, options2);
};
var rangeError = (...args) => {
  return new RangeError("Invalid range arguments: " + util$1.inspect(...args));
};
var invalidRange = (start, end, options2) => {
  if (options2.strictRanges === true) throw rangeError([start, end]);
  return [];
};
var invalidStep = (step, options2) => {
  if (options2.strictRanges === true) {
    throw new TypeError(`Expected step "${step}" to be a number`);
  }
  return [];
};
var fillNumbers = (start, end, step = 1, options2 = {}) => {
  let a = Number(start);
  let b = Number(end);
  if (!Number.isInteger(a) || !Number.isInteger(b)) {
    if (options2.strictRanges === true) throw rangeError([start, end]);
    return [];
  }
  if (a === 0) a = 0;
  if (b === 0) b = 0;
  let descending = a > b;
  let startString = String(start);
  let endString = String(end);
  let stepString = String(step);
  step = Math.max(Math.abs(step), 1);
  let padded = zeros(startString) || zeros(endString) || zeros(stepString);
  let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
  let toNumber = padded === false && stringify$6(start, end, options2) === false;
  let format2 = options2.transform || transform(toNumber);
  if (options2.toRegex && step === 1) {
    return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options2);
  }
  let parts = { negatives: [], positives: [] };
  let push2 = (num) => parts[num < 0 ? "negatives" : "positives"].push(Math.abs(num));
  let range2 = [];
  let index = 0;
  while (descending ? a >= b : a <= b) {
    if (options2.toRegex === true && step > 1) {
      push2(a);
    } else {
      range2.push(pad(format2(a, index), maxLen, toNumber));
    }
    a = descending ? a - step : a + step;
    index++;
  }
  if (options2.toRegex === true) {
    return step > 1 ? toSequence(parts, options2, maxLen) : toRegex(range2, null, { wrap: false, ...options2 });
  }
  return range2;
};
var fillLetters = (start, end, step = 1, options2 = {}) => {
  if (!isNumber(start) && start.length > 1 || !isNumber(end) && end.length > 1) {
    return invalidRange(start, end, options2);
  }
  let format2 = options2.transform || ((val) => String.fromCharCode(val));
  let a = `${start}`.charCodeAt(0);
  let b = `${end}`.charCodeAt(0);
  let descending = a > b;
  let min2 = Math.min(a, b);
  let max = Math.max(a, b);
  if (options2.toRegex && step === 1) {
    return toRange(min2, max, false, options2);
  }
  let range2 = [];
  let index = 0;
  while (descending ? a >= b : a <= b) {
    range2.push(format2(a, index));
    a = descending ? a - step : a + step;
    index++;
  }
  if (options2.toRegex === true) {
    return toRegex(range2, null, { wrap: false, options: options2 });
  }
  return range2;
};
var fill$2 = (start, end, step, options2 = {}) => {
  if (end == null && isValidValue(start)) {
    return [start];
  }
  if (!isValidValue(start) || !isValidValue(end)) {
    return invalidRange(start, end, options2);
  }
  if (typeof step === "function") {
    return fill$2(start, end, 1, { transform: step });
  }
  if (isObject(step)) {
    return fill$2(start, end, 0, step);
  }
  let opts = { ...options2 };
  if (opts.capture === true) opts.wrap = true;
  step = step || opts.step || 1;
  if (!isNumber(step)) {
    if (step != null && !isObject(step)) return invalidStep(step, opts);
    return fill$2(start, end, 1, step);
  }
  if (isNumber(start) && isNumber(end)) {
    return fillNumbers(start, end, step, opts);
  }
  return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
};
var fillRange = fill$2;
var fill$1 = fillRange;
var utils$d = utils$f;
var compile$1 = (ast, options2 = {}) => {
  const walk2 = (node2, parent = {}) => {
    const invalidBlock = utils$d.isInvalidBrace(parent);
    const invalidNode = node2.invalid === true && options2.escapeInvalid === true;
    const invalid = invalidBlock === true || invalidNode === true;
    const prefix = options2.escapeInvalid === true ? "\\" : "";
    let output = "";
    if (node2.isOpen === true) {
      return prefix + node2.value;
    }
    if (node2.isClose === true) {
      console.log("node.isClose", prefix, node2.value);
      return prefix + node2.value;
    }
    if (node2.type === "open") {
      return invalid ? prefix + node2.value : "(";
    }
    if (node2.type === "close") {
      return invalid ? prefix + node2.value : ")";
    }
    if (node2.type === "comma") {
      return node2.prev.type === "comma" ? "" : invalid ? node2.value : "|";
    }
    if (node2.value) {
      return node2.value;
    }
    if (node2.nodes && node2.ranges > 0) {
      const args = utils$d.reduce(node2.nodes);
      const range2 = fill$1(...args, { ...options2, wrap: false, toRegex: true, strictZeros: true });
      if (range2.length !== 0) {
        return args.length > 1 && range2.length > 1 ? `(${range2})` : range2;
      }
    }
    if (node2.nodes) {
      for (const child of node2.nodes) {
        output += walk2(child, node2);
      }
    }
    return output;
  };
  return walk2(ast);
};
var compile_1 = compile$1;
var fill = fillRange;
var stringify$5 = stringify$7;
var utils$c = utils$f;
var append$1 = (queue2 = "", stash = "", enclose = false) => {
  const result = [];
  queue2 = [].concat(queue2);
  stash = [].concat(stash);
  if (!stash.length) return queue2;
  if (!queue2.length) {
    return enclose ? utils$c.flatten(stash).map((ele) => `{${ele}}`) : stash;
  }
  for (const item of queue2) {
    if (Array.isArray(item)) {
      for (const value2 of item) {
        result.push(append$1(value2, stash, enclose));
      }
    } else {
      for (let ele of stash) {
        if (enclose === true && typeof ele === "string") ele = `{${ele}}`;
        result.push(Array.isArray(ele) ? append$1(item, ele, enclose) : item + ele);
      }
    }
  }
  return utils$c.flatten(result);
};
var expand$2 = (ast, options2 = {}) => {
  const rangeLimit = options2.rangeLimit === void 0 ? 1e3 : options2.rangeLimit;
  const walk2 = (node2, parent = {}) => {
    node2.queue = [];
    let p = parent;
    let q = parent.queue;
    while (p.type !== "brace" && p.type !== "root" && p.parent) {
      p = p.parent;
      q = p.queue;
    }
    if (node2.invalid || node2.dollar) {
      q.push(append$1(q.pop(), stringify$5(node2, options2)));
      return;
    }
    if (node2.type === "brace" && node2.invalid !== true && node2.nodes.length === 2) {
      q.push(append$1(q.pop(), ["{}"]));
      return;
    }
    if (node2.nodes && node2.ranges > 0) {
      const args = utils$c.reduce(node2.nodes);
      if (utils$c.exceedsLimit(...args, options2.step, rangeLimit)) {
        throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");
      }
      let range2 = fill(...args, options2);
      if (range2.length === 0) {
        range2 = stringify$5(node2, options2);
      }
      q.push(append$1(q.pop(), range2));
      node2.nodes = [];
      return;
    }
    const enclose = utils$c.encloseBrace(node2);
    let queue2 = node2.queue;
    let block = node2;
    while (block.type !== "brace" && block.type !== "root" && block.parent) {
      block = block.parent;
      queue2 = block.queue;
    }
    for (let i = 0; i < node2.nodes.length; i++) {
      const child = node2.nodes[i];
      if (child.type === "comma" && node2.type === "brace") {
        if (i === 1) queue2.push("");
        queue2.push("");
        continue;
      }
      if (child.type === "close") {
        q.push(append$1(q.pop(), queue2, enclose));
        continue;
      }
      if (child.value && child.type !== "open") {
        queue2.push(append$1(queue2.pop(), child.value));
        continue;
      }
      if (child.nodes) {
        walk2(child, node2);
      }
    }
    return queue2;
  };
  return utils$c.flatten(walk2(ast));
};
var expand_1$1 = expand$2;
var constants$3 = {
  MAX_LENGTH: 1e4,
  // Digits
  CHAR_0: "0",
  /* 0 */
  CHAR_9: "9",
  /* 9 */
  // Alphabet chars.
  CHAR_UPPERCASE_A: "A",
  /* A */
  CHAR_LOWERCASE_A: "a",
  /* a */
  CHAR_UPPERCASE_Z: "Z",
  /* Z */
  CHAR_LOWERCASE_Z: "z",
  /* z */
  CHAR_LEFT_PARENTHESES: "(",
  /* ( */
  CHAR_RIGHT_PARENTHESES: ")",
  /* ) */
  CHAR_ASTERISK: "*",
  /* * */
  // Non-alphabetic chars.
  CHAR_AMPERSAND: "&",
  /* & */
  CHAR_AT: "@",
  /* @ */
  CHAR_BACKSLASH: "\\",
  /* \ */
  CHAR_BACKTICK: "`",
  /* ` */
  CHAR_CARRIAGE_RETURN: "\r",
  /* \r */
  CHAR_CIRCUMFLEX_ACCENT: "^",
  /* ^ */
  CHAR_COLON: ":",
  /* : */
  CHAR_COMMA: ",",
  /* , */
  CHAR_DOLLAR: "$",
  /* . */
  CHAR_DOT: ".",
  /* . */
  CHAR_DOUBLE_QUOTE: '"',
  /* " */
  CHAR_EQUAL: "=",
  /* = */
  CHAR_EXCLAMATION_MARK: "!",
  /* ! */
  CHAR_FORM_FEED: "\f",
  /* \f */
  CHAR_FORWARD_SLASH: "/",
  /* / */
  CHAR_HASH: "#",
  /* # */
  CHAR_HYPHEN_MINUS: "-",
  /* - */
  CHAR_LEFT_ANGLE_BRACKET: "<",
  /* < */
  CHAR_LEFT_CURLY_BRACE: "{",
  /* { */
  CHAR_LEFT_SQUARE_BRACKET: "[",
  /* [ */
  CHAR_LINE_FEED: "\n",
  /* \n */
  CHAR_NO_BREAK_SPACE: " ",
  /* \u00A0 */
  CHAR_PERCENT: "%",
  /* % */
  CHAR_PLUS: "+",
  /* + */
  CHAR_QUESTION_MARK: "?",
  /* ? */
  CHAR_RIGHT_ANGLE_BRACKET: ">",
  /* > */
  CHAR_RIGHT_CURLY_BRACE: "}",
  /* } */
  CHAR_RIGHT_SQUARE_BRACKET: "]",
  /* ] */
  CHAR_SEMICOLON: ";",
  /* ; */
  CHAR_SINGLE_QUOTE: "'",
  /* ' */
  CHAR_SPACE: " ",
  /*   */
  CHAR_TAB: "	",
  /* \t */
  CHAR_UNDERSCORE: "_",
  /* _ */
  CHAR_VERTICAL_LINE: "|",
  /* | */
  CHAR_ZERO_WIDTH_NOBREAK_SPACE: "\uFEFF"
  /* \uFEFF */
};
var stringify$4 = stringify$7;
var {
  MAX_LENGTH,
  CHAR_BACKSLASH,
  /* \ */
  CHAR_BACKTICK,
  /* ` */
  CHAR_COMMA,
  /* , */
  CHAR_DOT,
  /* . */
  CHAR_LEFT_PARENTHESES,
  /* ( */
  CHAR_RIGHT_PARENTHESES,
  /* ) */
  CHAR_LEFT_CURLY_BRACE,
  /* { */
  CHAR_RIGHT_CURLY_BRACE,
  /* } */
  CHAR_LEFT_SQUARE_BRACKET,
  /* [ */
  CHAR_RIGHT_SQUARE_BRACKET,
  /* ] */
  CHAR_DOUBLE_QUOTE,
  /* " */
  CHAR_SINGLE_QUOTE,
  /* ' */
  CHAR_NO_BREAK_SPACE,
  CHAR_ZERO_WIDTH_NOBREAK_SPACE
} = constants$3;
var parse$c = (input, options2 = {}) => {
  if (typeof input !== "string") {
    throw new TypeError("Expected a string");
  }
  const opts = options2 || {};
  const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  if (input.length > max) {
    throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  }
  const ast = { type: "root", input, nodes: [] };
  const stack = [ast];
  let block = ast;
  let prev = ast;
  let brackets = 0;
  const length = input.length;
  let index = 0;
  let depth2 = 0;
  let value2;
  const advance = () => input[index++];
  const push2 = (node2) => {
    if (node2.type === "text" && prev.type === "dot") {
      prev.type = "text";
    }
    if (prev && prev.type === "text" && node2.type === "text") {
      prev.value += node2.value;
      return;
    }
    block.nodes.push(node2);
    node2.parent = block;
    node2.prev = prev;
    prev = node2;
    return node2;
  };
  push2({ type: "bos" });
  while (index < length) {
    block = stack[stack.length - 1];
    value2 = advance();
    if (value2 === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value2 === CHAR_NO_BREAK_SPACE) {
      continue;
    }
    if (value2 === CHAR_BACKSLASH) {
      push2({ type: "text", value: (options2.keepEscaping ? value2 : "") + advance() });
      continue;
    }
    if (value2 === CHAR_RIGHT_SQUARE_BRACKET) {
      push2({ type: "text", value: "\\" + value2 });
      continue;
    }
    if (value2 === CHAR_LEFT_SQUARE_BRACKET) {
      brackets++;
      let next;
      while (index < length && (next = advance())) {
        value2 += next;
        if (next === CHAR_LEFT_SQUARE_BRACKET) {
          brackets++;
          continue;
        }
        if (next === CHAR_BACKSLASH) {
          value2 += advance();
          continue;
        }
        if (next === CHAR_RIGHT_SQUARE_BRACKET) {
          brackets--;
          if (brackets === 0) {
            break;
          }
        }
      }
      push2({ type: "text", value: value2 });
      continue;
    }
    if (value2 === CHAR_LEFT_PARENTHESES) {
      block = push2({ type: "paren", nodes: [] });
      stack.push(block);
      push2({ type: "text", value: value2 });
      continue;
    }
    if (value2 === CHAR_RIGHT_PARENTHESES) {
      if (block.type !== "paren") {
        push2({ type: "text", value: value2 });
        continue;
      }
      block = stack.pop();
      push2({ type: "text", value: value2 });
      block = stack[stack.length - 1];
      continue;
    }
    if (value2 === CHAR_DOUBLE_QUOTE || value2 === CHAR_SINGLE_QUOTE || value2 === CHAR_BACKTICK) {
      const open2 = value2;
      let next;
      if (options2.keepQuotes !== true) {
        value2 = "";
      }
      while (index < length && (next = advance())) {
        if (next === CHAR_BACKSLASH) {
          value2 += next + advance();
          continue;
        }
        if (next === open2) {
          if (options2.keepQuotes === true) value2 += next;
          break;
        }
        value2 += next;
      }
      push2({ type: "text", value: value2 });
      continue;
    }
    if (value2 === CHAR_LEFT_CURLY_BRACE) {
      depth2++;
      const dollar = prev.value && prev.value.slice(-1) === "$" || block.dollar === true;
      const brace = {
        type: "brace",
        open: true,
        close: false,
        dollar,
        depth: depth2,
        commas: 0,
        ranges: 0,
        nodes: []
      };
      block = push2(brace);
      stack.push(block);
      push2({ type: "open", value: value2 });
      continue;
    }
    if (value2 === CHAR_RIGHT_CURLY_BRACE) {
      if (block.type !== "brace") {
        push2({ type: "text", value: value2 });
        continue;
      }
      const type = "close";
      block = stack.pop();
      block.close = true;
      push2({ type, value: value2 });
      depth2--;
      block = stack[stack.length - 1];
      continue;
    }
    if (value2 === CHAR_COMMA && depth2 > 0) {
      if (block.ranges > 0) {
        block.ranges = 0;
        const open2 = block.nodes.shift();
        block.nodes = [open2, { type: "text", value: stringify$4(block) }];
      }
      push2({ type: "comma", value: value2 });
      block.commas++;
      continue;
    }
    if (value2 === CHAR_DOT && depth2 > 0 && block.commas === 0) {
      const siblings = block.nodes;
      if (depth2 === 0 || siblings.length === 0) {
        push2({ type: "text", value: value2 });
        continue;
      }
      if (prev.type === "dot") {
        block.range = [];
        prev.value += value2;
        prev.type = "range";
        if (block.nodes.length !== 3 && block.nodes.length !== 5) {
          block.invalid = true;
          block.ranges = 0;
          prev.type = "text";
          continue;
        }
        block.ranges++;
        block.args = [];
        continue;
      }
      if (prev.type === "range") {
        siblings.pop();
        const before = siblings[siblings.length - 1];
        before.value += prev.value + value2;
        prev = before;
        block.ranges--;
        continue;
      }
      push2({ type: "dot", value: value2 });
      continue;
    }
    push2({ type: "text", value: value2 });
  }
  do {
    block = stack.pop();
    if (block.type !== "root") {
      block.nodes.forEach((node2) => {
        if (!node2.nodes) {
          if (node2.type === "open") node2.isOpen = true;
          if (node2.type === "close") node2.isClose = true;
          if (!node2.nodes) node2.type = "text";
          node2.invalid = true;
        }
      });
      const parent = stack[stack.length - 1];
      const index2 = parent.nodes.indexOf(block);
      parent.nodes.splice(index2, 1, ...block.nodes);
    }
  } while (stack.length > 0);
  push2({ type: "eos" });
  return ast;
};
var parse_1$2 = parse$c;
var stringify$3 = stringify$7;
var compile = compile_1;
var expand$1 = expand_1$1;
var parse$b = parse_1$2;
var braces$2 = (input, options2 = {}) => {
  let output = [];
  if (Array.isArray(input)) {
    for (const pattern2 of input) {
      const result = braces$2.create(pattern2, options2);
      if (Array.isArray(result)) {
        output.push(...result);
      } else {
        output.push(result);
      }
    }
  } else {
    output = [].concat(braces$2.create(input, options2));
  }
  if (options2 && options2.expand === true && options2.nodupes === true) {
    output = [...new Set(output)];
  }
  return output;
};
braces$2.parse = (input, options2 = {}) => parse$b(input, options2);
braces$2.stringify = (input, options2 = {}) => {
  if (typeof input === "string") {
    return stringify$3(braces$2.parse(input, options2), options2);
  }
  return stringify$3(input, options2);
};
braces$2.compile = (input, options2 = {}) => {
  if (typeof input === "string") {
    input = braces$2.parse(input, options2);
  }
  return compile(input, options2);
};
braces$2.expand = (input, options2 = {}) => {
  if (typeof input === "string") {
    input = braces$2.parse(input, options2);
  }
  let result = expand$1(input, options2);
  if (options2.noempty === true) {
    result = result.filter(Boolean);
  }
  if (options2.nodupes === true) {
    result = [...new Set(result)];
  }
  return result;
};
braces$2.create = (input, options2 = {}) => {
  if (input === "" || input.length < 3) {
    return [input];
  }
  return options2.expand !== true ? braces$2.compile(input, options2) : braces$2.expand(input, options2);
};
var braces_1 = braces$2;
var util = import_util.default;
var braces$1 = braces_1;
var picomatch$2 = picomatch$3;
var utils$b = utils$k;
var isEmptyString = (val) => val === "" || val === "./";
var micromatch$1 = (list, patterns, options2) => {
  patterns = [].concat(patterns);
  list = [].concat(list);
  let omit = /* @__PURE__ */ new Set();
  let keep = /* @__PURE__ */ new Set();
  let items = /* @__PURE__ */ new Set();
  let negatives = 0;
  let onResult = (state) => {
    items.add(state.output);
    if (options2 && options2.onResult) {
      options2.onResult(state);
    }
  };
  for (let i = 0; i < patterns.length; i++) {
    let isMatch2 = picomatch$2(String(patterns[i]), { ...options2, onResult }, true);
    let negated = isMatch2.state.negated || isMatch2.state.negatedExtglob;
    if (negated) negatives++;
    for (let item of list) {
      let matched = isMatch2(item, true);
      let match2 = negated ? !matched.isMatch : matched.isMatch;
      if (!match2) continue;
      if (negated) {
        omit.add(matched.output);
      } else {
        omit.delete(matched.output);
        keep.add(matched.output);
      }
    }
  }
  let result = negatives === patterns.length ? [...items] : [...keep];
  let matches2 = result.filter((item) => !omit.has(item));
  if (options2 && matches2.length === 0) {
    if (options2.failglob === true) {
      throw new Error(`No matches found for "${patterns.join(", ")}"`);
    }
    if (options2.nonull === true || options2.nullglob === true) {
      return options2.unescape ? patterns.map((p) => p.replace(/\\/g, "")) : patterns;
    }
  }
  return matches2;
};
micromatch$1.match = micromatch$1;
micromatch$1.matcher = (pattern2, options2) => picomatch$2(pattern2, options2);
micromatch$1.isMatch = (str, patterns, options2) => picomatch$2(patterns, options2)(str);
micromatch$1.any = micromatch$1.isMatch;
micromatch$1.not = (list, patterns, options2 = {}) => {
  patterns = [].concat(patterns).map(String);
  let result = /* @__PURE__ */ new Set();
  let items = [];
  let onResult = (state) => {
    if (options2.onResult) options2.onResult(state);
    items.push(state.output);
  };
  let matches2 = new Set(micromatch$1(list, patterns, { ...options2, onResult }));
  for (let item of items) {
    if (!matches2.has(item)) {
      result.add(item);
    }
  }
  return [...result];
};
micromatch$1.contains = (str, pattern2, options2) => {
  if (typeof str !== "string") {
    throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  }
  if (Array.isArray(pattern2)) {
    return pattern2.some((p) => micromatch$1.contains(str, p, options2));
  }
  if (typeof pattern2 === "string") {
    if (isEmptyString(str) || isEmptyString(pattern2)) {
      return false;
    }
    if (str.includes(pattern2) || str.startsWith("./") && str.slice(2).includes(pattern2)) {
      return true;
    }
  }
  return micromatch$1.isMatch(str, pattern2, { ...options2, contains: true });
};
micromatch$1.matchKeys = (obj, patterns, options2) => {
  if (!utils$b.isObject(obj)) {
    throw new TypeError("Expected the first argument to be an object");
  }
  let keys = micromatch$1(Object.keys(obj), patterns, options2);
  let res = {};
  for (let key of keys) res[key] = obj[key];
  return res;
};
micromatch$1.some = (list, patterns, options2) => {
  let items = [].concat(list);
  for (let pattern2 of [].concat(patterns)) {
    let isMatch2 = picomatch$2(String(pattern2), options2);
    if (items.some((item) => isMatch2(item))) {
      return true;
    }
  }
  return false;
};
micromatch$1.every = (list, patterns, options2) => {
  let items = [].concat(list);
  for (let pattern2 of [].concat(patterns)) {
    let isMatch2 = picomatch$2(String(pattern2), options2);
    if (!items.every((item) => isMatch2(item))) {
      return false;
    }
  }
  return true;
};
micromatch$1.all = (str, patterns, options2) => {
  if (typeof str !== "string") {
    throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
  }
  return [].concat(patterns).every((p) => picomatch$2(p, options2)(str));
};
micromatch$1.capture = (glob2, input, options2) => {
  let posix2 = utils$b.isWindows(options2);
  let regex2 = picomatch$2.makeRe(String(glob2), { ...options2, capture: true });
  let match2 = regex2.exec(posix2 ? utils$b.toPosixSlashes(input) : input);
  if (match2) {
    return match2.slice(1).map((v) => v === void 0 ? "" : v);
  }
};
micromatch$1.makeRe = (...args) => picomatch$2.makeRe(...args);
micromatch$1.scan = (...args) => picomatch$2.scan(...args);
micromatch$1.parse = (patterns, options2) => {
  let res = [];
  for (let pattern2 of [].concat(patterns || [])) {
    for (let str of braces$1(String(pattern2), options2)) {
      res.push(picomatch$2.parse(str, options2));
    }
  }
  return res;
};
micromatch$1.braces = (pattern2, options2) => {
  if (typeof pattern2 !== "string") throw new TypeError("Expected a string");
  if (options2 && options2.nobrace === true || !/\{.*\}/.test(pattern2)) {
    return [pattern2];
  }
  return braces$1(pattern2, options2);
};
micromatch$1.braceExpand = (pattern2, options2) => {
  if (typeof pattern2 !== "string") throw new TypeError("Expected a string");
  return micromatch$1.braces(pattern2, { ...options2, expand: true });
};
var micromatch_1 = micromatch$1;
var micromatch$2 = getDefaultExportFromCjs(micromatch_1);
Object.defineProperty(pattern$1, "__esModule", { value: true });
pattern$1.removeDuplicateSlashes = pattern$1.matchAny = pattern$1.convertPatternsToRe = pattern$1.makeRe = pattern$1.getPatternParts = pattern$1.expandBraceExpansion = pattern$1.expandPatternsWithBraceExpansion = pattern$1.isAffectDepthOfReadingPattern = pattern$1.endsWithSlashGlobStar = pattern$1.hasGlobStar = pattern$1.getBaseDirectory = pattern$1.isPatternRelatedToParentDirectory = pattern$1.getPatternsOutsideCurrentDirectory = pattern$1.getPatternsInsideCurrentDirectory = pattern$1.getPositivePatterns = pattern$1.getNegativePatterns = pattern$1.isPositivePattern = pattern$1.isNegativePattern = pattern$1.convertToNegativePattern = pattern$1.convertToPositivePattern = pattern$1.isDynamicPattern = pattern$1.isStaticPattern = void 0;
var path$g = import_path.default;
var globParent$1 = globParent$2;
var micromatch = micromatch_1;
var GLOBSTAR$1 = "**";
var ESCAPE_SYMBOL = "\\";
var COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
var REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[[^[]*]/;
var REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\([^(]*\|[^|]*\)/;
var GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\([^(]*\)/;
var BRACE_EXPANSION_SEPARATORS_RE = /,|\.\./;
var DOUBLE_SLASH_RE$1 = /(?!^)\/{2,}/g;
function isStaticPattern(pattern2, options2 = {}) {
  return !isDynamicPattern(pattern2, options2);
}
pattern$1.isStaticPattern = isStaticPattern;
function isDynamicPattern(pattern2, options2 = {}) {
  if (pattern2 === "") {
    return false;
  }
  if (options2.caseSensitiveMatch === false || pattern2.includes(ESCAPE_SYMBOL)) {
    return true;
  }
  if (COMMON_GLOB_SYMBOLS_RE.test(pattern2) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern2) || REGEX_GROUP_SYMBOLS_RE.test(pattern2)) {
    return true;
  }
  if (options2.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern2)) {
    return true;
  }
  if (options2.braceExpansion !== false && hasBraceExpansion(pattern2)) {
    return true;
  }
  return false;
}
pattern$1.isDynamicPattern = isDynamicPattern;
function hasBraceExpansion(pattern2) {
  const openingBraceIndex = pattern2.indexOf("{");
  if (openingBraceIndex === -1) {
    return false;
  }
  const closingBraceIndex = pattern2.indexOf("}", openingBraceIndex + 1);
  if (closingBraceIndex === -1) {
    return false;
  }
  const braceContent = pattern2.slice(openingBraceIndex, closingBraceIndex);
  return BRACE_EXPANSION_SEPARATORS_RE.test(braceContent);
}
function convertToPositivePattern(pattern2) {
  return isNegativePattern(pattern2) ? pattern2.slice(1) : pattern2;
}
pattern$1.convertToPositivePattern = convertToPositivePattern;
function convertToNegativePattern(pattern2) {
  return "!" + pattern2;
}
pattern$1.convertToNegativePattern = convertToNegativePattern;
function isNegativePattern(pattern2) {
  return pattern2.startsWith("!") && pattern2[1] !== "(";
}
pattern$1.isNegativePattern = isNegativePattern;
function isPositivePattern(pattern2) {
  return !isNegativePattern(pattern2);
}
pattern$1.isPositivePattern = isPositivePattern;
function getNegativePatterns(patterns) {
  return patterns.filter(isNegativePattern);
}
pattern$1.getNegativePatterns = getNegativePatterns;
function getPositivePatterns$1(patterns) {
  return patterns.filter(isPositivePattern);
}
pattern$1.getPositivePatterns = getPositivePatterns$1;
function getPatternsInsideCurrentDirectory(patterns) {
  return patterns.filter((pattern2) => !isPatternRelatedToParentDirectory(pattern2));
}
pattern$1.getPatternsInsideCurrentDirectory = getPatternsInsideCurrentDirectory;
function getPatternsOutsideCurrentDirectory(patterns) {
  return patterns.filter(isPatternRelatedToParentDirectory);
}
pattern$1.getPatternsOutsideCurrentDirectory = getPatternsOutsideCurrentDirectory;
function isPatternRelatedToParentDirectory(pattern2) {
  return pattern2.startsWith("..") || pattern2.startsWith("./..");
}
pattern$1.isPatternRelatedToParentDirectory = isPatternRelatedToParentDirectory;
function getBaseDirectory(pattern2) {
  return globParent$1(pattern2, { flipBackslashes: false });
}
pattern$1.getBaseDirectory = getBaseDirectory;
function hasGlobStar(pattern2) {
  return pattern2.includes(GLOBSTAR$1);
}
pattern$1.hasGlobStar = hasGlobStar;
function endsWithSlashGlobStar(pattern2) {
  return pattern2.endsWith("/" + GLOBSTAR$1);
}
pattern$1.endsWithSlashGlobStar = endsWithSlashGlobStar;
function isAffectDepthOfReadingPattern(pattern2) {
  const basename2 = path$g.basename(pattern2);
  return endsWithSlashGlobStar(pattern2) || isStaticPattern(basename2);
}
pattern$1.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
function expandPatternsWithBraceExpansion(patterns) {
  return patterns.reduce((collection, pattern2) => {
    return collection.concat(expandBraceExpansion(pattern2));
  }, []);
}
pattern$1.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
function expandBraceExpansion(pattern2) {
  const patterns = micromatch.braces(pattern2, { expand: true, nodupes: true, keepEscaping: true });
  patterns.sort((a, b) => a.length - b.length);
  return patterns.filter((pattern3) => pattern3 !== "");
}
pattern$1.expandBraceExpansion = expandBraceExpansion;
function getPatternParts(pattern2, options2) {
  let { parts } = micromatch.scan(pattern2, Object.assign(Object.assign({}, options2), { parts: true }));
  if (parts.length === 0) {
    parts = [pattern2];
  }
  if (parts[0].startsWith("/")) {
    parts[0] = parts[0].slice(1);
    parts.unshift("");
  }
  return parts;
}
pattern$1.getPatternParts = getPatternParts;
function makeRe(pattern2, options2) {
  return micromatch.makeRe(pattern2, options2);
}
pattern$1.makeRe = makeRe;
function convertPatternsToRe(patterns, options2) {
  return patterns.map((pattern2) => makeRe(pattern2, options2));
}
pattern$1.convertPatternsToRe = convertPatternsToRe;
function matchAny(entry2, patternsRe) {
  return patternsRe.some((patternRe) => patternRe.test(entry2));
}
pattern$1.matchAny = matchAny;
function removeDuplicateSlashes(pattern2) {
  return pattern2.replace(DOUBLE_SLASH_RE$1, "/");
}
pattern$1.removeDuplicateSlashes = removeDuplicateSlashes;
var stream$4 = {};
var Stream = import_stream.default;
var PassThrough = Stream.PassThrough;
var slice = Array.prototype.slice;
var merge2_1 = merge2$1;
function merge2$1() {
  const streamsQueue = [];
  const args = slice.call(arguments);
  let merging = false;
  let options2 = args[args.length - 1];
  if (options2 && !Array.isArray(options2) && options2.pipe == null) {
    args.pop();
  } else {
    options2 = {};
  }
  const doEnd = options2.end !== false;
  const doPipeError = options2.pipeError === true;
  if (options2.objectMode == null) {
    options2.objectMode = true;
  }
  if (options2.highWaterMark == null) {
    options2.highWaterMark = 64 * 1024;
  }
  const mergedStream = PassThrough(options2);
  function addStream() {
    for (let i = 0, len = arguments.length; i < len; i++) {
      streamsQueue.push(pauseStreams(arguments[i], options2));
    }
    mergeStream();
    return this;
  }
  function mergeStream() {
    if (merging) {
      return;
    }
    merging = true;
    let streams = streamsQueue.shift();
    if (!streams) {
      process.nextTick(endStream);
      return;
    }
    if (!Array.isArray(streams)) {
      streams = [streams];
    }
    let pipesCount = streams.length + 1;
    function next() {
      if (--pipesCount > 0) {
        return;
      }
      merging = false;
      mergeStream();
    }
    function pipe(stream4) {
      function onend() {
        stream4.removeListener("merge2UnpipeEnd", onend);
        stream4.removeListener("end", onend);
        if (doPipeError) {
          stream4.removeListener("error", onerror);
        }
        next();
      }
      function onerror(err2) {
        mergedStream.emit("error", err2);
      }
      if (stream4._readableState.endEmitted) {
        return next();
      }
      stream4.on("merge2UnpipeEnd", onend);
      stream4.on("end", onend);
      if (doPipeError) {
        stream4.on("error", onerror);
      }
      stream4.pipe(mergedStream, { end: false });
      stream4.resume();
    }
    for (let i = 0; i < streams.length; i++) {
      pipe(streams[i]);
    }
    next();
  }
  function endStream() {
    merging = false;
    mergedStream.emit("queueDrain");
    if (doEnd) {
      mergedStream.end();
    }
  }
  mergedStream.setMaxListeners(0);
  mergedStream.add = addStream;
  mergedStream.on("unpipe", function(stream4) {
    stream4.emit("merge2UnpipeEnd");
  });
  if (args.length) {
    addStream.apply(null, args);
  }
  return mergedStream;
}
function pauseStreams(streams, options2) {
  if (!Array.isArray(streams)) {
    if (!streams._readableState && streams.pipe) {
      streams = streams.pipe(PassThrough(options2));
    }
    if (!streams._readableState || !streams.pause || !streams.pipe) {
      throw new Error("Only readable stream can be merged.");
    }
    streams.pause();
  } else {
    for (let i = 0, len = streams.length; i < len; i++) {
      streams[i] = pauseStreams(streams[i], options2);
    }
  }
  return streams;
}
Object.defineProperty(stream$4, "__esModule", { value: true });
stream$4.merge = void 0;
var merge2 = merge2_1;
function merge$1(streams) {
  const mergedStream = merge2(streams);
  streams.forEach((stream4) => {
    stream4.once("error", (error2) => mergedStream.emit("error", error2));
  });
  mergedStream.once("close", () => propagateCloseEventToSources(streams));
  mergedStream.once("end", () => propagateCloseEventToSources(streams));
  return mergedStream;
}
stream$4.merge = merge$1;
function propagateCloseEventToSources(streams) {
  streams.forEach((stream4) => stream4.emit("close"));
}
var string$2 = {};
Object.defineProperty(string$2, "__esModule", { value: true });
string$2.isEmpty = string$2.isString = void 0;
function isString$1(input) {
  return typeof input === "string";
}
string$2.isString = isString$1;
function isEmpty$1(input) {
  return input === "";
}
string$2.isEmpty = isEmpty$1;
Object.defineProperty(utils$g, "__esModule", { value: true });
utils$g.string = utils$g.stream = utils$g.pattern = utils$g.path = utils$g.fs = utils$g.errno = utils$g.array = void 0;
var array = array$1;
utils$g.array = array;
var errno = errno$1;
utils$g.errno = errno;
var fs$h = fs$i;
utils$g.fs = fs$h;
var path$f = path$i;
utils$g.path = path$f;
var pattern = pattern$1;
utils$g.pattern = pattern;
var stream$3 = stream$4;
utils$g.stream = stream$3;
var string$1 = string$2;
utils$g.string = string$1;
Object.defineProperty(tasks, "__esModule", { value: true });
tasks.convertPatternGroupToTask = tasks.convertPatternGroupsToTasks = tasks.groupPatternsByBaseDirectory = tasks.getNegativePatternsAsPositive = tasks.getPositivePatterns = tasks.convertPatternsToTasks = tasks.generate = void 0;
var utils$a = utils$g;
function generate(input, settings2) {
  const patterns = processPatterns(input, settings2);
  const ignore = processPatterns(settings2.ignore, settings2);
  const positivePatterns = getPositivePatterns(patterns);
  const negativePatterns = getNegativePatternsAsPositive(patterns, ignore);
  const staticPatterns = positivePatterns.filter((pattern2) => utils$a.pattern.isStaticPattern(pattern2, settings2));
  const dynamicPatterns = positivePatterns.filter((pattern2) => utils$a.pattern.isDynamicPattern(pattern2, settings2));
  const staticTasks = convertPatternsToTasks(
    staticPatterns,
    negativePatterns,
    /* dynamic */
    false
  );
  const dynamicTasks = convertPatternsToTasks(
    dynamicPatterns,
    negativePatterns,
    /* dynamic */
    true
  );
  return staticTasks.concat(dynamicTasks);
}
tasks.generate = generate;
function processPatterns(input, settings2) {
  let patterns = input;
  if (settings2.braceExpansion) {
    patterns = utils$a.pattern.expandPatternsWithBraceExpansion(patterns);
  }
  if (settings2.baseNameMatch) {
    patterns = patterns.map((pattern2) => pattern2.includes("/") ? pattern2 : `**/${pattern2}`);
  }
  return patterns.map((pattern2) => utils$a.pattern.removeDuplicateSlashes(pattern2));
}
function convertPatternsToTasks(positive, negative, dynamic) {
  const tasks2 = [];
  const patternsOutsideCurrentDirectory = utils$a.pattern.getPatternsOutsideCurrentDirectory(positive);
  const patternsInsideCurrentDirectory = utils$a.pattern.getPatternsInsideCurrentDirectory(positive);
  const outsideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsOutsideCurrentDirectory);
  const insideCurrentDirectoryGroup = groupPatternsByBaseDirectory(patternsInsideCurrentDirectory);
  tasks2.push(...convertPatternGroupsToTasks(outsideCurrentDirectoryGroup, negative, dynamic));
  if ("." in insideCurrentDirectoryGroup) {
    tasks2.push(convertPatternGroupToTask(".", patternsInsideCurrentDirectory, negative, dynamic));
  } else {
    tasks2.push(...convertPatternGroupsToTasks(insideCurrentDirectoryGroup, negative, dynamic));
  }
  return tasks2;
}
tasks.convertPatternsToTasks = convertPatternsToTasks;
function getPositivePatterns(patterns) {
  return utils$a.pattern.getPositivePatterns(patterns);
}
tasks.getPositivePatterns = getPositivePatterns;
function getNegativePatternsAsPositive(patterns, ignore) {
  const negative = utils$a.pattern.getNegativePatterns(patterns).concat(ignore);
  const positive = negative.map(utils$a.pattern.convertToPositivePattern);
  return positive;
}
tasks.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
function groupPatternsByBaseDirectory(patterns) {
  const group = {};
  return patterns.reduce((collection, pattern2) => {
    const base = utils$a.pattern.getBaseDirectory(pattern2);
    if (base in collection) {
      collection[base].push(pattern2);
    } else {
      collection[base] = [pattern2];
    }
    return collection;
  }, group);
}
tasks.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
function convertPatternGroupsToTasks(positive, negative, dynamic) {
  return Object.keys(positive).map((base) => {
    return convertPatternGroupToTask(base, positive[base], negative, dynamic);
  });
}
tasks.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
function convertPatternGroupToTask(base, positive, negative, dynamic) {
  return {
    dynamic,
    positive,
    negative,
    base,
    patterns: [].concat(positive, negative.map(utils$a.pattern.convertToNegativePattern))
  };
}
tasks.convertPatternGroupToTask = convertPatternGroupToTask;
var async$7 = {};
var async$6 = {};
var out$3 = {};
var async$5 = {};
var async$4 = {};
var out$2 = {};
var async$3 = {};
var out$1 = {};
var async$2 = {};
Object.defineProperty(async$2, "__esModule", { value: true });
async$2.read = void 0;
function read$3(path3, settings2, callback) {
  settings2.fs.lstat(path3, (lstatError, lstat2) => {
    if (lstatError !== null) {
      callFailureCallback$2(callback, lstatError);
      return;
    }
    if (!lstat2.isSymbolicLink() || !settings2.followSymbolicLink) {
      callSuccessCallback$2(callback, lstat2);
      return;
    }
    settings2.fs.stat(path3, (statError, stat2) => {
      if (statError !== null) {
        if (settings2.throwErrorOnBrokenSymbolicLink) {
          callFailureCallback$2(callback, statError);
          return;
        }
        callSuccessCallback$2(callback, lstat2);
        return;
      }
      if (settings2.markSymbolicLink) {
        stat2.isSymbolicLink = () => true;
      }
      callSuccessCallback$2(callback, stat2);
    });
  });
}
async$2.read = read$3;
function callFailureCallback$2(callback, error2) {
  callback(error2);
}
function callSuccessCallback$2(callback, result) {
  callback(null, result);
}
var sync$8 = {};
Object.defineProperty(sync$8, "__esModule", { value: true });
sync$8.read = void 0;
function read$2(path3, settings2) {
  const lstat2 = settings2.fs.lstatSync(path3);
  if (!lstat2.isSymbolicLink() || !settings2.followSymbolicLink) {
    return lstat2;
  }
  try {
    const stat2 = settings2.fs.statSync(path3);
    if (settings2.markSymbolicLink) {
      stat2.isSymbolicLink = () => true;
    }
    return stat2;
  } catch (error2) {
    if (!settings2.throwErrorOnBrokenSymbolicLink) {
      return lstat2;
    }
    throw error2;
  }
}
sync$8.read = read$2;
var settings$3 = {};
var fs$g = {};
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.createFileSystemAdapter = exports2.FILE_SYSTEM_ADAPTER = void 0;
  const fs2 = import_fs.default;
  exports2.FILE_SYSTEM_ADAPTER = {
    lstat: fs2.lstat,
    stat: fs2.stat,
    lstatSync: fs2.lstatSync,
    statSync: fs2.statSync
  };
  function createFileSystemAdapter(fsMethods) {
    if (fsMethods === void 0) {
      return exports2.FILE_SYSTEM_ADAPTER;
    }
    return Object.assign(Object.assign({}, exports2.FILE_SYSTEM_ADAPTER), fsMethods);
  }
  exports2.createFileSystemAdapter = createFileSystemAdapter;
})(fs$g);
Object.defineProperty(settings$3, "__esModule", { value: true });
var fs$f = fs$g;
var Settings$2 = class Settings {
  constructor(_options2 = {}) {
    this._options = _options2;
    this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
    this.fs = fs$f.createFileSystemAdapter(this._options.fs);
    this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
    this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
  }
  _getValue(option, value2) {
    return option !== null && option !== void 0 ? option : value2;
  }
};
settings$3.default = Settings$2;
Object.defineProperty(out$1, "__esModule", { value: true });
out$1.statSync = out$1.stat = out$1.Settings = void 0;
var async$1 = async$2;
var sync$7 = sync$8;
var settings_1$3 = settings$3;
out$1.Settings = settings_1$3.default;
function stat$4(path3, optionsOrSettingsOrCallback, callback) {
  if (typeof optionsOrSettingsOrCallback === "function") {
    async$1.read(path3, getSettings$2(), optionsOrSettingsOrCallback);
    return;
  }
  async$1.read(path3, getSettings$2(optionsOrSettingsOrCallback), callback);
}
out$1.stat = stat$4;
function statSync2(path3, optionsOrSettings) {
  const settings2 = getSettings$2(optionsOrSettings);
  return sync$7.read(path3, settings2);
}
out$1.statSync = statSync2;
function getSettings$2(settingsOrOptions = {}) {
  if (settingsOrOptions instanceof settings_1$3.default) {
    return settingsOrOptions;
  }
  return new settings_1$3.default(settingsOrOptions);
}
var promise;
var queueMicrotask_1 = typeof queueMicrotask === "function" ? queueMicrotask.bind(typeof window !== "undefined" ? window : commonjsGlobal) : (cb) => (promise || (promise = Promise.resolve())).then(cb).catch((err2) => setTimeout(() => {
  throw err2;
}, 0));
var runParallel_1 = runParallel;
var queueMicrotask$1 = queueMicrotask_1;
function runParallel(tasks2, cb) {
  let results, pending, keys;
  let isSync = true;
  if (Array.isArray(tasks2)) {
    results = [];
    pending = tasks2.length;
  } else {
    keys = Object.keys(tasks2);
    results = {};
    pending = keys.length;
  }
  function done(err2) {
    function end() {
      if (cb) cb(err2, results);
      cb = null;
    }
    if (isSync) queueMicrotask$1(end);
    else end();
  }
  function each(i, err2, result) {
    results[i] = result;
    if (--pending === 0 || err2) {
      done(err2);
    }
  }
  if (!pending) {
    done(null);
  } else if (keys) {
    keys.forEach(function(key) {
      tasks2[key](function(err2, result) {
        each(key, err2, result);
      });
    });
  } else {
    tasks2.forEach(function(task, i) {
      task(function(err2, result) {
        each(i, err2, result);
      });
    });
  }
  isSync = false;
}
var constants$2 = {};
Object.defineProperty(constants$2, "__esModule", { value: true });
constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = void 0;
var NODE_PROCESS_VERSION_PARTS = process.versions.node.split(".");
if (NODE_PROCESS_VERSION_PARTS[0] === void 0 || NODE_PROCESS_VERSION_PARTS[1] === void 0) {
  throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);
}
var MAJOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
var MINOR_VERSION = Number.parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
var SUPPORTED_MAJOR_VERSION = 10;
var SUPPORTED_MINOR_VERSION = 10;
var IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
var IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
var utils$9 = {};
var fs$e = {};
Object.defineProperty(fs$e, "__esModule", { value: true });
fs$e.createDirentFromStats = void 0;
var DirentFromStats2 = class {
  constructor(name2, stats) {
    this.name = name2;
    this.isBlockDevice = stats.isBlockDevice.bind(stats);
    this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
    this.isDirectory = stats.isDirectory.bind(stats);
    this.isFIFO = stats.isFIFO.bind(stats);
    this.isFile = stats.isFile.bind(stats);
    this.isSocket = stats.isSocket.bind(stats);
    this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
  }
};
function createDirentFromStats(name2, stats) {
  return new DirentFromStats2(name2, stats);
}
fs$e.createDirentFromStats = createDirentFromStats;
Object.defineProperty(utils$9, "__esModule", { value: true });
utils$9.fs = void 0;
var fs$d = fs$e;
utils$9.fs = fs$d;
var common$a = {};
Object.defineProperty(common$a, "__esModule", { value: true });
common$a.joinPathSegments = void 0;
function joinPathSegments$1(a, b, separator) {
  if (a.endsWith(separator)) {
    return a + b;
  }
  return a + separator + b;
}
common$a.joinPathSegments = joinPathSegments$1;
Object.defineProperty(async$3, "__esModule", { value: true });
async$3.readdir = async$3.readdirWithFileTypes = async$3.read = void 0;
var fsStat$5 = out$1;
var rpl = runParallel_1;
var constants_1$1 = constants$2;
var utils$8 = utils$9;
var common$9 = common$a;
function read$1(directory, settings2, callback) {
  if (!settings2.stats && constants_1$1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
    readdirWithFileTypes$1(directory, settings2, callback);
    return;
  }
  readdir$3(directory, settings2, callback);
}
async$3.read = read$1;
function readdirWithFileTypes$1(directory, settings2, callback) {
  settings2.fs.readdir(directory, { withFileTypes: true }, (readdirError, dirents) => {
    if (readdirError !== null) {
      callFailureCallback$1(callback, readdirError);
      return;
    }
    const entries = dirents.map((dirent) => ({
      dirent,
      name: dirent.name,
      path: common$9.joinPathSegments(directory, dirent.name, settings2.pathSegmentSeparator)
    }));
    if (!settings2.followSymbolicLinks) {
      callSuccessCallback$1(callback, entries);
      return;
    }
    const tasks2 = entries.map((entry2) => makeRplTaskEntry(entry2, settings2));
    rpl(tasks2, (rplError, rplEntries) => {
      if (rplError !== null) {
        callFailureCallback$1(callback, rplError);
        return;
      }
      callSuccessCallback$1(callback, rplEntries);
    });
  });
}
async$3.readdirWithFileTypes = readdirWithFileTypes$1;
function makeRplTaskEntry(entry2, settings2) {
  return (done) => {
    if (!entry2.dirent.isSymbolicLink()) {
      done(null, entry2);
      return;
    }
    settings2.fs.stat(entry2.path, (statError, stats) => {
      if (statError !== null) {
        if (settings2.throwErrorOnBrokenSymbolicLink) {
          done(statError);
          return;
        }
        done(null, entry2);
        return;
      }
      entry2.dirent = utils$8.fs.createDirentFromStats(entry2.name, stats);
      done(null, entry2);
    });
  };
}
function readdir$3(directory, settings2, callback) {
  settings2.fs.readdir(directory, (readdirError, names) => {
    if (readdirError !== null) {
      callFailureCallback$1(callback, readdirError);
      return;
    }
    const tasks2 = names.map((name2) => {
      const path3 = common$9.joinPathSegments(directory, name2, settings2.pathSegmentSeparator);
      return (done) => {
        fsStat$5.stat(path3, settings2.fsStatSettings, (error2, stats) => {
          if (error2 !== null) {
            done(error2);
            return;
          }
          const entry2 = {
            name: name2,
            path: path3,
            dirent: utils$8.fs.createDirentFromStats(name2, stats)
          };
          if (settings2.stats) {
            entry2.stats = stats;
          }
          done(null, entry2);
        });
      };
    });
    rpl(tasks2, (rplError, entries) => {
      if (rplError !== null) {
        callFailureCallback$1(callback, rplError);
        return;
      }
      callSuccessCallback$1(callback, entries);
    });
  });
}
async$3.readdir = readdir$3;
function callFailureCallback$1(callback, error2) {
  callback(error2);
}
function callSuccessCallback$1(callback, result) {
  callback(null, result);
}
var sync$6 = {};
Object.defineProperty(sync$6, "__esModule", { value: true });
sync$6.readdir = sync$6.readdirWithFileTypes = sync$6.read = void 0;
var fsStat$4 = out$1;
var constants_1 = constants$2;
var utils$7 = utils$9;
var common$8 = common$a;
function read(directory, settings2) {
  if (!settings2.stats && constants_1.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
    return readdirWithFileTypes(directory, settings2);
  }
  return readdir$2(directory, settings2);
}
sync$6.read = read;
function readdirWithFileTypes(directory, settings2) {
  const dirents = settings2.fs.readdirSync(directory, { withFileTypes: true });
  return dirents.map((dirent) => {
    const entry2 = {
      dirent,
      name: dirent.name,
      path: common$8.joinPathSegments(directory, dirent.name, settings2.pathSegmentSeparator)
    };
    if (entry2.dirent.isSymbolicLink() && settings2.followSymbolicLinks) {
      try {
        const stats = settings2.fs.statSync(entry2.path);
        entry2.dirent = utils$7.fs.createDirentFromStats(entry2.name, stats);
      } catch (error2) {
        if (settings2.throwErrorOnBrokenSymbolicLink) {
          throw error2;
        }
      }
    }
    return entry2;
  });
}
sync$6.readdirWithFileTypes = readdirWithFileTypes;
function readdir$2(directory, settings2) {
  const names = settings2.fs.readdirSync(directory);
  return names.map((name2) => {
    const entryPath = common$8.joinPathSegments(directory, name2, settings2.pathSegmentSeparator);
    const stats = fsStat$4.statSync(entryPath, settings2.fsStatSettings);
    const entry2 = {
      name: name2,
      path: entryPath,
      dirent: utils$7.fs.createDirentFromStats(name2, stats)
    };
    if (settings2.stats) {
      entry2.stats = stats;
    }
    return entry2;
  });
}
sync$6.readdir = readdir$2;
var settings$2 = {};
var fs$c = {};
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.createFileSystemAdapter = exports2.FILE_SYSTEM_ADAPTER = void 0;
  const fs2 = import_fs.default;
  exports2.FILE_SYSTEM_ADAPTER = {
    lstat: fs2.lstat,
    stat: fs2.stat,
    lstatSync: fs2.lstatSync,
    statSync: fs2.statSync,
    readdir: fs2.readdir,
    readdirSync: fs2.readdirSync
  };
  function createFileSystemAdapter(fsMethods) {
    if (fsMethods === void 0) {
      return exports2.FILE_SYSTEM_ADAPTER;
    }
    return Object.assign(Object.assign({}, exports2.FILE_SYSTEM_ADAPTER), fsMethods);
  }
  exports2.createFileSystemAdapter = createFileSystemAdapter;
})(fs$c);
Object.defineProperty(settings$2, "__esModule", { value: true });
var path$e = import_path.default;
var fsStat$3 = out$1;
var fs$b = fs$c;
var Settings$1 = class Settings2 {
  constructor(_options2 = {}) {
    this._options = _options2;
    this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
    this.fs = fs$b.createFileSystemAdapter(this._options.fs);
    this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$e.sep);
    this.stats = this._getValue(this._options.stats, false);
    this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
    this.fsStatSettings = new fsStat$3.Settings({
      followSymbolicLink: this.followSymbolicLinks,
      fs: this.fs,
      throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
    });
  }
  _getValue(option, value2) {
    return option !== null && option !== void 0 ? option : value2;
  }
};
settings$2.default = Settings$1;
Object.defineProperty(out$2, "__esModule", { value: true });
out$2.Settings = out$2.scandirSync = out$2.scandir = void 0;
var async = async$3;
var sync$5 = sync$6;
var settings_1$2 = settings$2;
out$2.Settings = settings_1$2.default;
function scandir(path3, optionsOrSettingsOrCallback, callback) {
  if (typeof optionsOrSettingsOrCallback === "function") {
    async.read(path3, getSettings$1(), optionsOrSettingsOrCallback);
    return;
  }
  async.read(path3, getSettings$1(optionsOrSettingsOrCallback), callback);
}
out$2.scandir = scandir;
function scandirSync(path3, optionsOrSettings) {
  const settings2 = getSettings$1(optionsOrSettings);
  return sync$5.read(path3, settings2);
}
out$2.scandirSync = scandirSync;
function getSettings$1(settingsOrOptions = {}) {
  if (settingsOrOptions instanceof settings_1$2.default) {
    return settingsOrOptions;
  }
  return new settings_1$2.default(settingsOrOptions);
}
var queue = { exports: {} };
function reusify$1(Constructor) {
  var head = new Constructor();
  var tail = head;
  function get2() {
    var current = head;
    if (current.next) {
      head = current.next;
    } else {
      head = new Constructor();
      tail = head;
    }
    current.next = null;
    return current;
  }
  function release(obj) {
    tail.next = obj;
    tail = obj;
  }
  return {
    get: get2,
    release
  };
}
var reusify_1 = reusify$1;
var reusify = reusify_1;
function fastqueue(context, worker, _concurrency) {
  if (typeof context === "function") {
    _concurrency = worker;
    worker = context;
    context = null;
  }
  if (!(_concurrency >= 1)) {
    throw new Error("fastqueue concurrency must be equal to or greater than 1");
  }
  var cache = reusify(Task);
  var queueHead = null;
  var queueTail = null;
  var _running = 0;
  var errorHandler = null;
  var self2 = {
    push: push2,
    drain: noop$4,
    saturated: noop$4,
    pause,
    paused: false,
    get concurrency() {
      return _concurrency;
    },
    set concurrency(value2) {
      if (!(value2 >= 1)) {
        throw new Error("fastqueue concurrency must be equal to or greater than 1");
      }
      _concurrency = value2;
      if (self2.paused) return;
      for (; queueHead && _running < _concurrency; ) {
        _running++;
        release();
      }
    },
    running,
    resume: resume2,
    idle,
    length,
    getQueue,
    unshift,
    empty: noop$4,
    kill,
    killAndDrain,
    error: error2
  };
  return self2;
  function running() {
    return _running;
  }
  function pause() {
    self2.paused = true;
  }
  function length() {
    var current = queueHead;
    var counter = 0;
    while (current) {
      current = current.next;
      counter++;
    }
    return counter;
  }
  function getQueue() {
    var current = queueHead;
    var tasks2 = [];
    while (current) {
      tasks2.push(current.value);
      current = current.next;
    }
    return tasks2;
  }
  function resume2() {
    if (!self2.paused) return;
    self2.paused = false;
    if (queueHead === null) {
      _running++;
      release();
      return;
    }
    for (; queueHead && _running < _concurrency; ) {
      _running++;
      release();
    }
  }
  function idle() {
    return _running === 0 && self2.length() === 0;
  }
  function push2(value2, done) {
    var current = cache.get();
    current.context = context;
    current.release = release;
    current.value = value2;
    current.callback = done || noop$4;
    current.errorHandler = errorHandler;
    if (_running >= _concurrency || self2.paused) {
      if (queueTail) {
        queueTail.next = current;
        queueTail = current;
      } else {
        queueHead = current;
        queueTail = current;
        self2.saturated();
      }
    } else {
      _running++;
      worker.call(context, current.value, current.worked);
    }
  }
  function unshift(value2, done) {
    var current = cache.get();
    current.context = context;
    current.release = release;
    current.value = value2;
    current.callback = done || noop$4;
    current.errorHandler = errorHandler;
    if (_running >= _concurrency || self2.paused) {
      if (queueHead) {
        current.next = queueHead;
        queueHead = current;
      } else {
        queueHead = current;
        queueTail = current;
        self2.saturated();
      }
    } else {
      _running++;
      worker.call(context, current.value, current.worked);
    }
  }
  function release(holder) {
    if (holder) {
      cache.release(holder);
    }
    var next = queueHead;
    if (next && _running <= _concurrency) {
      if (!self2.paused) {
        if (queueTail === queueHead) {
          queueTail = null;
        }
        queueHead = next.next;
        next.next = null;
        worker.call(context, next.value, next.worked);
        if (queueTail === null) {
          self2.empty();
        }
      } else {
        _running--;
      }
    } else if (--_running === 0) {
      self2.drain();
    }
  }
  function kill() {
    queueHead = null;
    queueTail = null;
    self2.drain = noop$4;
  }
  function killAndDrain() {
    queueHead = null;
    queueTail = null;
    self2.drain();
    self2.drain = noop$4;
  }
  function error2(handler) {
    errorHandler = handler;
  }
}
function noop$4() {
}
function Task() {
  this.value = null;
  this.callback = noop$4;
  this.next = null;
  this.release = noop$4;
  this.context = null;
  this.errorHandler = null;
  var self2 = this;
  this.worked = function worked(err2, result) {
    var callback = self2.callback;
    var errorHandler = self2.errorHandler;
    var val = self2.value;
    self2.value = null;
    self2.callback = noop$4;
    if (self2.errorHandler) {
      errorHandler(err2, val);
    }
    callback.call(self2.context, err2, result);
    self2.release(self2);
  };
}
function queueAsPromised(context, worker, _concurrency) {
  if (typeof context === "function") {
    _concurrency = worker;
    worker = context;
    context = null;
  }
  function asyncWrapper(arg, cb) {
    worker.call(this, arg).then(function(res) {
      cb(null, res);
    }, cb);
  }
  var queue2 = fastqueue(context, asyncWrapper, _concurrency);
  var pushCb = queue2.push;
  var unshiftCb = queue2.unshift;
  queue2.push = push2;
  queue2.unshift = unshift;
  queue2.drained = drained;
  return queue2;
  function push2(value2) {
    var p = new Promise(function(resolve3, reject) {
      pushCb(value2, function(err2, result) {
        if (err2) {
          reject(err2);
          return;
        }
        resolve3(result);
      });
    });
    p.catch(noop$4);
    return p;
  }
  function unshift(value2) {
    var p = new Promise(function(resolve3, reject) {
      unshiftCb(value2, function(err2, result) {
        if (err2) {
          reject(err2);
          return;
        }
        resolve3(result);
      });
    });
    p.catch(noop$4);
    return p;
  }
  function drained() {
    if (queue2.idle()) {
      return new Promise(function(resolve3) {
        resolve3();
      });
    }
    var previousDrain = queue2.drain;
    var p = new Promise(function(resolve3) {
      queue2.drain = function() {
        previousDrain();
        resolve3();
      };
    });
    return p;
  }
}
queue.exports = fastqueue;
queue.exports.promise = queueAsPromised;
var queueExports = queue.exports;
var common$7 = {};
Object.defineProperty(common$7, "__esModule", { value: true });
common$7.joinPathSegments = common$7.replacePathSegmentSeparator = common$7.isAppliedFilter = common$7.isFatalError = void 0;
function isFatalError(settings2, error2) {
  if (settings2.errorFilter === null) {
    return true;
  }
  return !settings2.errorFilter(error2);
}
common$7.isFatalError = isFatalError;
function isAppliedFilter(filter2, value2) {
  return filter2 === null || filter2(value2);
}
common$7.isAppliedFilter = isAppliedFilter;
function replacePathSegmentSeparator(filepath, separator) {
  return filepath.split(/[/\\]/).join(separator);
}
common$7.replacePathSegmentSeparator = replacePathSegmentSeparator;
function joinPathSegments(a, b, separator) {
  if (a === "") {
    return b;
  }
  if (a.endsWith(separator)) {
    return a + b;
  }
  return a + separator + b;
}
common$7.joinPathSegments = joinPathSegments;
var reader$1 = {};
Object.defineProperty(reader$1, "__esModule", { value: true });
var common$6 = common$7;
var Reader$1 = class Reader {
  constructor(_root2, _settings) {
    this._root = _root2;
    this._settings = _settings;
    this._root = common$6.replacePathSegmentSeparator(_root2, _settings.pathSegmentSeparator);
  }
};
reader$1.default = Reader$1;
Object.defineProperty(async$4, "__esModule", { value: true });
var events_1 = import_events.default;
var fsScandir$2 = out$2;
var fastq = queueExports;
var common$5 = common$7;
var reader_1$4 = reader$1;
var AsyncReader = class extends reader_1$4.default {
  constructor(_root2, _settings) {
    super(_root2, _settings);
    this._settings = _settings;
    this._scandir = fsScandir$2.scandir;
    this._emitter = new events_1.EventEmitter();
    this._queue = fastq(this._worker.bind(this), this._settings.concurrency);
    this._isFatalError = false;
    this._isDestroyed = false;
    this._queue.drain = () => {
      if (!this._isFatalError) {
        this._emitter.emit("end");
      }
    };
  }
  read() {
    this._isFatalError = false;
    this._isDestroyed = false;
    setImmediate(() => {
      this._pushToQueue(this._root, this._settings.basePath);
    });
    return this._emitter;
  }
  get isDestroyed() {
    return this._isDestroyed;
  }
  destroy() {
    if (this._isDestroyed) {
      throw new Error("The reader is already destroyed");
    }
    this._isDestroyed = true;
    this._queue.killAndDrain();
  }
  onEntry(callback) {
    this._emitter.on("entry", callback);
  }
  onError(callback) {
    this._emitter.once("error", callback);
  }
  onEnd(callback) {
    this._emitter.once("end", callback);
  }
  _pushToQueue(directory, base) {
    const queueItem = { directory, base };
    this._queue.push(queueItem, (error2) => {
      if (error2 !== null) {
        this._handleError(error2);
      }
    });
  }
  _worker(item, done) {
    this._scandir(item.directory, this._settings.fsScandirSettings, (error2, entries) => {
      if (error2 !== null) {
        done(error2, void 0);
        return;
      }
      for (const entry2 of entries) {
        this._handleEntry(entry2, item.base);
      }
      done(null, void 0);
    });
  }
  _handleError(error2) {
    if (this._isDestroyed || !common$5.isFatalError(this._settings, error2)) {
      return;
    }
    this._isFatalError = true;
    this._isDestroyed = true;
    this._emitter.emit("error", error2);
  }
  _handleEntry(entry2, base) {
    if (this._isDestroyed || this._isFatalError) {
      return;
    }
    const fullpath = entry2.path;
    if (base !== void 0) {
      entry2.path = common$5.joinPathSegments(base, entry2.name, this._settings.pathSegmentSeparator);
    }
    if (common$5.isAppliedFilter(this._settings.entryFilter, entry2)) {
      this._emitEntry(entry2);
    }
    if (entry2.dirent.isDirectory() && common$5.isAppliedFilter(this._settings.deepFilter, entry2)) {
      this._pushToQueue(fullpath, base === void 0 ? void 0 : entry2.path);
    }
  }
  _emitEntry(entry2) {
    this._emitter.emit("entry", entry2);
  }
};
async$4.default = AsyncReader;
Object.defineProperty(async$5, "__esModule", { value: true });
var async_1$4 = async$4;
var AsyncProvider = class {
  constructor(_root2, _settings) {
    this._root = _root2;
    this._settings = _settings;
    this._reader = new async_1$4.default(this._root, this._settings);
    this._storage = [];
  }
  read(callback) {
    this._reader.onError((error2) => {
      callFailureCallback(callback, error2);
    });
    this._reader.onEntry((entry2) => {
      this._storage.push(entry2);
    });
    this._reader.onEnd(() => {
      callSuccessCallback(callback, this._storage);
    });
    this._reader.read();
  }
};
async$5.default = AsyncProvider;
function callFailureCallback(callback, error2) {
  callback(error2);
}
function callSuccessCallback(callback, entries) {
  callback(null, entries);
}
var stream$2 = {};
Object.defineProperty(stream$2, "__esModule", { value: true });
var stream_1$5 = import_stream.default;
var async_1$3 = async$4;
var StreamProvider = class {
  constructor(_root2, _settings) {
    this._root = _root2;
    this._settings = _settings;
    this._reader = new async_1$3.default(this._root, this._settings);
    this._stream = new stream_1$5.Readable({
      objectMode: true,
      read: () => {
      },
      destroy: () => {
        if (!this._reader.isDestroyed) {
          this._reader.destroy();
        }
      }
    });
  }
  read() {
    this._reader.onError((error2) => {
      this._stream.emit("error", error2);
    });
    this._reader.onEntry((entry2) => {
      this._stream.push(entry2);
    });
    this._reader.onEnd(() => {
      this._stream.push(null);
    });
    this._reader.read();
    return this._stream;
  }
};
stream$2.default = StreamProvider;
var sync$4 = {};
var sync$3 = {};
Object.defineProperty(sync$3, "__esModule", { value: true });
var fsScandir$1 = out$2;
var common$4 = common$7;
var reader_1$3 = reader$1;
var SyncReader = class extends reader_1$3.default {
  constructor() {
    super(...arguments);
    this._scandir = fsScandir$1.scandirSync;
    this._storage = [];
    this._queue = /* @__PURE__ */ new Set();
  }
  read() {
    this._pushToQueue(this._root, this._settings.basePath);
    this._handleQueue();
    return this._storage;
  }
  _pushToQueue(directory, base) {
    this._queue.add({ directory, base });
  }
  _handleQueue() {
    for (const item of this._queue.values()) {
      this._handleDirectory(item.directory, item.base);
    }
  }
  _handleDirectory(directory, base) {
    try {
      const entries = this._scandir(directory, this._settings.fsScandirSettings);
      for (const entry2 of entries) {
        this._handleEntry(entry2, base);
      }
    } catch (error2) {
      this._handleError(error2);
    }
  }
  _handleError(error2) {
    if (!common$4.isFatalError(this._settings, error2)) {
      return;
    }
    throw error2;
  }
  _handleEntry(entry2, base) {
    const fullpath = entry2.path;
    if (base !== void 0) {
      entry2.path = common$4.joinPathSegments(base, entry2.name, this._settings.pathSegmentSeparator);
    }
    if (common$4.isAppliedFilter(this._settings.entryFilter, entry2)) {
      this._pushToStorage(entry2);
    }
    if (entry2.dirent.isDirectory() && common$4.isAppliedFilter(this._settings.deepFilter, entry2)) {
      this._pushToQueue(fullpath, base === void 0 ? void 0 : entry2.path);
    }
  }
  _pushToStorage(entry2) {
    this._storage.push(entry2);
  }
};
sync$3.default = SyncReader;
Object.defineProperty(sync$4, "__esModule", { value: true });
var sync_1$3 = sync$3;
var SyncProvider = class {
  constructor(_root2, _settings) {
    this._root = _root2;
    this._settings = _settings;
    this._reader = new sync_1$3.default(this._root, this._settings);
  }
  read() {
    return this._reader.read();
  }
};
sync$4.default = SyncProvider;
var settings$1 = {};
Object.defineProperty(settings$1, "__esModule", { value: true });
var path$d = import_path.default;
var fsScandir = out$2;
var Settings3 = class {
  constructor(_options2 = {}) {
    this._options = _options2;
    this.basePath = this._getValue(this._options.basePath, void 0);
    this.concurrency = this._getValue(this._options.concurrency, Number.POSITIVE_INFINITY);
    this.deepFilter = this._getValue(this._options.deepFilter, null);
    this.entryFilter = this._getValue(this._options.entryFilter, null);
    this.errorFilter = this._getValue(this._options.errorFilter, null);
    this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$d.sep);
    this.fsScandirSettings = new fsScandir.Settings({
      followSymbolicLinks: this._options.followSymbolicLinks,
      fs: this._options.fs,
      pathSegmentSeparator: this._options.pathSegmentSeparator,
      stats: this._options.stats,
      throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
    });
  }
  _getValue(option, value2) {
    return option !== null && option !== void 0 ? option : value2;
  }
};
settings$1.default = Settings3;
Object.defineProperty(out$3, "__esModule", { value: true });
out$3.Settings = out$3.walkStream = out$3.walkSync = out$3.walk = void 0;
var async_1$2 = async$5;
var stream_1$4 = stream$2;
var sync_1$2 = sync$4;
var settings_1$1 = settings$1;
out$3.Settings = settings_1$1.default;
function walk$2(directory, optionsOrSettingsOrCallback, callback) {
  if (typeof optionsOrSettingsOrCallback === "function") {
    new async_1$2.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
    return;
  }
  new async_1$2.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
}
out$3.walk = walk$2;
function walkSync(directory, optionsOrSettings) {
  const settings2 = getSettings(optionsOrSettings);
  const provider2 = new sync_1$2.default(directory, settings2);
  return provider2.read();
}
out$3.walkSync = walkSync;
function walkStream(directory, optionsOrSettings) {
  const settings2 = getSettings(optionsOrSettings);
  const provider2 = new stream_1$4.default(directory, settings2);
  return provider2.read();
}
out$3.walkStream = walkStream;
function getSettings(settingsOrOptions = {}) {
  if (settingsOrOptions instanceof settings_1$1.default) {
    return settingsOrOptions;
  }
  return new settings_1$1.default(settingsOrOptions);
}
var reader = {};
Object.defineProperty(reader, "__esModule", { value: true });
var path$c = import_path.default;
var fsStat$2 = out$1;
var utils$6 = utils$g;
var Reader2 = class {
  constructor(_settings) {
    this._settings = _settings;
    this._fsStatSettings = new fsStat$2.Settings({
      followSymbolicLink: this._settings.followSymbolicLinks,
      fs: this._settings.fs,
      throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
    });
  }
  _getFullEntryPath(filepath) {
    return path$c.resolve(this._settings.cwd, filepath);
  }
  _makeEntry(stats, pattern2) {
    const entry2 = {
      name: pattern2,
      path: pattern2,
      dirent: utils$6.fs.createDirentFromStats(pattern2, stats)
    };
    if (this._settings.stats) {
      entry2.stats = stats;
    }
    return entry2;
  }
  _isFatalError(error2) {
    return !utils$6.errno.isEnoentCodeError(error2) && !this._settings.suppressErrors;
  }
};
reader.default = Reader2;
var stream$1 = {};
Object.defineProperty(stream$1, "__esModule", { value: true });
var stream_1$3 = import_stream.default;
var fsStat$1 = out$1;
var fsWalk$2 = out$3;
var reader_1$2 = reader;
var ReaderStream = class extends reader_1$2.default {
  constructor() {
    super(...arguments);
    this._walkStream = fsWalk$2.walkStream;
    this._stat = fsStat$1.stat;
  }
  dynamic(root, options2) {
    return this._walkStream(root, options2);
  }
  static(patterns, options2) {
    const filepaths = patterns.map(this._getFullEntryPath, this);
    const stream4 = new stream_1$3.PassThrough({ objectMode: true });
    stream4._write = (index, _enc, done) => {
      return this._getEntry(filepaths[index], patterns[index], options2).then((entry2) => {
        if (entry2 !== null && options2.entryFilter(entry2)) {
          stream4.push(entry2);
        }
        if (index === filepaths.length - 1) {
          stream4.end();
        }
        done();
      }).catch(done);
    };
    for (let i = 0; i < filepaths.length; i++) {
      stream4.write(i);
    }
    return stream4;
  }
  _getEntry(filepath, pattern2, options2) {
    return this._getStat(filepath).then((stats) => this._makeEntry(stats, pattern2)).catch((error2) => {
      if (options2.errorFilter(error2)) {
        return null;
      }
      throw error2;
    });
  }
  _getStat(filepath) {
    return new Promise((resolve3, reject) => {
      this._stat(filepath, this._fsStatSettings, (error2, stats) => {
        return error2 === null ? resolve3(stats) : reject(error2);
      });
    });
  }
};
stream$1.default = ReaderStream;
Object.defineProperty(async$6, "__esModule", { value: true });
var fsWalk$1 = out$3;
var reader_1$1 = reader;
var stream_1$2 = stream$1;
var ReaderAsync = class extends reader_1$1.default {
  constructor() {
    super(...arguments);
    this._walkAsync = fsWalk$1.walk;
    this._readerStream = new stream_1$2.default(this._settings);
  }
  dynamic(root, options2) {
    return new Promise((resolve3, reject) => {
      this._walkAsync(root, options2, (error2, entries) => {
        if (error2 === null) {
          resolve3(entries);
        } else {
          reject(error2);
        }
      });
    });
  }
  async static(patterns, options2) {
    const entries = [];
    const stream4 = this._readerStream.static(patterns, options2);
    return new Promise((resolve3, reject) => {
      stream4.once("error", reject);
      stream4.on("data", (entry2) => entries.push(entry2));
      stream4.once("end", () => resolve3(entries));
    });
  }
};
async$6.default = ReaderAsync;
var provider = {};
var deep = {};
var partial = {};
var matcher = {};
Object.defineProperty(matcher, "__esModule", { value: true });
var utils$5 = utils$g;
var Matcher = class {
  constructor(_patterns, _settings, _micromatchOptions) {
    this._patterns = _patterns;
    this._settings = _settings;
    this._micromatchOptions = _micromatchOptions;
    this._storage = [];
    this._fillStorage();
  }
  _fillStorage() {
    for (const pattern2 of this._patterns) {
      const segments = this._getPatternSegments(pattern2);
      const sections = this._splitSegmentsIntoSections(segments);
      this._storage.push({
        complete: sections.length <= 1,
        pattern: pattern2,
        segments,
        sections
      });
    }
  }
  _getPatternSegments(pattern2) {
    const parts = utils$5.pattern.getPatternParts(pattern2, this._micromatchOptions);
    return parts.map((part) => {
      const dynamic = utils$5.pattern.isDynamicPattern(part, this._settings);
      if (!dynamic) {
        return {
          dynamic: false,
          pattern: part
        };
      }
      return {
        dynamic: true,
        pattern: part,
        patternRe: utils$5.pattern.makeRe(part, this._micromatchOptions)
      };
    });
  }
  _splitSegmentsIntoSections(segments) {
    return utils$5.array.splitWhen(segments, (segment) => segment.dynamic && utils$5.pattern.hasGlobStar(segment.pattern));
  }
};
matcher.default = Matcher;
Object.defineProperty(partial, "__esModule", { value: true });
var matcher_1 = matcher;
var PartialMatcher = class extends matcher_1.default {
  match(filepath) {
    const parts = filepath.split("/");
    const levels = parts.length;
    const patterns = this._storage.filter((info) => !info.complete || info.segments.length > levels);
    for (const pattern2 of patterns) {
      const section = pattern2.sections[0];
      if (!pattern2.complete && levels > section.length) {
        return true;
      }
      const match2 = parts.every((part, index) => {
        const segment = pattern2.segments[index];
        if (segment.dynamic && segment.patternRe.test(part)) {
          return true;
        }
        if (!segment.dynamic && segment.pattern === part) {
          return true;
        }
        return false;
      });
      if (match2) {
        return true;
      }
    }
    return false;
  }
};
partial.default = PartialMatcher;
Object.defineProperty(deep, "__esModule", { value: true });
var utils$4 = utils$g;
var partial_1 = partial;
var DeepFilter = class {
  constructor(_settings, _micromatchOptions) {
    this._settings = _settings;
    this._micromatchOptions = _micromatchOptions;
  }
  getFilter(basePath, positive, negative) {
    const matcher2 = this._getMatcher(positive);
    const negativeRe = this._getNegativePatternsRe(negative);
    return (entry2) => this._filter(basePath, entry2, matcher2, negativeRe);
  }
  _getMatcher(patterns) {
    return new partial_1.default(patterns, this._settings, this._micromatchOptions);
  }
  _getNegativePatternsRe(patterns) {
    const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
    return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
  }
  _filter(basePath, entry2, matcher2, negativeRe) {
    if (this._isSkippedByDeep(basePath, entry2.path)) {
      return false;
    }
    if (this._isSkippedSymbolicLink(entry2)) {
      return false;
    }
    const filepath = utils$4.path.removeLeadingDotSegment(entry2.path);
    if (this._isSkippedByPositivePatterns(filepath, matcher2)) {
      return false;
    }
    return this._isSkippedByNegativePatterns(filepath, negativeRe);
  }
  _isSkippedByDeep(basePath, entryPath) {
    if (this._settings.deep === Infinity) {
      return false;
    }
    return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
  }
  _getEntryLevel(basePath, entryPath) {
    const entryPathDepth = entryPath.split("/").length;
    if (basePath === "") {
      return entryPathDepth;
    }
    const basePathDepth = basePath.split("/").length;
    return entryPathDepth - basePathDepth;
  }
  _isSkippedSymbolicLink(entry2) {
    return !this._settings.followSymbolicLinks && entry2.dirent.isSymbolicLink();
  }
  _isSkippedByPositivePatterns(entryPath, matcher2) {
    return !this._settings.baseNameMatch && !matcher2.match(entryPath);
  }
  _isSkippedByNegativePatterns(entryPath, patternsRe) {
    return !utils$4.pattern.matchAny(entryPath, patternsRe);
  }
};
deep.default = DeepFilter;
var entry$1 = {};
Object.defineProperty(entry$1, "__esModule", { value: true });
var utils$3 = utils$g;
var EntryFilter = class {
  constructor(_settings, _micromatchOptions) {
    this._settings = _settings;
    this._micromatchOptions = _micromatchOptions;
    this.index = /* @__PURE__ */ new Map();
  }
  getFilter(positive, negative) {
    const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
    const negativeRe = utils$3.pattern.convertPatternsToRe(negative, Object.assign(Object.assign({}, this._micromatchOptions), { dot: true }));
    return (entry2) => this._filter(entry2, positiveRe, negativeRe);
  }
  _filter(entry2, positiveRe, negativeRe) {
    const filepath = utils$3.path.removeLeadingDotSegment(entry2.path);
    if (this._settings.unique && this._isDuplicateEntry(filepath)) {
      return false;
    }
    if (this._onlyFileFilter(entry2) || this._onlyDirectoryFilter(entry2)) {
      return false;
    }
    if (this._isSkippedByAbsoluteNegativePatterns(filepath, negativeRe)) {
      return false;
    }
    const isDirectory2 = entry2.dirent.isDirectory();
    const isMatched = this._isMatchToPatterns(filepath, positiveRe, isDirectory2) && !this._isMatchToPatterns(filepath, negativeRe, isDirectory2);
    if (this._settings.unique && isMatched) {
      this._createIndexRecord(filepath);
    }
    return isMatched;
  }
  _isDuplicateEntry(filepath) {
    return this.index.has(filepath);
  }
  _createIndexRecord(filepath) {
    this.index.set(filepath, void 0);
  }
  _onlyFileFilter(entry2) {
    return this._settings.onlyFiles && !entry2.dirent.isFile();
  }
  _onlyDirectoryFilter(entry2) {
    return this._settings.onlyDirectories && !entry2.dirent.isDirectory();
  }
  _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
    if (!this._settings.absolute) {
      return false;
    }
    const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
    return utils$3.pattern.matchAny(fullpath, patternsRe);
  }
  _isMatchToPatterns(filepath, patternsRe, isDirectory2) {
    const isMatched = utils$3.pattern.matchAny(filepath, patternsRe);
    if (!isMatched && isDirectory2) {
      return utils$3.pattern.matchAny(filepath + "/", patternsRe);
    }
    return isMatched;
  }
};
entry$1.default = EntryFilter;
var error$1 = {};
Object.defineProperty(error$1, "__esModule", { value: true });
var utils$2 = utils$g;
var ErrorFilter = class {
  constructor(_settings) {
    this._settings = _settings;
  }
  getFilter() {
    return (error2) => this._isNonFatalError(error2);
  }
  _isNonFatalError(error2) {
    return utils$2.errno.isEnoentCodeError(error2) || this._settings.suppressErrors;
  }
};
error$1.default = ErrorFilter;
var entry = {};
Object.defineProperty(entry, "__esModule", { value: true });
var utils$1 = utils$g;
var EntryTransformer = class {
  constructor(_settings) {
    this._settings = _settings;
  }
  getTransformer() {
    return (entry2) => this._transform(entry2);
  }
  _transform(entry2) {
    let filepath = entry2.path;
    if (this._settings.absolute) {
      filepath = utils$1.path.makeAbsolute(this._settings.cwd, filepath);
      filepath = utils$1.path.unixify(filepath);
    }
    if (this._settings.markDirectories && entry2.dirent.isDirectory()) {
      filepath += "/";
    }
    if (!this._settings.objectMode) {
      return filepath;
    }
    return Object.assign(Object.assign({}, entry2), { path: filepath });
  }
};
entry.default = EntryTransformer;
Object.defineProperty(provider, "__esModule", { value: true });
var path$b = import_path.default;
var deep_1 = deep;
var entry_1 = entry$1;
var error_1 = error$1;
var entry_2 = entry;
var Provider = class {
  constructor(_settings) {
    this._settings = _settings;
    this.errorFilter = new error_1.default(this._settings);
    this.entryFilter = new entry_1.default(this._settings, this._getMicromatchOptions());
    this.deepFilter = new deep_1.default(this._settings, this._getMicromatchOptions());
    this.entryTransformer = new entry_2.default(this._settings);
  }
  _getRootDirectory(task) {
    return path$b.resolve(this._settings.cwd, task.base);
  }
  _getReaderOptions(task) {
    const basePath = task.base === "." ? "" : task.base;
    return {
      basePath,
      pathSegmentSeparator: "/",
      concurrency: this._settings.concurrency,
      deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
      entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
      errorFilter: this.errorFilter.getFilter(),
      followSymbolicLinks: this._settings.followSymbolicLinks,
      fs: this._settings.fs,
      stats: this._settings.stats,
      throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
      transform: this.entryTransformer.getTransformer()
    };
  }
  _getMicromatchOptions() {
    return {
      dot: this._settings.dot,
      matchBase: this._settings.baseNameMatch,
      nobrace: !this._settings.braceExpansion,
      nocase: !this._settings.caseSensitiveMatch,
      noext: !this._settings.extglob,
      noglobstar: !this._settings.globstar,
      posix: true,
      strictSlashes: false
    };
  }
};
provider.default = Provider;
Object.defineProperty(async$7, "__esModule", { value: true });
var async_1$1 = async$6;
var provider_1$2 = provider;
var ProviderAsync = class extends provider_1$2.default {
  constructor() {
    super(...arguments);
    this._reader = new async_1$1.default(this._settings);
  }
  async read(task) {
    const root = this._getRootDirectory(task);
    const options2 = this._getReaderOptions(task);
    const entries = await this.api(root, task, options2);
    return entries.map((entry2) => options2.transform(entry2));
  }
  api(root, task, options2) {
    if (task.dynamic) {
      return this._reader.dynamic(root, options2);
    }
    return this._reader.static(task.patterns, options2);
  }
};
async$7.default = ProviderAsync;
var stream = {};
Object.defineProperty(stream, "__esModule", { value: true });
var stream_1$1 = import_stream.default;
var stream_2 = stream$1;
var provider_1$1 = provider;
var ProviderStream = class extends provider_1$1.default {
  constructor() {
    super(...arguments);
    this._reader = new stream_2.default(this._settings);
  }
  read(task) {
    const root = this._getRootDirectory(task);
    const options2 = this._getReaderOptions(task);
    const source = this.api(root, task, options2);
    const destination = new stream_1$1.Readable({ objectMode: true, read: () => {
    } });
    source.once("error", (error2) => destination.emit("error", error2)).on("data", (entry2) => destination.emit("data", options2.transform(entry2))).once("end", () => destination.emit("end"));
    destination.once("close", () => source.destroy());
    return destination;
  }
  api(root, task, options2) {
    if (task.dynamic) {
      return this._reader.dynamic(root, options2);
    }
    return this._reader.static(task.patterns, options2);
  }
};
stream.default = ProviderStream;
var sync$2 = {};
var sync$1 = {};
Object.defineProperty(sync$1, "__esModule", { value: true });
var fsStat = out$1;
var fsWalk = out$3;
var reader_1 = reader;
var ReaderSync = class extends reader_1.default {
  constructor() {
    super(...arguments);
    this._walkSync = fsWalk.walkSync;
    this._statSync = fsStat.statSync;
  }
  dynamic(root, options2) {
    return this._walkSync(root, options2);
  }
  static(patterns, options2) {
    const entries = [];
    for (const pattern2 of patterns) {
      const filepath = this._getFullEntryPath(pattern2);
      const entry2 = this._getEntry(filepath, pattern2, options2);
      if (entry2 === null || !options2.entryFilter(entry2)) {
        continue;
      }
      entries.push(entry2);
    }
    return entries;
  }
  _getEntry(filepath, pattern2, options2) {
    try {
      const stats = this._getStat(filepath);
      return this._makeEntry(stats, pattern2);
    } catch (error2) {
      if (options2.errorFilter(error2)) {
        return null;
      }
      throw error2;
    }
  }
  _getStat(filepath) {
    return this._statSync(filepath, this._fsStatSettings);
  }
};
sync$1.default = ReaderSync;
Object.defineProperty(sync$2, "__esModule", { value: true });
var sync_1$1 = sync$1;
var provider_1 = provider;
var ProviderSync = class extends provider_1.default {
  constructor() {
    super(...arguments);
    this._reader = new sync_1$1.default(this._settings);
  }
  read(task) {
    const root = this._getRootDirectory(task);
    const options2 = this._getReaderOptions(task);
    const entries = this.api(root, task, options2);
    return entries.map(options2.transform);
  }
  api(root, task, options2) {
    if (task.dynamic) {
      return this._reader.dynamic(root, options2);
    }
    return this._reader.static(task.patterns, options2);
  }
};
sync$2.default = ProviderSync;
var settings = {};
(function(exports2) {
  Object.defineProperty(exports2, "__esModule", { value: true });
  exports2.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
  const fs2 = import_fs.default;
  const os2 = import_os.default;
  const CPU_COUNT = Math.max(os2.cpus().length, 1);
  exports2.DEFAULT_FILE_SYSTEM_ADAPTER = {
    lstat: fs2.lstat,
    lstatSync: fs2.lstatSync,
    stat: fs2.stat,
    statSync: fs2.statSync,
    readdir: fs2.readdir,
    readdirSync: fs2.readdirSync
  };
  class Settings4 {
    constructor(_options2 = {}) {
      this._options = _options2;
      this.absolute = this._getValue(this._options.absolute, false);
      this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
      this.braceExpansion = this._getValue(this._options.braceExpansion, true);
      this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
      this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
      this.cwd = this._getValue(this._options.cwd, process.cwd());
      this.deep = this._getValue(this._options.deep, Infinity);
      this.dot = this._getValue(this._options.dot, false);
      this.extglob = this._getValue(this._options.extglob, true);
      this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
      this.fs = this._getFileSystemMethods(this._options.fs);
      this.globstar = this._getValue(this._options.globstar, true);
      this.ignore = this._getValue(this._options.ignore, []);
      this.markDirectories = this._getValue(this._options.markDirectories, false);
      this.objectMode = this._getValue(this._options.objectMode, false);
      this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
      this.onlyFiles = this._getValue(this._options.onlyFiles, true);
      this.stats = this._getValue(this._options.stats, false);
      this.suppressErrors = this._getValue(this._options.suppressErrors, false);
      this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
      this.unique = this._getValue(this._options.unique, true);
      if (this.onlyDirectories) {
        this.onlyFiles = false;
      }
      if (this.stats) {
        this.objectMode = true;
      }
      this.ignore = [].concat(this.ignore);
    }
    _getValue(option, value2) {
      return option === void 0 ? value2 : option;
    }
    _getFileSystemMethods(methods = {}) {
      return Object.assign(Object.assign({}, exports2.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
    }
  }
  exports2.default = Settings4;
})(settings);
var taskManager = tasks;
var async_1 = async$7;
var stream_1 = stream;
var sync_1 = sync$2;
var settings_1 = settings;
var utils = utils$g;
async function FastGlob(source, options2) {
  assertPatternsInput(source);
  const works = getWorks(source, async_1.default, options2);
  const result = await Promise.all(works);
  return utils.array.flatten(result);
}
(function(FastGlob2) {
  FastGlob2.glob = FastGlob2;
  FastGlob2.globSync = sync2;
  FastGlob2.globStream = stream4;
  FastGlob2.async = FastGlob2;
  function sync2(source, options2) {
    assertPatternsInput(source);
    const works = getWorks(source, sync_1.default, options2);
    return utils.array.flatten(works);
  }
  FastGlob2.sync = sync2;
  function stream4(source, options2) {
    assertPatternsInput(source);
    const works = getWorks(source, stream_1.default, options2);
    return utils.stream.merge(works);
  }
  FastGlob2.stream = stream4;
  function generateTasks(source, options2) {
    assertPatternsInput(source);
    const patterns = [].concat(source);
    const settings2 = new settings_1.default(options2);
    return taskManager.generate(patterns, settings2);
  }
  FastGlob2.generateTasks = generateTasks;
  function isDynamicPattern2(source, options2) {
    assertPatternsInput(source);
    const settings2 = new settings_1.default(options2);
    return utils.pattern.isDynamicPattern(source, settings2);
  }
  FastGlob2.isDynamicPattern = isDynamicPattern2;
  function escapePath(source) {
    assertPatternsInput(source);
    return utils.path.escape(source);
  }
  FastGlob2.escapePath = escapePath;
  function convertPathToPattern(source) {
    assertPatternsInput(source);
    return utils.path.convertPathToPattern(source);
  }
  FastGlob2.convertPathToPattern = convertPathToPattern;
  (function(posix2) {
    function escapePath2(source) {
      assertPatternsInput(source);
      return utils.path.escapePosixPath(source);
    }
    posix2.escapePath = escapePath2;
    function convertPathToPattern2(source) {
      assertPatternsInput(source);
      return utils.path.convertPosixPathToPattern(source);
    }
    posix2.convertPathToPattern = convertPathToPattern2;
  })(FastGlob2.posix || (FastGlob2.posix = {}));
  (function(win322) {
    function escapePath2(source) {
      assertPatternsInput(source);
      return utils.path.escapeWindowsPath(source);
    }
    win322.escapePath = escapePath2;
    function convertPathToPattern2(source) {
      assertPatternsInput(source);
      return utils.path.convertWindowsPathToPattern(source);
    }
    win322.convertPathToPattern = convertPathToPattern2;
  })(FastGlob2.win32 || (FastGlob2.win32 = {}));
})(FastGlob || (FastGlob = {}));
function getWorks(source, _Provider, options2) {
  const patterns = [].concat(source);
  const settings2 = new settings_1.default(options2);
  const tasks2 = taskManager.generate(patterns, settings2);
  const provider2 = new _Provider(settings2);
  return tasks2.map(provider2.read, provider2);
}
function assertPatternsInput(input) {
  const source = [].concat(input);
  const isValidSource = source.every((item) => utils.string.isString(item) && !utils.string.isEmpty(item));
  if (!isValidSource) {
    throw new TypeError("Patterns must be a string (non empty) or an array of strings");
  }
}
var out = FastGlob;
var glob = getDefaultExportFromCjs(out);
var src$2 = {};
var path$a = import_path.default;
var fs$a = import_fs.default;
var os$3 = import_os.default;
var fsReadFileAsync = fs$a.promises.readFile;
function getDefaultSearchPlaces(name2, sync2) {
  return [
    "package.json",
    `.${name2}rc.json`,
    `.${name2}rc.js`,
    `.${name2}rc.cjs`,
    ...sync2 ? [] : [`.${name2}rc.mjs`],
    `.config/${name2}rc`,
    `.config/${name2}rc.json`,
    `.config/${name2}rc.js`,
    `.config/${name2}rc.cjs`,
    ...sync2 ? [] : [`.config/${name2}rc.mjs`],
    `${name2}.config.js`,
    `${name2}.config.cjs`,
    ...sync2 ? [] : [`${name2}.config.mjs`]
  ];
}
function parentDir(p) {
  return path$a.dirname(p) || path$a.sep;
}
var jsonLoader = (_, content) => JSON.parse(content);
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require2;
var defaultLoadersSync = Object.freeze({
  ".js": requireFunc,
  ".json": requireFunc,
  ".cjs": requireFunc,
  noExt: jsonLoader
});
src$2.defaultLoadersSync = defaultLoadersSync;
var dynamicImport = async (id) => {
  try {
    const mod = await import(
      /* webpackIgnore: true */
      id
    );
    return mod.default;
  } catch (e2) {
    try {
      return requireFunc(id);
    } catch (requireE) {
      if (requireE.code === "ERR_REQUIRE_ESM" || requireE instanceof SyntaxError && requireE.toString().includes("Cannot use import statement outside a module")) {
        throw e2;
      }
      throw requireE;
    }
  }
};
var defaultLoaders = Object.freeze({
  ".js": dynamicImport,
  ".mjs": dynamicImport,
  ".cjs": dynamicImport,
  ".json": jsonLoader,
  noExt: jsonLoader
});
src$2.defaultLoaders = defaultLoaders;
function getOptions(name2, options2, sync2) {
  const conf = {
    stopDir: os$3.homedir(),
    searchPlaces: getDefaultSearchPlaces(name2, sync2),
    ignoreEmptySearchPlaces: true,
    cache: true,
    transform: (x) => x,
    packageProp: [name2],
    ...options2,
    loaders: {
      ...sync2 ? defaultLoadersSync : defaultLoaders,
      ...options2.loaders
    }
  };
  conf.searchPlaces.forEach((place) => {
    const key = path$a.extname(place) || "noExt";
    const loader = conf.loaders[key];
    if (!loader) {
      throw new Error(`Missing loader for extension "${place}"`);
    }
    if (typeof loader !== "function") {
      throw new Error(
        `Loader for extension "${place}" is not a function: Received ${typeof loader}.`
      );
    }
  });
  return conf;
}
function getPackageProp(props, obj) {
  if (typeof props === "string" && props in obj) return obj[props];
  return (Array.isArray(props) ? props : props.split(".")).reduce(
    (acc, prop) => acc === void 0 ? acc : acc[prop],
    obj
  ) || null;
}
function validateFilePath(filepath) {
  if (!filepath) throw new Error("load must pass a non-empty string");
}
function validateLoader(loader, ext2) {
  if (!loader) throw new Error(`No loader specified for extension "${ext2}"`);
  if (typeof loader !== "function") throw new Error("loader is not a function");
}
var makeEmplace = (enableCache) => (c, filepath, res) => {
  if (enableCache) c.set(filepath, res);
  return res;
};
src$2.lilconfig = function lilconfig(name2, options2) {
  const {
    ignoreEmptySearchPlaces,
    loaders,
    packageProp,
    searchPlaces,
    stopDir,
    transform: transform2,
    cache
  } = getOptions(name2, options2 ?? {}, false);
  const searchCache = /* @__PURE__ */ new Map();
  const loadCache = /* @__PURE__ */ new Map();
  const emplace = makeEmplace(cache);
  return {
    async search(searchFrom = process.cwd()) {
      const result = {
        config: null,
        filepath: ""
      };
      const visited = /* @__PURE__ */ new Set();
      let dir = searchFrom;
      dirLoop: while (true) {
        if (cache) {
          const r2 = searchCache.get(dir);
          if (r2 !== void 0) {
            for (const p of visited) searchCache.set(p, r2);
            return r2;
          }
          visited.add(dir);
        }
        for (const searchPlace of searchPlaces) {
          const filepath = path$a.join(dir, searchPlace);
          try {
            await fs$a.promises.access(filepath);
          } catch {
            continue;
          }
          const content = String(await fsReadFileAsync(filepath));
          const loaderKey = path$a.extname(searchPlace) || "noExt";
          const loader = loaders[loaderKey];
          if (searchPlace === "package.json") {
            const pkg = await loader(filepath, content);
            const maybeConfig = getPackageProp(packageProp, pkg);
            if (maybeConfig != null) {
              result.config = maybeConfig;
              result.filepath = filepath;
              break dirLoop;
            }
            continue;
          }
          const isEmpty2 = content.trim() === "";
          if (isEmpty2 && ignoreEmptySearchPlaces) continue;
          if (isEmpty2) {
            result.isEmpty = true;
            result.config = void 0;
          } else {
            validateLoader(loader, loaderKey);
            result.config = await loader(filepath, content);
          }
          result.filepath = filepath;
          break dirLoop;
        }
        if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
        dir = parentDir(dir);
      }
      const transformed = (
        // not found
        result.filepath === "" && result.config === null ? transform2(null) : transform2(result)
      );
      if (cache) {
        for (const p of visited) searchCache.set(p, transformed);
      }
      return transformed;
    },
    async load(filepath) {
      validateFilePath(filepath);
      const absPath = path$a.resolve(process.cwd(), filepath);
      if (cache && loadCache.has(absPath)) {
        return loadCache.get(absPath);
      }
      const { base, ext: ext2 } = path$a.parse(absPath);
      const loaderKey = ext2 || "noExt";
      const loader = loaders[loaderKey];
      validateLoader(loader, loaderKey);
      const content = String(await fsReadFileAsync(absPath));
      if (base === "package.json") {
        const pkg = await loader(absPath, content);
        return emplace(
          loadCache,
          absPath,
          transform2({
            config: getPackageProp(packageProp, pkg),
            filepath: absPath
          })
        );
      }
      const result = {
        config: null,
        filepath: absPath
      };
      const isEmpty2 = content.trim() === "";
      if (isEmpty2 && ignoreEmptySearchPlaces)
        return emplace(
          loadCache,
          absPath,
          transform2({
            config: void 0,
            filepath: absPath,
            isEmpty: true
          })
        );
      result.config = isEmpty2 ? void 0 : await loader(absPath, content);
      return emplace(
        loadCache,
        absPath,
        transform2(isEmpty2 ? { ...result, isEmpty: isEmpty2, config: void 0 } : result)
      );
    },
    clearLoadCache() {
      if (cache) loadCache.clear();
    },
    clearSearchCache() {
      if (cache) searchCache.clear();
    },
    clearCaches() {
      if (cache) {
        loadCache.clear();
        searchCache.clear();
      }
    }
  };
};
src$2.lilconfigSync = function lilconfigSync(name2, options2) {
  const {
    ignoreEmptySearchPlaces,
    loaders,
    packageProp,
    searchPlaces,
    stopDir,
    transform: transform2,
    cache
  } = getOptions(name2, options2 ?? {}, true);
  const searchCache = /* @__PURE__ */ new Map();
  const loadCache = /* @__PURE__ */ new Map();
  const emplace = makeEmplace(cache);
  return {
    search(searchFrom = process.cwd()) {
      const result = {
        config: null,
        filepath: ""
      };
      const visited = /* @__PURE__ */ new Set();
      let dir = searchFrom;
      dirLoop: while (true) {
        if (cache) {
          const r2 = searchCache.get(dir);
          if (r2 !== void 0) {
            for (const p of visited) searchCache.set(p, r2);
            return r2;
          }
          visited.add(dir);
        }
        for (const searchPlace of searchPlaces) {
          const filepath = path$a.join(dir, searchPlace);
          try {
            fs$a.accessSync(filepath);
          } catch {
            continue;
          }
          const loaderKey = path$a.extname(searchPlace) || "noExt";
          const loader = loaders[loaderKey];
          const content = String(fs$a.readFileSync(filepath));
          if (searchPlace === "package.json") {
            const pkg = loader(filepath, content);
            const maybeConfig = getPackageProp(packageProp, pkg);
            if (maybeConfig != null) {
              result.config = maybeConfig;
              result.filepath = filepath;
              break dirLoop;
            }
            continue;
          }
          const isEmpty2 = content.trim() === "";
          if (isEmpty2 && ignoreEmptySearchPlaces) continue;
          if (isEmpty2) {
            result.isEmpty = true;
            result.config = void 0;
          } else {
            validateLoader(loader, loaderKey);
            result.config = loader(filepath, content);
          }
          result.filepath = filepath;
          break dirLoop;
        }
        if (dir === stopDir || dir === parentDir(dir)) break dirLoop;
        dir = parentDir(dir);
      }
      const transformed = (
        // not found
        result.filepath === "" && result.config === null ? transform2(null) : transform2(result)
      );
      if (cache) {
        for (const p of visited) searchCache.set(p, transformed);
      }
      return transformed;
    },
    load(filepath) {
      validateFilePath(filepath);
      const absPath = path$a.resolve(process.cwd(), filepath);
      if (cache && loadCache.has(absPath)) {
        return loadCache.get(absPath);
      }
      const { base, ext: ext2 } = path$a.parse(absPath);
      const loaderKey = ext2 || "noExt";
      const loader = loaders[loaderKey];
      validateLoader(loader, loaderKey);
      const content = String(fs$a.readFileSync(absPath));
      if (base === "package.json") {
        const pkg = loader(absPath, content);
        return transform2({
          config: getPackageProp(packageProp, pkg),
          filepath: absPath
        });
      }
      const result = {
        config: null,
        filepath: absPath
      };
      const isEmpty2 = content.trim() === "";
      if (isEmpty2 && ignoreEmptySearchPlaces)
        return emplace(
          loadCache,
          absPath,
          transform2({
            filepath: absPath,
            config: void 0,
            isEmpty: true
          })
        );
      result.config = isEmpty2 ? void 0 : loader(absPath, content);
      return emplace(
        loadCache,
        absPath,
        transform2(isEmpty2 ? { ...result, isEmpty: isEmpty2, config: void 0 } : result)
      );
    },
    clearLoadCache() {
      if (cache) loadCache.clear();
    },
    clearSearchCache() {
      if (cache) searchCache.clear();
    },
    clearCaches() {
      if (cache) {
        loadCache.clear();
        searchCache.clear();
      }
    }
  };
};
var ALIAS = Symbol.for("yaml.alias");
var DOC = Symbol.for("yaml.document");
var MAP = Symbol.for("yaml.map");
var PAIR = Symbol.for("yaml.pair");
var SCALAR$1 = Symbol.for("yaml.scalar");
var SEQ = Symbol.for("yaml.seq");
var NODE_TYPE = Symbol.for("yaml.node.type");
var isAlias = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === ALIAS;
var isDocument = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === DOC;
var isMap = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === MAP;
var isPair = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === PAIR;
var isScalar$1 = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SCALAR$1;
var isSeq = (node2) => !!node2 && typeof node2 === "object" && node2[NODE_TYPE] === SEQ;
function isCollection$1(node2) {
  if (node2 && typeof node2 === "object")
    switch (node2[NODE_TYPE]) {
      case MAP:
      case SEQ:
        return true;
    }
  return false;
}
function isNode$1(node2) {
  if (node2 && typeof node2 === "object")
    switch (node2[NODE_TYPE]) {
      case ALIAS:
      case MAP:
      case SCALAR$1:
      case SEQ:
        return true;
    }
  return false;
}
var hasAnchor = (node2) => (isScalar$1(node2) || isCollection$1(node2)) && !!node2.anchor;
var BREAK$1 = Symbol("break visit");
var SKIP$1 = Symbol("skip children");
var REMOVE$1 = Symbol("remove node");
function visit$1(node2, visitor) {
  const visitor_ = initVisitor(visitor);
  if (isDocument(node2)) {
    const cd = visit_(null, node2.contents, visitor_, Object.freeze([node2]));
    if (cd === REMOVE$1)
      node2.contents = null;
  } else
    visit_(null, node2, visitor_, Object.freeze([]));
}
visit$1.BREAK = BREAK$1;
visit$1.SKIP = SKIP$1;
visit$1.REMOVE = REMOVE$1;
function visit_(key, node2, visitor, path3) {
  const ctrl = callVisitor(key, node2, visitor, path3);
  if (isNode$1(ctrl) || isPair(ctrl)) {
    replaceNode(key, path3, ctrl);
    return visit_(key, ctrl, visitor, path3);
  }
  if (typeof ctrl !== "symbol") {
    if (isCollection$1(node2)) {
      path3 = Object.freeze(path3.concat(node2));
      for (let i = 0; i < node2.items.length; ++i) {
        const ci = visit_(i, node2.items[i], visitor, path3);
        if (typeof ci === "number")
          i = ci - 1;
        else if (ci === BREAK$1)
          return BREAK$1;
        else if (ci === REMOVE$1) {
          node2.items.splice(i, 1);
          i -= 1;
        }
      }
    } else if (isPair(node2)) {
      path3 = Object.freeze(path3.concat(node2));
      const ck = visit_("key", node2.key, visitor, path3);
      if (ck === BREAK$1)
        return BREAK$1;
      else if (ck === REMOVE$1)
        node2.key = null;
      const cv = visit_("value", node2.value, visitor, path3);
      if (cv === BREAK$1)
        return BREAK$1;
      else if (cv === REMOVE$1)
        node2.value = null;
    }
  }
  return ctrl;
}
async function visitAsync(node2, visitor) {
  const visitor_ = initVisitor(visitor);
  if (isDocument(node2)) {
    const cd = await visitAsync_(null, node2.contents, visitor_, Object.freeze([node2]));
    if (cd === REMOVE$1)
      node2.contents = null;
  } else
    await visitAsync_(null, node2, visitor_, Object.freeze([]));
}
visitAsync.BREAK = BREAK$1;
visitAsync.SKIP = SKIP$1;
visitAsync.REMOVE = REMOVE$1;
async function visitAsync_(key, node2, visitor, path3) {
  const ctrl = await callVisitor(key, node2, visitor, path3);
  if (isNode$1(ctrl) || isPair(ctrl)) {
    replaceNode(key, path3, ctrl);
    return visitAsync_(key, ctrl, visitor, path3);
  }
  if (typeof ctrl !== "symbol") {
    if (isCollection$1(node2)) {
      path3 = Object.freeze(path3.concat(node2));
      for (let i = 0; i < node2.items.length; ++i) {
        const ci = await visitAsync_(i, node2.items[i], visitor, path3);
        if (typeof ci === "number")
          i = ci - 1;
        else if (ci === BREAK$1)
          return BREAK$1;
        else if (ci === REMOVE$1) {
          node2.items.splice(i, 1);
          i -= 1;
        }
      }
    } else if (isPair(node2)) {
      path3 = Object.freeze(path3.concat(node2));
      const ck = await visitAsync_("key", node2.key, visitor, path3);
      if (ck === BREAK$1)
        return BREAK$1;
      else if (ck === REMOVE$1)
        node2.key = null;
      const cv = await visitAsync_("value", node2.value, visitor, path3);
      if (cv === BREAK$1)
        return BREAK$1;
      else if (cv === REMOVE$1)
        node2.value = null;
    }
  }
  return ctrl;
}
function initVisitor(visitor) {
  if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
    return Object.assign({
      Alias: visitor.Node,
      Map: visitor.Node,
      Scalar: visitor.Node,
      Seq: visitor.Node
    }, visitor.Value && {
      Map: visitor.Value,
      Scalar: visitor.Value,
      Seq: visitor.Value
    }, visitor.Collection && {
      Map: visitor.Collection,
      Seq: visitor.Collection
    }, visitor);
  }
  return visitor;
}
function callVisitor(key, node2, visitor, path3) {
  var _a4, _b3, _c2, _d2, _e2;
  if (typeof visitor === "function")
    return visitor(key, node2, path3);
  if (isMap(node2))
    return (_a4 = visitor.Map) == null ? void 0 : _a4.call(visitor, key, node2, path3);
  if (isSeq(node2))
    return (_b3 = visitor.Seq) == null ? void 0 : _b3.call(visitor, key, node2, path3);
  if (isPair(node2))
    return (_c2 = visitor.Pair) == null ? void 0 : _c2.call(visitor, key, node2, path3);
  if (isScalar$1(node2))
    return (_d2 = visitor.Scalar) == null ? void 0 : _d2.call(visitor, key, node2, path3);
  if (isAlias(node2))
    return (_e2 = visitor.Alias) == null ? void 0 : _e2.call(visitor, key, node2, path3);
  return void 0;
}
function replaceNode(key, path3, node2) {
  const parent = path3[path3.length - 1];
  if (isCollection$1(parent)) {
    parent.items[key] = node2;
  } else if (isPair(parent)) {
    if (key === "key")
      parent.key = node2;
    else
      parent.value = node2;
  } else if (isDocument(parent)) {
    parent.contents = node2;
  } else {
    const pt = isAlias(parent) ? "alias" : "scalar";
    throw new Error(`Cannot replace node with ${pt} parent`);
  }
}
var escapeChars = {
  "!": "%21",
  ",": "%2C",
  "[": "%5B",
  "]": "%5D",
  "{": "%7B",
  "}": "%7D"
};
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
var Directives = class _Directives {
  constructor(yaml2, tags) {
    this.docStart = null;
    this.docEnd = false;
    this.yaml = Object.assign({}, _Directives.defaultYaml, yaml2);
    this.tags = Object.assign({}, _Directives.defaultTags, tags);
  }
  clone() {
    const copy = new _Directives(this.yaml, this.tags);
    copy.docStart = this.docStart;
    return copy;
  }
  /**
   * During parsing, get a Directives instance for the current document and
   * update the stream state according to the current version's spec.
   */
  atDocument() {
    const res = new _Directives(this.yaml, this.tags);
    switch (this.yaml.version) {
      case "1.1":
        this.atNextDocument = true;
        break;
      case "1.2":
        this.atNextDocument = false;
        this.yaml = {
          explicit: _Directives.defaultYaml.explicit,
          version: "1.2"
        };
        this.tags = Object.assign({}, _Directives.defaultTags);
        break;
    }
    return res;
  }
  /**
   * @param onError - May be called even if the action was successful
   * @returns `true` on success
   */
  add(line, onError2) {
    if (this.atNextDocument) {
      this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
      this.tags = Object.assign({}, _Directives.defaultTags);
      this.atNextDocument = false;
    }
    const parts = line.trim().split(/[ \t]+/);
    const name2 = parts.shift();
    switch (name2) {
      case "%TAG": {
        if (parts.length !== 2) {
          onError2(0, "%TAG directive should contain exactly two parts");
          if (parts.length < 2)
            return false;
        }
        const [handle2, prefix] = parts;
        this.tags[handle2] = prefix;
        return true;
      }
      case "%YAML": {
        this.yaml.explicit = true;
        if (parts.length !== 1) {
          onError2(0, "%YAML directive should contain exactly one part");
          return false;
        }
        const [version3] = parts;
        if (version3 === "1.1" || version3 === "1.2") {
          this.yaml.version = version3;
          return true;
        } else {
          const isValid = /^\d+\.\d+$/.test(version3);
          onError2(6, `Unsupported YAML version ${version3}`, isValid);
          return false;
        }
      }
      default:
        onError2(0, `Unknown directive ${name2}`, true);
        return false;
    }
  }
  /**
   * Resolves a tag, matching handles to those defined in %TAG directives.
   *
   * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
   *   `'!local'` tag, or `null` if unresolvable.
   */
  tagName(source, onError2) {
    if (source === "!")
      return "!";
    if (source[0] !== "!") {
      onError2(`Not a valid tag: ${source}`);
      return null;
    }
    if (source[1] === "<") {
      const verbatim = source.slice(2, -1);
      if (verbatim === "!" || verbatim === "!!") {
        onError2(`Verbatim tags aren't resolved, so ${source} is invalid.`);
        return null;
      }
      if (source[source.length - 1] !== ">")
        onError2("Verbatim tags must end with a >");
      return verbatim;
    }
    const [, handle2, suffix] = source.match(/^(.*!)([^!]*)$/s);
    if (!suffix)
      onError2(`The ${source} tag has no suffix`);
    const prefix = this.tags[handle2];
    if (prefix) {
      try {
        return prefix + decodeURIComponent(suffix);
      } catch (error2) {
        onError2(String(error2));
        return null;
      }
    }
    if (handle2 === "!")
      return source;
    onError2(`Could not resolve tag: ${source}`);
    return null;
  }
  /**
   * Given a fully resolved tag, returns its printable string form,
   * taking into account current tag prefixes and defaults.
   */
  tagString(tag) {
    for (const [handle2, prefix] of Object.entries(this.tags)) {
      if (tag.startsWith(prefix))
        return handle2 + escapeTagName(tag.substring(prefix.length));
    }
    return tag[0] === "!" ? tag : `!<${tag}>`;
  }
  toString(doc) {
    const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
    const tagEntries = Object.entries(this.tags);
    let tagNames;
    if (doc && tagEntries.length > 0 && isNode$1(doc.contents)) {
      const tags = {};
      visit$1(doc.contents, (_key, node2) => {
        if (isNode$1(node2) && node2.tag)
          tags[node2.tag] = true;
      });
      tagNames = Object.keys(tags);
    } else
      tagNames = [];
    for (const [handle2, prefix] of tagEntries) {
      if (handle2 === "!!" && prefix === "tag:yaml.org,2002:")
        continue;
      if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
        lines.push(`%TAG ${handle2} ${prefix}`);
    }
    return lines.join("\n");
  }
};
Directives.defaultYaml = { explicit: false, version: "1.2" };
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
function anchorIsValid(anchor) {
  if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
    const sa = JSON.stringify(anchor);
    const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
    throw new Error(msg);
  }
  return true;
}
function anchorNames(root) {
  const anchors = /* @__PURE__ */ new Set();
  visit$1(root, {
    Value(_key, node2) {
      if (node2.anchor)
        anchors.add(node2.anchor);
    }
  });
  return anchors;
}
function findNewAnchor(prefix, exclude) {
  for (let i = 1; true; ++i) {
    const name2 = `${prefix}${i}`;
    if (!exclude.has(name2))
      return name2;
  }
}
function createNodeAnchors(doc, prefix) {
  const aliasObjects = [];
  const sourceObjects = /* @__PURE__ */ new Map();
  let prevAnchors = null;
  return {
    onAnchor: (source) => {
      aliasObjects.push(source);
      if (!prevAnchors)
        prevAnchors = anchorNames(doc);
      const anchor = findNewAnchor(prefix, prevAnchors);
      prevAnchors.add(anchor);
      return anchor;
    },
    /**
     * With circular references, the source node is only resolved after all
     * of its child nodes are. This is why anchors are set only after all of
     * the nodes have been created.
     */
    setAnchors: () => {
      for (const source of aliasObjects) {
        const ref = sourceObjects.get(source);
        if (typeof ref === "object" && ref.anchor && (isScalar$1(ref.node) || isCollection$1(ref.node))) {
          ref.node.anchor = ref.anchor;
        } else {
          const error2 = new Error("Failed to resolve repeated object (this should not happen)");
          error2.source = source;
          throw error2;
        }
      }
    },
    sourceObjects
  };
}
function applyReviver(reviver, obj, key, val) {
  if (val && typeof val === "object") {
    if (Array.isArray(val)) {
      for (let i = 0, len = val.length; i < len; ++i) {
        const v0 = val[i];
        const v1 = applyReviver(reviver, val, String(i), v0);
        if (v1 === void 0)
          delete val[i];
        else if (v1 !== v0)
          val[i] = v1;
      }
    } else if (val instanceof Map) {
      for (const k of Array.from(val.keys())) {
        const v0 = val.get(k);
        const v1 = applyReviver(reviver, val, k, v0);
        if (v1 === void 0)
          val.delete(k);
        else if (v1 !== v0)
          val.set(k, v1);
      }
    } else if (val instanceof Set) {
      for (const v0 of Array.from(val)) {
        const v1 = applyReviver(reviver, val, v0, v0);
        if (v1 === void 0)
          val.delete(v0);
        else if (v1 !== v0) {
          val.delete(v0);
          val.add(v1);
        }
      }
    } else {
      for (const [k, v0] of Object.entries(val)) {
        const v1 = applyReviver(reviver, val, k, v0);
        if (v1 === void 0)
          delete val[k];
        else if (v1 !== v0)
          val[k] = v1;
      }
    }
  }
  return reviver.call(obj, key, val);
}
function toJS(value2, arg, ctx) {
  if (Array.isArray(value2))
    return value2.map((v, i) => toJS(v, String(i), ctx));
  if (value2 && typeof value2.toJSON === "function") {
    if (!ctx || !hasAnchor(value2))
      return value2.toJSON(arg, ctx);
    const data = { aliasCount: 0, count: 1, res: void 0 };
    ctx.anchors.set(value2, data);
    ctx.onCreate = (res2) => {
      data.res = res2;
      delete ctx.onCreate;
    };
    const res = value2.toJSON(arg, ctx);
    if (ctx.onCreate)
      ctx.onCreate(res);
    return res;
  }
  if (typeof value2 === "bigint" && !(ctx == null ? void 0 : ctx.keep))
    return Number(value2);
  return value2;
}
var NodeBase = class {
  constructor(type) {
    Object.defineProperty(this, NODE_TYPE, { value: type });
  }
  /** Create a copy of this node.  */
  clone() {
    const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
    if (this.range)
      copy.range = this.range.slice();
    return copy;
  }
  /** A plain JavaScript representation of this node. */
  toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
    if (!isDocument(doc))
      throw new TypeError("A document argument is required");
    const ctx = {
      anchors: /* @__PURE__ */ new Map(),
      doc,
      keep: true,
      mapAsMap: mapAsMap === true,
      mapKeyWarned: false,
      maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
    };
    const res = toJS(this, "", ctx);
    if (typeof onAnchor === "function")
      for (const { count, res: res2 } of ctx.anchors.values())
        onAnchor(res2, count);
    return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
  }
};
var Alias = class extends NodeBase {
  constructor(source) {
    super(ALIAS);
    this.source = source;
    Object.defineProperty(this, "tag", {
      set() {
        throw new Error("Alias nodes cannot have tags");
      }
    });
  }
  /**
   * Resolve the value of this alias within `doc`, finding the last
   * instance of the `source` anchor before this node.
   */
  resolve(doc) {
    let found2 = void 0;
    visit$1(doc, {
      Node: (_key, node2) => {
        if (node2 === this)
          return visit$1.BREAK;
        if (node2.anchor === this.source)
          found2 = node2;
      }
    });
    return found2;
  }
  toJSON(_arg, ctx) {
    if (!ctx)
      return { source: this.source };
    const { anchors, doc, maxAliasCount } = ctx;
    const source = this.resolve(doc);
    if (!source) {
      const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
      throw new ReferenceError(msg);
    }
    let data = anchors.get(source);
    if (!data) {
      toJS(source, null, ctx);
      data = anchors.get(source);
    }
    if (!data || data.res === void 0) {
      const msg = "This should not happen: Alias anchor was not resolved?";
      throw new ReferenceError(msg);
    }
    if (maxAliasCount >= 0) {
      data.count += 1;
      if (data.aliasCount === 0)
        data.aliasCount = getAliasCount(doc, source, anchors);
      if (data.count * data.aliasCount > maxAliasCount) {
        const msg = "Excessive alias count indicates a resource exhaustion attack";
        throw new ReferenceError(msg);
      }
    }
    return data.res;
  }
  toString(ctx, _onComment, _onChompKeep) {
    const src2 = `*${this.source}`;
    if (ctx) {
      anchorIsValid(this.source);
      if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
        const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
        throw new Error(msg);
      }
      if (ctx.implicitKey)
        return `${src2} `;
    }
    return src2;
  }
};
function getAliasCount(doc, node2, anchors) {
  if (isAlias(node2)) {
    const source = node2.resolve(doc);
    const anchor = anchors && source && anchors.get(source);
    return anchor ? anchor.count * anchor.aliasCount : 0;
  } else if (isCollection$1(node2)) {
    let count = 0;
    for (const item of node2.items) {
      const c = getAliasCount(doc, item, anchors);
      if (c > count)
        count = c;
    }
    return count;
  } else if (isPair(node2)) {
    const kc = getAliasCount(doc, node2.key, anchors);
    const vc = getAliasCount(doc, node2.value, anchors);
    return Math.max(kc, vc);
  }
  return 1;
}
var isScalarValue = (value2) => !value2 || typeof value2 !== "function" && typeof value2 !== "object";
var Scalar = class extends NodeBase {
  constructor(value2) {
    super(SCALAR$1);
    this.value = value2;
  }
  toJSON(arg, ctx) {
    return (ctx == null ? void 0 : ctx.keep) ? this.value : toJS(this.value, arg, ctx);
  }
  toString() {
    return String(this.value);
  }
};
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
Scalar.PLAIN = "PLAIN";
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
var defaultTagPrefix = "tag:yaml.org,2002:";
function findTagObject(value2, tagName, tags) {
  if (tagName) {
    const match2 = tags.filter((t2) => t2.tag === tagName);
    const tagObj = match2.find((t2) => !t2.format) ?? match2[0];
    if (!tagObj)
      throw new Error(`Tag ${tagName} not found`);
    return tagObj;
  }
  return tags.find((t2) => {
    var _a4;
    return ((_a4 = t2.identify) == null ? void 0 : _a4.call(t2, value2)) && !t2.format;
  });
}
function createNode(value2, tagName, ctx) {
  var _a4, _b3, _c2;
  if (isDocument(value2))
    value2 = value2.contents;
  if (isNode$1(value2))
    return value2;
  if (isPair(value2)) {
    const map2 = (_b3 = (_a4 = ctx.schema[MAP]).createNode) == null ? void 0 : _b3.call(_a4, ctx.schema, null, ctx);
    map2.items.push(value2);
    return map2;
  }
  if (value2 instanceof String || value2 instanceof Number || value2 instanceof Boolean || typeof BigInt !== "undefined" && value2 instanceof BigInt) {
    value2 = value2.valueOf();
  }
  const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema2, sourceObjects } = ctx;
  let ref = void 0;
  if (aliasDuplicateObjects && value2 && typeof value2 === "object") {
    ref = sourceObjects.get(value2);
    if (ref) {
      if (!ref.anchor)
        ref.anchor = onAnchor(value2);
      return new Alias(ref.anchor);
    } else {
      ref = { anchor: null, node: null };
      sourceObjects.set(value2, ref);
    }
  }
  if (tagName == null ? void 0 : tagName.startsWith("!!"))
    tagName = defaultTagPrefix + tagName.slice(2);
  let tagObj = findTagObject(value2, tagName, schema2.tags);
  if (!tagObj) {
    if (value2 && typeof value2.toJSON === "function") {
      value2 = value2.toJSON();
    }
    if (!value2 || typeof value2 !== "object") {
      const node3 = new Scalar(value2);
      if (ref)
        ref.node = node3;
      return node3;
    }
    tagObj = value2 instanceof Map ? schema2[MAP] : Symbol.iterator in Object(value2) ? schema2[SEQ] : schema2[MAP];
  }
  if (onTagObj) {
    onTagObj(tagObj);
    delete ctx.onTagObj;
  }
  const node2 = (tagObj == null ? void 0 : tagObj.createNode) ? tagObj.createNode(ctx.schema, value2, ctx) : typeof ((_c2 = tagObj == null ? void 0 : tagObj.nodeClass) == null ? void 0 : _c2.from) === "function" ? tagObj.nodeClass.from(ctx.schema, value2, ctx) : new Scalar(value2);
  if (tagName)
    node2.tag = tagName;
  else if (!tagObj.default)
    node2.tag = tagObj.tag;
  if (ref)
    ref.node = node2;
  return node2;
}
function collectionFromPath(schema2, path3, value2) {
  let v = value2;
  for (let i = path3.length - 1; i >= 0; --i) {
    const k = path3[i];
    if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
      const a = [];
      a[k] = v;
      v = a;
    } else {
      v = /* @__PURE__ */ new Map([[k, v]]);
    }
  }
  return createNode(v, void 0, {
    aliasDuplicateObjects: false,
    keepUndefined: false,
    onAnchor: () => {
      throw new Error("This should not happen, please report a bug.");
    },
    schema: schema2,
    sourceObjects: /* @__PURE__ */ new Map()
  });
}
var isEmptyPath = (path3) => path3 == null || typeof path3 === "object" && !!path3[Symbol.iterator]().next().done;
var Collection = class extends NodeBase {
  constructor(type, schema2) {
    super(type);
    Object.defineProperty(this, "schema", {
      value: schema2,
      configurable: true,
      enumerable: false,
      writable: true
    });
  }
  /**
   * Create a copy of this collection.
   *
   * @param schema - If defined, overwrites the original's schema
   */
  clone(schema2) {
    const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
    if (schema2)
      copy.schema = schema2;
    copy.items = copy.items.map((it) => isNode$1(it) || isPair(it) ? it.clone(schema2) : it);
    if (this.range)
      copy.range = this.range.slice();
    return copy;
  }
  /**
   * Adds a value to the collection. For `!!map` and `!!omap` the value must
   * be a Pair instance or a `{ key, value }` object, which may not have a key
   * that already exists in the map.
   */
  addIn(path3, value2) {
    if (isEmptyPath(path3))
      this.add(value2);
    else {
      const [key, ...rest] = path3;
      const node2 = this.get(key, true);
      if (isCollection$1(node2))
        node2.addIn(rest, value2);
      else if (node2 === void 0 && this.schema)
        this.set(key, collectionFromPath(this.schema, rest, value2));
      else
        throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
  }
  /**
   * Removes a value from the collection.
   * @returns `true` if the item was found and removed.
   */
  deleteIn(path3) {
    const [key, ...rest] = path3;
    if (rest.length === 0)
      return this.delete(key);
    const node2 = this.get(key, true);
    if (isCollection$1(node2))
      return node2.deleteIn(rest);
    else
      throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
  }
  /**
   * Returns item at `key`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  getIn(path3, keepScalar) {
    const [key, ...rest] = path3;
    const node2 = this.get(key, true);
    if (rest.length === 0)
      return !keepScalar && isScalar$1(node2) ? node2.value : node2;
    else
      return isCollection$1(node2) ? node2.getIn(rest, keepScalar) : void 0;
  }
  hasAllNullValues(allowScalar) {
    return this.items.every((node2) => {
      if (!isPair(node2))
        return false;
      const n2 = node2.value;
      return n2 == null || allowScalar && isScalar$1(n2) && n2.value == null && !n2.commentBefore && !n2.comment && !n2.tag;
    });
  }
  /**
   * Checks if the collection includes a value with the key `key`.
   */
  hasIn(path3) {
    const [key, ...rest] = path3;
    if (rest.length === 0)
      return this.has(key);
    const node2 = this.get(key, true);
    return isCollection$1(node2) ? node2.hasIn(rest) : false;
  }
  /**
   * Sets a value in this collection. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  setIn(path3, value2) {
    const [key, ...rest] = path3;
    if (rest.length === 0) {
      this.set(key, value2);
    } else {
      const node2 = this.get(key, true);
      if (isCollection$1(node2))
        node2.setIn(rest, value2);
      else if (node2 === void 0 && this.schema)
        this.set(key, collectionFromPath(this.schema, rest, value2));
      else
        throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
  }
};
Collection.maxFlowStringSingleLineLength = 60;
var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#");
function indentComment(comment, indent) {
  if (/^\n+$/.test(comment))
    return comment.substring(1);
  return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment;
var FOLD_FLOW = "flow";
var FOLD_BLOCK = "block";
var FOLD_QUOTED = "quoted";
function foldFlowLines(text, indent, mode2 = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
  if (!lineWidth || lineWidth < 0)
    return text;
  const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
  if (text.length <= endStep)
    return text;
  const folds = [];
  const escapedFolds = {};
  let end = lineWidth - indent.length;
  if (typeof indentAtStart === "number") {
    if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
      folds.push(0);
    else
      end = lineWidth - indentAtStart;
  }
  let split = void 0;
  let prev = void 0;
  let overflow = false;
  let i = -1;
  let escStart = -1;
  let escEnd = -1;
  if (mode2 === FOLD_BLOCK) {
    i = consumeMoreIndentedLines(text, i, indent.length);
    if (i !== -1)
      end = i + endStep;
  }
  for (let ch; ch = text[i += 1]; ) {
    if (mode2 === FOLD_QUOTED && ch === "\\") {
      escStart = i;
      switch (text[i + 1]) {
        case "x":
          i += 3;
          break;
        case "u":
          i += 5;
          break;
        case "U":
          i += 9;
          break;
        default:
          i += 1;
      }
      escEnd = i;
    }
    if (ch === "\n") {
      if (mode2 === FOLD_BLOCK)
        i = consumeMoreIndentedLines(text, i, indent.length);
      end = i + indent.length + endStep;
      split = void 0;
    } else {
      if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== "	") {
        const next = text[i + 1];
        if (next && next !== " " && next !== "\n" && next !== "	")
          split = i;
      }
      if (i >= end) {
        if (split) {
          folds.push(split);
          end = split + endStep;
          split = void 0;
        } else if (mode2 === FOLD_QUOTED) {
          while (prev === " " || prev === "	") {
            prev = ch;
            ch = text[i += 1];
            overflow = true;
          }
          const j = i > escEnd + 1 ? i - 2 : escStart - 1;
          if (escapedFolds[j])
            return text;
          folds.push(j);
          escapedFolds[j] = true;
          end = j + endStep;
          split = void 0;
        } else {
          overflow = true;
        }
      }
    }
    prev = ch;
  }
  if (overflow && onOverflow)
    onOverflow();
  if (folds.length === 0)
    return text;
  if (onFold)
    onFold();
  let res = text.slice(0, folds[0]);
  for (let i2 = 0; i2 < folds.length; ++i2) {
    const fold = folds[i2];
    const end2 = folds[i2 + 1] || text.length;
    if (fold === 0)
      res = `
${indent}${text.slice(0, end2)}`;
    else {
      if (mode2 === FOLD_QUOTED && escapedFolds[fold])
        res += `${text[fold]}\\`;
      res += `
${indent}${text.slice(fold + 1, end2)}`;
    }
  }
  return res;
}
function consumeMoreIndentedLines(text, i, indent) {
  let end = i;
  let start = i + 1;
  let ch = text[start];
  while (ch === " " || ch === "	") {
    if (i < start + indent) {
      ch = text[++i];
    } else {
      do {
        ch = text[++i];
      } while (ch && ch !== "\n");
      end = i;
      start = i + 1;
      ch = text[start];
    }
  }
  return end;
}
var getFoldOptions = (ctx, isBlock2) => ({
  indentAtStart: isBlock2 ? ctx.indent.length : ctx.indentAtStart,
  lineWidth: ctx.options.lineWidth,
  minContentWidth: ctx.options.minContentWidth
});
var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
  if (!lineWidth || lineWidth < 0)
    return false;
  const limit = lineWidth - indentLength;
  const strLen = str.length;
  if (strLen <= limit)
    return false;
  for (let i = 0, start = 0; i < strLen; ++i) {
    if (str[i] === "\n") {
      if (i - start > limit)
        return true;
      start = i + 1;
      if (strLen - start <= limit)
        return false;
    }
  }
  return true;
}
function doubleQuotedString(value2, ctx) {
  const json = JSON.stringify(value2);
  if (ctx.options.doubleQuotedAsJSON)
    return json;
  const { implicitKey } = ctx;
  const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
  const indent = ctx.indent || (containsDocumentMarker(value2) ? "  " : "");
  let str = "";
  let start = 0;
  for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
    if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
      str += json.slice(start, i) + "\\ ";
      i += 1;
      start = i;
      ch = "\\";
    }
    if (ch === "\\")
      switch (json[i + 1]) {
        case "u":
          {
            str += json.slice(start, i);
            const code = json.substr(i + 2, 4);
            switch (code) {
              case "0000":
                str += "\\0";
                break;
              case "0007":
                str += "\\a";
                break;
              case "000b":
                str += "\\v";
                break;
              case "001b":
                str += "\\e";
                break;
              case "0085":
                str += "\\N";
                break;
              case "00a0":
                str += "\\_";
                break;
              case "2028":
                str += "\\L";
                break;
              case "2029":
                str += "\\P";
                break;
              default:
                if (code.substr(0, 2) === "00")
                  str += "\\x" + code.substr(2);
                else
                  str += json.substr(i, 6);
            }
            i += 5;
            start = i + 1;
          }
          break;
        case "n":
          if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
            i += 1;
          } else {
            str += json.slice(start, i) + "\n\n";
            while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
              str += "\n";
              i += 2;
            }
            str += indent;
            if (json[i + 2] === " ")
              str += "\\";
            i += 1;
            start = i + 1;
          }
          break;
        default:
          i += 1;
      }
  }
  str = start ? str + json.slice(start) : json;
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value2, ctx) {
  if (ctx.options.singleQuote === false || ctx.implicitKey && value2.includes("\n") || /[ \t]\n|\n[ \t]/.test(value2))
    return doubleQuotedString(value2, ctx);
  const indent = ctx.indent || (containsDocumentMarker(value2) ? "  " : "");
  const res = "'" + value2.replace(/'/g, "''").replace(/\n+/g, `$&
${indent}`) + "'";
  return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value2, ctx) {
  const { singleQuote } = ctx.options;
  let qs2;
  if (singleQuote === false)
    qs2 = doubleQuotedString;
  else {
    const hasDouble = value2.includes('"');
    const hasSingle = value2.includes("'");
    if (hasDouble && !hasSingle)
      qs2 = singleQuotedString;
    else if (hasSingle && !hasDouble)
      qs2 = doubleQuotedString;
    else
      qs2 = singleQuote ? singleQuotedString : doubleQuotedString;
  }
  return qs2(value2, ctx);
}
var blockEndNewlines;
try {
  blockEndNewlines = new RegExp("(^|(?\n";
  let chomp;
  let endStart;
  for (endStart = value2.length; endStart > 0; --endStart) {
    const ch = value2[endStart - 1];
    if (ch !== "\n" && ch !== "	" && ch !== " ")
      break;
  }
  let end = value2.substring(endStart);
  const endNlPos = end.indexOf("\n");
  if (endNlPos === -1) {
    chomp = "-";
  } else if (value2 === end || endNlPos !== end.length - 1) {
    chomp = "+";
    if (onChompKeep)
      onChompKeep();
  } else {
    chomp = "";
  }
  if (end) {
    value2 = value2.slice(0, -end.length);
    if (end[end.length - 1] === "\n")
      end = end.slice(0, -1);
    end = end.replace(blockEndNewlines, `$&${indent}`);
  }
  let startWithSpace = false;
  let startEnd;
  let startNlPos = -1;
  for (startEnd = 0; startEnd < value2.length; ++startEnd) {
    const ch = value2[startEnd];
    if (ch === " ")
      startWithSpace = true;
    else if (ch === "\n")
      startNlPos = startEnd;
    else
      break;
  }
  let start = value2.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
  if (start) {
    value2 = value2.substring(start.length);
    start = start.replace(/\n+/g, `$&${indent}`);
  }
  const indentSize = indent ? "2" : "1";
  let header = (literal ? "|" : ">") + (startWithSpace ? indentSize : "") + chomp;
  if (comment) {
    header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
    if (onComment)
      onComment();
  }
  if (literal) {
    value2 = value2.replace(/\n+/g, `$&${indent}`);
    return `${header}
${indent}${start}${value2}${end}`;
  }
  value2 = value2.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
  const body = foldFlowLines(`${start}${value2}${end}`, indent, FOLD_BLOCK, getFoldOptions(ctx, true));
  return `${header}
${indent}${body}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
  const { type, value: value2 } = item;
  const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
  if (implicitKey && value2.includes("\n") || inFlow && /[[\]{},]/.test(value2)) {
    return quotedString(value2, ctx);
  }
  if (!value2 || /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value2)) {
    return implicitKey || inFlow || !value2.includes("\n") ? quotedString(value2, ctx) : blockString(item, ctx, onComment, onChompKeep);
  }
  if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value2.includes("\n")) {
    return blockString(item, ctx, onComment, onChompKeep);
  }
  if (containsDocumentMarker(value2)) {
    if (indent === "") {
      ctx.forceBlockIndent = true;
      return blockString(item, ctx, onComment, onChompKeep);
    } else if (implicitKey && indent === indentStep) {
      return quotedString(value2, ctx);
    }
  }
  const str = value2.replace(/\n+/g, `$&
${indent}`);
  if (actualString) {
    const test = (tag) => {
      var _a4;
      return tag.default && tag.tag !== "tag:yaml.org,2002:str" && ((_a4 = tag.test) == null ? void 0 : _a4.test(str));
    };
    const { compat, tags } = ctx.doc.schema;
    if (tags.some(test) || (compat == null ? void 0 : compat.some(test)))
      return quotedString(value2, ctx);
  }
  return implicitKey ? str : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
  const { implicitKey, inFlow } = ctx;
  const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
  let { type } = item;
  if (type !== Scalar.QUOTE_DOUBLE) {
    if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
      type = Scalar.QUOTE_DOUBLE;
  }
  const _stringify = (_type2) => {
    switch (_type2) {
      case Scalar.BLOCK_FOLDED:
      case Scalar.BLOCK_LITERAL:
        return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
      case Scalar.QUOTE_DOUBLE:
        return doubleQuotedString(ss.value, ctx);
      case Scalar.QUOTE_SINGLE:
        return singleQuotedString(ss.value, ctx);
      case Scalar.PLAIN:
        return plainString(ss, ctx, onComment, onChompKeep);
      default:
        return null;
    }
  };
  let res = _stringify(type);
  if (res === null) {
    const { defaultKeyType, defaultStringType } = ctx.options;
    const t2 = implicitKey && defaultKeyType || defaultStringType;
    res = _stringify(t2);
    if (res === null)
      throw new Error(`Unsupported default string type ${t2}`);
  }
  return res;
}
function createStringifyContext(doc, options2) {
  const opt = Object.assign({
    blockQuote: true,
    commentString: stringifyComment,
    defaultKeyType: null,
    defaultStringType: "PLAIN",
    directives: null,
    doubleQuotedAsJSON: false,
    doubleQuotedMinMultiLineLength: 40,
    falseStr: "false",
    flowCollectionPadding: true,
    indentSeq: true,
    lineWidth: 80,
    minContentWidth: 20,
    nullStr: "null",
    simpleKeys: false,
    singleQuote: null,
    trueStr: "true",
    verifyAliasOrder: true
  }, doc.schema.toStringOptions, options2);
  let inFlow;
  switch (opt.collectionStyle) {
    case "block":
      inFlow = false;
      break;
    case "flow":
      inFlow = true;
      break;
    default:
      inFlow = null;
  }
  return {
    anchors: /* @__PURE__ */ new Set(),
    doc,
    flowCollectionPadding: opt.flowCollectionPadding ? " " : "",
    indent: "",
    indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : "  ",
    inFlow,
    options: opt
  };
}
function getTagObject(tags, item) {
  var _a4;
  if (item.tag) {
    const match2 = tags.filter((t2) => t2.tag === item.tag);
    if (match2.length > 0)
      return match2.find((t2) => t2.format === item.format) ?? match2[0];
  }
  let tagObj = void 0;
  let obj;
  if (isScalar$1(item)) {
    obj = item.value;
    const match2 = tags.filter((t2) => {
      var _a5;
      return (_a5 = t2.identify) == null ? void 0 : _a5.call(t2, obj);
    });
    tagObj = match2.find((t2) => t2.format === item.format) ?? match2.find((t2) => !t2.format);
  } else {
    obj = item;
    tagObj = tags.find((t2) => t2.nodeClass && obj instanceof t2.nodeClass);
  }
  if (!tagObj) {
    const name2 = ((_a4 = obj == null ? void 0 : obj.constructor) == null ? void 0 : _a4.name) ?? typeof obj;
    throw new Error(`Tag not resolved for ${name2} value`);
  }
  return tagObj;
}
function stringifyProps(node2, tagObj, { anchors, doc }) {
  if (!doc.directives)
    return "";
  const props = [];
  const anchor = (isScalar$1(node2) || isCollection$1(node2)) && node2.anchor;
  if (anchor && anchorIsValid(anchor)) {
    anchors.add(anchor);
    props.push(`&${anchor}`);
  }
  const tag = node2.tag ? node2.tag : tagObj.default ? null : tagObj.tag;
  if (tag)
    props.push(doc.directives.tagString(tag));
  return props.join(" ");
}
function stringify$2(item, ctx, onComment, onChompKeep) {
  var _a4;
  if (isPair(item))
    return item.toString(ctx, onComment, onChompKeep);
  if (isAlias(item)) {
    if (ctx.doc.directives)
      return item.toString(ctx);
    if ((_a4 = ctx.resolvedAliases) == null ? void 0 : _a4.has(item)) {
      throw new TypeError(`Cannot stringify circular structure without alias nodes`);
    } else {
      if (ctx.resolvedAliases)
        ctx.resolvedAliases.add(item);
      else
        ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
      item = item.resolve(ctx.doc);
    }
  }
  let tagObj = void 0;
  const node2 = isNode$1(item) ? item : ctx.doc.createNode(item, { onTagObj: (o2) => tagObj = o2 });
  if (!tagObj)
    tagObj = getTagObject(ctx.doc.schema.tags, node2);
  const props = stringifyProps(node2, tagObj, ctx);
  if (props.length > 0)
    ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
  const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node2, ctx, onComment, onChompKeep) : isScalar$1(node2) ? stringifyString(node2, ctx, onComment, onChompKeep) : node2.toString(ctx, onComment, onChompKeep);
  if (!props)
    return str;
  return isScalar$1(node2) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props}
${ctx.indent}${str}`;
}
function stringifyPair({ key, value: value2 }, ctx, onComment, onChompKeep) {
  const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
  let keyComment = isNode$1(key) && key.comment || null;
  if (simpleKeys) {
    if (keyComment) {
      throw new Error("With simple keys, key nodes cannot have comments");
    }
    if (isCollection$1(key) || !isNode$1(key) && typeof key === "object") {
      const msg = "With simple keys, collection cannot be used as a key value";
      throw new Error(msg);
    }
  }
  let explicitKey = !simpleKeys && (!key || keyComment && value2 == null && !ctx.inFlow || isCollection$1(key) || (isScalar$1(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object"));
  ctx = Object.assign({}, ctx, {
    allNullValues: false,
    implicitKey: !explicitKey && (simpleKeys || !allNullValues),
    indent: indent + indentStep
  });
  let keyCommentDone = false;
  let chompKeep = false;
  let str = stringify$2(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
  if (!explicitKey && !ctx.inFlow && str.length > 1024) {
    if (simpleKeys)
      throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
    explicitKey = true;
  }
  if (ctx.inFlow) {
    if (allNullValues || value2 == null) {
      if (keyCommentDone && onComment)
        onComment();
      return str === "" ? "?" : explicitKey ? `? ${str}` : str;
    }
  } else if (allNullValues && !simpleKeys || value2 == null && explicitKey) {
    str = `? ${str}`;
    if (keyComment && !keyCommentDone) {
      str += lineComment(str, ctx.indent, commentString(keyComment));
    } else if (chompKeep && onChompKeep)
      onChompKeep();
    return str;
  }
  if (keyCommentDone)
    keyComment = null;
  if (explicitKey) {
    if (keyComment)
      str += lineComment(str, ctx.indent, commentString(keyComment));
    str = `? ${str}
${indent}:`;
  } else {
    str = `${str}:`;
    if (keyComment)
      str += lineComment(str, ctx.indent, commentString(keyComment));
  }
  let vsb, vcb, valueComment;
  if (isNode$1(value2)) {
    vsb = !!value2.spaceBefore;
    vcb = value2.commentBefore;
    valueComment = value2.comment;
  } else {
    vsb = false;
    vcb = null;
    valueComment = null;
    if (value2 && typeof value2 === "object")
      value2 = doc.createNode(value2);
  }
  ctx.implicitKey = false;
  if (!explicitKey && !keyComment && isScalar$1(value2))
    ctx.indentAtStart = str.length + 1;
  chompKeep = false;
  if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value2) && !value2.flow && !value2.tag && !value2.anchor) {
    ctx.indent = ctx.indent.substring(2);
  }
  let valueCommentDone = false;
  const valueStr = stringify$2(value2, ctx, () => valueCommentDone = true, () => chompKeep = true);
  let ws = " ";
  if (keyComment || vsb || vcb) {
    ws = vsb ? "\n" : "";
    if (vcb) {
      const cs = commentString(vcb);
      ws += `
${indentComment(cs, ctx.indent)}`;
    }
    if (valueStr === "" && !ctx.inFlow) {
      if (ws === "\n")
        ws = "\n\n";
    } else {
      ws += `
${ctx.indent}`;
    }
  } else if (!explicitKey && isCollection$1(value2)) {
    const vs0 = valueStr[0];
    const nl0 = valueStr.indexOf("\n");
    const hasNewline = nl0 !== -1;
    const flow = ctx.inFlow ?? value2.flow ?? value2.items.length === 0;
    if (hasNewline || !flow) {
      let hasPropsLine = false;
      if (hasNewline && (vs0 === "&" || vs0 === "!")) {
        let sp0 = valueStr.indexOf(" ");
        if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
          sp0 = valueStr.indexOf(" ", sp0 + 1);
        }
        if (sp0 === -1 || nl0 < sp0)
          hasPropsLine = true;
      }
      if (!hasPropsLine)
        ws = `
${ctx.indent}`;
    }
  } else if (valueStr === "" || valueStr[0] === "\n") {
    ws = "";
  }
  str += ws + valueStr;
  if (ctx.inFlow) {
    if (valueCommentDone && onComment)
      onComment();
  } else if (valueComment && !valueCommentDone) {
    str += lineComment(str, ctx.indent, commentString(valueComment));
  } else if (chompKeep && onChompKeep) {
    onChompKeep();
  }
  return str;
}
function warn(logLevel, warning) {
  if (logLevel === "debug" || logLevel === "warn") {
    if (typeof process !== "undefined" && process.emitWarning)
      process.emitWarning(warning);
    else
      console.warn(warning);
  }
}
var MERGE_KEY = "<<";
function addPairToJSMap(ctx, map2, { key, value: value2 }) {
  if ((ctx == null ? void 0 : ctx.doc.schema.merge) && isMergeKey(key)) {
    value2 = isAlias(value2) ? value2.resolve(ctx.doc) : value2;
    if (isSeq(value2))
      for (const it of value2.items)
        mergeToJSMap(ctx, map2, it);
    else if (Array.isArray(value2))
      for (const it of value2)
        mergeToJSMap(ctx, map2, it);
    else
      mergeToJSMap(ctx, map2, value2);
  } else {
    const jsKey = toJS(key, "", ctx);
    if (map2 instanceof Map) {
      map2.set(jsKey, toJS(value2, jsKey, ctx));
    } else if (map2 instanceof Set) {
      map2.add(jsKey);
    } else {
      const stringKey = stringifyKey(key, jsKey, ctx);
      const jsValue = toJS(value2, stringKey, ctx);
      if (stringKey in map2)
        Object.defineProperty(map2, stringKey, {
          value: jsValue,
          writable: true,
          enumerable: true,
          configurable: true
        });
      else
        map2[stringKey] = jsValue;
    }
  }
  return map2;
}
var isMergeKey = (key) => key === MERGE_KEY || isScalar$1(key) && key.value === MERGE_KEY && (!key.type || key.type === Scalar.PLAIN);
function mergeToJSMap(ctx, map2, value2) {
  const source = ctx && isAlias(value2) ? value2.resolve(ctx.doc) : value2;
  if (!isMap(source))
    throw new Error("Merge sources must be maps or map aliases");
  const srcMap = source.toJSON(null, ctx, Map);
  for (const [key, value3] of srcMap) {
    if (map2 instanceof Map) {
      if (!map2.has(key))
        map2.set(key, value3);
    } else if (map2 instanceof Set) {
      map2.add(key);
    } else if (!Object.prototype.hasOwnProperty.call(map2, key)) {
      Object.defineProperty(map2, key, {
        value: value3,
        writable: true,
        enumerable: true,
        configurable: true
      });
    }
  }
  return map2;
}
function stringifyKey(key, jsKey, ctx) {
  if (jsKey === null)
    return "";
  if (typeof jsKey !== "object")
    return String(jsKey);
  if (isNode$1(key) && (ctx == null ? void 0 : ctx.doc)) {
    const strCtx = createStringifyContext(ctx.doc, {});
    strCtx.anchors = /* @__PURE__ */ new Set();
    for (const node2 of ctx.anchors.keys())
      strCtx.anchors.add(node2.anchor);
    strCtx.inFlow = true;
    strCtx.inStringifyKey = true;
    const strKey = key.toString(strCtx);
    if (!ctx.mapKeyWarned) {
      let jsonStr = JSON.stringify(strKey);
      if (jsonStr.length > 40)
        jsonStr = jsonStr.substring(0, 36) + '..."';
      warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
      ctx.mapKeyWarned = true;
    }
    return strKey;
  }
  return JSON.stringify(jsKey);
}
function createPair(key, value2, ctx) {
  const k = createNode(key, void 0, ctx);
  const v = createNode(value2, void 0, ctx);
  return new Pair(k, v);
}
var Pair = class _Pair {
  constructor(key, value2 = null) {
    Object.defineProperty(this, NODE_TYPE, { value: PAIR });
    this.key = key;
    this.value = value2;
  }
  clone(schema2) {
    let { key, value: value2 } = this;
    if (isNode$1(key))
      key = key.clone(schema2);
    if (isNode$1(value2))
      value2 = value2.clone(schema2);
    return new _Pair(key, value2);
  }
  toJSON(_, ctx) {
    const pair = (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {};
    return addPairToJSMap(ctx, pair, this);
  }
  toString(ctx, onComment, onChompKeep) {
    return (ctx == null ? void 0 : ctx.doc) ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
  }
};
function stringifyCollection(collection, ctx, options2) {
  const flow = ctx.inFlow ?? collection.flow;
  const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection;
  return stringify2(collection, ctx, options2);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
  const { indent, options: { commentString } } = ctx;
  const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
  let chompKeep = false;
  const lines = [];
  for (let i = 0; i < items.length; ++i) {
    const item = items[i];
    let comment2 = null;
    if (isNode$1(item)) {
      if (!chompKeep && item.spaceBefore)
        lines.push("");
      addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
      if (item.comment)
        comment2 = item.comment;
    } else if (isPair(item)) {
      const ik = isNode$1(item.key) ? item.key : null;
      if (ik) {
        if (!chompKeep && ik.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
      }
    }
    chompKeep = false;
    let str2 = stringify$2(item, itemCtx, () => comment2 = null, () => chompKeep = true);
    if (comment2)
      str2 += lineComment(str2, itemIndent, commentString(comment2));
    if (chompKeep && comment2)
      chompKeep = false;
    lines.push(blockItemPrefix + str2);
  }
  let str;
  if (lines.length === 0) {
    str = flowChars.start + flowChars.end;
  } else {
    str = lines[0];
    for (let i = 1; i < lines.length; ++i) {
      const line = lines[i];
      str += line ? `
${indent}${line}` : "\n";
    }
  }
  if (comment) {
    str += "\n" + indentComment(commentString(comment), indent);
    if (onComment)
      onComment();
  } else if (chompKeep && onChompKeep)
    onChompKeep();
  return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
  const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
  itemIndent += indentStep;
  const itemCtx = Object.assign({}, ctx, {
    indent: itemIndent,
    inFlow: true,
    type: null
  });
  let reqNewline = false;
  let linesAtValue = 0;
  const lines = [];
  for (let i = 0; i < items.length; ++i) {
    const item = items[i];
    let comment = null;
    if (isNode$1(item)) {
      if (item.spaceBefore)
        lines.push("");
      addCommentBefore(ctx, lines, item.commentBefore, false);
      if (item.comment)
        comment = item.comment;
    } else if (isPair(item)) {
      const ik = isNode$1(item.key) ? item.key : null;
      if (ik) {
        if (ik.spaceBefore)
          lines.push("");
        addCommentBefore(ctx, lines, ik.commentBefore, false);
        if (ik.comment)
          reqNewline = true;
      }
      const iv = isNode$1(item.value) ? item.value : null;
      if (iv) {
        if (iv.comment)
          comment = iv.comment;
        if (iv.commentBefore)
          reqNewline = true;
      } else if (item.value == null && (ik == null ? void 0 : ik.comment)) {
        comment = ik.comment;
      }
    }
    if (comment)
      reqNewline = true;
    let str = stringify$2(item, itemCtx, () => comment = null);
    if (i < items.length - 1)
      str += ",";
    if (comment)
      str += lineComment(str, itemIndent, commentString(comment));
    if (!reqNewline && (lines.length > linesAtValue || str.includes("\n")))
      reqNewline = true;
    lines.push(str);
    linesAtValue = lines.length;
  }
  const { start, end } = flowChars;
  if (lines.length === 0) {
    return start + end;
  } else {
    if (!reqNewline) {
      const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
      reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
    }
    if (reqNewline) {
      let str = start;
      for (const line of lines)
        str += line ? `
${indentStep}${indent}${line}` : "\n";
      return `${str}
${indent}${end}`;
    } else {
      return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
    }
  }
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
  if (comment && chompKeep)
    comment = comment.replace(/^\n+/, "");
  if (comment) {
    const ic = indentComment(commentString(comment), indent);
    lines.push(ic.trimStart());
  }
}
function findPair(items, key) {
  const k = isScalar$1(key) ? key.value : key;
  for (const it of items) {
    if (isPair(it)) {
      if (it.key === key || it.key === k)
        return it;
      if (isScalar$1(it.key) && it.key.value === k)
        return it;
    }
  }
  return void 0;
}
var YAMLMap = class extends Collection {
  static get tagName() {
    return "tag:yaml.org,2002:map";
  }
  constructor(schema2) {
    super(MAP, schema2);
    this.items = [];
  }
  /**
   * A generic collection parsing method that can be extended
   * to other node classes that inherit from YAMLMap
   */
  static from(schema2, obj, ctx) {
    const { keepUndefined, replacer } = ctx;
    const map2 = new this(schema2);
    const add = (key, value2) => {
      if (typeof replacer === "function")
        value2 = replacer.call(obj, key, value2);
      else if (Array.isArray(replacer) && !replacer.includes(key))
        return;
      if (value2 !== void 0 || keepUndefined)
        map2.items.push(createPair(key, value2, ctx));
    };
    if (obj instanceof Map) {
      for (const [key, value2] of obj)
        add(key, value2);
    } else if (obj && typeof obj === "object") {
      for (const key of Object.keys(obj))
        add(key, obj[key]);
    }
    if (typeof schema2.sortMapEntries === "function") {
      map2.items.sort(schema2.sortMapEntries);
    }
    return map2;
  }
  /**
   * Adds a value to the collection.
   *
   * @param overwrite - If not set `true`, using a key that is already in the
   *   collection will throw. Otherwise, overwrites the previous value.
   */
  add(pair, overwrite) {
    var _a4;
    let _pair;
    if (isPair(pair))
      _pair = pair;
    else if (!pair || typeof pair !== "object" || !("key" in pair)) {
      _pair = new Pair(pair, pair == null ? void 0 : pair.value);
    } else
      _pair = new Pair(pair.key, pair.value);
    const prev = findPair(this.items, _pair.key);
    const sortEntries = (_a4 = this.schema) == null ? void 0 : _a4.sortMapEntries;
    if (prev) {
      if (!overwrite)
        throw new Error(`Key ${_pair.key} already set`);
      if (isScalar$1(prev.value) && isScalarValue(_pair.value))
        prev.value.value = _pair.value;
      else
        prev.value = _pair.value;
    } else if (sortEntries) {
      const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
      if (i === -1)
        this.items.push(_pair);
      else
        this.items.splice(i, 0, _pair);
    } else {
      this.items.push(_pair);
    }
  }
  delete(key) {
    const it = findPair(this.items, key);
    if (!it)
      return false;
    const del = this.items.splice(this.items.indexOf(it), 1);
    return del.length > 0;
  }
  get(key, keepScalar) {
    const it = findPair(this.items, key);
    const node2 = it == null ? void 0 : it.value;
    return (!keepScalar && isScalar$1(node2) ? node2.value : node2) ?? void 0;
  }
  has(key) {
    return !!findPair(this.items, key);
  }
  set(key, value2) {
    this.add(new Pair(key, value2), true);
  }
  /**
   * @param ctx - Conversion context, originally set in Document#toJS()
   * @param {Class} Type - If set, forces the returned collection type
   * @returns Instance of Type, Map, or Object
   */
  toJSON(_, ctx, Type) {
    const map2 = Type ? new Type() : (ctx == null ? void 0 : ctx.mapAsMap) ? /* @__PURE__ */ new Map() : {};
    if (ctx == null ? void 0 : ctx.onCreate)
      ctx.onCreate(map2);
    for (const item of this.items)
      addPairToJSMap(ctx, map2, item);
    return map2;
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    for (const item of this.items) {
      if (!isPair(item))
        throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
    }
    if (!ctx.allNullValues && this.hasAllNullValues(false))
      ctx = Object.assign({}, ctx, { allNullValues: true });
    return stringifyCollection(this, ctx, {
      blockItemPrefix: "",
      flowChars: { start: "{", end: "}" },
      itemIndent: ctx.indent || "",
      onChompKeep,
      onComment
    });
  }
};
var map$1 = {
  collection: "map",
  default: true,
  nodeClass: YAMLMap,
  tag: "tag:yaml.org,2002:map",
  resolve(map2, onError2) {
    if (!isMap(map2))
      onError2("Expected a mapping for this tag");
    return map2;
  },
  createNode: (schema2, obj, ctx) => YAMLMap.from(schema2, obj, ctx)
};
var YAMLSeq = class extends Collection {
  static get tagName() {
    return "tag:yaml.org,2002:seq";
  }
  constructor(schema2) {
    super(SEQ, schema2);
    this.items = [];
  }
  add(value2) {
    this.items.push(value2);
  }
  /**
   * Removes a value from the collection.
   *
   * `key` must contain a representation of an integer for this to succeed.
   * It may be wrapped in a `Scalar`.
   *
   * @returns `true` if the item was found and removed.
   */
  delete(key) {
    const idx = asItemIndex(key);
    if (typeof idx !== "number")
      return false;
    const del = this.items.splice(idx, 1);
    return del.length > 0;
  }
  get(key, keepScalar) {
    const idx = asItemIndex(key);
    if (typeof idx !== "number")
      return void 0;
    const it = this.items[idx];
    return !keepScalar && isScalar$1(it) ? it.value : it;
  }
  /**
   * Checks if the collection includes a value with the key `key`.
   *
   * `key` must contain a representation of an integer for this to succeed.
   * It may be wrapped in a `Scalar`.
   */
  has(key) {
    const idx = asItemIndex(key);
    return typeof idx === "number" && idx < this.items.length;
  }
  /**
   * Sets a value in this collection. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   *
   * If `key` does not contain a representation of an integer, this will throw.
   * It may be wrapped in a `Scalar`.
   */
  set(key, value2) {
    const idx = asItemIndex(key);
    if (typeof idx !== "number")
      throw new Error(`Expected a valid index, not ${key}.`);
    const prev = this.items[idx];
    if (isScalar$1(prev) && isScalarValue(value2))
      prev.value = value2;
    else
      this.items[idx] = value2;
  }
  toJSON(_, ctx) {
    const seq2 = [];
    if (ctx == null ? void 0 : ctx.onCreate)
      ctx.onCreate(seq2);
    let i = 0;
    for (const item of this.items)
      seq2.push(toJS(item, String(i++), ctx));
    return seq2;
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    return stringifyCollection(this, ctx, {
      blockItemPrefix: "- ",
      flowChars: { start: "[", end: "]" },
      itemIndent: (ctx.indent || "") + "  ",
      onChompKeep,
      onComment
    });
  }
  static from(schema2, obj, ctx) {
    const { replacer } = ctx;
    const seq2 = new this(schema2);
    if (obj && Symbol.iterator in Object(obj)) {
      let i = 0;
      for (let it of obj) {
        if (typeof replacer === "function") {
          const key = obj instanceof Set ? it : String(i++);
          it = replacer.call(obj, key, it);
        }
        seq2.items.push(createNode(it, void 0, ctx));
      }
    }
    return seq2;
  }
};
function asItemIndex(key) {
  let idx = isScalar$1(key) ? key.value : key;
  if (idx && typeof idx === "string")
    idx = Number(idx);
  return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
}
var seq = {
  collection: "seq",
  default: true,
  nodeClass: YAMLSeq,
  tag: "tag:yaml.org,2002:seq",
  resolve(seq2, onError2) {
    if (!isSeq(seq2))
      onError2("Expected a sequence for this tag");
    return seq2;
  },
  createNode: (schema2, obj, ctx) => YAMLSeq.from(schema2, obj, ctx)
};
var string = {
  identify: (value2) => typeof value2 === "string",
  default: true,
  tag: "tag:yaml.org,2002:str",
  resolve: (str) => str,
  stringify(item, ctx, onComment, onChompKeep) {
    ctx = Object.assign({ actualString: true }, ctx);
    return stringifyString(item, ctx, onComment, onChompKeep);
  }
};
var nullTag = {
  identify: (value2) => value2 == null,
  createNode: () => new Scalar(null),
  default: true,
  tag: "tag:yaml.org,2002:null",
  test: /^(?:~|[Nn]ull|NULL)?$/,
  resolve: () => new Scalar(null),
  stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr
};
var boolTag = {
  identify: (value2) => typeof value2 === "boolean",
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
  resolve: (str) => new Scalar(str[0] === "t" || str[0] === "T"),
  stringify({ source, value: value2 }, ctx) {
    if (source && boolTag.test.test(source)) {
      const sv = source[0] === "t" || source[0] === "T";
      if (value2 === sv)
        return source;
    }
    return value2 ? ctx.options.trueStr : ctx.options.falseStr;
  }
};
function stringifyNumber({ format: format2, minFractionDigits, tag, value: value2 }) {
  if (typeof value2 === "bigint")
    return String(value2);
  const num = typeof value2 === "number" ? value2 : Number(value2);
  if (!isFinite(num))
    return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf";
  let n2 = JSON.stringify(value2);
  if (!format2 && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^\d/.test(n2)) {
    let i = n2.indexOf(".");
    if (i < 0) {
      i = n2.length;
      n2 += ".";
    }
    let d = minFractionDigits - (n2.length - i - 1);
    while (d-- > 0)
      n2 += "0";
  }
  return n2;
}
var floatNaN$1 = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  stringify: stringifyNumber
};
var floatExp$1 = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "EXP",
  test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
  resolve: (str) => parseFloat(str),
  stringify(node2) {
    const num = Number(node2.value);
    return isFinite(num) ? num.toExponential() : stringifyNumber(node2);
  }
};
var float$1 = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
  resolve(str) {
    const node2 = new Scalar(parseFloat(str));
    const dot = str.indexOf(".");
    if (dot !== -1 && str[str.length - 1] === "0")
      node2.minFractionDigits = str.length - dot - 1;
    return node2;
  },
  stringify: stringifyNumber
};
var intIdentify$2 = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
var intResolve$1 = (str, offset2, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset2), radix);
function intStringify$1(node2, radix, prefix) {
  const { value: value2 } = node2;
  if (intIdentify$2(value2) && value2 >= 0)
    return prefix + value2.toString(radix);
  return stringifyNumber(node2);
}
var intOct$1 = {
  identify: (value2) => intIdentify$2(value2) && value2 >= 0,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "OCT",
  test: /^0o[0-7]+$/,
  resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt),
  stringify: (node2) => intStringify$1(node2, 8, "0o")
};
var int$1 = {
  identify: intIdentify$2,
  default: true,
  tag: "tag:yaml.org,2002:int",
  test: /^[-+]?[0-9]+$/,
  resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt),
  stringify: stringifyNumber
};
var intHex$1 = {
  identify: (value2) => intIdentify$2(value2) && value2 >= 0,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "HEX",
  test: /^0x[0-9a-fA-F]+$/,
  resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt),
  stringify: (node2) => intStringify$1(node2, 16, "0x")
};
var schema$2 = [
  map$1,
  seq,
  string,
  nullTag,
  boolTag,
  intOct$1,
  int$1,
  intHex$1,
  floatNaN$1,
  floatExp$1,
  float$1
];
function intIdentify$1(value2) {
  return typeof value2 === "bigint" || Number.isInteger(value2);
}
var stringifyJSON = ({ value: value2 }) => JSON.stringify(value2);
var jsonScalars = [
  {
    identify: (value2) => typeof value2 === "string",
    default: true,
    tag: "tag:yaml.org,2002:str",
    resolve: (str) => str,
    stringify: stringifyJSON
  },
  {
    identify: (value2) => value2 == null,
    createNode: () => new Scalar(null),
    default: true,
    tag: "tag:yaml.org,2002:null",
    test: /^null$/,
    resolve: () => null,
    stringify: stringifyJSON
  },
  {
    identify: (value2) => typeof value2 === "boolean",
    default: true,
    tag: "tag:yaml.org,2002:bool",
    test: /^true|false$/,
    resolve: (str) => str === "true",
    stringify: stringifyJSON
  },
  {
    identify: intIdentify$1,
    default: true,
    tag: "tag:yaml.org,2002:int",
    test: /^-?(?:0|[1-9][0-9]*)$/,
    resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
    stringify: ({ value: value2 }) => intIdentify$1(value2) ? value2.toString() : JSON.stringify(value2)
  },
  {
    identify: (value2) => typeof value2 === "number",
    default: true,
    tag: "tag:yaml.org,2002:float",
    test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
    resolve: (str) => parseFloat(str),
    stringify: stringifyJSON
  }
];
var jsonError = {
  default: true,
  tag: "",
  test: /^/,
  resolve(str, onError2) {
    onError2(`Unresolved plain scalar ${JSON.stringify(str)}`);
    return str;
  }
};
var schema$1 = [map$1, seq].concat(jsonScalars, jsonError);
var binary = {
  identify: (value2) => value2 instanceof Uint8Array,
  // Buffer inherits from Uint8Array
  default: false,
  tag: "tag:yaml.org,2002:binary",
  /**
   * Returns a Buffer in node and an Uint8Array in browsers
   *
   * To use the resulting buffer as an image, you'll want to do something like:
   *
   *   const blob = new Blob([buffer], { type: 'image/jpeg' })
   *   document.querySelector('#photo').src = URL.createObjectURL(blob)
   */
  resolve(src2, onError2) {
    if (typeof Buffer === "function") {
      return Buffer.from(src2, "base64");
    } else if (typeof atob === "function") {
      const str = atob(src2.replace(/[\n\r]/g, ""));
      const buffer = new Uint8Array(str.length);
      for (let i = 0; i < str.length; ++i)
        buffer[i] = str.charCodeAt(i);
      return buffer;
    } else {
      onError2("This environment does not support reading binary tags; either Buffer or atob is required");
      return src2;
    }
  },
  stringify({ comment, type, value: value2 }, ctx, onComment, onChompKeep) {
    const buf = value2;
    let str;
    if (typeof Buffer === "function") {
      str = buf instanceof Buffer ? buf.toString("base64") : Buffer.from(buf.buffer).toString("base64");
    } else if (typeof btoa === "function") {
      let s = "";
      for (let i = 0; i < buf.length; ++i)
        s += String.fromCharCode(buf[i]);
      str = btoa(s);
    } else {
      throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");
    }
    if (!type)
      type = Scalar.BLOCK_LITERAL;
    if (type !== Scalar.QUOTE_DOUBLE) {
      const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
      const n2 = Math.ceil(str.length / lineWidth);
      const lines = new Array(n2);
      for (let i = 0, o2 = 0; i < n2; ++i, o2 += lineWidth) {
        lines[i] = str.substr(o2, lineWidth);
      }
      str = lines.join(type === Scalar.BLOCK_LITERAL ? "\n" : " ");
    }
    return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
  }
};
function resolvePairs(seq2, onError2) {
  if (isSeq(seq2)) {
    for (let i = 0; i < seq2.items.length; ++i) {
      let item = seq2.items[i];
      if (isPair(item))
        continue;
      else if (isMap(item)) {
        if (item.items.length > 1)
          onError2("Each pair must have its own sequence indicator");
        const pair = item.items[0] || new Pair(new Scalar(null));
        if (item.commentBefore)
          pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore}
${pair.key.commentBefore}` : item.commentBefore;
        if (item.comment) {
          const cn = pair.value ?? pair.key;
          cn.comment = cn.comment ? `${item.comment}
${cn.comment}` : item.comment;
        }
        item = pair;
      }
      seq2.items[i] = isPair(item) ? item : new Pair(item);
    }
  } else
    onError2("Expected a sequence for this tag");
  return seq2;
}
function createPairs(schema2, iterable, ctx) {
  const { replacer } = ctx;
  const pairs2 = new YAMLSeq(schema2);
  pairs2.tag = "tag:yaml.org,2002:pairs";
  let i = 0;
  if (iterable && Symbol.iterator in Object(iterable))
    for (let it of iterable) {
      if (typeof replacer === "function")
        it = replacer.call(iterable, String(i++), it);
      let key, value2;
      if (Array.isArray(it)) {
        if (it.length === 2) {
          key = it[0];
          value2 = it[1];
        } else
          throw new TypeError(`Expected [key, value] tuple: ${it}`);
      } else if (it && it instanceof Object) {
        const keys = Object.keys(it);
        if (keys.length === 1) {
          key = keys[0];
          value2 = it[key];
        } else {
          throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
        }
      } else {
        key = it;
      }
      pairs2.items.push(createPair(key, value2, ctx));
    }
  return pairs2;
}
var pairs = {
  collection: "seq",
  default: false,
  tag: "tag:yaml.org,2002:pairs",
  resolve: resolvePairs,
  createNode: createPairs
};
var YAMLOMap = class _YAMLOMap extends YAMLSeq {
  constructor() {
    super();
    this.add = YAMLMap.prototype.add.bind(this);
    this.delete = YAMLMap.prototype.delete.bind(this);
    this.get = YAMLMap.prototype.get.bind(this);
    this.has = YAMLMap.prototype.has.bind(this);
    this.set = YAMLMap.prototype.set.bind(this);
    this.tag = _YAMLOMap.tag;
  }
  /**
   * If `ctx` is given, the return type is actually `Map`,
   * but TypeScript won't allow widening the signature of a child method.
   */
  toJSON(_, ctx) {
    if (!ctx)
      return super.toJSON(_);
    const map2 = /* @__PURE__ */ new Map();
    if (ctx == null ? void 0 : ctx.onCreate)
      ctx.onCreate(map2);
    for (const pair of this.items) {
      let key, value2;
      if (isPair(pair)) {
        key = toJS(pair.key, "", ctx);
        value2 = toJS(pair.value, key, ctx);
      } else {
        key = toJS(pair, "", ctx);
      }
      if (map2.has(key))
        throw new Error("Ordered maps must not include duplicate keys");
      map2.set(key, value2);
    }
    return map2;
  }
  static from(schema2, iterable, ctx) {
    const pairs2 = createPairs(schema2, iterable, ctx);
    const omap2 = new this();
    omap2.items = pairs2.items;
    return omap2;
  }
};
YAMLOMap.tag = "tag:yaml.org,2002:omap";
var omap = {
  collection: "seq",
  identify: (value2) => value2 instanceof Map,
  nodeClass: YAMLOMap,
  default: false,
  tag: "tag:yaml.org,2002:omap",
  resolve(seq2, onError2) {
    const pairs2 = resolvePairs(seq2, onError2);
    const seenKeys = [];
    for (const { key } of pairs2.items) {
      if (isScalar$1(key)) {
        if (seenKeys.includes(key.value)) {
          onError2(`Ordered maps must not include duplicate keys: ${key.value}`);
        } else {
          seenKeys.push(key.value);
        }
      }
    }
    return Object.assign(new YAMLOMap(), pairs2);
  },
  createNode: (schema2, iterable, ctx) => YAMLOMap.from(schema2, iterable, ctx)
};
function boolStringify({ value: value2, source }, ctx) {
  const boolObj = value2 ? trueTag : falseTag;
  if (source && boolObj.test.test(source))
    return source;
  return value2 ? ctx.options.trueStr : ctx.options.falseStr;
}
var trueTag = {
  identify: (value2) => value2 === true,
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
  resolve: () => new Scalar(true),
  stringify: boolStringify
};
var falseTag = {
  identify: (value2) => value2 === false,
  default: true,
  tag: "tag:yaml.org,2002:bool",
  test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
  resolve: () => new Scalar(false),
  stringify: boolStringify
};
var floatNaN = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
  resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY,
  stringify: stringifyNumber
};
var floatExp = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "EXP",
  test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
  resolve: (str) => parseFloat(str.replace(/_/g, "")),
  stringify(node2) {
    const num = Number(node2.value);
    return isFinite(num) ? num.toExponential() : stringifyNumber(node2);
  }
};
var float = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
  resolve(str) {
    const node2 = new Scalar(parseFloat(str.replace(/_/g, "")));
    const dot = str.indexOf(".");
    if (dot !== -1) {
      const f2 = str.substring(dot + 1).replace(/_/g, "");
      if (f2[f2.length - 1] === "0")
        node2.minFractionDigits = f2.length;
    }
    return node2;
  },
  stringify: stringifyNumber
};
var intIdentify = (value2) => typeof value2 === "bigint" || Number.isInteger(value2);
function intResolve(str, offset2, radix, { intAsBigInt }) {
  const sign = str[0];
  if (sign === "-" || sign === "+")
    offset2 += 1;
  str = str.substring(offset2).replace(/_/g, "");
  if (intAsBigInt) {
    switch (radix) {
      case 2:
        str = `0b${str}`;
        break;
      case 8:
        str = `0o${str}`;
        break;
      case 16:
        str = `0x${str}`;
        break;
    }
    const n3 = BigInt(str);
    return sign === "-" ? BigInt(-1) * n3 : n3;
  }
  const n2 = parseInt(str, radix);
  return sign === "-" ? -1 * n2 : n2;
}
function intStringify(node2, radix, prefix) {
  const { value: value2 } = node2;
  if (intIdentify(value2)) {
    const str = value2.toString(radix);
    return value2 < 0 ? "-" + prefix + str.substr(1) : prefix + str;
  }
  return stringifyNumber(node2);
}
var intBin = {
  identify: intIdentify,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "BIN",
  test: /^[-+]?0b[0-1_]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
  stringify: (node2) => intStringify(node2, 2, "0b")
};
var intOct = {
  identify: intIdentify,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "OCT",
  test: /^[-+]?0[0-7_]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
  stringify: (node2) => intStringify(node2, 8, "0")
};
var int = {
  identify: intIdentify,
  default: true,
  tag: "tag:yaml.org,2002:int",
  test: /^[-+]?[0-9][0-9_]*$/,
  resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
  stringify: stringifyNumber
};
var intHex = {
  identify: intIdentify,
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "HEX",
  test: /^[-+]?0x[0-9a-fA-F_]+$/,
  resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
  stringify: (node2) => intStringify(node2, 16, "0x")
};
var YAMLSet = class _YAMLSet extends YAMLMap {
  constructor(schema2) {
    super(schema2);
    this.tag = _YAMLSet.tag;
  }
  add(key) {
    let pair;
    if (isPair(key))
      pair = key;
    else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
      pair = new Pair(key.key, null);
    else
      pair = new Pair(key, null);
    const prev = findPair(this.items, pair.key);
    if (!prev)
      this.items.push(pair);
  }
  /**
   * If `keepPair` is `true`, returns the Pair matching `key`.
   * Otherwise, returns the value of that Pair's key.
   */
  get(key, keepPair) {
    const pair = findPair(this.items, key);
    return !keepPair && isPair(pair) ? isScalar$1(pair.key) ? pair.key.value : pair.key : pair;
  }
  set(key, value2) {
    if (typeof value2 !== "boolean")
      throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value2}`);
    const prev = findPair(this.items, key);
    if (prev && !value2) {
      this.items.splice(this.items.indexOf(prev), 1);
    } else if (!prev && value2) {
      this.items.push(new Pair(key));
    }
  }
  toJSON(_, ctx) {
    return super.toJSON(_, ctx, Set);
  }
  toString(ctx, onComment, onChompKeep) {
    if (!ctx)
      return JSON.stringify(this);
    if (this.hasAllNullValues(true))
      return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
    else
      throw new Error("Set items must all have null values");
  }
  static from(schema2, iterable, ctx) {
    const { replacer } = ctx;
    const set2 = new this(schema2);
    if (iterable && Symbol.iterator in Object(iterable))
      for (let value2 of iterable) {
        if (typeof replacer === "function")
          value2 = replacer.call(iterable, value2, value2);
        set2.items.push(createPair(value2, null, ctx));
      }
    return set2;
  }
};
YAMLSet.tag = "tag:yaml.org,2002:set";
var set = {
  collection: "map",
  identify: (value2) => value2 instanceof Set,
  nodeClass: YAMLSet,
  default: false,
  tag: "tag:yaml.org,2002:set",
  createNode: (schema2, iterable, ctx) => YAMLSet.from(schema2, iterable, ctx),
  resolve(map2, onError2) {
    if (isMap(map2)) {
      if (map2.hasAllNullValues(true))
        return Object.assign(new YAMLSet(), map2);
      else
        onError2("Set items must all have null values");
    } else
      onError2("Expected a mapping for this tag");
    return map2;
  }
};
function parseSexagesimal(str, asBigInt) {
  const sign = str[0];
  const parts = sign === "-" || sign === "+" ? str.substring(1) : str;
  const num = (n2) => asBigInt ? BigInt(n2) : Number(n2);
  const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0));
  return sign === "-" ? num(-1) * res : res;
}
function stringifySexagesimal(node2) {
  let { value: value2 } = node2;
  let num = (n2) => n2;
  if (typeof value2 === "bigint")
    num = (n2) => BigInt(n2);
  else if (isNaN(value2) || !isFinite(value2))
    return stringifyNumber(node2);
  let sign = "";
  if (value2 < 0) {
    sign = "-";
    value2 *= num(-1);
  }
  const _60 = num(60);
  const parts = [value2 % _60];
  if (value2 < 60) {
    parts.unshift(0);
  } else {
    value2 = (value2 - parts[0]) / _60;
    parts.unshift(value2 % _60);
    if (value2 >= 60) {
      value2 = (value2 - parts[0]) / _60;
      parts.unshift(value2);
    }
  }
  return sign + parts.map((n2) => String(n2).padStart(2, "0")).join(":").replace(/000000\d*$/, "");
}
var intTime = {
  identify: (value2) => typeof value2 === "bigint" || Number.isInteger(value2),
  default: true,
  tag: "tag:yaml.org,2002:int",
  format: "TIME",
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
  resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
  stringify: stringifySexagesimal
};
var floatTime = {
  identify: (value2) => typeof value2 === "number",
  default: true,
  tag: "tag:yaml.org,2002:float",
  format: "TIME",
  test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
  resolve: (str) => parseSexagesimal(str, false),
  stringify: stringifySexagesimal
};
var timestamp = {
  identify: (value2) => value2 instanceof Date,
  default: true,
  tag: "tag:yaml.org,2002:timestamp",
  // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
  // may be omitted altogether, resulting in a date format. In such a case, the time part is
  // assumed to be 00:00:00Z (start of day, UTC).
  test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
  resolve(str) {
    const match2 = str.match(timestamp.test);
    if (!match2)
      throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
    const [, year, month, day, hour, minute, second] = match2.map(Number);
    const millisec = match2[7] ? Number((match2[7] + "00").substr(1, 3)) : 0;
    let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
    const tz = match2[8];
    if (tz && tz !== "Z") {
      let d = parseSexagesimal(tz, false);
      if (Math.abs(d) < 30)
        d *= 60;
      date -= 6e4 * d;
    }
    return new Date(date);
  },
  stringify: ({ value: value2 }) => value2.toISOString().replace(/((T00:00)?:00)?\.000Z$/, "")
};
var schema = [
  map$1,
  seq,
  string,
  nullTag,
  trueTag,
  falseTag,
  intBin,
  intOct,
  int,
  intHex,
  floatNaN,
  floatExp,
  float,
  binary,
  omap,
  pairs,
  set,
  intTime,
  floatTime,
  timestamp
];
var schemas = /* @__PURE__ */ new Map([
  ["core", schema$2],
  ["failsafe", [map$1, seq, string]],
  ["json", schema$1],
  ["yaml11", schema],
  ["yaml-1.1", schema]
]);
var tagsByName = {
  binary,
  bool: boolTag,
  float: float$1,
  floatExp: floatExp$1,
  floatNaN: floatNaN$1,
  floatTime,
  int: int$1,
  intHex: intHex$1,
  intOct: intOct$1,
  intTime,
  map: map$1,
  null: nullTag,
  omap,
  pairs,
  seq,
  set,
  timestamp
};
var coreKnownTags = {
  "tag:yaml.org,2002:binary": binary,
  "tag:yaml.org,2002:omap": omap,
  "tag:yaml.org,2002:pairs": pairs,
  "tag:yaml.org,2002:set": set,
  "tag:yaml.org,2002:timestamp": timestamp
};
function getTags(customTags, schemaName) {
  let tags = schemas.get(schemaName);
  if (!tags) {
    if (Array.isArray(customTags))
      tags = [];
    else {
      const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", ");
      throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
    }
  }
  if (Array.isArray(customTags)) {
    for (const tag of customTags)
      tags = tags.concat(tag);
  } else if (typeof customTags === "function") {
    tags = customTags(tags.slice());
  }
  return tags.map((tag) => {
    if (typeof tag !== "string")
      return tag;
    const tagObj = tagsByName[tag];
    if (tagObj)
      return tagObj;
    const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", ");
    throw new Error(`Unknown custom tag "${tag}"; use one of ${keys}`);
  });
}
var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
var Schema = class _Schema {
  constructor({ compat, customTags, merge: merge3, resolveKnownTags, schema: schema2, sortMapEntries, toStringDefaults }) {
    this.compat = Array.isArray(compat) ? getTags(compat, "compat") : compat ? getTags(null, compat) : null;
    this.merge = !!merge3;
    this.name = typeof schema2 === "string" && schema2 || "core";
    this.knownTags = resolveKnownTags ? coreKnownTags : {};
    this.tags = getTags(customTags, this.name);
    this.toStringOptions = toStringDefaults ?? null;
    Object.defineProperty(this, MAP, { value: map$1 });
    Object.defineProperty(this, SCALAR$1, { value: string });
    Object.defineProperty(this, SEQ, { value: seq });
    this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null;
  }
  clone() {
    const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this));
    copy.tags = this.tags.slice();
    return copy;
  }
};
function stringifyDocument(doc, options2) {
  var _a4;
  const lines = [];
  let hasDirectives = options2.directives === true;
  if (options2.directives !== false && doc.directives) {
    const dir = doc.directives.toString(doc);
    if (dir) {
      lines.push(dir);
      hasDirectives = true;
    } else if (doc.directives.docStart)
      hasDirectives = true;
  }
  if (hasDirectives)
    lines.push("---");
  const ctx = createStringifyContext(doc, options2);
  const { commentString } = ctx.options;
  if (doc.commentBefore) {
    if (lines.length !== 1)
      lines.unshift("");
    const cs = commentString(doc.commentBefore);
    lines.unshift(indentComment(cs, ""));
  }
  let chompKeep = false;
  let contentComment = null;
  if (doc.contents) {
    if (isNode$1(doc.contents)) {
      if (doc.contents.spaceBefore && hasDirectives)
        lines.push("");
      if (doc.contents.commentBefore) {
        const cs = commentString(doc.contents.commentBefore);
        lines.push(indentComment(cs, ""));
      }
      ctx.forceBlockIndent = !!doc.comment;
      contentComment = doc.contents.comment;
    }
    const onChompKeep = contentComment ? void 0 : () => chompKeep = true;
    let body = stringify$2(doc.contents, ctx, () => contentComment = null, onChompKeep);
    if (contentComment)
      body += lineComment(body, "", commentString(contentComment));
    if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") {
      lines[lines.length - 1] = `--- ${body}`;
    } else
      lines.push(body);
  } else {
    lines.push(stringify$2(doc.contents, ctx));
  }
  if ((_a4 = doc.directives) == null ? void 0 : _a4.docEnd) {
    if (doc.comment) {
      const cs = commentString(doc.comment);
      if (cs.includes("\n")) {
        lines.push("...");
        lines.push(indentComment(cs, ""));
      } else {
        lines.push(`... ${cs}`);
      }
    } else {
      lines.push("...");
    }
  } else {
    let dc = doc.comment;
    if (dc && chompKeep)
      dc = dc.replace(/^\n+/, "");
    if (dc) {
      if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "")
        lines.push("");
      lines.push(indentComment(commentString(dc), ""));
    }
  }
  return lines.join("\n") + "\n";
}
var Document = class _Document {
  constructor(value2, replacer, options2) {
    this.commentBefore = null;
    this.comment = null;
    this.errors = [];
    this.warnings = [];
    Object.defineProperty(this, NODE_TYPE, { value: DOC });
    let _replacer = null;
    if (typeof replacer === "function" || Array.isArray(replacer)) {
      _replacer = replacer;
    } else if (options2 === void 0 && replacer) {
      options2 = replacer;
      replacer = void 0;
    }
    const opt = Object.assign({
      intAsBigInt: false,
      keepSourceTokens: false,
      logLevel: "warn",
      prettyErrors: true,
      strict: true,
      uniqueKeys: true,
      version: "1.2"
    }, options2);
    this.options = opt;
    let { version: version3 } = opt;
    if (options2 == null ? void 0 : options2._directives) {
      this.directives = options2._directives.atDocument();
      if (this.directives.yaml.explicit)
        version3 = this.directives.yaml.version;
    } else
      this.directives = new Directives({ version: version3 });
    this.setSchema(version3, options2);
    this.contents = value2 === void 0 ? null : this.createNode(value2, _replacer, options2);
  }
  /**
   * Create a deep copy of this Document and its contents.
   *
   * Custom Node values that inherit from `Object` still refer to their original instances.
   */
  clone() {
    const copy = Object.create(_Document.prototype, {
      [NODE_TYPE]: { value: DOC }
    });
    copy.commentBefore = this.commentBefore;
    copy.comment = this.comment;
    copy.errors = this.errors.slice();
    copy.warnings = this.warnings.slice();
    copy.options = Object.assign({}, this.options);
    if (this.directives)
      copy.directives = this.directives.clone();
    copy.schema = this.schema.clone();
    copy.contents = isNode$1(this.contents) ? this.contents.clone(copy.schema) : this.contents;
    if (this.range)
      copy.range = this.range.slice();
    return copy;
  }
  /** Adds a value to the document. */
  add(value2) {
    if (assertCollection(this.contents))
      this.contents.add(value2);
  }
  /** Adds a value to the document. */
  addIn(path3, value2) {
    if (assertCollection(this.contents))
      this.contents.addIn(path3, value2);
  }
  /**
   * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
   *
   * If `node` already has an anchor, `name` is ignored.
   * Otherwise, the `node.anchor` value will be set to `name`,
   * or if an anchor with that name is already present in the document,
   * `name` will be used as a prefix for a new unique anchor.
   * If `name` is undefined, the generated anchor will use 'a' as a prefix.
   */
  createAlias(node2, name2) {
    if (!node2.anchor) {
      const prev = anchorNames(this);
      node2.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      !name2 || prev.has(name2) ? findNewAnchor(name2 || "a", prev) : name2;
    }
    return new Alias(node2.anchor);
  }
  createNode(value2, replacer, options2) {
    let _replacer = void 0;
    if (typeof replacer === "function") {
      value2 = replacer.call({ "": value2 }, "", value2);
      _replacer = replacer;
    } else if (Array.isArray(replacer)) {
      const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number;
      const asStr = replacer.filter(keyToStr).map(String);
      if (asStr.length > 0)
        replacer = replacer.concat(asStr);
      _replacer = replacer;
    } else if (options2 === void 0 && replacer) {
      options2 = replacer;
      replacer = void 0;
    }
    const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options2 ?? {};
    const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(
      this,
      // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
      anchorPrefix || "a"
    );
    const ctx = {
      aliasDuplicateObjects: aliasDuplicateObjects ?? true,
      keepUndefined: keepUndefined ?? false,
      onAnchor,
      onTagObj,
      replacer: _replacer,
      schema: this.schema,
      sourceObjects
    };
    const node2 = createNode(value2, tag, ctx);
    if (flow && isCollection$1(node2))
      node2.flow = true;
    setAnchors();
    return node2;
  }
  /**
   * Convert a key and a value into a `Pair` using the current schema,
   * recursively wrapping all values as `Scalar` or `Collection` nodes.
   */
  createPair(key, value2, options2 = {}) {
    const k = this.createNode(key, null, options2);
    const v = this.createNode(value2, null, options2);
    return new Pair(k, v);
  }
  /**
   * Removes a value from the document.
   * @returns `true` if the item was found and removed.
   */
  delete(key) {
    return assertCollection(this.contents) ? this.contents.delete(key) : false;
  }
  /**
   * Removes a value from the document.
   * @returns `true` if the item was found and removed.
   */
  deleteIn(path3) {
    if (isEmptyPath(path3)) {
      if (this.contents == null)
        return false;
      this.contents = null;
      return true;
    }
    return assertCollection(this.contents) ? this.contents.deleteIn(path3) : false;
  }
  /**
   * Returns item at `key`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  get(key, keepScalar) {
    return isCollection$1(this.contents) ? this.contents.get(key, keepScalar) : void 0;
  }
  /**
   * Returns item at `path`, or `undefined` if not found. By default unwraps
   * scalar values from their surrounding node; to disable set `keepScalar` to
   * `true` (collections are always returned intact).
   */
  getIn(path3, keepScalar) {
    if (isEmptyPath(path3))
      return !keepScalar && isScalar$1(this.contents) ? this.contents.value : this.contents;
    return isCollection$1(this.contents) ? this.contents.getIn(path3, keepScalar) : void 0;
  }
  /**
   * Checks if the document includes a value with the key `key`.
   */
  has(key) {
    return isCollection$1(this.contents) ? this.contents.has(key) : false;
  }
  /**
   * Checks if the document includes a value at `path`.
   */
  hasIn(path3) {
    if (isEmptyPath(path3))
      return this.contents !== void 0;
    return isCollection$1(this.contents) ? this.contents.hasIn(path3) : false;
  }
  /**
   * Sets a value in this document. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  set(key, value2) {
    if (this.contents == null) {
      this.contents = collectionFromPath(this.schema, [key], value2);
    } else if (assertCollection(this.contents)) {
      this.contents.set(key, value2);
    }
  }
  /**
   * Sets a value in this document. For `!!set`, `value` needs to be a
   * boolean to add/remove the item from the set.
   */
  setIn(path3, value2) {
    if (isEmptyPath(path3)) {
      this.contents = value2;
    } else if (this.contents == null) {
      this.contents = collectionFromPath(this.schema, Array.from(path3), value2);
    } else if (assertCollection(this.contents)) {
      this.contents.setIn(path3, value2);
    }
  }
  /**
   * Change the YAML version and schema used by the document.
   * A `null` version disables support for directives, explicit tags, anchors, and aliases.
   * It also requires the `schema` option to be given as a `Schema` instance value.
   *
   * Overrides all previously set schema options.
   */
  setSchema(version3, options2 = {}) {
    if (typeof version3 === "number")
      version3 = String(version3);
    let opt;
    switch (version3) {
      case "1.1":
        if (this.directives)
          this.directives.yaml.version = "1.1";
        else
          this.directives = new Directives({ version: "1.1" });
        opt = { merge: true, resolveKnownTags: false, schema: "yaml-1.1" };
        break;
      case "1.2":
      case "next":
        if (this.directives)
          this.directives.yaml.version = version3;
        else
          this.directives = new Directives({ version: version3 });
        opt = { merge: false, resolveKnownTags: true, schema: "core" };
        break;
      case null:
        if (this.directives)
          delete this.directives;
        opt = null;
        break;
      default: {
        const sv = JSON.stringify(version3);
        throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
      }
    }
    if (options2.schema instanceof Object)
      this.schema = options2.schema;
    else if (opt)
      this.schema = new Schema(Object.assign(opt, options2));
    else
      throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
  }
  // json & jsonArg are only used from toJSON()
  toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
    const ctx = {
      anchors: /* @__PURE__ */ new Map(),
      doc: this,
      keep: !json,
      mapAsMap: mapAsMap === true,
      mapKeyWarned: false,
      maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
    };
    const res = toJS(this.contents, jsonArg ?? "", ctx);
    if (typeof onAnchor === "function")
      for (const { count, res: res2 } of ctx.anchors.values())
        onAnchor(res2, count);
    return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
  }
  /**
   * A JSON representation of the document `contents`.
   *
   * @param jsonArg Used by `JSON.stringify` to indicate the array index or
   *   property name.
   */
  toJSON(jsonArg, onAnchor) {
    return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
  }
  /** A YAML representation of the document. */
  toString(options2 = {}) {
    if (this.errors.length > 0)
      throw new Error("Document with errors cannot be stringified");
    if ("indent" in options2 && (!Number.isInteger(options2.indent) || Number(options2.indent) <= 0)) {
      const s = JSON.stringify(options2.indent);
      throw new Error(`"indent" option must be a positive integer, not ${s}`);
    }
    return stringifyDocument(this, options2);
  }
};
function assertCollection(contents) {
  if (isCollection$1(contents))
    return true;
  throw new Error("Expected a YAML collection as document contents");
}
var YAMLError = class extends Error {
  constructor(name2, pos, code, message) {
    super();
    this.name = name2;
    this.code = code;
    this.message = message;
    this.pos = pos;
  }
};
var YAMLParseError = class extends YAMLError {
  constructor(pos, code, message) {
    super("YAMLParseError", pos, code, message);
  }
};
var YAMLWarning = class extends YAMLError {
  constructor(pos, code, message) {
    super("YAMLWarning", pos, code, message);
  }
};
var prettifyError = (src2, lc) => (error2) => {
  if (error2.pos[0] === -1)
    return;
  error2.linePos = error2.pos.map((pos) => lc.linePos(pos));
  const { line, col } = error2.linePos[0];
  error2.message += ` at line ${line}, column ${col}`;
  let ci = col - 1;
  let lineStr = src2.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
  if (ci >= 60 && lineStr.length > 80) {
    const trimStart = Math.min(ci - 39, lineStr.length - 79);
    lineStr = "…" + lineStr.substring(trimStart);
    ci -= trimStart - 1;
  }
  if (lineStr.length > 80)
    lineStr = lineStr.substring(0, 79) + "…";
  if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
    let prev = src2.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
    if (prev.length > 80)
      prev = prev.substring(0, 79) + "…\n";
    lineStr = prev + lineStr;
  }
  if (/[^ ]/.test(lineStr)) {
    let count = 1;
    const end = error2.linePos[1];
    if (end && end.line === line && end.col > col) {
      count = Math.max(1, Math.min(end.col - col, 80 - ci));
    }
    const pointer = " ".repeat(ci) + "^".repeat(count);
    error2.message += `:

${lineStr}
${pointer}
`;
  }
};
function resolveProps(tokens, { flow, indicator, next, offset: offset2, onError: onError2, parentIndent, startOnNewline }) {
  let spaceBefore = false;
  let atNewline = startOnNewline;
  let hasSpace = startOnNewline;
  let comment = "";
  let commentSep = "";
  let hasNewline = false;
  let hasNewlineAfterProp = false;
  let reqSpace = false;
  let tab = null;
  let anchor = null;
  let tag = null;
  let comma2 = null;
  let found2 = null;
  let start = null;
  for (const token of tokens) {
    if (reqSpace) {
      if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
        onError2(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
      reqSpace = false;
    }
    if (tab) {
      if (atNewline && token.type !== "comment" && token.type !== "newline") {
        onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
      }
      tab = null;
    }
    switch (token.type) {
      case "space":
        if (!flow && (indicator !== "doc-start" || (next == null ? void 0 : next.type) !== "flow-collection") && token.source.includes("	")) {
          tab = token;
        }
        hasSpace = true;
        break;
      case "comment": {
        if (!hasSpace)
          onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
        const cb = token.source.substring(1) || " ";
        if (!comment)
          comment = cb;
        else
          comment += commentSep + cb;
        commentSep = "";
        atNewline = false;
        break;
      }
      case "newline":
        if (atNewline) {
          if (comment)
            comment += token.source;
          else
            spaceBefore = true;
        } else
          commentSep += token.source;
        atNewline = true;
        hasNewline = true;
        if (anchor || tag)
          hasNewlineAfterProp = true;
        hasSpace = true;
        break;
      case "anchor":
        if (anchor)
          onError2(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
        if (token.source.endsWith(":"))
          onError2(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
        anchor = token;
        if (start === null)
          start = token.offset;
        atNewline = false;
        hasSpace = false;
        reqSpace = true;
        break;
      case "tag": {
        if (tag)
          onError2(token, "MULTIPLE_TAGS", "A node can have at most one tag");
        tag = token;
        if (start === null)
          start = token.offset;
        atNewline = false;
        hasSpace = false;
        reqSpace = true;
        break;
      }
      case indicator:
        if (anchor || tag)
          onError2(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`);
        if (found2)
          onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`);
        found2 = token;
        atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
        hasSpace = false;
        break;
      case "comma":
        if (flow) {
          if (comma2)
            onError2(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`);
          comma2 = token;
          atNewline = false;
          hasSpace = false;
          break;
        }
      default:
        onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`);
        atNewline = false;
        hasSpace = false;
    }
  }
  const last = tokens[tokens.length - 1];
  const end = last ? last.offset + last.source.length : offset2;
  if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) {
    onError2(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
  }
  if (tab && (atNewline && tab.indent <= parentIndent || (next == null ? void 0 : next.type) === "block-map" || (next == null ? void 0 : next.type) === "block-seq"))
    onError2(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
  return {
    comma: comma2,
    found: found2,
    spaceBefore,
    comment,
    hasNewline,
    hasNewlineAfterProp,
    anchor,
    tag,
    end,
    start: start ?? end
  };
}
function containsNewline(key) {
  if (!key)
    return null;
  switch (key.type) {
    case "alias":
    case "scalar":
    case "double-quoted-scalar":
    case "single-quoted-scalar":
      if (key.source.includes("\n"))
        return true;
      if (key.end) {
        for (const st of key.end)
          if (st.type === "newline")
            return true;
      }
      return false;
    case "flow-collection":
      for (const it of key.items) {
        for (const st of it.start)
          if (st.type === "newline")
            return true;
        if (it.sep) {
          for (const st of it.sep)
            if (st.type === "newline")
              return true;
        }
        if (containsNewline(it.key) || containsNewline(it.value))
          return true;
      }
      return false;
    default:
      return true;
  }
}
function flowIndentCheck(indent, fc, onError2) {
  if ((fc == null ? void 0 : fc.type) === "flow-collection") {
    const end = fc.end[0];
    if (end.indent === indent && (end.source === "]" || end.source === "}") && containsNewline(fc)) {
      const msg = "Flow end indicator should be more indented than parent";
      onError2(end, "BAD_INDENT", msg, true);
    }
  }
}
function mapIncludes(ctx, items, search) {
  const { uniqueKeys } = ctx.options;
  if (uniqueKeys === false)
    return false;
  const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar$1(a) && isScalar$1(b) && a.value === b.value && !(a.value === "<<" && ctx.schema.merge);
  return items.some((pair) => isEqual(pair.key, search));
}
var startColMsg = "All mapping items must start at the same column";
function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError2, tag) {
  var _a4;
  const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLMap;
  const map2 = new NodeClass(ctx.schema);
  if (ctx.atRoot)
    ctx.atRoot = false;
  let offset2 = bm.offset;
  let commentEnd = null;
  for (const collItem of bm.items) {
    const { start, key, sep: sep2, value: value2 } = collItem;
    const keyProps = resolveProps(start, {
      indicator: "explicit-key-ind",
      next: key ?? (sep2 == null ? void 0 : sep2[0]),
      offset: offset2,
      onError: onError2,
      parentIndent: bm.indent,
      startOnNewline: true
    });
    const implicitKey = !keyProps.found;
    if (implicitKey) {
      if (key) {
        if (key.type === "block-seq")
          onError2(offset2, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key");
        else if ("indent" in key && key.indent !== bm.indent)
          onError2(offset2, "BAD_INDENT", startColMsg);
      }
      if (!keyProps.anchor && !keyProps.tag && !sep2) {
        commentEnd = keyProps.end;
        if (keyProps.comment) {
          if (map2.comment)
            map2.comment += "\n" + keyProps.comment;
          else
            map2.comment = keyProps.comment;
        }
        continue;
      }
      if (keyProps.hasNewlineAfterProp || containsNewline(key)) {
        onError2(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line");
      }
    } else if (((_a4 = keyProps.found) == null ? void 0 : _a4.indent) !== bm.indent) {
      onError2(offset2, "BAD_INDENT", startColMsg);
    }
    const keyStart = keyProps.end;
    const keyNode = key ? composeNode2(ctx, key, keyProps, onError2) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError2);
    if (ctx.schema.compat)
      flowIndentCheck(bm.indent, key, onError2);
    if (mapIncludes(ctx, map2.items, keyNode))
      onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
    const valueProps = resolveProps(sep2 ?? [], {
      indicator: "map-value-ind",
      next: value2,
      offset: keyNode.range[2],
      onError: onError2,
      parentIndent: bm.indent,
      startOnNewline: !key || key.type === "block-scalar"
    });
    offset2 = valueProps.end;
    if (valueProps.found) {
      if (implicitKey) {
        if ((value2 == null ? void 0 : value2.type) === "block-map" && !valueProps.hasNewline)
          onError2(offset2, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings");
        if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
          onError2(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
      }
      const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError2) : composeEmptyNode2(ctx, offset2, sep2, null, valueProps, onError2);
      if (ctx.schema.compat)
        flowIndentCheck(bm.indent, value2, onError2);
      offset2 = valueNode.range[2];
      const pair = new Pair(keyNode, valueNode);
      if (ctx.options.keepSourceTokens)
        pair.srcToken = collItem;
      map2.items.push(pair);
    } else {
      if (implicitKey)
        onError2(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
      if (valueProps.comment) {
        if (keyNode.comment)
          keyNode.comment += "\n" + valueProps.comment;
        else
          keyNode.comment = valueProps.comment;
      }
      const pair = new Pair(keyNode);
      if (ctx.options.keepSourceTokens)
        pair.srcToken = collItem;
      map2.items.push(pair);
    }
  }
  if (commentEnd && commentEnd < offset2)
    onError2(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
  map2.range = [bm.offset, offset2, commentEnd ?? offset2];
  return map2;
}
function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError2, tag) {
  const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? YAMLSeq;
  const seq2 = new NodeClass(ctx.schema);
  if (ctx.atRoot)
    ctx.atRoot = false;
  let offset2 = bs.offset;
  let commentEnd = null;
  for (const { start, value: value2 } of bs.items) {
    const props = resolveProps(start, {
      indicator: "seq-item-ind",
      next: value2,
      offset: offset2,
      onError: onError2,
      parentIndent: bs.indent,
      startOnNewline: true
    });
    if (!props.found) {
      if (props.anchor || props.tag || value2) {
        if (value2 && value2.type === "block-seq")
          onError2(props.end, "BAD_INDENT", "All sequence items must start at the same column");
        else
          onError2(offset2, "MISSING_CHAR", "Sequence item without - indicator");
      } else {
        commentEnd = props.end;
        if (props.comment)
          seq2.comment = props.comment;
        continue;
      }
    }
    const node2 = value2 ? composeNode2(ctx, value2, props, onError2) : composeEmptyNode2(ctx, props.end, start, null, props, onError2);
    if (ctx.schema.compat)
      flowIndentCheck(bs.indent, value2, onError2);
    offset2 = node2.range[2];
    seq2.items.push(node2);
  }
  seq2.range = [bs.offset, offset2, commentEnd ?? offset2];
  return seq2;
}
function resolveEnd(end, offset2, reqSpace, onError2) {
  let comment = "";
  if (end) {
    let hasSpace = false;
    let sep2 = "";
    for (const token of end) {
      const { source, type } = token;
      switch (type) {
        case "space":
          hasSpace = true;
          break;
        case "comment": {
          if (reqSpace && !hasSpace)
            onError2(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
          const cb = source.substring(1) || " ";
          if (!comment)
            comment = cb;
          else
            comment += sep2 + cb;
          sep2 = "";
          break;
        }
        case "newline":
          if (comment)
            sep2 += source;
          hasSpace = true;
          break;
        default:
          onError2(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`);
      }
      offset2 += source.length;
    }
  }
  return { comment, offset: offset2 };
}
var blockMsg = "Block collections are not allowed within flow collections";
var isBlock$1 = (token) => token && (token.type === "block-map" || token.type === "block-seq");
function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError2, tag) {
  const isMap2 = fc.start.source === "{";
  const fcName = isMap2 ? "flow map" : "flow sequence";
  const NodeClass = (tag == null ? void 0 : tag.nodeClass) ?? (isMap2 ? YAMLMap : YAMLSeq);
  const coll = new NodeClass(ctx.schema);
  coll.flow = true;
  const atRoot = ctx.atRoot;
  if (atRoot)
    ctx.atRoot = false;
  let offset2 = fc.offset + fc.start.source.length;
  for (let i = 0; i < fc.items.length; ++i) {
    const collItem = fc.items[i];
    const { start, key, sep: sep2, value: value2 } = collItem;
    const props = resolveProps(start, {
      flow: fcName,
      indicator: "explicit-key-ind",
      next: key ?? (sep2 == null ? void 0 : sep2[0]),
      offset: offset2,
      onError: onError2,
      parentIndent: fc.indent,
      startOnNewline: false
    });
    if (!props.found) {
      if (!props.anchor && !props.tag && !sep2 && !value2) {
        if (i === 0 && props.comma)
          onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
        else if (i < fc.items.length - 1)
          onError2(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`);
        if (props.comment) {
          if (coll.comment)
            coll.comment += "\n" + props.comment;
          else
            coll.comment = props.comment;
        }
        offset2 = props.end;
        continue;
      }
      if (!isMap2 && ctx.options.strict && containsNewline(key))
        onError2(
          key,
          // checked by containsNewline()
          "MULTILINE_IMPLICIT_KEY",
          "Implicit keys of flow sequence pairs need to be on a single line"
        );
    }
    if (i === 0) {
      if (props.comma)
        onError2(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
    } else {
      if (!props.comma)
        onError2(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
      if (props.comment) {
        let prevItemComment = "";
        loop: for (const st of start) {
          switch (st.type) {
            case "comma":
            case "space":
              break;
            case "comment":
              prevItemComment = st.source.substring(1);
              break loop;
            default:
              break loop;
          }
        }
        if (prevItemComment) {
          let prev = coll.items[coll.items.length - 1];
          if (isPair(prev))
            prev = prev.value ?? prev.key;
          if (prev.comment)
            prev.comment += "\n" + prevItemComment;
          else
            prev.comment = prevItemComment;
          props.comment = props.comment.substring(prevItemComment.length + 1);
        }
      }
    }
    if (!isMap2 && !sep2 && !props.found) {
      const valueNode = value2 ? composeNode2(ctx, value2, props, onError2) : composeEmptyNode2(ctx, props.end, sep2, null, props, onError2);
      coll.items.push(valueNode);
      offset2 = valueNode.range[2];
      if (isBlock$1(value2))
        onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
    } else {
      const keyStart = props.end;
      const keyNode = key ? composeNode2(ctx, key, props, onError2) : composeEmptyNode2(ctx, keyStart, start, null, props, onError2);
      if (isBlock$1(key))
        onError2(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
      const valueProps = resolveProps(sep2 ?? [], {
        flow: fcName,
        indicator: "map-value-ind",
        next: value2,
        offset: keyNode.range[2],
        onError: onError2,
        parentIndent: fc.indent,
        startOnNewline: false
      });
      if (valueProps.found) {
        if (!isMap2 && !props.found && ctx.options.strict) {
          if (sep2)
            for (const st of sep2) {
              if (st === valueProps.found)
                break;
              if (st.type === "newline") {
                onError2(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line");
                break;
              }
            }
          if (props.start < valueProps.found.offset - 1024)
            onError2(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
        }
      } else if (value2) {
        if ("source" in value2 && value2.source && value2.source[0] === ":")
          onError2(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`);
        else
          onError2(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
      }
      const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError2) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep2, null, valueProps, onError2) : null;
      if (valueNode) {
        if (isBlock$1(value2))
          onError2(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
      } else if (valueProps.comment) {
        if (keyNode.comment)
          keyNode.comment += "\n" + valueProps.comment;
        else
          keyNode.comment = valueProps.comment;
      }
      const pair = new Pair(keyNode, valueNode);
      if (ctx.options.keepSourceTokens)
        pair.srcToken = collItem;
      if (isMap2) {
        const map2 = coll;
        if (mapIncludes(ctx, map2.items, keyNode))
          onError2(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
        map2.items.push(pair);
      } else {
        const map2 = new YAMLMap(ctx.schema);
        map2.flow = true;
        map2.items.push(pair);
        coll.items.push(map2);
      }
      offset2 = valueNode ? valueNode.range[2] : valueProps.end;
    }
  }
  const expectedEnd = isMap2 ? "}" : "]";
  const [ce, ...ee] = fc.end;
  let cePos = offset2;
  if (ce && ce.source === expectedEnd)
    cePos = ce.offset + ce.source.length;
  else {
    const name2 = fcName[0].toUpperCase() + fcName.substring(1);
    const msg = atRoot ? `${name2} must end with a ${expectedEnd}` : `${name2} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
    onError2(offset2, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
    if (ce && ce.source.length !== 1)
      ee.unshift(ce);
  }
  if (ee.length > 0) {
    const end = resolveEnd(ee, cePos, ctx.options.strict, onError2);
    if (end.comment) {
      if (coll.comment)
        coll.comment += "\n" + end.comment;
      else
        coll.comment = end.comment;
    }
    coll.range = [fc.offset, cePos, end.offset];
  } else {
    coll.range = [fc.offset, cePos, cePos];
  }
  return coll;
}
function resolveCollection(CN2, ctx, token, onError2, tagName, tag) {
  const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError2, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError2, tag) : resolveFlowCollection(CN2, ctx, token, onError2, tag);
  const Coll = coll.constructor;
  if (tagName === "!" || tagName === Coll.tagName) {
    coll.tag = Coll.tagName;
    return coll;
  }
  if (tagName)
    coll.tag = tagName;
  return coll;
}
function composeCollection(CN2, ctx, token, tagToken, onError2) {
  var _a4;
  const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg));
  const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
  if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq" || !expType) {
    return resolveCollection(CN2, ctx, token, onError2, tagName);
  }
  let tag = ctx.schema.tags.find((t2) => t2.tag === tagName && t2.collection === expType);
  if (!tag) {
    const kt = ctx.schema.knownTags[tagName];
    if (kt && kt.collection === expType) {
      ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
      tag = kt;
    } else {
      if (kt == null ? void 0 : kt.collection) {
        onError2(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection}`, true);
      } else {
        onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
      }
      return resolveCollection(CN2, ctx, token, onError2, tagName);
    }
  }
  const coll = resolveCollection(CN2, ctx, token, onError2, tagName, tag);
  const res = ((_a4 = tag.resolve) == null ? void 0 : _a4.call(tag, coll, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options)) ?? coll;
  const node2 = isNode$1(res) ? res : new Scalar(res);
  node2.range = coll.range;
  node2.tag = tagName;
  if (tag == null ? void 0 : tag.format)
    node2.format = tag.format;
  return node2;
}
function resolveBlockScalar(ctx, scalar, onError2) {
  const start = scalar.offset;
  const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError2);
  if (!header)
    return { value: "", type: null, comment: "", range: [start, start, start] };
  const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
  const lines = scalar.source ? splitLines(scalar.source) : [];
  let chompStart = lines.length;
  for (let i = lines.length - 1; i >= 0; --i) {
    const content = lines[i][1];
    if (content === "" || content === "\r")
      chompStart = i;
    else
      break;
  }
  if (chompStart === 0) {
    const value3 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
    let end2 = start + header.length;
    if (scalar.source)
      end2 += scalar.source.length;
    return { value: value3, type, comment: header.comment, range: [start, end2, end2] };
  }
  let trimIndent = scalar.indent + header.indent;
  let offset2 = scalar.offset + header.length;
  let contentStart = 0;
  for (let i = 0; i < chompStart; ++i) {
    const [indent, content] = lines[i];
    if (content === "" || content === "\r") {
      if (header.indent === 0 && indent.length > trimIndent)
        trimIndent = indent.length;
    } else {
      if (indent.length < trimIndent) {
        const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
        onError2(offset2 + indent.length, "MISSING_CHAR", message);
      }
      if (header.indent === 0)
        trimIndent = indent.length;
      contentStart = i;
      if (trimIndent === 0 && !ctx.atRoot) {
        const message = "Block scalar values in collections must be indented";
        onError2(offset2, "BAD_INDENT", message);
      }
      break;
    }
    offset2 += indent.length + content.length + 1;
  }
  for (let i = lines.length - 1; i >= chompStart; --i) {
    if (lines[i][0].length > trimIndent)
      chompStart = i + 1;
  }
  let value2 = "";
  let sep2 = "";
  let prevMoreIndented = false;
  for (let i = 0; i < contentStart; ++i)
    value2 += lines[i][0].slice(trimIndent) + "\n";
  for (let i = contentStart; i < chompStart; ++i) {
    let [indent, content] = lines[i];
    offset2 += indent.length + content.length + 1;
    const crlf = content[content.length - 1] === "\r";
    if (crlf)
      content = content.slice(0, -1);
    if (content && indent.length < trimIndent) {
      const src2 = header.indent ? "explicit indentation indicator" : "first line";
      const message = `Block scalar lines must not be less indented than their ${src2}`;
      onError2(offset2 - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
      indent = "";
    }
    if (type === Scalar.BLOCK_LITERAL) {
      value2 += sep2 + indent.slice(trimIndent) + content;
      sep2 = "\n";
    } else if (indent.length > trimIndent || content[0] === "	") {
      if (sep2 === " ")
        sep2 = "\n";
      else if (!prevMoreIndented && sep2 === "\n")
        sep2 = "\n\n";
      value2 += sep2 + indent.slice(trimIndent) + content;
      sep2 = "\n";
      prevMoreIndented = true;
    } else if (content === "") {
      if (sep2 === "\n")
        value2 += "\n";
      else
        sep2 = "\n";
    } else {
      value2 += sep2 + content;
      sep2 = " ";
      prevMoreIndented = false;
    }
  }
  switch (header.chomp) {
    case "-":
      break;
    case "+":
      for (let i = chompStart; i < lines.length; ++i)
        value2 += "\n" + lines[i][0].slice(trimIndent);
      if (value2[value2.length - 1] !== "\n")
        value2 += "\n";
      break;
    default:
      value2 += "\n";
  }
  const end = start + header.length + scalar.source.length;
  return { value: value2, type, comment: header.comment, range: [start, end, end] };
}
function parseBlockScalarHeader({ offset: offset2, props }, strict, onError2) {
  if (props[0].type !== "block-scalar-header") {
    onError2(props[0], "IMPOSSIBLE", "Block scalar header not found");
    return null;
  }
  const { source } = props[0];
  const mode2 = source[0];
  let indent = 0;
  let chomp = "";
  let error2 = -1;
  for (let i = 1; i < source.length; ++i) {
    const ch = source[i];
    if (!chomp && (ch === "-" || ch === "+"))
      chomp = ch;
    else {
      const n2 = Number(ch);
      if (!indent && n2)
        indent = n2;
      else if (error2 === -1)
        error2 = offset2 + i;
    }
  }
  if (error2 !== -1)
    onError2(error2, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`);
  let hasSpace = false;
  let comment = "";
  let length = source.length;
  for (let i = 1; i < props.length; ++i) {
    const token = props[i];
    switch (token.type) {
      case "space":
        hasSpace = true;
      case "newline":
        length += token.source.length;
        break;
      case "comment":
        if (strict && !hasSpace) {
          const message = "Comments must be separated from other tokens by white space characters";
          onError2(token, "MISSING_CHAR", message);
        }
        length += token.source.length;
        comment = token.source.substring(1);
        break;
      case "error":
        onError2(token, "UNEXPECTED_TOKEN", token.message);
        length += token.source.length;
        break;
      default: {
        const message = `Unexpected token in block scalar header: ${token.type}`;
        onError2(token, "UNEXPECTED_TOKEN", message);
        const ts = token.source;
        if (ts && typeof ts === "string")
          length += ts.length;
      }
    }
  }
  return { mode: mode2, indent, chomp, comment, length };
}
function splitLines(source) {
  const split = source.split(/\n( *)/);
  const first2 = split[0];
  const m = first2.match(/^( *)/);
  const line0 = (m == null ? void 0 : m[1]) ? [m[1], first2.slice(m[1].length)] : ["", first2];
  const lines = [line0];
  for (let i = 1; i < split.length; i += 2)
    lines.push([split[i], split[i + 1]]);
  return lines;
}
function resolveFlowScalar(scalar, strict, onError2) {
  const { offset: offset2, type, source, end } = scalar;
  let _type2;
  let value2;
  const _onError = (rel, code, msg) => onError2(offset2 + rel, code, msg);
  switch (type) {
    case "scalar":
      _type2 = Scalar.PLAIN;
      value2 = plainValue(source, _onError);
      break;
    case "single-quoted-scalar":
      _type2 = Scalar.QUOTE_SINGLE;
      value2 = singleQuotedValue(source, _onError);
      break;
    case "double-quoted-scalar":
      _type2 = Scalar.QUOTE_DOUBLE;
      value2 = doubleQuotedValue(source, _onError);
      break;
    default:
      onError2(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`);
      return {
        value: "",
        type: null,
        comment: "",
        range: [offset2, offset2 + source.length, offset2 + source.length]
      };
  }
  const valueEnd = offset2 + source.length;
  const re = resolveEnd(end, valueEnd, strict, onError2);
  return {
    value: value2,
    type: _type2,
    comment: re.comment,
    range: [offset2, valueEnd, re.offset]
  };
}
function plainValue(source, onError2) {
  let badChar = "";
  switch (source[0]) {
    case "	":
      badChar = "a tab character";
      break;
    case ",":
      badChar = "flow indicator character ,";
      break;
    case "%":
      badChar = "directive indicator character %";
      break;
    case "|":
    case ">": {
      badChar = `block scalar indicator ${source[0]}`;
      break;
    }
    case "@":
    case "`": {
      badChar = `reserved character ${source[0]}`;
      break;
    }
  }
  if (badChar)
    onError2(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
  return foldLines(source);
}
function singleQuotedValue(source, onError2) {
  if (source[source.length - 1] !== "'" || source.length === 1)
    onError2(source.length, "MISSING_CHAR", "Missing closing 'quote");
  return foldLines(source.slice(1, -1)).replace(/''/g, "'");
}
function foldLines(source) {
  let first2, line;
  try {
    first2 = new RegExp("(.*?)(? wsStart ? source.slice(wsStart, i + 1) : ch;
    } else {
      res += ch;
    }
  }
  if (source[source.length - 1] !== '"' || source.length === 1)
    onError2(source.length, "MISSING_CHAR", 'Missing closing "quote');
  return res;
}
function foldNewline(source, offset2) {
  let fold = "";
  let ch = source[offset2 + 1];
  while (ch === " " || ch === "	" || ch === "\n" || ch === "\r") {
    if (ch === "\r" && source[offset2 + 2] !== "\n")
      break;
    if (ch === "\n")
      fold += "\n";
    offset2 += 1;
    ch = source[offset2 + 1];
  }
  if (!fold)
    fold = " ";
  return { fold, offset: offset2 };
}
var escapeCodes = {
  "0": "\0",
  // null character
  a: "\x07",
  // bell character
  b: "\b",
  // backspace
  e: "\x1B",
  // escape character
  f: "\f",
  // form feed
  n: "\n",
  // line feed
  r: "\r",
  // carriage return
  t: "	",
  // horizontal tab
  v: "\v",
  // vertical tab
  N: "…",
  // Unicode next line
  _: " ",
  // Unicode non-breaking space
  L: "\u2028",
  // Unicode line separator
  P: "\u2029",
  // Unicode paragraph separator
  " ": " ",
  '"': '"',
  "/": "/",
  "\\": "\\",
  "	": "	"
};
function parseCharCode(source, offset2, length, onError2) {
  const cc = source.substr(offset2, length);
  const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
  const code = ok ? parseInt(cc, 16) : NaN;
  if (isNaN(code)) {
    const raw = source.substr(offset2 - 2, length + 2);
    onError2(offset2 - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
    return raw;
  }
  return String.fromCodePoint(code);
}
function composeScalar(ctx, token, tagToken, onError2) {
  const { value: value2, type, comment, range: range2 } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError2) : resolveFlowScalar(token, ctx.options.strict, onError2);
  const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError2(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
  const tag = tagToken && tagName ? findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError2) : token.type === "scalar" ? findScalarTagByTest(ctx, value2, token, onError2) : ctx.schema[SCALAR$1];
  let scalar;
  try {
    const res = tag.resolve(value2, (msg) => onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
    scalar = isScalar$1(res) ? res : new Scalar(res);
  } catch (error2) {
    const msg = error2 instanceof Error ? error2.message : String(error2);
    onError2(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
    scalar = new Scalar(value2);
  }
  scalar.range = range2;
  scalar.source = value2;
  if (type)
    scalar.type = type;
  if (tagName)
    scalar.tag = tagName;
  if (tag.format)
    scalar.format = tag.format;
  if (comment)
    scalar.comment = comment;
  return scalar;
}
function findScalarTagByName(schema2, value2, tagName, tagToken, onError2) {
  var _a4;
  if (tagName === "!")
    return schema2[SCALAR$1];
  const matchWithTest = [];
  for (const tag of schema2.tags) {
    if (!tag.collection && tag.tag === tagName) {
      if (tag.default && tag.test)
        matchWithTest.push(tag);
      else
        return tag;
    }
  }
  for (const tag of matchWithTest)
    if ((_a4 = tag.test) == null ? void 0 : _a4.test(value2))
      return tag;
  const kt = schema2.knownTags[tagName];
  if (kt && !kt.collection) {
    schema2.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
    return kt;
  }
  onError2(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
  return schema2[SCALAR$1];
}
function findScalarTagByTest({ directives, schema: schema2 }, value2, token, onError2) {
  const tag = schema2.tags.find((tag2) => {
    var _a4;
    return tag2.default && ((_a4 = tag2.test) == null ? void 0 : _a4.test(value2));
  }) || schema2[SCALAR$1];
  if (schema2.compat) {
    const compat = schema2.compat.find((tag2) => {
      var _a4;
      return tag2.default && ((_a4 = tag2.test) == null ? void 0 : _a4.test(value2));
    }) ?? schema2[SCALAR$1];
    if (tag.tag !== compat.tag) {
      const ts = directives.tagString(tag.tag);
      const cs = directives.tagString(compat.tag);
      const msg = `Value may be parsed as either ${ts} or ${cs}`;
      onError2(token, "TAG_RESOLVE_FAILED", msg, true);
    }
  }
  return tag;
}
function emptyScalarPosition(offset2, before, pos) {
  if (before) {
    if (pos === null)
      pos = before.length;
    for (let i = pos - 1; i >= 0; --i) {
      let st = before[i];
      switch (st.type) {
        case "space":
        case "comment":
        case "newline":
          offset2 -= st.source.length;
          continue;
      }
      st = before[++i];
      while ((st == null ? void 0 : st.type) === "space") {
        offset2 += st.source.length;
        st = before[++i];
      }
      break;
    }
  }
  return offset2;
}
var CN = { composeNode, composeEmptyNode };
function composeNode(ctx, token, props, onError2) {
  const { spaceBefore, comment, anchor, tag } = props;
  let node2;
  let isSrcToken = true;
  switch (token.type) {
    case "alias":
      node2 = composeAlias(ctx, token, onError2);
      if (anchor || tag)
        onError2(token, "ALIAS_PROPS", "An alias node must not specify any properties");
      break;
    case "scalar":
    case "single-quoted-scalar":
    case "double-quoted-scalar":
    case "block-scalar":
      node2 = composeScalar(ctx, token, tag, onError2);
      if (anchor)
        node2.anchor = anchor.source.substring(1);
      break;
    case "block-map":
    case "block-seq":
    case "flow-collection":
      node2 = composeCollection(CN, ctx, token, tag, onError2);
      if (anchor)
        node2.anchor = anchor.source.substring(1);
      break;
    default: {
      const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`;
      onError2(token, "UNEXPECTED_TOKEN", message);
      node2 = composeEmptyNode(ctx, token.offset, void 0, null, props, onError2);
      isSrcToken = false;
    }
  }
  if (anchor && node2.anchor === "")
    onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
  if (spaceBefore)
    node2.spaceBefore = true;
  if (comment) {
    if (token.type === "scalar" && token.source === "")
      node2.comment = comment;
    else
      node2.commentBefore = comment;
  }
  if (ctx.options.keepSourceTokens && isSrcToken)
    node2.srcToken = token;
  return node2;
}
function composeEmptyNode(ctx, offset2, before, pos, { spaceBefore, comment, anchor, tag, end }, onError2) {
  const token = {
    type: "scalar",
    offset: emptyScalarPosition(offset2, before, pos),
    indent: -1,
    source: ""
  };
  const node2 = composeScalar(ctx, token, tag, onError2);
  if (anchor) {
    node2.anchor = anchor.source.substring(1);
    if (node2.anchor === "")
      onError2(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
  }
  if (spaceBefore)
    node2.spaceBefore = true;
  if (comment) {
    node2.comment = comment;
    node2.range[2] = end;
  }
  return node2;
}
function composeAlias({ options: options2 }, { offset: offset2, source, end }, onError2) {
  const alias2 = new Alias(source.substring(1));
  if (alias2.source === "")
    onError2(offset2, "BAD_ALIAS", "Alias cannot be an empty string");
  if (alias2.source.endsWith(":"))
    onError2(offset2 + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
  const valueEnd = offset2 + source.length;
  const re = resolveEnd(end, valueEnd, options2.strict, onError2);
  alias2.range = [offset2, valueEnd, re.offset];
  if (re.comment)
    alias2.comment = re.comment;
  return alias2;
}
function composeDoc(options2, directives, { offset: offset2, start, value: value2, end }, onError2) {
  const opts = Object.assign({ _directives: directives }, options2);
  const doc = new Document(void 0, opts);
  const ctx = {
    atRoot: true,
    directives: doc.directives,
    options: doc.options,
    schema: doc.schema
  };
  const props = resolveProps(start, {
    indicator: "doc-start",
    next: value2 ?? (end == null ? void 0 : end[0]),
    offset: offset2,
    onError: onError2,
    parentIndent: 0,
    startOnNewline: true
  });
  if (props.found) {
    doc.directives.docStart = true;
    if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline)
      onError2(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
  }
  doc.contents = value2 ? composeNode(ctx, value2, props, onError2) : composeEmptyNode(ctx, props.end, start, null, props, onError2);
  const contentEnd = doc.contents.range[2];
  const re = resolveEnd(end, contentEnd, false, onError2);
  if (re.comment)
    doc.comment = re.comment;
  doc.range = [offset2, contentEnd, re.offset];
  return doc;
}
function getErrorPos(src2) {
  if (typeof src2 === "number")
    return [src2, src2 + 1];
  if (Array.isArray(src2))
    return src2.length === 2 ? src2 : [src2[0], src2[1]];
  const { offset: offset2, source } = src2;
  return [offset2, offset2 + (typeof source === "string" ? source.length : 1)];
}
function parsePrelude(prelude) {
  var _a4;
  let comment = "";
  let atComment = false;
  let afterEmptyLine = false;
  for (let i = 0; i < prelude.length; ++i) {
    const source = prelude[i];
    switch (source[0]) {
      case "#":
        comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
        atComment = true;
        afterEmptyLine = false;
        break;
      case "%":
        if (((_a4 = prelude[i + 1]) == null ? void 0 : _a4[0]) !== "#")
          i += 1;
        atComment = false;
        break;
      default:
        if (!atComment)
          afterEmptyLine = true;
        atComment = false;
    }
  }
  return { comment, afterEmptyLine };
}
var Composer = class {
  constructor(options2 = {}) {
    this.doc = null;
    this.atDirectives = false;
    this.prelude = [];
    this.errors = [];
    this.warnings = [];
    this.onError = (source, code, message, warning) => {
      const pos = getErrorPos(source);
      if (warning)
        this.warnings.push(new YAMLWarning(pos, code, message));
      else
        this.errors.push(new YAMLParseError(pos, code, message));
    };
    this.directives = new Directives({ version: options2.version || "1.2" });
    this.options = options2;
  }
  decorate(doc, afterDoc) {
    const { comment, afterEmptyLine } = parsePrelude(this.prelude);
    if (comment) {
      const dc = doc.contents;
      if (afterDoc) {
        doc.comment = doc.comment ? `${doc.comment}
${comment}` : comment;
      } else if (afterEmptyLine || doc.directives.docStart || !dc) {
        doc.commentBefore = comment;
      } else if (isCollection$1(dc) && !dc.flow && dc.items.length > 0) {
        let it = dc.items[0];
        if (isPair(it))
          it = it.key;
        const cb = it.commentBefore;
        it.commentBefore = cb ? `${comment}
${cb}` : comment;
      } else {
        const cb = dc.commentBefore;
        dc.commentBefore = cb ? `${comment}
${cb}` : comment;
      }
    }
    if (afterDoc) {
      Array.prototype.push.apply(doc.errors, this.errors);
      Array.prototype.push.apply(doc.warnings, this.warnings);
    } else {
      doc.errors = this.errors;
      doc.warnings = this.warnings;
    }
    this.prelude = [];
    this.errors = [];
    this.warnings = [];
  }
  /**
   * Current stream status information.
   *
   * Mostly useful at the end of input for an empty stream.
   */
  streamInfo() {
    return {
      comment: parsePrelude(this.prelude).comment,
      directives: this.directives,
      errors: this.errors,
      warnings: this.warnings
    };
  }
  /**
   * Compose tokens into documents.
   *
   * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
   * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
   */
  *compose(tokens, forceDoc = false, endOffset = -1) {
    for (const token of tokens)
      yield* this.next(token);
    yield* this.end(forceDoc, endOffset);
  }
  /** Advance the composer by one CST token. */
  *next(token) {
    switch (token.type) {
      case "directive":
        this.directives.add(token.source, (offset2, message, warning) => {
          const pos = getErrorPos(token);
          pos[0] += offset2;
          this.onError(pos, "BAD_DIRECTIVE", message, warning);
        });
        this.prelude.push(token.source);
        this.atDirectives = true;
        break;
      case "document": {
        const doc = composeDoc(this.options, this.directives, token, this.onError);
        if (this.atDirectives && !doc.directives.docStart)
          this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
        this.decorate(doc, false);
        if (this.doc)
          yield this.doc;
        this.doc = doc;
        this.atDirectives = false;
        break;
      }
      case "byte-order-mark":
      case "space":
        break;
      case "comment":
      case "newline":
        this.prelude.push(token.source);
        break;
      case "error": {
        const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message;
        const error2 = new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg);
        if (this.atDirectives || !this.doc)
          this.errors.push(error2);
        else
          this.doc.errors.push(error2);
        break;
      }
      case "doc-end": {
        if (!this.doc) {
          const msg = "Unexpected doc-end without preceding document";
          this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg));
          break;
        }
        this.doc.directives.docEnd = true;
        const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
        this.decorate(this.doc, true);
        if (end.comment) {
          const dc = this.doc.comment;
          this.doc.comment = dc ? `${dc}
${end.comment}` : end.comment;
        }
        this.doc.range[2] = end.offset;
        break;
      }
      default:
        this.errors.push(new YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`));
    }
  }
  /**
   * Call at end of input to yield any remaining document.
   *
   * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
   * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.
   */
  *end(forceDoc = false, endOffset = -1) {
    if (this.doc) {
      this.decorate(this.doc, true);
      yield this.doc;
      this.doc = null;
    } else if (forceDoc) {
      const opts = Object.assign({ _directives: this.directives }, this.options);
      const doc = new Document(void 0, opts);
      if (this.atDirectives)
        this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
      doc.range = [0, endOffset, endOffset];
      this.decorate(doc, false);
      yield doc;
    }
  }
};
function resolveAsScalar(token, strict = true, onError2) {
  if (token) {
    const _onError = (pos, code, message) => {
      const offset2 = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset;
      if (onError2)
        onError2(offset2, code, message);
      else
        throw new YAMLParseError([offset2, offset2 + 1], code, message);
    };
    switch (token.type) {
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
        return resolveFlowScalar(token, strict, _onError);
      case "block-scalar":
        return resolveBlockScalar({ options: { strict } }, token, _onError);
    }
  }
  return null;
}
function createScalarToken(value2, context) {
  const { implicitKey = false, indent, inFlow = false, offset: offset2 = -1, type = "PLAIN" } = context;
  const source = stringifyString({ type, value: value2 }, {
    implicitKey,
    indent: indent > 0 ? " ".repeat(indent) : "",
    inFlow,
    options: { blockQuote: true, lineWidth: -1 }
  });
  const end = context.end ?? [
    { type: "newline", offset: -1, indent, source: "\n" }
  ];
  switch (source[0]) {
    case "|":
    case ">": {
      const he = source.indexOf("\n");
      const head = source.substring(0, he);
      const body = source.substring(he + 1) + "\n";
      const props = [
        { type: "block-scalar-header", offset: offset2, indent, source: head }
      ];
      if (!addEndtoBlockProps(props, end))
        props.push({ type: "newline", offset: -1, indent, source: "\n" });
      return { type: "block-scalar", offset: offset2, indent, props, source: body };
    }
    case '"':
      return { type: "double-quoted-scalar", offset: offset2, indent, source, end };
    case "'":
      return { type: "single-quoted-scalar", offset: offset2, indent, source, end };
    default:
      return { type: "scalar", offset: offset2, indent, source, end };
  }
}
function setScalarValue(token, value2, context = {}) {
  let { afterKey = false, implicitKey = false, inFlow = false, type } = context;
  let indent = "indent" in token ? token.indent : null;
  if (afterKey && typeof indent === "number")
    indent += 2;
  if (!type)
    switch (token.type) {
      case "single-quoted-scalar":
        type = "QUOTE_SINGLE";
        break;
      case "double-quoted-scalar":
        type = "QUOTE_DOUBLE";
        break;
      case "block-scalar": {
        const header = token.props[0];
        if (header.type !== "block-scalar-header")
          throw new Error("Invalid block scalar header");
        type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL";
        break;
      }
      default:
        type = "PLAIN";
    }
  const source = stringifyString({ type, value: value2 }, {
    implicitKey: implicitKey || indent === null,
    indent: indent !== null && indent > 0 ? " ".repeat(indent) : "",
    inFlow,
    options: { blockQuote: true, lineWidth: -1 }
  });
  switch (source[0]) {
    case "|":
    case ">":
      setBlockScalarValue(token, source);
      break;
    case '"':
      setFlowScalarValue(token, source, "double-quoted-scalar");
      break;
    case "'":
      setFlowScalarValue(token, source, "single-quoted-scalar");
      break;
    default:
      setFlowScalarValue(token, source, "scalar");
  }
}
function setBlockScalarValue(token, source) {
  const he = source.indexOf("\n");
  const head = source.substring(0, he);
  const body = source.substring(he + 1) + "\n";
  if (token.type === "block-scalar") {
    const header = token.props[0];
    if (header.type !== "block-scalar-header")
      throw new Error("Invalid block scalar header");
    header.source = head;
    token.source = body;
  } else {
    const { offset: offset2 } = token;
    const indent = "indent" in token ? token.indent : -1;
    const props = [
      { type: "block-scalar-header", offset: offset2, indent, source: head }
    ];
    if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0))
      props.push({ type: "newline", offset: -1, indent, source: "\n" });
    for (const key of Object.keys(token))
      if (key !== "type" && key !== "offset")
        delete token[key];
    Object.assign(token, { type: "block-scalar", indent, props, source: body });
  }
}
function addEndtoBlockProps(props, end) {
  if (end)
    for (const st of end)
      switch (st.type) {
        case "space":
        case "comment":
          props.push(st);
          break;
        case "newline":
          props.push(st);
          return true;
      }
  return false;
}
function setFlowScalarValue(token, source, type) {
  switch (token.type) {
    case "scalar":
    case "double-quoted-scalar":
    case "single-quoted-scalar":
      token.type = type;
      token.source = source;
      break;
    case "block-scalar": {
      const end = token.props.slice(1);
      let oa = source.length;
      if (token.props[0].type === "block-scalar-header")
        oa -= token.props[0].source.length;
      for (const tok of end)
        tok.offset += oa;
      delete token.props;
      Object.assign(token, { type, source, end });
      break;
    }
    case "block-map":
    case "block-seq": {
      const offset2 = token.offset + source.length;
      const nl = { type: "newline", offset: offset2, indent: token.indent, source: "\n" };
      delete token.items;
      Object.assign(token, { type, source, end: [nl] });
      break;
    }
    default: {
      const indent = "indent" in token ? token.indent : -1;
      const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : [];
      for (const key of Object.keys(token))
        if (key !== "type" && key !== "offset")
          delete token[key];
      Object.assign(token, { type, indent, source, end });
    }
  }
}
var stringify$1 = (cst2) => "type" in cst2 ? stringifyToken(cst2) : stringifyItem(cst2);
function stringifyToken(token) {
  switch (token.type) {
    case "block-scalar": {
      let res = "";
      for (const tok of token.props)
        res += stringifyToken(tok);
      return res + token.source;
    }
    case "block-map":
    case "block-seq": {
      let res = "";
      for (const item of token.items)
        res += stringifyItem(item);
      return res;
    }
    case "flow-collection": {
      let res = token.start.source;
      for (const item of token.items)
        res += stringifyItem(item);
      for (const st of token.end)
        res += st.source;
      return res;
    }
    case "document": {
      let res = stringifyItem(token);
      if (token.end)
        for (const st of token.end)
          res += st.source;
      return res;
    }
    default: {
      let res = token.source;
      if ("end" in token && token.end)
        for (const st of token.end)
          res += st.source;
      return res;
    }
  }
}
function stringifyItem({ start, key, sep: sep2, value: value2 }) {
  let res = "";
  for (const st of start)
    res += st.source;
  if (key)
    res += stringifyToken(key);
  if (sep2)
    for (const st of sep2)
      res += st.source;
  if (value2)
    res += stringifyToken(value2);
  return res;
}
var BREAK = Symbol("break visit");
var SKIP = Symbol("skip children");
var REMOVE = Symbol("remove item");
function visit(cst2, visitor) {
  if ("type" in cst2 && cst2.type === "document")
    cst2 = { start: cst2.start, value: cst2.value };
  _visit(Object.freeze([]), cst2, visitor);
}
visit.BREAK = BREAK;
visit.SKIP = SKIP;
visit.REMOVE = REMOVE;
visit.itemAtPath = (cst2, path3) => {
  let item = cst2;
  for (const [field, index] of path3) {
    const tok = item == null ? void 0 : item[field];
    if (tok && "items" in tok) {
      item = tok.items[index];
    } else
      return void 0;
  }
  return item;
};
visit.parentCollection = (cst2, path3) => {
  const parent = visit.itemAtPath(cst2, path3.slice(0, -1));
  const field = path3[path3.length - 1][0];
  const coll = parent == null ? void 0 : parent[field];
  if (coll && "items" in coll)
    return coll;
  throw new Error("Parent collection not found");
};
function _visit(path3, item, visitor) {
  let ctrl = visitor(item, path3);
  if (typeof ctrl === "symbol")
    return ctrl;
  for (const field of ["key", "value"]) {
    const token = item[field];
    if (token && "items" in token) {
      for (let i = 0; i < token.items.length; ++i) {
        const ci = _visit(Object.freeze(path3.concat([[field, i]])), token.items[i], visitor);
        if (typeof ci === "number")
          i = ci - 1;
        else if (ci === BREAK)
          return BREAK;
        else if (ci === REMOVE) {
          token.items.splice(i, 1);
          i -= 1;
        }
      }
      if (typeof ctrl === "function" && field === "key")
        ctrl = ctrl(item, path3);
    }
  }
  return typeof ctrl === "function" ? ctrl(item, path3) : ctrl;
}
var BOM = "\uFEFF";
var DOCUMENT = "";
var FLOW_END = "";
var SCALAR = "";
var isCollection = (token) => !!token && "items" in token;
var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar");
function prettyToken(token) {
  switch (token) {
    case BOM:
      return "";
    case DOCUMENT:
      return "";
    case FLOW_END:
      return "";
    case SCALAR:
      return "";
    default:
      return JSON.stringify(token);
  }
}
function tokenType(source) {
  switch (source) {
    case BOM:
      return "byte-order-mark";
    case DOCUMENT:
      return "doc-mode";
    case FLOW_END:
      return "flow-error-end";
    case SCALAR:
      return "scalar";
    case "---":
      return "doc-start";
    case "...":
      return "doc-end";
    case "":
    case "\n":
    case "\r\n":
      return "newline";
    case "-":
      return "seq-item-ind";
    case "?":
      return "explicit-key-ind";
    case ":":
      return "map-value-ind";
    case "{":
      return "flow-map-start";
    case "}":
      return "flow-map-end";
    case "[":
      return "flow-seq-start";
    case "]":
      return "flow-seq-end";
    case ",":
      return "comma";
  }
  switch (source[0]) {
    case " ":
    case "	":
      return "space";
    case "#":
      return "comment";
    case "%":
      return "directive-line";
    case "*":
      return "alias";
    case "&":
      return "anchor";
    case "!":
      return "tag";
    case "'":
      return "single-quoted-scalar";
    case '"':
      return "double-quoted-scalar";
    case "|":
    case ">":
      return "block-scalar-header";
  }
  return null;
}
var cst = {
  __proto__: null,
  BOM,
  DOCUMENT,
  FLOW_END,
  SCALAR,
  createScalarToken,
  isCollection,
  isScalar,
  prettyToken,
  resolveAsScalar,
  setScalarValue,
  stringify: stringify$1,
  tokenType,
  visit
};
function isEmpty(ch) {
  switch (ch) {
    case void 0:
    case " ":
    case "\n":
    case "\r":
    case "	":
      return true;
    default:
      return false;
  }
}
var hexDigits = new Set("0123456789ABCDEFabcdef");
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
var flowIndicatorChars = new Set(",[]{}");
var invalidAnchorChars = new Set(" ,[]{}\n\r	");
var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
var Lexer = class {
  constructor() {
    this.atEnd = false;
    this.blockScalarIndent = -1;
    this.blockScalarKeep = false;
    this.buffer = "";
    this.flowKey = false;
    this.flowLevel = 0;
    this.indentNext = 0;
    this.indentValue = 0;
    this.lineEndPos = null;
    this.next = null;
    this.pos = 0;
  }
  /**
   * Generate YAML tokens from the `source` string. If `incomplete`,
   * a part of the last line may be left as a buffer for the next call.
   *
   * @returns A generator of lexical tokens
   */
  *lex(source, incomplete = false) {
    if (source) {
      if (typeof source !== "string")
        throw TypeError("source is not a string");
      this.buffer = this.buffer ? this.buffer + source : source;
      this.lineEndPos = null;
    }
    this.atEnd = !incomplete;
    let next = this.next ?? "stream";
    while (next && (incomplete || this.hasChars(1)))
      next = yield* this.parseNext(next);
  }
  atLineEnd() {
    let i = this.pos;
    let ch = this.buffer[i];
    while (ch === " " || ch === "	")
      ch = this.buffer[++i];
    if (!ch || ch === "#" || ch === "\n")
      return true;
    if (ch === "\r")
      return this.buffer[i + 1] === "\n";
    return false;
  }
  charAt(n2) {
    return this.buffer[this.pos + n2];
  }
  continueScalar(offset2) {
    let ch = this.buffer[offset2];
    if (this.indentNext > 0) {
      let indent = 0;
      while (ch === " ")
        ch = this.buffer[++indent + offset2];
      if (ch === "\r") {
        const next = this.buffer[indent + offset2 + 1];
        if (next === "\n" || !next && !this.atEnd)
          return offset2 + indent + 1;
      }
      return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset2 + indent : -1;
    }
    if (ch === "-" || ch === ".") {
      const dt = this.buffer.substr(offset2, 3);
      if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset2 + 3]))
        return -1;
    }
    return offset2;
  }
  getLine() {
    let end = this.lineEndPos;
    if (typeof end !== "number" || end !== -1 && end < this.pos) {
      end = this.buffer.indexOf("\n", this.pos);
      this.lineEndPos = end;
    }
    if (end === -1)
      return this.atEnd ? this.buffer.substring(this.pos) : null;
    if (this.buffer[end - 1] === "\r")
      end -= 1;
    return this.buffer.substring(this.pos, end);
  }
  hasChars(n2) {
    return this.pos + n2 <= this.buffer.length;
  }
  setNext(state) {
    this.buffer = this.buffer.substring(this.pos);
    this.pos = 0;
    this.lineEndPos = null;
    this.next = state;
    return null;
  }
  peek(n2) {
    return this.buffer.substr(this.pos, n2);
  }
  *parseNext(next) {
    switch (next) {
      case "stream":
        return yield* this.parseStream();
      case "line-start":
        return yield* this.parseLineStart();
      case "block-start":
        return yield* this.parseBlockStart();
      case "doc":
        return yield* this.parseDocument();
      case "flow":
        return yield* this.parseFlowCollection();
      case "quoted-scalar":
        return yield* this.parseQuotedScalar();
      case "block-scalar":
        return yield* this.parseBlockScalar();
      case "plain-scalar":
        return yield* this.parsePlainScalar();
    }
  }
  *parseStream() {
    let line = this.getLine();
    if (line === null)
      return this.setNext("stream");
    if (line[0] === BOM) {
      yield* this.pushCount(1);
      line = line.substring(1);
    }
    if (line[0] === "%") {
      let dirEnd = line.length;
      let cs = line.indexOf("#");
      while (cs !== -1) {
        const ch = line[cs - 1];
        if (ch === " " || ch === "	") {
          dirEnd = cs - 1;
          break;
        } else {
          cs = line.indexOf("#", cs + 1);
        }
      }
      while (true) {
        const ch = line[dirEnd - 1];
        if (ch === " " || ch === "	")
          dirEnd -= 1;
        else
          break;
      }
      const n2 = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
      yield* this.pushCount(line.length - n2);
      this.pushNewline();
      return "stream";
    }
    if (this.atLineEnd()) {
      const sp = yield* this.pushSpaces(true);
      yield* this.pushCount(line.length - sp);
      yield* this.pushNewline();
      return "stream";
    }
    yield DOCUMENT;
    return yield* this.parseLineStart();
  }
  *parseLineStart() {
    const ch = this.charAt(0);
    if (!ch && !this.atEnd)
      return this.setNext("line-start");
    if (ch === "-" || ch === ".") {
      if (!this.atEnd && !this.hasChars(4))
        return this.setNext("line-start");
      const s = this.peek(3);
      if (s === "---" && isEmpty(this.charAt(3))) {
        yield* this.pushCount(3);
        this.indentValue = 0;
        this.indentNext = 0;
        return "doc";
      } else if (s === "..." && isEmpty(this.charAt(3))) {
        yield* this.pushCount(3);
        return "stream";
      }
    }
    this.indentValue = yield* this.pushSpaces(false);
    if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
      this.indentNext = this.indentValue;
    return yield* this.parseBlockStart();
  }
  *parseBlockStart() {
    const [ch0, ch1] = this.peek(2);
    if (!ch1 && !this.atEnd)
      return this.setNext("block-start");
    if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
      const n2 = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
      this.indentNext = this.indentValue + 1;
      this.indentValue += n2;
      return yield* this.parseBlockStart();
    }
    return "doc";
  }
  *parseDocument() {
    yield* this.pushSpaces(true);
    const line = this.getLine();
    if (line === null)
      return this.setNext("doc");
    let n2 = yield* this.pushIndicators();
    switch (line[n2]) {
      case "#":
        yield* this.pushCount(line.length - n2);
      case void 0:
        yield* this.pushNewline();
        return yield* this.parseLineStart();
      case "{":
      case "[":
        yield* this.pushCount(1);
        this.flowKey = false;
        this.flowLevel = 1;
        return "flow";
      case "}":
      case "]":
        yield* this.pushCount(1);
        return "doc";
      case "*":
        yield* this.pushUntil(isNotAnchorChar);
        return "doc";
      case '"':
      case "'":
        return yield* this.parseQuotedScalar();
      case "|":
      case ">":
        n2 += yield* this.parseBlockScalarHeader();
        n2 += yield* this.pushSpaces(true);
        yield* this.pushCount(line.length - n2);
        yield* this.pushNewline();
        return yield* this.parseBlockScalar();
      default:
        return yield* this.parsePlainScalar();
    }
  }
  *parseFlowCollection() {
    let nl, sp;
    let indent = -1;
    do {
      nl = yield* this.pushNewline();
      if (nl > 0) {
        sp = yield* this.pushSpaces(false);
        this.indentValue = indent = sp;
      } else {
        sp = 0;
      }
      sp += yield* this.pushSpaces(true);
    } while (nl + sp > 0);
    const line = this.getLine();
    if (line === null)
      return this.setNext("flow");
    if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
      const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
      if (!atFlowEndMarker) {
        this.flowLevel = 0;
        yield FLOW_END;
        return yield* this.parseLineStart();
      }
    }
    let n2 = 0;
    while (line[n2] === ",") {
      n2 += yield* this.pushCount(1);
      n2 += yield* this.pushSpaces(true);
      this.flowKey = false;
    }
    n2 += yield* this.pushIndicators();
    switch (line[n2]) {
      case void 0:
        return "flow";
      case "#":
        yield* this.pushCount(line.length - n2);
        return "flow";
      case "{":
      case "[":
        yield* this.pushCount(1);
        this.flowKey = false;
        this.flowLevel += 1;
        return "flow";
      case "}":
      case "]":
        yield* this.pushCount(1);
        this.flowKey = true;
        this.flowLevel -= 1;
        return this.flowLevel ? "flow" : "doc";
      case "*":
        yield* this.pushUntil(isNotAnchorChar);
        return "flow";
      case '"':
      case "'":
        this.flowKey = true;
        return yield* this.parseQuotedScalar();
      case ":": {
        const next = this.charAt(1);
        if (this.flowKey || isEmpty(next) || next === ",") {
          this.flowKey = false;
          yield* this.pushCount(1);
          yield* this.pushSpaces(true);
          return "flow";
        }
      }
      default:
        this.flowKey = false;
        return yield* this.parsePlainScalar();
    }
  }
  *parseQuotedScalar() {
    const quote3 = this.charAt(0);
    let end = this.buffer.indexOf(quote3, this.pos + 1);
    if (quote3 === "'") {
      while (end !== -1 && this.buffer[end + 1] === "'")
        end = this.buffer.indexOf("'", end + 2);
    } else {
      while (end !== -1) {
        let n2 = 0;
        while (this.buffer[end - 1 - n2] === "\\")
          n2 += 1;
        if (n2 % 2 === 0)
          break;
        end = this.buffer.indexOf('"', end + 1);
      }
    }
    const qb = this.buffer.substring(0, end);
    let nl = qb.indexOf("\n", this.pos);
    if (nl !== -1) {
      while (nl !== -1) {
        const cs = this.continueScalar(nl + 1);
        if (cs === -1)
          break;
        nl = qb.indexOf("\n", cs);
      }
      if (nl !== -1) {
        end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
      }
    }
    if (end === -1) {
      if (!this.atEnd)
        return this.setNext("quoted-scalar");
      end = this.buffer.length;
    }
    yield* this.pushToIndex(end + 1, false);
    return this.flowLevel ? "flow" : "doc";
  }
  *parseBlockScalarHeader() {
    this.blockScalarIndent = -1;
    this.blockScalarKeep = false;
    let i = this.pos;
    while (true) {
      const ch = this.buffer[++i];
      if (ch === "+")
        this.blockScalarKeep = true;
      else if (ch > "0" && ch <= "9")
        this.blockScalarIndent = Number(ch) - 1;
      else if (ch !== "-")
        break;
    }
    return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
  }
  *parseBlockScalar() {
    let nl = this.pos - 1;
    let indent = 0;
    let ch;
    loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) {
      switch (ch) {
        case " ":
          indent += 1;
          break;
        case "\n":
          nl = i2;
          indent = 0;
          break;
        case "\r": {
          const next = this.buffer[i2 + 1];
          if (!next && !this.atEnd)
            return this.setNext("block-scalar");
          if (next === "\n")
            break;
        }
        default:
          break loop;
      }
    }
    if (!ch && !this.atEnd)
      return this.setNext("block-scalar");
    if (indent >= this.indentNext) {
      if (this.blockScalarIndent === -1)
        this.indentNext = indent;
      else {
        this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
      }
      do {
        const cs = this.continueScalar(nl + 1);
        if (cs === -1)
          break;
        nl = this.buffer.indexOf("\n", cs);
      } while (nl !== -1);
      if (nl === -1) {
        if (!this.atEnd)
          return this.setNext("block-scalar");
        nl = this.buffer.length;
      }
    }
    let i = nl + 1;
    ch = this.buffer[i];
    while (ch === " ")
      ch = this.buffer[++i];
    if (ch === "	") {
      while (ch === "	" || ch === " " || ch === "\r" || ch === "\n")
        ch = this.buffer[++i];
      nl = i - 1;
    } else if (!this.blockScalarKeep) {
      do {
        let i2 = nl - 1;
        let ch2 = this.buffer[i2];
        if (ch2 === "\r")
          ch2 = this.buffer[--i2];
        const lastChar = i2;
        while (ch2 === " ")
          ch2 = this.buffer[--i2];
        if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar)
          nl = i2;
        else
          break;
      } while (true);
    }
    yield SCALAR;
    yield* this.pushToIndex(nl + 1, true);
    return yield* this.parseLineStart();
  }
  *parsePlainScalar() {
    const inFlow = this.flowLevel > 0;
    let end = this.pos - 1;
    let i = this.pos - 1;
    let ch;
    while (ch = this.buffer[++i]) {
      if (ch === ":") {
        const next = this.buffer[i + 1];
        if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
          break;
        end = i;
      } else if (isEmpty(ch)) {
        let next = this.buffer[i + 1];
        if (ch === "\r") {
          if (next === "\n") {
            i += 1;
            ch = "\n";
            next = this.buffer[i + 1];
          } else
            end = i;
        }
        if (next === "#" || inFlow && flowIndicatorChars.has(next))
          break;
        if (ch === "\n") {
          const cs = this.continueScalar(i + 1);
          if (cs === -1)
            break;
          i = Math.max(i, cs - 2);
        }
      } else {
        if (inFlow && flowIndicatorChars.has(ch))
          break;
        end = i;
      }
    }
    if (!ch && !this.atEnd)
      return this.setNext("plain-scalar");
    yield SCALAR;
    yield* this.pushToIndex(end + 1, true);
    return inFlow ? "flow" : "doc";
  }
  *pushCount(n2) {
    if (n2 > 0) {
      yield this.buffer.substr(this.pos, n2);
      this.pos += n2;
      return n2;
    }
    return 0;
  }
  *pushToIndex(i, allowEmpty) {
    const s = this.buffer.slice(this.pos, i);
    if (s) {
      yield s;
      this.pos += s.length;
      return s.length;
    } else if (allowEmpty)
      yield "";
    return 0;
  }
  *pushIndicators() {
    switch (this.charAt(0)) {
      case "!":
        return (yield* this.pushTag()) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
      case "&":
        return (yield* this.pushUntil(isNotAnchorChar)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
      case "-":
      case "?":
      case ":": {
        const inFlow = this.flowLevel > 0;
        const ch1 = this.charAt(1);
        if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
          if (!inFlow)
            this.indentNext = this.indentValue + 1;
          else if (this.flowKey)
            this.flowKey = false;
          return (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)) + (yield* this.pushIndicators());
        }
      }
    }
    return 0;
  }
  *pushTag() {
    if (this.charAt(1) === "<") {
      let i = this.pos + 2;
      let ch = this.buffer[i];
      while (!isEmpty(ch) && ch !== ">")
        ch = this.buffer[++i];
      return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
    } else {
      let i = this.pos + 1;
      let ch = this.buffer[i];
      while (ch) {
        if (tagChars.has(ch))
          ch = this.buffer[++i];
        else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
          ch = this.buffer[i += 3];
        } else
          break;
      }
      return yield* this.pushToIndex(i, false);
    }
  }
  *pushNewline() {
    const ch = this.buffer[this.pos];
    if (ch === "\n")
      return yield* this.pushCount(1);
    else if (ch === "\r" && this.charAt(1) === "\n")
      return yield* this.pushCount(2);
    else
      return 0;
  }
  *pushSpaces(allowTabs) {
    let i = this.pos - 1;
    let ch;
    do {
      ch = this.buffer[++i];
    } while (ch === " " || allowTabs && ch === "	");
    const n2 = i - this.pos;
    if (n2 > 0) {
      yield this.buffer.substr(this.pos, n2);
      this.pos = i;
    }
    return n2;
  }
  *pushUntil(test) {
    let i = this.pos;
    let ch = this.buffer[i];
    while (!test(ch))
      ch = this.buffer[++i];
    return yield* this.pushToIndex(i, false);
  }
};
var LineCounter = class {
  constructor() {
    this.lineStarts = [];
    this.addNewLine = (offset2) => this.lineStarts.push(offset2);
    this.linePos = (offset2) => {
      let low = 0;
      let high = this.lineStarts.length;
      while (low < high) {
        const mid = low + high >> 1;
        if (this.lineStarts[mid] < offset2)
          low = mid + 1;
        else
          high = mid;
      }
      if (this.lineStarts[low] === offset2)
        return { line: low + 1, col: 1 };
      if (low === 0)
        return { line: 0, col: offset2 };
      const start = this.lineStarts[low - 1];
      return { line: low, col: offset2 - start + 1 };
    };
  }
};
function includesToken(list, type) {
  for (let i = 0; i < list.length; ++i)
    if (list[i].type === type)
      return true;
  return false;
}
function findNonEmptyIndex(list) {
  for (let i = 0; i < list.length; ++i) {
    switch (list[i].type) {
      case "space":
      case "comment":
      case "newline":
        break;
      default:
        return i;
    }
  }
  return -1;
}
function isFlowToken(token) {
  switch (token == null ? void 0 : token.type) {
    case "alias":
    case "scalar":
    case "single-quoted-scalar":
    case "double-quoted-scalar":
    case "flow-collection":
      return true;
    default:
      return false;
  }
}
function getPrevProps(parent) {
  switch (parent.type) {
    case "document":
      return parent.start;
    case "block-map": {
      const it = parent.items[parent.items.length - 1];
      return it.sep ?? it.start;
    }
    case "block-seq":
      return parent.items[parent.items.length - 1].start;
    default:
      return [];
  }
}
function getFirstKeyStartProps(prev) {
  var _a4;
  if (prev.length === 0)
    return [];
  let i = prev.length;
  loop: while (--i >= 0) {
    switch (prev[i].type) {
      case "doc-start":
      case "explicit-key-ind":
      case "map-value-ind":
      case "seq-item-ind":
      case "newline":
        break loop;
    }
  }
  while (((_a4 = prev[++i]) == null ? void 0 : _a4.type) === "space") {
  }
  return prev.splice(i, prev.length);
}
function fixFlowSeqItems(fc) {
  if (fc.start.type === "flow-seq-start") {
    for (const it of fc.items) {
      if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) {
        if (it.key)
          it.value = it.key;
        delete it.key;
        if (isFlowToken(it.value)) {
          if (it.value.end)
            Array.prototype.push.apply(it.value.end, it.sep);
          else
            it.value.end = it.sep;
        } else
          Array.prototype.push.apply(it.start, it.sep);
        delete it.sep;
      }
    }
  }
}
var Parser = class {
  /**
   * @param onNewLine - If defined, called separately with the start position of
   *   each new line (in `parse()`, including the start of input).
   */
  constructor(onNewLine) {
    this.atNewLine = true;
    this.atScalar = false;
    this.indent = 0;
    this.offset = 0;
    this.onKeyLine = false;
    this.stack = [];
    this.source = "";
    this.type = "";
    this.lexer = new Lexer();
    this.onNewLine = onNewLine;
  }
  /**
   * Parse `source` as a YAML stream.
   * If `incomplete`, a part of the last line may be left as a buffer for the next call.
   *
   * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.
   *
   * @returns A generator of tokens representing each directive, document, and other structure.
   */
  *parse(source, incomplete = false) {
    if (this.onNewLine && this.offset === 0)
      this.onNewLine(0);
    for (const lexeme of this.lexer.lex(source, incomplete))
      yield* this.next(lexeme);
    if (!incomplete)
      yield* this.end();
  }
  /**
   * Advance the parser by the `source` of one lexical token.
   */
  *next(source) {
    this.source = source;
    if (this.atScalar) {
      this.atScalar = false;
      yield* this.step();
      this.offset += source.length;
      return;
    }
    const type = tokenType(source);
    if (!type) {
      const message = `Not a YAML token: ${source}`;
      yield* this.pop({ type: "error", offset: this.offset, message, source });
      this.offset += source.length;
    } else if (type === "scalar") {
      this.atNewLine = false;
      this.atScalar = true;
      this.type = "scalar";
    } else {
      this.type = type;
      yield* this.step();
      switch (type) {
        case "newline":
          this.atNewLine = true;
          this.indent = 0;
          if (this.onNewLine)
            this.onNewLine(this.offset + source.length);
          break;
        case "space":
          if (this.atNewLine && source[0] === " ")
            this.indent += source.length;
          break;
        case "explicit-key-ind":
        case "map-value-ind":
        case "seq-item-ind":
          if (this.atNewLine)
            this.indent += source.length;
          break;
        case "doc-mode":
        case "flow-error-end":
          return;
        default:
          this.atNewLine = false;
      }
      this.offset += source.length;
    }
  }
  /** Call at end of input to push out any remaining constructions */
  *end() {
    while (this.stack.length > 0)
      yield* this.pop();
  }
  get sourceToken() {
    const st = {
      type: this.type,
      offset: this.offset,
      indent: this.indent,
      source: this.source
    };
    return st;
  }
  *step() {
    const top = this.peek(1);
    if (this.type === "doc-end" && (!top || top.type !== "doc-end")) {
      while (this.stack.length > 0)
        yield* this.pop();
      this.stack.push({
        type: "doc-end",
        offset: this.offset,
        source: this.source
      });
      return;
    }
    if (!top)
      return yield* this.stream();
    switch (top.type) {
      case "document":
        return yield* this.document(top);
      case "alias":
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
        return yield* this.scalar(top);
      case "block-scalar":
        return yield* this.blockScalar(top);
      case "block-map":
        return yield* this.blockMap(top);
      case "block-seq":
        return yield* this.blockSequence(top);
      case "flow-collection":
        return yield* this.flowCollection(top);
      case "doc-end":
        return yield* this.documentEnd(top);
    }
    yield* this.pop();
  }
  peek(n2) {
    return this.stack[this.stack.length - n2];
  }
  *pop(error2) {
    const token = error2 ?? this.stack.pop();
    if (!token) {
      const message = "Tried to pop an empty stack";
      yield { type: "error", offset: this.offset, source: "", message };
    } else if (this.stack.length === 0) {
      yield token;
    } else {
      const top = this.peek(1);
      if (token.type === "block-scalar") {
        token.indent = "indent" in top ? top.indent : 0;
      } else if (token.type === "flow-collection" && top.type === "document") {
        token.indent = 0;
      }
      if (token.type === "flow-collection")
        fixFlowSeqItems(token);
      switch (top.type) {
        case "document":
          top.value = token;
          break;
        case "block-scalar":
          top.props.push(token);
          break;
        case "block-map": {
          const it = top.items[top.items.length - 1];
          if (it.value) {
            top.items.push({ start: [], key: token, sep: [] });
            this.onKeyLine = true;
            return;
          } else if (it.sep) {
            it.value = token;
          } else {
            Object.assign(it, { key: token, sep: [] });
            this.onKeyLine = !it.explicitKey;
            return;
          }
          break;
        }
        case "block-seq": {
          const it = top.items[top.items.length - 1];
          if (it.value)
            top.items.push({ start: [], value: token });
          else
            it.value = token;
          break;
        }
        case "flow-collection": {
          const it = top.items[top.items.length - 1];
          if (!it || it.value)
            top.items.push({ start: [], key: token, sep: [] });
          else if (it.sep)
            it.value = token;
          else
            Object.assign(it, { key: token, sep: [] });
          return;
        }
        default:
          yield* this.pop();
          yield* this.pop(token);
      }
      if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) {
        const last = token.items[token.items.length - 1];
        if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) {
          if (top.type === "document")
            top.end = last.start;
          else
            top.items.push({ start: last.start });
          token.items.splice(-1, 1);
        }
      }
    }
  }
  *stream() {
    switch (this.type) {
      case "directive-line":
        yield { type: "directive", offset: this.offset, source: this.source };
        return;
      case "byte-order-mark":
      case "space":
      case "comment":
      case "newline":
        yield this.sourceToken;
        return;
      case "doc-mode":
      case "doc-start": {
        const doc = {
          type: "document",
          offset: this.offset,
          start: []
        };
        if (this.type === "doc-start")
          doc.start.push(this.sourceToken);
        this.stack.push(doc);
        return;
      }
    }
    yield {
      type: "error",
      offset: this.offset,
      message: `Unexpected ${this.type} token in YAML stream`,
      source: this.source
    };
  }
  *document(doc) {
    if (doc.value)
      return yield* this.lineEnd(doc);
    switch (this.type) {
      case "doc-start": {
        if (findNonEmptyIndex(doc.start) !== -1) {
          yield* this.pop();
          yield* this.step();
        } else
          doc.start.push(this.sourceToken);
        return;
      }
      case "anchor":
      case "tag":
      case "space":
      case "comment":
      case "newline":
        doc.start.push(this.sourceToken);
        return;
    }
    const bv = this.startBlockValue(doc);
    if (bv)
      this.stack.push(bv);
    else {
      yield {
        type: "error",
        offset: this.offset,
        message: `Unexpected ${this.type} token in YAML document`,
        source: this.source
      };
    }
  }
  *scalar(scalar) {
    if (this.type === "map-value-ind") {
      const prev = getPrevProps(this.peek(2));
      const start = getFirstKeyStartProps(prev);
      let sep2;
      if (scalar.end) {
        sep2 = scalar.end;
        sep2.push(this.sourceToken);
        delete scalar.end;
      } else
        sep2 = [this.sourceToken];
      const map2 = {
        type: "block-map",
        offset: scalar.offset,
        indent: scalar.indent,
        items: [{ start, key: scalar, sep: sep2 }]
      };
      this.onKeyLine = true;
      this.stack[this.stack.length - 1] = map2;
    } else
      yield* this.lineEnd(scalar);
  }
  *blockScalar(scalar) {
    switch (this.type) {
      case "space":
      case "comment":
      case "newline":
        scalar.props.push(this.sourceToken);
        return;
      case "scalar":
        scalar.source = this.source;
        this.atNewLine = true;
        this.indent = 0;
        if (this.onNewLine) {
          let nl = this.source.indexOf("\n") + 1;
          while (nl !== 0) {
            this.onNewLine(this.offset + nl);
            nl = this.source.indexOf("\n", nl) + 1;
          }
        }
        yield* this.pop();
        break;
      default:
        yield* this.pop();
        yield* this.step();
    }
  }
  *blockMap(map2) {
    var _a4;
    const it = map2.items[map2.items.length - 1];
    switch (this.type) {
      case "newline":
        this.onKeyLine = false;
        if (it.value) {
          const end = "end" in it.value ? it.value.end : void 0;
          const last = Array.isArray(end) ? end[end.length - 1] : void 0;
          if ((last == null ? void 0 : last.type) === "comment")
            end == null ? void 0 : end.push(this.sourceToken);
          else
            map2.items.push({ start: [this.sourceToken] });
        } else if (it.sep) {
          it.sep.push(this.sourceToken);
        } else {
          it.start.push(this.sourceToken);
        }
        return;
      case "space":
      case "comment":
        if (it.value) {
          map2.items.push({ start: [this.sourceToken] });
        } else if (it.sep) {
          it.sep.push(this.sourceToken);
        } else {
          if (this.atIndentedComment(it.start, map2.indent)) {
            const prev = map2.items[map2.items.length - 2];
            const end = (_a4 = prev == null ? void 0 : prev.value) == null ? void 0 : _a4.end;
            if (Array.isArray(end)) {
              Array.prototype.push.apply(end, it.start);
              end.push(this.sourceToken);
              map2.items.pop();
              return;
            }
          }
          it.start.push(this.sourceToken);
        }
        return;
    }
    if (this.indent >= map2.indent) {
      const atMapIndent = !this.onKeyLine && this.indent === map2.indent;
      const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind";
      let start = [];
      if (atNextItem && it.sep && !it.value) {
        const nl = [];
        for (let i = 0; i < it.sep.length; ++i) {
          const st = it.sep[i];
          switch (st.type) {
            case "newline":
              nl.push(i);
              break;
            case "space":
              break;
            case "comment":
              if (st.indent > map2.indent)
                nl.length = 0;
              break;
            default:
              nl.length = 0;
          }
        }
        if (nl.length >= 2)
          start = it.sep.splice(nl[1]);
      }
      switch (this.type) {
        case "anchor":
        case "tag":
          if (atNextItem || it.value) {
            start.push(this.sourceToken);
            map2.items.push({ start });
            this.onKeyLine = true;
          } else if (it.sep) {
            it.sep.push(this.sourceToken);
          } else {
            it.start.push(this.sourceToken);
          }
          return;
        case "explicit-key-ind":
          if (!it.sep && !it.explicitKey) {
            it.start.push(this.sourceToken);
            it.explicitKey = true;
          } else if (atNextItem || it.value) {
            start.push(this.sourceToken);
            map2.items.push({ start, explicitKey: true });
          } else {
            this.stack.push({
              type: "block-map",
              offset: this.offset,
              indent: this.indent,
              items: [{ start: [this.sourceToken], explicitKey: true }]
            });
          }
          this.onKeyLine = true;
          return;
        case "map-value-ind":
          if (it.explicitKey) {
            if (!it.sep) {
              if (includesToken(it.start, "newline")) {
                Object.assign(it, { key: null, sep: [this.sourceToken] });
              } else {
                const start2 = getFirstKeyStartProps(it.start);
                this.stack.push({
                  type: "block-map",
                  offset: this.offset,
                  indent: this.indent,
                  items: [{ start: start2, key: null, sep: [this.sourceToken] }]
                });
              }
            } else if (it.value) {
              map2.items.push({ start: [], key: null, sep: [this.sourceToken] });
            } else if (includesToken(it.sep, "map-value-ind")) {
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start, key: null, sep: [this.sourceToken] }]
              });
            } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
              const start2 = getFirstKeyStartProps(it.start);
              const key = it.key;
              const sep2 = it.sep;
              sep2.push(this.sourceToken);
              delete it.key, delete it.sep;
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start: start2, key, sep: sep2 }]
              });
            } else if (start.length > 0) {
              it.sep = it.sep.concat(start, this.sourceToken);
            } else {
              it.sep.push(this.sourceToken);
            }
          } else {
            if (!it.sep) {
              Object.assign(it, { key: null, sep: [this.sourceToken] });
            } else if (it.value || atNextItem) {
              map2.items.push({ start, key: null, sep: [this.sourceToken] });
            } else if (includesToken(it.sep, "map-value-ind")) {
              this.stack.push({
                type: "block-map",
                offset: this.offset,
                indent: this.indent,
                items: [{ start: [], key: null, sep: [this.sourceToken] }]
              });
            } else {
              it.sep.push(this.sourceToken);
            }
          }
          this.onKeyLine = true;
          return;
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar": {
          const fs2 = this.flowScalar(this.type);
          if (atNextItem || it.value) {
            map2.items.push({ start, key: fs2, sep: [] });
            this.onKeyLine = true;
          } else if (it.sep) {
            this.stack.push(fs2);
          } else {
            Object.assign(it, { key: fs2, sep: [] });
            this.onKeyLine = true;
          }
          return;
        }
        default: {
          const bv = this.startBlockValue(map2);
          if (bv) {
            if (atMapIndent && bv.type !== "block-seq") {
              map2.items.push({ start });
            }
            this.stack.push(bv);
            return;
          }
        }
      }
    }
    yield* this.pop();
    yield* this.step();
  }
  *blockSequence(seq2) {
    var _a4;
    const it = seq2.items[seq2.items.length - 1];
    switch (this.type) {
      case "newline":
        if (it.value) {
          const end = "end" in it.value ? it.value.end : void 0;
          const last = Array.isArray(end) ? end[end.length - 1] : void 0;
          if ((last == null ? void 0 : last.type) === "comment")
            end == null ? void 0 : end.push(this.sourceToken);
          else
            seq2.items.push({ start: [this.sourceToken] });
        } else
          it.start.push(this.sourceToken);
        return;
      case "space":
      case "comment":
        if (it.value)
          seq2.items.push({ start: [this.sourceToken] });
        else {
          if (this.atIndentedComment(it.start, seq2.indent)) {
            const prev = seq2.items[seq2.items.length - 2];
            const end = (_a4 = prev == null ? void 0 : prev.value) == null ? void 0 : _a4.end;
            if (Array.isArray(end)) {
              Array.prototype.push.apply(end, it.start);
              end.push(this.sourceToken);
              seq2.items.pop();
              return;
            }
          }
          it.start.push(this.sourceToken);
        }
        return;
      case "anchor":
      case "tag":
        if (it.value || this.indent <= seq2.indent)
          break;
        it.start.push(this.sourceToken);
        return;
      case "seq-item-ind":
        if (this.indent !== seq2.indent)
          break;
        if (it.value || includesToken(it.start, "seq-item-ind"))
          seq2.items.push({ start: [this.sourceToken] });
        else
          it.start.push(this.sourceToken);
        return;
    }
    if (this.indent > seq2.indent) {
      const bv = this.startBlockValue(seq2);
      if (bv) {
        this.stack.push(bv);
        return;
      }
    }
    yield* this.pop();
    yield* this.step();
  }
  *flowCollection(fc) {
    const it = fc.items[fc.items.length - 1];
    if (this.type === "flow-error-end") {
      let top;
      do {
        yield* this.pop();
        top = this.peek(1);
      } while (top && top.type === "flow-collection");
    } else if (fc.end.length === 0) {
      switch (this.type) {
        case "comma":
        case "explicit-key-ind":
          if (!it || it.sep)
            fc.items.push({ start: [this.sourceToken] });
          else
            it.start.push(this.sourceToken);
          return;
        case "map-value-ind":
          if (!it || it.value)
            fc.items.push({ start: [], key: null, sep: [this.sourceToken] });
          else if (it.sep)
            it.sep.push(this.sourceToken);
          else
            Object.assign(it, { key: null, sep: [this.sourceToken] });
          return;
        case "space":
        case "comment":
        case "newline":
        case "anchor":
        case "tag":
          if (!it || it.value)
            fc.items.push({ start: [this.sourceToken] });
          else if (it.sep)
            it.sep.push(this.sourceToken);
          else
            it.start.push(this.sourceToken);
          return;
        case "alias":
        case "scalar":
        case "single-quoted-scalar":
        case "double-quoted-scalar": {
          const fs2 = this.flowScalar(this.type);
          if (!it || it.value)
            fc.items.push({ start: [], key: fs2, sep: [] });
          else if (it.sep)
            this.stack.push(fs2);
          else
            Object.assign(it, { key: fs2, sep: [] });
          return;
        }
        case "flow-map-end":
        case "flow-seq-end":
          fc.end.push(this.sourceToken);
          return;
      }
      const bv = this.startBlockValue(fc);
      if (bv)
        this.stack.push(bv);
      else {
        yield* this.pop();
        yield* this.step();
      }
    } else {
      const parent = this.peek(2);
      if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) {
        yield* this.pop();
        yield* this.step();
      } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") {
        const prev = getPrevProps(parent);
        const start = getFirstKeyStartProps(prev);
        fixFlowSeqItems(fc);
        const sep2 = fc.end.splice(1, fc.end.length);
        sep2.push(this.sourceToken);
        const map2 = {
          type: "block-map",
          offset: fc.offset,
          indent: fc.indent,
          items: [{ start, key: fc, sep: sep2 }]
        };
        this.onKeyLine = true;
        this.stack[this.stack.length - 1] = map2;
      } else {
        yield* this.lineEnd(fc);
      }
    }
  }
  flowScalar(type) {
    if (this.onNewLine) {
      let nl = this.source.indexOf("\n") + 1;
      while (nl !== 0) {
        this.onNewLine(this.offset + nl);
        nl = this.source.indexOf("\n", nl) + 1;
      }
    }
    return {
      type,
      offset: this.offset,
      indent: this.indent,
      source: this.source
    };
  }
  startBlockValue(parent) {
    switch (this.type) {
      case "alias":
      case "scalar":
      case "single-quoted-scalar":
      case "double-quoted-scalar":
        return this.flowScalar(this.type);
      case "block-scalar-header":
        return {
          type: "block-scalar",
          offset: this.offset,
          indent: this.indent,
          props: [this.sourceToken],
          source: ""
        };
      case "flow-map-start":
      case "flow-seq-start":
        return {
          type: "flow-collection",
          offset: this.offset,
          indent: this.indent,
          start: this.sourceToken,
          items: [],
          end: []
        };
      case "seq-item-ind":
        return {
          type: "block-seq",
          offset: this.offset,
          indent: this.indent,
          items: [{ start: [this.sourceToken] }]
        };
      case "explicit-key-ind": {
        this.onKeyLine = true;
        const prev = getPrevProps(parent);
        const start = getFirstKeyStartProps(prev);
        start.push(this.sourceToken);
        return {
          type: "block-map",
          offset: this.offset,
          indent: this.indent,
          items: [{ start, explicitKey: true }]
        };
      }
      case "map-value-ind": {
        this.onKeyLine = true;
        const prev = getPrevProps(parent);
        const start = getFirstKeyStartProps(prev);
        return {
          type: "block-map",
          offset: this.offset,
          indent: this.indent,
          items: [{ start, key: null, sep: [this.sourceToken] }]
        };
      }
    }
    return null;
  }
  atIndentedComment(start, indent) {
    if (this.type !== "comment")
      return false;
    if (this.indent <= indent)
      return false;
    return start.every((st) => st.type === "newline" || st.type === "space");
  }
  *documentEnd(docEnd) {
    if (this.type !== "doc-mode") {
      if (docEnd.end)
        docEnd.end.push(this.sourceToken);
      else
        docEnd.end = [this.sourceToken];
      if (this.type === "newline")
        yield* this.pop();
    }
  }
  *lineEnd(token) {
    switch (this.type) {
      case "comma":
      case "doc-start":
      case "doc-end":
      case "flow-seq-end":
      case "flow-map-end":
      case "map-value-ind":
        yield* this.pop();
        yield* this.step();
        break;
      case "newline":
        this.onKeyLine = false;
      case "space":
      case "comment":
      default:
        if (token.end)
          token.end.push(this.sourceToken);
        else
          token.end = [this.sourceToken];
        if (this.type === "newline")
          yield* this.pop();
    }
  }
};
function parseOptions(options2) {
  const prettyErrors = options2.prettyErrors !== false;
  const lineCounter = options2.lineCounter || prettyErrors && new LineCounter() || null;
  return { lineCounter, prettyErrors };
}
function parseAllDocuments(source, options2 = {}) {
  const { lineCounter, prettyErrors } = parseOptions(options2);
  const parser = new Parser(lineCounter == null ? void 0 : lineCounter.addNewLine);
  const composer = new Composer(options2);
  const docs = Array.from(composer.compose(parser.parse(source)));
  if (prettyErrors && lineCounter)
    for (const doc of docs) {
      doc.errors.forEach(prettifyError(source, lineCounter));
      doc.warnings.forEach(prettifyError(source, lineCounter));
    }
  if (docs.length > 0)
    return docs;
  return Object.assign([], { empty: true }, composer.streamInfo());
}
function parseDocument(source, options2 = {}) {
  const { lineCounter, prettyErrors } = parseOptions(options2);
  const parser = new Parser(lineCounter == null ? void 0 : lineCounter.addNewLine);
  const composer = new Composer(options2);
  let doc = null;
  for (const _doc of composer.compose(parser.parse(source), true, source.length)) {
    if (!doc)
      doc = _doc;
    else if (doc.options.logLevel !== "silent") {
      doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
      break;
    }
  }
  if (prettyErrors && lineCounter) {
    doc.errors.forEach(prettifyError(source, lineCounter));
    doc.warnings.forEach(prettifyError(source, lineCounter));
  }
  return doc;
}
function parse$a(src2, reviver, options2) {
  let _reviver = void 0;
  if (typeof reviver === "function") {
    _reviver = reviver;
  } else if (options2 === void 0 && reviver && typeof reviver === "object") {
    options2 = reviver;
  }
  const doc = parseDocument(src2, options2);
  if (!doc)
    return null;
  doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning));
  if (doc.errors.length > 0) {
    if (doc.options.logLevel !== "silent")
      throw doc.errors[0];
    else
      doc.errors = [];
  }
  return doc.toJS(Object.assign({ reviver: _reviver }, options2));
}
function stringify(value2, replacer, options2) {
  let _replacer = null;
  if (typeof replacer === "function" || Array.isArray(replacer)) {
    _replacer = replacer;
  } else if (options2 === void 0 && replacer) {
    options2 = replacer;
  }
  if (typeof options2 === "string")
    options2 = options2.length;
  if (typeof options2 === "number") {
    const indent = Math.round(options2);
    options2 = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent };
  }
  if (value2 === void 0) {
    const { keepUndefined } = options2 ?? replacer ?? {};
    if (!keepUndefined)
      return void 0;
  }
  return new Document(value2, _replacer, options2).toString(options2);
}
var YAML = {
  __proto__: null,
  Alias,
  CST: cst,
  Composer,
  Document,
  Lexer,
  LineCounter,
  Pair,
  Parser,
  Scalar,
  Schema,
  YAMLError,
  YAMLMap,
  YAMLParseError,
  YAMLSeq,
  YAMLWarning,
  isAlias,
  isCollection: isCollection$1,
  isDocument,
  isMap,
  isNode: isNode$1,
  isPair,
  isScalar: isScalar$1,
  isSeq,
  parse: parse$a,
  parseAllDocuments,
  parseDocument,
  stringify,
  visit: visit$1,
  visitAsync
};
var browser$2 = {
  __proto__: null,
  Alias,
  CST: cst,
  Composer,
  Document,
  Lexer,
  LineCounter,
  Pair,
  Parser,
  Scalar,
  Schema,
  YAMLError,
  YAMLMap,
  YAMLParseError,
  YAMLSeq,
  YAMLWarning,
  default: YAML,
  isAlias,
  isCollection: isCollection$1,
  isDocument,
  isMap,
  isNode: isNode$1,
  isPair,
  isScalar: isScalar$1,
  isSeq,
  parse: parse$a,
  parseAllDocuments,
  parseDocument,
  stringify,
  visit: visit$1,
  visitAsync
};
var require$$3 = getAugmentedNamespace(browser$2);
var { createRequire, createRequireFromPath } = import_module.default;
function req$2(name2, rootFile) {
  const create = createRequire || createRequireFromPath;
  const require3 = create(rootFile);
  return require3(name2);
}
var req_1 = req$2;
var req$1 = req_1;
var options = (config2, file) => {
  if (config2.parser && typeof config2.parser === "string") {
    try {
      config2.parser = req$1(config2.parser, file);
    } catch (err2) {
      throw new Error(`Loading PostCSS Parser failed: ${err2.message}

(@${file})`);
    }
  }
  if (config2.syntax && typeof config2.syntax === "string") {
    try {
      config2.syntax = req$1(config2.syntax, file);
    } catch (err2) {
      throw new Error(`Loading PostCSS Syntax failed: ${err2.message}

(@${file})`);
    }
  }
  if (config2.stringifier && typeof config2.stringifier === "string") {
    try {
      config2.stringifier = req$1(config2.stringifier, file);
    } catch (err2) {
      throw new Error(`Loading PostCSS Stringifier failed: ${err2.message}

(@${file})`);
    }
  }
  if (config2.plugins) {
    delete config2.plugins;
  }
  return config2;
};
var options_1 = options;
var req = req_1;
var load = (plugin, options2, file) => {
  try {
    if (options2 === null || options2 === void 0 || Object.keys(options2).length === 0) {
      return req(plugin, file);
    } else {
      return req(plugin, file)(options2);
    }
  } catch (err2) {
    throw new Error(`Loading PostCSS Plugin failed: ${err2.message}

(@${file})`);
  }
};
var plugins = (config2, file) => {
  let plugins2 = [];
  if (Array.isArray(config2.plugins)) {
    plugins2 = config2.plugins.filter(Boolean);
  } else {
    plugins2 = Object.keys(config2.plugins).filter((plugin) => {
      return config2.plugins[plugin] !== false ? plugin : "";
    }).map((plugin) => {
      return load(plugin, config2.plugins[plugin], file);
    });
  }
  if (plugins2.length && plugins2.length > 0) {
    plugins2.forEach((plugin, i) => {
      if (plugin.default) {
        plugin = plugin.default;
      }
      if (plugin.postcss === true) {
        plugin = plugin();
      } else if (plugin.postcss) {
        plugin = plugin.postcss;
      }
      if (
        // eslint-disable-next-line
        !(typeof plugin === "object" && Array.isArray(plugin.plugins) || typeof plugin === "object" && plugin.postcssPlugin || typeof plugin === "function")
      ) {
        throw new TypeError(`Invalid PostCSS Plugin found at: plugins[${i}]

(@${file})`);
      }
    });
  }
  return plugins2;
};
var plugins_1 = plugins;
var resolve2 = import_path.default.resolve;
var url$4 = import_url.default;
var config$1 = src$2;
var yaml = require$$3;
var loadOptions = options_1;
var loadPlugins = plugins_1;
var interopRequireDefault = (obj) => obj && obj.__esModule ? obj : { default: obj };
var processResult = (ctx, result) => {
  const file = result.filepath || "";
  let config2 = interopRequireDefault(result.config).default || {};
  if (typeof config2 === "function") {
    config2 = config2(ctx);
  } else {
    config2 = Object.assign({}, config2, ctx);
  }
  if (!config2.plugins) {
    config2.plugins = [];
  }
  return {
    plugins: loadPlugins(config2, file),
    options: loadOptions(config2, file),
    file
  };
};
var createContext = (ctx) => {
  ctx = Object.assign({
    cwd: process.cwd(),
    env: "development"
  }, ctx);
  if (!ctx.env) {
    process.env.NODE_ENV = "development";
  }
  return ctx;
};
var importDefault = async (filepath) => {
  const module = await import(url$4.pathToFileURL(filepath).href);
  return module.default;
};
var addTypeScriptLoader = (options2 = {}, loader) => {
  const moduleName = "postcss";
  return {
    ...options2,
    searchPlaces: [
      ...options2.searchPlaces || [],
      "package.json",
      `.${moduleName}rc`,
      `.${moduleName}rc.json`,
      `.${moduleName}rc.yaml`,
      `.${moduleName}rc.yml`,
      `.${moduleName}rc.ts`,
      `.${moduleName}rc.cts`,
      `.${moduleName}rc.js`,
      `.${moduleName}rc.cjs`,
      `.${moduleName}rc.mjs`,
      `${moduleName}.config.ts`,
      `${moduleName}.config.cts`,
      `${moduleName}.config.js`,
      `${moduleName}.config.cjs`,
      `${moduleName}.config.mjs`
    ],
    loaders: {
      ...options2.loaders,
      ".yaml": (filepath, content) => yaml.parse(content),
      ".yml": (filepath, content) => yaml.parse(content),
      ".js": importDefault,
      ".cjs": importDefault,
      ".mjs": importDefault,
      ".ts": loader,
      ".cts": loader
    }
  };
};
var withTypeScriptLoader = (rcFunc) => {
  return (ctx, path3, options2) => {
    return rcFunc(ctx, path3, addTypeScriptLoader(options2, (configFile) => {
      let registerer = { enabled() {
      } };
      try {
        registerer = __require2("ts-node").register({
          // transpile to cjs even if compilerOptions.module in tsconfig is not Node16/NodeNext.
          moduleTypes: { "**/*.cts": "cjs" }
        });
        return __require2(configFile);
      } catch (err2) {
        if (err2.code === "MODULE_NOT_FOUND") {
          throw new Error(
            `'ts-node' is required for the TypeScript configuration files. Make sure it is installed
Error: ${err2.message}`
          );
        }
        throw err2;
      } finally {
        registerer.enabled(false);
      }
    }));
  };
};
var rc = withTypeScriptLoader((ctx, path3, options2) => {
  ctx = createContext(ctx);
  path3 = path3 ? resolve2(path3) : process.cwd();
  return config$1.lilconfig("postcss", options2).search(path3).then((result) => {
    if (!result) {
      throw new Error(`No PostCSS Config found in: ${path3}`);
    }
    return processResult(ctx, result);
  });
});
var src$1 = rc;
var postcssrc = getDefaultExportFromCjs(src$1);
var HashbangComment;
var Identifier;
var JSXIdentifier;
var JSXPunctuator;
var JSXString;
var JSXText;
var KeywordsWithExpressionAfter;
var KeywordsWithNoLineTerminatorAfter;
var LineTerminatorSequence;
var MultiLineComment;
var Newline;
var NumericLiteral;
var Punctuator;
var RegularExpressionLiteral;
var SingleLineComment;
var StringLiteral;
var Template;
var TokensNotPrecedingObjectLiteral;
var TokensPrecedingExpression;
var WhiteSpace;
RegularExpressionLiteral = /\/(?![*\/])(?:\[(?:[^\]\\\n\r\u2028\u2029]+|\\.)*\]|[^\/\\\n\r\u2028\u2029]+|\\.)*(\/[$_\u200C\u200D\p{ID_Continue}]*|\\)?/yu;
Punctuator = /--|\+\+|=>|\.{3}|\??\.(?!\d)|(?:&&|\|\||\?\?|[+\-%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2}|\/(?![\/*]))=?|[?~,:;[\](){}]/y;
Identifier = /(\x23?)(?=[$_\p{ID_Start}\\])(?:[$_\u200C\u200D\p{ID_Continue}]+|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+/yu;
StringLiteral = /(['"])(?:[^'"\\\n\r]+|(?!\1)['"]|\\(?:\r\n|[^]))*(\1)?/y;
NumericLiteral = /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[oO][0-7](?:_?[0-7])*|0[bB][01](?:_?[01])*)n?|0n|[1-9](?:_?\d)*n|(?:(?:0(?!\d)|0\d*[89]\d*|[1-9](?:_?\d)*)(?:\.(?:\d(?:_?\d)*)?)?|\.\d(?:_?\d)*)(?:[eE][+-]?\d(?:_?\d)*)?|0[0-7]+/y;
Template = /[`}](?:[^`\\$]+|\\[^]|\$(?!\{))*(`|\$\{)?/y;
WhiteSpace = /[\t\v\f\ufeff\p{Zs}]+/yu;
LineTerminatorSequence = /\r?\n|[\r\u2028\u2029]/y;
MultiLineComment = /\/\*(?:[^*]+|\*(?!\/))*(\*\/)?/y;
SingleLineComment = /\/\/.*/y;
HashbangComment = /^#!.*/;
JSXPunctuator = /[<>.:={}]|\/(?![\/*])/y;
JSXIdentifier = /[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}-]*/yu;
JSXString = /(['"])(?:[^'"]+|(?!\1)['"])*(\1)?/y;
JSXText = /[^<>{}]+/y;
TokensPrecedingExpression = /^(?:[\/+-]|\.{3}|\?(?:InterpolationIn(?:JSX|Template)|NoLineTerminatorHere|NonExpressionParenEnd|UnaryIncDec))?$|[{}([,;<>=*%&|^!~?:]$/;
TokensNotPrecedingObjectLiteral = /^(?:=>|[;\]){}]|else|\?(?:NoLineTerminatorHere|NonExpressionParenEnd))?$/;
KeywordsWithExpressionAfter = /^(?:await|case|default|delete|do|else|instanceof|new|return|throw|typeof|void|yield)$/;
KeywordsWithNoLineTerminatorAfter = /^(?:return|throw|yield)$/;
Newline = RegExp(LineTerminatorSequence.source);
var jsTokens_1 = function* (input, { jsx = false } = {}) {
  var braces2, firstCodePoint, isExpression, lastIndex, lastSignificantToken, length, match2, mode2, nextLastIndex, nextLastSignificantToken, parenNesting, postfixIncDec, punctuator, stack;
  ({ length } = input);
  lastIndex = 0;
  lastSignificantToken = "";
  stack = [
    { tag: "JS" }
  ];
  braces2 = [];
  parenNesting = 0;
  postfixIncDec = false;
  if (match2 = HashbangComment.exec(input)) {
    yield {
      type: "HashbangComment",
      value: match2[0]
    };
    lastIndex = match2[0].length;
  }
  while (lastIndex < length) {
    mode2 = stack[stack.length - 1];
    switch (mode2.tag) {
      case "JS":
      case "JSNonExpressionParen":
      case "InterpolationInTemplate":
      case "InterpolationInJSX":
        if (input[lastIndex] === "/" && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
          RegularExpressionLiteral.lastIndex = lastIndex;
          if (match2 = RegularExpressionLiteral.exec(input)) {
            lastIndex = RegularExpressionLiteral.lastIndex;
            lastSignificantToken = match2[0];
            postfixIncDec = true;
            yield {
              type: "RegularExpressionLiteral",
              value: match2[0],
              closed: match2[1] !== void 0 && match2[1] !== "\\"
            };
            continue;
          }
        }
        Punctuator.lastIndex = lastIndex;
        if (match2 = Punctuator.exec(input)) {
          punctuator = match2[0];
          nextLastIndex = Punctuator.lastIndex;
          nextLastSignificantToken = punctuator;
          switch (punctuator) {
            case "(":
              if (lastSignificantToken === "?NonExpressionParenKeyword") {
                stack.push({
                  tag: "JSNonExpressionParen",
                  nesting: parenNesting
                });
              }
              parenNesting++;
              postfixIncDec = false;
              break;
            case ")":
              parenNesting--;
              postfixIncDec = true;
              if (mode2.tag === "JSNonExpressionParen" && parenNesting === mode2.nesting) {
                stack.pop();
                nextLastSignificantToken = "?NonExpressionParenEnd";
                postfixIncDec = false;
              }
              break;
            case "{":
              Punctuator.lastIndex = 0;
              isExpression = !TokensNotPrecedingObjectLiteral.test(lastSignificantToken) && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken));
              braces2.push(isExpression);
              postfixIncDec = false;
              break;
            case "}":
              switch (mode2.tag) {
                case "InterpolationInTemplate":
                  if (braces2.length === mode2.nesting) {
                    Template.lastIndex = lastIndex;
                    match2 = Template.exec(input);
                    lastIndex = Template.lastIndex;
                    lastSignificantToken = match2[0];
                    if (match2[1] === "${") {
                      lastSignificantToken = "?InterpolationInTemplate";
                      postfixIncDec = false;
                      yield {
                        type: "TemplateMiddle",
                        value: match2[0]
                      };
                    } else {
                      stack.pop();
                      postfixIncDec = true;
                      yield {
                        type: "TemplateTail",
                        value: match2[0],
                        closed: match2[1] === "`"
                      };
                    }
                    continue;
                  }
                  break;
                case "InterpolationInJSX":
                  if (braces2.length === mode2.nesting) {
                    stack.pop();
                    lastIndex += 1;
                    lastSignificantToken = "}";
                    yield {
                      type: "JSXPunctuator",
                      value: "}"
                    };
                    continue;
                  }
              }
              postfixIncDec = braces2.pop();
              nextLastSignificantToken = postfixIncDec ? "?ExpressionBraceEnd" : "}";
              break;
            case "]":
              postfixIncDec = true;
              break;
            case "++":
            case "--":
              nextLastSignificantToken = postfixIncDec ? "?PostfixIncDec" : "?UnaryIncDec";
              break;
            case "<":
              if (jsx && (TokensPrecedingExpression.test(lastSignificantToken) || KeywordsWithExpressionAfter.test(lastSignificantToken))) {
                stack.push({ tag: "JSXTag" });
                lastIndex += 1;
                lastSignificantToken = "<";
                yield {
                  type: "JSXPunctuator",
                  value: punctuator
                };
                continue;
              }
              postfixIncDec = false;
              break;
            default:
              postfixIncDec = false;
          }
          lastIndex = nextLastIndex;
          lastSignificantToken = nextLastSignificantToken;
          yield {
            type: "Punctuator",
            value: punctuator
          };
          continue;
        }
        Identifier.lastIndex = lastIndex;
        if (match2 = Identifier.exec(input)) {
          lastIndex = Identifier.lastIndex;
          nextLastSignificantToken = match2[0];
          switch (match2[0]) {
            case "for":
            case "if":
            case "while":
            case "with":
              if (lastSignificantToken !== "." && lastSignificantToken !== "?.") {
                nextLastSignificantToken = "?NonExpressionParenKeyword";
              }
          }
          lastSignificantToken = nextLastSignificantToken;
          postfixIncDec = !KeywordsWithExpressionAfter.test(match2[0]);
          yield {
            type: match2[1] === "#" ? "PrivateIdentifier" : "IdentifierName",
            value: match2[0]
          };
          continue;
        }
        StringLiteral.lastIndex = lastIndex;
        if (match2 = StringLiteral.exec(input)) {
          lastIndex = StringLiteral.lastIndex;
          lastSignificantToken = match2[0];
          postfixIncDec = true;
          yield {
            type: "StringLiteral",
            value: match2[0],
            closed: match2[2] !== void 0
          };
          continue;
        }
        NumericLiteral.lastIndex = lastIndex;
        if (match2 = NumericLiteral.exec(input)) {
          lastIndex = NumericLiteral.lastIndex;
          lastSignificantToken = match2[0];
          postfixIncDec = true;
          yield {
            type: "NumericLiteral",
            value: match2[0]
          };
          continue;
        }
        Template.lastIndex = lastIndex;
        if (match2 = Template.exec(input)) {
          lastIndex = Template.lastIndex;
          lastSignificantToken = match2[0];
          if (match2[1] === "${") {
            lastSignificantToken = "?InterpolationInTemplate";
            stack.push({
              tag: "InterpolationInTemplate",
              nesting: braces2.length
            });
            postfixIncDec = false;
            yield {
              type: "TemplateHead",
              value: match2[0]
            };
          } else {
            postfixIncDec = true;
            yield {
              type: "NoSubstitutionTemplate",
              value: match2[0],
              closed: match2[1] === "`"
            };
          }
          continue;
        }
        break;
      case "JSXTag":
      case "JSXTagEnd":
        JSXPunctuator.lastIndex = lastIndex;
        if (match2 = JSXPunctuator.exec(input)) {
          lastIndex = JSXPunctuator.lastIndex;
          nextLastSignificantToken = match2[0];
          switch (match2[0]) {
            case "<":
              stack.push({ tag: "JSXTag" });
              break;
            case ">":
              stack.pop();
              if (lastSignificantToken === "/" || mode2.tag === "JSXTagEnd") {
                nextLastSignificantToken = "?JSX";
                postfixIncDec = true;
              } else {
                stack.push({ tag: "JSXChildren" });
              }
              break;
            case "{":
              stack.push({
                tag: "InterpolationInJSX",
                nesting: braces2.length
              });
              nextLastSignificantToken = "?InterpolationInJSX";
              postfixIncDec = false;
              break;
            case "/":
              if (lastSignificantToken === "<") {
                stack.pop();
                if (stack[stack.length - 1].tag === "JSXChildren") {
                  stack.pop();
                }
                stack.push({ tag: "JSXTagEnd" });
              }
          }
          lastSignificantToken = nextLastSignificantToken;
          yield {
            type: "JSXPunctuator",
            value: match2[0]
          };
          continue;
        }
        JSXIdentifier.lastIndex = lastIndex;
        if (match2 = JSXIdentifier.exec(input)) {
          lastIndex = JSXIdentifier.lastIndex;
          lastSignificantToken = match2[0];
          yield {
            type: "JSXIdentifier",
            value: match2[0]
          };
          continue;
        }
        JSXString.lastIndex = lastIndex;
        if (match2 = JSXString.exec(input)) {
          lastIndex = JSXString.lastIndex;
          lastSignificantToken = match2[0];
          yield {
            type: "JSXString",
            value: match2[0],
            closed: match2[2] !== void 0
          };
          continue;
        }
        break;
      case "JSXChildren":
        JSXText.lastIndex = lastIndex;
        if (match2 = JSXText.exec(input)) {
          lastIndex = JSXText.lastIndex;
          lastSignificantToken = match2[0];
          yield {
            type: "JSXText",
            value: match2[0]
          };
          continue;
        }
        switch (input[lastIndex]) {
          case "<":
            stack.push({ tag: "JSXTag" });
            lastIndex++;
            lastSignificantToken = "<";
            yield {
              type: "JSXPunctuator",
              value: "<"
            };
            continue;
          case "{":
            stack.push({
              tag: "InterpolationInJSX",
              nesting: braces2.length
            });
            lastIndex++;
            lastSignificantToken = "?InterpolationInJSX";
            postfixIncDec = false;
            yield {
              type: "JSXPunctuator",
              value: "{"
            };
            continue;
        }
    }
    WhiteSpace.lastIndex = lastIndex;
    if (match2 = WhiteSpace.exec(input)) {
      lastIndex = WhiteSpace.lastIndex;
      yield {
        type: "WhiteSpace",
        value: match2[0]
      };
      continue;
    }
    LineTerminatorSequence.lastIndex = lastIndex;
    if (match2 = LineTerminatorSequence.exec(input)) {
      lastIndex = LineTerminatorSequence.lastIndex;
      postfixIncDec = false;
      if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
        lastSignificantToken = "?NoLineTerminatorHere";
      }
      yield {
        type: "LineTerminatorSequence",
        value: match2[0]
      };
      continue;
    }
    MultiLineComment.lastIndex = lastIndex;
    if (match2 = MultiLineComment.exec(input)) {
      lastIndex = MultiLineComment.lastIndex;
      if (Newline.test(match2[0])) {
        postfixIncDec = false;
        if (KeywordsWithNoLineTerminatorAfter.test(lastSignificantToken)) {
          lastSignificantToken = "?NoLineTerminatorHere";
        }
      }
      yield {
        type: "MultiLineComment",
        value: match2[0],
        closed: match2[1] !== void 0
      };
      continue;
    }
    SingleLineComment.lastIndex = lastIndex;
    if (match2 = SingleLineComment.exec(input)) {
      lastIndex = SingleLineComment.lastIndex;
      postfixIncDec = false;
      yield {
        type: "SingleLineComment",
        value: match2[0]
      };
      continue;
    }
    firstCodePoint = String.fromCodePoint(input.codePointAt(lastIndex));
    lastIndex += firstCodePoint.length;
    lastSignificantToken = firstCodePoint;
    postfixIncDec = false;
    yield {
      type: mode2.tag.startsWith("JSX") ? "JSXInvalid" : "Invalid",
      value: firstCodePoint
    };
  }
  return void 0;
};
var jsTokens = getDefaultExportFromCjs(jsTokens_1);
function stripLiteralJsTokens(code, options2) {
  const FILL = " ";
  const FILL_COMMENT = " ";
  let result = "";
  const tokens = [];
  for (const token of jsTokens(code, { jsx: false })) {
    tokens.push(token);
    if (token.type === "SingleLineComment") {
      result += FILL_COMMENT.repeat(token.value.length);
      continue;
    }
    if (token.type === "MultiLineComment") {
      result += token.value.replace(/[^\n]/g, FILL_COMMENT);
      continue;
    }
    if (token.type === "StringLiteral") {
      if (!token.closed) {
        result += token.value;
        continue;
      }
      const body = token.value.slice(1, -1);
      {
        result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
        continue;
      }
    }
    if (token.type === "NoSubstitutionTemplate") {
      const body = token.value.slice(1, -1);
      {
        result += `\`${body.replace(/[^\n]/g, FILL)}\``;
        continue;
      }
    }
    if (token.type === "RegularExpressionLiteral") {
      const body = token.value;
      {
        result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
        continue;
      }
    }
    if (token.type === "TemplateHead") {
      const body = token.value.slice(1, -2);
      {
        result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
        continue;
      }
    }
    if (token.type === "TemplateTail") {
      const body = token.value.slice(0, -2);
      {
        result += `}${body.replace(/[^\n]/g, FILL)}\``;
        continue;
      }
    }
    if (token.type === "TemplateMiddle") {
      const body = token.value.slice(1, -2);
      {
        result += `}${body.replace(/[^\n]/g, FILL)}\${`;
        continue;
      }
    }
    result += token.value;
  }
  return {
    result,
    tokens
  };
}
function stripLiteral(code, options2) {
  return stripLiteralDetailed(code).result;
}
function stripLiteralDetailed(code, options2) {
  return stripLiteralJsTokens(code);
}
var main$1 = { exports: {} };
var name = "dotenv";
var version$1 = "16.4.5";
var description = "Loads environment variables from .env file";
var main = "lib/main.js";
var types = "lib/main.d.ts";
var exports = {
  ".": {
    types: "./lib/main.d.ts",
    require: "./lib/main.js",
    "default": "./lib/main.js"
  },
  "./config": "./config.js",
  "./config.js": "./config.js",
  "./lib/env-options": "./lib/env-options.js",
  "./lib/env-options.js": "./lib/env-options.js",
  "./lib/cli-options": "./lib/cli-options.js",
  "./lib/cli-options.js": "./lib/cli-options.js",
  "./package.json": "./package.json"
};
var scripts = {
  "dts-check": "tsc --project tests/types/tsconfig.json",
  lint: "standard",
  "lint-readme": "standard-markdown",
  pretest: "npm run lint && npm run dts-check",
  test: "tap tests/*.js --100 -Rspec",
  "test:coverage": "tap --coverage-report=lcov",
  prerelease: "npm test",
  release: "standard-version"
};
var repository = {
  type: "git",
  url: "git://github.com/motdotla/dotenv.git"
};
var funding = "https://dotenvx.com";
var keywords = [
  "dotenv",
  "env",
  ".env",
  "environment",
  "variables",
  "config",
  "settings"
];
var readmeFilename = "README.md";
var license = "BSD-2-Clause";
var devDependencies = {
  "@definitelytyped/dtslint": "^0.0.133",
  "@types/node": "^18.11.3",
  decache: "^4.6.1",
  sinon: "^14.0.1",
  standard: "^17.0.0",
  "standard-markdown": "^7.1.0",
  "standard-version": "^9.5.0",
  tap: "^16.3.0",
  tar: "^6.1.11",
  typescript: "^4.8.4"
};
var engines = {
  node: ">=12"
};
var browser$1 = {
  fs: false
};
var require$$4 = {
  name,
  version: version$1,
  description,
  main,
  types,
  exports,
  scripts,
  repository,
  funding,
  keywords,
  readmeFilename,
  license,
  devDependencies,
  engines,
  browser: browser$1
};
var fs$9 = import_fs.default;
var path$9 = import_path.default;
var os$2 = import_os.default;
var crypto$1 = import_crypto.default;
var packageJson = require$$4;
var version2 = packageJson.version;
var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
function parse$9(src2) {
  const obj = {};
  let lines = src2.toString();
  lines = lines.replace(/\r\n?/mg, "\n");
  let match2;
  while ((match2 = LINE.exec(lines)) != null) {
    const key = match2[1];
    let value2 = match2[2] || "";
    value2 = value2.trim();
    const maybeQuote = value2[0];
    value2 = value2.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
    if (maybeQuote === '"') {
      value2 = value2.replace(/\\n/g, "\n");
      value2 = value2.replace(/\\r/g, "\r");
    }
    obj[key] = value2;
  }
  return obj;
}
function _parseVault(options2) {
  const vaultPath = _vaultPath(options2);
  const result = DotenvModule.configDotenv({ path: vaultPath });
  if (!result.parsed) {
    const err2 = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
    err2.code = "MISSING_DATA";
    throw err2;
  }
  const keys = _dotenvKey(options2).split(",");
  const length = keys.length;
  let decrypted;
  for (let i = 0; i < length; i++) {
    try {
      const key = keys[i].trim();
      const attrs = _instructions(result, key);
      decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
      break;
    } catch (error2) {
      if (i + 1 >= length) {
        throw error2;
      }
    }
  }
  return DotenvModule.parse(decrypted);
}
function _log(message) {
  console.log(`[dotenv@${version2}][INFO] ${message}`);
}
function _warn(message) {
  console.log(`[dotenv@${version2}][WARN] ${message}`);
}
function _debug(message) {
  console.log(`[dotenv@${version2}][DEBUG] ${message}`);
}
function _dotenvKey(options2) {
  if (options2 && options2.DOTENV_KEY && options2.DOTENV_KEY.length > 0) {
    return options2.DOTENV_KEY;
  }
  if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
    return process.env.DOTENV_KEY;
  }
  return "";
}
function _instructions(result, dotenvKey) {
  let uri;
  try {
    uri = new URL(dotenvKey);
  } catch (error2) {
    if (error2.code === "ERR_INVALID_URL") {
      const err2 = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
      err2.code = "INVALID_DOTENV_KEY";
      throw err2;
    }
    throw error2;
  }
  const key = uri.password;
  if (!key) {
    const err2 = new Error("INVALID_DOTENV_KEY: Missing key part");
    err2.code = "INVALID_DOTENV_KEY";
    throw err2;
  }
  const environment = uri.searchParams.get("environment");
  if (!environment) {
    const err2 = new Error("INVALID_DOTENV_KEY: Missing environment part");
    err2.code = "INVALID_DOTENV_KEY";
    throw err2;
  }
  const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
  const ciphertext = result.parsed[environmentKey];
  if (!ciphertext) {
    const err2 = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
    err2.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
    throw err2;
  }
  return { ciphertext, key };
}
function _vaultPath(options2) {
  let possibleVaultPath = null;
  if (options2 && options2.path && options2.path.length > 0) {
    if (Array.isArray(options2.path)) {
      for (const filepath of options2.path) {
        if (fs$9.existsSync(filepath)) {
          possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
        }
      }
    } else {
      possibleVaultPath = options2.path.endsWith(".vault") ? options2.path : `${options2.path}.vault`;
    }
  } else {
    possibleVaultPath = path$9.resolve(process.cwd(), ".env.vault");
  }
  if (fs$9.existsSync(possibleVaultPath)) {
    return possibleVaultPath;
  }
  return null;
}
function _resolveHome(envPath) {
  return envPath[0] === "~" ? path$9.join(os$2.homedir(), envPath.slice(1)) : envPath;
}
function _configVault(options2) {
  _log("Loading env from encrypted .env.vault");
  const parsed = DotenvModule._parseVault(options2);
  let processEnv = process.env;
  if (options2 && options2.processEnv != null) {
    processEnv = options2.processEnv;
  }
  DotenvModule.populate(processEnv, parsed, options2);
  return { parsed };
}
function configDotenv(options2) {
  const dotenvPath = path$9.resolve(process.cwd(), ".env");
  let encoding = "utf8";
  const debug2 = Boolean(options2 && options2.debug);
  if (options2 && options2.encoding) {
    encoding = options2.encoding;
  } else {
    if (debug2) {
      _debug("No encoding is specified. UTF-8 is used by default");
    }
  }
  let optionPaths = [dotenvPath];
  if (options2 && options2.path) {
    if (!Array.isArray(options2.path)) {
      optionPaths = [_resolveHome(options2.path)];
    } else {
      optionPaths = [];
      for (const filepath of options2.path) {
        optionPaths.push(_resolveHome(filepath));
      }
    }
  }
  let lastError;
  const parsedAll = {};
  for (const path3 of optionPaths) {
    try {
      const parsed = DotenvModule.parse(fs$9.readFileSync(path3, { encoding }));
      DotenvModule.populate(parsedAll, parsed, options2);
    } catch (e2) {
      if (debug2) {
        _debug(`Failed to load ${path3} ${e2.message}`);
      }
      lastError = e2;
    }
  }
  let processEnv = process.env;
  if (options2 && options2.processEnv != null) {
    processEnv = options2.processEnv;
  }
  DotenvModule.populate(processEnv, parsedAll, options2);
  if (lastError) {
    return { parsed: parsedAll, error: lastError };
  } else {
    return { parsed: parsedAll };
  }
}
function config(options2) {
  if (_dotenvKey(options2).length === 0) {
    return DotenvModule.configDotenv(options2);
  }
  const vaultPath = _vaultPath(options2);
  if (!vaultPath) {
    _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
    return DotenvModule.configDotenv(options2);
  }
  return DotenvModule._configVault(options2);
}
function decrypt(encrypted, keyStr) {
  const key = Buffer.from(keyStr.slice(-64), "hex");
  let ciphertext = Buffer.from(encrypted, "base64");
  const nonce = ciphertext.subarray(0, 12);
  const authTag = ciphertext.subarray(-16);
  ciphertext = ciphertext.subarray(12, -16);
  try {
    const aesgcm = crypto$1.createDecipheriv("aes-256-gcm", key, nonce);
    aesgcm.setAuthTag(authTag);
    return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
  } catch (error2) {
    const isRange = error2 instanceof RangeError;
    const invalidKeyLength = error2.message === "Invalid key length";
    const decryptionFailed = error2.message === "Unsupported state or unable to authenticate data";
    if (isRange || invalidKeyLength) {
      const err2 = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
      err2.code = "INVALID_DOTENV_KEY";
      throw err2;
    } else if (decryptionFailed) {
      const err2 = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
      err2.code = "DECRYPTION_FAILED";
      throw err2;
    } else {
      throw error2;
    }
  }
}
function populate(processEnv, parsed, options2 = {}) {
  const debug2 = Boolean(options2 && options2.debug);
  const override = Boolean(options2 && options2.override);
  if (typeof parsed !== "object") {
    const err2 = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
    err2.code = "OBJECT_REQUIRED";
    throw err2;
  }
  for (const key of Object.keys(parsed)) {
    if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
      if (override === true) {
        processEnv[key] = parsed[key];
      }
      if (debug2) {
        if (override === true) {
          _debug(`"${key}" is already defined and WAS overwritten`);
        } else {
          _debug(`"${key}" is already defined and was NOT overwritten`);
        }
      }
    } else {
      processEnv[key] = parsed[key];
    }
  }
}
var DotenvModule = {
  configDotenv,
  _configVault,
  _parseVault,
  config,
  decrypt,
  parse: parse$9,
  populate
};
main$1.exports.configDotenv = DotenvModule.configDotenv;
main$1.exports._configVault = DotenvModule._configVault;
main$1.exports._parseVault = DotenvModule._parseVault;
main$1.exports.config = DotenvModule.config;
main$1.exports.decrypt = DotenvModule.decrypt;
var parse_1$1 = main$1.exports.parse = DotenvModule.parse;
main$1.exports.populate = DotenvModule.populate;
main$1.exports = DotenvModule;
var DOTENV_SUBSTITUTION_REGEX = /(\\)?(\$)(?!\()(\{?)([\w.]+)(?::?-((?:\$\{(?:\$\{(?:\$\{[^}]*\}|[^}])*}|[^}])*}|[^}])+))?(\}?)/gi;
function _resolveEscapeSequences(value2) {
  return value2.replace(/\\\$/g, "$");
}
function interpolate(value2, processEnv, parsed) {
  return value2.replace(DOTENV_SUBSTITUTION_REGEX, (match2, escaped2, dollarSign, openBrace, key, defaultValue, closeBrace) => {
    if (escaped2 === "\\") {
      return match2.slice(1);
    } else {
      if (processEnv[key]) {
        if (processEnv[key] === parsed[key]) {
          return processEnv[key];
        } else {
          return interpolate(processEnv[key], processEnv, parsed);
        }
      }
      if (parsed[key]) {
        if (parsed[key] === value2) {
          return parsed[key];
        } else {
          return interpolate(parsed[key], processEnv, parsed);
        }
      }
      if (defaultValue) {
        if (defaultValue.startsWith("$")) {
          return interpolate(defaultValue, processEnv, parsed);
        } else {
          return defaultValue;
        }
      }
      return "";
    }
  });
}
function expand(options2) {
  let processEnv = process.env;
  if (options2 && options2.processEnv != null) {
    processEnv = options2.processEnv;
  }
  for (const key in options2.parsed) {
    let value2 = options2.parsed[key];
    const inProcessEnv = Object.prototype.hasOwnProperty.call(processEnv, key);
    if (inProcessEnv) {
      if (processEnv[key] === options2.parsed[key]) {
        value2 = interpolate(value2, processEnv, options2.parsed);
      } else {
        value2 = processEnv[key];
      }
    } else {
      value2 = interpolate(value2, processEnv, options2.parsed);
    }
    options2.parsed[key] = _resolveEscapeSequences(value2);
  }
  for (const processKey in options2.parsed) {
    processEnv[processKey] = options2.parsed[processKey];
  }
  return options2;
}
var expand_1 = expand;
function getEnvFilesForMode(mode2, envDir) {
  return [
    /** default file */
    `.env`,
    /** local file */
    `.env.local`,
    /** mode file */
    `.env.${mode2}`,
    /** mode local file */
    `.env.${mode2}.local`
  ].map((file) => normalizePath$3(import_node_path3.default.join(envDir, file)));
}
function loadEnv(mode2, envDir, prefixes = "VITE_") {
  if (mode2 === "local") {
    throw new Error(
      `"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.`
    );
  }
  prefixes = arraify(prefixes);
  const env2 = {};
  const envFiles = getEnvFilesForMode(mode2, envDir);
  const parsed = Object.fromEntries(
    envFiles.flatMap((filePath) => {
      var _a4;
      if (!((_a4 = tryStatSync(filePath)) == null ? void 0 : _a4.isFile())) return [];
      return Object.entries(parse_1$1(import_node_fs2.default.readFileSync(filePath)));
    })
  );
  if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === void 0) {
    process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
  }
  if (parsed.BROWSER && process.env.BROWSER === void 0) {
    process.env.BROWSER = parsed.BROWSER;
  }
  if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === void 0) {
    process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
  }
  const processEnv = { ...process.env };
  expand_1({ parsed, processEnv });
  for (const [key, value2] of Object.entries(parsed)) {
    if (prefixes.some((prefix) => key.startsWith(prefix))) {
      env2[key] = value2;
    }
  }
  for (const key in process.env) {
    if (prefixes.some((prefix) => key.startsWith(prefix))) {
      env2[key] = process.env[key];
    }
  }
  return env2;
}
function resolveEnvPrefix({
  envPrefix = "VITE_"
}) {
  envPrefix = arraify(envPrefix);
  if (envPrefix.includes("")) {
    throw new Error(
      `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
    );
  }
  return envPrefix;
}
var modulePreloadPolyfillId = "vite/modulepreload-polyfill";
var resolvedModulePreloadPolyfillId = "\0" + modulePreloadPolyfillId + ".js";
function modulePreloadPolyfillPlugin(config2) {
  const skip = config2.command !== "build" || config2.build.ssr;
  let polyfillString;
  return {
    name: "vite:modulepreload-polyfill",
    resolveId(id) {
      if (id === modulePreloadPolyfillId) {
        return resolvedModulePreloadPolyfillId;
      }
    },
    load(id) {
      if (id === resolvedModulePreloadPolyfillId) {
        if (skip) {
          return "";
        }
        if (!polyfillString) {
          polyfillString = `${isModernFlag}&&(${polyfill.toString()}());`;
        }
        return { code: polyfillString, moduleSideEffects: true };
      }
    }
  };
}
function polyfill() {
  const relList = document.createElement("link").relList;
  if (relList && relList.supports && relList.supports("modulepreload")) {
    return;
  }
  for (const link of document.querySelectorAll('link[rel="modulepreload"]')) {
    processPreload(link);
  }
  new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type !== "childList") {
        continue;
      }
      for (const node2 of mutation.addedNodes) {
        if (node2.tagName === "LINK" && node2.rel === "modulepreload")
          processPreload(node2);
      }
    }
  }).observe(document, { childList: true, subtree: true });
  function getFetchOpts(link) {
    const fetchOpts = {};
    if (link.integrity) fetchOpts.integrity = link.integrity;
    if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
    if (link.crossOrigin === "use-credentials")
      fetchOpts.credentials = "include";
    else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
    else fetchOpts.credentials = "same-origin";
    return fetchOpts;
  }
  function processPreload(link) {
    if (link.ep)
      return;
    link.ep = true;
    const fetchOpts = getFetchOpts(link);
    fetch(link.href, fetchOpts);
  }
}
var htmlProxyRE$1 = /\?html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(js|css)$/;
var isHtmlProxyRE = /\?html-proxy\b/;
var inlineCSSRE$1 = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g;
var inlineImportRE = new RegExp(`(?]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is;
var moduleScriptRE = /[ \t]*]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i;
var modulePreloadLinkRE = /[ \t]*]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?\/>/i;
var importMapAppendRE = new RegExp(
  [moduleScriptRE, modulePreloadLinkRE].map((r2) => r2.source).join("|"),
  "i"
);
var isHTMLProxy = (id) => isHtmlProxyRE.test(id);
var isHTMLRequest = (request) => htmlLangRE.test(request);
var htmlProxyMap = /* @__PURE__ */ new WeakMap();
var htmlProxyResult = /* @__PURE__ */ new Map();
function htmlInlineProxyPlugin(config2) {
  htmlProxyMap.set(config2, /* @__PURE__ */ new Map());
  return {
    name: "vite:html-inline-proxy",
    resolveId(id) {
      if (isHTMLProxy(id)) {
        return id;
      }
    },
    load(id) {
      var _a4;
      const proxyMatch = id.match(htmlProxyRE$1);
      if (proxyMatch) {
        const index = Number(proxyMatch[1]);
        const file = cleanUrl(id);
        const url2 = file.replace(normalizePath$3(config2.root), "");
        const result = (_a4 = htmlProxyMap.get(config2).get(url2)) == null ? void 0 : _a4[index];
        if (result) {
          return result;
        } else {
          throw new Error(`No matching HTML proxy module found from ${id}`);
        }
      }
    }
  };
}
function addToHTMLProxyCache(config2, filePath, index, result) {
  if (!htmlProxyMap.get(config2)) {
    htmlProxyMap.set(config2, /* @__PURE__ */ new Map());
  }
  if (!htmlProxyMap.get(config2).get(filePath)) {
    htmlProxyMap.get(config2).set(filePath, []);
  }
  htmlProxyMap.get(config2).get(filePath)[index] = result;
}
function addToHTMLProxyTransformResult(hash2, code) {
  htmlProxyResult.set(hash2, code);
}
var assetAttrsConfig = {
  link: ["href"],
  video: ["src", "poster"],
  source: ["src", "srcset"],
  img: ["src", "srcset"],
  image: ["xlink:href", "href"],
  use: ["xlink:href", "href"]
};
var noInlineLinkRels = /* @__PURE__ */ new Set([
  "icon",
  "apple-touch-icon",
  "apple-touch-startup-image",
  "manifest"
]);
var isAsyncScriptMap = /* @__PURE__ */ new WeakMap();
function nodeIsElement(node2) {
  return node2.nodeName[0] !== "#";
}
function traverseNodes(node2, visitor) {
  visitor(node2);
  if (nodeIsElement(node2) || node2.nodeName === "#document" || node2.nodeName === "#document-fragment") {
    node2.childNodes.forEach((childNode) => traverseNodes(childNode, visitor));
  }
}
async function traverseHtml(html, filePath, visitor) {
  const { parse: parse4 } = await import("./dep-D-7KCb9p-QLXNKUUS.js");
  const ast = parse4(html, {
    scriptingEnabled: false,
    // parse inside