@0xobelisk/sui-cli 1.2.0-pre.43 → 1.2.0-pre.45

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/dubhe.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import Ho from"yargs";import{hideBin as Uo}from"yargs/helpers";import nt from"chalk";import{execSync as U,spawn as Se}from"child_process";import k from"chalk";import rt from"chalk";function J(){console.log(rt.yellow(`
2
+ import qo from"yargs";import{hideBin as Ko}from"yargs/helpers";import it from"chalk";import{execSync as z,spawn as Te}from"child_process";import x from"chalk";import ct from"chalk";function Q(){console.log(ct.yellow(`
3
3
  Welcome to Dubhe
4
4
  --from team@obelisk
5
5
  ________ ___ ___ ________ ___ ___ _______
@@ -10,83 +10,83 @@ Welcome to Dubhe
10
10
  \\ \\_______\\ \\_______\\ \\_______\\ \\__\\ \\__\\ \\_______\\
11
11
  \\|_______|\\|_______|\\|_______|\\|__|\\|__|\\|_______|
12
12
 
13
- `))}import{Transaction as ee}from"@0xobelisk/sui-client";import{execSync as vt}from"child_process";import C from"chalk";import*as ie from"fs/promises";import{mkdirSync as dt,writeFileSync as ut}from"fs";import{dirname as pt}from"path";import{SUI_PRIVATE_KEY_PREFIX as gt}from"@mysten/sui/cryptography";import V from"chalk";import{ZodError as at}from"zod";import{fromZodError as it,ValidationError as lt}from"zod-validation-error";var re=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},E=class extends Error{name="DubheCliError"};function N(e){if(e instanceof lt)console.log(V.redBright(e.message));else if(e instanceof at){let t=it(e,{prefixSeparator:`
13
+ `))}import{Transaction as oe}from"@0xobelisk/sui-client";import{execSync as Ct}from"child_process";import _ from"chalk";import*as ce from"fs/promises";import{mkdirSync as mt,writeFileSync as ft}from"fs";import{dirname as ht}from"path";import{SUI_PRIVATE_KEY_PREFIX as yt}from"@mysten/sui/cryptography";import W from"chalk";import{ZodError as dt}from"zod";import{fromZodError as ut,ValidationError as pt}from"zod-validation-error";var ie=class extends Error{name="NotInsideProjectError";message="You are not inside a Dubhe project"},I=class extends Error{name="DubheCliError"};function F(e){if(e instanceof pt)console.log(W.redBright(e.message));else if(e instanceof dt){let t=ut(e,{prefixSeparator:`
14
14
  - `,issueSeparator:`
15
- - `});console.log(V.redBright(t.message))}else e instanceof re?(console.log(V.red(e.message)),console.log(""),console.log(V.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof E?console.log(V.red(e)):console.log(e)}import*as R from"fs";import A from"chalk";import{spawn as ye}from"child_process";import{Dubhe as mt,loadMetadata as ft}from"@0xobelisk/sui-client";var L={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.43",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",publishConfig:{access:"public"},engines:{node:">=18"},exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"}};function le(e){if(e.startsWith(gt))return e.length===70?e:!1;if(e.startsWith("0x")){let t=e.slice(2);return t.length===64?t:!1}else return e.length===64?e:!1}async function ce(e,t){try{let o=await ie.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch(o){throw new Error(`read .history/sui_${t}/latest.json failed. ${o}`)}}async function X(e,t){try{let o=await ie.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function Z(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await X(o,"mainnet");case"testnet":return await X(o,"testnet");case"devnet":return await X(o,"devnet");case"localnet":return await X(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function be(e,t){return(await ce(e,t)).packageId}async function de(e,t,o,n,s,r,i){let u={projectName:e,network:t,packageId:o,dappHub:n,components:i,upgradeCap:s,version:r},c=process.cwd(),d=JSON.stringify(u,null,2);await ae(d,`${c}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function W(e,t,o){let n=process.cwd();try{let s=await ft(t,o);if(s){let r=JSON.stringify(s,null,2);await ae(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await ae(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(A.yellow(`Warning: Failed to save metadata: ${s}`))}}async function ae(e,t,o){dt(pt(t),{recursive:!0}),ut(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function ht(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${L.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${L.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function Q(e,t){let o=R.readFileSync(e,"utf-8"),n=ht(t),s=o.replace(/Dubhe = \{.*\}/,n);R.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function yt(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"sui_getLatestCheckpointSequenceNumber",params:[]})});return t.ok?!(await t.json()).error:!1}catch{return!1}}async function bt(e){let t={localnet:"http://127.0.0.1:9000",devnet:"https://fullnode.devnet.sui.io:443/",testnet:"https://fullnode.testnet.sui.io:443/",mainnet:"https://fullnode.mainnet.sui.io:443/"},o=t[e];if(!await yt(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,r)=>{let i="",u="",c=ye("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});c.stdout.on("data",d=>{u+=d.toString()}),c.stderr.on("data",d=>{i+=d.toString()}),c.on("error",d=>{console.error(A.red(`
16
- \u274C Failed to execute sui command: ${d.message}`)),r(new Error(`Failed to execute sui command: ${d.message}`))}),c.on("exit",d=>{if(i.includes("already exists")||u.includes("already exists")){console.log(A.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(d===0)console.log(A.green(`Successfully added environment ${e}`)),s();else{let h=i||u||`Process exited with code ${d}`;console.error(A.red(`
17
- \u274C Failed to add environment ${e}`)),console.error(A.red(` \u2514\u2500 ${h.trim()}`)),r(new Error(h))}})})}async function H(e){try{return await bt(e),new Promise((t,o)=>{let n="",s="",r=ye("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{n+=i.toString()}),r.on("error",i=>{console.error(A.red(`
18
- \u274C Failed to execute sui command: ${i.message}`)),o(new Error(`Failed to execute sui command: ${i.message}`))}),r.on("exit",i=>{if(i===0)console.log(A.green(`Successfully switched to environment ${e}`)),t();else{let u=n||s||`Process exited with code ${i}`;console.error(A.red(`
19
- \u274C Failed to switch to environment ${e}`)),console.error(A.red(` \u2514\u2500 ${u.trim()}`)),o(new Error(u))}})})}catch(t){throw t}}var j=e=>new Promise(t=>setTimeout(t,e));function wt(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new E(`Missing private key environment variable.
15
+ - `});console.log(W.redBright(t.message))}else e instanceof ie?(console.log(W.red(e.message)),console.log(""),console.log(W.blue("To learn more about Dubhe's configuration, please go to https://github.com/0xobelisk"))):e instanceof I?console.log(W.red(e)):console.log(e)}import*as U from"fs";import M from"chalk";import{spawn as we}from"child_process";import{Dubhe as bt,loadMetadata as wt}from"@0xobelisk/sui-client";var B={name:"@0xobelisk/sui-cli",version:"1.2.0-pre.45",description:"Tookit for interacting with move eps framework",keywords:["sui","obelisk labs","move","blockchain"],type:"module",author:"team@obelisk.build",homepage:"https://github.com/0xobelisk/dubhe/tree/main/packages/sui-cli#readme",bugs:"https://github.com/0xobelisk/dubhe/issues",repository:{type:"git",url:"https://github.com/0xobelisk/dubhe.git"},license:"Apache-2.0",publishConfig:{access:"public"},engines:{node:">=18"},exports:{".":"./dist/index.js"},types:"src/index.ts",bin:{dubhe:"./dist/dubhe.js"},scripts:{build:"pnpm run type-check && pnpm run build:js","build:js":"tsup && chmod +x ./dist/dubhe.js",clean:"pnpm run clean:js","clean:js":"rimraf dist",dev:"tsup --watch",lint:"eslint . --ext .ts",format:"prettier --write .","format:check":"prettier --check .","type-check":"tsc --noEmit",validate:"pnpm format:check && pnpm type-check"},dependencies:{"@0xobelisk/sui-client":"workspace:*","@0xobelisk/sui-common":"workspace:*","@mysten/sui":"^1.19.0","@types/sqlite3":"^3.1.11","@types/wait-on":"^5.3.4",chalk:"^5.0.1",child_process:"^1.0.2",chokidar:"^3.5.3","cli-progress":"^3.12.0","cli-table3":"^0.6.5",dotenv:"^16.0.3",ejs:"^3.1.8",execa:"^7.0.0",glob:"^8.0.3","http-proxy-agent":"^7.0.2","https-proxy-agent":"^7.0.6",inquirer:"^9.2.15",ora:"^5.4.1",path:"^0.12.7",sqlite:"^5.1.1",sqlite3:"^5.1.7",typescript:"5.1.6","wait-on":"^7.0.1",yargs:"^17.7.1",zod:"^3.22.3","zod-validation-error":"^1.3.0"},devDependencies:{"@types/cli-progress":"^3.11.5","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@types/inquirer":"^9.0.7","@types/node":"^18.15.11","@types/yargs":"^17.0.10",eslint:"^8.56.0","eslint-config-prettier":"^9.1.0",prettier:"3.3.3","ts-node":"^10.9.1",tsup:"^6.7.0",tsx:"^3.12.6",vitest:"0.31.4"}};function de(e){if(e.startsWith(yt))return e.length===70?e:!1;if(e.startsWith("0x")){let t=e.slice(2);return t.length===64?t:!1}else return e.length===64?e:!1}async function ue(e,t){try{let o=await ce.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o)}catch(o){throw new Error(`read .history/sui_${t}/latest.json failed. ${o}`)}}async function Z(e,t){try{let o=await ce.readFile(`${e}/.history/sui_${t}/latest.json`,"utf8");return JSON.parse(o).dappHub}catch{return""}}async function ee(e){let o=`${process.cwd()}/src/dubhe`;switch(e){case"mainnet":return await Z(o,"mainnet");case"testnet":return await Z(o,"testnet");case"devnet":return await Z(o,"devnet");case"localnet":return await Z(o,"localnet");default:throw new Error(`Invalid network: ${e}`)}}async function ve(e,t){return(await ue(e,t)).packageId}async function pe(e,t,o,n,s,r,i,u,c){let d={projectName:e,network:t,packageId:o,dappHub:n,upgradeCap:s,version:r,components:i,resources:u,enums:c},f=process.cwd(),m=JSON.stringify(d,null,2);await le(m,`${f}/src/${e}/.history/sui_${t}/latest.json`,"Update deploy log")}async function q(e,t,o){let n=process.cwd();try{let s=await wt(t,o);if(s){let r=JSON.stringify(s,null,2);await le(r,`${n}/src/${e}/.history/sui_${t}/${o}.json`,"Save package metadata"),await le(r,`${n}/metadata.json`,"Save latest metadata")}}catch(s){console.warn(M.yellow(`Warning: Failed to save metadata: ${s}`))}}async function le(e,t,o){mt(ht(t),{recursive:!0}),ft(t,e),o!==void 0&&console.log(`${o}: ${t}`)}function vt(e){switch(e){case"localnet":return'Dubhe = { local = "../dubhe" }';case"testnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${B.version}" }`;case"mainnet":return`Dubhe = { git = "https://github.com/0xobelisk/dubhe-wip.git", subdir = "packages/sui-framework/src/dubhe", rev = "v${B.version}" }`;default:throw new Error(`Unsupported network: ${e}`)}}async function te(e,t){let o=U.readFileSync(e,"utf-8"),n=vt(t),s=o.replace(/Dubhe = \{.*\}/,n);U.writeFileSync(e,s,"utf-8"),console.log(`Updated Dubhe dependency in ${e} for ${t}.`)}async function xt(e){try{let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"sui_getLatestCheckpointSequenceNumber",params:[]})});return t.ok?!(await t.json()).error:!1}catch{return!1}}async function kt(e){let t={localnet:"http://127.0.0.1:9000",devnet:"https://fullnode.devnet.sui.io:443/",testnet:"https://fullnode.testnet.sui.io:443/",mainnet:"https://fullnode.mainnet.sui.io:443/"},o=t[e];if(!await xt(o))throw new Error(`RPC endpoint ${o} is not available. Please check your network connection or try again later.`);return new Promise((s,r)=>{let i="",u="",c=we("sui",["client","new-env","--alias",e,"--rpc",t[e]],{env:{...process.env},stdio:"pipe"});c.stdout.on("data",d=>{u+=d.toString()}),c.stderr.on("data",d=>{i+=d.toString()}),c.on("error",d=>{console.error(M.red(`
16
+ \u274C Failed to execute sui command: ${d.message}`)),r(new Error(`Failed to execute sui command: ${d.message}`))}),c.on("exit",d=>{if(i.includes("already exists")||u.includes("already exists")){console.log(M.yellow(`Environment ${e} already exists, proceeding...`)),s();return}if(d===0)console.log(M.green(`Successfully added environment ${e}`)),s();else{let f=i||u||`Process exited with code ${d}`;console.error(M.red(`
17
+ \u274C Failed to add environment ${e}`)),console.error(M.red(` \u2514\u2500 ${f.trim()}`)),r(new Error(f))}})})}async function L(e){try{return await kt(e),new Promise((t,o)=>{let n="",s="",r=we("sui",["client","switch","--env",e],{env:{...process.env},stdio:"pipe"});r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{n+=i.toString()}),r.on("error",i=>{console.error(M.red(`
18
+ \u274C Failed to execute sui command: ${i.message}`)),o(new Error(`Failed to execute sui command: ${i.message}`))}),r.on("exit",i=>{if(i===0)console.log(M.green(`Successfully switched to environment ${e}`)),t();else{let u=n||s||`Process exited with code ${i}`;console.error(M.red(`
19
+ \u274C Failed to switch to environment ${e}`)),console.error(M.red(` \u2514\u2500 ${u.trim()}`)),o(new Error(u))}})})}catch(t){throw t}}var O=e=>new Promise(t=>setTimeout(t,e));function $t(){let e=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(!e)throw new I(`Missing private key environment variable.
20
20
  Run 'echo "PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
21
21
  or 'echo "NEXT_PUBLIC_PRIVATE_KEY=YOUR_PRIVATE_KEY" > .env'
22
- in your contracts directory to use the default sui private key.`);let t=le(e);if(t===!1)throw new E("Please check your privateKey.");return t}function F({network:e,packageId:t,metadata:o}){let n=wt();return new mt({networkType:e,secretKey:n,packageId:t,metadata:o})}function we(e){let t=Object.entries(e.components).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{entity_id:"address"},{value:r}],keys:["entity_id"]}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"]}};let i=r.fields||{},u=r.keys||["entity_id"];return!i.entity_id&&u.includes("entity_id")&&(i.entity_id="address"),{[s]:{fields:Object.entries(i).map(([c,d])=>({[c]:d})),keys:u}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[]}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[]}};let i=r.fields||{},u=r.keys||[];return{[s]:{fields:Object.entries(i).map(([c,d])=>({[c]:d})),keys:u}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((u,c)=>u.localeCompare(c)).map((u,c)=>({[c]:u}));return{[s]:{fields:i}}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function ue(e,t){let o=`${e}/Move.toml`,s=R.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);R.writeFileSync(o,s,"utf-8")}import*as T from"fs";import*as ve from"path";async function xe(e,t){if(!T.existsSync(e))return;let o=T.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");T.writeFileSync(e,s,"utf-8")}function ke(e,t,o,n,s){let r=ve.resolve(e),i=T.readFileSync(r,"utf-8"),u=i.split(`
23
- `),c=u.findIndex(y=>y.trim()===`[env.${t}]`),d={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(c===-1)if(o==="publish")d.originalPublishedId=s,d.latestPublishedId=s,d.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let y=c+1;y<u.length;y++){let v=u[y].trim();if(v.startsWith("["))break;let[_,p]=v.split("=").map(l=>l.trim().replace(/"/g,""));switch(_){case"original-published-id":d.originalPublishedId=p;break;case"latest-published-id":d.latestPublishedId=p;break;case"published-version":d.publishedVersion=parseInt(p,10);break}}o==="publish"?(d.originalPublishedId=s,d.latestPublishedId=s,d.publishedVersion=1):o==="upgrade"&&(d.latestPublishedId=s,d.publishedVersion+=1)}let h=`
22
+ in your contracts directory to use the default sui private key.`);let t=de(e);if(t===!1)throw new I("Please check your privateKey.");return t}function R({network:e,packageId:t,metadata:o}){let n=$t();return new bt({networkType:e,secretKey:n,packageId:t,metadata:o})}function xe(e){let t=Object.entries(e.components).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{entity_id:"address"},{value:r}],keys:["entity_id"]}};if(Object.keys(r).length===0)return{[s]:{fields:[{entity_id:"address"}],keys:["entity_id"]}};let i=r.fields||{},u=r.keys||["entity_id"];return!i.entity_id&&u.includes("entity_id")&&(i.entity_id="address"),{[s]:{fields:Object.entries(i).map(([c,d])=>({[c]:d})),keys:u}}}),o=Object.entries(e.resources).map(([s,r])=>{if(typeof r=="string")return{[s]:{fields:[{value:r}],keys:[]}};if(Object.keys(r).length===0)return{[s]:{fields:[],keys:[]}};let i=r.fields||{},u=r.keys||[];return{[s]:{fields:Object.entries(i).map(([c,d])=>({[c]:d})),keys:u}}}),n=Object.entries(e.enums||{}).map(([s,r])=>{let i=r.sort((u,c)=>u.localeCompare(c)).map((u,c)=>({[c]:u}));return{[s]:{fields:i}}});return JSON.stringify({components:t,resources:o,enums:n},null,2)}function ge(e,t){let o=`${e}/Move.toml`,s=U.readFileSync(o,"utf-8").replace(/dubhe\s*=\s*"[^"]*"/,`dubhe = "${t}"`);U.writeFileSync(o,s,"utf-8")}import*as A from"fs";import*as ke from"path";async function $e(e,t){if(!A.existsSync(e))return;let o=A.readFileSync(e,"utf-8"),n=new RegExp(`\\[env\\.${t}\\][\\s\\S]*?(?=\\[|$)`,"g"),s=o.replace(n,"");A.writeFileSync(e,s,"utf-8")}function Ce(e,t,o,n,s){let r=ke.resolve(e),i=A.readFileSync(r,"utf-8"),u=i.split(`
23
+ `),c=u.findIndex(h=>h.trim()===`[env.${t}]`),d={chainId:n,originalPublishedId:"",latestPublishedId:"",publishedVersion:0};if(c===-1)if(o==="publish")d.originalPublishedId=s,d.latestPublishedId=s,d.publishedVersion=1;else throw new Error(`Network type [env.${t}] not found in the file and cannot upgrade.`);else{for(let h=c+1;h<u.length;h++){let y=u[h].trim();if(y.startsWith("["))break;let[$,P]=y.split("=").map(l=>l.trim().replace(/"/g,""));switch($){case"original-published-id":d.originalPublishedId=P;break;case"latest-published-id":d.latestPublishedId=P;break;case"published-version":d.publishedVersion=parseInt(P,10);break}}o==="publish"?(d.originalPublishedId=s,d.latestPublishedId=s,d.publishedVersion=1):o==="upgrade"&&(d.latestPublishedId=s,d.publishedVersion+=1)}let f=`
24
24
  [env.${t}]
25
25
  chain-id = "${d.chainId}"
26
26
  original-published-id = "${d.originalPublishedId}"
27
27
  latest-published-id = "${d.latestPublishedId}"
28
28
  published-version = "${d.publishedVersion}"
29
- `,f=c===-1?i+h:u.slice(0,c).join(`
30
- `)+h;T.writeFileSync(r,f,"utf-8")}function $e(e){let t,o;try{let n=JSON.parse(vt(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(C.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function Ce(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.data.reduce((r,i)=>r+Number(i.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(C.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function xt(e,t,o,n,s){console.log(`
31
- \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let r=await Ce(e);console.log(" \u251C\u2500 Validating Environment..."),await xe(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
- \u{1F4E6} Building Contract...`);let[i,u]=$e(n);console.log(`
33
- \u{1F504} Publishing Contract...`);let c=new ee;s&&c.setGasBudget(s);let[d]=c.publish({modules:i,dependencies:u});c.transferObjects([d],e.getAddress());let h;try{h=await e.signAndSendTxn({tx:c})}catch(m){console.error(C.red(" \u2514\u2500 Publication failed")),console.error(m.message),process.exit(1)}(!h||h.effects?.status.status==="failure")&&(console.log(C.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let f=1,y="",v="",_=t.components,p="",l=[];h.objectChanges.map(m=>{m.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${m.packageId}`),y=m.packageId||""),m.type==="created"&&m.objectType&&m.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${m.objectId}`),p=m.objectId||""),m.type==="created"&&m.objectType&&m.objectType.includes("dapp_hub::DappHub")&&(v=m.objectId||""),m.type==="created"&&l.push(m)}),console.log(` \u2514\u2500 Transaction: ${h.digest}`),ke(`${n}/Move.lock`,o,"publish",r,y),console.log(`
34
- \u26A1 Executing Deploy Hook...`),await j(5e3);let g=new ee,x=[],b=t.name==="dubhe"?v:await Z(o);x.push(g.object(b)),x.push(g.object("0x6")),g.moveCall({target:`${y}::genesis::run`,arguments:x});let S;try{S=await e.signAndSendTxn({tx:g})}catch(m){console.error(C.red(" \u2514\u2500 Deploy hook execution failed")),console.error(m.message),process.exit(1)}if(S.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${S.digest}`),console.log(`
35
- \u{1F4CB} Created Objects:`),l.map($=>{console.log(` \u251C\u2500 Type: ${$.objectType}`),console.log(` \u2514\u2500 ID: ${$.objectId}`)}),await de(t.name,o,y,v,p,f,_),await W(t.name,o,y);let m=JSON.parse(T.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));m.package_id=y,T.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(m,null,2)),console.log(`
29
+ `,m=c===-1?i+f:u.slice(0,c).join(`
30
+ `)+f;A.writeFileSync(r,m,"utf-8")}function Se(e){let t,o;try{let n=JSON.parse(Ct(`sui move build --dump-bytecode-as-base64 --path ${e}`,{encoding:"utf-8",stdio:"pipe"}));t=n.modules,o=n.dependencies}catch(n){console.error(_.red(" \u2514\u2500 Build failed")),console.error(n.stdout),process.exit(1)}return[t,o]}async function _e(e){let t=await e.suiInteractor.currentClient.getChainIdentifier();console.log(` \u251C\u2500 ChainId: ${t}`);let o=e.getAddress(),n=await e.suiInteractor.currentClient.getCoins({owner:o,coinType:"0x2::sui::SUI"});if(n.data.length>0){let s=n.data.reduce((r,i)=>r+Number(i.balance),0);if(s>0)return console.log(` \u251C\u2500 Deployer balance: ${s/10**9} SUI`),t;console.log(_.yellow(" \u251C\u2500 Deployer balance: 0 SUI, please ensure your account has sufficient SUI balance"))}return t}async function St(e,t,o,n,s){console.log(`
31
+ \u{1F680} Starting Contract Publication...`),console.log(` \u251C\u2500 Project: ${n}`),console.log(` \u251C\u2500 Network: ${o}`),console.log(" \u251C\u2500 Waiting for node...");let r=await _e(e);console.log(" \u251C\u2500 Validating Environment..."),await $e(`${n}/Move.lock`,o),console.log(` \u2514\u2500 Account: ${e.getAddress()}`),console.log(`
32
+ \u{1F4E6} Building Contract...`);let[i,u]=Se(n);console.log(`
33
+ \u{1F504} Publishing Contract...`);let c=new oe;s&&c.setGasBudget(s);let[d]=c.publish({modules:i,dependencies:u});c.transferObjects([d],e.getAddress());let f;try{f=await e.signAndSendTxn({tx:c})}catch(g){console.error(_.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}(!f||f.effects?.status.status==="failure")&&(console.log(_.red(" \u2514\u2500 Publication failed")),process.exit(1)),console.log(" \u251C\u2500 Processing publication results...");let m=1,h="",y="",$=t.components,P=t.resources,l=t.enums,p="",b=[];f.objectChanges.map(g=>{g.type==="published"&&(console.log(` \u251C\u2500 Package ID: ${g.packageId}`),h=g.packageId||""),g.type==="created"&&g.objectType&&g.objectType==="0x2::package::UpgradeCap"&&(console.log(` \u251C\u2500 Upgrade Cap: ${g.objectId}`),p=g.objectId||""),g.type==="created"&&g.objectType&&g.objectType.includes("dapp_service::DappHub")&&(y=g.objectId||""),g.type==="created"&&b.push(g)}),console.log(` \u2514\u2500 Transaction: ${f.digest}`),Ce(`${n}/Move.lock`,o,"publish",r,h),console.log(`
34
+ \u26A1 Executing Deploy Hook...`),await O(5e3);let v=new oe,C=[],S=t.name==="dubhe"?y:await ee(o);C.push(v.object(S)),C.push(v.object("0x6")),v.moveCall({target:`${h}::genesis::run`,arguments:C});let D;try{D=await e.signAndSendTxn({tx:v})}catch(g){console.error(_.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}if(D.effects?.status.status==="success"){console.log(" \u251C\u2500 Hook execution successful"),console.log(` \u251C\u2500 Transaction: ${D.digest}`),console.log(`
35
+ \u{1F4CB} Created Objects:`),b.map(k=>{console.log(` \u251C\u2500 ID: ${k.objectId}`),console.log(` \u2514\u2500 Type: ${k.objectType}`)}),await pe(t.name,o,h,y,p,m,$,P,l),await q(t.name,o,h);let g=JSON.parse(A.readFileSync(`${process.cwd()}/dubhe.config.json`,"utf-8"));g.package_id=h,A.writeFileSync(`${process.cwd()}/dubhe.config.json`,JSON.stringify(g,null,2)),console.log(`
36
36
  \u2705 Contract Publication Complete
37
- `)}else console.log(C.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(C.yellow(" Please republish or manually call deploy_hook::run")),console.log(C.yellow(" Please check the transaction digest:")),console.log(C.yellow(` ${S.digest}`)),process.exit(1)}async function kt(e){return T.existsSync(e)?!0:(console.log(C.yellow(`
38
- \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(C.yellow(" \u251C\u2500 Expected Path:"),e),console.log(C.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(C.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(C.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(C.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(C.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function $t(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await kt(n))return;console.log(`
39
- \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await Ce(e);await xe(`${n}/Move.lock`,t),await ue(n,"0x0");let[r,i]=$e(n),u=new ee,[c]=u.publish({modules:r,dependencies:i});u.transferObjects([c],e.getAddress());let d;try{d=await e.signAndSendTxn({tx:u})}catch(g){console.error(C.red(" \u2514\u2500 Publication failed")),console.error(g.message),process.exit(1)}(!d||d.effects?.status.status==="failure")&&(console.log(C.red(" \u2514\u2500 Publication failed")),process.exit(1));let h=1,f="",y="",v={},_="";d.objectChanges.map(g=>{g.type==="published"&&(f=g.packageId||""),g.type==="created"&&g.objectType&&g.objectType==="0x2::package::UpgradeCap"&&(_=g.objectId||""),g.type==="created"&&g.objectType&&g.objectType.includes("dapp_hub::DappHub")&&(y=g.objectId||"")}),await j(3e3);let p=new ee;p.moveCall({target:`${f}::dubhe_genesis::run`,arguments:[p.object(y),p.object("0x6")]});let l;try{l=await e.signAndSendTxn({tx:p})}catch(g){console.error(C.red(" \u2514\u2500 Deploy hook execution failed")),console.error(g.message),process.exit(1)}if(l.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await ue(n,f),await de("dubhe",t,f,y,_,h,v),ke(`${n}/Move.lock`,t,"publish",s,f)}async function _e(e,t,o){await H(t);let n=F({network:t}),r=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await $t(n,t),e.name!=="dubhe"&&await Q(`${r}/Move.toml`,t),await xt(n,e,t,r,o)}import{Dubhe as Ct}from"@0xobelisk/sui-client";import*as te from"fs";function _t(){console.log(k.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{U("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let o of t)try{let n=U(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
- `).filter(r=>r);console.log(k.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{U(`kill -TERM ${r}`,{stdio:"ignore"}),console.log(k.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{U(`kill -KILL ${r}`,{stdio:"ignore"}),console.log(k.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log(k.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?k.green(" \u2514\u2500 Local Node stopped successfully"):k.gray(" \u2514\u2500 No running Local Node found"))}function St(e){try{te.existsSync(e)?(console.log(k.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),te.rmSync(e,{recursive:!0,force:!0}),console.log(k.green(" \u2514\u2500 Directory removed successfully"))):console.log(k.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(k.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function Pt(){try{if(process.platform==="win32")return U('tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH').toString().trim().toLowerCase().includes("sui.exe");{let e=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let t of e)try{let o=U(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function Dt(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new Ct({secretKey:t}).getSigner();Se("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${s.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(k.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(k.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Et(e){let t=()=>{console.log(k.yellow(`
41
- \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function Pe(e,t){if(t)console.log(k.cyan(`
42
- \u{1F504} Force mode enabled`)),_t(),console.log(k.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await j(3e3),St(e),console.log("");else if(Pt()){console.log(k.yellow(`
43
- \u26A0\uFE0F Warning: Local Node Already Running`)),console.log(k.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(k.yellow(" \u2514\u2500 Please stop the existing process first"));return}J(),console.log("\u{1F680} Starting Local Node...");let o=null;try{if(o=Se("sui",["start","--with-faucet","--force-regenesis","--data-ingestion-dir",e],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",s=>{console.error(k.red(`
44
- \u274C Failed to Start Local Node`)),console.error(k.red(` \u2514\u2500 Error: ${s.message}`))}),await j(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await Dt(),await j(2e3),le("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new E("Please check your privateKey.");console.log(k.green("\u{1F389} Local environment is ready!")),Et(o),await new Promise(s=>{o?.on("exit",()=>s())})}catch(n){console.error(k.red(`
45
- \u274C Failed to Start Local Node`)),console.error(k.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var Tt={command:"node",describe:"Manage local Sui node",builder:{"data-dir":{type:"string",default:".chk",desc:"Path to the data directory"},force:{type:"boolean",default:!1,desc:"Force restart: stop existing node and remove data directory"}},async handler({"data-dir":e,force:t}){try{await Pe(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},De=Tt;import{requestSuiFromFaucetV0 as It,getFaucetHost as At}from"@mysten/sui/faucet";import{SuiClient as Nt,getFullnodeUrl as Ft}from"@mysten/sui/client";var pe=60,Mt=1e3,Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],jt={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=F(e).getAddress():o=t,console.log(`
37
+ `)}else console.log(_.yellow(" \u2514\u2500 Deploy hook execution failed")),console.log(_.yellow(" Please republish or manually call deploy_hook::run")),console.log(_.yellow(" Please check the transaction digest:")),console.log(_.yellow(` ${D.digest}`)),process.exit(1)}async function _t(e){return A.existsSync(e)?!0:(console.log(_.yellow(`
38
+ \u2139\uFE0F Dubhe Framework Files Not Found`)),console.log(_.yellow(" \u251C\u2500 Expected Path:"),e),console.log(_.yellow(" \u251C\u2500 To set up Dubhe Framework:")),console.log(_.yellow(" \u2502 1. Create directory: mkdir -p contracts/dubhe")),console.log(_.yellow(" \u2502 2. Clone repository: git clone https://github.com/0xobelisk/dubhe contracts/dubhe")),console.log(_.yellow(" \u2502 3. Or download from: https://github.com/0xobelisk/dubhe")),console.log(_.yellow(" \u2514\u2500 After setup, restart the local node")),!1)}async function Pt(e,t){let n=`${process.cwd()}/src/dubhe`;if(!await _t(n))return;console.log(`
39
+ \u{1F680} Starting Dubhe Framework Publication...`),console.log(" \u251C\u2500 Waiting for node...");let s=await _e(e);await $e(`${n}/Move.lock`,t),await ge(n,"0x0");let[r,i]=Se(n),u=new oe,[c]=u.publish({modules:r,dependencies:i});u.transferObjects([c],e.getAddress());let d;try{d=await e.signAndSendTxn({tx:u})}catch(l){console.error(_.red(" \u2514\u2500 Publication failed")),console.error(l.message),process.exit(1)}(!d||d.effects?.status.status==="failure")&&(console.log(_.red(" \u2514\u2500 Publication failed")),process.exit(1));let f=1,m="",h="",y="";d.objectChanges.map(l=>{l.type==="published"&&(m=l.packageId||""),l.type==="created"&&l.objectType&&l.objectType==="0x2::package::UpgradeCap"&&(y=l.objectId||""),l.type==="created"&&l.objectType&&l.objectType.includes("dapp_service::DappHub")&&(h=l.objectId||"")}),await O(3e3);let $=new oe;$.moveCall({target:`${m}::dubhe_genesis::run`,arguments:[$.object(h),$.object("0x6")]});let P;try{P=await e.signAndSendTxn({tx:$})}catch(l){console.error(_.red(" \u2514\u2500 Deploy hook execution failed")),console.error(l.message),process.exit(1)}if(P.effects?.status.status!=="success")throw new Error("Deploy hook execution failed");await ge(n,m),await pe("dubhe",t,m,h,y,f,{},{},{}),Ce(`${n}/Move.lock`,t,"publish",s,m)}async function Pe(e,t,o){await L(t);let n=R({network:t}),r=`${process.cwd()}/src/${e.name}`;t==="localnet"&&e.name!=="dubhe"&&await Pt(n,t),e.name!=="dubhe"&&await te(`${r}/Move.toml`,t),await St(n,e,t,r,o)}import{Dubhe as Tt}from"@0xobelisk/sui-client";import*as ne from"fs";function Dt(){console.log(x.yellow("\u{1F514} Stopping existing Local Node..."));let e=!1;if(process.platform==="win32")try{z("taskkill /F /IM sui.exe",{stdio:"ignore"}),e=!0}catch{}else{let t=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let o of t)try{let n=z(`pgrep -f "${o}"`,{stdio:"pipe"}).toString().trim();if(n){let s=n.split(`
40
+ `).filter(r=>r);console.log(x.cyan(` \u251C\u2500 Found ${s.length} process(es) matching "${o}"`)),s.forEach(r=>{try{z(`kill -TERM ${r}`,{stdio:"ignore"}),console.log(x.cyan(` \u251C\u2500 Sent SIGTERM to process ${r}`))}catch{try{z(`kill -KILL ${r}`,{stdio:"ignore"}),console.log(x.cyan(` \u251C\u2500 Force killed process ${r}`))}catch{console.log(x.gray(` \u251C\u2500 Process ${r} already terminated`))}}}),e=!0;break}}catch{continue}}console.log(e?x.green(" \u2514\u2500 Local Node stopped successfully"):x.gray(" \u2514\u2500 No running Local Node found"))}function Et(e){try{ne.existsSync(e)?(console.log(x.yellow(`\u{1F5D1}\uFE0F Removing directory: ${e}`)),ne.rmSync(e,{recursive:!0,force:!0}),console.log(x.green(" \u2514\u2500 Directory removed successfully"))):console.log(x.gray(` \u2514\u2500 Directory ${e} does not exist`))}catch(t){console.error(x.red(` \u2514\u2500 Error removing directory: ${t.message}`))}}function It(){try{if(process.platform==="win32")return z('tasklist /FI "IMAGENAME eq sui.exe" /FO CSV /NH').toString().trim().toLowerCase().includes("sui.exe");{let e=["sui start","sui.*start","^sui","sui.*--with-faucet"];for(let t of e)try{let o=z(`pgrep -f "${t}"`,{stdio:"pipe"}).toString().trim();if(o&&o.length>0)return!0}catch{continue}return!1}}catch{return!1}}async function At(){let e=["suiprivkey1qq3ez3dje66l8pypgxynr7yymwps6uhn7vyczespj84974j3zya0wdpu76v","suiprivkey1qp6vcyg8r2x88fllmjmxtpzjl95gd9dugqrgz7xxf50w6rqdqzetg7x4d7s","suiprivkey1qpy3a696eh3m55fwa8h38ss063459u4n2dm9t24w2hlxxzjp2x34q8sdsnc","suiprivkey1qzxwp29favhzrjd95f6uj9nskjwal6nh9g509jpun395y6g72d6jqlmps4c","suiprivkey1qzhq4lv38sesah4uzsqkkmeyjx860xqjdz8qgw36tmrdd5tnle3evxpng57","suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c"];console.log("\u{1F4DD}Accounts"),console.log("=========="),e.forEach((t,o)=>{let s=new Tt({secretKey:t}).getSigner();Te("curl",["--location","--request","POST","http://127.0.0.1:9123/gas","--header","Content-Type: application/json","--data-raw",`{"FixedAmountRequest": {"recipient": "${s.toSuiAddress()}"}}`],{env:{...process.env},stdio:"ignore",detached:!0}),console.log(` \u250C\u2500 Account #${o}: ${s.toSuiAddress()}(1000 SUI)`),console.log(` \u2514\u2500 Private Key: ${t}`)}),console.log("=========="),console.log(x.yellow("\u2139\uFE0F WARNING: These accounts, and their private keys, are publicly known.")),console.log(x.yellow("Any funds sent to them on Mainnet or any other live network WILL BE LOST."))}function Nt(e){let t=()=>{console.log(x.yellow(`
41
+ \u{1F514} Stopping Local Node...`)),e&&e.kill("SIGINT"),process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}async function De(e,t){if(t)console.log(x.cyan(`
42
+ \u{1F504} Force mode enabled`)),Dt(),console.log(x.yellow(" \u251C\u2500 Waiting for processes to terminate...")),await O(3e3),Et(e),console.log("");else if(It()){console.log(x.yellow(`
43
+ \u26A0\uFE0F Warning: Local Node Already Running`)),console.log(x.yellow(" \u251C\u2500 Cannot start a new instance")),console.log(x.yellow(" \u2514\u2500 Please stop the existing process first"));return}Q(),console.log("\u{1F680} Starting Local Node...");let o=null;try{if(o=Te("sui",["start","--with-faucet","--force-regenesis","--data-ingestion-dir",e],{env:{...process.env,RUST_LOG:"off,sui_node=info"},stdio:"ignore"}),o.on("error",s=>{console.error(x.red(`
44
+ \u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${s.message}`))}),await O(5e3),console.log(" \u251C\u2500 Faucet: Enabled"),console.log(" \u2514\u2500 Force Regenesis: Yes"),console.log(" \u2514\u2500 HTTP server: http://127.0.0.1:9000/"),console.log(" \u2514\u2500 Faucet server: http://127.0.0.1:9123/"),await At(),await O(2e3),de("suiprivkey1qzez45sjjsepjgtksqvpq6jw7dzw3zq0dx7a4sulfypd73acaynw5jl9x2c")===!1)throw new I("Please check your privateKey.");console.log(x.green("\u{1F389} Local environment is ready!")),Nt(o),await new Promise(s=>{o?.on("exit",()=>s())})}catch(n){console.error(x.red(`
45
+ \u274C Failed to Start Local Node`)),console.error(x.red(` \u2514\u2500 Error: ${n.message}`)),o&&o.kill("SIGINT"),process.exit(1)}}var Mt={command:"node",describe:"Manage local Sui node",builder:{"data-dir":{type:"string",default:".chk",desc:"Path to the data directory"},force:{type:"boolean",default:!1,desc:"Force restart: stop existing node and remove data directory"}},async handler({"data-dir":e,force:t}){try{await De(e,t)}catch(o){console.error("Error executing command:",o),process.exit(1)}}},Ee=Mt;import{requestSuiFromFaucetV0 as Ft,getFaucetHost as Rt}from"@mysten/sui/faucet";import{SuiClient as jt,getFullnodeUrl as Ot}from"@mysten/sui/client";var me=60,Ht=1e3,Ie=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ut={command:"faucet",describe:"Interact with a Dubhe faucet",builder(e){return e.options({network:{type:"string",desc:"URL of the Dubhe faucet",choices:["testnet","devnet","localnet"],default:"localnet"},recipient:{type:"string",desc:"Sui address to fund"}})},async handler({network:e,recipient:t}){let o="";t===void 0?o=R(e).getAddress():o=t,console.log(`
46
46
  \u{1F30A} Starting Faucet Operation...`),console.log(` \u251C\u2500 Network: ${e}`),t===void 0?(console.log(" \u251C\u2500 Using Environment PrivateKey"),console.log(` \u251C\u2500 Generated Address: ${o}`)):console.log(` \u251C\u2500 Using Provided Address: ${o}`),console.log(" \u251C\u2500 Requesting funds from faucet...");let n=0,s=!1,r=0,i=Date.now(),u=!1,c=()=>{u=!0,process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(`
47
- \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",c);try{for(;n<pe&&!s&&!u;)try{await It({host:At(e),recipient:o}),s=!0}catch{if(u)break;n++,n===pe&&(console.log(` \u2514\u2500 Failed to request funds after ${pe} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let v=Math.floor((Date.now()-i)/1e3),_=Ee[r%Ee.length];r++,process.stdout.write(`\r \u251C\u2500 ${_} Retrying... (${v}s)`),await new Promise(p=>setTimeout(p,Mt))}}finally{process.removeListener("SIGINT",c)}u&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let d=new Nt({url:Ft(e)}),h={owner:o},f=await d.getBalance(h);console.log(`
48
- \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(f.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
47
+ \u2514\u2500 Operation cancelled by user`),process.exit(0)};process.on("SIGINT",c);try{for(;n<me&&!s&&!u;)try{await Ft({host:Rt(e),recipient:o}),s=!0}catch{if(u)break;n++,n===me&&(console.log(` \u2514\u2500 Failed to request funds after ${me} attempts.`),console.log(" \u2514\u2500 Please check your network connection and try again later."),process.exit(1));let y=Math.floor((Date.now()-i)/1e3),$=Ie[r%Ie.length];r++,process.stdout.write(`\r \u251C\u2500 ${$} Retrying... (${y}s)`),await new Promise(P=>setTimeout(P,Ht))}}finally{process.removeListener("SIGINT",c)}u&&process.exit(0),process.stdout.write("\r"+" ".repeat(50)+"\r"),console.log(" \u2514\u2500 Checking balance...");let d=new jt({url:Ot(e)}),f={owner:o},m=await d.getBalance(f);console.log(`
48
+ \u{1F4B0} Account Summary`),console.log(` \u251C\u2500 Address: ${o}`),console.log(` \u2514\u2500 Balance: ${(Number(m.totalBalance)/1e9).toFixed(4)} SUI`),console.log(`
49
49
  \u2705 Faucet Operation Complete
50
- `),process.exit(0)}},Te=jt;import{schemaGen as Ot,loadConfig as Rt}from"@0xobelisk/sui-common";import Ht from"chalk";import Ut from"node:path";var zt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await Rt(e),n=Ut.dirname(e);await Ot(n,o,t),process.exit(0)}catch(o){console.log(Ht.red("Schemagen failed!")),console.error(o.message)}}},Ie=zt;import{loadConfig as Vt}from"@0xobelisk/sui-common";import{execSync as Lt}from"child_process";var Wt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await Vt(t);Lt(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await _e(n,e,o)}catch(n){N(n),process.exit(1)}process.exit(0)}},Ae=Wt;import{execSync as Bt}from"child_process";import{loadConfig as qt}from"@0xobelisk/sui-common";var Kt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await qt(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Bt(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Ne=Kt;import{execSync as Yt,exec as Gt}from"child_process";import Jt from"chalk";import{loadConfig as Xt}from"@0xobelisk/sui-common";var Zt={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await Xt(e),r=`${process.cwd()}/src/${n.name}`;await H(t),await Q(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,u=Yt(i,{encoding:"utf-8"});console.log(u),Gt(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(Jt.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Fe=Zt;var Qt={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){J()}},Me=Qt;import{Dubhe as je}from"@0xobelisk/sui-client";import*as q from"fs";import B from"chalk";async function Oe(e=!1,t=!1){t&&(console.log(B.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(B.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
- `)));let o=process.cwd(),n,s="";try{s=q.readFileSync(`${o}/.env`,"utf8");let r=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(r=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),r){let i=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",u=s.split(`
52
- `),c=!1;for(let f=u.length-1;f>=0;f--){let y=u[f];if(y.endsWith(r)){let[v]=y.split("=");t?c=v==="PRIVATE_KEY":c=v==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(c){for(let f=u.length-1;f>=0;f--)if(u[f].endsWith(r)){let v=`${i}=${r}`;u[f]=v,s=u.join(`
53
- `),q.writeFileSync(`${o}/.env`,s);break}}let h=new je({secretKey:r}).getSigner();console.log(B.blue(`Using existing account: ${h.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new je().getSigner();n=i.getSecretKey();let c=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
- `+c:s=c,q.writeFileSync(`${o}/.env`,s),console.log(B.green(`File created/updated at: ${o}/.env`)),console.log(B.blue(`New account generated: ${i.toSuiAddress()}`))}}var eo={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await Oe(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Re=eo;import to from"chalk";import oo from"dotenv";oo.config();async function He(e){try{let o=await F({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new E("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(to.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new E("Failed to check balance: "+t)}}var no={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await He(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},Ue=no;import{mkdirSync as so,writeFileSync as ro}from"fs";import{dirname as ao}from"path";async function io(e,t,o){let n=await Z(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
50
+ `),process.exit(0)}},Ae=Ut;import{schemaGen as Lt,loadConfig as zt}from"@0xobelisk/sui-common";import Vt from"chalk";import Wt from"node:path";var Bt={command:"schemagen",describe:"Autogenerate Dubhe schemas based on the config file",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"}},async handler({"config-path":e,network:t}){try{if(!e)throw new Error("Config path is required");let o=await zt(e),n=Wt.dirname(e);await Lt(n,o,t),process.exit(0)}catch(o){console.log(Vt.red("Schemagen failed!")),console.error(o.message)}}},Ne=Bt;import{loadConfig as qt}from"@0xobelisk/sui-common";import{execSync as Kt}from"child_process";var Gt={command:"publish",describe:"Publish dubhe move contract",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",default:"dubhe.config.ts",desc:"Configuration file path"},"gas-budget":{type:"number",desc:"Optional gas budget for the transaction",optional:!0}})},async handler({network:e,"config-path":t,"gas-budget":o}){try{let n=await qt(t);Kt(`pnpm dubhe convert-json --config-path ${t}`,{encoding:"utf-8"}),await Pe(n,e,o)}catch(n){F(n),process.exit(1)}process.exit(0)}},Me=Gt;import{execSync as Yt}from"child_process";import{loadConfig as Jt}from"@0xobelisk/sui-common";var Xt={command:"test",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},test:{type:"string",desc:"Run a specific test"},"gas-limit":{type:"string",desc:"Set the gas limit for the test",default:"100000000"}})},async handler({"config-path":e,test:t,"gas-limit":o}){try{console.log("\u{1F680} Running move test");let n=await Jt(e),i=`sui move test --path ${`${process.cwd()}/src/${n.name}`} ${t?` --test ${t}`:""} --gas-limit ${o}`;Yt(i,{stdio:"inherit",encoding:"utf-8"})}catch{process.exit(0)}}},Fe=Xt;import{execSync as Qt,exec as Zt}from"child_process";import eo from"chalk";import{loadConfig as to}from"@0xobelisk/sui-common";var oo={command:"build",describe:"Run tests in Dubhe contracts",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},network:{type:"string",default:"localnet",choices:["mainnet","testnet","devnet","localnet"],desc:"Node network (mainnet/testnet/devnet/localnet)"},"dump-bytecode-as-base64":{type:"boolean",default:!1,desc:"Dump bytecode as base64"}})},async handler({"config-path":e,network:t,"dump-bytecode-as-base64":o}){try{console.log("\u{1F680} Running move build");let n=await to(e),r=`${process.cwd()}/src/${n.name}`;await L(t),await te(r+"/Move.toml",t);let i=`sui move build --path ${r} ${o?" --dump-bytecode-as-base64":""}`,u=Qt(i,{encoding:"utf-8"});console.log(u),Zt(`pnpm dubhe convert-json --config-path ${e}`)}catch(n){console.error(eo.red("Error executing sui move build:")),console.log(n.stdout),process.exit(0)}}},Re=oo;var no={command:"hello",describe:"hello, dubhe",builder(e){return e},async handler(){Q()}},je=no;import{Dubhe as Oe}from"@0xobelisk/sui-client";import*as G from"fs";import K from"chalk";async function He(e=!1,t=!1){t&&(console.log(K.gray("Note: The generated account will be stored in the .env file with NEXT_PUBLIC_ prefix for client-side usage.")),console.log(K.yellow(`Warning: Do not expose the .env file, it is intended for local testing only.
51
+ `)));let o=process.cwd(),n,s="";try{s=G.readFileSync(`${o}/.env`,"utf8");let r=process.env.PRIVATE_KEY||process.env.NEXT_PUBLIC_PRIVATE_KEY;if(t&&(r=process.env.NEXT_PUBLIC_PRIVATE_KEY||process.env.PRIVATE_KEY),r){let i=t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY",u=s.split(`
52
+ `),c=!1;for(let m=u.length-1;m>=0;m--){let h=u[m];if(h.endsWith(r)){let[y]=h.split("=");t?c=y==="PRIVATE_KEY":c=y==="NEXT_PUBLIC_PRIVATE_KEY";break}}if(c){for(let m=u.length-1;m>=0;m--)if(u[m].endsWith(r)){let y=`${i}=${r}`;u[m]=y,s=u.join(`
53
+ `),G.writeFileSync(`${o}/.env`,s);break}}let f=new Oe({secretKey:r}).getSigner();console.log(K.blue(`Using existing account: ${f.toSuiAddress()}`));return}}catch{}if(e||!n){let i=new Oe().getSigner();n=i.getSecretKey();let c=`${t?"NEXT_PUBLIC_PRIVATE_KEY":"PRIVATE_KEY"}=${n}`;s?s=s.trim()+`
54
+ `+c:s=c,G.writeFileSync(`${o}/.env`,s),console.log(K.green(`File created/updated at: ${o}/.env`)),console.log(K.blue(`New account generated: ${i.toSuiAddress()}`))}}var so={command:"generate-key",describe:"Generate a new account keypair and save it to a .env file",builder:{force:{type:"boolean",default:!1,desc:"Force generate a new keypair"},"use-next-public":{type:"boolean",default:!1,desc:"Use the NEXT_PUBLIC_ prefix for client-side usage"}},async handler({force:e,"use-next-public":t}){try{await He(e,t)}catch(o){console.error("Error generating account:",o),process.exit(1)}process.exit(0)}},Ue=so;import ro from"chalk";import ao from"dotenv";ao.config();async function Le(e){try{let o=await R({network:e}).getBalance(),n=Number(o.totalBalance)/1e9;if(n===0)throw new I("Your account balance is 0 SUI. Please get some SUI to proceed.");console.log(ro.green(`Current account balance: ${n.toFixed(4)} SUI`))}catch(t){throw new I("Failed to check balance: "+t)}}var io={command:"check-balance",describe:"Check the balance of the account",builder:{network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to check balance on",default:"localnet"}},async handler({network:e}){try{await Le(e)}catch(t){console.error("Error checking balance:",t),process.exit(1)}process.exit(0)}},ze=io;import{mkdirSync as lo,writeFileSync as co}from"fs";import{dirname as uo}from"path";async function po(e,t,o){let n=await ee(e),s=`type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
55
55
 
56
56
  export const NETWORK: NetworkType = '${e}';
57
57
  export const PACKAGE_ID = '${t}';
58
58
  export const DUBHE_SCHEMA_ID = '${n}';
59
- `;lo(s,o,"storeConfig")}async function lo(e,t,o){so(ao(t),{recursive:!0}),ro(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function ze(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await ce(s,t);await io(r.network,r.packageId,o)}import{loadConfig as co}from"@0xobelisk/sui-common";var uo={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await co(e);await ze(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},Ve=uo;import po from"chokidar";import{exec as go}from"child_process";var mo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{go("pnpm dubhe schemagen",(n,s,r)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(r){console.error(`schemagen stderr: ${r}`);return}console.log(`schemagen stdout: ${s}`)})},o=po.watch(e,{persistent:!0});o.on("change",n=>{console.log(`${n} has been changed. Running schemagen...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{o.close(),console.log(`
60
- Watch stopped.`),process.exit()})}},Le=mo;import fo from"wait-on";import ho from"ora";import oe from"chalk";var yo={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=ho({text:`Waiting for service to start ${oe.cyan(t.url)}...`,color:"cyan"});o.start();try{await fo({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(oe.green("Service is ready!")),process.exit(0)}catch{o.fail(oe.red("Timeout waiting for service")),console.error(oe.yellow("Please make sure the service is running...")),process.exit(1)}}},We=yo;var bo={command:"switch-env",describe:"Switch environment",builder(e){return e.option("network",{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"})},async handler(e){await H(e.network)}},Be=bo;import wo from"dotenv";import z from"chalk";wo.config();var vo={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=F({network:e}),o=t.getSigner();console.log(z.blue("Account Information:")),console.log(` Network: ${z.green(e)}`),console.log(` Address: ${z.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${z.green(s)} SUI`)}catch{console.log(` Balance: ${z.red("Failed to fetch balance")} ${z.gray("(Network error)")}`)}}catch(t){N(t),process.exit(1)}}},qe=vo;import{loadConfig as xo}from"@0xobelisk/sui-common";async function Ke(e,t,o){if(o)await W(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await be(n,t);await W(e.name,t,s)}}var ko={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await xo(t);await Ke(n,e,o)}catch(n){N(n),process.exit(1)}process.exit(0)}},Ye=ko;import a from"chalk";import{spawn as $o}from"child_process";import Ge from"cli-table3";import ge from"inquirer";import*as Qe from"cli-progress";import*as w from"fs";import*as P from"path";import*as O from"os";import{HttpsProxyAgent as Je}from"https-proxy-agent";import{HttpProxyAgent as Co}from"http-proxy-agent";function me(){let e=process.platform,t=process.arch,o,n;switch(e){case"darwin":o="macos";break;case"win32":o="windows";break;case"linux":o="ubuntu";break;default:o=e}switch(t){case"x64":n="x86_64";break;case"arm64":n="aarch64";break;default:n=t}return{platform:e,arch:t,platformForAsset:o,archForAsset:n}}var D={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:P.join(O.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe-wip",binaryName:"dubhe-indexer",installDir:P.join(O.homedir(),".dubhe","bin")}};async function M(e,t=[]){return new Promise(o=>{let n=$o(e,t,{shell:!0}),s="",r="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{r+=i.toString()}),n.on("close",i=>{o({code:i||0,stdout:s,stderr:r})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:r})})})}async function _o(e,t){let o=await fe(e,{headers:{"User-Agent":"dubhe-cli"}});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let n=o.headers.get("content-length"),s=n?parseInt(n):0,r=new Qe.SingleBar({format:a.cyan("Download Progress")+" |{bar}| {percentage}% | {value}/{total} MB | Speed: {speed} MB/s | ETA: {eta}s",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,barsize:30,forceRedraw:!0});s>0?r.start(Math.round(s/1024/1024*100)/100,0,{speed:"0.00"}):console.log(a.blue("\u{1F4E5} Downloading... (unable to get file size)"));let i=o.body?.getReader();if(!i)throw new Error("Unable to get response stream");let u=[],c=0,d=Date.now();try{for(;;){let{done:l,value:g}=await i.read();if(l)break;if(u.push(g),c+=g.length,s>0){let x=Math.round(c/1024/1024*100)/100,b=(Date.now()-d)/1e3,S=b>0?Math.round(x/b*100)/100:0;r.update(x,{speed:S.toFixed(2)})}}let h=u.reduce((l,g)=>l+g.length,0),f=new Uint8Array(h),y=0;for(let l of u)f.set(l,y),y+=l.length;w.writeFileSync(t,f),s>0&&r.stop();let v=Math.round(c/1024/1024*100)/100,_=(Date.now()-d)/1e3,p=_>0?Math.round(v/_*100)/100:0;console.log(a.green(`\u2713 Download completed! ${v} MB, average speed: ${p} MB/s`))}catch(h){throw s>0&&r.stop(),h}}async function fe(e,t={}){let o=process.env.HTTP_PROXY||process.env.http_proxy,n=process.env.HTTPS_PROXY||process.env.https_proxy,s=process.env.NO_PROXY||process.env.no_proxy;if(s){let u=s.split(",").map(d=>d.trim()),c=new URL(e).hostname;for(let d of u)if(d==="*"||c===d||c.endsWith("."+d)||d.startsWith(".")&&c.endsWith(d))return fetch(e,t)}let r=new URL(e).protocol,i;if(r==="https:"&&n?i=new Je(n):r==="http:"&&o?i=new Co(o):n&&r==="https:"&&(i=new Je(n)),i)try{let u={...t,dispatcher:i};return await fetch(e,u)}catch{try{let c={...t,agent:i};return await fetch(e,c)}catch{return console.log(a.yellow(" \u26A0\uFE0F Warning: Could not use proxy, falling back to direct connection")),fetch(e,t)}}return fetch(e,t)}async function he(e,t=10,o=3){let n=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=o;s++)try{s>1&&console.log(a.gray(` Retry ${s}/${o}...`));let r=await fe(n,{headers:{"User-Agent":"dubhe-cli",Accept:"application/vnd.github.v3+json"}});if(!r.ok)throw r.status===403?new Error(`GitHub API rate limit: ${r.status}. Please retry later or set GITHUB_TOKEN environment variable`):new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);return await r.json()}catch(r){if(s>1&&console.log(a.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${r instanceof Error?r.message:String(r)}`)),s===o)return console.error(a.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(i=>setTimeout(i,1e3*s))}return[]}function Y(e,t){return e.assets.filter(n=>{let s=n.name.toLowerCase(),r=[t.platformForAsset.toLowerCase(),...t.platformForAsset==="macos"?["darwin","apple"]:[],...t.platformForAsset==="windows"?["win","win32","windows"]:[],...t.platformForAsset==="ubuntu"?["linux","gnu"]:[]],i=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],u=r.some(h=>s.includes(h)),c=i.some(h=>s.includes(h)),d=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return u&&c&&d}).map(n=>n.name)}async function So(e,t){let o=D[e];return o?(await he(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:Y(s,t).length>0})):[]}async function Po(e){try{let t=G();if(!t){console.log(a.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:o,configFile:n}=t,s=o==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(w.existsSync(n)&&w.readFileSync(n,"utf8").includes(e)){console.log(a.green(` \u2713 PATH already configured in ${n}`));return}let i=`# Added by dubhe doctor
59
+ `;go(s,o,"storeConfig")}async function go(e,t,o){lo(uo(t),{recursive:!0}),co(t,e),o!==void 0&&console.log(`${o}: ${t}`)}async function Ve(e,t,o){let s=`${process.cwd()}/src/${e.name}`,r=await ue(s,t);await po(r.network,r.packageId,o)}import{loadConfig as mo}from"@0xobelisk/sui-common";var fo={command:"config-store",describe:"Store configuration for the Dubhe project",builder:{"config-path":{type:"string",default:"dubhe.config.ts",desc:"Path to the config file"},network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],desc:"Network to store config for"},"output-ts-path":{type:"string",desc:"Specify the output path for the generated TypeScript configuration file (e.g., ./src/config/generated.ts)"}},async handler({"config-path":e,network:t,"output-ts-path":o}){try{let n=await mo(e);await Ve(n,t,o)}catch(n){console.error("Error storing config:",n),process.exit(1)}process.exit(0)}},We=fo;import ho from"chokidar";import{exec as yo}from"child_process";var bo={command:"watch",describe:"Watch dubhe config",builder(e){return e},async handler(){let e="dubhe.config.ts",t=()=>{yo("pnpm dubhe schemagen",(n,s,r)=>{if(n){console.error(`Error executing schemagen: ${n.message}`);return}if(r){console.error(`schemagen stderr: ${r}`);return}console.log(`schemagen stdout: ${s}`)})},o=ho.watch(e,{persistent:!0});o.on("change",n=>{console.log(`${n} has been changed. Running schemagen...`),t()}),console.log(`Watching for changes in ${e}...`),process.on("SIGINT",()=>{o.close(),console.log(`
60
+ Watch stopped.`),process.exit()})}},Be=bo;import wo from"wait-on";import vo from"ora";import se from"chalk";var xo={command:"wait",describe:"Wait for service to be ready",builder(e){return e.option("url",{type:"string",description:"URL to wait for"}).option("timeout",{type:"number",description:"Timeout (in milliseconds)",default:18e4}).option("interval",{type:"number",description:"Check interval (in milliseconds)",default:1e3})},async handler(e){let t=e,o=vo({text:`Waiting for service to start ${se.cyan(t.url)}...`,color:"cyan"});o.start();try{await wo({resources:[t.url],timeout:t.timeout,interval:t.interval,validateStatus:n=>n===200}),o.succeed(se.green("Service is ready!")),process.exit(0)}catch{o.fail(se.red("Timeout waiting for service")),console.error(se.yellow("Please make sure the service is running...")),process.exit(1)}}},qe=xo;var ko={command:"switch-env",describe:"Switch environment",builder(e){return e.option("network",{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Switch to node network (mainnet/testnet/devnet/localnet)"})},async handler(e){await L(e.network)}},Ke=ko;import $o from"dotenv";import V from"chalk";$o.config();var Co={command:"info",describe:"Get information about the current Sui node",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"}})},handler:async({network:e})=>{try{let t=R({network:e}),o=t.getSigner();console.log(V.blue("Account Information:")),console.log(` Network: ${V.green(e)}`),console.log(` Address: ${V.green(o.toSuiAddress())}`);try{let n=await t.getBalance("0x2::sui::SUI"),s=(Number(n.totalBalance)/10**9).toFixed(4);console.log(` Balance: ${V.green(s)} SUI`)}catch{console.log(` Balance: ${V.red("Failed to fetch balance")} ${V.gray("(Network error)")}`)}}catch(t){F(t),process.exit(1)}}},Ge=Co;import{loadConfig as So}from"@0xobelisk/sui-common";async function Ye(e,t,o){if(o)await q(e.name,t,o);else{let n=`${process.cwd()}/src/${e.name}`,s=await ve(n,t);await q(e.name,t,s)}}var _o={command:"load-metadata",describe:"Load metadata for a package",builder(e){return e.options({network:{type:"string",choices:["mainnet","testnet","devnet","localnet"],default:"localnet",desc:"Node network (mainnet/testnet/devnet/localnet)"},"config-path":{type:"string",desc:"Configuration file path",default:"dubhe.config.ts"},"package-id":{type:"string",desc:"Package ID to load metadata for",optional:!0}})},async handler({network:e,"config-path":t,"package-id":o}){try{let n=await So(t);await Ye(n,e,o)}catch(n){F(n),process.exit(1)}process.exit(0)}},Je=_o;import a from"chalk";import{spawn as Po}from"child_process";import Xe from"cli-table3";import fe from"inquirer";import*as tt from"cli-progress";import*as w from"fs";import*as T from"path";import*as H from"os";import*as ot from"net";import{HttpsProxyAgent as Qe}from"https-proxy-agent";import{HttpProxyAgent as To}from"http-proxy-agent";function he(){let e=process.platform,t=process.arch,o,n;switch(e){case"darwin":o="macos";break;case"win32":o="windows";break;case"linux":o="ubuntu";break;default:o=e}switch(t){case"x64":n="x86_64";break;case"arm64":n="aarch64";break;default:n=t}return{platform:e,arch:t,platformForAsset:o,archForAsset:n}}var E={sui:{name:"sui",repo:"MystenLabs/sui",binaryName:"sui",installDir:T.join(H.homedir(),".dubhe","bin")},"dubhe-indexer":{name:"dubhe-indexer",repo:"0xobelisk/dubhe-wip",binaryName:"dubhe-indexer",installDir:T.join(H.homedir(),".dubhe","bin")}};async function j(e,t=[]){return new Promise(o=>{let n=Po(e,t,{shell:!0}),s="",r="";n.stdout?.on("data",i=>{s+=i.toString()}),n.stderr?.on("data",i=>{r+=i.toString()}),n.on("close",i=>{o({code:i||0,stdout:s,stderr:r})}),n.on("error",()=>{o({code:-1,stdout:s,stderr:r})})})}async function Do(e,t){let o=await ye(e,{headers:{"User-Agent":"dubhe-cli"}});if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);let n=o.headers.get("content-length"),s=n?parseInt(n):0,r=new tt.SingleBar({format:a.cyan("Download Progress")+" |{bar}| {percentage}% | {value}/{total} MB | Speed: {speed} MB/s | ETA: {eta}s",barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,barsize:30,forceRedraw:!0});s>0?r.start(Math.round(s/1024/1024*100)/100,0,{speed:"0.00"}):console.log(a.blue("\u{1F4E5} Downloading... (unable to get file size)"));let i=o.body?.getReader();if(!i)throw new Error("Unable to get response stream");let u=[],c=0,d=Date.now();try{for(;;){let{done:l,value:p}=await i.read();if(l)break;if(u.push(p),c+=p.length,s>0){let b=Math.round(c/1024/1024*100)/100,v=(Date.now()-d)/1e3,C=v>0?Math.round(b/v*100)/100:0;r.update(b,{speed:C.toFixed(2)})}}let f=u.reduce((l,p)=>l+p.length,0),m=new Uint8Array(f),h=0;for(let l of u)m.set(l,h),h+=l.length;w.writeFileSync(t,m),s>0&&r.stop();let y=Math.round(c/1024/1024*100)/100,$=(Date.now()-d)/1e3,P=$>0?Math.round(y/$*100)/100:0;console.log(a.green(`\u2713 Download completed! ${y} MB, average speed: ${P} MB/s`))}catch(f){throw s>0&&r.stop(),f}}async function ye(e,t={}){let o=process.env.HTTP_PROXY||process.env.http_proxy,n=process.env.HTTPS_PROXY||process.env.https_proxy,s=process.env.NO_PROXY||process.env.no_proxy;if(s){let u=s.split(",").map(d=>d.trim()),c=new URL(e).hostname;for(let d of u)if(d==="*"||c===d||c.endsWith("."+d)||d.startsWith(".")&&c.endsWith(d))return fetch(e,t)}let r=new URL(e).protocol,i;if(r==="https:"&&n?i=new Qe(n):r==="http:"&&o?i=new To(o):n&&r==="https:"&&(i=new Qe(n)),i)try{let u={...t,dispatcher:i};return await fetch(e,u)}catch{try{let c={...t,agent:i};return await fetch(e,c)}catch{return console.log(a.yellow(" \u26A0\uFE0F Warning: Could not use proxy, falling back to direct connection")),fetch(e,t)}}return fetch(e,t)}async function be(e,t=10,o=3){let n=`https://api.github.com/repos/${e}/releases?per_page=${t}`;for(let s=1;s<=o;s++)try{s>1&&console.log(a.gray(` Retry ${s}/${o}...`));let r=await ye(n,{headers:{"User-Agent":"dubhe-cli",Accept:"application/vnd.github.v3+json"}});if(!r.ok)throw r.status===403?new Error(`GitHub API rate limit: ${r.status}. Please retry later or set GITHUB_TOKEN environment variable`):new Error(`GitHub API request failed: ${r.status} ${r.statusText}`);return await r.json()}catch(r){if(s>1&&console.log(a.yellow(` \u26A0\uFE0F Attempt ${s} failed: ${r instanceof Error?r.message:String(r)}`)),s===o)return console.error(a.red(` \u274C Failed to fetch releases after ${o} attempts`)),[];await new Promise(i=>setTimeout(i,1e3*s))}return[]}function J(e,t){return e.assets.filter(n=>{let s=n.name.toLowerCase(),r=[t.platformForAsset.toLowerCase(),...t.platformForAsset==="macos"?["darwin","apple"]:[],...t.platformForAsset==="windows"?["win","win32","windows"]:[],...t.platformForAsset==="ubuntu"?["linux","gnu"]:[]],i=[t.archForAsset.toLowerCase(),...t.archForAsset==="x86_64"?["amd64","x64"]:[],...t.archForAsset==="aarch64"?["arm64"]:[]],u=r.some(f=>s.includes(f)),c=i.some(f=>s.includes(f)),d=s.endsWith(".tar.gz")||s.endsWith(".zip")||s.endsWith(".tgz")||s.endsWith(".tar.bz2")||s.endsWith(".tar.xz");return u&&c&&d}).map(n=>n.name)}async function Eo(e,t){let o=E[e];return o?(await be(o.repo,10)).map(s=>({version:s.tag_name,hasCompatibleAsset:J(s,t).length>0})):[]}async function Io(e){try{let t=X();if(!t){console.log(a.gray(`Please add to PATH: export PATH="$PATH:${e}"`));return}let{shellName:o,configFile:n}=t,s=o==="fish"?`set -gx PATH $PATH ${e}`:`export PATH="$PATH:${e}"`;if(w.existsSync(n)&&w.readFileSync(n,"utf8").includes(e)){console.log(a.green(` \u2713 PATH already configured in ${n}`));return}let i=`# Added by dubhe doctor
61
61
  ${s}`;w.appendFileSync(n,`
62
62
  ${i}
63
- `),console.log(a.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(a.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(a.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(a.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function G(){let e=O.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:P.join(e,".zshrc")};if(t.includes("bash")){let n=P.join(e,".bash_profile"),s=P.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&w.existsSync(n)?n:s}}else if(t.includes("fish")){let n=P.join(e,".config","fish");return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:P.join(n,"config.fish")}}}let o=[{name:"zsh",file:P.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?P.join(e,".bash_profile"):P.join(e,".bashrc")},{name:"bash",file:P.join(e,".bashrc")}];for(let n of o)if(w.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||w.existsSync("/bin/zsh")?{shellName:"zsh",configFile:P.join(e,".zshrc")}:null}async function Xe(e,t){let o=D[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=me();console.log(a.gray(` System: ${n.platform}/${n.arch}`));try{console.log(a.gray(" Fetching release information..."));let s=await he(o.repo,10);if(s.length===0)return console.error(a.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let r=null;if(t){if(r=s.find(l=>l.tag_name===t)||null,!r)return console.error(`Version ${t} not found`),!1}else for(let l of s)if(Y(l,n).length>0){r=l;break}if(!r)return console.error("No compatible version found"),!1;let i=Y(r,n);if(i.length===0)return console.error(`Version ${r.tag_name} has no compatible binaries`),!1;let u=i[0],c=r.assets.find(l=>l.name===u);if(!c)return console.error(`Asset file not found: ${u}`),!1;console.log(a.green(` \u2713 Found compatible version: ${r.tag_name}`)),console.log(a.gray(` Download file: ${c.name}`));try{let l=await fe(c.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(a.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let g=l.headers.get("content-length");g&&console.log(a.gray(` File size: ${Math.round(parseInt(g)/1024/1024*100)/100} MB`))}}catch{console.log(a.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}w.existsSync(o.installDir)||(w.mkdirSync(o.installDir,{recursive:!0}),console.log(a.gray(` Created install directory: ${o.installDir}`))),console.log(a.blue(" \u{1F4E5} Downloading..."));let d=P.join(O.tmpdir(),c.name),h=3;for(let l=1;l<=h;l++)try{l>1&&console.log(a.gray(` Attempt ${l} to download...`)),await _o(c.browser_download_url,d);break}catch(g){let x=g instanceof Error?g.message:String(g);if(console.log(a.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${x}`)),l===h)throw new Error(`Download failed after ${h} attempts: ${x}`);console.log(a.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(b=>setTimeout(b,l*2e3))}console.log(a.blue(" \u{1F4E6} Extracting and installing..."));let f=P.join(O.tmpdir(),`extract_${Date.now()}`);if(w.mkdirSync(f,{recursive:!0}),c.name.endsWith(".tar.gz")||c.name.endsWith(".tgz")){let l=await M("tar",["-xzf",d,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(c.name.endsWith(".tar.bz2")){let l=await M("tar",["-xjf",d,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(c.name.endsWith(".tar.xz")){let l=await M("tar",["-xJf",d,"-C",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(c.name.endsWith(".zip")){let l=await M("unzip",["-q",d,"-d",f]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${c.name}`);let y=l=>{let g=w.readdirSync(l,{withFileTypes:!0});for(let x of g){let b=P.join(l,x.name);if(x.isDirectory()){let S=y(b);if(S)return S}else if(x.name===o.binaryName||x.name===`${o.binaryName}.exe`)return b}return null},v=y(f);if(!v)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let _=P.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return w.copyFileSync(v,_),process.platform!=="win32"&&w.chmodSync(_,493),w.rmSync(d,{force:!0}),w.rmSync(f,{recursive:!0,force:!0}),console.log(a.green(" \u2705 Installation completed!")),console.log(a.gray(` Location: ${_}`)),console.log(a.gray(` Version: ${r.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(a.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(a.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await Po(o.installDir)),!0}catch(s){return console.error(a.red(`\u274C Installation failed: ${s}`)),!1}}async function Do(e){let t=me(),o=await So(e,t);if(o.length===0)return console.log(a.red(`Unable to get version information for ${e}`)),null;let n=o.filter(r=>r.hasCompatibleAsset).slice(0,5);if(n.length===0)return console.log(a.red("No compatible versions found for current system")),null;console.log(a.blue(`
63
+ `),console.log(a.green(` \u2713 Automatically added to PATH in ${n}`)),console.log(a.blue(` \u{1F4DD} To apply changes: source ${n} or restart terminal`))}catch(t){console.log(a.yellow(` \u26A0\uFE0F Could not auto-configure PATH: ${t instanceof Error?t.message:String(t)}`)),console.log(a.gray(` Please manually add to PATH: export PATH="$PATH:${e}"`))}}function X(){let e=H.homedir(),t=process.env.SHELL;if(t){if(t.includes("zsh"))return{shellName:"zsh",configFile:T.join(e,".zshrc")};if(t.includes("bash")){let n=T.join(e,".bash_profile"),s=T.join(e,".bashrc");return{shellName:"bash",configFile:process.platform==="darwin"&&w.existsSync(n)?n:s}}else if(t.includes("fish")){let n=T.join(e,".config","fish");return w.existsSync(n)||w.mkdirSync(n,{recursive:!0}),{shellName:"fish",configFile:T.join(n,"config.fish")}}}let o=[{name:"zsh",file:T.join(e,".zshrc")},{name:"bash",file:process.platform==="darwin"?T.join(e,".bash_profile"):T.join(e,".bashrc")},{name:"bash",file:T.join(e,".bashrc")}];for(let n of o)if(w.existsSync(n.file))return{shellName:n.name,configFile:n.file};return process.env.ZSH||w.existsSync("/bin/zsh")?{shellName:"zsh",configFile:T.join(e,".zshrc")}:null}async function Ze(e,t){let o=E[e];if(!o)return console.error(`Unknown tool: ${e}`),!1;let n=he();console.log(a.gray(` System: ${n.platform}/${n.arch}`));try{console.log(a.gray(" Fetching release information..."));let s=await be(o.repo,10);if(s.length===0)return console.error(a.red(` \u274C Unable to fetch releases for ${o.name}`)),!1;let r=null;if(t){if(r=s.find(l=>l.tag_name===t)||null,!r)return console.error(`Version ${t} not found`),!1}else for(let l of s)if(J(l,n).length>0){r=l;break}if(!r)return console.error("No compatible version found"),!1;let i=J(r,n);if(i.length===0)return console.error(`Version ${r.tag_name} has no compatible binaries`),!1;let u=i[0],c=r.assets.find(l=>l.name===u);if(!c)return console.error(`Asset file not found: ${u}`),!1;console.log(a.green(` \u2713 Found compatible version: ${r.tag_name}`)),console.log(a.gray(` Download file: ${c.name}`));try{let l=await ye(c.browser_download_url,{method:"HEAD",headers:{"User-Agent":"dubhe-cli"}});if(!l.ok)console.log(a.yellow(` \u26A0\uFE0F Warning: Unable to access download file (${l.status})`));else{let p=l.headers.get("content-length");p&&console.log(a.gray(` File size: ${Math.round(parseInt(p)/1024/1024*100)/100} MB`))}}catch{console.log(a.yellow(" \u26A0\uFE0F Warning: Unable to verify download file"))}w.existsSync(o.installDir)||(w.mkdirSync(o.installDir,{recursive:!0}),console.log(a.gray(` Created install directory: ${o.installDir}`))),console.log(a.blue(" \u{1F4E5} Downloading..."));let d=T.join(H.tmpdir(),c.name),f=3;for(let l=1;l<=f;l++)try{l>1&&console.log(a.gray(` Attempt ${l} to download...`)),await Do(c.browser_download_url,d);break}catch(p){let b=p instanceof Error?p.message:String(p);if(console.log(a.yellow(` \u26A0\uFE0F Download failed (attempt ${l}): ${b}`)),l===f)throw new Error(`Download failed after ${f} attempts: ${b}`);console.log(a.gray(` Waiting ${l*2} seconds before retry...`)),await new Promise(v=>setTimeout(v,l*2e3))}console.log(a.blue(" \u{1F4E6} Extracting and installing..."));let m=T.join(H.tmpdir(),`extract_${Date.now()}`);if(w.mkdirSync(m,{recursive:!0}),c.name.endsWith(".tar.gz")||c.name.endsWith(".tgz")){let l=await j("tar",["-xzf",d,"-C",m]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(c.name.endsWith(".tar.bz2")){let l=await j("tar",["-xjf",d,"-C",m]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(c.name.endsWith(".tar.xz")){let l=await j("tar",["-xJf",d,"-C",m]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else if(c.name.endsWith(".zip")){let l=await j("unzip",["-q",d,"-d",m]);if(l.code!==0)throw new Error(`Extraction failed: ${l.stderr}`)}else throw new Error(`Unsupported compression format: ${c.name}`);let h=l=>{let p=w.readdirSync(l,{withFileTypes:!0});for(let b of p){let v=T.join(l,b.name);if(b.isDirectory()){let C=h(v);if(C)return C}else if(b.name===o.binaryName||b.name===`${o.binaryName}.exe`)return v}return null},y=h(m);if(!y)throw new Error(`Cannot find ${o.binaryName} binary in extracted files`);let $=T.join(o.installDir,o.binaryName+(process.platform==="win32"?".exe":""));return w.copyFileSync(y,$),process.platform!=="win32"&&w.chmodSync($,493),w.rmSync(d,{force:!0}),w.rmSync(m,{recursive:!0,force:!0}),console.log(a.green(" \u2705 Installation completed!")),console.log(a.gray(` Location: ${$}`)),console.log(a.gray(` Version: ${r.tag_name}`)),(process.env.PATH||"").includes(o.installDir)||(console.log(a.yellow(" \u26A0\uFE0F Warning: Install directory is not in PATH environment variable")),process.platform==="win32"?console.log(a.gray(` Please add to PATH: set PATH=%PATH%;${o.installDir}`)):await Io(o.installDir)),!0}catch(s){return console.error(a.red(`\u274C Installation failed: ${s}`)),!1}}async function Ao(e){let t=he(),o=await Eo(e,t);if(o.length===0)return console.log(a.red(`Unable to get version information for ${e}`)),null;let n=o.filter(r=>r.hasCompatibleAsset).slice(0,5);if(n.length===0)return console.log(a.red("No compatible versions found for current system")),null;console.log(a.blue(`
64
64
  \u{1F4CB} Select version for ${e}`)),console.log(a.gray(`System: ${t.platform}/${t.arch}`)),console.log(a.gray(`Compatible versions (latest 5):
65
- `));let s=n.map((r,i)=>({name:`${r.version} ${i===0?a.green("(latest)"):a.gray("(available)")}`,value:r.version,short:r.version}));try{let r=await ge.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new ge.Separator,{name:a.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return r.version==="cancel"?(console.log(a.gray("Installation cancelled")),null):r.version}catch{return console.log(a.gray(`
66
- Installation cancelled`)),null}}function ne(e){let t=D[e];if(!t)return!1;let o=P.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return w.existsSync(o)}async function K(e,t="--version"){try{let o=await M(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
67
- `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(ne(e)){let n=G(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:Ze(e)}}}catch{if(ne(e)){let n=G(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:Ze(e)}}}function Ze(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe-wip/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function Eo(){try{let e=await M("node",["--version"]);if(e.code===0){let t=e.stdout.trim();return parseFloat(t.replace("v",""))>=18?{name:"Node.js Version",status:"success",message:`${t} (meets requirement >=18.0)`}:{name:"Node.js Version",status:"warning",message:`${t} (recommend upgrade to >=18.0)`,fixSuggestion:"Please upgrade Node.js to 18.0 or higher"}}else return{name:"Node.js Version",status:"error",message:"Not installed",fixSuggestion:"Please install Node.js 18.0 or higher"}}catch{return{name:"Node.js Version",status:"error",message:"Check failed",fixSuggestion:"Please install Node.js"}}}async function To(){try{return(await M("docker",["info"])).code===0?{name:"Docker Service",status:"success",message:"Running"}:{name:"Docker Service",status:"warning",message:"Not running",fixSuggestion:"Please start Docker service"}}catch{return{name:"Docker Service",status:"error",message:"Check failed",fixSuggestion:"Please install and start Docker"}}}async function Io(){try{let e=await M("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}function Ao(e){let t={success:a.green("\u2713"),warning:a.yellow("!"),error:a.red("\u2717")},o={success:a.green("Pass"),warning:a.yellow("Warning"),error:a.red("Fail")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function No(e){if(console.log(a.bold.blue(`
65
+ `));let s=n.map((r,i)=>({name:`${r.version} ${i===0?a.green("(latest)"):a.gray("(available)")}`,value:r.version,short:r.version}));try{let r=await fe.prompt([{type:"list",name:"version",message:"Please select a version to install:",choices:[...s,new fe.Separator,{name:a.gray("Cancel installation"),value:"cancel"}],default:s[0].value}]);return r.version==="cancel"?(console.log(a.gray("Installation cancelled")),null):r.version}catch{return console.log(a.gray(`
66
+ Installation cancelled`)),null}}function re(e){let t=E[e];if(!t)return!1;let o=T.join(t.installDir,t.binaryName+(process.platform==="win32"?".exe":""));return w.existsSync(o)}async function Y(e,t="--version"){try{let o=await j(e,[t]);if(o.code===0){let n=o.stdout.trim().split(`
67
+ `)[0];return{name:e,status:"success",message:`Installed ${n}`}}else{if(re(e)){let n=X(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:et(e)}}}catch{if(re(e)){let n=X(),s=n?n.configFile:"~/.zshrc (or ~/.bashrc)";return{name:e,status:"warning",message:"Installed but not in PATH",fixSuggestion:`Binary exists in install directory. Please apply PATH changes: source ${s} (or restart terminal), then run dubhe doctor again`}}return{name:e,status:"error",message:"Not installed",fixSuggestion:et(e)}}}function et(e){return{docker:"Visit https://docs.docker.com/get-docker/ to install Docker","docker-compose":"Visit https://docs.docker.com/compose/install/ to install Docker Compose",sui:"Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install","dubhe-indexer":"Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe-wip/releases",pnpm:"Run: npm install -g pnpm",node:"Visit https://nodejs.org/ to download and install Node.js"}[e]||`Please install ${e}`}async function No(){try{let e=await j("node",["--version"]);if(e.code===0){let t=e.stdout.trim();return parseFloat(t.replace("v",""))>=18?{name:"Node.js Version",status:"success",message:`${t} (meets requirement >=18.0)`}:{name:"Node.js Version",status:"warning",message:`${t} (recommend upgrade to >=18.0)`,fixSuggestion:"Please upgrade Node.js to 18.0 or higher"}}else return{name:"Node.js Version",status:"error",message:"Not installed",fixSuggestion:"Please install Node.js 18.0 or higher"}}catch{return{name:"Node.js Version",status:"error",message:"Check failed",fixSuggestion:"Please install Node.js"}}}async function Mo(){try{return(await j("docker",["info"])).code===0?{name:"Docker Service",status:"success",message:"Running"}:{name:"Docker Service",status:"warning",message:"Not running",fixSuggestion:"Please start Docker service"}}catch{return{name:"Docker Service",status:"error",message:"Check failed",fixSuggestion:"Please install and start Docker"}}}async function Fo(){try{let e=await j("npm",["config","get","registry"]);return e.code===0?{name:"NPM Configuration",status:"success",message:`Configured (${e.stdout.trim()})`}:{name:"NPM Configuration",status:"warning",message:"Configuration issue",fixSuggestion:"Check NPM configuration: npm config list"}}catch{return{name:"NPM Configuration",status:"warning",message:"Check failed",fixSuggestion:"Please install Node.js and NPM"}}}async function nt(e){let t=["127.0.0.1","0.0.0.0"];for(let o of t)if(!await Ro(e,o))return!1;return!0}async function Ro(e,t){return new Promise(o=>{let n=ot.createServer(),s=setTimeout(()=>{n.close(),o(!1)},2e3);n.listen(e,t,()=>{clearTimeout(s),n.close(()=>{o(!0)})}),n.on("error",r=>{clearTimeout(s),n.close(),r.code,o(!1)})})}async function jo(){try{return await nt(5432)?{name:"PostgreSQL Port (5432)",status:"success",message:"Available"}:{name:"PostgreSQL Port (5432)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"PostgreSQL Port (5432)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}async function Oo(){try{return await nt(4e3)?{name:"GraphQL Server Port (4000)",status:"success",message:"Available"}:{name:"GraphQL Server Port (4000)",status:"warning",message:"Port is occupied",fixSuggestion:"Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure."}}catch{return{name:"GraphQL Server Port (4000)",status:"warning",message:"Check failed",fixSuggestion:"Unable to check port status"}}}function Ho(e){let t={success:a.green("\u2713"),warning:a.yellow("!"),error:a.red("\u2717")},o={success:a.green("Pass"),warning:a.yellow("Warning"),error:a.red("Fail")},n="";return e.status==="success"?n=e.message:n=e.fixSuggestion||e.message,[e.name,`${t[e.status]} ${o[e.status]}`,n]}async function Uo(e){if(console.log(a.bold.blue(`
68
68
  \u{1F50D} Dubhe Doctor - Development Environment Checker
69
- `)),e.listVersions){let p=e.listVersions;D[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(a.blue(`\u{1F4CB} Available versions for ${p}:`));let l=me();console.log(a.gray(`System: ${l.platform}/${l.arch}
70
- `));let g=D[p],x=await he(g.repo,10);x.length===0&&(console.log(a.red("Unable to get version information")),process.exit(1));let b=x.map(m=>({version:m.tag_name,hasCompatibleAsset:Y(m,l).length>0,publishDate:new Date(m.published_at).toLocaleDateString("en-US")})),S=new Ge({head:[a.bold.cyan("Version"),a.bold.cyan("Compatibility"),a.bold.cyan("Release Date")],colWidths:[30,15,25]});if(b.forEach(m=>{S.push([m.version,m.hasCompatibleAsset?a.green("\u2713 Compatible"):a.red("\u2717 Incompatible"),m.publishDate])}),console.log(S.toString()),e.debug&&b.length>0){console.log(a.blue(`
71
- \u{1F50D} Debug Information:`));let m=b.find($=>$.hasCompatibleAsset);if(m){let $=x.find(I=>I.tag_name===m.version);if($){console.log(a.gray(`Latest compatible version: ${m.version}`)),console.log(a.gray("Available asset files:")),$.assets.forEach(se=>{console.log(a.gray(` - ${se.name}`))});let I=Y($,l);console.log(a.gray("Compatible asset files:")),I.forEach(se=>{console.log(a.green(` \u2713 ${se}`))})}}}process.exit(0)}if(console.log(a.gray(`Checking your development environment...
72
- `)),e.install){let p=e.install;D[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),console.log(a.gray(`Supported tools: ${Object.keys(D).join(", ")}`)),process.exit(1));let l=null;e.selectVersion&&(l=await Do(p),l||process.exit(1));let g=await Xe(p,l||void 0);process.exit(g?0:1)}let t=[];console.log(`Running checks...
73
- `);let o=await Eo();t.push(o);let n=await K("pnpm");t.push(n);let s=await Io();s.status==="error"&&(s.status="warning"),t.push(s);let r=await K("docker");t.push(r);let i=null;r.status==="success"&&(i=await To(),t.push(i));let u=await K("docker-compose");t.push(u);let c=await K("sui");t.push(c);let d=await K("dubhe-indexer");t.push(d);let h=new Ge({head:[a.bold.cyan("Check Item"),a.bold.cyan("Result"),a.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(Ao(p))}),console.log(h.toString());let f={success:t.filter(p=>p.status==="success").length,warning:t.filter(p=>p.status==="warning").length,error:t.filter(p=>p.status==="error").length};console.log(`
74
- `+a.bold("\u{1F4CA} Check Summary:")),console.log(` ${a.green("\u2713 Passed:")} ${f.success} items`),console.log(` ${a.yellow("! Warning:")} ${f.warning} items`),console.log(` ${a.red("\u2717 Failed:")} ${f.error} items`);let y=t.filter(p=>p.status==="error"),v=y.filter(p=>D[p.name]),_=y.filter(p=>!D[p.name]);if(_.length>0&&(console.log(a.blue(`
75
- \u{1F527} Missing tools that require manual installation:`)),_.forEach(p=>{console.log(` ${a.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),v.length>0){let p=v.filter(g=>ne(g.name)),l=v.filter(g=>!ne(g.name));if(p.length>0){let g=p.map(m=>m.name).join(", "),x=D[p[0].name]?.installDir||"~/.dubhe/bin",b=G(),S=b?b.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.yellow(`
76
- \u26A0\uFE0F Tools already installed but not in PATH: ${g}`)),console.log(a.gray(` Location: ${x}`)),console.log(a.blue(" To fix this, apply PATH changes:")),console.log(a.green(` source ${S}`)),console.log(a.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(a.gray(` If you want to reinstall, remove the files from ${x} and run dubhe doctor again`))}if(l.length>0){let g=l.map(x=>x.name).join(", ");console.log(a.blue(`
77
- \u{1F680} Auto-installable tools detected: ${g}`));try{if((await ge.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${g})`,default:!0}])).installAll){console.log(a.blue(`
69
+ `)),e.listVersions){let p=e.listVersions;E[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),process.exit(1)),console.log(a.blue(`\u{1F4CB} Available versions for ${p}:`));let b=he();console.log(a.gray(`System: ${b.platform}/${b.arch}
70
+ `));let v=E[p],C=await be(v.repo,10);C.length===0&&(console.log(a.red("Unable to get version information")),process.exit(1));let S=C.map(g=>({version:g.tag_name,hasCompatibleAsset:J(g,b).length>0,publishDate:new Date(g.published_at).toLocaleDateString("en-US")})),D=new Xe({head:[a.bold.cyan("Version"),a.bold.cyan("Compatibility"),a.bold.cyan("Release Date")],colWidths:[30,15,25]});if(S.forEach(g=>{D.push([g.version,g.hasCompatibleAsset?a.green("\u2713 Compatible"):a.red("\u2717 Incompatible"),g.publishDate])}),console.log(D.toString()),e.debug&&S.length>0){console.log(a.blue(`
71
+ \u{1F50D} Debug Information:`));let g=S.find(k=>k.hasCompatibleAsset);if(g){let k=C.find(N=>N.tag_name===g.version);if(k){console.log(a.gray(`Latest compatible version: ${g.version}`)),console.log(a.gray("Available asset files:")),k.assets.forEach(ae=>{console.log(a.gray(` - ${ae.name}`))});let N=J(k,b);console.log(a.gray("Compatible asset files:")),N.forEach(ae=>{console.log(a.green(` \u2713 ${ae}`))})}}}process.exit(0)}if(console.log(a.gray(`Checking your development environment...
72
+ `)),e.install){let p=e.install;E[p]||(console.error(a.red(`\u274C Unsupported tool: ${p}`)),console.log(a.gray(`Supported tools: ${Object.keys(E).join(", ")}`)),process.exit(1));let b=null;e.selectVersion&&(b=await Ao(p),b||process.exit(1));let v=await Ze(p,b||void 0);process.exit(v?0:1)}let t=[];console.log(`Running checks...
73
+ `);let o=await No();t.push(o);let n=await Y("pnpm");t.push(n);let s=await Fo();s.status==="error"&&(s.status="warning"),t.push(s);let r=await Y("docker");t.push(r);let i=null;r.status==="success"&&(i=await Mo(),t.push(i));let u=await Y("docker-compose");t.push(u);let c=await Y("sui");t.push(c);let d=await Y("dubhe-indexer");t.push(d);let f=await jo();t.push(f);let m=await Oo();t.push(m);let h=new Xe({head:[a.bold.cyan("Check Item"),a.bold.cyan("Result"),a.bold.cyan("Description/Fix Suggestion")],colWidths:[25,15,60],style:{head:["cyan"],border:["grey"]},wordWrap:!0});t.forEach(p=>{h.push(Ho(p))}),console.log(h.toString());let y={success:t.filter(p=>p.status==="success").length,warning:t.filter(p=>p.status==="warning").length,error:t.filter(p=>p.status==="error").length};console.log(`
74
+ `+a.bold("\u{1F4CA} Check Summary:")),console.log(` ${a.green("\u2713 Passed:")} ${y.success} items`),console.log(` ${a.yellow("! Warning:")} ${y.warning} items`),console.log(` ${a.red("\u2717 Failed:")} ${y.error} items`);let $=t.filter(p=>p.status==="error"),P=$.filter(p=>E[p.name]),l=$.filter(p=>!E[p.name]);if(l.length>0&&(console.log(a.blue(`
75
+ \u{1F527} Missing tools that require manual installation:`)),l.forEach(p=>{console.log(` ${a.red("\u2717")} ${p.name}: ${p.fixSuggestion||p.message}`)})),P.length>0){let p=P.filter(v=>re(v.name)),b=P.filter(v=>!re(v.name));if(p.length>0){let v=p.map(g=>g.name).join(", "),C=E[p[0].name]?.installDir||"~/.dubhe/bin",S=X(),D=S?S.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.yellow(`
76
+ \u26A0\uFE0F Tools already installed but not in PATH: ${v}`)),console.log(a.gray(` Location: ${C}`)),console.log(a.blue(" To fix this, apply PATH changes:")),console.log(a.green(` source ${D}`)),console.log(a.blue(" Or restart your terminal, then run: dubhe doctor")),console.log(a.gray(` If you want to reinstall, remove the files from ${C} and run dubhe doctor again`))}if(b.length>0){let v=b.map(C=>C.name).join(", ");console.log(a.blue(`
77
+ \u{1F680} Auto-installable tools detected: ${v}`));try{if((await fe.prompt([{type:"confirm",name:"installAll",message:`Would you like to automatically install these tools? (${v})`,default:!0}])).installAll){console.log(a.blue(`
78
78
  \u{1F4E6} Starting installation of auto-installable tools...
79
- `));let b=[];for(let $ of l){console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.blue(`\u{1F4E6} Installing ${$.name}...`)),console.log(a.blue(`${"=".repeat(60)}`));let I=await Xe($.name);b.push({name:$.name,success:I}),I?console.log(a.green(`
80
- \u2705 ${$.name} installation completed successfully!`)):(console.log(a.red(`
81
- \u274C ${$.name} installation failed`)),console.log(a.gray(` Manual installation: dubhe doctor --install ${$.name}`))),console.log("")}console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.bold("\u{1F4CB} Installation Summary:")),console.log(a.blue(`${"=".repeat(60)}`)),b.forEach($=>{let I=$.success?a.green("\u2705 Success"):a.red("\u274C Failed");console.log(` ${$.name}: ${I}`)});let S=b.filter($=>$.success).length,m=b.length-S;if(console.log(`
82
- ${a.green("Successful:")} ${S}/${b.length}`),m>0&&console.log(` ${a.red("Failed:")} ${m}/${b.length}`),S>0){let $=G(),I=$?$.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.blue(`
83
- \u{1F504} Next Steps:`)),console.log(a.yellow(" 1. Apply PATH changes by running:")),console.log(a.green(` source ${I}`)),console.log(a.yellow(" 2. Or restart your terminal")),console.log(a.yellow(" 3. Then run the doctor check again:")),console.log(a.green(" dubhe doctor")),console.log(a.gray(`
79
+ `));let S=[];for(let k of b){console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.blue(`\u{1F4E6} Installing ${k.name}...`)),console.log(a.blue(`${"=".repeat(60)}`));let N=await Ze(k.name);S.push({name:k.name,success:N}),N?console.log(a.green(`
80
+ \u2705 ${k.name} installation completed successfully!`)):(console.log(a.red(`
81
+ \u274C ${k.name} installation failed`)),console.log(a.gray(` Manual installation: dubhe doctor --install ${k.name}`))),console.log("")}console.log(a.blue(`${"=".repeat(60)}`)),console.log(a.bold("\u{1F4CB} Installation Summary:")),console.log(a.blue(`${"=".repeat(60)}`)),S.forEach(k=>{let N=k.success?a.green("\u2705 Success"):a.red("\u274C Failed");console.log(` ${k.name}: ${N}`)});let D=S.filter(k=>k.success).length,g=S.length-D;if(console.log(`
82
+ ${a.green("Successful:")} ${D}/${S.length}`),g>0&&console.log(` ${a.red("Failed:")} ${g}/${S.length}`),D>0){let k=X(),N=k?k.configFile:"~/.zshrc (or ~/.bashrc)";console.log(a.blue(`
83
+ \u{1F504} Next Steps:`)),console.log(a.yellow(" 1. Apply PATH changes by running:")),console.log(a.green(` source ${N}`)),console.log(a.yellow(" 2. Or restart your terminal")),console.log(a.yellow(" 3. Then run the doctor check again:")),console.log(a.green(" dubhe doctor")),console.log(a.gray(`
84
84
  This will verify that all tools are properly configured.`))}else console.log(a.red(`
85
85
  \u274C All installations failed. Please check the error messages above.`))}else console.log(a.gray(`
86
- Auto-installation skipped. You can install them manually later:`)),l.forEach(b=>{console.log(a.gray(` dubhe doctor --install ${b.name}`))})}catch{console.log(a.gray(`
87
- Installation cancelled. You can install them manually later:`)),l.forEach(b=>{console.log(a.gray(` dubhe doctor --install ${b.name}`))})}}}v.length===0&&(f.error>0?(console.log(a.red(`
88
- \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),process.exit(1)):f.warning>0?console.log(a.yellow(`
86
+ Auto-installation skipped. You can install them manually later:`)),b.forEach(S=>{console.log(a.gray(` dubhe doctor --install ${S.name}`))})}catch{console.log(a.gray(`
87
+ Installation cancelled. You can install them manually later:`)),b.forEach(S=>{console.log(a.gray(` dubhe doctor --install ${S.name}`))})}}}P.length===0&&(y.error>0?(console.log(a.red(`
88
+ \u274C Your environment has some issues. Please fix them according to the suggestions above.`)),process.exit(1)):y.warning>0?console.log(a.yellow(`
89
89
  \u26A0\uFE0F Your environment is basically ready, but we recommend fixing the warnings for better development experience.`)):console.log(a.green(`
90
90
  \u2705 Congratulations! Your development environment is fully ready!`))),console.log(a.gray(`
91
- \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var Fo={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("install",{type:"string",describe:"Auto-install specified tool (sui, dubhe-indexer)",choices:Object.keys(D)}).option("select-version",{type:"boolean",default:!1,describe:"Select specific version for installation"}).option("list-versions",{type:"string",describe:"List available versions for specified tool",choices:Object.keys(D)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await No({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(a.red("Error occurred during check:"),t),process.exit(1)}}},et=Fo;import Mo from"chalk";import{loadConfig as jo}from"@0xobelisk/sui-common";import Oo from"fs";var Ro={command:"convert-json",describe:"Convert JSON from Dubhe config to config.json",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},"output-path":{type:"string",default:"dubhe.config.json",description:"Output path for the config.json file"}})},async handler({"config-path":e,"output-path":t}){try{console.log("\u{1F680} Running convert json");let o=await jo(e),n=we(o);Oo.writeFileSync(t,n)}catch(o){console.error(Mo.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},tt=Ro;var ot=[De,Ae,Te,Ie,Ne,Fe,Me,Re,Ue,Ve,Le,We,Be,qe,Ye,et,tt];import*as st from"dotenv";st.config();Ho(Uo(process.argv)).scriptName("dubhe").command(ot).version(L.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(nt.red(e)),e.includes("Missing required argument")&&console.log(nt.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(N(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
91
+ \u{1F4A1} Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe`))}var Lo={command:"doctor",describe:"Check if local development environment is ready",builder(e){return e.option("install",{type:"string",describe:"Auto-install specified tool (sui, dubhe-indexer)",choices:Object.keys(E)}).option("select-version",{type:"boolean",default:!1,describe:"Select specific version for installation"}).option("list-versions",{type:"string",describe:"List available versions for specified tool",choices:Object.keys(E)}).option("debug",{type:"boolean",default:!1,describe:"Show detailed debug information"})},async handler(e){try{await Uo({install:e.install,selectVersion:e["select-version"],listVersions:e["list-versions"],debug:e.debug})}catch(t){console.error(a.red("Error occurred during check:"),t),process.exit(1)}}},st=Lo;import zo from"chalk";import{loadConfig as Vo}from"@0xobelisk/sui-common";import Wo from"fs";var Bo={command:"convert-json",describe:"Convert JSON from Dubhe config to config.json",builder(e){return e.options({"config-path":{type:"string",default:"dubhe.config.ts",description:"Options to pass to forge test"},"output-path":{type:"string",default:"dubhe.config.json",description:"Output path for the config.json file"}})},async handler({"config-path":e,"output-path":t}){try{console.log("\u{1F680} Running convert json");let o=await Vo(e),n=xe(o);Wo.writeFileSync(t,n)}catch(o){console.error(zo.red("Error executing convert json:")),console.log(o.stdout),process.exit(0)}}},rt=Bo;var at=[Ee,Me,Ae,Ne,Fe,Re,je,Ue,ze,We,Be,qe,Ke,Ge,Je,st,rt];import*as lt from"dotenv";lt.config();qo(Ko(process.argv)).scriptName("dubhe").command(at).version(B.version).demandCommand(1,"Please provide a command").recommendCommands().strict().fail((e,t)=>{console.error(it.red(e)),e.includes("Missing required argument")&&console.log(it.yellow(`Run 'pnpm dubhe ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),t!=null&&(F(t),console.log("")),process.exit(1)}).alias({h:"help"}).argv;
92
92
  //# sourceMappingURL=dubhe.js.map