var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], 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);

// src/template.ts
var template_exports = {};
__export(template_exports, {
  ERegistry: () => ERegistry,
  unpackTemplate: () => unpackTemplate
});
module.exports = __toCommonJS(template_exports);
var import_utils = require("@winner-fed/utils");
var import_tar = require("@winner-fed/utils/compiled/tar");
var ERegistry = /* @__PURE__ */ ((ERegistry2) => {
  ERegistry2["npm"] = "https://registry.npmjs.com/";
  ERegistry2["taobao"] = "https://registry.npmmirror.com/";
  ERegistry2["winner"] = "http://artifactory.hundsun.com/artifactory/api/npm/winnerproject-npm-virtual/";
  return ERegistry2;
})(ERegistry || {});
var unpackTemplate = async (opts) => {
  const { template, dest, registry } = opts;
  import_utils.logger.info(
    `Init a new project with template ${import_utils.chalk.blue(template)} from npm ...`
  );
  const tryDownload = async (name) => {
    const url = await getNpmPkgTarUrl({ registry, name });
    if (!url) {
      return;
    }
    try {
      return await downloadTar({ dest, url });
    } catch (e) {
      throw new Error(`Download ${name} failed from ${registry}`, { cause: e });
    }
  };
  const nameList = [];
  const isStartWithWin = template.startsWith("@winner-fed/");
  if (template.endsWith("-template")) {
    if (isStartWithWin) {
      nameList.push(template);
    } else {
      nameList.push(`@winner-fed/${template}`);
    }
  } else if (isStartWithWin) {
    nameList.push(`${template}-template`);
  } else {
    nameList.push(`@winner-fed/${template}-template`);
  }
  for await (const name of nameList) {
    const success = await tryDownload(name);
    if (success) {
      import_utils.logger.ready(`Init ${import_utils.chalk.green(name)} success`);
      return success;
    }
  }
  throw new Error(
    `Template ${nameList.map((i) => import_utils.chalk.yellow(i)).join(", ")} not found from ${registry}`
  );
};
async function getNpmPkgTarUrl(opts) {
  var _a;
  const { registry, name } = opts;
  const nameWithoutScope = name.startsWith("@") ? name.split("/")[1] : name;
  const latestPkgInfoUrl = `${registry}${name}/latest`;
  let headers = {};
  const res = await import_utils.axios.get(latestPkgInfoUrl, {
    headers: {
      ...headers
    },
    validateStatus: () => true
  });
  const latestVersion = (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.version;
  if (!latestVersion) {
    return;
  }
  return `${registry}${name}/-/${nameWithoutScope}-${latestVersion}.tgz`;
}
async function downloadTar(opts) {
  const { dest, url } = opts;
  let headers = {};
  return new Promise(async (resolve, reject) => {
    try {
      const res = await import_utils.axios.get(url, {
        headers: {
          ...headers
        },
        responseType: "stream"
      });
      import_utils.fsExtra.mkdirpSync(dest);
      res.data.pipe(
        (0, import_tar.x)({
          C: dest,
          strip: 1
        })
      );
      resolve(dest);
    } catch (e) {
      if (import_utils.fsExtra.existsSync(dest)) {
        import_utils.fsExtra.removeSync(dest);
      }
      reject(e);
    }
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ERegistry,
  unpackTemplate
});
