phala 0.0.1-alpha → 0.0.1-alpha-4
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.
Potentially problematic release.
This version of phala might be problematic. Click here for more details.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js
CHANGED
@@ -107,8 +107,8 @@ Operation completed. Full log available at: ${c}`),i()):a(new Error(`Process exi
|
|
107
107
|
- If you run with the simulator, set DSTACK_SIMULATOR_ENDPOINT to http://host.docker.internal:8090`);E(e);let i=["-f",e,"up","-d"];return o&&(E(o),i.splice(2,0,"--env-file",o)),await tt("docker-compose",i),n.stop(!0,"Docker Compose file running successfully"),!0}catch(n){return r.error(`Failed to run Docker Compose file: ${n instanceof Error?n.message:String(n)}`),!1}}async runSimulator(e){try{r.info(`Running TEE simulator with image ${e}`),r.info("Pulling latest simulator image..."),await ee(`docker pull ${e}`),r.info("Starting simulator in background...");let{stdout:o}=await ee(`docker run -d --name tee-simulator --rm -p 8090:8090 ${e}`),n=o.trim();return r.success(`TEE simulator running successfully. Container ID: ${n}`),r.info(`
|
108
108
|
|
109
109
|
Useful commands:`),r.info(`- View logs: docker logs -f ${n}`),r.info(`- Stop simulator: docker stop ${n}`),!0}catch(o){return r.error(`Failed to run TEE simulator: ${o instanceof Error?o.message:String(o)}`),!1}}async stopSimulator(){try{let e=r.startSpinner("Stopping TEE simulator...");return await ee("docker stop tee-simulator"),e.stop(!0,"TEE simulator stopped successfully"),!0}catch(e){return r.error(`Failed to stop TEE simulator: ${e instanceof Error?e.message:String(e)}`),!1}}static async listLocalImages(){try{let{stdout:e}=await ee('docker images --format "{{.Repository}}:{{.Tag}}"');return e.split(`
|
110
|
-
`).filter(n=>n&&!n.includes("<none>")).map(n=>{let[i,a]=n.split(":"),m=i.split("/");return{name:m.length>1?m[1]:i,tag:a}})}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import st from"prompts";var it=new _r().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,o=t.password,n=t.registry;if(!e){let m=await st({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:c=>c.length>0?!0:"Username cannot be empty"});m.username||(r.error("Username is required"),process.exit(1)),e=m.username}if(!o){let m=await st({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:c=>c.length>0?!0:"Password cannot be empty"});m.password||(r.error("Password is required"),process.exit(1)),o=m.password}await new h("",e,n).login(e,o,n)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await De({username:e,password:o,registry:n||null}),r.success("Logged in to Docker Hub successfully")}catch(e){r.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as xr}from"commander";import at from"path";import mt from"inquirer";import $r from"fs";var ct=new xr().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 x();if(e||(r.error('Docker credentials not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let m=await mt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:c=>c.trim()?!0:"Image name is required"}]);t.image=m.image}if(!t.tag){let m=await mt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:c=>c.trim()?!0:"Tag is required"}]);t.tag=m.tag}let o=at.resolve(process.cwd(),t.file);$r.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await V("Enter the path to your Dockerfile:","Dockerfile","file"));let n=at.resolve(process.cwd(),t.file);await new h(t.image,e.username,e.registry).buildImage(n,t.tag)||(r.error("Failed to build Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){r.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Pr}from"commander";import pt from"inquirer";var lt=new Pr().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 x();e||(r.error('Docker credentials not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image,n=t.tag;if(!o||!n){let m=await h.listLocalImages();if(m.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let c=Array.from(new Set(m.map(f=>f.name))),{selectedImage:p}=await pt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:c}]);o=p}if(!n){let c=m.filter(f=>f.name===o).map(f=>f.tag);c.length===0&&(r.error(`No tags found for image ${o}`),process.exit(1));let{selectedTag:p}=await pt.prompt([{type:"list",name:"selectedTag",message:`Select a tag for ${o}:`,choices:c}]);n=p}}await new h(o,e.username,e.registry).pushImage(n)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${o}:${n} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Dr}from"commander";var ut=new Dr().name("tags").description("List tags for a Docker image").requiredOption("-i, --image <image>","Image name").option("-j, --json","Output in JSON format").action(async t=>{try{let e=await x();e||(r.error('Docker credentials not found. Please login first with "teecloud docker login"'),process.exit(1));let n=await new h(t.image,e.username,e.registry).listTags();if(n.length===0){r.info(`No tags found for image ${e.username}/${t.image}`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}r.info(`Tags for image ${e.username}/${t.image}:`),n.forEach(i=>{r.info(`- ${i}`)})}catch(e){r.error(`Failed to list tags: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Ir}from"commander";import te from"inquirer";import dt from"fs";import ft from"path";var gt=new Ir().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,o=t.env;if(e)try{E(e)}catch{r.error(`File not found: ${e}`),process.exit(1)}else{let a=ft.join(process.cwd(),"docker-compose.yml");if(dt.existsSync(a)){let{useDefault:c}=await te.prompt([{type:"confirm",name:"useDefault",message:"Use docker-compose.yml in current directory?",default:!0}]);c&&(e=a)}if(!e){let{composePath:c}=await te.prompt([{type:"input",name:"composePath",message:"Enter path to docker-compose.yml file:",validate:p=>E(p)?!0:"File not found"}]);e=c}}if(!o&&!t.skipEnv){let a=ft.join(process.cwd(),".env");if(dt.existsSync(a)){let{useDefault:c}=await te.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);c&&(o=a)}if(!o){let{envPath:c}=await te.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:p=>{try{return E(p),!0}catch{return`File not found: ${p}`}}}]);o=c}}let n=new h("");if(o){try{E(o)}catch{r.error(`File not found: ${o}`),process.exit(1)}r.info(`Running Docker Compose with compose file: ${e} and env file: ${o}`)}else r.info(`Running Docker Compose with compose file: ${e} without env file`);await n.runComposeLocally(e,o)||(r.error("Failed to run Docker Compose"),process.exit(1)),r.success("Docker Compose is running")}catch(e){r.error(`Failed to run Docker Compose: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Tr}from"commander";import b from"inquirer";import K from"fs";import re from"path";var yt=new Tr().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 x();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `tcc docker login`"),process.exit(1));let o=t.image||"",n=t.tag||"";if((!o||!n)&&!t.manual)try{r.info("Detecting local Docker images...");let p=await h.listLocalImages();if(p.length===0)r.warn("No local Docker images found. You will need to enter image details manually.");else{let f=new Map;if(p.forEach(d=>{f.has(d.name)||f.set(d.name,[]),f.get(d.name)?.push(d.tag)}),o&&!n){let d=f.get(o)||[];if(d.length>0){let{imageTag:u}=await b.prompt([{type:"list",name:"imageTag",message:`Select a tag for ${o}:`,choices:[...d,new b.Separator,"[ Enter manually ]"]}]);u!=="[ Enter manually ]"&&(n=u)}else r.warn(`No tags found for image ${o}. You will need to enter the tag manually.`)}else if(!o){let d=Array.from(f.keys()),{imageName:u}=await b.prompt([{type:"list",name:"imageName",message:"Select a Docker image:",choices:[...d,new b.Separator,"[ Enter manually ]"]}]);if(u!=="[ Enter manually ]"){o=u;let y=f.get(u)||[],{imageTag:l}=await b.prompt([{type:"list",name:"imageTag",message:"Select a tag:",choices:[...y,new b.Separator,"[ Enter manually ]"]}]);l!=="[ Enter manually ]"&&(n=l)}}}}catch(p){r.warn(`Failed to detect local images: ${p instanceof Error?p.message:String(p)}`),r.info("Continuing with manual input...")}if(!o){let{inputImage:p}=await b.prompt([{type:"input",name:"inputImage",message:"Enter Docker image name:",validate:f=>f.trim()?!0:"Image name cannot be empty"}]);o=p}if(!n){let{inputTag:p}=await b.prompt([{type:"input",name:"inputTag",message:`Enter tag for image ${o}:`,validate:f=>f.trim()?!0:"Tag cannot be empty"}]);n=p}let i=t.envFile;if(i)try{E(i)}catch{r.error(`File not found: ${i}`),process.exit(1)}else{let p=re.join(process.cwd(),".env");if(K.existsSync(p)){let{useDefault:d}=await b.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);d&&(i=p)}if(!i){let{envPath:d}=await b.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:u=>{try{return E(u),!0}catch{return`File not found: ${u}`}}}]);i=d}}let a=t.output;if(!a&&(a=re.join(process.cwd(),"docker-compose.yml"),K.existsSync(a))){let{confirmOverwrite:p}=await b.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${a} already exists. Overwrite?`,default:!1}]);if(!p){let{customPath:f}=await b.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:re.join(process.cwd(),`${o}-${n}-compose.yml`)}]);a=f}}let m=new h(o,e.username,e.registry);i?r.info(`Generating Docker Compose file for ${o}:${n} using env file: ${i}`):r.info(`Generating Docker Compose file for ${o}:${n} without env file`);let c=await m.buildComposeFile(n,i,t.template);if(c!==a){let p=re.dirname(a);K.existsSync(p)||(r.info(`Creating directory: ${p}`),K.mkdirSync(p,{recursive:!0})),K.copyFileSync(c,a)}r.success(`Docker Compose file generated successfully: ${a}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var ht=new Fr().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(it).addCommand(ct).addCommand(lt).addCommand(ut).addCommand(gt).addCommand(yt);import{Command as Vr}from"commander";import{Command as Ar}from"commander";var Ct=new Ar().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",Te).action(async t=>{try{await new h("").runSimulator(t.image)||(r.error("Failed to start TEE simulator"),process.exit(1))}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Mr}from"commander";var vt=new Mr().name("stop").description("Stop the TEE simulator").action(async()=>{try{await new h("").stopSimulator()||(r.error("Failed to stop TEE simulator"),process.exit(1))}catch(t){r.error(`Failed to stop TEE simulator: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});var wt=new Vr().name("simulator").description("TEE simulator commands").addCommand(Ct).addCommand(vt);import{Command as jr}from"commander";import{Command as Ur}from"commander";import H from"fs";import St from"path";import Rr from"os";var oe=St.join(Rr.homedir(),".phala-cloud"),ye=St.join(oe,"config.json"),ge={apiUrl:"https://cloud-api.phala.network",cloudUrl:"https://cloud.phala.network",defaultTeepodId:3,defaultImage:"dstack-dev-0.3.5",defaultVcpu:1,defaultMemory:2048,defaultDiskSize:20};function Nr(){if(!H.existsSync(oe))try{H.mkdirSync(oe,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${oe}:`,t),t}}function ne(){try{if(H.existsSync(ye)){let t=H.readFileSync(ye,"utf8");return{...ge,...JSON.parse(t)}}return ge}catch(t){return r.error("Failed to load configuration:",t),ge}}function Or(t){Nr();try{H.writeFileSync(ye,JSON.stringify({...ne(),...t},null,2),{mode:384}),r.success("Configuration saved successfully.")}catch(e){throw r.error("Failed to save configuration:",e),e}}function kt(t){return ne()[t]}function Et(t,e){let o=ne();o[t]=e,Or(o)}function bt(){return ne()}var _t=new Ur().name("get").description("Get a configuration value").argument("<key>","Configuration key").action(t=>{try{let e=kt(t);e===void 0&&(r.error(`Configuration key '${t}' not found`),process.exit(1)),r.info(`${t}: ${JSON.stringify(e)}`)}catch(e){r.error(`Failed to get configuration value: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Lr}from"commander";var xt=new Lr().name("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action((t,e)=>{try{let o=e;if(e.startsWith("{")||e.startsWith("[")||e==="true"||e==="false"||!isNaN(Number(e)))try{o=JSON.parse(e)}catch{}Et(t,o),r.success(`Configuration value for '${t}' set successfully`)}catch(o){r.error(`Failed to set configuration value: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as zr}from"commander";var $t=new zr().name("list").description("List all configuration values").option("-j, --json","Output in JSON format").action(t=>{try{let e=bt();if(t.json){console.log(JSON.stringify(e,null,2));return}r.info("Configuration values:");for(let[o,n]of Object.entries(e))r.info(`${o}: ${JSON.stringify(n)}`)}catch(e){r.error(`Failed to list configuration values: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Pt=new jr().name("config").description("Manage your local configuration").addCommand(_t).addCommand(xt).addCommand($t);import{Command as no}from"commander";import{Command as Br}from"commander";import{z as Dt}from"zod";async function he(){try{let t=await w.get(C.CVMS(0));return Dt.array(de).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function R(t){try{let e=await w.get(C.CVM_BY_APP_ID(t));return Ue.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function It(t){try{let e=await w.post(C.CVM_PUBKEY,t);return Oe.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Tt(t){try{let e=await w.post(C.CVM_FROM_CONFIGURATION,t);return Ne.parse(e)}catch(e){throw e instanceof Dt.ZodError?(console.error("Schema validation error:",JSON.stringify(e.errors,null,2)),console.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 Ft(t){try{return await w.post(C.CVM_START(t)),!0}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function At(t){try{return await w.post(C.CVM_STOP(t)),!0}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Mt(t){try{return await w.post(C.CVM_RESTART(t)),!0}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Vt(t,e){try{let o=await w.put(C.CVM_UPGRADE(t),e);return ze.parse(o)}catch(o){throw new Error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`)}}async function Rt(t){try{return await w.delete(C.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function S(){let{logger:t}=await import("./logger-LBGFMBSV.js"),e=(await import("inquirer")).default,o=t.startSpinner("Fetching available CVMs"),n=await he();if(o.stop(!0),!n||n.length===0){t.info("No CVMs found for your account");return}let i=n.map(m=>{let c=m.hosted?.app_id||m.hosted?.id,p=m.name||m.hosted&&m.hosted.name,f=m.status||m.hosted&&m.hosted.status;return{name:`${p||"Unnamed"} (${c}) - Status: ${f||"Unknown"}`,value:c}}),{selectedCvm:a}=await e.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:i}]);return a}async function Nt(t){try{return await w.get(C.CVM_ATTESTATION(t))}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function Ot(t,e,o,n,i){try{let a={};if(e!==void 0&&(a.vcpu=e),o!==void 0&&(a.memory=o),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 w.patch(C.CVM_RESIZE(t),a),!0}catch(a){throw new Error(`Failed to resize CVM: ${a instanceof Error?a.message:String(a)}`)}}var Ut=new Br().name("list").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=r.startSpinner("Fetching CVMs"),o=await he();if(e.stop(!0),!o||o.length===0){r.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(o,null,2));return}o.forEach(n=>{r.keyValueTable({"App ID":n.hosted.app_id,Name:n.name,Status:n.status,"Node Info URL":n.hosted.app_url,"App URL":`${T}/dashboard/cvms/app_${n.hosted.app_id}`})}),r.success(`Found ${o.length} CVMs:`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Gr}from"commander";var Lt=new Gr().name("get").description("Get details of a CVM").option("-i, --id <app-id>","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async t=>{try{let e=t.id;if(!e&&(e=await S(),!e))return;let o=r.startSpinner(`Fetching CVM with App ID ${e}`),n=await R(e);if(o.stop(!0),n||(r.error(`CVM with App ID ${e} not found`),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}r.keyValueTable({Name:n.name,Status: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":`${T}/dashboard/cvms/app_${n.app_id}`})}catch(e){r.error(`Failed to get CVM details: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as qr}from"commander";var zt=new qr().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 S(),!t))return;let e=r.startSpinner(`Starting CVM with App ID ${t}`);await Ft(t),e.stop(!0),r.success(`CVM with App ID ${t} started successfully`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Kr}from"commander";var jt=new Kr().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 S(),!t))return;let e=r.startSpinner(`Stopping CVM with App ID ${t}`);await At(t),e.stop(!0),r.success(`CVM with App ID ${t} stopped successfully`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Hr}from"commander";var Bt=new Hr().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 S(),!t))return;let e=r.startSpinner(`Restarting CVM with App ID ${t}`);await Mt(t),e.stop(!0),r.success(`CVM with App ID ${t} restarted successfully`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Zr}from"commander";import se from"chalk";var Gt=new Zr().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){r.info("No CVM specified, fetching available CVMs...");let n=await S();if(!n)return;t=n}r.info(`Fetching attestation information for CVM ${t}...`);let o=r.startSpinner("Fetching attestation information");try{let n=await Nt(t);if(o.stop(!0),!n||Object.keys(n).length===0){r.info("No attestation information found");return}if(e?.json){console.log(JSON.stringify(n,null,2));return}r.success("Attestation Summary:");let i={Status:n.is_online?se.green("Online"):se.red("Offline"),"Public Access":n.is_public?se.green("Enabled"):se.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};r.keyValueTable(i,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((a,m)=>{r.success(`Certificate #${m+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let c={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};r.keyValueTable(c,{borderStyle:"single"})}),n.tcb_info&&(r.success("Trusted Computing Base (TCB) Information:"),r.keyValueTable(n.tcb_info,{borderStyle:"single"}))}catch(n){throw o.stop(!0),n}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as Yr}from"commander";import{encryptEnvVars as Wr}from"@phala/dstack-sdk/encrypt-env-vars";import J from"fs";import ie from"path";import P from"inquirer";import Jr from"fs";var Z=(t,e)=>{let o={};if(t){for(let n of t)if(n.includes("=")){let[i,a]=n.split("=");i&&a&&(o[i]=a)}}if(e){let n=Jr.readFileSync(e,"utf8");for(let i of n.split(`
|
111
|
-
`))if(!(!i.trim()||i.trim().startsWith("#"))&&i.includes("=")){let[a,...m]=i.split("="),c=m.join("="),p=c.search(/\s+#/);p!==-1&&(c=c.substring(0,p).trim()),a&&c&&(o[a.trim()]=c.trim())}}return Object.entries(o).map(([n,i])=>({key:n,value:i}))};var qt=new Yr().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(L)).option("--memory <memory>","Memory in MB",String(z)).option("--disk-size <diskSize>","Disk size in GB",String(j)).option("--teepod-id <teepodId>","TEEPod ID to use").option("--image <image>","Version of dstack image to use").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:l}=await P.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:g=>g.trim()?!0:"CVM name is required"}]);t.name=l}let e=ie.join(process.cwd(),"examples"),o=[];if(J.existsSync(e)){let l=J.readdirSync(e,{withFileTypes:!0}).filter(g=>g.isDirectory()&&!g.name.startsWith(".")).map(g=>g.name);o.push(...l)}let n="";try{if(!t.compose)if(o.length>0){let g=[...o.map((v,_)=>({name:v,value:{type:"example",name:v}})),new P.Separator,{name:"Enter a file path",value:{type:"custom"}}],{selection:k}=await P.prompt([{type:"list",name:"selection",message:"Choose a Docker Compose example or enter a custom path:",choices:g}]);if(k.type==="example"){let v=ie.join(e,k.name),_=["docker-compose.yml","docker-compose.yaml"],Ce=!1;for(let Yt of _){let ve=ie.join(v,Yt);if(J.existsSync(ve)){t.compose=ve,Ce=!0,r.info(`Using example: ${k.name} (${t.compose})`);break}}Ce||(r.error(`Could not find docker-compose.yml or docker-compose.yaml in ${v}`),process.exit(1))}else{let{customPath:v}=await P.prompt([{type:"input",name:"customPath",message:"Enter the path to your Docker Compose file:",validate:_=>_.trim()?!0:"Docker Compose file path is required"}]);t.compose=v}}else{let{customPath:g}=await P.prompt([{type:"input",name:"customPath",message:"Enter the path to your Docker Compose file:",validate:k=>k.trim()?!0:"Docker Compose file path is required"}]);t.compose=g}let l=ie.resolve(t.compose);J.existsSync(l)||(r.error(`Docker Compose file not found: ${l}`),process.exit(1)),n=J.readFileSync(l,"utf8")}catch(l){r.error(`Failed to read Docker Compose file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}let i=[];if(t.envFile)try{i=Z([],t.envFile)}catch(l){r.error(`Failed to read environment file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}else if(!t.skipEnv){let l=await V("Enter the path to your environment file:",".env","file");i=Z([],l)}let a=[];if(t.vcpu===String(L)&&a.push({type:"input",name:"vcpu",message:`Enter number of vCPUs (default: ${L}):`,default:String(L),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),t.memory===String(z)&&a.push({type:"input",name:"memory",message:`Enter memory in MB (default: ${z}):`,default:String(z),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),t.diskSize===String(j)&&a.push({type:"input",name:"diskSize",message:`Enter disk size in GB (default: ${j}):`,default:String(j),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),a.length>0){let l=await P.prompt(a);l.vcpu&&(t.vcpu=l.vcpu),l.memory&&(t.memory=l.memory),l.diskSize&&(t.diskSize=l.diskSize)}if(!t.teepodId){let l=r.startSpinner("Fetching available TEEPods"),g=await M();l.stop(!0),g.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:k}=await P.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:g.map(_=>({name:`${_.name} (${_.status})`,value:_.id}))}]),v=g.find(_=>_.id===k);v||(r.error("Failed to find selected TEEPod"),process.exit(1)),r.info(`Selected TEEPod: ${v.name}`),t.teepodId=v.id}if(!t.image){let g=(await Q(t.teepodId)).map(v=>({name:`${v.name}`,value:v.name})),{selectedImage:k}=await P.prompt([{type:"list",name:"selectedImage",message:"Select an image:",choices:g}]);t.image=k.value}let m={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:n,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=r.startSpinner("Getting public key from CVM"),p=await It(m);c.stop(!0),p||(r.error("Failed to get public key from CVM"),process.exit(1));let f=r.startSpinner("Encrypting environment variables"),d=await Wr(i,p.app_env_encrypt_pubkey);f.stop(!0),t.debug&&(r.debug("Public key:",p.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",d),r.debug("Environment variables:",JSON.stringify(i)));let u=r.startSpinner("Creating CVM"),y=await Tt({...m,encrypted_env:d,app_env_encrypt_pubkey:p.app_env_encrypt_pubkey,app_id_salt:p.app_id_salt});u.stop(!0),y||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.info(`CVM ID: ${y.id}`),r.info(`Name: ${y.name}`),r.info(`Status: ${y.status}`),r.info(`App ID: ${y.app_id}`),y.app_url?r.info(`App URL: ${y.app_url}`):r.info(`App URL: ${T}/dashboard/cvms/app_${y.app_id}`),r.info(""),r.info("Your CVM is being created. You can check its status with:"),r.info(`phala cvms
|
110
|
+
`).filter(n=>n&&!n.includes("<none>")).map(n=>{let[i,a]=n.split(":"),m=i.split("/");return{name:m.length>1?m[1]:i,tag:a}})}catch(e){return r.error(`Failed to list local Docker images: ${e instanceof Error?e.message:String(e)}`),[]}}};import st from"prompts";var it=new _r().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,o=t.password,n=t.registry;if(!e){let m=await st({type:"text",name:"username",message:"Enter your Docker Hub username:",validate:c=>c.length>0?!0:"Username cannot be empty"});m.username||(r.error("Username is required"),process.exit(1)),e=m.username}if(!o){let m=await st({type:"password",name:"password",message:"Enter your Docker Hub password:",validate:c=>c.length>0?!0:"Password cannot be empty"});m.password||(r.error("Password is required"),process.exit(1)),o=m.password}await new h("",e,n).login(e,o,n)||(r.error("Failed to login to Docker Hub"),process.exit(1)),await De({username:e,password:o,registry:n||null}),r.success("Logged in to Docker Hub successfully")}catch(e){r.error(`Failed to login to Docker Hub: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as xr}from"commander";import at from"path";import mt from"inquirer";import $r from"fs";var ct=new xr().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 x();if(e||(r.error('Docker credentials not found. Please login first with "phala docker login"'),process.exit(1)),!t.image){let m=await mt.prompt([{type:"input",name:"image",message:"Enter the Docker image name:",validate:c=>c.trim()?!0:"Image name is required"}]);t.image=m.image}if(!t.tag){let m=await mt.prompt([{type:"input",name:"tag",message:"Enter the Docker image tag:",default:"latest",validate:c=>c.trim()?!0:"Tag is required"}]);t.tag=m.tag}let o=at.resolve(process.cwd(),t.file);$r.existsSync(o)||(r.info(`Default Dockerfile not found at ${o}`),t.file=await V("Enter the path to your Dockerfile:","Dockerfile","file"));let n=at.resolve(process.cwd(),t.file);await new h(t.image,e.username,e.registry).buildImage(n,t.tag)||(r.error("Failed to build Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${t.image}:${t.tag} built successfully`)}catch(e){r.error(`Failed to build Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Pr}from"commander";import pt from"inquirer";var lt=new Pr().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 x();e||(r.error('Docker credentials not found. Please login first with "phala docker login"'),process.exit(1));let o=t.image,n=t.tag;if(!o||!n){let m=await h.listLocalImages();if(m.length===0&&(r.error('No local Docker images found. Please build an image first with "phala docker build"'),process.exit(1)),!o){let c=Array.from(new Set(m.map(f=>f.name))),{selectedImage:p}=await pt.prompt([{type:"list",name:"selectedImage",message:"Select an image to push:",choices:c}]);o=p}if(!n){let c=m.filter(f=>f.name===o).map(f=>f.tag);c.length===0&&(r.error(`No tags found for image ${o}`),process.exit(1));let{selectedTag:p}=await pt.prompt([{type:"list",name:"selectedTag",message:`Select a tag for ${o}:`,choices:c}]);n=p}}await new h(o,e.username,e.registry).pushImage(n)||(r.error("Failed to push Docker image"),process.exit(1)),r.success(`Docker image ${e.username}/${o}:${n} pushed successfully`)}catch(e){r.error(`Failed to push Docker image: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Dr}from"commander";var ut=new Dr().name("tags").description("List tags for a Docker image").requiredOption("-i, --image <image>","Image name").option("-j, --json","Output in JSON format").action(async t=>{try{let e=await x();e||(r.error('Docker credentials not found. Please login first with "teecloud docker login"'),process.exit(1));let n=await new h(t.image,e.username,e.registry).listTags();if(n.length===0){r.info(`No tags found for image ${e.username}/${t.image}`);return}if(t.json){console.log(JSON.stringify(n,null,2));return}r.info(`Tags for image ${e.username}/${t.image}:`),n.forEach(i=>{r.info(`- ${i}`)})}catch(e){r.error(`Failed to list tags: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Ir}from"commander";import te from"inquirer";import dt from"fs";import ft from"path";var gt=new Ir().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,o=t.env;if(e)try{E(e)}catch{r.error(`File not found: ${e}`),process.exit(1)}else{let a=ft.join(process.cwd(),"docker-compose.yml");if(dt.existsSync(a)){let{useDefault:c}=await te.prompt([{type:"confirm",name:"useDefault",message:"Use docker-compose.yml in current directory?",default:!0}]);c&&(e=a)}if(!e){let{composePath:c}=await te.prompt([{type:"input",name:"composePath",message:"Enter path to docker-compose.yml file:",validate:p=>E(p)?!0:"File not found"}]);e=c}}if(!o&&!t.skipEnv){let a=ft.join(process.cwd(),".env");if(dt.existsSync(a)){let{useDefault:c}=await te.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);c&&(o=a)}if(!o){let{envPath:c}=await te.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:p=>{try{return E(p),!0}catch{return`File not found: ${p}`}}}]);o=c}}let n=new h("");if(o){try{E(o)}catch{r.error(`File not found: ${o}`),process.exit(1)}r.info(`Running Docker Compose with compose file: ${e} and env file: ${o}`)}else r.info(`Running Docker Compose with compose file: ${e} without env file`);await n.runComposeLocally(e,o)||(r.error("Failed to run Docker Compose"),process.exit(1)),r.success("Docker Compose is running")}catch(e){r.error(`Failed to run Docker Compose: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Tr}from"commander";import b from"inquirer";import K from"fs";import re from"path";var yt=new Tr().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 x();(!e||!e.username)&&(r.error("Docker Hub username not found. Please login first with `tcc docker login`"),process.exit(1));let o=t.image||"",n=t.tag||"";if((!o||!n)&&!t.manual)try{r.info("Detecting local Docker images...");let p=await h.listLocalImages();if(p.length===0)r.warn("No local Docker images found. You will need to enter image details manually.");else{let f=new Map;if(p.forEach(d=>{f.has(d.name)||f.set(d.name,[]),f.get(d.name)?.push(d.tag)}),o&&!n){let d=f.get(o)||[];if(d.length>0){let{imageTag:u}=await b.prompt([{type:"list",name:"imageTag",message:`Select a tag for ${o}:`,choices:[...d,new b.Separator,"[ Enter manually ]"]}]);u!=="[ Enter manually ]"&&(n=u)}else r.warn(`No tags found for image ${o}. You will need to enter the tag manually.`)}else if(!o){let d=Array.from(f.keys()),{imageName:u}=await b.prompt([{type:"list",name:"imageName",message:"Select a Docker image:",choices:[...d,new b.Separator,"[ Enter manually ]"]}]);if(u!=="[ Enter manually ]"){o=u;let y=f.get(u)||[],{imageTag:l}=await b.prompt([{type:"list",name:"imageTag",message:"Select a tag:",choices:[...y,new b.Separator,"[ Enter manually ]"]}]);l!=="[ Enter manually ]"&&(n=l)}}}}catch(p){r.warn(`Failed to detect local images: ${p instanceof Error?p.message:String(p)}`),r.info("Continuing with manual input...")}if(!o){let{inputImage:p}=await b.prompt([{type:"input",name:"inputImage",message:"Enter Docker image name:",validate:f=>f.trim()?!0:"Image name cannot be empty"}]);o=p}if(!n){let{inputTag:p}=await b.prompt([{type:"input",name:"inputTag",message:`Enter tag for image ${o}:`,validate:f=>f.trim()?!0:"Tag cannot be empty"}]);n=p}let i=t.envFile;if(i)try{E(i)}catch{r.error(`File not found: ${i}`),process.exit(1)}else{let p=re.join(process.cwd(),".env");if(K.existsSync(p)){let{useDefault:d}=await b.prompt([{type:"confirm",name:"useDefault",message:"Use .env file in current directory?",default:!0}]);d&&(i=p)}if(!i){let{envPath:d}=await b.prompt([{type:"input",name:"envPath",message:"Enter path to environment variables file:",validate:u=>{try{return E(u),!0}catch{return`File not found: ${u}`}}}]);i=d}}let a=t.output;if(!a&&(a=re.join(process.cwd(),"docker-compose.yml"),K.existsSync(a))){let{confirmOverwrite:p}=await b.prompt([{type:"confirm",name:"confirmOverwrite",message:`File ${a} already exists. Overwrite?`,default:!1}]);if(!p){let{customPath:f}=await b.prompt([{type:"input",name:"customPath",message:"Enter alternative output path:",default:re.join(process.cwd(),"docker-generated-compose.yml")}]);a=f}}let m=new h(o,e.username,e.registry);i?r.info(`Generating Docker Compose file for ${o}:${n} using env file: ${i}`):r.info(`Generating Docker Compose file for ${o}:${n} without env file`);let c=await m.buildComposeFile(n,i,t.template);if(c!==a){let p=re.dirname(a);K.existsSync(p)||(r.info(`Creating directory: ${p}`),K.mkdirSync(p,{recursive:!0})),K.copyFileSync(c,a)}r.success(`Docker Compose file generated successfully: ${a}`)}catch(e){r.error(`Failed to generate Docker Compose file: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var ht=new Fr().name("docker").description("Login to Docker Hub and manage Docker images").addCommand(it).addCommand(ct).addCommand(lt).addCommand(ut).addCommand(gt).addCommand(yt);import{Command as Vr}from"commander";import{Command as Ar}from"commander";var Ct=new Ar().name("start").description("Start the TEE simulator").option("-i, --image <image>","Simulator image",Te).action(async t=>{try{await new h("").runSimulator(t.image)||(r.error("Failed to start TEE simulator"),process.exit(1))}catch(e){r.error(`Failed to start TEE simulator: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Mr}from"commander";var vt=new Mr().name("stop").description("Stop the TEE simulator").action(async()=>{try{await new h("").stopSimulator()||(r.error("Failed to stop TEE simulator"),process.exit(1))}catch(t){r.error(`Failed to stop TEE simulator: ${t instanceof Error?t.message:String(t)}`),process.exit(1)}});var wt=new Vr().name("simulator").description("TEE simulator commands").addCommand(Ct).addCommand(vt);import{Command as jr}from"commander";import{Command as Ur}from"commander";import H from"fs";import St from"path";import Rr from"os";var oe=St.join(Rr.homedir(),".phala-cloud"),ye=St.join(oe,"config.json"),ge={apiUrl:"https://cloud-api.phala.network",cloudUrl:"https://cloud.phala.network",defaultTeepodId:3,defaultImage:"dstack-dev-0.3.5",defaultVcpu:1,defaultMemory:2048,defaultDiskSize:20};function Nr(){if(!H.existsSync(oe))try{H.mkdirSync(oe,{recursive:!0})}catch(t){throw r.error(`Failed to create directory ${oe}:`,t),t}}function ne(){try{if(H.existsSync(ye)){let t=H.readFileSync(ye,"utf8");return{...ge,...JSON.parse(t)}}return ge}catch(t){return r.error("Failed to load configuration:",t),ge}}function Or(t){Nr();try{H.writeFileSync(ye,JSON.stringify({...ne(),...t},null,2),{mode:384}),r.success("Configuration saved successfully.")}catch(e){throw r.error("Failed to save configuration:",e),e}}function kt(t){return ne()[t]}function Et(t,e){let o=ne();o[t]=e,Or(o)}function bt(){return ne()}var _t=new Ur().name("get").description("Get a configuration value").argument("<key>","Configuration key").action(t=>{try{let e=kt(t);e===void 0&&(r.error(`Configuration key '${t}' not found`),process.exit(1)),r.info(`${t}: ${JSON.stringify(e)}`)}catch(e){r.error(`Failed to get configuration value: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Lr}from"commander";var xt=new Lr().name("set").description("Set a configuration value").argument("<key>","Configuration key").argument("<value>","Configuration value").action((t,e)=>{try{let o=e;if(e.startsWith("{")||e.startsWith("[")||e==="true"||e==="false"||!isNaN(Number(e)))try{o=JSON.parse(e)}catch{}Et(t,o),r.success(`Configuration value for '${t}' set successfully`)}catch(o){r.error(`Failed to set configuration value: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as zr}from"commander";var $t=new zr().name("list").description("List all configuration values").option("-j, --json","Output in JSON format").action(t=>{try{let e=bt();if(t.json){console.log(JSON.stringify(e,null,2));return}r.info("Configuration values:");for(let[o,n]of Object.entries(e))r.info(`${o}: ${JSON.stringify(n)}`)}catch(e){r.error(`Failed to list configuration values: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});var Pt=new jr().name("config").description("Manage your local configuration").addCommand(_t).addCommand(xt).addCommand($t);import{Command as no}from"commander";import{Command as Br}from"commander";import{z as Dt}from"zod";async function he(){try{let t=await w.get(C.CVMS(0));return Dt.array(de).parse(t)}catch(t){throw new Error(`Failed to get CVMs: ${t instanceof Error?t.message:String(t)}`)}}async function R(t){try{let e=await w.get(C.CVM_BY_APP_ID(t));return Ue.parse(e)}catch(e){throw new Error(`Failed to get CVM by App ID: ${e instanceof Error?e.message:String(e)}`)}}async function It(t){try{let e=await w.post(C.CVM_PUBKEY,t);return Oe.parse(e)}catch(e){throw new Error(`Failed to get pubkey from CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Tt(t){try{let e=await w.post(C.CVM_FROM_CONFIGURATION,t);return Ne.parse(e)}catch(e){throw e instanceof Dt.ZodError?(console.error("Schema validation error:",JSON.stringify(e.errors,null,2)),console.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 Ft(t){try{return await w.post(C.CVM_START(t)),!0}catch(e){throw new Error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`)}}async function At(t){try{return await w.post(C.CVM_STOP(t)),!0}catch(e){throw new Error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Mt(t){try{return await w.post(C.CVM_RESTART(t)),!0}catch(e){throw new Error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`)}}async function Vt(t,e){try{let o=await w.put(C.CVM_UPGRADE(t),e);return ze.parse(o)}catch(o){throw new Error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`)}}async function Rt(t){try{return await w.delete(C.CVM_BY_APP_ID(t)),!0}catch(e){throw new Error(`Failed to delete CVM: ${e instanceof Error?e.message:String(e)}`)}}async function S(){let{logger:t}=await import("./logger-LBGFMBSV.js"),e=(await import("inquirer")).default,o=t.startSpinner("Fetching available CVMs"),n=await he();if(o.stop(!0),!n||n.length===0){t.info("No CVMs found for your account");return}let i=n.map(m=>{let c=m.hosted?.app_id||m.hosted?.id,p=m.name||m.hosted&&m.hosted.name,f=m.status||m.hosted&&m.hosted.status;return{name:`${p||"Unnamed"} (${c}) - Status: ${f||"Unknown"}`,value:c}}),{selectedCvm:a}=await e.prompt([{type:"list",name:"selectedCvm",message:"Select a CVM:",choices:i}]);return a}async function Nt(t){try{return await w.get(C.CVM_ATTESTATION(t))}catch(e){throw new Error(`Failed to get attestation information: ${e instanceof Error?e.message:String(e)}`)}}async function Ot(t,e,o,n,i){try{let a={};if(e!==void 0&&(a.vcpu=e),o!==void 0&&(a.memory=o),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 w.patch(C.CVM_RESIZE(t),a),!0}catch(a){throw new Error(`Failed to resize CVM: ${a instanceof Error?a.message:String(a)}`)}}var Ut=new Br().name("list").description("List all CVMs").option("-j, --json","Output in JSON format").action(async t=>{try{let e=r.startSpinner("Fetching CVMs"),o=await he();if(e.stop(!0),!o||o.length===0){r.info("No CVMs found");return}if(t.json){console.log(JSON.stringify(o,null,2));return}o.forEach(n=>{r.keyValueTable({"App ID":n.hosted.app_id,Name:n.name,Status:n.status,"Node Info URL":n.hosted.app_url,"App URL":`${T}/dashboard/cvms/app_${n.hosted.app_id}`})}),r.success(`Found ${o.length} CVMs:`)}catch(e){r.error(`Failed to list CVMs: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Gr}from"commander";var Lt=new Gr().name("get").description("Get details of a CVM").option("-i, --id <app-id>","App ID of the CVM (optional)").option("-j, --json","Output in JSON format").action(async t=>{try{let e=t.id;if(!e&&(e=await S(),!e))return;let o=r.startSpinner(`Fetching CVM with App ID ${e}`),n=await R(e);if(o.stop(!0),n||(r.error(`CVM with App ID ${e} not found`),process.exit(1)),t.json){console.log(JSON.stringify(n,null,2));return}r.keyValueTable({Name:n.name,Status: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":`${T}/dashboard/cvms/app_${n.app_id}`})}catch(e){r.error(`Failed to get CVM details: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as qr}from"commander";var zt=new qr().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 S(),!t))return;let e=r.startSpinner(`Starting CVM with App ID ${t}`);await Ft(t),e.stop(!0),r.success(`CVM with App ID ${t} started successfully`)}catch(e){r.error(`Failed to start CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Kr}from"commander";var jt=new Kr().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 S(),!t))return;let e=r.startSpinner(`Stopping CVM with App ID ${t}`);await At(t),e.stop(!0),r.success(`CVM with App ID ${t} stopped successfully`)}catch(e){r.error(`Failed to stop CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Hr}from"commander";var Bt=new Hr().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 S(),!t))return;let e=r.startSpinner(`Restarting CVM with App ID ${t}`);await Mt(t),e.stop(!0),r.success(`CVM with App ID ${t} restarted successfully`)}catch(e){r.error(`Failed to restart CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Zr}from"commander";import se from"chalk";var Gt=new Zr().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){r.info("No CVM specified, fetching available CVMs...");let n=await S();if(!n)return;t=n}r.info(`Fetching attestation information for CVM ${t}...`);let o=r.startSpinner("Fetching attestation information");try{let n=await Nt(t);if(o.stop(!0),!n||Object.keys(n).length===0){r.info("No attestation information found");return}if(e?.json){console.log(JSON.stringify(n,null,2));return}r.success("Attestation Summary:");let i={Status:n.is_online?se.green("Online"):se.red("Offline"),"Public Access":n.is_public?se.green("Enabled"):se.yellow("Disabled"),Error:n.error||"None",Certificates:`${n.app_certificates?.length||0} found`};r.keyValueTable(i,{borderStyle:"rounded"}),n.app_certificates&&n.app_certificates.length>0&&n.app_certificates.forEach((a,m)=>{r.success(`Certificate #${m+1} (${a.position_in_chain===0?"End Entity":"CA"}):`);let c={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};r.keyValueTable(c,{borderStyle:"single"})}),n.tcb_info&&(r.success("Trusted Computing Base (TCB) Information:"),r.keyValueTable(n.tcb_info,{borderStyle:"single"}))}catch(n){throw o.stop(!0),n}}catch(o){r.error(`Failed to get attestation information: ${o instanceof Error?o.message:String(o)}`)}});import{Command as Yr}from"commander";import{encryptEnvVars as Wr}from"@phala/dstack-sdk/encrypt-env-vars";import J from"fs";import ie from"path";import P from"inquirer";import Jr from"fs";var Z=(t,e)=>{let o={};if(t){for(let n of t)if(n.includes("=")){let[i,a]=n.split("=");i&&a&&(o[i]=a)}}if(e){let n=Jr.readFileSync(e,"utf8");for(let i of n.split(`
|
111
|
+
`))if(!(!i.trim()||i.trim().startsWith("#"))&&i.includes("=")){let[a,...m]=i.split("="),c=m.join("="),p=c.search(/\s+#/);p!==-1&&(c=c.substring(0,p).trim()),a&&c&&(o[a.trim()]=c.trim())}}return Object.entries(o).map(([n,i])=>({key:n,value:i}))};var qt=new Yr().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(L)).option("--memory <memory>","Memory in MB",String(z)).option("--disk-size <diskSize>","Disk size in GB",String(j)).option("--teepod-id <teepodId>","TEEPod ID to use").option("--image <image>","Version of dstack image to use").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:l}=await P.prompt([{type:"input",name:"name",message:"Enter a name for the CVM:",validate:g=>g.trim()?!0:"CVM name is required"}]);t.name=l}let e=ie.join(process.cwd(),"examples"),o=[];if(J.existsSync(e)){let l=J.readdirSync(e,{withFileTypes:!0}).filter(g=>g.isDirectory()&&!g.name.startsWith(".")).map(g=>g.name);o.push(...l)}let n="";try{if(!t.compose)if(o.length>0){let g=[...o.map((v,_)=>({name:v,value:{type:"example",name:v}})),new P.Separator,{name:"Enter a file path",value:{type:"custom"}}],{selection:k}=await P.prompt([{type:"list",name:"selection",message:"Choose a Docker Compose example or enter a custom path:",choices:g}]);if(k.type==="example"){let v=ie.join(e,k.name),_=["docker-compose.yml","docker-compose.yaml"],Ce=!1;for(let Yt of _){let ve=ie.join(v,Yt);if(J.existsSync(ve)){t.compose=ve,Ce=!0,r.info(`Using example: ${k.name} (${t.compose})`);break}}Ce||(r.error(`Could not find docker-compose.yml or docker-compose.yaml in ${v}`),process.exit(1))}else{let{customPath:v}=await P.prompt([{type:"input",name:"customPath",message:"Enter the path to your Docker Compose file:",validate:_=>_.trim()?!0:"Docker Compose file path is required"}]);t.compose=v}}else{let{customPath:g}=await P.prompt([{type:"input",name:"customPath",message:"Enter the path to your Docker Compose file:",validate:k=>k.trim()?!0:"Docker Compose file path is required"}]);t.compose=g}let l=ie.resolve(t.compose);J.existsSync(l)||(r.error(`Docker Compose file not found: ${l}`),process.exit(1)),n=J.readFileSync(l,"utf8")}catch(l){r.error(`Failed to read Docker Compose file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}let i=[];if(t.envFile)try{i=Z([],t.envFile)}catch(l){r.error(`Failed to read environment file: ${l instanceof Error?l.message:String(l)}`),process.exit(1)}else if(!t.skipEnv){let l=await V("Enter the path to your environment file:",".env","file");i=Z([],l)}let a=[];if(t.vcpu===String(L)&&a.push({type:"input",name:"vcpu",message:`Enter number of vCPUs (default: ${L}):`,default:String(L),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),t.memory===String(z)&&a.push({type:"input",name:"memory",message:`Enter memory in MB (default: ${z}):`,default:String(z),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),t.diskSize===String(j)&&a.push({type:"input",name:"diskSize",message:`Enter disk size in GB (default: ${j}):`,default:String(j),validate:l=>{let g=parseInt(l);return isNaN(g)||g<=0?"Please enter a valid positive number":!0}}),a.length>0){let l=await P.prompt(a);l.vcpu&&(t.vcpu=l.vcpu),l.memory&&(t.memory=l.memory),l.diskSize&&(t.diskSize=l.diskSize)}if(!t.teepodId){let l=r.startSpinner("Fetching available TEEPods"),g=await M();l.stop(!0),g.length===0&&(r.error("No TEEPods available. Please try again later."),process.exit(1));let{selectedTeepodId:k}=await P.prompt([{type:"list",name:"selectedTeepodId",message:"Select a TEEPod:",choices:g.map(_=>({name:`${_.name} (${_.status})`,value:_.id}))}]),v=g.find(_=>_.id===k);v||(r.error("Failed to find selected TEEPod"),process.exit(1)),r.info(`Selected TEEPod: ${v.name}`),t.teepodId=v.id}if(!t.image){let g=(await Q(t.teepodId)).map(v=>({name:`${v.name}`,value:v.name})),{selectedImage:k}=await P.prompt([{type:"list",name:"selectedImage",message:"Select an image:",choices:g}]);t.image=k.value}let m={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:n,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=r.startSpinner("Getting public key from CVM"),p=await It(m);c.stop(!0),p||(r.error("Failed to get public key from CVM"),process.exit(1));let f=r.startSpinner("Encrypting environment variables"),d=await Wr(i,p.app_env_encrypt_pubkey);f.stop(!0),t.debug&&(r.debug("Public key:",p.app_env_encrypt_pubkey),r.debug("Encrypted environment variables:",d),r.debug("Environment variables:",JSON.stringify(i)));let u=r.startSpinner("Creating CVM"),y=await Tt({...m,encrypted_env:d,app_env_encrypt_pubkey:p.app_env_encrypt_pubkey,app_id_salt:p.app_id_salt});u.stop(!0),y||(r.error("Failed to create CVM"),process.exit(1)),r.success("CVM created successfully"),r.info(`CVM ID: ${y.id}`),r.info(`Name: ${y.name}`),r.info(`Status: ${y.status}`),r.info(`App ID: ${y.app_id}`),y.app_url?r.info(`App URL: ${y.app_url}`):r.info(`App URL: ${T}/dashboard/cvms/app_${y.app_id}`),r.info(""),r.info("Your CVM is being created. You can check its status with:"),r.info(`phala cvms get ${y.app_id}`)}catch(e){r.error(`Failed to create CVM: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}});import{Command as Xr}from"commander";import Qr from"inquirer";var Kt=new Xr().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 S(),!t))return;if(!e.force){let{confirm:i}=await Qr.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){r.info("Deletion cancelled");return}}let o=r.startSpinner(`Deleting CVM ${t}`),n=await Rt(t);o.stop(!0),n||(r.error(`Failed to delete CVM ${t}`),process.exit(1)),r.success(`CVM ${t} deleted successfully`)}catch(o){r.error(`Failed to delete CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as eo}from"commander";import to from"fs";import{encryptEnvVars as ro}from"@phala/dstack-sdk/encrypt-env-vars";var Ht=new eo().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){r.info("No CVM specified, fetching available CVMs...");let d=await S();if(!d)return;t=d}let o=r.startSpinner(`Fetching current configuration for CVM ${t}`),n=await R(t);o.stop(!0),n||(r.error(`CVM with App ID ${t} not found`),process.exit(1));let i={};e.compose||(e.compose=await V("Enter the path to your Docker Compose file:","docker-compose.yml","file"));let a="";if(e.compose)try{a=to.readFileSync(e.compose,"utf8")}catch(d){r.error(`Failed to read Docker Compose file: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}let m="";if(e.envFile){let d=[];if(e.envFile)try{d=Z([],e.envFile),m=await ro(d,n.encrypted_env_pubkey)}catch(u){r.error(`Failed to read environment file: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}}let c={compose_manifest:{docker_compose_file:a,manifest_version:1,runner:"docker-compose",version:"1.0.0",features:["kms","tproxy-net"],name:`app_${e.appId}`},encrypted_env:m,allow_restart:!0},p=r.startSpinner(`Upgrading CVM ${t}`),f=await Vt(t,c);p.stop(!0),f||(r.error("Failed to upgrade CVM"),process.exit(1)),r.success(`CVM ${t} upgraded successfully`),f.detail&&r.info(`Details: ${f.detail}`)}catch(o){r.error(`Failed to upgrade CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});import{Command as oo}from"commander";import Y from"inquirer";var Zt=new oo().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 S(),!t)){r.info("No CVMs found or selection cancelled");return}let o=await R(t),n=e.vcpu,i=e.memory,a=e.diskSize,m=e.allowRestart;n||(n=(await Y.prompt([{type:"input",name:"vcpu",message:"Enter number of vCPUs:",validate:u=>{let y=parseInt(u);return isNaN(y)||y<0?"Please enter a valid non-negative number":!0},default:o.vcpu,filter:u=>parseInt(u)}])).vcpu),i||(i=(await Y.prompt([{type:"input",name:"memory",message:"Enter memory in MB:",validate:u=>{let y=parseInt(u);return isNaN(y)||y<0?"Please enter a valid non-negative number":!0},default:o.memory,filter:u=>parseInt(u)}])).memory),a||(a=(await Y.prompt([{type:"input",name:"diskSize",message:"Enter disk size in GB:",validate:u=>{let y=parseInt(u);return isNaN(y)||y<0?"Please enter a valid non-negative number":!0},default:o.disk_size,filter:u=>parseInt(u)}])).diskSize),m||(m=(await Y.prompt([{type:"confirm",name:"allowRestart",message:"Allow restart of the CVM if needed for resizing?",default:!1}])).allowRestart);let c=`Are you sure you want to resize CVM ${t} with the following changes:
|
112
112
|
`;if(r.keyValueTable({vCPUs:o.vcpu!==n?`${o.vcpu} -> ${n}`:o.vcpu,Memory:o.memory!==i?`${o.memory} MB -> ${i} MB`:o.memory,"Disk Size":o.disk_size!==a?`${o.disk_size} GB -> ${a} GB`:o.disk_size,"Allow Restart":m?"Yes":"No"}),!e.yes){let{confirm:d}=await Y.prompt([{type:"confirm",name:"confirm",message:c,default:!1}]);if(!d){r.info("Resize operation cancelled");return}}let p=r.startSpinner(`Resizing CVM with App ID ${t}`);await Ot(t,n,i,a,m?1:0),p.stop(!0),r.success(`CVM with App ID ${t} resized successfully`)}catch(o){r.error(`Failed to resize CVM: ${o instanceof Error?o.message:String(o)}`),process.exit(1)}});var Jt=new no().name("cvms").description("Manage Phala Confidential Virtual Machines (CVMs)").addCommand(Ut).addCommand(Lt).addCommand(qt).addCommand(Ht).addCommand(zt).addCommand(jt).addCommand(Bt).addCommand(Gt).addCommand(Kt).addCommand(Zt);process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function io(){new so().name("phala").description(`${Ee}
|
113
113
|
Phala Cloud CLI - Manage your Phala Cloud Deployments`).version("0.0.1").addCommand(Ze).addCommand(Xe).addCommand(ht).addCommand(wt).addCommand(Pt).addCommand(Jt).parse(process.argv)}io().catch(t=>{r.error("An error occurred:",t),process.exit(1)});
|
114
114
|
//# sourceMappingURL=index.js.map
|