import { __name } from './chunk-IBAHCH6O.js';

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/core-D1daCTTE.js
var NOOP_EXTENSION = /* @__PURE__ */ __name(() => {
  return /* @__PURE__ */ Object.create(null);
}, "NOOP_EXTENSION");
function plugin(options = {}) {
  const { id, name, setup, onExtension, dependencies: dependencies2 } = options;
  const extension2 = options.extension || NOOP_EXTENSION;
  const pluginFn = /* @__PURE__ */ __name(async (ctx) => {
    if (setup) await setup(ctx);
  }, "pluginFn");
  const props = {
    writable: false,
    enumerable: true,
    configurable: true
  };
  return Object.defineProperties(pluginFn, {
    id: {
      value: id,
      ...props
    },
    ...name && { name: {
      value: name,
      ...props
    } },
    ...dependencies2 && { dependencies: {
      value: dependencies2,
      ...props
    } },
    ...extension2 && { extension: {
      value: {
        key: Symbol(id),
        factory: extension2,
        onFactory: onExtension
      },
      ...props
    } }
  });
}
__name(plugin, "plugin");

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/constants-D_ixLD32.js
var ANONYMOUS_COMMAND_NAME = "(anonymous)";
var NOOP = /* @__PURE__ */ __name(() => {
}, "NOOP");
var CLI_OPTIONS_DEFAULT = {
  name: void 0,
  description: void 0,
  version: void 0,
  cwd: void 0,
  usageSilent: false,
  subCommands: void 0,
  leftMargin: 2,
  middleMargin: 10,
  usageOptionType: false,
  usageOptionValue: true,
  renderHeader: void 0,
  renderUsage: void 0,
  renderValidationErrors: void 0,
  plugins: void 0,
  fallbackToEntry: false
};

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/utils-jNy8sqR5.js
function kebabnize(str) {
  return str.replace(/[A-Z]/g, (match, offset) => (offset > 0 ? "-" : "") + match.toLowerCase());
}
__name(kebabnize, "kebabnize");
function isLazyCommand(cmd) {
  return typeof cmd === "function" && "commandName" in cmd && !!cmd.commandName;
}
__name(isLazyCommand, "isLazyCommand");
async function resolveLazyCommand(cmd, name, needRunResolving = false) {
  let command;
  if (isLazyCommand(cmd)) {
    const baseCommand = {
      name: cmd.commandName,
      description: cmd.description,
      args: cmd.args,
      examples: cmd.examples,
      internal: cmd.internal,
      entry: cmd.entry,
      subCommands: cmd.subCommands
    };
    if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
    command = Object.assign(create(), baseCommand);
    if (needRunResolving) {
      const loaded = await cmd();
      if (typeof loaded === "function") command.run = loaded;
      else if (typeof loaded === "object") {
        if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
        command.run = loaded.run;
        command.name = loaded.name;
        command.description = loaded.description;
        command.args = loaded.args;
        command.examples = loaded.examples;
        command.internal = loaded.internal;
        command.entry = loaded.entry;
        command.subCommands = loaded.subCommands || cmd.subCommands;
        if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
      } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
    }
  } else command = Object.assign(create(), cmd);
  if (command.name == null && name) command.name = name;
  return deepFreeze(command);
}
__name(resolveLazyCommand, "resolveLazyCommand");
function create(obj = null) {
  return Object.create(obj);
}
__name(create, "create");
function log(...args) {
  console.log(...args);
}
__name(log, "log");
function getCommandSubCommands(cmd) {
  const subCommands = isLazyCommand(cmd) ? cmd.subCommands : typeof cmd === "object" ? cmd.subCommands : void 0;
  if (!subCommands) return;
  if (subCommands instanceof Map) return subCommands.size > 0 ? subCommands : void 0;
  if (typeof subCommands === "object") {
    const entries = Object.entries(subCommands);
    if (entries.length === 0) return;
    const map = /* @__PURE__ */ new Map();
    for (const [name, cmd2] of entries) map.set(name, cmd2);
    return map;
  }
}
__name(getCommandSubCommands, "getCommandSubCommands");
function deepFreeze(obj, ignores = []) {
  if (obj === null || typeof obj !== "object") return obj;
  for (const key of Object.keys(obj)) {
    const value = obj[key];
    if (ignores.includes(key)) continue;
    if (typeof value === "object" && value !== null) deepFreeze(value, ignores);
  }
  return Object.freeze(obj);
}
__name(deepFreeze, "deepFreeze");

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/src-dTYUlEw_.js
var BUILD_IN_PREFIX_AND_KEY_SEPARATOR = `_:`;
var ARG_PREFIX_AND_KEY_SEPARATOR = `arg:`;
var COMMON_ARGS = {
  help: {
    type: "boolean",
    short: "h",
    description: "Display this help message"
  },
  version: {
    type: "boolean",
    short: "v",
    description: "Display this version"
  }
};
var NEGATABLE = "Negatable of";
var en_US_default = {
  COMMAND: "COMMAND",
  COMMANDS: "COMMANDS",
  SUBCOMMAND: "SUBCOMMAND",
  USAGE: "USAGE",
  ARGUMENTS: "ARGUMENTS",
  OPTIONS: "OPTIONS",
  EXAMPLES: "EXAMPLES",
  FORMORE: "For more info, run any command with the `--help` flag",
  NEGATABLE,
  DEFAULT: "default",
  CHOICES: "choices",
  help: "Display this help message",
  version: "Display this version"
};
function resolveBuiltInKey(key) {
  return `_:${key}`;
}
__name(resolveBuiltInKey, "resolveBuiltInKey");
function resolveArgKey(key, name) {
  return `${name ? `${name}:` : ""}arg:${key}`;
}
__name(resolveArgKey, "resolveArgKey");
function resolveKey(key, name) {
  return `${name ? `${name}:` : ""}${key}`;
}
__name(resolveKey, "resolveKey");
async function resolveExamples$1(ctx, examples) {
  return typeof examples === "string" ? examples : typeof examples === "function" ? await examples(ctx) : "";
}
__name(resolveExamples$1, "resolveExamples$1");
function namespacedId(id) {
  return `g:${id}`;
}
__name(namespacedId, "namespacedId");
function makeShortLongOptionPair(schema, name, toKebab) {
  let key = `--${toKebab || schema.toKebab ? kebabnize(name) : name}`;
  if (schema.short) key = `-${schema.short}, ${key}`;
  return key;
}
__name(makeShortLongOptionPair, "makeShortLongOptionPair");
function localizable(ctx, cmd, translate) {
  async function localize(key, values) {
    if (translate) return translate(key, values);
    if (key.startsWith(BUILD_IN_PREFIX_AND_KEY_SEPARATOR)) return en_US_default[key.slice(BUILD_IN_PREFIX_AND_KEY_SEPARATOR.length)] || key;
    const namaspacedArgKey = resolveKey(ARG_PREFIX_AND_KEY_SEPARATOR, ctx.name);
    if (key.startsWith(namaspacedArgKey)) {
      let argKey = key.slice(namaspacedArgKey.length);
      let negatable = false;
      if (argKey.startsWith("no-")) {
        argKey = argKey.slice(3);
        negatable = true;
      }
      const schema = ctx.args[argKey];
      if (!schema) return argKey;
      return negatable && schema.type === "boolean" && schema.negatable ? `${NEGATABLE} ${makeShortLongOptionPair(schema, argKey, ctx.toKebab)}` : schema.description || "";
    }
    if (key === resolveKey("description", ctx.name)) return "";
    else if (key === resolveKey("examples", ctx.name)) return await resolveExamples$1(ctx, cmd.examples);
    else return key;
  }
  __name(localize, "localize");
  return localize;
}
__name(localizable, "localizable");
function renderHeader(ctx) {
  const title = ctx.env.description || ctx.env.name || "";
  return Promise.resolve(title ? `${title} (${ctx.env.name || ""}${ctx.env.version ? ` v${ctx.env.version}` : ""})` : title);
}
__name(renderHeader, "renderHeader");
var pluginId = namespacedId("renderer");
var COMMON_ARGS_KEYS = Object.keys(COMMON_ARGS);
async function renderUsage(ctx) {
  const messages = [];
  if (ctx.callMode === "subCommand") {
    const description = await resolveDescription(ctx);
    if (description) messages.push(description, "");
  }
  messages.push(...await renderUsageSection(ctx), "");
  if (ctx.omitted && await hasCommands(ctx)) messages.push(...await renderCommandsSection(ctx), "");
  if (hasPositionalArgs(ctx.args)) messages.push(...await renderPositionalArgsSection(ctx), "");
  if (hasOptionalArgs(ctx.args)) messages.push(...await renderOptionalArgsSection(ctx), "");
  const examples = await renderExamplesSection(ctx);
  if (examples.length > 0) messages.push(...examples, "");
  return messages.join("\n");
}
__name(renderUsage, "renderUsage");
async function renderPositionalArgsSection(ctx) {
  const messages = [];
  messages.push(`${await ctx.extensions[pluginId].text(resolveBuiltInKey("ARGUMENTS"))}:`);
  messages.push(await generatePositionalArgsUsage(ctx));
  return messages;
}
__name(renderPositionalArgsSection, "renderPositionalArgsSection");
async function renderOptionalArgsSection(ctx) {
  const messages = [];
  messages.push(`${await ctx.extensions[pluginId].text(resolveBuiltInKey("OPTIONS"))}:`);
  messages.push(await generateOptionalArgsUsage(ctx, getOptionalArgsPairs(ctx)));
  return messages;
}
__name(renderOptionalArgsSection, "renderOptionalArgsSection");
async function renderExamplesSection(ctx) {
  const messages = [];
  const resolvedExamples = await resolveExamples(ctx);
  if (resolvedExamples) {
    const examples = resolvedExamples.split("\n").map((example) => example.padStart(ctx.env.leftMargin + example.length));
    messages.push(`${await ctx.extensions[pluginId].text(resolveBuiltInKey("EXAMPLES"))}:`, ...examples);
  }
  return messages;
}
__name(renderExamplesSection, "renderExamplesSection");
async function renderUsageSection(ctx) {
  const messages = [`${await ctx.extensions[pluginId].text(resolveBuiltInKey("USAGE"))}:`];
  const usageStr = await makeUsageSymbols(ctx);
  messages.push(usageStr.padStart(ctx.env.leftMargin + usageStr.length));
  return messages;
}
__name(renderUsageSection, "renderUsageSection");
async function makeUsageSymbols(ctx) {
  const messages = [await resolveEntry(ctx)];
  if (ctx.omitted) if (await hasCommands(ctx)) messages.push(` [${await ctx.extensions[pluginId].text(resolveBuiltInKey("COMMANDS"))}]`);
  else messages.push(`${ctx.callMode === "subCommand" ? ` ${await resolveSubCommand(ctx)}` : ""}`);
  else messages.push(`${ctx.callMode === "subCommand" ? ` ${await resolveSubCommand(ctx)}` : ""}`);
  const optionsSymbols = await generateOptionsSymbols(ctx, ctx.args);
  if (optionsSymbols) messages.push(" ", optionsSymbols);
  const positionalSymbols = generatePositionalSymbols(ctx.args);
  if (positionalSymbols) messages.push(" ", positionalSymbols);
  return messages.join("");
}
__name(makeUsageSymbols, "makeUsageSymbols");
async function renderCommandsSection(ctx) {
  const messages = [`${await ctx.extensions[pluginId].text(resolveBuiltInKey("COMMANDS"))}:`];
  const loadedCommands = await ctx.extensions?.[pluginId].loadCommands() || [];
  const commandMaxLength = Math.max(...loadedCommands.map((cmd) => (cmd.name || "").length));
  const commandsStr = await Promise.all(loadedCommands.map(async (cmd) => {
    const desc = cmd.description || "";
    const optionSymbol = await generateOptionsSymbols(ctx, ctx.args);
    const positionalSymbol = generatePositionalSymbols(ctx.args);
    const commandStr = await makeCommandSymbol(ctx, cmd);
    const symbolLength = desc.length > 0 ? commandMaxLength + optionSymbol.length + positionalSymbol.length : 0;
    const command = `${commandStr.padEnd(symbolLength + ctx.env.middleMargin)}${desc}`;
    return `${command.padStart(ctx.env.leftMargin + command.length)}`;
  }));
  messages.push(...commandsStr, "", `${await ctx.extensions[pluginId].text(resolveBuiltInKey("FORMORE"))}:`);
  const basePath = ctx.commandPath && ctx.commandPath.length > 0 ? `${ctx.env.name} ${ctx.commandPath.join(" ")}` : ctx.env.name;
  messages.push(...loadedCommands.map((cmd) => {
    let commandStr = cmd.entry ? "" : cmd.name || "";
    if (commandStr) commandStr += " ";
    const commandHelp = `${basePath} ${commandStr}--help`;
    return `${commandHelp.padStart(ctx.env.leftMargin + commandHelp.length)}`;
  }));
  return messages;
}
__name(renderCommandsSection, "renderCommandsSection");
async function makeCommandSymbol(ctx, cmd) {
  const optionSymbol = await generateOptionsSymbols(ctx, ctx.args);
  const positionalSymbol = generatePositionalSymbols(ctx.args);
  let commandStr = cmd.entry ? cmd.name === void 0 || cmd.name === "(anonymous)" ? "" : `[${cmd.name}]` : cmd.name || "";
  if (optionSymbol) {
    if (commandStr) commandStr += " ";
    commandStr += `${optionSymbol}`;
  }
  if (positionalSymbol) {
    if (commandStr) commandStr += " ";
    commandStr += `${positionalSymbol}`;
  }
  return commandStr;
}
__name(makeCommandSymbol, "makeCommandSymbol");
async function resolveEntry(ctx) {
  return ctx.env.name || await ctx.extensions[pluginId].text(resolveBuiltInKey("COMMAND"));
}
__name(resolveEntry, "resolveEntry");
async function resolveSubCommand(ctx) {
  if (ctx.commandPath && ctx.commandPath.length > 0) return ctx.commandPath.join(" ");
  return ctx.name || await ctx.extensions[pluginId].text(resolveBuiltInKey("SUBCOMMAND"));
}
__name(resolveSubCommand, "resolveSubCommand");
async function resolveDescription(ctx) {
  return await ctx.extensions[pluginId].text(resolveKey("description", ctx.name)) || ctx.description || "";
}
__name(resolveDescription, "resolveDescription");
async function resolveExamples(ctx) {
  const ret = await ctx.extensions[pluginId].text(resolveKey("examples", ctx.name));
  if (ret) return ret;
  const command = ctx.env.subCommands?.get(ctx.name || "");
  return await resolveExamples$1(ctx, command?.examples);
}
__name(resolveExamples, "resolveExamples");
async function hasCommands(ctx) {
  return (await ctx.extensions?.[pluginId].loadCommands() || []).length > 1;
}
__name(hasCommands, "hasCommands");
function hasOptionalArgs(args) {
  return Object.values(args).some((arg) => arg.type !== "positional");
}
__name(hasOptionalArgs, "hasOptionalArgs");
function hasPositionalArgs(args) {
  return Object.values(args).some((arg) => arg.type === "positional");
}
__name(hasPositionalArgs, "hasPositionalArgs");
function hasAllDefaultOptions(args) {
  return !!(args && Object.values(args).every((arg) => arg.default));
}
__name(hasAllDefaultOptions, "hasAllDefaultOptions");
async function generateOptionsSymbols(ctx, args) {
  return hasOptionalArgs(args) ? hasAllDefaultOptions(args) ? `[${await ctx.extensions[pluginId].text(resolveBuiltInKey("OPTIONS"))}]` : `<${await ctx.extensions[pluginId].text(resolveBuiltInKey("OPTIONS"))}>` : "";
}
__name(generateOptionsSymbols, "generateOptionsSymbols");
function getOptionalArgsPairs(ctx) {
  return Object.entries(ctx.args).reduce((acc, [name, schema]) => {
    if (schema.type === "positional") return acc;
    let key = makeShortLongOptionPair(schema, name, ctx.toKebab);
    if (schema.type !== "boolean") {
      const displayName = ctx.toKebab || schema.toKebab ? kebabnize(name) : name;
      key = schema.default ? `${key} [${displayName}]` : `${key} <${displayName}>`;
    }
    acc[name] = key;
    if (schema.type === "boolean" && schema.negatable && !COMMON_ARGS_KEYS.includes(name)) {
      const displayName = ctx.toKebab || schema.toKebab ? kebabnize(name) : name;
      acc[`no-${name}`] = `--no-${displayName}`;
    }
    return acc;
  }, /* @__PURE__ */ Object.create(null));
}
__name(getOptionalArgsPairs, "getOptionalArgsPairs");
var resolveNegatableKey = /* @__PURE__ */ __name((key) => key.split("no-")[1], "resolveNegatableKey");
function resolveNegatableType(key, ctx) {
  return ctx.args[key.startsWith("no-") ? resolveNegatableKey(key) : key].type;
}
__name(resolveNegatableType, "resolveNegatableType");
async function generateDefaultDisplayValue(ctx, schema) {
  return `${await ctx.extensions[pluginId].text(resolveBuiltInKey("DEFAULT"))}: ${schema.default}`;
}
__name(generateDefaultDisplayValue, "generateDefaultDisplayValue");
async function resolveDisplayValue(ctx, key) {
  if (COMMON_ARGS_KEYS.includes(key)) return "";
  const schema = ctx.args[key];
  if ((schema.type === "boolean" || schema.type === "number" || schema.type === "string" || schema.type === "custom") && schema.default !== void 0) return `(${await generateDefaultDisplayValue(ctx, schema)})`;
  if (schema.type === "enum") {
    const _default = schema.default === void 0 ? "" : await generateDefaultDisplayValue(ctx, schema);
    const choices = `${await ctx.extensions[pluginId].text(resolveBuiltInKey("CHOICES"))}: ${schema.choices.join(" | ")}`;
    return `(${_default ? `${_default}, ${choices}` : choices})`;
  }
  return "";
}
__name(resolveDisplayValue, "resolveDisplayValue");
async function generateOptionalArgsUsage(ctx, optionsPairs) {
  const optionsMaxLength = Math.max(...Object.entries(optionsPairs).map(([_, value]) => value.length));
  const optionSchemaMaxLength = ctx.env.usageOptionType ? Math.max(...Object.entries(optionsPairs).map(([key]) => resolveNegatableType(key, ctx).length)) : 0;
  return (await Promise.all(Object.entries(optionsPairs).map(async ([key, value]) => {
    let rawDesc = await ctx.extensions[pluginId].text(resolveArgKey(key, ctx.name));
    if (!rawDesc && key.startsWith("no-")) {
      const name = resolveNegatableKey(key);
      const schema = ctx.args[name];
      const optionKey = makeShortLongOptionPair(schema, name, ctx.toKebab);
      rawDesc = `${await ctx.extensions[pluginId].text(resolveBuiltInKey("NEGATABLE"))} ${optionKey}`;
    }
    const optionsSchema = ctx.env.usageOptionType ? `[${resolveNegatableType(key, ctx)}] ` : "";
    const valueDesc = key.startsWith("no-") ? "" : await resolveDisplayValue(ctx, key);
    const desc = `${optionsSchema ? optionsSchema.padEnd(optionSchemaMaxLength + 3) : ""}${rawDesc}`;
    const descLength = desc.length + valueDesc.length;
    const option = `${value.padEnd((descLength > 0 ? optionsMaxLength : 0) + ctx.env.middleMargin)}${desc}${valueDesc ? ` ${valueDesc}` : ""}`;
    return `${option.padStart(ctx.env.leftMargin + option.length)}`;
  }))).join("\n");
}
__name(generateOptionalArgsUsage, "generateOptionalArgsUsage");
function getPositionalArgs(args) {
  return Object.entries(args).filter(([_, schema]) => schema.type === "positional");
}
__name(getPositionalArgs, "getPositionalArgs");
async function generatePositionalArgsUsage(ctx) {
  const positionals = getPositionalArgs(ctx.args);
  const argsMaxLength = Math.max(...positionals.map(([name]) => name.length));
  return (await Promise.all(positionals.map(async ([name]) => {
    const desc = await ctx.extensions[pluginId].text(resolveArgKey(name, ctx.name)) || ctx.args[name].description || "";
    const arg = `${name.padEnd(argsMaxLength + ctx.env.middleMargin)} ${desc}`;
    return `${arg.padStart(ctx.env.leftMargin + arg.length)}`;
  }))).join("\n");
}
__name(generatePositionalArgsUsage, "generatePositionalArgsUsage");
function generatePositionalSymbols(args) {
  return hasPositionalArgs(args) ? getPositionalArgs(args).map(([name, arg]) => {
    const elements = [];
    if (!arg.multiple || arg.required) elements.push(`<${name}>`);
    if (arg.multiple) elements.push(`[<${name}> ...]`);
    return elements.join(" ");
  }).join(" ") : "";
}
__name(generatePositionalSymbols, "generatePositionalSymbols");
function renderValidationErrors(_ctx, error) {
  const messages = [];
  for (const err of error.errors) messages.push(err.message);
  return Promise.resolve(messages.join("\n"));
}
__name(renderValidationErrors, "renderValidationErrors");
var i18nPluginId = namespacedId("i18n");
var dependencies = [{
  id: i18nPluginId,
  optional: true
}];
function renderer() {
  return plugin({
    id: pluginId,
    name: "usage renderer",
    dependencies,
    extension: /* @__PURE__ */ __name((ctx, cmd) => {
      const i18n = ctx.extensions[i18nPluginId];
      let cachedCommands;
      async function loadCommands() {
        if (cachedCommands) return cachedCommands;
        const subCommands = [...ctx.env.subCommands || []];
        cachedCommands = (await Promise.all(subCommands.map(async ([name, cmd2]) => await resolveLazyCommand(cmd2, name)))).filter((cmd2) => !cmd2.internal).filter(Boolean);
        cachedCommands.sort((a, b) => {
          if (a.entry && !b.entry) return -1;
          if (!a.entry && b.entry) return 1;
          if (a.name && b.name) return a.name.localeCompare(b.name);
          if (a.name && !b.name) return -1;
          if (!a.name && b.name) return 1;
          return 0;
        });
        return cachedCommands;
      }
      __name(loadCommands, "loadCommands");
      return {
        text: localizable(ctx, cmd, i18n?.translate),
        loadCommands
      };
    }, "extension"),
    setup: /* @__PURE__ */ __name((ctx) => {
      ctx.decorateHeaderRenderer(async (_baseRenderer, cmdCtx) => await renderHeader(cmdCtx));
      ctx.decorateUsageRenderer(async (_baseRenderer, cmdCtx) => await renderUsage(cmdCtx));
      ctx.decorateValidationErrorsRenderer(async (_baseRenderer, cmdCtx, error) => await renderValidationErrors(cmdCtx, error));
    }, "setup")
  });
}
__name(renderer, "renderer");

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/context.js
async function createCommandContext({ args = {}, explicit = {}, values = {}, positionals = [], rest = [], argv = [], tokens = [], command = {}, extensions = {}, cliOptions = {}, callMode = "entry", commandPath = [], omitted = false, validationError }) {
  const _args = Object.entries(args).reduce((acc, [key, value]) => {
    acc[key] = Object.assign(create(), value);
    return acc;
  }, create());
  const env = Object.assign(create(), CLI_OPTIONS_DEFAULT, cliOptions);
  if (command.rendering) {
    const { header, usage, validationErrors } = command.rendering;
    if (header !== void 0) env.renderHeader = header;
    if (usage !== void 0) env.renderUsage = usage;
    if (validationErrors !== void 0) env.renderValidationErrors = validationErrors;
  }
  const core = Object.assign(create(), {
    name: getCommandName(command),
    description: command.description,
    omitted,
    callMode,
    commandPath,
    env,
    args: _args,
    explicit,
    values,
    positionals,
    rest,
    _: argv,
    tokens,
    toKebab: command.toKebab,
    log: cliOptions.usageSilent ? NOOP : log,
    validationError
  });
  if (Object.keys(extensions).length > 0) {
    const ext = create(null);
    Object.defineProperty(core, "extensions", {
      value: ext,
      writable: false,
      enumerable: true,
      configurable: true
    });
    for (const [key, extension2] of Object.entries(extensions)) {
      ext[key] = await extension2.factory(core, command);
      if (extension2.onFactory) await extension2.onFactory(core, command);
    }
  }
  return deepFreeze(core, ["extensions"]);
}
__name(createCommandContext, "createCommandContext");
function getCommandName(cmd) {
  if (isLazyCommand(cmd)) return cmd.commandName || cmd.name || "(anonymous)";
  else if (typeof cmd === "object") return cmd.name || "(anonymous)";
  else return ANONYMOUS_COMMAND_NAME;
}
__name(getCommandName, "getCommandName");

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/core-BKtZQ6dG.js
var HYPHEN_CHAR = "-";
var HYPHEN_CODE = HYPHEN_CHAR.codePointAt(0);
var EQUAL_CHAR = "=";
var EQUAL_CODE = EQUAL_CHAR.codePointAt(0);
var TERMINATOR = "--";
var SHORT_OPTION_PREFIX = HYPHEN_CHAR;
var LONG_OPTION_PREFIX = "--";
function parseArgs(args, options = {}) {
  const { allowCompatible = false } = options;
  const tokens = [];
  const remainings = [...args];
  let index = -1;
  let groupCount = 0;
  let hasShortValueSeparator = false;
  while (remainings.length > 0) {
    const arg = remainings.shift();
    if (arg == void 0) break;
    const nextArg = remainings[0];
    if (groupCount > 0) groupCount--;
    else index++;
    if (arg === TERMINATOR) {
      tokens.push({
        kind: "option-terminator",
        index
      });
      const mapped = remainings.map((arg2) => {
        return {
          kind: "positional",
          index: ++index,
          value: arg2
        };
      });
      tokens.push(...mapped);
      break;
    }
    if (isShortOption(arg)) {
      const shortOption = arg.charAt(1);
      let value;
      let inlineValue;
      if (groupCount) {
        tokens.push({
          kind: "option",
          name: shortOption,
          rawName: arg,
          index,
          value,
          inlineValue
        });
        if (groupCount === 1 && hasOptionValue(nextArg)) {
          value = remainings.shift();
          if (hasShortValueSeparator) {
            inlineValue = true;
            hasShortValueSeparator = false;
          }
          tokens.push({
            kind: "option",
            index,
            value,
            inlineValue
          });
        }
      } else tokens.push({
        kind: "option",
        name: shortOption,
        rawName: arg,
        index,
        value,
        inlineValue
      });
      if (value != null) ++index;
      continue;
    }
    if (isShortOptionGroup(arg)) {
      const expanded = [];
      let shortValue = "";
      for (let i = 1; i < arg.length; i++) {
        const shortableOption = arg.charAt(i);
        if (hasShortValueSeparator) shortValue += shortableOption;
        else if (!allowCompatible && shortableOption.codePointAt(0) === EQUAL_CODE) hasShortValueSeparator = true;
        else expanded.push(`${SHORT_OPTION_PREFIX}${shortableOption}`);
      }
      if (shortValue) expanded.push(shortValue);
      remainings.unshift(...expanded);
      groupCount = expanded.length;
      continue;
    }
    if (isLongOption(arg)) {
      const longOption = arg.slice(2);
      tokens.push({
        kind: "option",
        name: longOption,
        rawName: arg,
        index,
        value: void 0,
        inlineValue: void 0
      });
      continue;
    }
    if (isLongOptionAndValue(arg)) {
      const equalIndex = arg.indexOf(EQUAL_CHAR);
      const longOption = arg.slice(2, equalIndex);
      const value = arg.slice(equalIndex + 1);
      tokens.push({
        kind: "option",
        name: longOption,
        rawName: `${LONG_OPTION_PREFIX}${longOption}`,
        index,
        value,
        inlineValue: true
      });
      continue;
    }
    tokens.push({
      kind: "positional",
      index,
      value: arg
    });
  }
  return tokens;
}
__name(parseArgs, "parseArgs");
function isShortOption(arg) {
  return arg.length === 2 && arg.codePointAt(0) === HYPHEN_CODE && arg.codePointAt(1) !== HYPHEN_CODE;
}
__name(isShortOption, "isShortOption");
function isShortOptionGroup(arg) {
  if (arg.length <= 2) return false;
  if (arg.codePointAt(0) !== HYPHEN_CODE) return false;
  if (arg.codePointAt(1) === HYPHEN_CODE) return false;
  return true;
}
__name(isShortOptionGroup, "isShortOptionGroup");
function isLongOption(arg) {
  return hasLongOptionPrefix(arg) && !arg.includes(EQUAL_CHAR, 3);
}
__name(isLongOption, "isLongOption");
function isLongOptionAndValue(arg) {
  return hasLongOptionPrefix(arg) && arg.includes(EQUAL_CHAR, 3);
}
__name(isLongOptionAndValue, "isLongOptionAndValue");
function hasLongOptionPrefix(arg) {
  return arg.startsWith(LONG_OPTION_PREFIX) && arg.length > 2;
}
__name(hasLongOptionPrefix, "hasLongOptionPrefix");
function hasOptionValue(value) {
  return !(value == null) && value.codePointAt(0) !== HYPHEN_CODE;
}
__name(hasOptionValue, "hasOptionValue");
var SKIP_POSITIONAL_DEFAULT = -1;
function resolveArgs(args, tokens, { shortGrouping = false, skipPositional = SKIP_POSITIONAL_DEFAULT, toKebab = false } = {}) {
  const skipPositionalIndex = typeof skipPositional === "number" ? Math.max(skipPositional, SKIP_POSITIONAL_DEFAULT) : SKIP_POSITIONAL_DEFAULT;
  const rest = [];
  const optionTokens = [];
  const positionalTokens = [];
  let currentLongOption;
  let currentShortOption;
  const expandableShortOptions = [];
  function toShortValue() {
    if (expandableShortOptions.length === 0) return;
    else {
      const value = expandableShortOptions.map((token) => token.name).join("");
      expandableShortOptions.length = 0;
      return value;
    }
  }
  __name(toShortValue, "toShortValue");
  function applyLongOptionValue(value) {
    if (currentLongOption) {
      currentLongOption.value = value;
      optionTokens.push({ ...currentLongOption });
      currentLongOption = void 0;
    }
  }
  __name(applyLongOptionValue, "applyLongOptionValue");
  function applyShortOptionValue(value) {
    if (currentShortOption) {
      currentShortOption.value = value || toShortValue();
      optionTokens.push({ ...currentShortOption });
      currentShortOption = void 0;
    }
  }
  __name(applyShortOptionValue, "applyShortOptionValue");
  const schemas = Object.values(args);
  let terminated = false;
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    if (token.kind === "positional") {
      if (terminated && token.value) {
        rest.push(token.value);
        continue;
      }
      if (currentShortOption) if (schemas.find((schema) => schema.short === currentShortOption.name && schema.type === "boolean")) {
        positionalTokens.push({ ...token });
        applyShortOptionValue();
      } else applyShortOptionValue(token.value);
      else if (currentLongOption) if (args[currentLongOption.name]?.type === "boolean") {
        positionalTokens.push({ ...token });
        applyLongOptionValue();
      } else applyLongOptionValue(token.value);
      else positionalTokens.push({ ...token });
    } else if (token.kind === "option") if (token.rawName) {
      if (hasLongOptionPrefix(token.rawName)) {
        applyLongOptionValue();
        if (token.inlineValue) optionTokens.push({ ...token });
        else currentLongOption = { ...token };
        applyShortOptionValue();
      } else if (isShortOption(token.rawName)) if (currentShortOption) {
        if (currentShortOption.index === token.index) if (shortGrouping) {
          currentShortOption.value = token.value;
          optionTokens.push({ ...currentShortOption });
          currentShortOption = { ...token };
        } else expandableShortOptions.push({ ...token });
        else {
          currentShortOption.value = toShortValue();
          optionTokens.push({ ...currentShortOption });
          currentShortOption = { ...token };
        }
        applyLongOptionValue();
      } else {
        currentShortOption = { ...token };
        applyLongOptionValue();
      }
    } else {
      if (currentShortOption && currentShortOption.index == token.index && token.inlineValue) {
        currentShortOption.value = token.value;
        optionTokens.push({ ...currentShortOption });
        currentShortOption = void 0;
      }
      applyLongOptionValue();
    }
    else {
      if (token.kind === "option-terminator") terminated = true;
      applyLongOptionValue();
      applyShortOptionValue();
    }
  }
  applyLongOptionValue();
  applyShortOptionValue();
  const values = /* @__PURE__ */ Object.create(null);
  const errors = [];
  const explicit = /* @__PURE__ */ Object.create(null);
  const actualInputNames = /* @__PURE__ */ new Map();
  function checkTokenName(option, schema, token) {
    return token.name === (schema.type === "boolean" ? schema.negatable && token.name?.startsWith("no-") ? `no-${option}` : option : option);
  }
  __name(checkTokenName, "checkTokenName");
  const positionalItemCount = tokens.filter((token) => token.kind === "positional").length;
  function getPositionalSkipIndex() {
    return Math.min(skipPositionalIndex, positionalItemCount);
  }
  __name(getPositionalSkipIndex, "getPositionalSkipIndex");
  let positionalsCount = 0;
  for (const [rawArg, schema] of Object.entries(args)) {
    const arg = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
    explicit[rawArg] = false;
    if (schema.type === "positional") {
      if (skipPositionalIndex > SKIP_POSITIONAL_DEFAULT) while (positionalsCount <= getPositionalSkipIndex()) positionalsCount++;
      if (schema.multiple) {
        const remainingPositionals = positionalTokens.slice(positionalsCount);
        if (remainingPositionals.length > 0) {
          if (typeof schema.parse === "function") {
            const parsed = [];
            for (const p of remainingPositionals) try {
              parsed.push(schema.parse(p.value));
            } catch (error) {
              errors.push(error);
            }
            values[rawArg] = parsed;
          } else values[rawArg] = remainingPositionals.map((p) => p.value);
          positionalsCount += remainingPositionals.length;
          explicit[rawArg] = true;
        } else if (schema.required) errors.push(createRequireError(arg, schema));
      } else {
        const positional = positionalTokens[positionalsCount];
        if (positional != null) {
          if (typeof schema.parse === "function") try {
            values[rawArg] = schema.parse(positional.value);
          } catch (error) {
            errors.push(error);
          }
          else values[rawArg] = positional.value;
          explicit[rawArg] = true;
        } else errors.push(createRequireError(arg, schema));
        positionalsCount++;
      }
      continue;
    }
    if (schema.required) {
      if (!optionTokens.find((token) => {
        return schema.short && token.name === schema.short || token.rawName && hasLongOptionPrefix(token.rawName) && token.name === arg;
      })) {
        errors.push(createRequireError(arg, schema));
        continue;
      }
    }
    for (let i = 0; i < optionTokens.length; i++) {
      const token = optionTokens[i];
      if (checkTokenName(arg, schema, token) && token.rawName != void 0 && hasLongOptionPrefix(token.rawName) || schema.short === token.name && token.rawName != void 0 && isShortOption(token.rawName)) {
        const invalid = validateRequire(token, arg, schema);
        if (invalid) {
          errors.push(invalid);
          continue;
        }
        explicit[rawArg] = true;
        const actualInputName = isShortOption(token.rawName) ? `-${token.name}` : `--${arg}`;
        actualInputNames.set(rawArg, actualInputName);
        const [parsedValue, error] = parse(token, arg, schema);
        if (error) errors.push(error);
        else if (schema.multiple) {
          values[rawArg] ||= [];
          values[rawArg].push(parsedValue);
        } else values[rawArg] = parsedValue;
      }
    }
    if (values[rawArg] == null && schema.default != null) values[rawArg] = schema.default;
  }
  const conflictErrors = checkConflicts(args, explicit, toKebab, actualInputNames);
  errors.push(...conflictErrors);
  return {
    values,
    positionals: positionalTokens.map((token) => token.value),
    rest,
    error: errors.length > 0 ? new AggregateError(errors) : void 0,
    explicit
  };
}
__name(resolveArgs, "resolveArgs");
function parse(token, option, schema) {
  if (typeof schema.parse === "function") try {
    if (schema.type === "boolean") {
      const boolValue = !(schema.negatable && token.name.startsWith("no-"));
      return [schema.parse(String(boolValue)), void 0];
    }
    return [schema.parse(token.value ?? String(schema.default ?? "")), void 0];
  } catch (error) {
    return [void 0, error];
  }
  switch (schema.type) {
    case "string":
      return typeof token.value === "string" ? [token.value || schema.default, void 0] : [void 0, createTypeError(option, schema)];
    case "boolean":
      return [!(schema.negatable && token.name.startsWith("no-")), void 0];
    case "number":
      if (!isNumeric(token.value)) return [void 0, createTypeError(option, schema)];
      return token.value ? [+token.value, void 0] : [+(schema.default || ""), void 0];
    case "enum":
      if (schema.choices && !schema.choices.includes(token.value)) return [void 0, new ArgResolveError(`Optional argument '--${option}' ${schema.short ? `or '-${schema.short}' ` : ""}should be chosen from '${schema.type}' [${schema.choices.map((c) => JSON.stringify(c)).join(", ")}] values`, option, "type", schema)];
      return [token.value || schema.default, void 0];
    case "custom":
      throw new TypeError(`argument '${option}' should have a 'parse' function`);
    default:
      throw new Error(`Unsupported argument type '${schema.type}' for option '${option}'`);
  }
}
__name(parse, "parse");
function createRequireError(option, schema) {
  return new ArgResolveError(schema.type === "positional" ? `Positional argument '${option}' is required` : `Optional argument '--${option}' ${schema.short ? `or '-${schema.short}' ` : ""}is required`, option, "required", schema);
}
__name(createRequireError, "createRequireError");
var ArgResolveError = class extends Error {
  static {
    __name(this, "ArgResolveError");
  }
  name;
  schema;
  type;
  /**
  * Create an `ArgResolveError` instance.
  *
  * @param message - the error message
  * @param name - the name of the argument
  * @param type - the type of the error, either 'type' or 'required'
  * @param schema - the argument schema that caused the error
  */
  constructor(message, name, type, schema) {
    super(message);
    this.name = name;
    this.type = type;
    this.schema = schema;
  }
};
function validateRequire(token, option, schema) {
  if (schema.required && schema.type !== "boolean" && !token.value) return createRequireError(option, schema);
}
__name(validateRequire, "validateRequire");
function isNumeric(str) {
  return str.trim() !== "" && !isNaN(str);
}
__name(isNumeric, "isNumeric");
function createTypeError(option, schema) {
  return new ArgResolveError(`Optional argument '--${option}' ${schema.short ? `or '-${schema.short}' ` : ""}should be '${schema.type}'`, option, "type", schema);
}
__name(createTypeError, "createTypeError");
function checkConflicts(args, explicit, toKebab, actualInputNames) {
  for (const rawArg in args) {
    const schema = args[rawArg];
    if (!explicit[rawArg]) continue;
    if (!schema.conflicts) continue;
    const conflicts = Array.isArray(schema.conflicts) ? schema.conflicts : [schema.conflicts];
    for (let i = 0; i < conflicts.length; i++) {
      const conflictingArg = conflicts[i];
      if (!explicit[conflictingArg]) continue;
      const arg = toKebab || schema.toKebab ? kebabnize(rawArg) : rawArg;
      const conflictingArgKebab = toKebab || args[conflictingArg]?.toKebab ? kebabnize(conflictingArg) : conflictingArg;
      return [new ArgResolveError(`Optional argument '${actualInputNames.get(rawArg) || `--${arg}`}' conflicts with '${actualInputNames.get(conflictingArg) || `--${conflictingArgKebab}`}'`, rawArg, "conflict", schema)];
    }
  }
  return [];
}
__name(checkConflicts, "checkConflicts");
var EMPTY_RENDERER = /* @__PURE__ */ __name(() => Promise.resolve(""), "EMPTY_RENDERER");
function createDecorators() {
  const headerDecorators = [];
  const usageDecorators = [];
  const validationDecorators = [];
  const commandDecorators = [];
  function buildRenderer(decorators, defaultRenderer) {
    if (decorators.length === 0) return defaultRenderer;
    let renderer2 = defaultRenderer;
    for (const decorator2 of decorators) {
      const previousRenderer = renderer2;
      renderer2 = /* @__PURE__ */ __name((ctx) => decorator2(previousRenderer, ctx), "renderer");
    }
    return renderer2;
  }
  __name(buildRenderer, "buildRenderer");
  return Object.freeze({
    addHeaderDecorator(decorator2) {
      headerDecorators.push(decorator2);
    },
    addUsageDecorator(decorator2) {
      usageDecorators.push(decorator2);
    },
    addValidationErrorsDecorator(decorator2) {
      validationDecorators.push(decorator2);
    },
    addCommandDecorator(decorator2) {
      commandDecorators.push(decorator2);
    },
    get commandDecorators() {
      return [...commandDecorators];
    },
    getHeaderRenderer() {
      return buildRenderer(headerDecorators, EMPTY_RENDERER);
    },
    getUsageRenderer() {
      return buildRenderer(usageDecorators, EMPTY_RENDERER);
    },
    getValidationErrorsRenderer() {
      if (validationDecorators.length === 0) return EMPTY_RENDERER;
      let renderer2 = EMPTY_RENDERER;
      for (const decorator2 of validationDecorators) {
        const previousRenderer = renderer2;
        renderer2 = /* @__PURE__ */ __name((ctx, error) => decorator2(previousRenderer, ctx, error), "renderer");
      }
      return renderer2;
    }
  });
}
__name(createDecorators, "createDecorators");
function createPluginContext(decorators, initialSubCommands) {
  const globalOptions = /* @__PURE__ */ new Map();
  const subCommands = new Map(initialSubCommands || []);
  return Object.freeze({
    get globalOptions() {
      return new Map(globalOptions);
    },
    addGlobalOption(name, schema) {
      if (!name) throw new Error("Option name must be a non-empty string");
      if (globalOptions.has(name)) throw new Error(`Global option '${name}' is already registered`);
      globalOptions.set(name, schema);
    },
    get subCommands() {
      return new Map(subCommands);
    },
    addCommand(name, command) {
      if (!name) throw new Error("Command name must be a non-empty string");
      if (subCommands.has(name)) throw new Error(`Command '${name}' is already registered`);
      subCommands.set(name, command);
    },
    hasCommand(name) {
      return subCommands.has(name);
    },
    decorateHeaderRenderer(decorator2) {
      decorators.addHeaderDecorator(decorator2);
    },
    decorateUsageRenderer(decorator2) {
      decorators.addUsageDecorator(decorator2);
    },
    decorateValidationErrorsRenderer(decorator2) {
      decorators.addValidationErrorsDecorator(decorator2);
    },
    decorateCommand(decorator2) {
      decorators.addCommandDecorator(decorator2);
    }
  });
}
__name(createPluginContext, "createPluginContext");
function resolveDependencies(plugins) {
  const sorted = [];
  const visited = /* @__PURE__ */ new Set();
  const visiting = /* @__PURE__ */ new Set();
  const pluginMap = /* @__PURE__ */ new Map();
  for (const plugin2 of plugins) if (plugin2.id) {
    if (pluginMap.has(plugin2.id)) console.warn(`Duplicate plugin id detected: \`${plugin2.id}\``);
    pluginMap.set(plugin2.id, plugin2);
  }
  function visit(plugin2) {
    if (!plugin2.id) return;
    if (visited.has(plugin2.id)) return;
    if (visiting.has(plugin2.id)) throw new Error(`Circular dependency detected: \`${[...visiting].join(` -> `) + " -> " + plugin2.id}\``);
    visiting.add(plugin2.id);
    const deps = plugin2.dependencies || [];
    for (const dep of deps) {
      const depId = typeof dep === "string" ? dep : dep.id;
      const isOptional = typeof dep === "string" ? false : dep.optional || false;
      const depPlugin = pluginMap.get(depId);
      if (!depPlugin && !isOptional) throw new Error(`Missing required dependency: \`${depId}\` on \`${plugin2.id}\``);
      if (depPlugin) visit(depPlugin);
    }
    visiting.delete(plugin2.id);
    visited.add(plugin2.id);
    sorted.push(plugin2);
  }
  __name(visit, "visit");
  for (const plugin2 of plugins) visit(plugin2);
  return sorted;
}
__name(resolveDependencies, "resolveDependencies");
async function cliCore(argv, entry, options, plugins) {
  const decorators = createDecorators();
  const pluginContext = createPluginContext(decorators, createInitialSubCommands(options, entry));
  const resolvedPlugins = await applyPlugins(pluginContext, [...plugins, ...options.plugins || []]);
  const cliOptions = normalizeCliOptions(options, decorators, pluginContext);
  const tokens = parseArgs(argv);
  const resolved = resolveCommandTree(tokens, entry, cliOptions);
  const { commandName: name, command, callMode, commandPath, depth, levelSubCommands } = resolved;
  if (!command) throw new Error(`Command not found: ${name || ""}`);
  if (levelSubCommands) cliOptions.subCommands = levelSubCommands;
  const resolvedCommand = isLazyCommand(command) ? await resolveLazyCommand(command, name, true) : command;
  const args = resolveArguments(pluginContext, getCommandArgs(resolvedCommand));
  const skipPositional = depth > 0 ? depth - 1 : -1;
  const { explicit, values, positionals, rest, error } = resolveArgs(args, tokens, {
    shortGrouping: true,
    toKebab: resolvedCommand.toKebab,
    skipPositional
  });
  const omitted = resolved.omitted;
  return await executeCommand(resolvedCommand, await createCommandContext({
    args,
    explicit,
    values,
    positionals,
    rest,
    argv,
    tokens,
    omitted,
    callMode,
    commandPath,
    command: resolvedCommand,
    extensions: getPluginExtensions(resolvedPlugins),
    validationError: error,
    cliOptions
  }), decorators.commandDecorators);
}
__name(cliCore, "cliCore");
async function applyPlugins(pluginContext, plugins) {
  const sortedPlugins = resolveDependencies(plugins);
  try {
    for (const plugin2 of sortedPlugins)
      await plugin2(pluginContext);
  } catch (error) {
    console.error("Error loading plugin:", error.message);
  }
  return sortedPlugins;
}
__name(applyPlugins, "applyPlugins");
function getCommandArgs(cmd) {
  if (isLazyCommand(cmd)) return cmd.args || create();
  else if (typeof cmd === "object") return cmd.args || create();
  else return create();
}
__name(getCommandArgs, "getCommandArgs");
function resolveArguments(pluginContext, args) {
  return Object.assign(create(), Object.fromEntries(pluginContext.globalOptions), args);
}
__name(resolveArguments, "resolveArguments");
var isObject = /* @__PURE__ */ __name((val) => val !== null && typeof val === "object", "isObject");
function createInitialSubCommands(options, entryCmd) {
  const hasSubCommands = options.subCommands ? options.subCommands instanceof Map ? options.subCommands.size > 0 : isObject(options.subCommands) && Object.keys(options.subCommands).length > 0 : false;
  const subCommands = new Map(options.subCommands instanceof Map ? options.subCommands : []);
  if (!(options.subCommands instanceof Map) && isObject(options.subCommands)) for (const [name, cmd] of Object.entries(options.subCommands)) subCommands.set(name, cmd);
  if (hasSubCommands) {
    if (isLazyCommand(entryCmd)) {
      const entryCopy = Object.assign((...args) => entryCmd(...args), entryCmd, { entry: true });
      subCommands.set(resolveEntryName(entryCopy), entryCopy);
    } else if (typeof entryCmd === "object") {
      const entryCopy = Object.assign(create(), entryCmd, { entry: true });
      subCommands.set(resolveEntryName(entryCopy), entryCopy);
    } else if (typeof entryCmd === "function") {
      const name = entryCmd.name || "(anonymous)";
      subCommands.set(name, {
        run: entryCmd,
        name,
        entry: true
      });
    }
  }
  return subCommands;
}
__name(createInitialSubCommands, "createInitialSubCommands");
function normalizeCliOptions(options, decorators, pluginContext) {
  const subCommands = new Map(pluginContext.subCommands);
  const resolvedOptions = Object.assign(create(), CLI_OPTIONS_DEFAULT, options, { subCommands });
  if (resolvedOptions.renderHeader === void 0) resolvedOptions.renderHeader = decorators.getHeaderRenderer();
  if (resolvedOptions.renderUsage === void 0) resolvedOptions.renderUsage = decorators.getUsageRenderer();
  if (resolvedOptions.renderValidationErrors === void 0) resolvedOptions.renderValidationErrors = decorators.getValidationErrorsRenderer();
  return resolvedOptions;
}
__name(normalizeCliOptions, "normalizeCliOptions");
function getPositionalTokens(tokens) {
  return tokens.filter((t) => t.kind === "positional").map((t) => t.value).filter((v) => !!v);
}
__name(getPositionalTokens, "getPositionalTokens");
function resolveCommandTree(tokens, entry, options) {
  const positionals = getPositionalTokens(tokens);
  function resolveAsEntry() {
    if (typeof entry === "function") if ("commandName" in entry && entry.commandName) return {
      commandName: entry.commandName,
      command: entry,
      callMode: "entry",
      commandPath: [],
      depth: 0,
      omitted: options.subCommands.size > 0 && !positionals[0],
      levelSubCommands: options.subCommands.size > 0 ? options.subCommands : void 0
    };
    else return {
      command: {
        run: entry,
        entry: true
      },
      callMode: "entry",
      commandPath: [],
      depth: 0,
      omitted: options.subCommands.size > 0 && !positionals[0],
      levelSubCommands: options.subCommands.size > 0 ? options.subCommands : void 0
    };
    else if (typeof entry === "object") return {
      commandName: resolveEntryName(entry),
      command: entry,
      callMode: "entry",
      commandPath: [],
      depth: 0,
      omitted: options.subCommands.size > 0 && !positionals[0],
      levelSubCommands: options.subCommands.size > 0 ? options.subCommands : void 0
    };
    else return {
      callMode: "unexpected",
      commandPath: [],
      depth: 0,
      omitted: false,
      levelSubCommands: void 0
    };
  }
  __name(resolveAsEntry, "resolveAsEntry");
  if (positionals.length === 0 || options.subCommands.size === 0) return resolveAsEntry();
  let currentSubCommands = options.subCommands;
  let resolvedCommand;
  let resolvedName;
  const commandPath = [];
  let depth = 0;
  for (let i = 0; i < positionals.length; i++) {
    const token = positionals[i];
    const cmd = currentSubCommands.get(token);
    if (cmd == null) {
      if (depth === 0) {
        if (options.fallbackToEntry) return resolveAsEntry();
        return {
          commandName: token,
          callMode: "unexpected",
          commandPath: [],
          depth: 0,
          omitted: false,
          levelSubCommands: void 0
        };
      }
      break;
    }
    let resolved = cmd;
    if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName: token });
    else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name: token });
    resolvedCommand = resolved;
    resolvedName = token;
    commandPath.push(token);
    depth++;
    const nestedSubCommands = getCommandSubCommands(cmd);
    if (nestedSubCommands && nestedSubCommands.size > 0) currentSubCommands = nestedSubCommands;
    else break;
  }
  if (!resolvedCommand) return resolveAsEntry();
  const resolvedSubCommands = getCommandSubCommands(resolvedCommand);
  const omitted = resolvedSubCommands != null && resolvedSubCommands.size > 0;
  let levelSubCommands;
  if (omitted && resolvedSubCommands) {
    levelSubCommands = new Map(resolvedSubCommands);
    let entryCopy;
    if (typeof resolvedCommand === "function") entryCopy = Object.assign((...args) => resolvedCommand(...args), resolvedCommand, { entry: true });
    else entryCopy = Object.assign(create(), resolvedCommand, { entry: true });
    levelSubCommands.set(resolvedName || resolveEntryName(entryCopy), entryCopy);
  }
  return {
    commandName: resolvedName,
    command: resolvedCommand,
    callMode: depth > 0 ? "subCommand" : "entry",
    commandPath,
    depth,
    omitted,
    levelSubCommands
  };
}
__name(resolveCommandTree, "resolveCommandTree");
function resolveEntryName(entry) {
  return isLazyCommand(entry) ? entry.commandName || "(anonymous)" : entry.name || "(anonymous)";
}
__name(resolveEntryName, "resolveEntryName");
function getPluginExtensions(plugins) {
  const extensions = create();
  for (const plugin2 of plugins) if (plugin2.extension) {
    const key = plugin2.id;
    if (extensions[key]) console.warn(`Plugin "${key}" is already installed. Ignore it for command context extending.`);
    else extensions[key] = plugin2.extension;
  }
  return extensions;
}
__name(getPluginExtensions, "getPluginExtensions");
async function executeCommand(cmd, ctx, decorators) {
  const baseRunner = cmd.run || NOOP;
  const decoratedRunner = decorators.reduceRight((runner, decorator2) => decorator2(runner), baseRunner);
  try {
    if (ctx.env.onBeforeCommand) await ctx.env.onBeforeCommand(ctx);
    const result = await decoratedRunner(ctx);
    if (ctx.env.onAfterCommand) await ctx.env.onAfterCommand(ctx, result);
    return typeof result === "string" ? result : void 0;
  } catch (error) {
    if (ctx.env.onErrorCommand) try {
      await ctx.env.onErrorCommand(ctx, error);
    } catch (hookError) {
      console.error("Error in onErrorCommand hook:", hookError);
    }
    throw error;
  }
}
__name(executeCommand, "executeCommand");

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/cli-DfaFk6tk.js
var pluginId2 = namespacedId("global");
var decorator = /* @__PURE__ */ __name((baseRunner) => async (ctx) => {
  const { values, validationError, extensions: { [pluginId2]: { showVersion, showHeader, showUsage, showValidationErrors } } } = ctx;
  if (values.version) return showVersion();
  const buf = [];
  const header = await showHeader();
  if (header) buf.push(header);
  if (values.help) {
    const usage = await showUsage();
    if (usage) {
      buf.push(usage);
      return buf.join("\n");
    }
    return;
  }
  if (validationError) {
    await showValidationErrors(validationError);
    throw validationError;
  }
  return baseRunner(ctx);
}, "decorator");
function extension(ctx) {
  return {
    showVersion: /* @__PURE__ */ __name(() => {
      const version = ctx.env.version || "unknown";
      if (!ctx.env.usageSilent) ctx.log(version);
      return version;
    }, "showVersion"),
    showHeader: /* @__PURE__ */ __name(async () => {
      let header;
      if (ctx.env.renderHeader != null) {
        header = await ctx.env.renderHeader(ctx);
        if (header) {
          ctx.log(header);
          ctx.log();
        }
      }
      return header;
    }, "showHeader"),
    showUsage: /* @__PURE__ */ __name(async () => {
      if (ctx.env.renderUsage != null) {
        const usage = await ctx.env.renderUsage(ctx);
        if (usage) {
          ctx.log(usage);
          return usage;
        }
      }
    }, "showUsage"),
    showValidationErrors: /* @__PURE__ */ __name(async (error) => {
      if (ctx.env.renderValidationErrors === null) return;
      if (ctx.env.renderValidationErrors !== void 0) {
        const message = await ctx.env.renderValidationErrors(ctx, error);
        ctx.log(message);
        return message;
      }
    }, "showValidationErrors")
  };
}
__name(extension, "extension");
function global() {
  return plugin({
    id: pluginId2,
    name: "global options",
    extension,
    setup(ctx) {
      for (const [name, schema] of Object.entries(COMMON_ARGS)) ctx.addGlobalOption(name, schema);
      ctx.decorateCommand(decorator);
    }
  });
}
__name(global, "global");
async function cli(args, entry, options = {}) {
  return cliCore(args, entry, options, [global(), renderer()]);
}
__name(cli, "cli");

// ../../node_modules/.bun/gunshi@0.32.0/node_modules/gunshi/lib/definition.js
function define(definition) {
  return definition;
}
__name(define, "define");
/*! Bundled license information:

gunshi/lib/core-D1daCTTE.js:
gunshi/lib/constants-D_ixLD32.js:
gunshi/lib/utils-jNy8sqR5.js:
gunshi/lib/src-dTYUlEw_.js:
gunshi/lib/context.js:
gunshi/lib/cli-DfaFk6tk.js:
gunshi/lib/definition.js:
gunshi/lib/index.js:
gunshi/lib/index.js:
  (**
  * @author kazuya kawaguchi (a.k.a. kazupon)
  * @license MIT
  *)

gunshi/lib/core-BKtZQ6dG.js:
  (**
  * forked from `nodejs/node` (`pkgjs/parseargs`)
  * repository url: https://github.com/nodejs/node (https://github.com/pkgjs/parseargs)
  * code url: https://github.com/nodejs/node/blob/main/lib/internal/util/parse_args/parse_args.js
  *
  * @author kazuya kawaguchi (a.k.a. kazupon)
  * @license MIT
  *)
  (**
  * @author kazuya kawaguchi (a.k.a. kazupon)
  * @license MIT
  *)
*/

export { cli, define };
//# sourceMappingURL=chunk-WIL4LMMA.js.map
//# sourceMappingURL=chunk-WIL4LMMA.js.map