edgeone-cli 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{Command}from"commander";import fs from"fs";import inquirer from"inquirer";import os from"os";import path from"path";import{decrypt,encrypt,isEncrypted}from"../utils/crypto.js";const CONFIG_DIR=path.join(os.homedir(),".edgeone-cli"),CONFIG_FILE=path.join(CONFIG_DIR,"config.json");export function ensureConfigDir(){fs.existsSync(CONFIG_DIR)||fs.mkdirSync(CONFIG_DIR,{recursive:!0})}export function readConfig(){if(fs.existsSync(CONFIG_FILE)){const content=fs.readFileSync(CONFIG_FILE,"utf-8"),stored=JSON.parse(content);let secretKey=stored.secretKey,needsMigration=!stored.encrypted;if(stored.encrypted||isEncrypted(stored.secretKey))try{secretKey=decrypt(stored.secretKey),needsMigration=!1}catch{needsMigration=!1}let domainIdList=[];stored.domainIdList&&stored.domainIdList.length>0&&(domainIdList="string"==typeof stored.domainIdList[0]?stored.domainIdList.map(id=>({id})):stored.domainIdList);const config={secretId:stored.secretId,secretKey,endpoint:stored.endpoint,mode:stored.mode||"production",domainIdList};return needsMigration&&(writeConfig(config),console.log(chalk.gray("💡 配置已自动升级为加密格式"))),config}return null}export function writeConfig(config){ensureConfigDir();const encryptedSecretKey=encrypt(config.secretKey),stored={secretId:config.secretId,secretKey:encryptedSecretKey,endpoint:config.endpoint,mode:config.mode,domainIdList:config.domainIdList,encrypted:!0};fs.writeFileSync(CONFIG_FILE,JSON.stringify(stored,null,2),"utf-8")}function maskString(str,showLength=4){return str?str.length<=2*showLength?str:str.slice(0,showLength)+"****"+str.slice(-showLength):"N/A"}const configCmd=new Command("config").description("管理 EdgeOne 配置");configCmd.command("init").description("初始化配置").action(async()=>{const existingConfig=readConfig();if(existingConfig){console.log(chalk.yellow("\n⚠ 检测到已存在的配置:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` SecretId: ${chalk.green(maskString(existingConfig.secretId))}`),console.log(` SecretKey: ${chalk.green(maskString(existingConfig.secretKey))}`),console.log(` 接口请求域名: ${chalk.yellow(existingConfig.endpoint||"teo.tencentcloudapi.com")}`),console.log(` 运行模式: ${"debug"===existingConfig.mode?chalk.yellow("调试模式"):chalk.green("生产模式")}`),console.log(chalk.gray("─".repeat(40)));const{confirm}=await inquirer.prompt([{type:"confirm",name:"confirm",message:"已有配置将被覆盖,是否继续?",default:!1}]);if(!confirm)return void console.log(chalk.gray("已取消"))}console.log(chalk.cyan("\n🔧 开始初始化 EdgeOne 配置\n"));const answers=await inquirer.prompt([{type:"input",name:"secretId",message:"请输入 SecretId:",validate:input=>""!==input.trim()||"SecretId 不能为空"},{type:"password",name:"secretKey",message:"请输入 SecretKey:",mask:"*",validate:input=>""!==input.trim()||"SecretKey 不能为空"},{type:"input",name:"endpoint",message:"请输入接口请求域名:",default:"teo.tencentcloudapi.com"},{type:"list",name:"mode",message:"请选择运行模式:",choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}],default:"production"},{type:"input",name:"domainIdList",message:"请输入站点列表,格式: id:备注(多个用逗号分隔,留空跳过):",default:""}]);let domainIdList=[];const domainIdInput=answers.domainIdList;domainIdInput&&domainIdInput.trim()&&(domainIdList=domainIdInput.split(",").map(item=>{if((item=item.trim()).includes(":")){const[id,name]=item.split(":");return{id:id.trim(),name:name.trim()}}return{id:item}}).filter(zone=>""!==zone.id)),writeConfig({secretId:answers.secretId,secretKey:answers.secretKey,endpoint:answers.endpoint||"teo.tencentcloudapi.com",mode:answers.mode||"production",domainIdList}),console.log(chalk.green("\n✅ 配置已加密保存到: "+CONFIG_FILE))}),configCmd.command("show").description("显示当前配置").action(function(){const config=readConfig();if(!config)return void console.log(chalk.yellow('⚠ 未找到配置文件,请先运行 "edgeone-cli config init"'));const modeText="debug"===config.mode?"调试模式":"生产模式",modeColor="debug"===config.mode?chalk.yellow:chalk.green;console.log(chalk.cyan("\n📋 当前配置:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` SecretId: ${chalk.green(maskString(config.secretId))}`),console.log(` SecretKey: ${chalk.green(maskString(config.secretKey))}`),console.log(` 接口请求域名: ${chalk.yellow(config.endpoint||"teo.tencentcloudapi.com")}`),console.log(` 运行模式: ${modeColor(modeText)}`),config.domainIdList&&config.domainIdList.length>0&&(console.log(" 站点列表:"),config.domainIdList.forEach((zone,idx)=>{const display=zone.name?`${zone.name} (${zone.id})`:zone.id;console.log(` ${idx+1}. ${chalk.yellow(display)}`)})),console.log(chalk.gray("─".repeat(40)))}),configCmd.command("remove").description("删除配置文件").action(async()=>{if(!fs.existsSync(CONFIG_FILE))return void console.log(chalk.yellow("⚠ 配置文件不存在"));const{confirm}=await inquirer.prompt([{type:"confirm",name:"confirm",message:"确定要删除配置文件吗?",default:!1}]);confirm?(fs.unlinkSync(CONFIG_FILE),console.log(chalk.green("✅ 配置文件已删除"))):console.log(chalk.gray("已取消"))}),configCmd.command("edit").description("编辑配置项").action(async()=>{const config=readConfig();if(!config)return void console.log(chalk.yellow('⚠ 未找到配置文件,请先运行 "edgeone-cli config init"'));const answers=await inquirer.prompt([{type:"list",name:"field",message:"选择要修改的配置项:",choices:[{name:"SecretId",value:"secretId"},{name:"SecretKey",value:"secretKey"},{name:"接口请求域名",value:"endpoint"},{name:"运行模式",value:"mode"},{name:"站点列表",value:"domainIdList"}]},{type:"input",name:"value",message:answers=>`请输入新的 ${answers.field}:`,when:answers=>"secretKey"!==answers.field&&"mode"!==answers.field&&"domainIdList"!==answers.field,validate:input=>""!==input.trim()||"不能为空"},{type:"password",name:"value",message:"请输入新的 SecretKey:",mask:"*",when:answers=>"secretKey"===answers.field,validate:input=>""!==input.trim()||"不能为空"},{type:"list",name:"value",message:"请选择运行模式:",when:answers=>"mode"===answers.field,choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}]},{type:"input",name:"value",message:"请输入站点列表(多个用逗号分隔):",when:answers=>"domainIdList"===answers.field,default:""}]);if("domainIdList"===answers.field){const domainIdInput=answers.value,domainIds=domainIdInput&&domainIdInput.trim()?domainIdInput.split(",").map(id=>id.trim()).filter(id=>""!==id):[];config[answers.field]=domainIds}else config[answers.field]=answers.value;writeConfig(config),console.log(chalk.green("✅ 配置已更新"))});export default configCmd;export{CONFIG_FILE};
1
+ import chalk from"chalk";import{Command}from"commander";import fs from"fs";import inquirer from"inquirer";import os from"os";import path from"path";import{decrypt,encrypt,isEncrypted}from"../utils/crypto.js";const CONFIG_DIR=path.join(os.homedir(),".edgeone-cli"),CONFIG_FILE=path.join(CONFIG_DIR,"config.json");export function ensureConfigDir(){fs.existsSync(CONFIG_DIR)||fs.mkdirSync(CONFIG_DIR,{recursive:!0})}export function readConfig(){if(fs.existsSync(CONFIG_FILE)){const content=fs.readFileSync(CONFIG_FILE,"utf-8"),stored=JSON.parse(content);let secretKey=stored.secretKey,needsMigration=!stored.encrypted;if(stored.encrypted||isEncrypted(stored.secretKey))try{secretKey=decrypt(stored.secretKey),needsMigration=!1}catch{needsMigration=!1}let domainIdList=[];stored.domainIdList&&stored.domainIdList.length>0&&(domainIdList="string"==typeof stored.domainIdList[0]?stored.domainIdList.map(id=>({id})):stored.domainIdList);const config={secretId:stored.secretId,secretKey,endpoint:stored.endpoint,mode:stored.mode||"production",domainIdList};return needsMigration&&(writeConfig(config),console.log(chalk.gray("💡 配置已自动升级为加密格式"))),config}return null}export function writeConfig(config){ensureConfigDir();const encryptedSecretKey=encrypt(config.secretKey),stored={secretId:config.secretId,secretKey:encryptedSecretKey,endpoint:config.endpoint,mode:config.mode,domainIdList:config.domainIdList,encrypted:!0};fs.writeFileSync(CONFIG_FILE,JSON.stringify(stored,null,2),"utf-8")}function maskString(str,showLength=4){return str?str.length<=2*showLength?str:str.slice(0,showLength)+"****"+str.slice(-showLength):"N/A"}const configCmd=new Command("config").description("管理 EdgeOne 配置");configCmd.command("init").description("初始化配置").action(async()=>{const existingConfig=readConfig();if(existingConfig){console.log(chalk.yellow("\n⚠ 检测到已存在的配置:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` SecretId: ${chalk.green(maskString(existingConfig.secretId))}`),console.log(` SecretKey: ${chalk.green(maskString(existingConfig.secretKey))}`),console.log(` 接口请求域名: ${chalk.yellow(existingConfig.endpoint||"teo.tencentcloudapi.com")}`),console.log(` 运行模式: ${"debug"===existingConfig.mode?chalk.yellow("调试模式"):chalk.green("生产模式")}`),console.log(chalk.gray("─".repeat(40)));const{confirm}=await inquirer.prompt([{type:"confirm",name:"confirm",message:"已有配置将被覆盖,是否继续?",default:!1}]);if(!confirm)return void console.log(chalk.gray("已取消"))}console.log(chalk.cyan("\n🔧 开始初始化 EdgeOne 配置\n"));const answers=await inquirer.prompt([{type:"input",name:"secretId",message:"请输入 SecretId:",validate:input=>""!==input.trim()||"SecretId 不能为空"},{type:"password",name:"secretKey",message:"请输入 SecretKey:",mask:"*",validate:input=>""!==input.trim()||"SecretKey 不能为空"},{type:"input",name:"endpoint",message:"请输入接口请求域名:",default:"teo.tencentcloudapi.com"},{type:"list",name:"mode",message:"请选择运行模式:",choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}],default:"production"},{type:"input",name:"domainIdList",message:"请输入站点列表,格式: id:备注(多个用逗号分隔,留空跳过):",default:""}]);let domainIdList=[];const domainIdInput=answers.domainIdList;domainIdInput&&domainIdInput.trim()&&(domainIdList=domainIdInput.split(",").map(item=>{if((item=item.trim()).includes(":")){const firstColonIndex=item.indexOf(":");return{id:item.slice(0,firstColonIndex).trim(),name:item.slice(firstColonIndex+1).trim()}}return{id:item}}).filter(zone=>""!==zone.id)),writeConfig({secretId:answers.secretId,secretKey:answers.secretKey,endpoint:answers.endpoint||"teo.tencentcloudapi.com",mode:answers.mode||"production",domainIdList}),console.log(chalk.green("\n✅ 配置已加密保存到: "+CONFIG_FILE))}),configCmd.command("show").description("显示当前配置").action(function(){const config=readConfig();if(!config)return void console.log(chalk.yellow('⚠ 未找到配置文件,请先运行 "edgeone-cli config init"'));const modeText="debug"===config.mode?"调试模式":"生产模式",modeColor="debug"===config.mode?chalk.yellow:chalk.green;console.log(chalk.cyan("\n📋 当前配置:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` SecretId: ${chalk.green(maskString(config.secretId))}`),console.log(` SecretKey: ${chalk.green(maskString(config.secretKey))}`),console.log(` 接口请求域名: ${chalk.yellow(config.endpoint||"teo.tencentcloudapi.com")}`),console.log(` 运行模式: ${modeColor(modeText)}`),config.domainIdList&&config.domainIdList.length>0&&(console.log(" 站点列表:"),config.domainIdList.forEach((zone,idx)=>{const display=zone.name?`${zone.name} (${zone.id})`:zone.id;console.log(` ${idx+1}. ${chalk.yellow(display)}`)})),console.log(chalk.gray("─".repeat(40)))}),configCmd.command("remove").description("删除配置文件").action(async()=>{if(!fs.existsSync(CONFIG_FILE))return void console.log(chalk.yellow("⚠ 配置文件不存在"));const{confirm}=await inquirer.prompt([{type:"confirm",name:"confirm",message:"确定要删除配置文件吗?",default:!1}]);confirm?(fs.unlinkSync(CONFIG_FILE),console.log(chalk.green("✅ 配置文件已删除"))):console.log(chalk.gray("已取消"))}),configCmd.command("edit").description("编辑配置项").action(async()=>{const config=readConfig();if(!config)return void console.log(chalk.yellow('⚠ 未找到配置文件,请先运行 "edgeone-cli config init"'));const answers=await inquirer.prompt([{type:"list",name:"field",message:"选择要修改的配置项:",choices:[{name:"SecretId",value:"secretId"},{name:"SecretKey",value:"secretKey"},{name:"接口请求域名",value:"endpoint"},{name:"运行模式",value:"mode"},{name:"站点列表",value:"domainIdList"}]},{type:"input",name:"value",message:answers=>`请输入新的 ${answers.field}:`,when:answers=>"secretKey"!==answers.field&&"mode"!==answers.field&&"domainIdList"!==answers.field,validate:input=>""!==input.trim()||"不能为空"},{type:"password",name:"value",message:"请输入新的 SecretKey:",mask:"*",when:answers=>"secretKey"===answers.field,validate:input=>""!==input.trim()||"不能为空"},{type:"list",name:"value",message:"请选择运行模式:",when:answers=>"mode"===answers.field,choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}]},{type:"input",name:"value",message:"请输入站点列表(多个用逗号分隔):",when:answers=>"domainIdList"===answers.field,default:""}]);if("domainIdList"===answers.field){const domainIdInput=answers.value,domainIdList=domainIdInput&&domainIdInput.trim()?domainIdInput.split(",").map(item=>{if((item=item.trim()).includes(":")){const firstColonIndex=item.indexOf(":");return{id:item.slice(0,firstColonIndex).trim(),name:item.slice(firstColonIndex+1).trim()}}return{id:item}}).filter(zone=>""!==zone.id):[];config[answers.field]=domainIdList}else config[answers.field]=answers.value;writeConfig(config),console.log(chalk.green("✅ 配置已更新"))});export default configCmd;export{CONFIG_FILE};
package/dist/repl.js CHANGED
@@ -1 +1 @@
1
- import chalk from"chalk";import inquirer from"inquirer";import{EdgeOneClient}from"./api/client.js";import{readConfig}from"./commands/config.js";async function pauseToContinue(){await inquirer.prompt([{type:"input",name:"continue",message:"按 Enter 键返回..."}])}function showBanner(){console.log(""),console.log(chalk.cyan("╔════════════════════════════════════╗")),console.log(chalk.cyan("║")+" "+chalk.white.bold("EdgeOne CLI")+" "+chalk.cyan("║")),console.log(chalk.cyan("║")+" "+chalk.gray("本地化 EdgeOne 服务管理工具")+" "+chalk.cyan("║")),console.log(chalk.cyan("╚════════════════════════════════════╝")),console.log("")}export async function startInteractive(){readConfig()||(showBanner(),await initConfig()),await async function(){for(;;){console.clear(),showBanner();const answers=await inquirer.prompt([{type:"list",name:"action",message:"请选择操作:",choices:[{name:"🔓 配置管理",value:"config"},{name:"🧹 清除缓存",value:"purge"},{name:"🚀 内容预热",value:"prefetch"},{name:"🌐 站点状态",value:"zone-status"},new inquirer.Separator("─────────────────"),{name:"❌ 退出",value:"exit"}],pageSize:10}]);"exit"===answers.action&&(console.log(chalk.gray("\n👋 再见!\n")),process.exit(0)),answers.action&&await handleAction(answers.action)}}()}async function handleAction(action){const config=readConfig();switch(action){case"config":await async function(){const answers=await inquirer.prompt([{type:"list",name:"action",message:"配置管理:",choices:[{name:"查看配置",value:"show"},{name:"编辑配置",value:"edit"},{name:"删除配置",value:"remove"},{name:"初始化配置",value:"init"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===answers.action)return;if("init"===answers.action)return void await initConfig();const config=readConfig();if(!config)return void console.log(chalk.yellow("\n⚠️ 配置不存在,请先初始化\n"));const{EdgeOneClient}=await import("./api/client.js");new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode);switch(answers.action){case"show":await async function(config){const modeText="debug"===config.mode?"调试模式":"生产模式",modeColor="debug"===config.mode?chalk.yellow:chalk.green;console.log(chalk.cyan("\n📋 当前配置:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` SecretId: ${chalk.green(maskString(config.secretId))}`),console.log(` SecretKey: ${chalk.green(maskString(config.secretKey))}`),console.log(` 接口请求域名: ${chalk.yellow(config.endpoint||"teo.tencentcloudapi.com")}`),console.log(` 运行模式: ${modeColor(modeText)}`),config.domainIdList&&config.domainIdList.length>0&&(console.log(" 站点列表:"),config.domainIdList.forEach((zone,idx)=>{const display=zone.name?`${zone.name} (${zone.id})`:zone.id;console.log(` ${idx+1}. ${chalk.yellow(display)}`)}));console.log(chalk.gray("─".repeat(40))),console.log(""),await pauseToContinue()}(config);break;case"edit":await async function(config){const answers=await inquirer.prompt([{type:"list",name:"action",message:"选择要修改的配置项:",choices:[{name:"SecretId",value:"secretId"},{name:"SecretKey",value:"secretKey"},{name:"接口请求域名",value:"endpoint"},{name:"运行模式",value:"mode"},{name:"站点列表",value:"domainIdList"}]}]);let newValue;"secretId"===answers.action?(newValue=await inquirer.prompt([{type:"input",name:"value",message:"请输入新的 SecretId:",validate:i=>i.trim()||"不能为空"}]),config.secretId=newValue.value):"secretKey"===answers.action?(newValue=await inquirer.prompt([{type:"password",name:"value",message:"请输入新的 SecretKey:",mask:"*",validate:i=>i.trim()||"不能为空"}]),config.secretKey=newValue.value):"endpoint"===answers.action?(newValue=await inquirer.prompt([{type:"input",name:"value",message:"请输入新的接口请求域名:"}]),config.endpoint=newValue.value):"mode"===answers.action?(newValue=await inquirer.prompt([{type:"list",name:"value",message:"请选择运行模式:",choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}]}]),config.mode=newValue.value):"domainIdList"===answers.action&&(config.domainIdList&&config.domainIdList.length>0&&(console.log(chalk.gray("\n当前站点列表:")),config.domainIdList.forEach((zone,idx)=>{const display=zone.name?`${zone.name} (${zone.id})`:zone.id;console.log(` ${idx+1}. ${chalk.yellow(display)}`)}),console.log("")),newValue=await inquirer.prompt([{type:"input",name:"value",message:"请输入站点列表,格式: id:备注(多个用逗号分隔):"}]),newValue.value?config.domainIdList=newValue.value.split(",").map(item=>{if((item=item.trim()).includes(":")){const[id,name]=item.split(":");return{id:id.trim(),name:name.trim()}}return{id:item}}).filter(zone=>""!==zone.id):config.domainIdList=[]);const{writeConfig}=await import("./commands/config.js");writeConfig(config),console.log(chalk.green("\n✅ 配置已更新\n"))}(config);break;case"remove":await async function(){const{confirm}=await inquirer.prompt([{type:"confirm",name:"confirm",message:"确定要删除配置文件吗?",default:!1}]);if(confirm){const fs=await import("fs"),path=await import("path"),os=await import("os"),CONFIG_FILE=path.join(os.homedir(),".edgeone-cli","config.json");fs.existsSync(CONFIG_FILE)&&(fs.unlinkSync(CONFIG_FILE),console.log(chalk.green("\n✅ 配置文件已删除\n")))}}()}}();break;case"purge":config?await async function(config){const actionAnswers=await inquirer.prompt([{type:"list",name:"type",message:"选择操作:",choices:[{name:"清除缓存",value:"purge"},{name:"查询历史",value:"history"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===actionAnswers.type)return;if("history"===actionAnswers.type)return void await async function(config){let zoneIds=[];if(!(config.domainIdList&&config.domainIdList.length>0))return void console.log(chalk.yellow("\n⚠️ 未配置站点列表,请使用 --zone 参数指定或在配置中添加\n"));{const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id,short:zone.name||zone.id}));zoneIds=(await inquirer.prompt([{type:"checkbox",name:"zones",message:"选择站点 (可多选):",choices:zoneChoices,validate:input=>input.length>0||"请至少选择一个站点"}])).zones}await async function(config,zoneIds){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n📋 清除缓存历史记录\n")),console.log(chalk.gray("ZoneIds: "+zoneIds.join(", "))));try{const result=await client.describePurgeTasks(zoneIds);if(result.Response?.Error)console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`);else{console.log(chalk.green("\n✅ 查询成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`);const tasks=result.Response?.Tasks||[];if(tasks.length>0){const{default:Table}=await import("cli-table3"),table=new Table({head:[chalk.gray("状态"),chalk.gray("清除地址"),chalk.gray("时间"),chalk.gray("类型")],colWidths:[8,50,30,8],chars:{mid:"","left-mid":"","mid-mid":"","right-mid":""}});tasks.forEach(task=>{const status="success"===task.Status?chalk.green("✓"):chalk.red("✗"),target=task.Target||"all",type="purge_url"===task.Type?"URL":"purge_prefix"===task.Type?"目录":"全部",createTime=task.CreateTime?task.CreateTime.replace("T"," ").replace("Z","").slice(0,19):"",displayTarget=target.length>47?target.slice(0,44)+"...":target;table.push([status,chalk.yellow(displayTarget),chalk.gray(createTime),type])}),console.log(chalk.cyan("\n📋 清除缓存记录:\n")),console.log(table.toString()),console.log(` 总计: ${chalk.yellow(result.Response?.TotalCount||tasks.length)} 条记录`)}else console.log(chalk.gray("\n 暂无清除记录\n"))}}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,zoneIds)}(config);const answers=await inquirer.prompt([{type:"list",name:"type",message:"选择清除类型:",choices:[{name:"清除全部缓存",value:"all"},{name:"清除指定目录缓存",value:"dir"},{name:"清除指定 URL 缓存",value:"url"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===answers.type)return;let targets=[],purgeType="purge_all",zoneId="*";if(config.domainIdList&&config.domainIdList.length>0){const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id})),zoneAnswers=await inquirer.prompt([{type:"list",name:"zone",message:"选择站点:",choices:["* (全部站点)",...zoneChoices]}]);"* (全部站点)"!==zoneAnswers.zone&&(zoneId=zoneAnswers.zone)}if("all"===answers.type){if(!(await inquirer.prompt([{type:"confirm",name:"confirm",message:`确认清除全部缓存? (Zone: ${zoneId})`,default:!1}])).confirm)return;purgeType="purge_all"}else if("dir"===answers.type){const dirAnswers=await inquirer.prompt([{type:"input",name:"dir",message:"请输入目录路径 (输入 :q 或按 Ctrl+C 返回):"}]);if(":q"===dirAnswers.dir||!dirAnswers.dir)return;targets=[dirAnswers.dir],purgeType="purge_prefix"}else if("url"===answers.type){const urlAnswers=await inquirer.prompt([{type:"input",name:"urls",message:"请输入 URL (多个用空格分隔, 输入 :q 或按 Ctrl+C 返回):"}]);if(":q"===urlAnswers.urls||!urlAnswers.urls)return;targets=urlAnswers.urls.split(/\s+/).filter(u=>u.trim()),purgeType="purge_url"}await async function(config,type,targets,zoneId){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔄 清除缓存任务\n")),console.log(chalk.gray("API 参数:")),console.log(` ZoneId: ${chalk.green(zoneId)}`),console.log(` Type: ${chalk.green(type)}`),targets.length>0&&console.log(` Targets: ${chalk.green(JSON.stringify(targets))}`),console.log(""));try{const result=await client.createPurgeTask({zoneId,type,targets});result.Response?.Error?(console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`)):(console.log(chalk.green("\n✅ 请求成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`),result.Response?.JobId&&console.log(` JobId: ${chalk.yellow(result.Response.JobId)}`))}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,purgeType,targets,zoneId)}(config):(console.log(chalk.yellow("\n⚠️ 请先初始化配置\n")),await initConfig());break;case"prefetch":config?await async function(config){const actionAnswers=await inquirer.prompt([{type:"list",name:"type",message:"选择操作:",choices:[{name:"内容预热",value:"prefetch"},{name:"查询历史",value:"history"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===actionAnswers.type)return;if("history"===actionAnswers.type)return void await async function(config){let zoneIds=[];if(!(config.domainIdList&&config.domainIdList.length>0))return void console.log(chalk.yellow("\n⚠️ 未配置站点列表,请使用 --zone 参数指定或在配置中添加\n"));{const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id,short:zone.name||zone.id}));zoneIds=(await inquirer.prompt([{type:"checkbox",name:"zones",message:"选择站点 (可多选):",choices:zoneChoices,validate:input=>input.length>0||"请至少选择一个站点"}])).zones}await async function(config,zoneIds){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n📋 预热任务历史记录\n")),console.log(chalk.gray("ZoneIds: "+zoneIds.join(", "))));try{const result=await client.describePrefetchTasks(zoneIds);if(result.Response?.Error)console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`);else{console.log(chalk.green("\n✅ 查询成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`);const tasks=result.Response?.PrefetchTasks||[];if(tasks.length>0){const{default:Table}=await import("cli-table3"),table=new Table({head:[chalk.gray("状态"),chalk.gray("预热地址"),chalk.gray("时间")],colWidths:[8,60,30],chars:{mid:"","left-mid":"","mid-mid":"","right-mid":""}});tasks.forEach(task=>{const status="success"===task.Status?chalk.green("✓"):"processing"===task.Status?chalk.yellow("⏳"):chalk.red("✗"),target=task.Target||"unknown",createTime=task.CreateTime?task.CreateTime.replace("T"," ").replace("Z","").slice(0,19):"",displayTarget=target.length>57?target.slice(0,54)+"...":target;table.push([status,chalk.yellow(displayTarget),chalk.gray(createTime)])}),console.log(chalk.cyan("\n📋 预热任务记录:\n")),console.log(table.toString()),console.log(` 总计: ${chalk.yellow(result.Response?.TotalCount||tasks.length)} 条记录`)}else console.log(chalk.gray("\n 暂无预热记录\n"))}}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,zoneIds)}(config);const answers=await inquirer.prompt([{type:"input",name:"urls",message:"请输入要预热的 URL (多个用空格分隔, 输入 :q 或按 Ctrl+C 返回):"}]);if(":q"===answers.urls||!answers.urls.trim())return;const urls=answers.urls.split(/\s+/).filter(u=>u.trim());let zoneId="*";if(config.domainIdList&&config.domainIdList.length>0){const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id})),zoneAnswers=await inquirer.prompt([{type:"list",name:"zone",message:"选择站点:",choices:["* (全部站点)",...zoneChoices]}]);"* (全部站点)"!==zoneAnswers.zone&&(zoneId=zoneAnswers.zone)}if(!(await inquirer.prompt([{type:"confirm",name:"confirm",message:`确认预热以下 URL?\n ${urls.join("\n ")}\n`,default:!0}])).confirm)return;await async function(config,urls,zoneId){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔥 预热任务\n")),console.log(chalk.gray("URL列表:")),urls.forEach(u=>console.log(` - ${chalk.yellow(u)}`)),console.log(`\nZone ID: ${chalk.green(zoneId)}`),console.log(""));try{const result=await client.createPrefetchTask({zoneId,urls});result.Response?.Error?(console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`)):(console.log(chalk.green("\n✅ 预热任务已提交!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`),result.Response?.JobId&&console.log(` JobId: ${chalk.yellow(result.Response.JobId)}`))}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,urls,zoneId)}(config):(console.log(chalk.yellow("\n⚠️ 请先初始化配置\n")),await initConfig());break;case"zone-status":config?await async function(config){if(!config.domainIdList||0===config.domainIdList.length)return console.log(chalk.yellow("\n⚠️ 未配置站点列表,请先在配置中添加站点\n")),void await pauseToContinue();const answers=await inquirer.prompt([{type:"list",name:"action",message:"站点状态管理:",choices:[{name:"🔍 查看站点状态",value:"view"},{name:"🔘 修改站点状态",value:"modify"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===answers.action)return;"view"===answers.action?await async function(config){const selectedZoneId=await selectZone(config,"选择要查看的站点:");if(!selectedZoneId)return;const selectedZone=config.domainIdList.find(z=>z.id===selectedZoneId),zoneDisplay=selectedZone?.name||selectedZoneId,client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔍 查看站点状态\n")),console.log(chalk.gray("API 参数:")),console.log(` Action: ${chalk.green("DescribeZones")}`),console.log(` ZoneIds: ${chalk.green([selectedZoneId])}`),console.log(""));try{const result=await client.describeZoneStatus({zoneId:selectedZoneId});if(result.Response?.Error)console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`);else{console.log(chalk.green("\n✅ 查询成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`);const zones=result.Response?.Zones||[];if(zones.length>0){const zone=zones[0],paused=zone.Paused,statusText=paused?"关闭":"开启",statusColor=paused?chalk.red:chalk.green;let accessType="未知";!zone.NSDetail||zone.CNAMEDetail||zone.DNSPodDetail?!zone.CNAMEDetail||zone.NSDetail||zone.DNSPodDetail?!zone.DNSPodDetail||zone.NSDetail||zone.CNAMEDetail||(accessType="DNSPod"):accessType="CNAME":accessType="NS";const nameServers=zone.NameServers||[],dnsServers=nameServers.length>0?nameServers.join(", "):"无",area={global:"全球加速",mainland:"中国大陆",overseas:"境外"}[zone.Area]||zone.Area||"未知";console.log(chalk.cyan("\n📋 站点状态:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` 站点名称: ${chalk.yellow(zoneDisplay)}`),console.log(` 站点ID: ${chalk.yellow(selectedZoneId)}`),console.log(` 状态: ${statusColor(statusText)} (${paused})`),console.log(chalk.gray("─".repeat(40))),console.log(` 接入方式: ${chalk.yellow(accessType)}`),console.log(` DNS服务器: ${chalk.yellow(dnsServers)}`),console.log(` 加速区域: ${chalk.yellow(area)}`),console.log(chalk.gray("─".repeat(40)))}else console.log(chalk.gray("\n 未找到站点信息\n"))}}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config):"modify"===answers.action&&await async function(config){const selectedZoneId=await selectZone(config,"选择要修改的站点:");if(!selectedZoneId)return;const selectedZone=config.domainIdList.find(z=>z.id===selectedZoneId),zoneDisplay=selectedZone?.name||selectedZoneId,statusAnswers=await inquirer.prompt([{type:"list",name:"paused",message:`选择站点状态 (${zoneDisplay}):`,choices:[{name:"开启 (Paused: false)",value:!1},{name:"关闭 (Paused: true)",value:!0},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===statusAnswers.paused)return;const paused=statusAnswers.paused,statusText=paused?"关闭":"开启";if(!(await inquirer.prompt([{type:"confirm",name:"confirm",message:`确认将站点 ${zoneDisplay} 设置为 ${statusText}?`,default:!0}])).confirm)return;await async function(config,zoneId,paused,statusText){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔘 修改站点状态\n")),console.log(chalk.gray("API 参数:")),console.log(` Action: ${chalk.green("ModifyZoneStatus")}`),console.log(` ZoneId: ${chalk.green(zoneId)}`),console.log(` Paused: ${chalk.green(paused)}`),console.log(""));try{const result=await client.modifyZoneStatus({zoneId,paused});result.Response?.Error?(console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`)):(console.log(chalk.green("\n✅ 站点状态已更新!")),console.log(` 状态: ${chalk.yellow(statusText)}`),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`))}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,selectedZoneId,paused,statusText)}(config)}(config):(console.log(chalk.yellow("\n⚠️ 请先初始化配置\n")),await initConfig())}}async function initConfig(){const existingConfig=readConfig();if(existingConfig){const{overwrite}=await inquirer.prompt([{type:"confirm",name:"overwrite",message:"配置已存在,是否覆盖?",default:!1}]);if(!overwrite)return}const defaultDomainList=existingConfig?.domainIdList?existingConfig.domainIdList.map(z=>z.name?`${z.id}:${z.name}`:z.id).join(", "):"",answers=await inquirer.prompt([{type:"input",name:"secretId",message:"请输入 SecretId:",default:existingConfig?.secretId||"",validate:input=>!!input.trim()||"SecretId 不能为空"},{type:"password",name:"secretKey",message:"请输入 SecretKey:",mask:"*",validate:input=>!!input.trim()||"SecretKey 不能为空"},{type:"input",name:"endpoint",message:"请输入接口请求域名:",default:existingConfig?.endpoint||"teo.tencentcloudapi.com"},{type:"list",name:"mode",message:"请选择运行模式:",choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}],default:existingConfig?.mode||"production"},{type:"input",name:"domainIdList",message:"请输入站点列表,格式: id:备注(多个用逗号分隔,留空跳过):",default:defaultDomainList}]),{writeConfig}=await import("./commands/config.js");let domainIdList=[];answers.domainIdList&&answers.domainIdList.trim()&&(domainIdList=answers.domainIdList.split(",").map(item=>{if((item=item.trim()).includes(":")){const[id,name]=item.split(":");return{id:id.trim(),name:name.trim()}}return{id:item}}).filter(zone=>""!==zone.id)),writeConfig({secretId:answers.secretId,secretKey:answers.secretKey,endpoint:answers.endpoint,mode:answers.mode,domainIdList});const action=existingConfig?"更新":"保存";console.log(chalk.green(`\n✅ 配置已${action}\n`))}function maskString(str,showLength=4){return str?str.length<=2*showLength?str:str.slice(0,showLength)+"****"+str.slice(-showLength):"N/A"}async function selectZone(config,message){const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id})),zoneAnswers=await inquirer.prompt([{type:"list",name:"zone",message,choices:[...zoneChoices,new inquirer.Separator,{name:"← 返回",value:"back"}]}]);return"back"===zoneAnswers.zone?null:zoneAnswers.zone}
1
+ import chalk from"chalk";import inquirer from"inquirer";import{EdgeOneClient}from"./api/client.js";import{readConfig}from"./commands/config.js";async function pauseToContinue(){await inquirer.prompt([{type:"input",name:"continue",message:"按 Enter 键返回..."}])}function showBanner(){console.log(""),console.log(chalk.cyan("╔════════════════════════════════════╗")),console.log(chalk.cyan("║")+" "+chalk.white.bold("EdgeOne CLI")+" "+chalk.cyan("║")),console.log(chalk.cyan("║")+" "+chalk.gray("本地化 EdgeOne 服务管理工具")+" "+chalk.cyan("║")),console.log(chalk.cyan("╚════════════════════════════════════╝")),console.log("")}export async function startInteractive(){readConfig()||(showBanner(),await initConfig()),await async function(){for(;;){console.clear(),showBanner();const answers=await inquirer.prompt([{type:"list",name:"action",message:"请选择操作:",choices:[{name:"🔓 配置管理",value:"config"},{name:"🧹 清除缓存",value:"purge"},{name:"🚀 内容预热",value:"prefetch"},{name:"🌐 站点状态",value:"zone-status"},new inquirer.Separator("─────────────────"),{name:"❌ 退出",value:"exit"}],pageSize:10}]);"exit"===answers.action&&(console.log(chalk.gray("\n👋 再见!\n")),process.exit(0)),answers.action&&await handleAction(answers.action)}}()}async function handleAction(action){const config=readConfig();switch(action){case"config":await async function(){const answers=await inquirer.prompt([{type:"list",name:"action",message:"配置管理:",choices:[{name:"查看配置",value:"show"},{name:"编辑配置",value:"edit"},{name:"删除配置",value:"remove"},{name:"初始化配置",value:"init"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===answers.action)return;if("init"===answers.action)return void await initConfig();const config=readConfig();if(!config)return void console.log(chalk.yellow("\n⚠️ 配置不存在,请先初始化\n"));const{EdgeOneClient}=await import("./api/client.js");new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode);switch(answers.action){case"show":await async function(config){const modeText="debug"===config.mode?"调试模式":"生产模式",modeColor="debug"===config.mode?chalk.yellow:chalk.green;console.log(chalk.cyan("\n📋 当前配置:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` SecretId: ${chalk.green(maskString(config.secretId))}`),console.log(` SecretKey: ${chalk.green(maskString(config.secretKey))}`),console.log(` 接口请求域名: ${chalk.yellow(config.endpoint||"teo.tencentcloudapi.com")}`),console.log(` 运行模式: ${modeColor(modeText)}`),config.domainIdList&&config.domainIdList.length>0&&(console.log(" 站点列表:"),config.domainIdList.forEach((zone,idx)=>{const display=zone.name?`${zone.name} (${zone.id})`:zone.id;console.log(` ${idx+1}. ${chalk.yellow(display)}`)}));console.log(chalk.gray("─".repeat(40))),console.log(""),await pauseToContinue()}(config);break;case"edit":await async function(config){const answers=await inquirer.prompt([{type:"list",name:"action",message:"选择要修改的配置项:",choices:[{name:"SecretId",value:"secretId"},{name:"SecretKey",value:"secretKey"},{name:"接口请求域名",value:"endpoint"},{name:"运行模式",value:"mode"},{name:"站点列表",value:"domainIdList"}]}]);let newValue;"secretId"===answers.action?(newValue=await inquirer.prompt([{type:"input",name:"value",message:"请输入新的 SecretId:",validate:i=>i.trim()||"不能为空"}]),config.secretId=newValue.value):"secretKey"===answers.action?(newValue=await inquirer.prompt([{type:"password",name:"value",message:"请输入新的 SecretKey:",mask:"*",validate:i=>i.trim()||"不能为空"}]),config.secretKey=newValue.value):"endpoint"===answers.action?(newValue=await inquirer.prompt([{type:"input",name:"value",message:"请输入新的接口请求域名:"}]),config.endpoint=newValue.value):"mode"===answers.action?(newValue=await inquirer.prompt([{type:"list",name:"value",message:"请选择运行模式:",choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}]}]),config.mode=newValue.value):"domainIdList"===answers.action&&(config.domainIdList&&config.domainIdList.length>0&&(console.log(chalk.gray("\n当前站点列表:")),config.domainIdList.forEach((zone,idx)=>{const display=zone.name?`${zone.name} (${zone.id})`:zone.id;console.log(` ${idx+1}. ${chalk.yellow(display)}`)}),console.log("")),newValue=await inquirer.prompt([{type:"input",name:"value",message:"请输入站点列表,格式: id:备注(多个用逗号分隔):"}]),newValue.value?config.domainIdList=newValue.value.split(",").map(item=>{if((item=item.trim()).includes(":")){const firstColonIndex=item.indexOf(":");return{id:item.slice(0,firstColonIndex).trim(),name:item.slice(firstColonIndex+1).trim()}}return{id:item}}).filter(zone=>""!==zone.id):config.domainIdList=[]);const{writeConfig}=await import("./commands/config.js");writeConfig(config),console.log(chalk.green("\n✅ 配置已更新\n"))}(config);break;case"remove":await async function(){const{confirm}=await inquirer.prompt([{type:"confirm",name:"confirm",message:"确定要删除配置文件吗?",default:!1}]);if(confirm){const fs=await import("fs"),path=await import("path"),os=await import("os"),CONFIG_FILE=path.join(os.homedir(),".edgeone-cli","config.json");fs.existsSync(CONFIG_FILE)&&(fs.unlinkSync(CONFIG_FILE),console.log(chalk.green("\n✅ 配置文件已删除\n")))}}()}}();break;case"purge":config?await async function(config){const actionAnswers=await inquirer.prompt([{type:"list",name:"type",message:"选择操作:",choices:[{name:"清除缓存",value:"purge"},{name:"查询历史",value:"history"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===actionAnswers.type)return;if("history"===actionAnswers.type)return void await async function(config){let zoneIds=[];if(!(config.domainIdList&&config.domainIdList.length>0))return void console.log(chalk.yellow("\n⚠️ 未配置站点列表,请使用 --zone 参数指定或在配置中添加\n"));{const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id,short:zone.name||zone.id}));zoneIds=(await inquirer.prompt([{type:"checkbox",name:"zones",message:"选择站点 (可多选):",choices:zoneChoices,validate:input=>input.length>0||"请至少选择一个站点"}])).zones}await async function(config,zoneIds){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n📋 清除缓存历史记录\n")),console.log(chalk.gray("ZoneIds: "+zoneIds.join(", "))));try{const result=await client.describePurgeTasks(zoneIds);if(result.Response?.Error)console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`);else{console.log(chalk.green("\n✅ 查询成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`);const tasks=result.Response?.Tasks||[];if(tasks.length>0){const{default:Table}=await import("cli-table3"),table=new Table({head:[chalk.gray("状态"),chalk.gray("清除地址"),chalk.gray("时间"),chalk.gray("类型")],colWidths:[8,50,30,8],chars:{mid:"","left-mid":"","mid-mid":"","right-mid":""}});tasks.forEach(task=>{const status="success"===task.Status?chalk.green("✓"):chalk.red("✗"),target=task.Target||"all",type="purge_url"===task.Type?"URL":"purge_prefix"===task.Type?"目录":"全部",createTime=task.CreateTime?task.CreateTime.replace("T"," ").replace("Z","").slice(0,19):"",displayTarget=target.length>47?target.slice(0,44)+"...":target;table.push([status,chalk.yellow(displayTarget),chalk.gray(createTime),type])}),console.log(chalk.cyan("\n📋 清除缓存记录:\n")),console.log(table.toString()),console.log(` 总计: ${chalk.yellow(result.Response?.TotalCount||tasks.length)} 条记录`)}else console.log(chalk.gray("\n 暂无清除记录\n"))}}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,zoneIds)}(config);const answers=await inquirer.prompt([{type:"list",name:"type",message:"选择清除类型:",choices:[{name:"清除全部缓存",value:"all"},{name:"清除指定目录缓存",value:"dir"},{name:"清除指定 URL 缓存",value:"url"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===answers.type)return;let targets=[],purgeType="purge_all",zoneId="*";if(config.domainIdList&&config.domainIdList.length>0){const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id})),zoneAnswers=await inquirer.prompt([{type:"list",name:"zone",message:"选择站点:",choices:["* (全部站点)",...zoneChoices]}]);"* (全部站点)"!==zoneAnswers.zone&&(zoneId=zoneAnswers.zone)}if("all"===answers.type){if(!(await inquirer.prompt([{type:"confirm",name:"confirm",message:`确认清除全部缓存? (Zone: ${zoneId})`,default:!1}])).confirm)return;purgeType="purge_all"}else if("dir"===answers.type){const dirAnswers=await inquirer.prompt([{type:"input",name:"dir",message:"请输入目录路径 (输入 :q 或按 Ctrl+C 返回):"}]);if(":q"===dirAnswers.dir||!dirAnswers.dir)return;targets=[dirAnswers.dir],purgeType="purge_prefix"}else if("url"===answers.type){const urlAnswers=await inquirer.prompt([{type:"input",name:"urls",message:"请输入 URL (多个用空格分隔, 输入 :q 或按 Ctrl+C 返回):"}]);if(":q"===urlAnswers.urls||!urlAnswers.urls)return;targets=urlAnswers.urls.split(/\s+/).filter(u=>u.trim()),purgeType="purge_url"}await async function(config,type,targets,zoneId){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔄 清除缓存任务\n")),console.log(chalk.gray("API 参数:")),console.log(` ZoneId: ${chalk.green(zoneId)}`),console.log(` Type: ${chalk.green(type)}`),targets.length>0&&console.log(` Targets: ${chalk.green(JSON.stringify(targets))}`),console.log(""));try{const result=await client.createPurgeTask({zoneId,type,targets});result.Response?.Error?(console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`)):(console.log(chalk.green("\n✅ 请求成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`),result.Response?.JobId&&console.log(` JobId: ${chalk.yellow(result.Response.JobId)}`))}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,purgeType,targets,zoneId)}(config):(console.log(chalk.yellow("\n⚠️ 请先初始化配置\n")),await initConfig());break;case"prefetch":config?await async function(config){const actionAnswers=await inquirer.prompt([{type:"list",name:"type",message:"选择操作:",choices:[{name:"内容预热",value:"prefetch"},{name:"查询历史",value:"history"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===actionAnswers.type)return;if("history"===actionAnswers.type)return void await async function(config){let zoneIds=[];if(!(config.domainIdList&&config.domainIdList.length>0))return void console.log(chalk.yellow("\n⚠️ 未配置站点列表,请使用 --zone 参数指定或在配置中添加\n"));{const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id,short:zone.name||zone.id}));zoneIds=(await inquirer.prompt([{type:"checkbox",name:"zones",message:"选择站点 (可多选):",choices:zoneChoices,validate:input=>input.length>0||"请至少选择一个站点"}])).zones}await async function(config,zoneIds){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n📋 预热任务历史记录\n")),console.log(chalk.gray("ZoneIds: "+zoneIds.join(", "))));try{const result=await client.describePrefetchTasks(zoneIds);if(result.Response?.Error)console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`);else{console.log(chalk.green("\n✅ 查询成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`);const tasks=result.Response?.PrefetchTasks||[];if(tasks.length>0){const{default:Table}=await import("cli-table3"),table=new Table({head:[chalk.gray("状态"),chalk.gray("预热地址"),chalk.gray("时间")],colWidths:[8,60,30],chars:{mid:"","left-mid":"","mid-mid":"","right-mid":""}});tasks.forEach(task=>{const status="success"===task.Status?chalk.green("✓"):"processing"===task.Status?chalk.yellow("⏳"):chalk.red("✗"),target=task.Target||"unknown",createTime=task.CreateTime?task.CreateTime.replace("T"," ").replace("Z","").slice(0,19):"",displayTarget=target.length>57?target.slice(0,54)+"...":target;table.push([status,chalk.yellow(displayTarget),chalk.gray(createTime)])}),console.log(chalk.cyan("\n📋 预热任务记录:\n")),console.log(table.toString()),console.log(` 总计: ${chalk.yellow(result.Response?.TotalCount||tasks.length)} 条记录`)}else console.log(chalk.gray("\n 暂无预热记录\n"))}}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,zoneIds)}(config);const answers=await inquirer.prompt([{type:"input",name:"urls",message:"请输入要预热的 URL (多个用空格分隔, 输入 :q 或按 Ctrl+C 返回):"}]);if(":q"===answers.urls||!answers.urls.trim())return;const urls=answers.urls.split(/\s+/).filter(u=>u.trim());let zoneId="*";if(config.domainIdList&&config.domainIdList.length>0){const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id})),zoneAnswers=await inquirer.prompt([{type:"list",name:"zone",message:"选择站点:",choices:["* (全部站点)",...zoneChoices]}]);"* (全部站点)"!==zoneAnswers.zone&&(zoneId=zoneAnswers.zone)}if(!(await inquirer.prompt([{type:"confirm",name:"confirm",message:`确认预热以下 URL?\n ${urls.join("\n ")}\n`,default:!0}])).confirm)return;await async function(config,urls,zoneId){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔥 预热任务\n")),console.log(chalk.gray("URL列表:")),urls.forEach(u=>console.log(` - ${chalk.yellow(u)}`)),console.log(`\nZone ID: ${chalk.green(zoneId)}`),console.log(""));try{const result=await client.createPrefetchTask({zoneId,urls});result.Response?.Error?(console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`)):(console.log(chalk.green("\n✅ 预热任务已提交!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`),result.Response?.JobId&&console.log(` JobId: ${chalk.yellow(result.Response.JobId)}`))}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,urls,zoneId)}(config):(console.log(chalk.yellow("\n⚠️ 请先初始化配置\n")),await initConfig());break;case"zone-status":config?await async function(config){if(!config.domainIdList||0===config.domainIdList.length)return console.log(chalk.yellow("\n⚠️ 未配置站点列表,请先在配置中添加站点\n")),void await pauseToContinue();const answers=await inquirer.prompt([{type:"list",name:"action",message:"站点状态管理:",choices:[{name:"🔍 查看站点状态",value:"view"},{name:"🔘 修改站点状态",value:"modify"},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===answers.action)return;"view"===answers.action?await async function(config){const selectedZoneId=await selectZone(config,"选择要查看的站点:");if(!selectedZoneId)return;const selectedZone=config.domainIdList.find(z=>z.id===selectedZoneId),zoneDisplay=selectedZone?.name||selectedZoneId,client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔍 查看站点状态\n")),console.log(chalk.gray("API 参数:")),console.log(` Action: ${chalk.green("DescribeZones")}`),console.log(` ZoneIds: ${chalk.green([selectedZoneId])}`),console.log(""));try{const result=await client.describeZoneStatus({zoneId:selectedZoneId});if(result.Response?.Error)console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`);else{console.log(chalk.green("\n✅ 查询成功!")),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`);const zones=result.Response?.Zones||[];if(zones.length>0){const zone=zones[0],paused=zone.Paused,statusText=paused?"关闭":"开启",statusColor=paused?chalk.red:chalk.green;let accessType="未知";!zone.NSDetail||zone.CNAMEDetail||zone.DNSPodDetail?!zone.CNAMEDetail||zone.NSDetail||zone.DNSPodDetail?!zone.DNSPodDetail||zone.NSDetail||zone.CNAMEDetail||(accessType="DNSPod"):accessType="CNAME":accessType="NS";const nameServers=zone.NameServers||[],dnsServers=nameServers.length>0?nameServers.join(", "):"无",area={global:"全球加速",mainland:"中国大陆",overseas:"境外"}[zone.Area]||zone.Area||"未知";console.log(chalk.cyan("\n📋 站点状态:\n")),console.log(chalk.gray("─".repeat(40))),console.log(` 站点名称: ${chalk.yellow(zoneDisplay)}`),console.log(` 站点ID: ${chalk.yellow(selectedZoneId)}`),console.log(` 状态: ${statusColor(statusText)} (${paused})`),console.log(chalk.gray("─".repeat(40))),console.log(` 接入方式: ${chalk.yellow(accessType)}`),console.log(` DNS服务器: ${chalk.yellow(dnsServers)}`),console.log(` 加速区域: ${chalk.yellow(area)}`),console.log(chalk.gray("─".repeat(40)))}else console.log(chalk.gray("\n 未找到站点信息\n"))}}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config):"modify"===answers.action&&await async function(config){const selectedZoneId=await selectZone(config,"选择要修改的站点:");if(!selectedZoneId)return;const selectedZone=config.domainIdList.find(z=>z.id===selectedZoneId),zoneDisplay=selectedZone?.name||selectedZoneId,statusAnswers=await inquirer.prompt([{type:"list",name:"paused",message:`选择站点状态 (${zoneDisplay}):`,choices:[{name:"开启 (Paused: false)",value:!1},{name:"关闭 (Paused: true)",value:!0},new inquirer.Separator,{name:"← 返回",value:"back"}]}]);if("back"===statusAnswers.paused)return;const paused=statusAnswers.paused,statusText=paused?"关闭":"开启";if(!(await inquirer.prompt([{type:"confirm",name:"confirm",message:`确认将站点 ${zoneDisplay} 设置为 ${statusText}?`,default:!0}])).confirm)return;await async function(config,zoneId,paused,statusText){const client=new EdgeOneClient(config.secretId,config.secretKey,config.endpoint||"teo.tencentcloudapi.com","ap-guangzhou",config.mode),isDebug="debug"===config.mode;isDebug&&(console.log(chalk.cyan("\n🔘 修改站点状态\n")),console.log(chalk.gray("API 参数:")),console.log(` Action: ${chalk.green("ModifyZoneStatus")}`),console.log(` ZoneId: ${chalk.green(zoneId)}`),console.log(` Paused: ${chalk.green(paused)}`),console.log(""));try{const result=await client.modifyZoneStatus({zoneId,paused});result.Response?.Error?(console.log(chalk.red("\n❌ 请求失败:")),console.log(` 错误码: ${chalk.yellow(result.Response.Error.Code)}`),console.log(` 错误信息: ${chalk.yellow(result.Response.Error.Message)}`)):(console.log(chalk.green("\n✅ 站点状态已更新!")),console.log(` 状态: ${chalk.yellow(statusText)}`),console.log(` RequestId: ${chalk.yellow(result.Response?.RequestId)}`))}catch(error){console.log(chalk.red("\n❌ 请求异常:")),console.log(` ${error.message}`)}console.log(""),await pauseToContinue()}(config,selectedZoneId,paused,statusText)}(config)}(config):(console.log(chalk.yellow("\n⚠️ 请先初始化配置\n")),await initConfig())}}async function initConfig(){const existingConfig=readConfig();if(existingConfig){const{overwrite}=await inquirer.prompt([{type:"confirm",name:"overwrite",message:"配置已存在,是否覆盖?",default:!1}]);if(!overwrite)return}const defaultDomainList=existingConfig?.domainIdList?existingConfig.domainIdList.map(z=>z.name?`${z.id}:${z.name}`:z.id).join(", "):"",answers=await inquirer.prompt([{type:"input",name:"secretId",message:"请输入 SecretId:",default:existingConfig?.secretId||"",validate:input=>!!input.trim()||"SecretId 不能为空"},{type:"password",name:"secretKey",message:"请输入 SecretKey:",mask:"*",validate:input=>!!input.trim()||"SecretKey 不能为空"},{type:"input",name:"endpoint",message:"请输入接口请求域名:",default:existingConfig?.endpoint||"teo.tencentcloudapi.com"},{type:"list",name:"mode",message:"请选择运行模式:",choices:[{name:"生产模式 (不显示调试信息)",value:"production"},{name:"调试模式 (显示详细请求信息)",value:"debug"}],default:existingConfig?.mode||"production"},{type:"input",name:"domainIdList",message:"请输入站点列表,格式: id:备注(多个用逗号分隔,留空跳过):",default:defaultDomainList}]),{writeConfig}=await import("./commands/config.js");let domainIdList=[];answers.domainIdList&&answers.domainIdList.trim()&&(domainIdList=answers.domainIdList.split(",").map(item=>{if((item=item.trim()).includes(":")){const firstColonIndex=item.indexOf(":");return{id:item.slice(0,firstColonIndex).trim(),name:item.slice(firstColonIndex+1).trim()}}return{id:item}}).filter(zone=>""!==zone.id)),writeConfig({secretId:answers.secretId,secretKey:answers.secretKey,endpoint:answers.endpoint,mode:answers.mode,domainIdList});const action=existingConfig?"更新":"保存";console.log(chalk.green(`\n✅ 配置已${action}\n`))}function maskString(str,showLength=4){return str?str.length<=2*showLength?str:str.slice(0,showLength)+"****"+str.slice(-showLength):"N/A"}async function selectZone(config,message){const zoneChoices=config.domainIdList.map(zone=>({name:zone.name||zone.id,value:zone.id})),zoneAnswers=await inquirer.prompt([{type:"list",name:"zone",message,choices:[...zoneChoices,new inquirer.Separator,{name:"← 返回",value:"back"}]}]);return"back"===zoneAnswers.zone?null:zoneAnswers.zone}
package/package.json CHANGED
@@ -1,10 +1,9 @@
1
1
  {
2
2
  "name": "edgeone-cli",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "description": "EdgeOne CLI - 本地化 EdgeOne 服务管理工具",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
7
  "bin": {
9
8
  "edgeone-cli": "dist/index.js"
10
9
  },