"use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// ../../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs
var _events = require('events');
function toArr(any) {
  return any == null ? [] : Array.isArray(any) ? any : [any];
}
function toVal(out, key, val, opts) {
  var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
  out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
}
function mri2(args, opts) {
  args = args || [];
  opts = opts || {};
  var k, arr, arg, name, val, out = { _: [] };
  var i = 0, j = 0, idx = 0, len = args.length;
  const alibi = opts.alias !== void 0;
  const strict = opts.unknown !== void 0;
  const defaults = opts.default !== void 0;
  opts.alias = opts.alias || {};
  opts.string = toArr(opts.string);
  opts.boolean = toArr(opts.boolean);
  if (alibi) {
    for (k in opts.alias) {
      arr = opts.alias[k] = toArr(opts.alias[k]);
      for (i = 0; i < arr.length; i++) {
        (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
      }
    }
  }
  for (i = opts.boolean.length; i-- > 0; ) {
    arr = opts.alias[opts.boolean[i]] || [];
    for (j = arr.length; j-- > 0; )
      opts.boolean.push(arr[j]);
  }
  for (i = opts.string.length; i-- > 0; ) {
    arr = opts.alias[opts.string[i]] || [];
    for (j = arr.length; j-- > 0; )
      opts.string.push(arr[j]);
  }
  if (defaults) {
    for (k in opts.default) {
      name = typeof opts.default[k];
      arr = opts.alias[k] = opts.alias[k] || [];
      if (opts[name] !== void 0) {
        opts[name].push(k);
        for (i = 0; i < arr.length; i++) {
          opts[name].push(arr[i]);
        }
      }
    }
  }
  const keys = strict ? Object.keys(opts.alias) : [];
  for (i = 0; i < len; i++) {
    arg = args[i];
    if (arg === "--") {
      out._ = out._.concat(args.slice(++i));
      break;
    }
    for (j = 0; j < arg.length; j++) {
      if (arg.charCodeAt(j) !== 45)
        break;
    }
    if (j === 0) {
      out._.push(arg);
    } else if (arg.substring(j, j + 3) === "no-") {
      name = arg.substring(j + 3);
      if (strict && !~keys.indexOf(name)) {
        return opts.unknown(arg);
      }
      out[name] = false;
    } else {
      for (idx = j + 1; idx < arg.length; idx++) {
        if (arg.charCodeAt(idx) === 61)
          break;
      }
      name = arg.substring(j, idx);
      val = arg.substring(++idx) || (i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i]);
      arr = j === 2 ? [name] : name;
      for (idx = 0; idx < arr.length; idx++) {
        name = arr[idx];
        if (strict && !~keys.indexOf(name))
          return opts.unknown("-".repeat(j) + name);
        toVal(out, name, idx + 1 < arr.length || val, opts);
      }
    }
  }
  if (defaults) {
    for (k in opts.default) {
      if (out[k] === void 0) {
        out[k] = opts.default[k];
      }
    }
  }
  if (alibi) {
    for (k in out) {
      arr = opts.alias[k] || [];
      while (arr.length > 0) {
        out[arr.shift()] = out[k];
      }
    }
  }
  return out;
}
var removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
var findAllBrackets = (v) => {
  const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
  const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
  const res = [];
  const parse = (match) => {
    let variadic = false;
    let value = match[1];
    if (value.startsWith("...")) {
      value = value.slice(3);
      variadic = true;
    }
    return {
      required: match[0].startsWith("<"),
      value,
      variadic
    };
  };
  let angledMatch;
  while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
    res.push(parse(angledMatch));
  }
  let squareMatch;
  while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
    res.push(parse(squareMatch));
  }
  return res;
};
var getMriOptions = (options) => {
  const result = { alias: {}, boolean: [] };
  for (const [index, option] of options.entries()) {
    if (option.names.length > 1) {
      result.alias[option.names[0]] = option.names.slice(1);
    }
    if (option.isBoolean) {
      if (option.negated) {
        const hasStringTypeOption = options.some((o, i) => {
          return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
        });
        if (!hasStringTypeOption) {
          result.boolean.push(option.names[0]);
        }
      } else {
        result.boolean.push(option.names[0]);
      }
    }
  }
  return result;
};
var findLongest = (arr) => {
  return arr.sort((a, b) => {
    return a.length > b.length ? -1 : 1;
  })[0];
};
var padRight = (str, length) => {
  return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
};
var camelcase = (input) => {
  return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
    return p1 + p2.toUpperCase();
  });
};
var setDotProp = (obj, keys, val) => {
  let i = 0;
  let length = keys.length;
  let t = obj;
  let x;
  for (; i < length; ++i) {
    x = t[keys[i]];
    t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
  }
};
var setByType = (obj, transforms) => {
  for (const key of Object.keys(transforms)) {
    const transform = transforms[key];
    if (transform.shouldTransform) {
      obj[key] = Array.prototype.concat.call([], obj[key]);
      if (typeof transform.transformFunction === "function") {
        obj[key] = obj[key].map(transform.transformFunction);
      }
    }
  }
};
var getFileName = (input) => {
  const m = /([^\\\/]+)$/.exec(input);
  return m ? m[1] : "";
};
var camelcaseOptionName = (name) => {
  return name.split(".").map((v, i) => {
    return i === 0 ? camelcase(v) : v;
  }).join(".");
};
var CACError = class extends Error {
  constructor(message) {
    super(message);
    this.name = this.constructor.name;
    if (typeof Error.captureStackTrace === "function") {
      Error.captureStackTrace(this, this.constructor);
    } else {
      this.stack = new Error(message).stack;
    }
  }
};
var Option = class {
  constructor(rawName, description, config) {
    this.rawName = rawName;
    this.description = description;
    this.config = Object.assign({}, config);
    rawName = rawName.replace(/\.\*/g, "");
    this.negated = false;
    this.names = removeBrackets(rawName).split(",").map((v) => {
      let name = v.trim().replace(/^-{1,2}/, "");
      if (name.startsWith("no-")) {
        this.negated = true;
        name = name.replace(/^no-/, "");
      }
      return camelcaseOptionName(name);
    }).sort((a, b) => a.length > b.length ? 1 : -1);
    this.name = this.names[this.names.length - 1];
    if (this.negated && this.config.default == null) {
      this.config.default = true;
    }
    if (rawName.includes("<")) {
      this.required = true;
    } else if (rawName.includes("[")) {
      this.required = false;
    } else {
      this.isBoolean = true;
    }
  }
};
var processArgs = process.argv;
var platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
var Command = class {
  constructor(rawName, description, config = {}, cli2) {
    this.rawName = rawName;
    this.description = description;
    this.config = config;
    this.cli = cli2;
    this.options = [];
    this.aliasNames = [];
    this.name = removeBrackets(rawName);
    this.args = findAllBrackets(rawName);
    this.examples = [];
  }
  usage(text) {
    this.usageText = text;
    return this;
  }
  allowUnknownOptions() {
    this.config.allowUnknownOptions = true;
    return this;
  }
  ignoreOptionDefaultValue() {
    this.config.ignoreOptionDefaultValue = true;
    return this;
  }
  version(version2, customFlags = "-v, --version") {
    this.versionNumber = version2;
    this.option(customFlags, "Display version number");
    return this;
  }
  example(example) {
    this.examples.push(example);
    return this;
  }
  option(rawName, description, config) {
    const option = new Option(rawName, description, config);
    this.options.push(option);
    return this;
  }
  alias(name) {
    this.aliasNames.push(name);
    return this;
  }
  action(callback) {
    this.commandAction = callback;
    return this;
  }
  isMatched(name) {
    return this.name === name || this.aliasNames.includes(name);
  }
  get isDefaultCommand() {
    return this.name === "" || this.aliasNames.includes("!");
  }
  get isGlobalCommand() {
    return this instanceof GlobalCommand;
  }
  hasOption(name) {
    name = name.split(".")[0];
    return this.options.find((option) => {
      return option.names.includes(name);
    });
  }
  outputHelp() {
    const { name, commands } = this.cli;
    const {
      versionNumber,
      options: globalOptions,
      helpCallback
    } = this.cli.globalCommand;
    let sections = [
      {
        body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
      }
    ];
    sections.push({
      title: "Usage",
      body: `  $ ${name} ${this.usageText || this.rawName}`
    });
    const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
    if (showCommands) {
      const longestCommandName = findLongest(commands.map((command) => command.rawName));
      sections.push({
        title: "Commands",
        body: commands.map((command) => {
          return `  ${padRight(command.rawName, longestCommandName.length)}  ${command.description}`;
        }).join("\n")
      });
      sections.push({
        title: `For more info, run any command with the \`--help\` flag`,
        body: commands.map((command) => `  $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
      });
    }
    let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
    if (!this.isGlobalCommand && !this.isDefaultCommand) {
      options = options.filter((option) => option.name !== "version");
    }
    if (options.length > 0) {
      const longestOptionName = findLongest(options.map((option) => option.rawName));
      sections.push({
        title: "Options",
        body: options.map((option) => {
          return `  ${padRight(option.rawName, longestOptionName.length)}  ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
        }).join("\n")
      });
    }
    if (this.examples.length > 0) {
      sections.push({
        title: "Examples",
        body: this.examples.map((example) => {
          if (typeof example === "function") {
            return example(name);
          }
          return example;
        }).join("\n")
      });
    }
    if (helpCallback) {
      sections = helpCallback(sections) || sections;
    }
    console.log(sections.map((section) => {
      return section.title ? `${section.title}:
${section.body}` : section.body;
    }).join("\n\n"));
  }
  outputVersion() {
    const { name } = this.cli;
    const { versionNumber } = this.cli.globalCommand;
    if (versionNumber) {
      console.log(`${name}/${versionNumber} ${platformInfo}`);
    }
  }
  checkRequiredArgs() {
    const minimalArgsCount = this.args.filter((arg) => arg.required).length;
    if (this.cli.args.length < minimalArgsCount) {
      throw new CACError(`missing required args for command \`${this.rawName}\``);
    }
  }
  checkUnknownOptions() {
    const { options, globalCommand } = this.cli;
    if (!this.config.allowUnknownOptions) {
      for (const name of Object.keys(options)) {
        if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
          throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
        }
      }
    }
  }
  checkOptionValue() {
    const { options: parsedOptions, globalCommand } = this.cli;
    const options = [...globalCommand.options, ...this.options];
    for (const option of options) {
      const value = parsedOptions[option.name.split(".")[0]];
      if (option.required) {
        const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
        if (value === true || value === false && !hasNegated) {
          throw new CACError(`option \`${option.rawName}\` value is missing`);
        }
      }
    }
  }
};
var GlobalCommand = class extends Command {
  constructor(cli2) {
    super("@@global@@", "", {}, cli2);
  }
};
var __assign = Object.assign;
var CAC = class extends _events.EventEmitter {
  constructor(name = "") {
    super();
    this.name = name;
    this.commands = [];
    this.rawArgs = [];
    this.args = [];
    this.options = {};
    this.globalCommand = new GlobalCommand(this);
    this.globalCommand.usage("<command> [options]");
  }
  usage(text) {
    this.globalCommand.usage(text);
    return this;
  }
  command(rawName, description, config) {
    const command = new Command(rawName, description || "", config, this);
    command.globalCommand = this.globalCommand;
    this.commands.push(command);
    return command;
  }
  option(rawName, description, config) {
    this.globalCommand.option(rawName, description, config);
    return this;
  }
  help(callback) {
    this.globalCommand.option("-h, --help", "Display this message");
    this.globalCommand.helpCallback = callback;
    this.showHelpOnExit = true;
    return this;
  }
  version(version2, customFlags = "-v, --version") {
    this.globalCommand.version(version2, customFlags);
    this.showVersionOnExit = true;
    return this;
  }
  example(example) {
    this.globalCommand.example(example);
    return this;
  }
  outputHelp() {
    if (this.matchedCommand) {
      this.matchedCommand.outputHelp();
    } else {
      this.globalCommand.outputHelp();
    }
  }
  outputVersion() {
    this.globalCommand.outputVersion();
  }
  setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
    this.args = args;
    this.options = options;
    if (matchedCommand) {
      this.matchedCommand = matchedCommand;
    }
    if (matchedCommandName) {
      this.matchedCommandName = matchedCommandName;
    }
    return this;
  }
  unsetMatchedCommand() {
    this.matchedCommand = void 0;
    this.matchedCommandName = void 0;
  }
  parse(argv = processArgs, {
    run = true
  } = {}) {
    this.rawArgs = argv;
    if (!this.name) {
      this.name = argv[1] ? getFileName(argv[1]) : "cli";
    }
    let shouldParse = true;
    for (const command of this.commands) {
      const parsed = this.mri(argv.slice(2), command);
      const commandName = parsed.args[0];
      if (command.isMatched(commandName)) {
        shouldParse = false;
        const parsedInfo = __assign(__assign({}, parsed), {
          args: parsed.args.slice(1)
        });
        this.setParsedInfo(parsedInfo, command, commandName);
        this.emit(`command:${commandName}`, command);
      }
    }
    if (shouldParse) {
      for (const command of this.commands) {
        if (command.name === "") {
          shouldParse = false;
          const parsed = this.mri(argv.slice(2), command);
          this.setParsedInfo(parsed, command);
          this.emit(`command:!`, command);
        }
      }
    }
    if (shouldParse) {
      const parsed = this.mri(argv.slice(2));
      this.setParsedInfo(parsed);
    }
    if (this.options.help && this.showHelpOnExit) {
      this.outputHelp();
      run = false;
      this.unsetMatchedCommand();
    }
    if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
      this.outputVersion();
      run = false;
      this.unsetMatchedCommand();
    }
    const parsedArgv = { args: this.args, options: this.options };
    if (run) {
      this.runMatchedCommand();
    }
    if (!this.matchedCommand && this.args[0]) {
      this.emit("command:*");
    }
    return parsedArgv;
  }
  mri(argv, command) {
    const cliOptions = [
      ...this.globalCommand.options,
      ...command ? command.options : []
    ];
    const mriOptions = getMriOptions(cliOptions);
    let argsAfterDoubleDashes = [];
    const doubleDashesIndex = argv.indexOf("--");
    if (doubleDashesIndex > -1) {
      argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
      argv = argv.slice(0, doubleDashesIndex);
    }
    let parsed = mri2(argv, mriOptions);
    parsed = Object.keys(parsed).reduce((res, name) => {
      return __assign(__assign({}, res), {
        [camelcaseOptionName(name)]: parsed[name]
      });
    }, { _: [] });
    const args = parsed._;
    const options = {
      "--": argsAfterDoubleDashes
    };
    const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
    let transforms = /* @__PURE__ */ Object.create(null);
    for (const cliOption of cliOptions) {
      if (!ignoreDefault && cliOption.config.default !== void 0) {
        for (const name of cliOption.names) {
          options[name] = cliOption.config.default;
        }
      }
      if (Array.isArray(cliOption.config.type)) {
        if (transforms[cliOption.name] === void 0) {
          transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
          transforms[cliOption.name]["shouldTransform"] = true;
          transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
        }
      }
    }
    for (const key of Object.keys(parsed)) {
      if (key !== "_") {
        const keys = key.split(".");
        setDotProp(options, keys, parsed[key]);
        setByType(options, transforms);
      }
    }
    return {
      args,
      options
    };
  }
  runMatchedCommand() {
    const { args, options, matchedCommand: command } = this;
    if (!command || !command.commandAction)
      return;
    command.checkUnknownOptions();
    command.checkOptionValue();
    command.checkRequiredArgs();
    const actionArgs = [];
    command.args.forEach((arg, index) => {
      if (arg.variadic) {
        actionArgs.push(args.slice(index));
      } else {
        actionArgs.push(args[index]);
      }
    });
    actionArgs.push(options);
    return command.commandAction.apply(this, actionArgs);
  }
};
var cac = (name = "") => new CAC(name);

// src/node/init.ts
var _util = require('util');
var _path = require('path'); var _path2 = _interopRequireDefault(_path);
var _fs = require('fs');
var _ncp = require('ncp');
var _prompts = require('prompts'); var _prompts2 = _interopRequireDefault(_prompts);
var _rimraf = require('rimraf');

// src/node/editFiles.ts


async function editFiles(target) {
  await updateViteConfigFile(target);
  await updateTsconfigFile(target);
  await updateMainTSFile(target);
}
async function updateViteConfigFile(target) {
  const configFile = _path.join.call(void 0, target, "vite.config.ts");
  const configContent = _fs.readFileSync.call(void 0, configFile, { encoding: "utf-8" });
  const pattern = /\/\*\* Delete below \*\/([\s\S]*?)\/\*\* End \*\//;
  const result = configContent.replace(pattern, "").trim().replace(/^\s*$\n/gm, "");
  _fs.writeFileSync.call(void 0, configFile, result);
}
async function updateTsconfigFile(target) {
  const configFile = _path.join.call(void 0, target, "tsconfig.json");
  const configContent = _fs.readFileSync.call(void 0, configFile, { encoding: "utf-8" });
  const pattern = /\/\/\s*Delete\sbelow([\S\s]*?)\/\/\s*End/gi;
  const result = configContent.replace(pattern, "").trim().replace(/^\s*$\n/gm, "");
  _fs.writeFileSync.call(void 0, configFile, result);
}
async function updateMainTSFile(target) {
  const tsFile = _path.join.call(void 0, target, "src", "main.ts");
  const tsContent = _fs.readFileSync.call(void 0, tsFile, { encoding: "utf-8" });
  const pattern = /(.*)(\r?\n\s*\/\*\* 正式环境使用下面的地址 \*\/)/g;
  const result = tsContent.replace(pattern, "").replace(/\/\/\W/g, "");
  _fs.writeFileSync.call(void 0, tsFile, result);
}

// src/node/depend.ts


var _npminstall = require('npminstall'); var _npminstall2 = _interopRequireDefault(_npminstall);

// src/utils/crypto.ts
var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);


var _buffer = require('buffer');
var secretKey = "longrise-leap";
var IV_LENGTH = 16;
function encrypt(text) {
  const iv = _crypto2.default.randomBytes(IV_LENGTH);
  const algorithm = "aes-256-cbc";
  const key = _crypto2.default.createHash("sha256").update(secretKey).digest();
  const cipher = _crypto2.default.createCipheriv(algorithm, key, iv);
  const encryptedBytes = new Uint8Array(cipher.update(text, "utf8"));
  const finalEncryptedBytes = new Uint8Array(cipher.final());
  const encryptedResult = new Uint8Array(encryptedBytes.length + finalEncryptedBytes.length);
  encryptedResult.set(encryptedBytes);
  encryptedResult.set(finalEncryptedBytes, encryptedBytes.length);
  return `${_buffer.Buffer.from(encryptedResult).toString("hex")}.${iv.toString("hex")}`;
}

// src/utils/chalk.ts
var _chalk = require('chalk'); var _chalk2 = _interopRequireDefault(_chalk);
function info(message) {
  console.log(_chalk2.default.blue("> Info:"), message);
}
function startInstallMessage() {
  console.log(`${time()}${_chalk2.default.blue("\u5F00\u59CB\u5B89\u88C5\u9879\u76EE\u4F9D\u8D56\uFF01")}`);
}
function installSuccessMessage() {
  console.log(`${time()} ${_chalk2.default.green("\u5B89\u88C5\u6210\u529F\uFF01")}`);
}
function copyStartMessage() {
  console.log(`${time()}${_chalk2.default.blue("\u5F00\u59CB\u521D\u59CB\u5316\u9879\u76EE\u2026\u2026")}`);
}
function copyEndMessage() {
  console.log(`${time()}${_chalk2.default.green("\u521D\u59CB\u5316\u6210\u529F\uFF01")}`);
}
function updateFileMessage() {
  console.log(`${time()}${_chalk2.default.blue("\u5373\u5C06\u505A\u6700\u540E\u4FEE\u6539\uFF01")}`);
}
function updateFileSuccessMessage() {
  console.log(`${time()}${_chalk2.default.green("\u4E00\u5207\u51C6\u5907\u5C31\u7EEA\uFF01")}`);
}
function time() {
  const date = /* @__PURE__ */ new Date();
  const hour = format(date.getHours());
  const minute = format(date.getMinutes());
  const second = format(date.getSeconds());
  return _chalk2.default.gray(`${hour}:${minute}:${second} `);
}
function format(n) {
  return n >= 10 ? `${n}` : `0${n}`;
}

// src/node/depend.ts
async function getPackagesAndInstall(target) {
  let dependencies = null;
  let devDependencies = null;
  const packageJsonFile = _path.join.call(void 0, target, "package.json");
  const jsonContent = _fs.readFileSync.call(void 0, packageJsonFile, { encoding: "utf-8" });
  const jsonObj = JSON.parse(jsonContent);
  dependencies = jsonObj.dependencies;
  devDependencies = jsonObj.devDependencies;
  const install = {
    dependencies,
    devDependencies
  };
  const pattern = /("dependencies"[\s\S]*?\n\s*\}\s*,\s*\n)|("devDependencies"[\s\S]*?\n\s*\}\s*\n)/g;
  const result = jsonContent.replace(pattern, "").replace(/,(?=\s*})/gm, "");
  const r = JSON.parse(result);
  const rs = JSON.stringify(r, null, 2);
  _fs.writeFileSync.call(void 0, packageJsonFile, rs);
  const licence = _path2.default.join(target, "licence");
  if (!_fs.existsSync.call(void 0, licence))
    _fs.writeFileSync.call(void 0, licence, encrypt(JSON.stringify(install)));
  await installAllPackages(install);
}
async function installAllPackages(install) {
  const pkgs = computedPkgs(install);
  startInstallMessage();
  await _npminstall2.default.call(void 0, {
    root: process.cwd(),
    pkgs
  }).catch((err) => {
    if (err)
      console.log(err);
  });
  installSuccessMessage();
}
function computedPkgs(install) {
  const pkgs = [];
  Object.keys(install).forEach((type) => {
    Object.keys(install[type]).forEach((name) => {
      pkgs.push({
        name,
        version: install[type][name]
      });
    });
  });
  return pkgs;
}

// src/utils/file.ts


var { readdir, stat, rmdir, unlink } = _fs.promises;
function isDirectoryEmpty(targetDir) {
  return new Promise((resolve, reject) => {
    if (!_fs.existsSync.call(void 0, targetDir)) {
      resolve(true);
      return;
    }
    const files = _fs.readdirSync.call(void 0, targetDir);
    resolve(files.length === 0);
  });
}

// src/node/init.ts
var copy = _util.promisify.call(void 0, _ncp.ncp);
async function initProject(type) {
  let pkg = type;
  if (!pkg) {
    const res = await _prompts2.default.call(void 0, {
      type: "select",
      name: "package",
      message: "\u8BF7\u9009\u62E9\u8981\u521B\u5EFA\u7684\u9879\u76EE\u7C7B\u578B\uFF01",
      choices: [{
        title: "\u684C\u9762\u7AEFvue3\u9879\u76EE\u6A21\u677F",
        value: "desktop-vue3"
      }, {
        title: "\u6587\u6863\u7CFB\u7EDF\u6A21\u677F",
        value: "doc"
      }],
      initial: 0
    });
    pkg = res.package;
  }
  const sourceDir = _path.join.call(void 0, __dirname, "..", "src", "template", pkg);
  const targetDir = process.cwd();
  if (!_fs.existsSync.call(void 0, sourceDir)) {
    console.log("\u7F3A\u5C11\u6A21\u677F");
    return;
  }
  const isEmptyDirectory = await isDirectoryEmpty(targetDir);
  if (!isEmptyDirectory) {
    const res = await _prompts2.default.call(void 0, {
      type: "confirm",
      name: "empty",
      message: "\u68C0\u6D4B\u5230\u975E\u7A7A\u76EE\u5F55\uFF0C\u786E\u8BA4\u8981\u6E05\u7A7A\u5417\uFF1F",
      initial: true
    });
    if (res.empty) {
      try {
        await _rimraf.rimraf.call(void 0, targetDir, {
          glob: true
        });
      } catch (err) {
        console.log("busy");
      }
    } else {
      console.log("\u60A8\u6CA1\u6709\u540C\u610F\uFF0C\u5373\u5C06\u7ED3\u675F");
      return;
    }
  }
  if (!_fs.existsSync.call(void 0, sourceDir)) {
    console.log(`Error: The template directory '${sourceDir}' doesn't exist.`);
    return;
  }
  try {
    copyStartMessage();
    await copy(sourceDir, targetDir);
    copyEndMessage();
    updateFileMessage();
    await editFiles(targetDir);
    updateFileSuccessMessage();
    await getPackagesAndInstall(targetDir);
    console.log("\u521D\u59CB\u5316\u5B8C\u6210");
  } catch (error) {
    console.error(`Error: Failed to copy files. ${error.message}`);
  }
}

// package.json
var version = "0.0.1";

// src/index.ts
var cli = cac("ldesign").version(version).help();
info("\u6B22\u8FCE\u4F7F\u7528\uFF01");
cli.command("init [type]", "\u521D\u59CB\u5316\u4E00\u4E2A\u9879\u76EE").action(initProject);
cli.parse();
//# sourceMappingURL=index.js.map