@deveco-test/deveco-cli-common 1.3.11-Test.5 → 1.3.12-Test.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- import _r from"path";import*as x from"fs";import*as ve from"path";import{homedir as ct}from"os";import*as me from"fs";import*as v from"path";function ge(r){let e=v.resolve(r),t=[],n=e;for(;;)try{let i=me.realpathSync(n);return t.length===0?i:v.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=v.dirname(n);if(o===n)return e;t.push(v.basename(n)),n=o}}function z(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function he(r){let e=z(r);if(!e)throw new Error("Path must not be empty.");return ge(e)}var lt="deveco-cli",ye,q=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function ut(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":z(r))||ve.join(ct(),".local","share",lt);try{return he(t)}catch(n){throw new q(n instanceof Error?n.message:String(n))}}function A(){if(ye!==void 0)return ye;let r=ut();try{if(x.existsSync(r))return x.realpathSync(r)}catch{}return r}import rt from"crypto";import m from"fs";import j from"os";import y from"path";import dt from"https";var Ee={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var P=class r{static ENDPOINT=Ee.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:i}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(i)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,i){let o=new URL(e);return new Promise((s,a)=>{let c=dt.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:t,timeout:i},g=>{let h=[];g.on("data",S=>h.push(S)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(h).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(n),c.end()})}};var Se={identity:r=>r,camelCase:r=>r,snakeCase:r=>r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},K=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(o=>this.transform(o));if(typeof e!="object")return e;let t=this.config.namingStrategy??Se.identity,n=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(e)){let a=n[o]??t(o);i[a]=this.transform(s)}return i}},Te=new K({namingStrategy:Se.snakeCase,fieldNames:{}});import R from"crypto";import O from"fs";import ft from"path";var N="aes-256-gcm",mt=12,gt="deveco-cli-trace-file",ht="trace-file-secret",Ae=32;function Ce(r){try{let e=O.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Ae?e:null}catch{return null}}function be(r){let e=ft.join(r,ht),t=Ce(e);if(t)return X(t);let n=R.randomBytes(Ae).toString("base64");try{O.mkdirSync(r,{recursive:!0});try{O.writeFileSync(e,n,{flag:"wx"})}catch{let i=Ce(e);if(i)return X(i);O.writeFileSync(e,n)}}catch{}return X(n)}function X(r){return R.createHash("sha256").update(gt).update(r).digest()}function we(r,e){let t=R.randomBytes(mt),n=R.createCipheriv(N,e,t),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:N,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(o)}function xe(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!yt(t))return r;try{let n=R.createDecipheriv(N,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function yt(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===N&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as d from"fs";import*as M from"path";import*as k from"os";import*as T from"path";import rn from"json5";var sn=64*1024;function Re(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??T.join(k.homedir(),"AppData","Local");return T.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?T.join(k.homedir(),"Library","Logs","devecocli-mcp-server"):T.join(k.homedir(),".local","share","devecocli-mcp-server","logs")}var De="mcp-server.log",vt="mcp-server",Et={maxSize:10*1024*1024,maxFiles:4},Y=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...Et,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Re(),this.currentLogFile=M.join(this.logDir,De),d.existsSync(this.logDir)||d.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return M.join(this.logDir,`${vt}-${e}.log.${t}`)}fileExists(e){try{return d.accessSync(e,d.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=d.readdirSync(this.logDir),t=[];for(let i of e)if(i===De||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=M.join(this.logDir,i),s=d.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{d.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&d.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&d.renameSync(o,s)}let n=this.getRotatedFileName(e,1);d.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=d.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=d.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{d.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${o}
2
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);d.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{d.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},D=null;function St(r=!1){D&&D.dispose(),D=new Y(r)}function I(){return D||St(!1),D}var f={debug:(r,...e)=>I().debug(r,...e),info:(r,...e)=>I().info(r,...e),warn:(r,...e)=>I().warn(r,...e),error:(r,...e)=>I().error(r,...e)};import _e from"fs";import Tt from"path";var F=300*1e3,B=3600*1e3,Pe=10080*60*1e3,b=8*1024*1024,Oe=3600*1e3,Le=".pending",Ct=/\.reclaim-\d+-\d+$/;function U(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var At="upload-state.json";function Ne(r){return Tt.join(r,At)}function bt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function W(r){try{let e=_e.readFileSync(Ne(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return bt()}}function J(r,e){try{_e.writeFileSync(Ne(r),JSON.stringify(e),"utf8")}catch{}}function ke(r){let e=W(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),J(r,e))}function Ie(r){let e=W(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,J(r,e)}function Me(r){let e=W(r);e.lastRetryAt=Date.now(),J(r,e)}function Fe(r){let e=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function Z(r){if(!r.startsWith("telemetry-"))return null;let e=Ct.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(Le))return null;let n=t.slice(0,-Le.length);return n.endsWith(".txt")?n:null}function Be(r){return Z(r)!==null}import wt from"crypto";import G from"fs";import xt from"path";var Rt="install-id";function Dt(r){return xt.join(r,Rt)}function Ue(r){try{let e=G.readFileSync(r,"utf8").trim();return Lt(e)?e:null}catch{return null}}function Lt(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r)}function Ge(r){let e=Dt(r),t=Ue(e);if(t)return t;let n=wt.randomUUID();try{G.mkdirSync(r,{recursive:!0});try{G.writeFileSync(e,n,{flag:"wx"})}catch{let i=Ue(e);if(i)return i;G.writeFileSync(e,n)}}catch{}return n}import Gt from"axios";var $e={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Q={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var _t={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function Pt(r){try{return new URL(r)}catch{return null}}function $(r){var e=(typeof r=="string"?Pt(r):r)||{},t=e.protocol,n=e.host,i=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),i=parseInt(i)||_t[t]||0,!Ot(n,i)))return"";var o=ee(t+"_proxy")||ee("all_proxy");return o&&o.indexOf("://")===-1&&(o=t+"://"+o),o}function Ot(r,e){var t=ee("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var i=n.match(/^(.+):(\d+)$/),o=i?i[1]:n,s=i?parseInt(i[2]):0;return s&&s!==e?!0:/^[.*]/.test(o)?(o.charAt(0)==="*"&&(o=o.slice(1)),!r.endsWith(o)):r!==o}):!0}function ee(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as je}from"child_process";import*as C from"fs";import*as ze from"os";import*as H from"path";var qe=6e4;async function Nt(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await He(r,"ProxyServer");if(!e)return null;let t=await He(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function He(r,e){return new Promise(t=>{let n=je("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="";n.stdout.on("data",o=>{i+=o.toString()}),n.on("error",()=>t(null)),n.on("close",o=>{if(o!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(i);t(s?s[1]:null)})})}function kt(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function It(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ve(r){let e={},t=0,n="";for(let i of r.split(/\r?\n/)){let o=i.trim();if(!o)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(o);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(o);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function Mt(r,e,t,n){let i=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((r.timeoutMs??qe)/1e3)))];return r.method&&r.method!=="GET"&&i.push("-X",r.method),r.data!==void 0&&i.push("--data-binary",r.data),i.push(...Ft(r.headers,r.data!==void 0)),n?(i.push("--dump-header",t),i.push("--output",n)):i.push("--include"),i.push(r.url),i}function Ft(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],i=!1;for(let[o,s]of Object.entries(r??{})){let a=o.toLowerCase();a==="content-type"&&(i=!0),t.has(a)||n.push("-H",`${o}: ${s}`)}return e&&!i&&n.push("-H","Content-Type: application/json"),n}function Bt(r,e,t){if(t){let g=C.readFileSync(e,"utf8"),h=C.readFileSync(t),S=Ve(g);return{statusCode:S.statusCode,statusText:S.statusText,body:h.toString("base64"),headers:S.headers,bodyBuffer:h}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let i=r.slice(n),o=i.indexOf(`\r
1
+ import Hr from"path";import*as R from"fs";import*as Ce from"path";import{homedir as dt}from"os";import*as ve from"fs";import*as E from"path";function W(r){let e=E.resolve(r),t=[],n=e;for(;;)try{let o=ve.realpathSync(n);return t.length===0?o:E.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=E.dirname(n);if(i===n)return e;t.push(E.basename(n)),n=i}}function X(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Se(r){let e=X(r);if(!e)throw new Error("Path must not be empty.");return W(e)}var ft="deveco-cli",Te,Y=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function mt(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":X(r))||Ce.join(dt(),".local","share",ft);try{return Se(t)}catch(n){throw new Y(n instanceof Error?n.message:String(n))}}function b(){if(Te!==void 0)return Te;let r=mt();try{if(R.existsSync(r))return R.realpathSync(r)}catch{}return r}import st from"crypto";import m from"fs";import K from"os";import y from"path";import ht from"https";var be={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var k=class r{static ENDPOINT=be.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(e,t){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:t.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(e,"utf8"))};try{let{body:o}=await this.httpPost(r.ENDPOINT,n,Buffer.from(e,"utf8"),6e4);return r.isSuccess(o)}catch{return!1}}static isSuccess(e){try{let t=JSON.parse(e),n=t?.code??t?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(e,t,n,o){let i=new URL(e);return new Promise((s,a)=>{let l=ht.request({protocol:i.protocol,hostname:i.hostname,port:i.port||(i.protocol==="https:"?443:80),path:i.pathname+i.search,method:"POST",headers:t,timeout:o},g=>{let h=[];g.on("data",S=>h.push(S)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(h).toString("utf8")})})});l.on("timeout",()=>{l.destroy(new Error("request timeout"))}),l.on("error",a),l.write(n),l.end()})}};var Ae={identity:r=>r,camelCase:r=>r,snakeCase:r=>r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()},J=class{constructor(e={}){this.config=e}serialize(e){let t=this.transform(e);return this.config.pretty?JSON.stringify(t,null,2):JSON.stringify(t)}toObject(e){return this.transform(e)}transform(e){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.transform(i));if(typeof e!="object")return e;let t=this.config.namingStrategy??Ae.identity,n=this.config.fieldNames??{},o={};for(let[i,s]of Object.entries(e)){let a=n[i]??t(i);o[a]=this.transform(s)}return o}},we=new J({namingStrategy:Ae.snakeCase,fieldNames:{}});import P from"crypto";import M from"fs";import yt from"path";var F="aes-256-gcm",Et=12,vt="deveco-cli-trace-file",St="trace-file-secret",Re=32;function xe(r){try{let e=M.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Re?e:null}catch{return null}}function Pe(r){let e=yt.join(r,St),t=xe(e);if(t)return Z(t);let n=P.randomBytes(Re).toString("base64");try{M.mkdirSync(r,{recursive:!0});try{M.writeFileSync(e,n,{flag:"wx"})}catch{let o=xe(e);if(o)return Z(o);M.writeFileSync(e,n)}}catch{}return Z(n)}function Z(r){return P.createHash("sha256").update(vt).update(r).digest()}function De(r,e){let t=P.randomBytes(Et),n=P.createCipheriv(F,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:F,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function Le(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!Tt(t))return r;try{let n=P.createDecipheriv(F,e,Buffer.from(t.iv,"base64"));return n.setAuthTag(Buffer.from(t.authTag,"base64")),Buffer.concat([n.update(Buffer.from(t.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function Tt(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===F&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as d from"fs";import*as $ from"path";import*as D from"os";import*as T from"path";import hn from"json5";var Sn=64*1024;function _e(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??T.join(D.homedir(),"AppData","Local");return T.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?T.join(D.homedir(),"Library","Logs","devecocli-mcp-server"):T.join(D.homedir(),".local","share","devecocli-mcp-server","logs")}var Ne="mcp-server.log",Ct="mcp-server",bt={maxSize:10*1024*1024,maxFiles:4},Q=class r{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;minLevel;static LEVEL_ORDER={debug:0,info:1,warn:2,error:3};constructor(e,t){this.rotationOptions={...bt,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=_e(),this.currentLogFile=$.join(this.logDir,Ne),d.existsSync(this.logDir)||d.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${o}`}getRotatedFileName(e,t){return $.join(this.logDir,`${Ct}-${e}.log.${t}`)}fileExists(e){try{return d.accessSync(e,d.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=d.readdirSync(this.logDir),t=[];for(let o of e)if(o===Ne||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=$.join(this.logDir,o),s=d.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let o=n;o<t.length;o++)try{d.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&d.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&d.renameSync(i,s)}let n=this.getRotatedFileName(e,1);d.renameSync(this.currentLogFile,n),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=d.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=d.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{d.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...n){if(this.mode==="silent"||r.LEVEL_ORDER[e]<r.LEVEL_ORDER[this.minLevel])return;let o=n.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] [pid=${process.pid}] ${i}
2
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let l=Buffer.from(a);d.writeSync(this.fd,l),this.checkRotation(l.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{d.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},L=null;function At(r=!1){L&&L.dispose(),L=new Q(r)}function B(){return L||At(!1),L}var f={debug:(r,...e)=>B().debug(r,...e),info:(r,...e)=>B().info(r,...e),warn:(r,...e)=>B().warn(r,...e),error:(r,...e)=>B().error(r,...e)};import Oe from"fs";import wt from"path";var U=300*1e3,G=3600*1e3,ke=10080*60*1e3,A=8*1024*1024,Me=3600*1e3,Ie=".pending",xt=/\.reclaim-\d+-\d+$/;function H(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Rt="upload-state.json";function Fe(r){return wt.join(r,Rt)}function Pt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ee(r){try{let e=Oe.readFileSync(Fe(r),"utf8"),t=JSON.parse(e);return{firstEventAt:typeof t.firstEventAt=="number"?t.firstEventAt:null,lastUploadAt:typeof t.lastUploadAt=="number"?t.lastUploadAt:null,lastRetryAt:typeof t.lastRetryAt=="number"?t.lastRetryAt:null}}catch{return Pt()}}function te(r,e){try{Oe.writeFileSync(Fe(r),JSON.stringify(e),"utf8")}catch{}}function Be(r){let e=ee(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),te(r,e))}function $e(r){let e=ee(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,te(r,e)}function Ue(r){let e=ee(r);e.lastRetryAt=Date.now(),te(r,e)}function Ge(r){let e=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!e)return null;let t=Date.parse(`${e[1]}-${e[2]}-${e[3]}T00:00:00`);return Number.isFinite(t)?t:null}function re(r){if(!r.startsWith("telemetry-"))return null;let e=xt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(Ie))return null;let n=t.slice(0,-Ie.length);return n.endsWith(".txt")?n:null}function He(r){return re(r)!==null}import Dt from"crypto";import j from"fs";import Lt from"path";var _t="install-id";function Nt(r){return Lt.join(r,_t)}function je(r){try{let e=j.readFileSync(r,"utf8").trim();return It(e)?e:null}catch{return null}}function It(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r)}function Ve(r){let e=Nt(r),t=je(e);if(t)return t;let n=Dt.randomUUID();try{j.mkdirSync(r,{recursive:!0});try{j.writeFileSync(e,n,{flag:"wx"})}catch{let o=je(e);if(o)return o;j.writeFileSync(e,n)}}catch{}return n}import Xt from"axios";var ze={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},ne={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var Ot={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function kt(r){try{return new URL(r)}catch{return null}}function V(r){var e=(typeof r=="string"?kt(r):r)||{},t=e.protocol,n=e.host,o=e.port;if(typeof n!="string"||!n||typeof t!="string"||(t=t.split(":",1)[0],n=n.replace(/:\d*$/,""),o=parseInt(o)||Ot[t]||0,!Mt(n,o)))return"";var i=oe(t+"_proxy")||oe("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function Mt(r,e){var t=oe("no_proxy").toLowerCase();return t?t==="*"?!1:t.split(/[,\s]/).every(function(n){if(!n)return!0;var o=n.match(/^(.+):(\d+)$/),i=o?o[1]:n,s=o?parseInt(o[2]):0;return s&&s!==e?!0:/^[.*]/.test(i)?(i.charAt(0)==="*"&&(i=i.slice(1)),!r.endsWith(i)):r!==i}):!0}function oe(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}import{spawn as We}from"child_process";import*as C from"fs";import*as Xe from"os";import*as z from"path";var Ye=6e4;async function Ft(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await qe(r,"ProxyServer");if(!e)return null;let t=await qe(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function qe(r,e){return new Promise(t=>{let n=We("reg.exe",["query",r,"/v",e],{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="";n.stdout.on("data",i=>{o+=i.toString()}),n.on("error",()=>t(null)),n.on("close",i=>{if(i!==0){t(null);return}let s=/REG_\w+\s+(\S+)/.exec(o);t(s?s[1]:null)})})}function Bt(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function $t(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function Ke(r){let e={},t=0,n="";for(let o of r.split(/\r?\n/)){let i=o.trim();if(!i)continue;let s=/^HTTP\/\d(?:\.\d)?\s+(\d{3})\s*(.*)$/.exec(i);if(s){t=parseInt(s[1],10),n=s[2]??"";continue}let a=/^([^:]+):\s*(.*)$/.exec(i);a&&(e[a[1].toLowerCase()]=a[2])}return{statusCode:t,statusText:n,headers:e}}function Ut(r,e,t,n){let o=["--silent","--show-error","--location","--ssl-no-revoke","--insecure","-x",`http://${e}`,"--proxy-ntlm","--proxy-user",":","--max-time",String(Math.max(1,Math.floor((r.timeoutMs??Ye)/1e3)))];return r.method&&r.method!=="GET"&&o.push("-X",r.method),r.data!==void 0&&o.push("--data-binary",r.data),o.push(...Gt(r.headers,r.data!==void 0)),n?(o.push("--dump-header",t),o.push("--output",n)):o.push("--include"),o.push(r.url),o}function Gt(r,e){let t=new Set(["content-length","host","connection","proxy-authorization","proxy-connection","accept-encoding"]),n=[],o=!1;for(let[i,s]of Object.entries(r??{})){let a=i.toLowerCase();a==="content-type"&&(o=!0),t.has(a)||n.push("-H",`${i}: ${s}`)}return e&&!o&&n.push("-H","Content-Type: application/json"),n}function Ht(r,e,t){if(t){let g=C.readFileSync(e,"utf8"),h=C.readFileSync(t),S=Ke(g);return{statusCode:S.statusCode,statusText:S.statusText,body:h.toString("base64"),headers:S.headers,bodyBuffer:h}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let o=r.slice(n),i=o.indexOf(`\r
3
3
  \r
4
- `);if(o===-1)return null;let s=i.slice(0,o),a=i.slice(o+4),c=Ve(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function Ke(r){if(process.platform!=="win32")return null;let e=kt()??await Nt();if(!e)return null;let t;r.binary&&(t=C.mkdtempSync(H.join(ze.tmpdir(),"curl-")));let n=t?H.join(t,"header.tmp"):void 0,i=t?H.join(t,"body.tmp"):void 0;try{let o=Mt(r,e,n,i),s=await Ut(o,r.timeoutMs);return!s||s.code!==0?null:Bt(s.stdout,n,i)}catch{return null}finally{t&&C.rmSync(t,{recursive:!0,force:!0})}}function Ut(r,e){let t=It();return new Promise(n=>{let i=je(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),o="",s=!1,a=setTimeout(()=>{s||(s=!0,i.kill())},e??qe);i.stdout.on("data",c=>{o+=c.toString()}),i.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),i.on("close",c=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:c??-1,stdout:o})})})}function $t(r){let e=new URL(r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}var te=class{client;constructor(){let e={timeout:$e.HTTP_TIMEOUT_MS,headers:{"User-Agent":Q.USER_AGENT,"accept-language":Q.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Gt.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=$(t.url??"");return t.proxy=n?$t(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`,i=new Error(`${t.message}
5
- ${n}`);throw i.code=t.code,i.response=t.response,i})}async get(e,t){try{let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"GET",t)}}async post(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,signal:t?.signal,maxContentLength:t?.maxContentLength,maxBodyLength:t?.maxBodyLength,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer){if(i.statusCode!==200)throw new Error(`HTTP ${i.statusCode}`);return i.bodyBuffer}throw n}}async postAllowFailure(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}async deleteAllowFailure(e,t){try{let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{return await this.requestBinary(e,t)}catch(n){let i=await this.tryCurlFallback(n,e,"GET",t,!0);if(i?.bodyBuffer)return{statusCode:i.statusCode,statusText:i.statusText,buffer:i.bodyBuffer,body:i.bodyBuffer.toString("utf8")};throw n}}async requestBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let i=Buffer.from(n.data);return{statusCode:n.status,statusText:n.statusText??"",buffer:i,body:i.toString("utf8")}}async withCurlFallback(e,t,n,i){let o=await this.tryCurlFallback(e,t,n,i,!1);if(o)return{data:o.body,statusCode:o.statusCode,statusText:o.statusText,headers:o.headers};throw e}async tryCurlFallback(e,t,n,i,o=!1){if(Ht(i)||process.platform!=="win32"||!(e instanceof Error)||!Vt(e))return null;let s,a=t;return n==="GET"?i?.params&&(a=jt(t,i.params)):i?.params!==void 0&&i.params!==null&&(s=typeof i.params=="string"?i.params:JSON.stringify(i.params)),Ke({url:a,method:n,data:s,headers:i?.headers,timeoutMs:i?.timeout,binary:o})}},re=new te;function Ht(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function Vt(r){if(r.response?.status===407)return!0;let e=r.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:r.code==="SELF_SIGNED_CERT_IN_CHAIN"||r.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||r.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||r.code==="CERT_HAS_EXPIRED"||r.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function jt(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[o,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${o}[]`,String(a));else t.append(o,String(s));let n=t.toString();if(!n)return r;let i=r.includes("?")?"&":"?";return`${r}${i}${n}`}import{AsyncLocalStorage as zt}from"async_hooks";var qt=new zt;function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;qt.getStore()?console.error(`[DEBUG] ${e}`):console.log(`[DEBUG] ${e}`)}}import Kt from"fs";import Xt from"http";import Yt from"https";import Wt from"path";import Xe from"tls";import oe from"crypto";import{URL as Jt}from"url";import{yellow as Zt}from"colorette";var Qt=`-----BEGIN CERTIFICATE-----
4
+ `);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),l=Ke(s);return{statusCode:l.statusCode,statusText:l.statusText,body:a,headers:l.headers}}async function Je(r){if(process.platform!=="win32")return null;let e=Bt()??await Ft();if(!e)return null;let t;r.binary&&(t=C.mkdtempSync(z.join(Xe.tmpdir(),"curl-")));let n=t?z.join(t,"header.tmp"):void 0,o=t?z.join(t,"body.tmp"):void 0;try{let i=Ut(r,e,n,o),s=await jt(i,r.timeoutMs);return!s||s.code!==0?null:Ht(s.stdout,n,o)}catch{return null}finally{t&&C.rmSync(t,{recursive:!0,force:!0})}}function jt(r,e){let t=$t();return new Promise(n=>{let o=We(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="",s=!1,a=setTimeout(()=>{s||(s=!0,o.kill())},e??Ye);o.stdout.on("data",l=>{i+=l.toString()}),o.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),o.on("close",l=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:l??-1,stdout:i})})})}var _=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};var I=class extends _{category;constructor(e,t,n,o){super(t,n,o),this.name="CategorizedTraceError",this.category=e}};function N(...r){return e=>r.includes(e.name)}function zt(...r){return e=>{let t=e.code;return typeof t=="string"&&r.includes(t)}}function ie(r,...e){return t=>{let n=t.code;return t.name===r&&typeof n=="string"&&e.includes(n)}}function qt(r){return r.code==="ETIMEDOUT"||/timeout/i.test(r.name)}function Kt(r){let e=r.code;return r.name==="ScreenRecordError"&&typeof e=="string"&&e.endsWith("_TIMEOUT")}var zn=[{category:"Timeout",match:qt},{category:"Internal",match:N("ExecaError")},{category:"RuntimeCondition",match:N("CacheDirError","DocPathSafetyError")},{category:"InvalidArgument",match:N("SelectorParseError")},{category:"InvalidArgument",match:N("InvalidArgumentError")},{category:"InvalidArgument",match:zt("INVALID_ARGUMENT","INVALID_RECORDING_PATH")},{category:"Timeout",match:Kt},{category:"InvalidArgument",match:ie("FaultLogError","INVALID_ARGUMENTS","INVALID_INPUT","INPUT_OVERSIZED")},{category:"RuntimeCondition",match:ie("FaultLogError","FILE_NOT_FOUND","UNRECOGNIZED_LOG")},{category:"Internal",match:ie("FaultLogError","INTERNAL_ERROR")},{category:"RuntimeCondition",match:N("GrsError")}];function Yt(r){let e=new URL(r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,auth:{username:decodeURIComponent(e.username),password:decodeURIComponent(e.password)}}}function Jt(r,e){return r==="ETIMEDOUT"||r==="ECONNABORTED"&&/timeout/i.test(e)}function Zt(r){let e=`Network connection failed (${r.code}). Please check your proxy configuration or network settings`,t=new I(Jt(r.code,r.message)?"Timeout":"RuntimeCondition",`${r.message}
5
+ ${e}`,r.code??"Unknown",{cause:r});return t.code=r.code,t.response=r.response,t}var se=class{client;constructor(){let e={timeout:ze.HTTP_TIMEOUT_MS,headers:{"User-Agent":ne.USER_AGENT,"accept-language":ne.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=Xt.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=V(t.url??"");return t.proxy=n?Yt(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{throw Zt(t)})}async get(e,t){try{let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"GET",t)}}async post(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,signal:t?.signal,maxContentLength:t?.maxContentLength,maxBodyLength:t?.maxBodyLength,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){try{let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}catch(n){let o=await this.tryCurlFallback(n,e,"GET",t,!0);if(o?.bodyBuffer){if(o.statusCode!==200)throw new Error(`HTTP ${o.statusCode}`);return o.bodyBuffer}throw n}}async postAllowFailure(e,t){try{let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"POST",t)}}async deleteAllowFailure(e,t){try{let n=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});return this.convertResponse(n)}catch(n){return this.withCurlFallback(n,e,"DELETE",t)}}async getBinaryAllowFailure(e,t){try{return await this.requestBinary(e,t)}catch(n){let o=await this.tryCurlFallback(n,e,"GET",t,!0);if(o?.bodyBuffer)return{statusCode:o.statusCode,statusText:o.statusText,buffer:o.bodyBuffer,body:o.bodyBuffer.toString("utf8")};throw n}}async requestBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,httpsAgent:t?.httpsAgent,validateStatus:()=>!0});if(n.status===407)throw Object.assign(new Error("407 Proxy Authentication Required"),{response:{status:407}});let o=Buffer.from(n.data);return{statusCode:n.status,statusText:n.statusText??"",buffer:o,body:o.toString("utf8")}}async withCurlFallback(e,t,n,o){let i=await this.tryCurlFallback(e,t,n,o,!1);if(i)return{data:i.body,statusCode:i.statusCode,statusText:i.statusText,headers:i.headers};throw e}async tryCurlFallback(e,t,n,o,i=!1){if(Qt(o)||process.platform!=="win32"||!(e instanceof Error)||!er(e))return null;let s,a=t;return n==="GET"?o?.params&&(a=tr(t,o.params)):o?.params!==void 0&&o.params!==null&&(s=typeof o.params=="string"?o.params:JSON.stringify(o.params)),Je({url:a,method:n,data:s,headers:o?.headers,timeoutMs:o?.timeout,binary:i})}},ae=new se;function Qt(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function er(r){if(r.response?.status===407)return!0;let e=r.message??"";return/proxy auth(?:oriz|entic)/i.test(e)?!0:r.code==="SELF_SIGNED_CERT_IN_CHAIN"||r.code==="DEPTH_ZERO_SELF_SIGNED_CERT"||r.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||r.code==="CERT_HAS_EXPIRED"||r.code==="ERR_TLS_CERT_ALTNAME_INVALID"}function tr(r,e){if(!e||typeof e!="object")return r;let t=new URLSearchParams;for(let[i,s]of Object.entries(e))if(s!=null)if(Array.isArray(s))for(let a of s)t.append(`${i}[]`,String(a));else t.append(i,String(s));let n=t.toString();if(!n)return r;let o=r.includes("?")?"&":"?";return`${r}${o}${n}`}import{AsyncLocalStorage as rr}from"async_hooks";var nr=new rr;function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;nr.getStore()?console.error(`[DEBUG] ${e}`):console.log(`[DEBUG] ${e}`)}}import or from"fs";import ir from"http";import sr from"https";import ar from"path";import Ze from"tls";import le from"crypto";import{URL as cr}from"url";import{yellow as ur}from"colorette";var lr=`-----BEGIN CERTIFICATE-----
6
6
  MIIF/TCCA+WgAwIBAgIIIQV1CU5bvEMwDQYJKoZIhvcNAQELBQAwUDELMAkGA1UE
7
7
  BhMCQ04xDzANBgNVBAoMBkh1YXdlaTETMBEGA1UECwwKSHVhd2VpIENCRzEbMBkG
8
8
  A1UEAwwSSHVhd2VpIENCRyBSb290IENBMB4XDTE4MDEzMDA3NDI1OVoXDTM4MDEy
@@ -36,11 +36,11 @@ zYl5snR6SmrDfVmtsyz8aMqifx4gsVV2M5/owv8H3bUdOd5RbkKhzOS2Pmep0bbw
36
36
  WRFUrWuQ+5ci2LLkZyIt9ffNR8W9gbmZOZZTrwSFRIT1Q433NOzCQNDjKwnekGAx
37
37
  8o746tqqZxGCXgy2MaIIqvajhNw9Dr3NBQ8ziWyqaQBk2RrCWh6Q++Sd0b5L3RwH
38
38
  rQ==
39
- -----END CERTIFICATE-----`,er=new oe.X509Certificate(Qt),Ye=[{cert:er}];function tr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new oe.X509Certificate(n)})}catch{}return e}var We=new Set,V;function rr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(V&&V.envValue===r)return V.anchors;let e=r?nr(r):[],t=e.length?[...Ye,...e]:Ye;return V={envValue:r,anchors:t},t}function nr(r){try{let e=tr(Kt.readFileSync(r,"utf8"));return e.length===0&&Je(r,"no parseable certificate found"),e}catch(e){return Je(r,e instanceof Error?e.message:String(e)),[]}}function Je(r,e){We.has(r)||(We.add(r),console.warn(Zt(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Wt.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function ir(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let i=n.fingerprint256||n.fingerprint||"";if(!i||t.has(i))break;t.add(i);try{e.push(new oe.X509Certificate(n.raw))}catch{break}let o=n.issuerCertificate??null;if(o===r)break;n=o}return e}function or(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!sr(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=ar(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function sr(r,e){for(let n of e){let i=r.findIndex(o=>o.fingerprint256===n.cert.fingerprint256);if(i>=0&&Ze(r,i))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&Ze(r,r.length-1))return!0}catch{}return!1}function Ze(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function ar(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!lr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function cr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=ir(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):or(n,e,rr())}function lr(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let i of t.split(",")){let o=i.trim();if(!o.startsWith("DNS:"))continue;let s=o.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var ur=8e3,ne=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let n of this.destroyers)try{n()}catch{}this.callback(e,t)}}},ie=class extends Yt.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??ur}createConnection(e,t){let n=e.host||e.servername||"",i=e.port||443,o=`https://${n}:${i}`,s=$(o),a=new ne(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,i,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let i=Xe.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,t,n),i}createConnectionViaProxy(e,t,n,i,o){let s;try{s=new Jt(t)}catch{o.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),c=this.buildProxyHeaders(s,n,i);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${i}`);let g=Xt.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${i}`,headers:c});o.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),o.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}o.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,o,n)}),g.on("error",h=>{o.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,i){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let o=Xe.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,n,i)}buildProxyHeaders(e,t,n){let i={Host:`${t}:${n}`};if(e.username||e.password){let o=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(o).toString("base64")}`}return i}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let i=cr(e,n);i?(e.destroy(i),t.settle(i)):t.settle(null,e)}),e.once("error",i=>{t.settle(i)})}},se=new ie({keepAlive:!0});var ae=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],w=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var pr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],dr="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",fr="devecostudio",mr=8e3;async function ce(r){let e=[],t="";for(let o of pr){let s=await gr(o,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(o=>o==="incomplete"))throw new w("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,i=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new w("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${i}${t?` Last endpoint error: ${t}`:""}`)}async function gr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${fr}`;p(()=>`[GRS] POST ${t}`);try{let n=await re.post(t,{headers:{"User-Agent":dr},httpsAgent:se,timeout:mr}),i=re.parseJson(n);return i.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${i.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${i.resultCode}`}):hr(i.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(i.services).length} service groups`),{outcome:"ok",services:i.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let i=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${i}`),{outcome:"network",detail:i}}}function hr(r){return ae.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import Qe from"fs";import yr from"path";var vr="com.huawei.devecostudio.region",Er={[vr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},Sr=1440*60*1e3,et=new Set(["CN","HK","MO"]),le=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return et.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=Er,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Tr(this.countryCode);if(e){this.services=e.services,this.resolved=!0,p(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}p(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await ce(this.countryCode);this.services=t,this.resolved=!0,await Cr(this.countryCode,t)}},E=new le;function tt(r){return yr.join(A(),`grs_${r}.json`)}async function Tr(r){try{let e=await Qe.promises.readFile(tt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Sr?null:t}catch{return null}}async function Cr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await Qe.promises.writeFile(tt(r),JSON.stringify(t),"utf8")}catch{}}var L=class r{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new P;storageDir="";failedDir="";installId="";get disabled(){return U()||!E.isCN()}traceFileKey=Buffer.alloc(0);sessionId=rt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.11-Test.5",this.nodeVersion=process.version,this.installId=Ge(e).replace(/-/g,""),this.traceFileKey=be(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let o=t;await this.record(e,o.duration_ms,o.success,o.error_code);return}let n=t,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(e,s,!0,null),o}catch(o){let s=Date.now()-i,a=this.toErrorCode(o);throw await this.record(e,s,!1,a),o}}async record(e,t,n,i){let o=this.buildTraceEvent(e,t,n,i);try{let s=we(JSON.stringify(o),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
40
- `,"utf8"),ke(this.storageDir)}catch{}}buildTraceEvent(e,t,n,i){let o=`${r.EVENT_PREFIX}${e.event}`,s=Te.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:rt.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:o,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:i,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=j.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=j.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return j.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(j.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return y.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.debug("[telemetry] scheduler not started (telemetry disabled)");return}f.debug(`[telemetry] scheduler started (flush every ${F/1e3}s, retry failed every ${B/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},F)},F),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},B)},B)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),f.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return f.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return Ie(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return f.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await m.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(o=>o.startsWith("telemetry-")&&o.endsWith(".txt")).map(o=>y.join(this.failedDir,o)),i=!0;for(let o of n){let s=y.basename(o),a=Fe(s);if(a!==null){if(e-a>Pe){try{await m.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||f.warn("[telemetry] retry failed"),Me(this.storageDir),i}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await m.promises.readdir(t)}catch{continue}for(let i of n)Be(i)&&await this.reclaimOrphan(y.join(t,i),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<Oe)return;n=g.size}catch{return}let i=y.dirname(e),o=Z(y.basename(e));if(o===null)return;let s=await this.claimOrphan(e,i,o);if(s===null)return;let a=y.join(i,o),c=b-await this.fileSize(a);if(n>c){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){f.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}f.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let i=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,i)}catch{return null}return await this.touch(i),i}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return f.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){f.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await m.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await m.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await m.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>y.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>b){f.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${b}), dropped without uploading`);try{await m.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await m.promises.rename(e,n)}catch{return!1}await this.touch(n);let i;try{i=await m.promises.readFile(n,"utf8")}catch{return!1}let o=i.split(`
41
- `).map(s=>s.trim()).filter(Boolean);if(o.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,o)}collectDecryptBatch(e,t){let n=[],i=16,o=t;for(;o<e.length&&n.length<r.MAX_BATCH;){let s=xe(e[o],this.traceFileKey);if(s===null){o++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&i+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),i+=a,o++}return{batch:n,next:o}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let i=n,{batch:o,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(o);if(a.length===0)continue;let c=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(c,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let h=t.slice(i).join(`
39
+ -----END CERTIFICATE-----`,pr=new le.X509Certificate(lr),Qe=[{cert:pr}];function dr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new le.X509Certificate(n)})}catch{}return e}var et=new Set,q;function fr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(q&&q.envValue===r)return q.anchors;let e=r?mr(r):[],t=e.length?[...Qe,...e]:Qe;return q={envValue:r,anchors:t},t}function mr(r){try{let e=dr(or.readFileSync(r,"utf8"));return e.length===0&&tt(r,"no parseable certificate found"),e}catch(e){return tt(r,e instanceof Error?e.message:String(e)),[]}}function tt(r,e){et.has(r)||(et.add(r),console.warn(ur(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${ar.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function gr(r){let e=[],t=new Set,n=r;for(;n&&n.raw;){let o=n.fingerprint256||n.fingerprint||"";if(!o||t.has(o))break;t.add(o);try{e.push(new le.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function hr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!yr(r,t))return p(()=>"[GRS TLS] No trusted anchor (built-in intermediate CA or NODE_EXTRA_CA_CERTS) matched the presented chain"),new Error("[GRS TLS] Server certificate chain is not trusted by the built-in CA or NODE_EXTRA_CA_CERTS");let n=Er(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function yr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&rt(r,o))return!0}let t=r[r.length-1];for(let n of e)if(n.cert.subject===t.issuer)try{if(t.verify(n.cert.publicKey)&&rt(r,r.length-1))return!0}catch{}return!1}function rt(r,e){try{for(let t=e;t>0;t--)if(!r[t-1].verify(r[t].publicKey))return!1;return!0}catch{return!1}}function Er(r,e){let t=Date.now();if(new Date(r.validFrom).getTime()>t||new Date(r.validTo).getTime()<t)return new Error("[GRS TLS] Server certificate is expired or not yet valid");if(!Sr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function vr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=gr(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):hr(n,e,fr())}function Sr(r,e){let t=r.subjectAltName??"",n=e.toLowerCase();for(let o of t.split(",")){let i=o.trim();if(!i.startsWith("DNS:"))continue;let s=i.slice(4).toLowerCase();if(s===n)return!0;if(s.startsWith("*.")){let a=s.slice(1),l=n.slice(0,-a.length);if(n.endsWith(a)&&l.length>0&&!l.includes("."))return!0}}return!1}var Tr=8e3,ce=class{constructor(e,t){this.callback=e;this.timeoutMs=t}settled=!1;timer;destroyers=[];onDestroy(e){this.destroyers.push(e)}start(){this.timer=setTimeout(()=>{this.settle(new Error(`[GRS] Connection deadline (${this.timeoutMs}ms) exceeded during CONNECT/TLS handshake`))},this.timeoutMs)}settle(e,t){if(!this.settled){if(this.settled=!0,this.timer&&clearTimeout(this.timer),e)for(let n of this.destroyers)try{n()}catch{}this.callback(e,t)}}},ue=class extends sr.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Tr}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=V(i),a=new ce(t,this.connectTimeoutMs);if(a.start(),s){this.createConnectionViaProxy(e,s,n,o,a);return}return this.createDirectConnection(e,a,n)}createDirectConnection(e,t,n){let o=Ze.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}createConnectionViaProxy(e,t,n,o,i){let s;try{s=new cr(t)}catch{i.settle(new Error(`[GRS] Invalid proxy URL: ${t}`));return}let a=Number(s.port)||(s.protocol==="https:"?443:80),l=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.hostname}:${a} to ${n}:${o}`);let g=ir.request({host:s.hostname,port:a,method:"CONNECT",path:`${n}:${o}`,headers:l});i.onDestroy(()=>g.destroy()),g.on("connect",(h,S)=>{if(h.statusCode!==200){S.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${h.statusCode} ${h.statusMessage||""}`));return}i.onDestroy(()=>S.destroy()),this.startTlsOverTunnel(e,S,i,n)}),g.on("error",h=>{i.settle(new Error(`[GRS] Proxy connection failed: ${h.message}`))}),g.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=Ze.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`};if(e.username||e.password){let i=`${decodeURIComponent(e.username)}:${decodeURIComponent(e.password)}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(i).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=vr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},pe=new ue({keepAlive:!0});var de=[{group:"com.huawei.devecostudio.region",key:"spaceintroduce"},{group:"com.huawei.devecostudio.region",key:"userinfo"},{group:"com.huawei.devecostudio.region",key:"agcsign"},{group:"com.huawei.devecostudio.region",key:"agcups"},{group:"com.huawei.devecostudio.region",key:"agreementservice"}],w=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Cr=["https://grs.dbankcloud.com/grs/2.0/router","https://grs.dbankcloud.cn/grs/2.0/router","https://grs.dbankcloud.asia/grs/2.0/router","https://grs.platform.dbankcloud.ru/grs/2.0/router"],br="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Ar="devecostudio",wr=8e3;async function fe(r){let e=[],t="";for(let i of Cr){let s=await xr(i,r);if(s.outcome==="ok")return s.services;e.push(s.outcome),s.detail&&(t=s.detail)}if(e.some(i=>i==="incomplete"))throw new w("no-config",`GRS returned no valid configuration for country code ${r} (this region may not be supported)`);let n=process.env.HTTPS_PROXY||process.env.HTTP_PROXY,o=n?`Current proxy: ${n}. Verify the proxy is running and allows CONNECT to grs.dbankcloud.com:443. If the proxy inspects TLS, set NODE_EXTRA_CA_CERTS to a PEM file with your corporate CA \u2014 untrusted GRS certificates are rejected.`:"No proxy configured (HTTP_PROXY/HTTPS_PROXY). If you are behind a corporate firewall, set HTTPS_PROXY=http://your-proxy:port.";throw new w("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function xr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Ar}`;p(()=>`[GRS] POST ${t}`);try{let n=await ae.post(t,{headers:{"User-Agent":br},httpsAgent:pe,timeout:wr}),o=ae.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Rr(o.services)?(p(()=>`[GRS] hit ${r}, received ${Object.keys(o.services).length} service groups`),{outcome:"ok",services:o.services}):(p(()=>`[GRS] ${r} returned incomplete config (missing required service keys), skipping`),{outcome:"incomplete",detail:"missing required service keys"})}catch(n){let o=n instanceof Error?n.message:String(n);return p(()=>`[GRS] ${r} request failed: ${o}`),{outcome:"network",detail:o}}}function Rr(r){return de.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import nt from"fs";import Pr from"path";var Dr="com.huawei.devecostudio.region",Lr={[Dr]:{spaceintroduce:"https://cn.devecostudio.huawei.com",userinfo:"https://gopenuser-drcn.platform.dbankcloud.cn",agcsign:"https://connect-api.cloud.huawei.com",agcups:"https://connect-api.cloud.huawei.com",agreementservice:"https://terms-drcn.platform.dbankcloud.cn",agcdeveloper:"https://developer.huawei.com"}},_r=1440*60*1e3,ot=new Set(["CN","HK","MO"]),me=class{countryCode="";services={};resolved=!1;isCN(){return this.countryCode==="CN"}isOnlineAllowed(){return ot.has(this.countryCode)}getService(e,t){let n=this.services[e]?.[t];if(!n)throw new Error(`GRS service ${e}.${t} not available`);return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new Error("Country code not set, cannot resolve GRS");if(this.countryCode==="CN"){this.services=Lr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Nr(this.countryCode);if(e){this.services=e.services,this.resolved=!0,p(()=>`[GRS] cache hit country=${this.countryCode}, skipping request`);return}p(()=>`[GRS] cache miss or expired, requesting GRS country=${this.countryCode}`);let t=await fe(this.countryCode);this.services=t,this.resolved=!0,await Ir(this.countryCode,t)}},v=new me;function it(r){return Pr.join(b(),`grs_${r}.json`)}async function Nr(r){try{let e=await nt.promises.readFile(it(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>_r?null:t}catch{return null}}async function Ir(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await nt.promises.writeFile(it(r),JSON.stringify(t),"utf8")}catch{}}var O=class r{static MAX_BATCH=200;static MAX_PAYLOAD_BYTES=Math.floor(1.7*1024*1024);static TRACE_OS_VERSION="1.0";static COUNTRY_CODE="CN";static EVENT_PREFIX="devecocli_";uploader=new k;storageDir="";failedDir="";installId="";get disabled(){return H()||!v.isCN()}traceFileKey=Buffer.alloc(0);sessionId=st.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=y.join(e,"failed"),this.cliVersion="1.3.12-Test.1",this.nodeVersion=process.version,this.installId=Ve(e).replace(/-/g,""),this.traceFileKey=Pe(e),m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0}),f.debug(`[telemetry] init: dir=${e}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(e){this.devecoStudioVersion=e,f.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,f.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,f.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return f.debug("[telemetry] track skipped: telemetry not initialized"),typeof t=="function"?t():void 0;if(!t){await this.record(e,0,!0,null);return}if(typeof t!="function"){let i=t;await this.record(e,i.duration_ms,i.success,i.error_code);return}let n=t,o=Date.now();try{let i=await n(),s=Date.now()-o;return await this.record(e,s,!0,null),i}catch(i){let s=Date.now()-o,a=this.toErrorCode(i);throw await this.record(e,s,!1,a),i}}async record(e,t,n,o){let i=this.buildTraceEvent(e,t,n,o);try{let s=De(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
40
+ `,"utf8"),Be(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=we.toObject(e);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:i,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:st.randomUUID(),trace_os_version:r.TRACE_OS_VERSION,os_arch:this.resolveOsArch(),action:i,trace_os_name:this.resolveOsName(),version:`${this.cliVersion}_${this.resolveOsSuffix()}`,deveco_studio_version:this.formatVersion(this.devecoStudioVersion),command_line_version:this.formatVersion(this.cltVersion),source_type:this.sourceType,session_id:this.sessionId,node_version:this.nodeVersion,ram:this.resolveTotalRam(),duration_ms:t,success:n,error_code:o,event_detail:s}}}toErrorCode(e){return e instanceof Error?e.code??e.name:"UnknownError"}resolveOsArch(){let e=K.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=K.release().split(".");return(parseInt(e[e.length-1],10)||0)>=22e3?"Windows 11":"Windows 10"}case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}resolveOsSuffix(){switch(process.platform){case"win32":return"windows";case"darwin":return K.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(K.totalmem()/1024)}KB`}formatVersion(e){return e?`${e}_${this.resolveOsSuffix()}`:""}dateString(){let e=new Date,t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${e.getFullYear()}-${t}-${n}`}currentFile(){return y.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.debug("[telemetry] scheduler not started (telemetry disabled)");return}f.debug(`[telemetry] scheduler started (flush every ${U/1e3}s, retry failed every ${G/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},U)},U),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},G)},G)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),this.retryInitialTimer&&(clearTimeout(this.retryInitialTimer),this.retryInitialTimer=null),this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),f.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return f.debug("[telemetry] flush skipped: telemetry not initialized"),!0;let e=await this.listPendingFiles(),t=!0;for(let n of e)await this.flushFile(n)||(t=!1);return $e(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return f.debug("[telemetry] retryFailed skipped: telemetry not initialized"),!0;await this.reclaimStalePending();let e=Date.now(),t;try{t=await m.promises.readdir(this.failedDir)}catch{return!0}let n=t.filter(i=>i.startsWith("telemetry-")&&i.endsWith(".txt")).map(i=>y.join(this.failedDir,i)),o=!0;for(let i of n){let s=y.basename(i),a=Ge(s);if(a!==null){if(e-a>ke){try{await m.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||f.warn("[telemetry] retry failed"),Ue(this.storageDir),o}async reclaimStalePending(){let e=Date.now();for(let t of[this.storageDir,this.failedDir]){let n;try{n=await m.promises.readdir(t)}catch{continue}for(let o of n)He(o)&&await this.reclaimOrphan(y.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<Me)return;n=g.size}catch{return}let o=y.dirname(e),i=re(y.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=y.join(o,i),l=A-await this.fileSize(a);if(n>l){try{await m.promises.unlink(s)}catch{}f.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${l})`);return}if(await this.mergeOrphanInto(s,a)){f.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}f.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=y.join(t,`${n}.pending.reclaim-${process.pid}-${Date.now()}`);try{await m.promises.rename(e,o)}catch{return null}return await this.touch(o),o}async mergeOrphanInto(e,t){try{await m.promises.appendFile(t,await m.promises.readFile(e))}catch(n){return f.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){f.warn(`[telemetry] merged but failed to remove orphan pending: ${e}: ${n instanceof Error?n.message:String(n)}`)}return!0}async fileSize(e){try{return(await m.promises.stat(e)).size}catch{return 0}}async touch(e){let t=new Date;try{await m.promises.utimes(e,t,t)}catch{}}runExclusive(e){let t=()=>e(),n=this.flushChain.then(t,t);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let e;try{e=await m.promises.readdir(this.storageDir)}catch{return[]}return e.filter(t=>t.startsWith("telemetry-")&&t.endsWith(".txt")).map(t=>y.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>A){f.warn(`[telemetry] ${y.basename(e)} is ${t} bytes (> ${A}), dropped without uploading`);try{await m.promises.unlink(e)}catch{}return!0}let n=e+".pending";try{await m.promises.rename(e,n)}catch{return!1}await this.touch(n);let o;try{o=await m.promises.readFile(n,"utf8")}catch{return!1}let i=o.split(`
41
+ `).map(s=>s.trim()).filter(Boolean);if(i.length===0){try{await m.promises.unlink(n)}catch{}return!0}return this.uploadInBatches(n,i)}collectDecryptBatch(e,t){let n=[],o=16,i=t;for(;i<e.length&&n.length<r.MAX_BATCH;){let s=Le(e[i],this.traceFileKey);if(s===null){i++;continue}let a=Buffer.byteLength(s,"utf8")+1;if(n.length>0&&o+a>r.MAX_PAYLOAD_BYTES)break;n.push(s),o+=a,i++}return{batch:n,next:i}}async uploadInBatches(e,t){let n=0;for(;n<t.length;){let o=n,{batch:i,next:s}=this.collectDecryptBatch(t,n);n=s;let a=this.buildPayloadItems(i);if(a.length===0)continue;let l=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(l,this.installId)}catch{}if(!g){f.warn("[telemetry] upload failed");let h=t.slice(o).join(`
42
42
  `)+`
43
- `;return await this.moveToFailed(e,h),!1}}try{await m.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let i=JSON.parse(n);t.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=y.basename(e,".pending"),i=y.join(this.failedDir,n),o=t.split(`
44
- `).filter(Boolean),s=b-await this.fileSize(i),a=this.takeNewestWithinBudget(o,s);a.length<o.length&&f.warn(`[telemetry] failed file capped at ${b} bytes, dropped ${o.length-a.length} older events`);try{a.length>0&&await m.promises.appendFile(i,a.join(`
43
+ `;return await this.moveToFailed(e,h),!1}}try{await m.promises.unlink(e)}catch{}return!0}buildPayloadItems(e){let t=[];for(let n of e)try{let o=JSON.parse(n);t.push({action:o.event,detail:JSON.stringify(o.properties),timestamp:Number(o.eventtime)||Date.now()})}catch{}return t}async moveToFailed(e,t){let n=y.basename(e,".pending"),o=y.join(this.failedDir,n),i=t.split(`
44
+ `).filter(Boolean),s=A-await this.fileSize(o),a=this.takeNewestWithinBudget(i,s);a.length<i.length&&f.warn(`[telemetry] failed file capped at ${A} bytes, dropped ${i.length-a.length} older events`);try{a.length>0&&await m.promises.appendFile(o,a.join(`
45
45
  `)+`
46
- `,"utf8")}catch{return}try{await m.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],i=0;for(let o=e.length-1;o>=0;o--){let s=Buffer.byteLength(e[o],"utf8")+1;if(i+s>t)break;i+=s,n.push(e[o])}return n.reverse(),n}};var _=new L;import{spawn as eo}from"child_process";import{existsSync as ro}from"fs";import{dirname as io,join as oo}from"path";import{fileURLToPath as ao}from"url";var Ar=new Set(["C","POSIX"]);function ue(){let r=br();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Ar.has(r))return p("[region] locale=C/POSIX\uFF0C\u89C6\u4E3A\u65E0\u4FE1\u53F7\uFF0C\u4EA4\u7531\u65F6\u533A\u515C\u5E95"),null;let e=r.split(".")[0],t=wr(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function br(){let r=process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG;if(r)return r.trim();try{return Intl.DateTimeFormat().resolvedOptions().locale||null}catch{return null}}function wr(r){let e=r.split(/[-_]/);if(e.length<2)return null;for(let t=e.length-1;t>=0;t--){let n=e[t];if(/^[A-Za-z]{2}$/.test(n))return n.toUpperCase()}return null}var pe={"Asia/Shanghai":"CN","Asia/Urumqi":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Pyongyang":"KP","Asia/Ulaanbaatar":"MN","Asia/Singapore":"SG","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Manila":"PH","Asia/Kuala_Lumpur":"MY","Asia/Kuching":"MY","Asia/Ho_Chi_Minh":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Yangon":"MM","Asia/Brunei":"BN","Asia/Dili":"TL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Mumbai":"IN","Asia/Delhi":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Colombo":"LK","Asia/Kathmandu":"NP","Asia/Thimphu":"BT","Asia/Male":"MV","Asia/Almaty":"KZ","Asia/Aqtobe":"KZ","Asia/Qyzylorda":"KZ","Asia/Tashkent":"UZ","Asia/Dushanbe":"TJ","Asia/Bishkek":"KG","Asia/Ashgabat":"TM","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Bahrain":"BH","Asia/Kuwait":"KW","Asia/Muscat":"OM","Asia/Aden":"YE","Asia/Baghdad":"IQ","Asia/Tehran":"IR","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Beirut":"LB","Asia/Damascus":"SY","Asia/Amman":"JO","Asia/Kabul":"AF","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Tbilisi":"GE","Asia/Nicosia":"CY","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Vienna":"AT","Europe/Zurich":"CH","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Moscow":"RU","Europe/Kaliningrad":"RU","Europe/Lisbon":"PT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Minsk":"BY","Europe/Bucharest":"RO","Europe/Sofia":"BG","Europe/Belgrade":"RS","Europe/Zagreb":"HR","Europe/Ljubljana":"SI","Europe/Sarajevo":"BA","Europe/Skopje":"MK","Europe/Tirane":"AL","Europe/Riga":"LV","Europe/Tallinn":"EE","Europe/Vilnius":"LT","Europe/Chisinau":"MD","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","America/Juneau":"US","America/Honolulu":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Halifax":"CA","America/Edmonton":"CA","America/Winnipeg":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Buenos_Aires":"AR","America/Santiago":"CL","America/Lima":"PE","America/Bogota":"CO","America/Caracas":"VE","America/Guayaquil":"EC","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Havana":"CU","America/Santo_Domingo":"DO","America/Jamaica":"JM","America/Port-au-Prince":"HT","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Hobart":"AU","Pacific/Auckland":"NZ","Pacific/Fiji":"FJ","Pacific/Guam":"GU","Africa/Cairo":"EG","Africa/Lagos":"NG","Africa/Johannesburg":"ZA","Africa/Nairobi":"KE","Africa/Casablanca":"MA","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Accra":"GH","Africa/Addis_Ababa":"ET","Africa/Dar_es_Salaam":"TZ","Africa/Khartoum":"SD","Africa/Tripoli":"LY"};function de(){let r=ue();if(r)return{code:r,source:"locale"};let e=nt();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function nt(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=pe[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import it from"fs";import ot from"path";import{homedir as xr}from"os";var Rr="country.region.xml",Dr=".config",Lr="deveco-cli";function st(){let r=process.env.DEVECO_CLI_DATA_DIR?A():ot.join(xr(),Dr,Lr);return ot.join(r,Rr)}function fe(){let r=st();try{if(!it.existsSync(r))return null;let t=it.readFileSync(r,"utf8").match(/<countryregion\s+name="([A-Za-z]{2})"/);return t?t[1].toUpperCase():(p(()=>`[region] country.region.xml malformed: ${r}`),null)}catch(e){return p(()=>`[region] failed to read country.region.xml: ${e.message}`),null}}var at=fe();if(at)E.setCountryCode(at);else{let r=de();r&&E.setCountryCode(r.code)}if(!E.isCN())f.info("[telemetry] background upload skipped (non-CN region)");else{let r=_r.join(A(),"TraceLogData",E.countryCode);_.init(r),(async()=>{try{await _.flush(),await _.retryFailed()}catch(e){f.warn("[telemetry] background upload error:",e),process.exit(1)}})()}
46
+ `,"utf8")}catch{return}try{await m.promises.unlink(e)}catch{}}takeNewestWithinBudget(e,t){if(t<=0)return[];let n=[],o=0;for(let i=e.length-1;i>=0;i--){let s=Buffer.byteLength(e[i],"utf8")+1;if(o+s>t)break;o+=s,n.push(e[i])}return n.reverse(),n}};var x=new O;import{execFile as bi,spawn as Ai}from"child_process";import{existsSync as xi,readdirSync as Ri,readFileSync as Pi}from"fs";import{spawn as Gi}from"child_process";import{existsSync as ji}from"fs";import{dirname as zi,join as qi}from"path";import{fileURLToPath as Wi}from"url";var kr=new Set(["C","POSIX"]);function ge(){let r=Mr();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),kr.has(r))return p("[region] locale=C/POSIX\uFF0C\u89C6\u4E3A\u65E0\u4FE1\u53F7\uFF0C\u4EA4\u7531\u65F6\u533A\u515C\u5E95"),null;let e=r.split(".")[0],t=Fr(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function Mr(){let r=process.env.LC_ALL||process.env.LC_MESSAGES||process.env.LANG;if(r)return r.trim();try{return Intl.DateTimeFormat().resolvedOptions().locale||null}catch{return null}}function Fr(r){let e=r.split(/[-_]/);if(e.length<2)return null;for(let t=e.length-1;t>=0;t--){let n=e[t];if(/^[A-Za-z]{2}$/.test(n))return n.toUpperCase()}return null}var he={"Asia/Shanghai":"CN","Asia/Urumqi":"CN","Asia/Hong_Kong":"HK","Asia/Macau":"MO","Asia/Taipei":"TW","Asia/Tokyo":"JP","Asia/Seoul":"KR","Asia/Pyongyang":"KP","Asia/Ulaanbaatar":"MN","Asia/Singapore":"SG","Asia/Bangkok":"TH","Asia/Jakarta":"ID","Asia/Makassar":"ID","Asia/Jayapura":"ID","Asia/Manila":"PH","Asia/Kuala_Lumpur":"MY","Asia/Kuching":"MY","Asia/Ho_Chi_Minh":"VN","Asia/Phnom_Penh":"KH","Asia/Vientiane":"LA","Asia/Yangon":"MM","Asia/Brunei":"BN","Asia/Dili":"TL","Asia/Kolkata":"IN","Asia/Calcutta":"IN","Asia/Mumbai":"IN","Asia/Delhi":"IN","Asia/Karachi":"PK","Asia/Dhaka":"BD","Asia/Colombo":"LK","Asia/Kathmandu":"NP","Asia/Thimphu":"BT","Asia/Male":"MV","Asia/Almaty":"KZ","Asia/Aqtobe":"KZ","Asia/Qyzylorda":"KZ","Asia/Tashkent":"UZ","Asia/Dushanbe":"TJ","Asia/Bishkek":"KG","Asia/Ashgabat":"TM","Asia/Dubai":"AE","Asia/Riyadh":"SA","Asia/Qatar":"QA","Asia/Bahrain":"BH","Asia/Kuwait":"KW","Asia/Muscat":"OM","Asia/Aden":"YE","Asia/Baghdad":"IQ","Asia/Tehran":"IR","Asia/Jerusalem":"IL","Asia/Tel_Aviv":"IL","Asia/Beirut":"LB","Asia/Damascus":"SY","Asia/Amman":"JO","Asia/Kabul":"AF","Asia/Baku":"AZ","Asia/Yerevan":"AM","Asia/Tbilisi":"GE","Asia/Nicosia":"CY","Europe/London":"GB","Europe/Dublin":"IE","Europe/Paris":"FR","Europe/Berlin":"DE","Europe/Madrid":"ES","Europe/Rome":"IT","Europe/Amsterdam":"NL","Europe/Brussels":"BE","Europe/Vienna":"AT","Europe/Zurich":"CH","Europe/Stockholm":"SE","Europe/Oslo":"NO","Europe/Copenhagen":"DK","Europe/Helsinki":"FI","Europe/Warsaw":"PL","Europe/Prague":"CZ","Europe/Budapest":"HU","Europe/Moscow":"RU","Europe/Kaliningrad":"RU","Europe/Lisbon":"PT","Europe/Athens":"GR","Europe/Istanbul":"TR","Europe/Kyiv":"UA","Europe/Kiev":"UA","Europe/Minsk":"BY","Europe/Bucharest":"RO","Europe/Sofia":"BG","Europe/Belgrade":"RS","Europe/Zagreb":"HR","Europe/Ljubljana":"SI","Europe/Sarajevo":"BA","Europe/Skopje":"MK","Europe/Tirane":"AL","Europe/Riga":"LV","Europe/Tallinn":"EE","Europe/Vilnius":"LT","Europe/Chisinau":"MD","America/New_York":"US","America/Chicago":"US","America/Denver":"US","America/Los_Angeles":"US","America/Phoenix":"US","America/Anchorage":"US","America/Juneau":"US","America/Honolulu":"US","America/Toronto":"CA","America/Vancouver":"CA","America/Halifax":"CA","America/Edmonton":"CA","America/Winnipeg":"CA","America/Mexico_City":"MX","America/Sao_Paulo":"BR","America/Argentina/Buenos_Aires":"AR","America/Buenos_Aires":"AR","America/Santiago":"CL","America/Lima":"PE","America/Bogota":"CO","America/Caracas":"VE","America/Guayaquil":"EC","America/La_Paz":"BO","America/Asuncion":"PY","America/Montevideo":"UY","America/Havana":"CU","America/Santo_Domingo":"DO","America/Jamaica":"JM","America/Port-au-Prince":"HT","Australia/Sydney":"AU","Australia/Melbourne":"AU","Australia/Brisbane":"AU","Australia/Perth":"AU","Australia/Adelaide":"AU","Australia/Hobart":"AU","Pacific/Auckland":"NZ","Pacific/Fiji":"FJ","Pacific/Guam":"GU","Africa/Cairo":"EG","Africa/Lagos":"NG","Africa/Johannesburg":"ZA","Africa/Nairobi":"KE","Africa/Casablanca":"MA","Africa/Algiers":"DZ","Africa/Tunis":"TN","Africa/Accra":"GH","Africa/Addis_Ababa":"ET","Africa/Dar_es_Salaam":"TZ","Africa/Khartoum":"SD","Africa/Tripoli":"LY"};function ye(){let r=ge();if(r)return{code:r,source:"locale"};let e=at();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function at(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=he[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import ct from"fs";import ut from"path";import{homedir as Br}from"os";var $r="country.region.xml",Ur=".config",Gr="deveco-cli";function lt(){let r=process.env.DEVECO_CLI_DATA_DIR?b():ut.join(Br(),Ur,Gr);return ut.join(r,$r)}function Ee(){let r=lt();try{if(!ct.existsSync(r))return null;let t=ct.readFileSync(r,"utf8").match(/<countryregion\s+name="([A-Za-z]{2})"/);return t?t[1].toUpperCase():(p(()=>`[region] country.region.xml malformed: ${r}`),null)}catch(e){return p(()=>`[region] failed to read country.region.xml: ${e.message}`),null}}var pt=Ee();if(pt)v.setCountryCode(pt);else{let r=ye();r&&v.setCountryCode(r.code)}if(!v.isCN())f.info("[telemetry] background upload skipped (non-CN region)");else{let r=Hr.join(b(),"TraceLogData",v.countryCode);x.init(r),(async()=>{try{await x.flush(),await x.retryFailed()}catch(e){f.warn("[telemetry] background upload error:",e),process.exit(1)}})()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/deveco-cli-common",
3
- "version": "1.3.11-Test.5",
3
+ "version": "1.3.12-Test.1",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "supportedDocsApi": 1,
6
6
  "license": "MIT",
@@ -67,7 +67,7 @@
67
67
  "ui-verification-mcp": "0.0.20",
68
68
  "xpath": "^0.0.35",
69
69
  "zod": "^4.4.3",
70
- "@deveco-test/deveco-cli-knowledgebase": "1.3.11-Test.5"
70
+ "@deveco-test/deveco-cli-knowledgebase": "1.3.12-Test.1"
71
71
  },
72
72
  "devDependencies": {
73
73
  "@types/adm-zip": "^0.5.8",
@@ -39,6 +39,7 @@ Compile and package project/modules. (Defaults: `--product default`, `--build-mo
39
39
  - **Build efficiency**: if build/clean is slow, consult https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-build-optimize-practices for build optimization practices.
40
40
  - **Clean mode**: `devecocli build clean [--mode <mode>] [--modules <m1> <m2>]` runs in module mode by default and reads build options (analyze/parallel/incremental/daemon) from `hvigor-config.json5` `execution`, matching DevEco Studio.
41
41
  - **Build artifacts**: on success, prints absolute paths of all produced `.hap`/`.hsp`/`.har`/`.app` files for direct use.
42
+ - **debugLine**: disabled by default. Pass `--debug-line` to build to forward `-p debugLine=true` to hvigor.
42
43
  - **Signing config**: `--signing-config <name>` overrides the product's default signing config from `build-profile.json5`, enabling release builds with a release signing config.
43
44
 
44
45
  ### `devecocli check lint`
@@ -172,6 +173,7 @@ Build, install, and launch. After a successful ability launch (and after a succe
172
173
  - `--ability <ability>`: Default from `module.json5`.
173
174
  - `--uninstall`: Uninstall existing app first (Fixes signing key issues).
174
175
  - `--skip-build`: Deploy existing artifacts.
176
+ - `--debug-line`: Forward `-p debugLine=true` to hvigor for the full build, `--apply`, and hot-reload compiles (default: disabled).
175
177
  - `--apply <fileName>`: **Fast incremental deploy** — rebuilds only changed files into a signed hqf, installs via `bm quickfix -a -f -o`, then restarts the app. Much faster than a full `devecocli run` for iterating on code changes. Modules are auto-detected from the file paths in `<fileName>` (no `--module` needed).
176
178
  - `<fileName>`: a plain file name (no path separators) under the project's `.hvigor/` directory; the caller writes the changed-file list there. File name is sanitized to prevent path traversal. Content: list of **source file paths changed this round** (one per line, relative to project root or absolute; `#` comments and blank lines ignored; typically `.ets`/`.ts`/`.cpp`/resource files). The changeFileList is **incrementally merged** — only list files changed since the last apply; previously listed files are retained automatically.
177
179
  - **Prereq**: DevEco Studio ≥6.1.1 (hvigor `assembleDevHqf` support; below is rejected with an upgrade hint); run `devecocli run` once first (full build + deploy — `--apply` reuses its build intermediates and generates its own short-lived `buildConfig.json` per apply). Normal `run`/`build` clears the symbol table required by cold-reload ArkTS patches; the first `--apply` with ArkTS changes after a normal build automatically runs a full `assembleHap`/`assembleHsp` bootstrap (by module type) to regenerate it (may take tens of seconds on a cold cache; resource-only applies skip this). Consecutive applies without an intervening normal build reuse the symbol table and are fast.
@@ -302,6 +304,7 @@ Inspect UI on a connected device. All subcommands accept `--device <name|serial>
302
304
  |---|---|---|
303
305
  | `layout` | Dump ArkUI accessibility layout tree — **visible area only** (on-screen nodes). Requires device API 20+ | `--id <id>`, `--window <windowId>`, `--all-windows`, `--depth <n>` (0=unlimited, 1=root only, 2=root+children), `--format default\|json`, `--mode full\|simplified` |
304
306
  | `window list` | List active windows | `--format default\|json`, `--all` (include system windows) |
307
+ | `display list` | List displays with id, width and height (px) — source of `--display <displayId>` values for `ui screenshot` | `--format default\|json`, `--all` (add screen id, refresh rate, VPR, rotation columns; unreported fields render as `-`, or `null` in json) |
305
308
  | `screenshot` | Capture a screenshot of the device screen | `--display <displayId>`, required `--path <path>` (existing directory or PNG file path; relative paths supported; writable destination; no overwrite) |
306
309
  | `screenrecord` | Record the screen to an MP4 file (physical devices only; emulators are rejected) | interactive by default, or `start` / `stop` / `status`; required `--path <dir|file.mp4>` for interactive and `start`; `stop --force` stops a recording not started by this CLI; `status --format table\|json` |
307
310
  | `click [x] [y]` | Tap at the specified coordinates or node | `--id <id>` (auto-resolves to center), `--selector <expr>`, `--window <windowId>` (used with `--id` or `--selector`) |
@@ -356,6 +359,8 @@ devecocli testing update --service MemLeakTest
356
359
  devecocli testing run MemLeakTest --package com.example.myapp --sn <serial> --duration 10 --yes
357
360
  ```
358
361
 
362
+ **Device**: `--sn` must be the device the user confirmed. With several devices connected (`devecocli device list`), ask which one to test and wait for the answer; never default to the first serial.
363
+
359
364
  **Progress**: run `testing run` with the globally installed CLI (`& "$env:APPDATA\npm\devecocli.cmd"` on Windows, `"$(npm prefix -g)/bin/devecocli"` elsewhere) so output streams.
360
365
 
361
366
  **Result**: the run ends with `[REPORT] 报告已生成: <dir>`; read `<dir>/export/2d_report_data.json` (`isTaskPass`, `expandData[].resultSummary`, `expandData[].resultDetails[].status`) or `<dir>/export/Task-*.html` — never print the JSON. Services that write no `2d_report_data.json` keep the verdict in `<dir>/report/<taskId>_report.json` (`taskResult.taskPass`). Exit code stays `0` even when the task fails; on failure read `[ERROR]` / `[SUGGEST]`.
package/skills/index.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "generatedAt": "2026-11-05T10:31:37.827Z",
2
+ "generatedAt": "2026-11-10T09:37:34.921Z",
3
3
  "skills": [
4
4
  {
5
5
  "name": "deveco-cli",