phala 0.0.1-alpha-9 → 0.0.1-alpha-10

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.
package/dist/index.js CHANGED
@@ -111,7 +111,7 @@ Operation completed. Full log available at: ${p}`),i()):a(new Error(`Process exi
111
111
 
112
112
  Useful commands:`),o.info(`- View logs: docker logs -f ${i}`),o.info(`- Stop simulator: docker stop ${i}
113
113
  `),Ue(`http://localhost:${r}`),!0}catch(n){return o.error(`Failed to run TEE simulator: ${n instanceof Error?n.message:String(n)}`),!1}}async stopSimulator(){try{let e=o.startSpinner("Stopping TEE simulator...");return await de("docker stop tee-simulator"),await K(),e.stop(!0,"TEE simulator stopped successfully"),!0}catch(e){return o.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),!1}}static async listLocalImages(){try{let{stdout:e}=await de('docker images --format "{{.Repository}}:{{.Tag}}"'),n=(await O())?.username;return e.split(`
114
- `).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${n}/`)).map(a=>{let[c,p]=a.split(":"),u=c.split("/");return{name:u.length>1?u[1]:c,tag:p}})}catch(e){return o.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import Ft from"prompts";var It=new no().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async t=>{try{let e=t.username,r=t.password,n=t.registry;if(!e){o.info("First we need your Docker Hub username to check if you are already logged in.");let p=await Ft({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:u=>u.length>0?!0:"Username cannot be empty"});p.username||(o.error("Username is required"),process.exit(1)),e=p.username}let i=new _("",e,n);if(await i.login(e)){o.success(`${e} is logged in to Docker Hub`);return}if(!r){let p=await Ft({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:u=>u.length>0?!0:"Password cannot be empty"});p.password||(o.error("Password is required"),process.exit(1)),r=p.password}await i.login(e,r,n)||(o.error("Failed to login to Docker Hub"),process.exit(1)),await et({username:e,registry:n||null}),o.success("Logged in to Docker Hub successfully")}catch(e){o.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as io}from"commander";import Rt from"path";import Mt from"inquirer";import so from"fs";var Vt=new io().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async t=>{try{let e=await O();if(e||(o.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let c=await Mt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:p=>p.trim()?!0:"Image name is required"}]);t.image=c.image}if(!t.tag){let c=await Mt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:p=>p.trim()?!0:"Tag is required"}]);t.tag=c.tag}let r=Rt.resolve(process.cwd(),t.file);so.existsSync(r)||(o.info(`Default Dockerfile not found at ${r}`),t.file=await G("Enter the path to your Dockerfile:","Dockerfile","file"));let n=Rt.resolve(process.cwd(),t.file);await new _(t.image,e.username,e.registry).buildImage(n,t.tag)||(o.error("Failed to build Docker image"),process.exit(1)),o.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){o.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as ao}from"commander";import Lt from"inquirer";var Nt=new ao().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").action(async t=>{try{let e=await O();e||(o.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let r=t.image,n=t.tag;if(!r||!n){let c=await _.listLocalImages();if(c.length===0&&(o.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!r){let p=Array.from(new Set(c.map(d=>d.name))),{selectedImage:u}=await Lt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:p}]);r=u}if(!n){let p=c.filter(d=>d.name===r).map(d=>d.tag);p.length===0&&(o.error(`No tags found for image ${r}`),process.exit(1));let{selectedTag:u}=await Lt.prompt([{type:"list",name:"selectedTag",message:`Select a tag for ${r}:`,choices:p}]);n=u}}await new _(r,e.username,e.registry).pushImage(n)||(o.error("Failed to push Docker image"),process.exit(1)),o.success(`Docker image ${e.username}/${r}:${n} pushed successfully`)}catch(e){o.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as co}from"commander";import Ee from"inquirer";import Ot from"fs";import Ut from"path";var zt=new co().name("run").description("Run a Docker Compose setup").option("-c, --compose <compose>","Path to docker-compose.yml file").option("-e, --env-file <env-file>","Path to environment variables file").option("--skip-env","Skip environment variables file prompt",!0).action(async t=>{try{let e=t.compose,r=t.env;if(e)try{R(e)}catch{o.error(`File not found: ${e}`),process.exit(1)}else{let a=Ut.join(process.cwd(),"docker-compose.yml");if(Ot.existsSync(a)){let{useDefault:p}=await Ee.prompt([{type:"confirm",name:"useDefault",message:"Use docker-compose.yml in current directory?",default:!0}]);p&&(e=a)}if(!e){let{composePath:p}=await Ee.prompt([{type:"input",name:"composePath",message:"Enter path to docker-compose.yml file:",validate:u=>R(u)?!0:"File not found"}]);e=p}}if(!r&&!t.skipEnv){let a=Ut.join(process.cwd(),".env");if(Ot.existsSync(a)){let{useDefault:p}=await Ee.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);p&&(r=a)}if(!r){let{envPath:p}=await Ee.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:u=>{try{return R(u),!0}catch{return`File not found: ${u}`}}}]);r=p}}let n=new _("");if(r){try{R(r)}catch{o.error(`File not found: ${r}`),process.exit(1)}o.info(`Running Docker Compose with compose file: ${e} and env file: ${r}`)}else o.info(`Running Docker Compose with compose file: ${e} without env file`);await n.runComposeLocally(e,r)||(o.error("Failed to run Docker Compose"),process.exit(1)),o.success("Docker Compose is running")}catch(e){o.error(`Failed to run Docker Compose: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as mo}from"commander";import M from"inquirer";import fe from"fs";import xe from"path";var jt=new mo().name("generate").description("Generate a Docker Compose file").option("-i, --image <image>","Docker image name to use in the compose file").option("-t, --tag <tag>","Docker image tag to use in the compose file").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").option("--manual","Skip automatic image detection and enter image/tag manually").action(async t=>{try{let e=await O();(!e||!e.username)&&(o.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let r=t.image||"",n=t.tag||"";if((!r||!n)&&!t.manual)try{o.info("Detecting local Docker images...");let u=await _.listLocalImages();if(u.length===0)o.warn("No local Docker images found. You will need to enter image details manually.");else{let d=new Map;if(u.forEach(v=>{d.has(v.name)||d.set(v.name,[]),d.get(v.name)?.push(v.tag)}),r&&!n){let v=d.get(r)||[];if(v.length>0){let{imageTag:y}=await M.prompt([{type:"list",name:"imageTag",message:`Select a tag for ${r}:`,choices:[...v,new M.Separator,"[ Enter manually ]"]}]);y!=="[ Enter manually ]"&&(n=y)}else o.warn(`No tags found for image ${r}. You will need to enter the tag manually.`)}else if(!r){let v=Array.from(d.keys()),{imageName:y}=await M.prompt([{type:"list",name:"imageName",message:"Select a Docker image:",choices:[...v,new M.Separator,"[ Enter manually ]"]}]);if(y!=="[ Enter manually ]"){r=y;let m=d.get(y)||[],{imageTag:l}=await M.prompt([{type:"list",name:"imageTag",message:"Select a tag:",choices:[...m,new M.Separator,"[ Enter manually ]"]}]);l!=="[ Enter manually ]"&&(n=l)}}}}catch(u){o.warn(`Failed to detect local images: ${u instanceof Error?u.message:String(u)}`),o.info("Continuing with manual input...")}if(!r){let{inputImage:u}=await M.prompt([{type:"input",name:"inputImage",message:"Enter Docker image name:",validate:d=>d.trim()?!0:"Image name cannot be empty"}]);r=u}if(!n){let{inputTag:u}=await M.prompt([{type:"input",name:"inputTag",message:`Enter tag for image ${r}:`,validate:d=>d.trim()?!0:"Tag cannot be empty"}]);n=u}let i=t.envFile;if(i)try{R(i)}catch{o.error(`File not found: ${i}`),process.exit(1)}else{let u=xe.join(process.cwd(),".env");if(fe.existsSync(u)){let{useDefault:v}=await M.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);v&&(i=u)}if(!i){let{envPath:v}=await M.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:y=>{try{return R(y),!0}catch{return`File not found: ${y}`}}}]);i=v}}let a=t.output;if(!a&&(a=xe.join(process.cwd(),"docker-compose.yml"),fe.existsSync(a))){let{confirmOverwrite:u}=await M.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${a} already exists. Overwrite?`,default:!1}]);if(!u){let{customPath:d}=await M.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:xe.join(process.cwd(),"docker-generated-compose.yml")}]);a=d}}let c=new _(r,e.username,e.registry);i?o.info(`Generating Docker Compose file for ${r}:${n} using env file: ${i}`):o.info(`Generating Docker Compose file for ${r}:${n} without env file`);let p=await c.buildComposeFile(n,i,t.template);if(p!==a){let u=xe.dirname(a);fe.existsSync(u)||(o.info(`Creating directory: ${u}`),fe.mkdirSync(u,{recursive:!0})),fe.copyFileSync(p,a)}o.success(`Docker Compose file generated successfully: ${a}`)}catch(e){o.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Wt=new lo().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(It).addCommand(Vt).addCommand(zt).addCommand(Nt).addCommand(jt);import{Command as fo}from"commander";import{Command as po}from"commander";var Bt=new po().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",ot).option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{if(t.type==="docker")await new _("").runSimulator(t.image,t.port)||(o.error("Failed to start TEE simulator"),process.exit(1));else if(t.type==="native")if(xt()||await _t(),await Se()){o.success("TEE simulator is already running");return}else{let r=$t();o.success("TEE simulator started successfully")}else o.error("Invalid simulator type"),process.exit(1)}catch(e){o.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as uo}from"commander";var Gt=new uo().name("stop").description("Stop the TEE simulator").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{t.type==="docker"?await new _("").stopSimulator()||(o.error("Failed to stop TEE simulator"),process.exit(1)):t.type==="native"?await Tt()||(o.error("Failed to stop TEE simulator"),process.exit(1)):(o.error("Invalid simulator type"),process.exit(1))}catch(e){o.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Kt=new fo().name("simulator").description("TEE simulator commands").addCommand(Bt).addCommand(Gt);import{Command as Fo}from"commander";import{Command as ho}from"commander";import go from"inquirer";import{z as Ht}from"zod";async function _e(){try{let t=await $.get(x.CVMS(0));return Ht.array(Me).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function T(t){let r=(await _e()).find(n=>n.hosted?.app_id===t||`app_${n.hosted?.app_id}`===t);if(!r)o.error(`CVM with App ID ${t} not detected`),process.exit(1);else return o.success(`CVM with App ID ${t} detected`),r.hosted?.app_id}async function te(t){try{let e=await $.get(x.CVM_BY_APP_ID(t));return dt.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function qt(t){try{let e=await $.post(x.CVM_PUBKEY,t);return ut.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Zt(t){try{let e=await $.post(x.CVM_FROM_CONFIGURATION,t);return pt.parse(e)}catch(e){throw e instanceof Ht.ZodError?(o.error("Schema validation error:",JSON.stringify(e.errors,null,2)),o.error("API response:",JSON.stringify(e.format(),null,2)),new Error(`Response validation failed: ${JSON.stringify(e.errors)}`)):new Error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Jt(t){try{return await $.post(x.CVM_START(t)),!0}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Yt(t){try{return await $.post(x.CVM_STOP(t)),!0}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Xt(t){try{return await $.post(x.CVM_RESTART(t)),!0}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Qt(t,e){try{let r=await $.put(x.CVM_UPGRADE(t),e);return gt.parse(r)}catch(r){throw new Error(`Failed to upgrade CVM: ${r instanceof Error?r.message:String(r)}`)}}async function er(t){try{return await $.delete(x.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function P(){let t=o.startSpinner("Fetching available CVMs"),e=await _e();if(t.stop(!0),!e||e.length===0){o.info("No CVMs found for your account");return}let r=e.map(i=>{let a=i.hosted?.app_id||i.hosted?.id,c=i.name||i.hosted&&i.hosted.name,p=i.status||i.hosted&&i.hosted.status;return{name:`${c||"Unnamed"} (${a}) - Status: ${p||"Unknown"}`,value:a}}),{selectedCvm:n}=await go.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:r}]);return n}async function tr(t){try{return await $.get(x.CVM_ATTESTATION(t))}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function rr(t,e,r,n,i){try{let a={};if(e!==void 0&&(a.vcpu=e),r!==void 0&&(a.memory=r),n!==void 0&&(a.disk_size=n),i!==void 0&&(a.allow_restart=i),Object.keys(a).length===0)throw new Error("At least one resource parameter must be provided");return await $.patch(x.CVM_RESIZE(t),a),!0}catch(a){throw new Error(`Failed to resize CVM: ${a instanceof Error?a.message:String(a)}`)}}import je from"chalk";var or=new ho().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=o.startSpinner("Fetching CVMs"),r=await _e();if(e.stop(!0),!r||r.length===0){o.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(r,null,2));return}r.forEach(n=>{o.keyValueTable({"App ID":`app_${n.hosted.app_id}`,Name:n.name,Status:n.status==="running"?je.green(n.status):n.status==="stopped"?je.red(n.status):je.yellow(n.status),"Node Info URL":n.hosted.app_url,"App URL":`${J}/dashboard/cvms/app_${n.hosted.app_id}`})}),o.success(`Found ${r.length} CVMs:`)}catch(e){o.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as yo}from"commander";import We from"chalk";var nr=new yo().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{if(t)t=await T(t);else if(t=await P(),!t){o.info("No CVMs found or selection cancelled");return}let r=o.startSpinner(`Fetching CVM with App ID ${t}`),n=await te(t);if(r.stop(!0),n||(o.error(`CVM with App ID ${t} not found`),process.exit(1)),e.json){console.log(JSON.stringify(n,null,2));return}o.keyValueTable({Name:n.name,"App ID":`app_${n.app_id}`,Status:n.status==="running"?We.green(n.status):n.status==="stopped"?We.red(n.status):We.yellow(n.status),vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"TEEPod ID":n.teepod_id,"App URL":`${J}/dashboard/cvms/app_${n.app_id}`})}catch(r){o.error(`Failed to get CVM details: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as vo}from"commander";var ir=new vo().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;let e=o.startSpinner(`Starting CVM with App ID ${t}`);await Jt(t),e.stop(!0),o.success(`CVM with App ID ${t} started successfully`)}catch(e){o.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as bo}from"commander";var sr=new bo().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;let e=o.startSpinner(`Stopping CVM with App ID ${t}`);await Yt(t),e.stop(!0),o.success(`CVM with App ID ${t} stopped successfully`)}catch(e){o.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Co}from"commander";var ar=new Co().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;let e=o.startSpinner(`Restarting CVM with App ID ${t}`);await Xt(t),e.stop(!0),o.success(`CVM with App ID ${t} restarted successfully`)}catch(e){o.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as wo}from"commander";import $e from"chalk";var cr=new wo().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{if(t)t=await T(t);else{o.info("No CVM specified, fetching available CVMs...");let n=await P();if(!n)return;t=n}o.info(`Fetching attestation information for CVM ${t}...`);let r=o.startSpinner("Fetching attestation information");try{let n=await tr(t);if(r.stop(!0),!n||Object.keys(n).length===0){o.info("No attestation information found");return}if(e?.json){o.info(JSON.stringify(n,null,2));return}o.success("Attestation Summary:");let i={Status:n.is_online?$e.green("Online"):$e.red("Offline"),"Public Access":n.is_public?$e.green("Enabled"):$e.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};o.keyValueTable(i,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((a,c)=>{o.success(`Certificate #${c+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let p={Subject:`${a.subject.common_name||"Unknown"}${a.subject.organization?` (${a.subject.organization})`:""}`,Issuer:`${a.issuer.common_name||"Unknown"}${a.issuer.organization?` (${a.issuer.organization})`:""}`,"Serial Number":a.serial_number,Validity:`${new Date(a.not_before).toLocaleString()} to ${new Date(a.not_after).toLocaleString()}`,Fingerprint:a.fingerprint,"Signature Algorithm":a.signature_algorithm,"Is CA":a.is_ca?"Yes":"No","Position in Chain":a.position_in_chain};o.keyValueTable(p,{borderStyle:"single"})}),n.tcb_info&&(o.success("Trusted Computing Base (TCB) Information:"),o.keyValueTable(n.tcb_info,{borderStyle:"single"}))}catch(n){throw r.stop(!0),n}}catch(r){o.error(`Failed to get attestation information: ${r instanceof Error?r.message:String(r)}`)}});import{Command as So}from"commander";import{encryptEnvVars as Eo}from"@phala/dstack-sdk/encrypt-env-vars";import mr from"fs";import xo from"path";import he from"inquirer";import ko from"fs";var ge=(t,e)=>{let r={};if(t){for(let n of t)if(n.includes("=")){let[i,a]=n.split("=");i&&a&&(r[i]=a)}}if(e){let n=ko.readFileSync(e,"utf8");for(let i of n.split(`
114
+ `).filter(a=>a&&!a.includes("<none>")).filter(a=>a.includes(`${n}/`)).map(a=>{let[c,p]=a.split(":"),u=c.split("/");return{name:u.length>1?u[1]:c,tag:p}})}catch(e){return o.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import Ft from"prompts";var It=new no().name("login").description("Login to Docker Hub").option("-u, --username <username>","Docker Hub username").option("-p, --password <password>","Docker Hub password").option("-r, --registry <registry>","Docker registry URL").action(async t=>{try{let e=t.username,r=t.password,n=t.registry;if(!e){o.info("First we need your Docker Hub username to check if you are already logged in.");let p=await Ft({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:u=>u.length>0?!0:"Username cannot be empty"});p.username||(o.error("Username is required"),process.exit(1)),e=p.username}let i=new _("",e,n);if(await i.login(e)){o.success(`${e} is logged in to Docker Hub`);return}if(!r){let p=await Ft({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:u=>u.length>0?!0:"Password cannot be empty"});p.password||(o.error("Password is required"),process.exit(1)),r=p.password}await i.login(e,r,n)||(o.error("Failed to login to Docker Hub"),process.exit(1)),await et({username:e,registry:n||null}),o.success("Logged in to Docker Hub successfully")}catch(e){o.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as io}from"commander";import Rt from"path";import Mt from"inquirer";import so from"fs";var Vt=new io().name("build").description("Build a Docker image").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").option("-f, --file <file>","Path to Dockerfile","Dockerfile").action(async t=>{try{let e=await O();if(e||(o.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let c=await Mt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:p=>p.trim()?!0:"Image name is required"}]);t.image=c.image}if(!t.tag){let c=await Mt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:p=>p.trim()?!0:"Tag is required"}]);t.tag=c.tag}let r=Rt.resolve(process.cwd(),t.file);so.existsSync(r)||(o.info(`Default Dockerfile not found at ${r}`),t.file=await G("Enter the path to your Dockerfile:","Dockerfile","file"));let n=Rt.resolve(process.cwd(),t.file);await new _(t.image,e.username,e.registry).buildImage(n,t.tag)||(o.error("Failed to build Docker image"),process.exit(1)),o.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){o.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as ao}from"commander";import Lt from"inquirer";var Nt=new ao().name("push").description("Push a Docker image to Docker Hub").option("-i, --image <image>","Image name").option("-t, --tag <tag>","Image tag").action(async t=>{try{let e=await O();e||(o.error('Docker information not found. Please login first with "phala docker login"'),process.exit(1));let r=t.image,n=t.tag;if(!r||!n){let c=await _.listLocalImages();if(c.length===0&&(o.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!r){let p=Array.from(new Set(c.map(d=>d.name))),{selectedImage:u}=await Lt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:p}]);r=u}if(!n){let p=c.filter(d=>d.name===r).map(d=>d.tag);p.length===0&&(o.error(`No tags found for image ${r}`),process.exit(1));let{selectedTag:u}=await Lt.prompt([{type:"list",name:"selectedTag",message:`Select a tag for ${r}:`,choices:p}]);n=u}}await new _(r,e.username,e.registry).pushImage(n)||(o.error("Failed to push Docker image"),process.exit(1)),o.success(`Docker image ${e.username}/${r}:${n} pushed successfully`)}catch(e){o.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as co}from"commander";import Ee from"inquirer";import Ot from"fs";import Ut from"path";var zt=new co().name("run").description("Run a Docker Compose setup").option("-c, --compose <compose>","Path to docker-compose.yml file").option("-e, --env-file <envFile>","Path to environment variables file").option("--skip-env","Skip environment variables file prompt",!0).action(async t=>{try{let e=t.compose,r=t.envFile;if(e)try{R(e)}catch{o.error(`File not found: ${e}`),process.exit(1)}else{let a=Ut.join(process.cwd(),"docker-compose.yml");if(Ot.existsSync(a)){let{useDefault:p}=await Ee.prompt([{type:"confirm",name:"useDefault",message:"Use docker-compose.yml in current directory?",default:!0}]);p&&(e=a)}if(!e){let{composePath:p}=await Ee.prompt([{type:"input",name:"composePath",message:"Enter path to docker-compose.yml file:",validate:u=>R(u)?!0:"File not found"}]);e=p}}if(!r&&!t.skipEnv){let a=Ut.join(process.cwd(),".env");if(Ot.existsSync(a)){let{useDefault:p}=await Ee.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);p&&(r=a)}if(!r){let{envPath:p}=await Ee.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:u=>{try{return R(u),!0}catch{return`File not found: ${u}`}}}]);r=p}}let n=new _("");if(r){o.info(`Validating env file: ${r}`);try{R(r)}catch{o.error(`File not found: ${r}`),process.exit(1)}o.info(`Running Docker Compose with compose file: ${e} and env file: ${r}`)}else o.info(`Running Docker Compose with compose file: ${e} without env file`);await n.runComposeLocally(e,r)||(o.error("Failed to run Docker Compose"),process.exit(1)),o.success("Docker Compose is running")}catch(e){o.error(`Failed to run Docker Compose: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as mo}from"commander";import M from"inquirer";import fe from"fs";import xe from"path";var jt=new mo().name("generate").description("Generate a Docker Compose file").option("-i, --image <image>","Docker image name to use in the compose file").option("-t, --tag <tag>","Docker image tag to use in the compose file").option("-e, --env-file <envFile>","Path to environment variables file").option("-o, --output <output>","Output path for generated docker-compose.yml").option("--template <template>","Template to use for the generated docker-compose.yml").option("--manual","Skip automatic image detection and enter image/tag manually").action(async t=>{try{let e=await O();(!e||!e.username)&&(o.error("Docker Hub username not found. Please login first with `phala docker login`"),process.exit(1));let r=t.image||"",n=t.tag||"";if((!r||!n)&&!t.manual)try{o.info("Detecting local Docker images...");let u=await _.listLocalImages();if(u.length===0)o.warn("No local Docker images found. You will need to enter image details manually.");else{let d=new Map;if(u.forEach(v=>{d.has(v.name)||d.set(v.name,[]),d.get(v.name)?.push(v.tag)}),r&&!n){let v=d.get(r)||[];if(v.length>0){let{imageTag:y}=await M.prompt([{type:"list",name:"imageTag",message:`Select a tag for ${r}:`,choices:[...v,new M.Separator,"[ Enter manually ]"]}]);y!=="[ Enter manually ]"&&(n=y)}else o.warn(`No tags found for image ${r}. You will need to enter the tag manually.`)}else if(!r){let v=Array.from(d.keys()),{imageName:y}=await M.prompt([{type:"list",name:"imageName",message:"Select a Docker image:",choices:[...v,new M.Separator,"[ Enter manually ]"]}]);if(y!=="[ Enter manually ]"){r=y;let m=d.get(y)||[],{imageTag:l}=await M.prompt([{type:"list",name:"imageTag",message:"Select a tag:",choices:[...m,new M.Separator,"[ Enter manually ]"]}]);l!=="[ Enter manually ]"&&(n=l)}}}}catch(u){o.warn(`Failed to detect local images: ${u instanceof Error?u.message:String(u)}`),o.info("Continuing with manual input...")}if(!r){let{inputImage:u}=await M.prompt([{type:"input",name:"inputImage",message:"Enter Docker image name:",validate:d=>d.trim()?!0:"Image name cannot be empty"}]);r=u}if(!n){let{inputTag:u}=await M.prompt([{type:"input",name:"inputTag",message:`Enter tag for image ${r}:`,validate:d=>d.trim()?!0:"Tag cannot be empty"}]);n=u}let i=t.envFile;if(i)try{R(i)}catch{o.error(`File not found: ${i}`),process.exit(1)}else{let u=xe.join(process.cwd(),".env");if(fe.existsSync(u)){let{useDefault:v}=await M.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);v&&(i=u)}if(!i){let{envPath:v}=await M.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:y=>{try{return R(y),!0}catch{return`File not found: ${y}`}}}]);i=v}}let a=t.output;if(!a&&(a=xe.join(process.cwd(),"docker-compose.yml"),fe.existsSync(a))){let{confirmOverwrite:u}=await M.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${a} already exists. Overwrite?`,default:!1}]);if(!u){let{customPath:d}=await M.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:xe.join(process.cwd(),"docker-generated-compose.yml")}]);a=d}}let c=new _(r,e.username,e.registry);i?o.info(`Generating Docker Compose file for ${r}:${n} using env file: ${i}`):o.info(`Generating Docker Compose file for ${r}:${n} without env file`);let p=await c.buildComposeFile(n,i,t.template);if(p!==a){let u=xe.dirname(a);fe.existsSync(u)||(o.info(`Creating directory: ${u}`),fe.mkdirSync(u,{recursive:!0})),fe.copyFileSync(p,a)}o.success(`Docker Compose file generated successfully: ${a}`)}catch(e){o.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Wt=new lo().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(It).addCommand(Vt).addCommand(zt).addCommand(Nt).addCommand(jt);import{Command as fo}from"commander";import{Command as po}from"commander";var Bt=new po().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",ot).option("-p, --port <port>","Simulator port (default: 8090)","8090").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{if(t.type==="docker")await new _("").runSimulator(t.image,t.port)||(o.error("Failed to start TEE simulator"),process.exit(1));else if(t.type==="native")if(xt()||await _t(),await Se()){o.success("TEE simulator is already running");return}else{let r=$t();o.success("TEE simulator started successfully")}else o.error("Invalid simulator type"),process.exit(1)}catch(e){o.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as uo}from"commander";var Gt=new uo().name("stop").description("Stop the TEE simulator").option("-t, --type <type>","Simulator type (docker, native)","docker").action(async t=>{try{t.type==="docker"?await new _("").stopSimulator()||(o.error("Failed to stop TEE simulator"),process.exit(1)):t.type==="native"?await Tt()||(o.error("Failed to stop TEE simulator"),process.exit(1)):(o.error("Invalid simulator type"),process.exit(1))}catch(e){o.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Kt=new fo().name("simulator").description("TEE simulator commands").addCommand(Bt).addCommand(Gt);import{Command as Fo}from"commander";import{Command as ho}from"commander";import go from"inquirer";import{z as Ht}from"zod";async function _e(){try{let t=await $.get(x.CVMS(0));return Ht.array(Me).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function T(t){let r=(await _e()).find(n=>n.hosted?.app_id===t||`app_${n.hosted?.app_id}`===t);if(!r)o.error(`CVM with App ID ${t} not detected`),process.exit(1);else return o.success(`CVM with App ID ${t} detected`),r.hosted?.app_id}async function te(t){try{let e=await $.get(x.CVM_BY_APP_ID(t));return dt.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function qt(t){try{let e=await $.post(x.CVM_PUBKEY,t);return ut.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Zt(t){try{let e=await $.post(x.CVM_FROM_CONFIGURATION,t);return pt.parse(e)}catch(e){throw e instanceof Ht.ZodError?(o.error("Schema validation error:",JSON.stringify(e.errors,null,2)),o.error("API response:",JSON.stringify(e.format(),null,2)),new Error(`Response validation failed: ${JSON.stringify(e.errors)}`)):new Error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Jt(t){try{return await $.post(x.CVM_START(t)),!0}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Yt(t){try{return await $.post(x.CVM_STOP(t)),!0}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Xt(t){try{return await $.post(x.CVM_RESTART(t)),!0}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Qt(t,e){try{let r=await $.put(x.CVM_UPGRADE(t),e);return gt.parse(r)}catch(r){throw new Error(`Failed to upgrade CVM: ${r instanceof Error?r.message:String(r)}`)}}async function er(t){try{return await $.delete(x.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function P(){let t=o.startSpinner("Fetching available CVMs"),e=await _e();if(t.stop(!0),!e||e.length===0){o.info("No CVMs found for your account");return}let r=e.map(i=>{let a=i.hosted?.app_id||i.hosted?.id,c=i.name||i.hosted&&i.hosted.name,p=i.status||i.hosted&&i.hosted.status;return{name:`${c||"Unnamed"} (${a}) - Status: ${p||"Unknown"}`,value:a}}),{selectedCvm:n}=await go.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:r}]);return n}async function tr(t){try{return await $.get(x.CVM_ATTESTATION(t))}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function rr(t,e,r,n,i){try{let a={};if(e!==void 0&&(a.vcpu=e),r!==void 0&&(a.memory=r),n!==void 0&&(a.disk_size=n),i!==void 0&&(a.allow_restart=i),Object.keys(a).length===0)throw new Error("At least one resource parameter must be provided");return await $.patch(x.CVM_RESIZE(t),a),!0}catch(a){throw new Error(`Failed to resize CVM: ${a instanceof Error?a.message:String(a)}`)}}import je from"chalk";var or=new ho().name("list").alias("ls").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=o.startSpinner("Fetching CVMs"),r=await _e();if(e.stop(!0),!r||r.length===0){o.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(r,null,2));return}r.forEach(n=>{o.keyValueTable({"App ID":`app_${n.hosted.app_id}`,Name:n.name,Status:n.status==="running"?je.green(n.status):n.status==="stopped"?je.red(n.status):je.yellow(n.status),"Node Info URL":n.hosted.app_url,"App URL":`${J}/dashboard/cvms/app_${n.hosted.app_id}`})}),o.success(`Found ${r.length} CVMs:`)}catch(e){o.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as yo}from"commander";import We from"chalk";var nr=new yo().name("get").description("Get details of a CVM").argument("[app-id]","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{if(t)t=await T(t);else if(t=await P(),!t){o.info("No CVMs found or selection cancelled");return}let r=o.startSpinner(`Fetching CVM with App ID ${t}`),n=await te(t);if(r.stop(!0),n||(o.error(`CVM with App ID ${t} not found`),process.exit(1)),e.json){console.log(JSON.stringify(n,null,2));return}o.keyValueTable({Name:n.name,"App ID":`app_${n.app_id}`,Status:n.status==="running"?We.green(n.status):n.status==="stopped"?We.red(n.status):We.yellow(n.status),vCPU:n.vcpu,Memory:`${n.memory} MB`,"Disk Size":`${n.disk_size} GB`,"Dstack Image":n.base_image,"TEEPod ID":n.teepod_id,"App URL":`${J}/dashboard/cvms/app_${n.app_id}`})}catch(r){o.error(`Failed to get CVM details: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as vo}from"commander";var ir=new vo().name("start").description("Start a stopped CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;let e=o.startSpinner(`Starting CVM with App ID ${t}`);await Jt(t),e.stop(!0),o.success(`CVM with App ID ${t} started successfully`)}catch(e){o.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as bo}from"commander";var sr=new bo().name("stop").description("Stop a running CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;let e=o.startSpinner(`Stopping CVM with App ID ${t}`);await Yt(t),e.stop(!0),o.success(`CVM with App ID ${t} stopped successfully`)}catch(e){o.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Co}from"commander";var ar=new Co().name("restart").description("Restart a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").action(async t=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;let e=o.startSpinner(`Restarting CVM with App ID ${t}`);await Xt(t),e.stop(!0),o.success(`CVM with App ID ${t} restarted successfully`)}catch(e){o.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as wo}from"commander";import $e from"chalk";var cr=new wo().name("attestation").description("Get attestation information for a CVM").argument("[app-id]","CVM app ID (will prompt for selection if not provided)").option("-j, --json","Output in JSON format").action(async(t,e)=>{try{if(t)t=await T(t);else{o.info("No CVM specified, fetching available CVMs...");let n=await P();if(!n)return;t=n}o.info(`Fetching attestation information for CVM ${t}...`);let r=o.startSpinner("Fetching attestation information");try{let n=await tr(t);if(r.stop(!0),!n||Object.keys(n).length===0){o.info("No attestation information found");return}if(e?.json){o.info(JSON.stringify(n,null,2));return}o.success("Attestation Summary:");let i={Status:n.is_online?$e.green("Online"):$e.red("Offline"),"Public Access":n.is_public?$e.green("Enabled"):$e.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};o.keyValueTable(i,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((a,c)=>{o.success(`Certificate #${c+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let p={Subject:`${a.subject.common_name||"Unknown"}${a.subject.organization?` (${a.subject.organization})`:""}`,Issuer:`${a.issuer.common_name||"Unknown"}${a.issuer.organization?` (${a.issuer.organization})`:""}`,"Serial Number":a.serial_number,Validity:`${new Date(a.not_before).toLocaleString()} to ${new Date(a.not_after).toLocaleString()}`,Fingerprint:a.fingerprint,"Signature Algorithm":a.signature_algorithm,"Is CA":a.is_ca?"Yes":"No","Position in Chain":a.position_in_chain};o.keyValueTable(p,{borderStyle:"single"})}),n.tcb_info&&(o.success("Trusted Computing Base (TCB) Information:"),o.keyValueTable(n.tcb_info,{borderStyle:"single"}))}catch(n){throw r.stop(!0),n}}catch(r){o.error(`Failed to get attestation information: ${r instanceof Error?r.message:String(r)}`)}});import{Command as So}from"commander";import{encryptEnvVars as Eo}from"@phala/dstack-sdk/encrypt-env-vars";import mr from"fs";import xo from"path";import he from"inquirer";import ko from"fs";var ge=(t,e)=>{let r={};if(t){for(let n of t)if(n.includes("=")){let[i,a]=n.split("=");i&&a&&(r[i]=a)}}if(e){let n=ko.readFileSync(e,"utf8");for(let i of n.split(`
115
115
  `))if(!(!i.trim()||i.trim().startsWith("#"))&&i.includes("=")){let[a,...c]=i.split("="),p=c.join("="),u=p.search(/\s+#/);u!==-1&&(p=p.substring(0,u).trim()),a&&p&&(r[a.trim()]=p.trim())}}return Object.entries(r).map(([n,i])=>({key:n,value:i}))};var lr=new So().name("create").description("Create a new CVM").option("-n, --name <name>","Name of the CVM").option("-c, --compose <compose>","Path to Docker Compose file").option("--vcpu <vcpu>","Number of vCPUs",String(se)).option("--memory <memory>","Memory in MB",String(ae)).option("--disk-size <diskSize>","Disk size in GB",String(ce)).option("--teepod-id <teepodId>","TEEPod ID to use",nt).option("--image <image>","Version of dstack image to use",it).option("-e, --env-file <envFile>","Path to environment file").option("--skip-env","Skip environment variable prompt",!1).option("--debug","Enable debug mode",!1).action(async t=>{try{if(!t.name){let{name:m}=await he.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:l=>l.trim()?!0:"CVM name is required"}]);t.name=m}if(!t.compose){let l=ke(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");t.compose=await G("Enter the path to your Docker Compose file:",l,"file")}let e=xo.resolve(t.compose);mr.existsSync(e)||(o.error(`Docker Compose file not found: ${e}`),process.exit(1));let r=mr.readFileSync(e,"utf8");await K();let n=[];if(t.envFile)try{n=ge([],t.envFile)}catch(m){o.error(`Failed to read environment file: ${m instanceof Error?m.message:String(m)}`),process.exit(1)}else if(!t.skipEnv)if(await he.prompt([{type:"confirm",name:"shouldSkip",message:"Do you want to skip environment variable prompt?",default:!1}]))o.info("Skipping environment variable prompt");else{let l=await G("Enter the path to your environment file:",".env","file");n=ge([],l)}let i=[];if(t.vcpu===String(se)&&i.push({type:"input",name:"vcpu",message:`Enter number of vCPUs (default: ${se}):`,default:String(se),validate:m=>{let l=parseInt(m);return isNaN(l)||l<=0?"Please enter a valid positive number":!0}}),t.memory===String(ae)&&i.push({type:"input",name:"memory",message:`Enter memory in MB (default: ${ae}):`,default:String(ae),validate:m=>{let l=parseInt(m);return isNaN(l)||l<=0?"Please enter a valid positive number":!0}}),t.diskSize===String(ce)&&i.push({type:"input",name:"diskSize",message:`Enter disk size in GB (default: ${ce}):`,default:String(ce),validate:m=>{let l=parseInt(m);return isNaN(l)||l<=0?"Please enter a valid positive number":!0}}),i.length>0){let m=await he.prompt(i);m.vcpu&&(t.vcpu=m.vcpu),m.memory&&(t.memory=m.memory),m.diskSize&&(t.diskSize=m.diskSize)}if(!t.teepodId){let m=o.startSpinner("Fetching available TEEPods"),l=await B();m.stop(!0),l.length===0&&(o.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:f}=await he.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:l.map(b=>({name:`${b.name}`,value:b.teepod_id}))}]),h=l.find(b=>b.teepod_id===f);h||(o.error("Failed to find selected TEEPod"),process.exit(1)),o.info(`Selected TEEPod: ${h.name}`),t.teepodId=h.teepod_id}if(!t.image){let l=(await we(t.teepodId)).map(h=>({name:`${h.name}`,value:h.name})),{selectedImage:f}=await he.prompt([{type:"list",name:"selectedImage",message:"Select an image:",choices:l}]);t.image=f.value}let a={teepod_id:t.teepodId||3,name:t.name,image:t.image||"dstack-dev-0.3.5",vcpu:parseInt(t.vcpu),memory:parseInt(t.memory),disk_size:parseInt(t.diskSize),compose_manifest:{docker_compose_file:r,docker_config:{url:"",username:"",password:""},features:["kms","tproxy-net"],kms_enabled:!0,manifest_version:2,name:t.name,public_logs:!0,public_sysinfo:!0,tproxy_enabled:!0},listed:!1},c=o.startSpinner("Getting public key from CVM"),p=await qt(a);c.stop(!0),p||(o.error("Failed to get public key from CVM"),process.exit(1));let u=o.startSpinner("Encrypting environment variables"),d=await Eo(n,p.app_env_encrypt_pubkey);u.stop(!0),t.debug&&(o.debug("Public key:",p.app_env_encrypt_pubkey),o.debug("Encrypted environment variables:",d),o.debug("Environment variables:",JSON.stringify(n)));let v=o.startSpinner("Creating CVM"),y=await Zt({...a,encrypted_env:d,app_env_encrypt_pubkey:p.app_env_encrypt_pubkey,app_id_salt:p.app_id_salt});v.stop(!0),y||(o.error("Failed to create CVM"),process.exit(1)),o.success("CVM created successfully"),o.info(`CVM ID: ${y.id}`),o.info(`Name: ${y.name}`),o.info(`Status: ${y.status}`),o.info(`App ID: ${y.app_id}`),y.app_url?o.info(`App URL: ${y.app_url}`):o.info(`App URL: ${J}/dashboard/cvms/app_${y.app_id}`),o.info(""),o.info("Your CVM is being created. You can check its status with:"),o.info(`phala cvms get ${y.app_id}`)}catch(e){o.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as _o}from"commander";import $o from"inquirer";var pr=new _o().name("delete").description("Delete a CVM").argument("[app-id]","App ID of the CVM to delete (if not provided, a selection prompt will appear)").option("-f, --force","Skip confirmation prompt",!1).action(async(t,e)=>{try{if(t)t=await T(t);else if(t=await P(),!t)return;if(!e.force){let{confirm:i}=await $o.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete CVM with App ID ${t}? This action cannot be undone.`,default:!1}]);if(!i){o.info("Deletion cancelled");return}}let r=o.startSpinner(`Deleting CVM ${t}`),n=await er(t);r.stop(!0),n||(o.error(`Failed to delete CVM ${t}`),process.exit(1)),o.success(`CVM ${t} deleted successfully`)}catch(r){o.error(`Failed to delete CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as To}from"commander";import Po from"fs";import{encryptEnvVars as Do}from"@phala/dstack-sdk/encrypt-env-vars";var ur=new To().name("upgrade").description("Upgrade a CVM to a new version").argument("[app-id]","CVM app ID to upgrade (will prompt for selection if not provided)").option("-c, --compose <compose>","Path to new Docker Compose file").option("-e, --env-file <envFile>","Path to environment file").option("--debug","Enable debug mode",!1).action(async(t,e)=>{try{if(t)t=await T(t);else{o.info("No CVM specified, fetching available CVMs...");let d=await P();if(!d)return;t=d}let r=o.startSpinner(`Fetching current configuration for CVM ${t}`),n=await te(t);if(r.stop(!0),n||(o.error(`CVM with App ID ${t} not found`),process.exit(1)),!e.compose){let v=ke(["docker-compose.yml","docker-compose.yaml"],"Detected docker compose file: {path}");e.compose=await G("Enter the path to your Docker Compose file:",v,"file")}let i="";if(e.compose)try{i=Po.readFileSync(e.compose,"utf8")}catch(d){o.error(`Failed to read Docker Compose file: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}await K();let a="";if(e.envFile){let d=[];if(e.envFile)try{d=ge([],e.envFile),a=await Do(d,n.encrypted_env_pubkey)}catch(v){o.error(`Failed to read environment file: ${v instanceof Error?v.message:String(v)}`),process.exit(1)}}let c={compose_manifest:{docker_compose_file:i,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${e.appId}`},encrypted_env:a,allow_restart:!0},p=o.startSpinner(`Upgrading CVM ${t}`),u=await Qt(t,c);p.stop(!0),u||(o.error("Failed to upgrade CVM"),process.exit(1)),o.success(`CVM ${t} upgraded successfully`),u.detail&&o.info(`Details: ${u.detail}`)}catch(r){o.error(`Failed to upgrade CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});import{Command as Ao}from"commander";import ye from"inquirer";import j from"chalk";var dr=new Ao().name("resize").description("Resize resources for a CVM").argument("[app-id]","App ID of the CVM (if not provided, a selection prompt will appear)").option("-v, --vcpu <vcpu>","Number of virtual CPUs").option("-m, --memory <memory>","Memory size in MB").option("-d, --disk-size <diskSize>","Disk size in GB").option("-r, --allow-restart <allowRestart>","Allow restart of the CVM if needed for resizing").option("-y, --yes","Automatically confirm the resize operation").action(async(t,e)=>{try{if(t)t=await T(t);else if(t=await P(),!t){o.info("No CVMs found or selection cancelled");return}let r=await te(t),n=e.vcpu,i=e.memory,a=e.diskSize,c=e.allowRestart;n||(n=(await ye.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:y=>{let m=parseInt(y);return isNaN(m)||m<0?"Please enter a valid non-negative number":!0},default:r.vcpu,filter:y=>parseInt(y)}])).vcpu),i||(i=(await ye.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:y=>{let m=parseInt(y);return isNaN(m)||m<0?"Please enter a valid non-negative number":!0},default:r.memory,filter:y=>parseInt(y)}])).memory),a||(a=(await ye.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:y=>{let m=parseInt(y);return isNaN(m)||m<0?"Please enter a valid non-negative number":!0},default:r.disk_size,filter:y=>parseInt(y)}])).diskSize),c||(c=(await ye.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let p=`Are you sure you want to resize CVM ${t} with the following changes:
116
116
  `;if(o.keyValueTable({vCPUs:r.vcpu!==n?`${j.red(r.vcpu)} -> ${j.green(n)}`:r.vcpu,Memory:r.memory!==i?`${j.red(r.memory)} MB -> ${j.green(i)} MB`:r.memory,"Disk Size":r.disk_size!==a?`${j.red(r.disk_size)} GB -> ${j.green(a)} GB`:r.disk_size,"Allow Restart":c?j.green("Yes"):j.red("No")}),!e.yes){let{confirm:v}=await ye.prompt([{type:"confirm",name:"confirm",message:p,default:!1}]);if(!v){o.info("Resize operation cancelled");return}}let u=o.startSpinner(`Resizing CVM with App ID ${t}`);await rr(t,n,i,a,c?1:0),u.stop(!0),o.success(`CVM with App ID ${t} resized successfully`)}catch(r){o.error(`Failed to resize CVM: ${r instanceof Error?r.message:String(r)}`),process.exit(1)}});var fr=new Fo().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(or).addCommand(nr).addCommand(lr).addCommand(ur).addCommand(ir).addCommand(sr).addCommand(ar).addCommand(cr).addCommand(pr).addCommand(dr);process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Ro(){new Io().name("phala").description(`${qe}
117
117
  Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("0.0.1").addCommand(wt).addCommand(fr).addCommand(Wt).addCommand(Kt).addCommand(Et).parse(process.argv)}Ro().catch(t=>{o.error("An error occurred:",t),process.exit(1)});