@deveco-test/deveco-cli-common 1.3.13-23.2 → 1.4.0-25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +1 -1
- package/README.md +306 -1
- package/dist/cli.js +226 -224
- package/dist/internal/telemetry-upload-background.js +6 -6
- package/package.json +2 -2
- package/skills/deveco-cli/SKILL.md +22 -1
- package/skills/hmos-dfx-analyzer/SKILL.md +42 -8
- package/skills/hmos-dfx-analyzer/references/report-encoding-pitfalls.md +41 -0
- package/skills/hmos-dfx-analyzer/scripts/export_report.py +10 -4
- package/skills/hmos-dfx-analyzer/test-cases/functional.md +54 -6
- package/skills/hmos-dfx-analyzer/test-cases/smoke.md +40 -3
- package/skills/hmos-dfx-analyzer/test-cases/trigger.md +21 -2
- package/skills/index.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);f.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{f.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},k=null;function
|
|
1
|
+
import sn from"path";import*as _ from"fs";import*as _e from"path";import{homedir as It}from"os";var w=class extends Error{traceMessage;constructor(e,t,n){super(e,n),this.name="TraceError",this.traceMessage=t??e}};function ee(r){if(r instanceof w)return r.traceMessage;if(r instanceof Error){let e=r.code;return typeof e=="string"&&e!==""?e:r.name}return"UnknownError"}function te(r,e){return`${r}:${e}`}var h=class extends w{category;constructor(e,t,n,o){super(t,n,o),this.name="CategorizedTraceError",this.category=e}};function A(...r){return e=>r.includes(e.name)}function F(r,...e){return t=>{let n=t.code;return t.name===r&&typeof n=="string"&&e.includes(n)}}function Rt(r){let e=r.code;return e==="ETIMEDOUT"||e==="RPC_TIMEOUT"||/timeout/i.test(r.name)}function Pt(r){let e=r.code;return r.name==="ScreenRecordError"&&typeof e=="string"&&e.endsWith("_TIMEOUT")}var Lt=[{category:"Timeout",match:Rt},{category:"Internal",match:A("ExecaError")},{category:"RuntimeCondition",match:A("CacheDirError","DocPathSafetyError")},{category:"InvalidArgument",match:A("SelectorParseError")},{category:"InvalidArgument",match:A("InvalidApiLevelError")},{category:"InvalidArgument",match:A("TemplateNotFoundError")},{category:"InvalidArgument",match:A("InvalidArgumentError")},{category:"InvalidArgument",match:F("ScreenRecordError","INVALID_ARGUMENT","INVALID_RECORDING_PATH")},{category:"Timeout",match:Pt},{category:"InvalidArgument",match:F("FaultLogError","INVALID_ARGUMENTS","INVALID_INPUT","INPUT_OVERSIZED")},{category:"RuntimeCondition",match:F("FaultLogError","FILE_NOT_FOUND","UNRECOGNIZED_LOG")},{category:"Internal",match:F("FaultLogError","INTERNAL_ERROR")},{category:"RuntimeCondition",match:A("GrsError")}];function Dt(r){return Lt.find(t=>t.match(r))?.category??"Other"}function re(r){if(r instanceof h)return te(r.category,r.traceMessage);let e=r instanceof Error?Dt(r):"Other";return te(e,ee(r))}import*as Le from"fs";import*as S from"path";function ne(r){let e=S.resolve(r),t=[],n=e;for(;;)try{let o=Le.realpathSync(n);return t.length===0?o:S.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=S.dirname(n);if(i===n)return e;t.push(S.basename(n)),n=i}}function oe(r){let e=r.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function De(r){let e=oe(r);if(!e)throw new h("InvalidArgument","Path must not be empty.","Path must not be empty.");return ne(e)}var _t="deveco-cli",Ie,ie=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function Nt(){let r=process.env.DEVECO_CLI_DATA_DIR,t=(r===void 0||r===""?"":oe(r))||_e.join(It(),".local","share",_t);try{return De(t)}catch(n){throw new ie(n instanceof Error?n.message:String(n))}}function R(){if(Ie!==void 0)return Ie;let r=Nt();try{if(_.existsSync(r))return _.realpathSync(r)}catch{}return r}import St from"crypto";import m from"fs";import Q from"os";import E from"path";import kt from"https";var Ne={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var $=class r{static ENDPOINT=Ne.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 c=kt.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 v=[];g.on("data",I=>v.push(I)),g.on("end",()=>{s({code:g.statusCode??0,body:Buffer.concat(v).toString("utf8")})})});c.on("timeout",()=>{c.destroy(new Error("request timeout"))}),c.on("error",a),c.write(n),c.end()})}};var Oe={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()},se=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??Oe.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}},ke=new se({namingStrategy:Oe.snakeCase,fieldNames:{}});import N from"crypto";import U from"fs";import Mt from"path";var G="aes-256-gcm",Ft=12,Bt="deveco-cli-trace-file",$t="trace-file-secret",Fe=32;function Me(r){try{let e=U.readFileSync(r,"utf8").trim();return e&&Buffer.from(e,"base64").length===Fe?e:null}catch{return null}}function Be(r){let e=Mt.join(r,$t),t=Me(e);if(t)return ae(t);let n=N.randomBytes(Fe).toString("base64");try{U.mkdirSync(r,{recursive:!0});try{U.writeFileSync(e,n,{flag:"wx"})}catch{let o=Me(e);if(o)return ae(o);U.writeFileSync(e,n)}}catch{}return ae(n)}function ae(r){return N.createHash("sha256").update(Bt).update(r).digest()}function $e(r,e){let t=N.randomBytes(Ft),n=N.createCipheriv(G,e,t),o=Buffer.concat([n.update(r,"utf8"),n.final()]),i={version:1,algorithm:G,ciphertext:o.toString("base64"),iv:t.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(i)}function Ue(r,e){let t;try{t=JSON.parse(r)}catch{return null}if(!Ut(t))return r;try{let n=N.createDecipheriv(G,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 Ut(r){if(!r||typeof r!="object")return!1;let e=r;return e.version===1&&e.algorithm===G&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}import*as f from"fs";import*as j from"path";import*as O from"os";import*as b from"path";import $n from"json5";var jn=64*1024;function Ge(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??b.join(O.homedir(),"AppData","Local");return b.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?b.join(O.homedir(),"Library","Logs","devecocli-mcp-server"):b.join(O.homedir(),".local","share","devecocli-mcp-server","logs")}var He="mcp-server.log",Gt="mcp-server",Ht={maxSize:10*1024*1024,maxFiles:4},ce=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={...Ht,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Ge(),this.currentLogFile=j.join(this.logDir,He),f.existsSync(this.logDir)||f.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 j.join(this.logDir,`${Gt}-${e}.log.${t}`)}fileExists(e){try{return f.accessSync(e,f.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=f.readdirSync(this.logDir),t=[];for(let o of e)if(o===He||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=j.join(this.logDir,o),s=f.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{f.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)&&f.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)&&f.renameSync(i,s)}let n=this.getRotatedFileName(e,1);f.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=f.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=f.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{f.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(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).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 c=Buffer.from(a);f.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{f.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},k=null;function jt(r=!1){k&&k.dispose(),k=new ce(r)}function H(){return k||jt(!1),k}var d={debug:(r,...e)=>H().debug(r,...e),info:(r,...e)=>H().info(r,...e),warn:(r,...e)=>H().warn(r,...e),error:(r,...e)=>H().error(r,...e)};import Ve from"fs";import Vt from"path";var V=300*1e3,z=3600*1e3,ze=10080*60*1e3,P=8*1024*1024,qe=3600*1e3,je=".pending",zt=/\.reclaim-\d+-\d+$/;function q(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var qt="upload-state.json";function Ke(r){return Vt.join(r,qt)}function Kt(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function ue(r){try{let e=Ve.readFileSync(Ke(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 Kt()}}function le(r,e){try{Ve.writeFileSync(Ke(r),JSON.stringify(e),"utf8")}catch{}}function We(r){let e=ue(r);e.firstEventAt===null&&(e.firstEventAt=Date.now(),le(r,e))}function Xe(r){let e=ue(r);e.lastUploadAt=Date.now(),e.firstEventAt=null,le(r,e)}function Ye(r){let e=ue(r);e.lastRetryAt=Date.now(),le(r,e)}function Je(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 pe(r){if(!r.startsWith("telemetry-"))return null;let e=zt.exec(r),t=e?r.slice(0,e.index):r;if(!t.endsWith(je))return null;let n=t.slice(0,-je.length);return n.endsWith(".txt")?n:null}function K(r){return pe(r)!==null}import Wt from"crypto";import W from"fs";import Xt from"path";var Yt="install-id";function Jt(r){return Xt.join(r,Yt)}function Ze(r){try{let e=W.readFileSync(r,"utf8").trim();return Zt(e)?e:null}catch{return null}}function Zt(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 Qe(r){let e=Jt(r),t=Ze(e);if(t)return t;let n=Wt.randomUUID();try{W.mkdirSync(r,{recursive:!0});try{W.writeFileSync(e,n,{flag:"wx"})}catch{let o=Ze(e);if(o)return o;W.writeFileSync(e,n)}}catch{}return n}import y from"fs";import C from"path";var Qt="install-id",er="trace-file-secret",de="upload-state.json",et="failed";function rt(r){return r.startsWith("telemetry-")&&r.endsWith(".txt")||K(r)}function tr(r){try{return y.readdirSync(r).filter(rt)}catch{return[]}}function rr(r,e,t){try{return y.existsSync(e)?t?(y.appendFileSync(e,y.readFileSync(r)),y.rmSync(r),!0):!1:(y.renameSync(r,e),!0)}catch{return!1}}function tt(r,e,t){let n=0;for(let o of r)rr(C.join(e,o),C.join(t,o),!0)&&n++;return n}function nt(r){let e=C.dirname(r);e!==r&&(nr(e,r),or(e,r))}function nr(r,e){for(let t of[Qt,er]){let n=C.join(e,t),o=C.join(r,t);if(y.existsSync(n)&&y.existsSync(o))try{y.rmSync(n)}catch{}}}function or(r,e){let t;try{t=y.readdirSync(r)}catch{return}let n=t.filter(rt),o=C.join(r,et),i=tr(o),s=t.includes(de);if(n.length===0&&i.length===0&&!s)return;let a=C.join(e,et);try{y.mkdirSync(e,{recursive:!0}),y.mkdirSync(a,{recursive:!0})}catch{return}let c=tt(n,r,e)+tt(i,o,a);ir(r,e,s);try{y.rmdirSync(o)}catch{}c>0&&d.debug(`[telemetry] migrated ${c} legacy trace files into region dir`)}function ir(r,e,t){if(!t)return;let n=C.join(r,de),o=C.join(e,de);try{y.existsSync(o)?y.rmSync(n):y.renameSync(n,o)}catch{}}import hr from"axios";var ot={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},fe={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 sr={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function ar(r){try{return new URL(r)}catch{return null}}function X(r){var e=(typeof r=="string"?ar(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)||sr[t]||0,!cr(n,o)))return"";var i=me(t+"_proxy")||me("all_proxy");return i&&i.indexOf("://")===-1&&(i=t+"://"+i),i}function cr(r,e){var t=me("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 me(r){return process.env[r.toLowerCase()]||process.env[r.toUpperCase()]||""}function Y(r){try{let e=new URL(r);return`${e.protocol}//${e.host}`}catch{return"<redacted>"}}import{spawn as at}from"child_process";import*as x from"fs";import*as ct from"os";import*as J from"path";var ut=6e4;async function ur(){if(process.platform!=="win32")return null;let r="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",e=await it(r,"ProxyServer");if(!e)return null;let t=await it(r,"ProxyEnable");return t!=="1"&&t!=="0x1"?null:e.trim()}function it(r,e){return new Promise(t=>{let n=at("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 lr(){let r=process.env.HTTPS_PROXY??process.env.HTTP_PROXY??"";if(!r)return null;try{return new URL(r).host}catch{return r}}function pr(){return`${process.env.SystemRoot??"C:\\Windows"}\\System32\\curl.exe`}function st(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 dr(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??ut)/1e3)))];return r.method&&r.method!=="GET"&&o.push("-X",r.method),r.data!==void 0&&o.push("--data-binary",r.data),o.push(...fr(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 fr(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 mr(r,e,t){if(t){let g=x.readFileSync(e,"utf8"),v=x.readFileSync(t),I=st(g);return{statusCode:I.statusCode,statusText:I.statusText,body:v.toString("base64"),headers:I.headers,bodyBuffer:v}}let n=r.lastIndexOf("HTTP/");if(n===-1)return null;let o=r.slice(n),i=o.indexOf(`\r
|
|
3
3
|
\r
|
|
4
|
-
`);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),c=st(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function lt(r){if(process.platform!=="win32")return null;let e=
|
|
5
|
-
${e}`,r.code??"Unknown",{cause:r});return t.code=r.code,t.response=r.response,t}var ge=class{client;constructor(){let e={timeout:ot.HTTP_TIMEOUT_MS,headers:{"User-Agent":fe.USER_AGENT,"accept-language":fe.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=
|
|
4
|
+
`);if(i===-1)return null;let s=o.slice(0,i),a=o.slice(i+4),c=st(s);return{statusCode:c.statusCode,statusText:c.statusText,body:a,headers:c.headers}}async function lt(r){if(process.platform!=="win32")return null;let e=lr()??await ur();if(!e)return null;let t;r.binary&&(t=x.mkdtempSync(J.join(ct.tmpdir(),"curl-")));let n=t?J.join(t,"header.tmp"):void 0,o=t?J.join(t,"body.tmp"):void 0;try{let i=dr(r,e,n,o),s=await gr(i,r.timeoutMs);return!s||s.code!==0?null:mr(s.stdout,n,o)}catch{return null}finally{t&&x.rmSync(t,{recursive:!0,force:!0})}}function gr(r,e){let t=pr();return new Promise(n=>{let o=at(t,r,{windowsHide:!0,stdio:["ignore","pipe","pipe"]}),i="",s=!1,a=setTimeout(()=>{s||(s=!0,o.kill())},e??ut);o.stdout.on("data",c=>{i+=c.toString()}),o.on("error",()=>{s||(s=!0,clearTimeout(a),n(null))}),o.on("close",c=>{if(clearTimeout(a),s){n(null);return}s=!0,n({code:c??-1,stdout:i})})})}function he(r){let e=new URL(r),t=pt(e.username,r),n=pt(e.password,r);return{protocol:e.protocol,host:e.hostname,port:e.port?Number.parseInt(e.port,10):e.protocol==="https:"?443:80,...t||n?{auth:{username:t,password:n}}:{}}}function pt(r,e){try{return decodeURIComponent(r)}catch{throw new h("InvalidArgument",`Invalid proxy URL ${JSON.stringify(Y(e))}: malformed percent-encoding in credentials. Percent-encode special characters (e.g. '@' as '%40') in the proxy URL.`,"Invalid proxy URL.")}}function yr(r,e){return r==="ETIMEDOUT"||r==="ECONNABORTED"&&/timeout/i.test(e)}function Er(r){let e=`Network connection failed (${r.code}). Please check your proxy configuration or network settings`,t=new h(yr(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 ge=class{client;constructor(){let e={timeout:ot.HTTP_TIMEOUT_MS,headers:{"User-Agent":fe.USER_AGENT,"accept-language":fe.ACCEPT_LANGUAGE},transformResponse:[t=>t]};this.client=hr.create(e),this.client.interceptors.request.use(t=>{if(t.httpsAgent)return t.proxy=!1,t;let n=X(t.url??"");return t.proxy=n?he(n):!1,t}),this.client.interceptors.response.use(t=>t,t=>{throw Er(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 h("Internal",`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,"Failed to parse JSON response.",{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 h("Internal",`HTTP ${n.status}`,"HTTP request failed.");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 h("Internal",`HTTP ${o.statusCode}`,"HTTP request failed.");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(vr(o)||process.platform!=="win32"||!(e instanceof Error)||!Sr(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)),lt({url:a,method:n,data:s,headers:o?.headers,timeoutMs:o?.timeout,binary:i})}},ye=new ge;function vr(r){return!!r?.signal||(r?.maxBodyLength??-1)>=0||(r?.maxContentLength??-1)>=0}function Sr(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}`}function p(r){if(process.env.DEVECO_CLI_DEBUG){let e=typeof r=="function"?r():r;console.error(`[DEBUG] ${e}`)}}import Cr from"fs";import br from"http";import Ar from"https";import xr from"path";import dt from"tls";import Se from"crypto";import{yellow as wr}from"colorette";var Rr=`-----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-----`,Rr=new Se.X509Certificate(wr),ft=[{cert:Rr}];function Pr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new Se.X509Certificate(n)})}catch{}return e}var mt=new Set,Z;function Lr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(Z&&Z.envValue===r)return Z.anchors;let e=r?Dr(r):[],t=e.length?[...ft,...e]:ft;return Z={envValue:r,anchors:t},t}function Dr(r){try{let e=Pr(Tr.readFileSync(r,"utf8"));return e.length===0&>(r,"no parseable certificate found"),e}catch(e){return gt(r,e instanceof Error?e.message:String(e)),[]}}function gt(r,e){mt.has(r)||(mt.add(r),console.warn(xr(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${Ar.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 o=n.fingerprint256||n.fingerprint||"";if(!o||t.has(o))break;t.add(o);try{e.push(new Se.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function _r(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Nr(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=Or(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function Nr(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&ht(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)&&ht(r,r.length-1))return!0}catch{}return!1}function ht(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 Or(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(!Mr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function kr(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"):_r(n,e,Lr())}function Mr(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),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var Fr=8e3,Ee=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)}}},ve=class extends br.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Fr}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=X(i),a=new Ee(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=dt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return he(e)}catch(n){return t.settle(new Error(`[GRS] ${n.message}`)),null}}createConnectionViaProxy(e,t,n,o,i){let s=this.parseProxyOrSettle(t,i);if(!s)return;let a=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${n}:${o}`);let c=Cr.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>c.destroy()),c.on("connect",(g,v)=>{if(g.statusCode!==200){v.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>v.destroy()),this.startTlsOverTunnel(e,v,i,n)}),c.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),c.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=dt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`},i=e.auth;if(i&&(i.username||i.password)){let s=`${i.username}:${i.password}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=kr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},Te=new ve({keepAlive:!0});var Ce=[{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"}],L=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var Br=["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"],$r="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Ur="devecostudio",Gr=8e3;async function be(r){let e=[],t="";for(let i of Br){let s=await Hr(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 L("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: ${Y(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 L("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function Hr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Ur}`;p(()=>`[GRS] POST ${t}`);try{let n=await ye.post(t,{headers:{"User-Agent":$r},httpsAgent:Te,timeout:Gr}),o=ye.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):jr(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 jr(r){return Ce.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import yt from"fs";import Vr from"path";var zr="com.huawei.devecostudio.region",qr={[zr]:{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"}},Kr=1440*60*1e3,Et=new Set(["CN","HK","MO"]),Ae=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 h("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new h("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=qr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Wr(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 be(this.countryCode);this.services=t,this.resolved=!0,await Xr(this.countryCode,t)}},T=new Ae;function vt(r){return Vr.join(R(),`grs_${r}.json`)}async function Wr(r){try{let e=await yt.promises.readFile(vt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Kr?null:t}catch{return null}}async function Xr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await yt.promises.writeFile(vt(r),JSON.stringify(t),"utf8")}catch{}}var M=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 $;storageDir="";failedDir="";installId="";get disabled(){return q()||!T.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(){d.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=E.join(e,"failed"),this.cliVersion="1.3.13-23.2",this.nodeVersion=process.version,m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0});let t=E.dirname(e);this.installId=Qe(t).replace(/-/g,""),this.traceFileKey=Be(t),nt(e),d.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,d.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,d.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,d.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return d.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=re(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=$e(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
|
|
39
|
+
-----END CERTIFICATE-----`,Pr=new Se.X509Certificate(Rr),ft=[{cert:Pr}];function Lr(r){let e=[],t=r.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let n of t)try{e.push({cert:new Se.X509Certificate(n)})}catch{}return e}var mt=new Set,Z;function Dr(){let r=process.env.NODE_EXTRA_CA_CERTS;if(Z&&Z.envValue===r)return Z.anchors;let e=r?Ir(r):[],t=e.length?[...ft,...e]:ft;return Z={envValue:r,anchors:t},t}function Ir(r){try{let e=Lr(Cr.readFileSync(r,"utf8"));return e.length===0&>(r,"no parseable certificate found"),e}catch(e){return gt(r,e instanceof Error?e.message:String(e)),[]}}function gt(r,e){mt.has(r)||(mt.add(r),console.warn(wr(`[devecocli] GRS TLS: failed to load NODE_EXTRA_CA_CERTS (${xr.basename(r)}): ${e} \u2014 falling back to the built-in CA only.`)))}function _r(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 Se.X509Certificate(n.raw))}catch{break}let i=n.issuerCertificate??null;if(i===r)break;n=i}return e}function Nr(r,e,t){if(r.length===0)return new Error("[GRS TLS] Server did not provide a certificate");if(!Or(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=kr(r[0],e);if(n)return n;p(()=>"[GRS TLS] Verification passed: certificate chain anchored on a trusted CA")}function Or(r,e){for(let n of e){let o=r.findIndex(i=>i.fingerprint256===n.cert.fingerprint256);if(o>=0&&ht(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)&&ht(r,r.length-1))return!0}catch{}return!1}function ht(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 kr(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(!Fr(r,e))return new Error(`[GRS TLS] Server certificate does not match host ${e}`)}function Mr(r,e){let t=r.getPeerCertificate(!0);if(!t||!t.raw)return new Error("[GRS TLS] Server did not provide a certificate");let n=_r(t);return n.length===0?new Error("[GRS TLS] Server certificate could not be parsed"):Nr(n,e,Dr())}function Fr(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),c=n.slice(0,-a.length);if(n.endsWith(a)&&c.length>0&&!c.includes("."))return!0}}return!1}var Br=8e3,Ee=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)}}},ve=class extends Ar.Agent{connectTimeoutMs;constructor(e){super(e),this.connectTimeoutMs=e?.connectTimeoutMs??Br}createConnection(e,t){let n=e.host||e.servername||"",o=e.port||443,i=`https://${n}:${o}`,s=X(i),a=new Ee(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=dt.connect({...e,rejectUnauthorized:!1});return t.onDestroy(()=>o.destroy()),this.attachTlsVerification(o,t,n),o}parseProxyOrSettle(e,t){try{return he(e)}catch(n){return t.settle(new Error(`[GRS] ${n.message}`)),null}}createConnectionViaProxy(e,t,n,o,i){let s=this.parseProxyOrSettle(t,i);if(!s)return;let a=this.buildProxyHeaders(s,n,o);p(()=>`[GRS] Connecting via proxy ${s.host}:${s.port} to ${n}:${o}`);let c=br.request({host:s.host,port:s.port,method:"CONNECT",path:`${n}:${o}`,headers:a});i.onDestroy(()=>c.destroy()),c.on("connect",(g,v)=>{if(g.statusCode!==200){v.destroy(),i.settle(new Error(`[GRS] Proxy CONNECT failed: ${g.statusCode} ${g.statusMessage||""}`));return}i.onDestroy(()=>v.destroy()),this.startTlsOverTunnel(e,v,i,n)}),c.on("error",g=>{i.settle(new Error(`[GRS] Proxy connection failed: ${g.message}`))}),c.end()}startTlsOverTunnel(e,t,n,o){p(()=>"[GRS] Proxy tunnel established, starting TLS handshake");let i=dt.connect({...e,socket:t,rejectUnauthorized:!1});n.onDestroy(()=>i.destroy()),this.attachTlsVerification(i,n,o)}buildProxyHeaders(e,t,n){let o={Host:`${t}:${n}`},i=e.auth;if(i&&(i.username||i.password)){let s=`${i.username}:${i.password}`;o["Proxy-Authorization"]=`Basic ${Buffer.from(s).toString("base64")}`}return o}attachTlsVerification(e,t,n){e.once("secureConnect",()=>{let o=Mr(e,n);o?(e.destroy(o),t.settle(o)):t.settle(null,e)}),e.once("error",o=>{t.settle(o)})}},Te=new ve({keepAlive:!0});var Ce=[{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"}],L=class extends Error{kind;constructor(e,t){super(t),this.name="GrsError",this.kind=e}};var $r=["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"],Ur="com.huawei.deveco.common-grs/0.1 (Windows;Linux;Mac) Deveco-grs/-1",Gr="devecostudio",Hr=8e3;async function be(r){let e=[],t="";for(let i of $r){let s=await jr(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 L("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: ${Y(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 L("network",`GRS endpoints unreachable (grs.dbankcloud.com is globally reachable). ${o}${t?` Last endpoint error: ${t}`:""}`)}async function jr(r,e){let t=`${r}?issue_country=${encodeURIComponent(e)}&app_name=${Gr}`;p(()=>`[GRS] POST ${t}`);try{let n=await ye.post(t,{headers:{"User-Agent":Ur},httpsAgent:Te,timeout:Hr}),o=ye.parseJson(n);return o.resultCode!==0?(p(()=>`[GRS] ${r} resultCode=${o.resultCode}, skipping`),{outcome:"incomplete",detail:`resultCode=${o.resultCode}`}):Vr(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 Vr(r){return Ce.every(({group:e,key:t})=>typeof r[e]?.[t]=="string")}import yt from"fs";import zr from"path";var qr="com.huawei.devecostudio.region",Kr={[qr]:{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"}},Wr=1440*60*1e3,Et=new Set(["CN","HK","MO"]),Ae=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 h("RuntimeCondition",`GRS service ${e}.${t} not available`,"GRS service not available.");return n}setCountryCode(e){this.countryCode=e}async resolve(){if(!this.countryCode)throw new h("RuntimeCondition","Country code not set, cannot resolve GRS","Country code not set.");if(this.countryCode==="CN"){this.services=Kr,this.resolved=!0,p(()=>"[GRS] CN uses hardcoded services, skipping GRS request");return}let e=await Xr(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 be(this.countryCode);this.services=t,this.resolved=!0,await Yr(this.countryCode,t)}},T=new Ae;function vt(r){return zr.join(R(),`grs_${r}.json`)}async function Xr(r){try{let e=await yt.promises.readFile(vt(r),"utf8"),t=JSON.parse(e);return t.countryCode!==r||Date.now()-t.fetchedAt>Wr?null:t}catch{return null}}async function Yr(r,e){let t={services:e,fetchedAt:Date.now(),countryCode:r};try{await yt.promises.writeFile(vt(r),JSON.stringify(t),"utf8")}catch{}}function Tt(){return!q()&&T.isCN()}var M=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 $;storageDir="";failedDir="";installId="";get disabled(){return!Tt()}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(){d.debug(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(e){this.storageDir=e,this.failedDir=E.join(e,"failed"),this.cliVersion="1.4.0-25",this.nodeVersion=process.version,m.mkdirSync(e,{recursive:!0}),m.mkdirSync(this.failedDir,{recursive:!0});let t=E.dirname(e);this.installId=Qe(t).replace(/-/g,""),this.traceFileKey=Be(t),nt(e),d.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,d.debug(`[telemetry] studio version set: ${e}`)}setSourceType(e){this.sourceType=e,d.debug(`[telemetry] sourceType set: ${e}`)}setCltVersion(e){this.cltVersion=e,d.debug(`[telemetry] CLT version set: ${e}`)}async track(e,t){if(this.disabled)return typeof t=="function"?t():void 0;if(!this.storageDir)return d.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=re(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=$e(JSON.stringify(i),this.traceFileKey);await m.promises.appendFile(this.currentFile(),s+`
|
|
40
40
|
`,"utf8"),We(this.storageDir)}catch{}}buildTraceEvent(e,t,n,o){let i=`${r.EVENT_PREFIX}${e.event}`,s=ke.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}}}resolveOsArch(){let e=Q.arch();return e==="x64"?"amd64":e}resolveOsName(){switch(process.platform){case"win32":{let e=Q.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 Q.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}resolveTotalRam(){return`${Math.round(Q.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 E.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){d.debug("[telemetry] scheduler not started (telemetry disabled)");return}d.debug(`[telemetry] scheduler started (flush every ${V/1e3}s, retry failed every ${z/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},V)},V),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},z)},z)}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),d.debug("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)return d.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 Xe(this.storageDir),t}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)return d.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=>E.join(this.failedDir,i)),o=!0;for(let i of n){let s=E.basename(i),a=Je(s);if(a!==null){if(e-a>ze){try{await m.promises.unlink(i)}catch{}continue}await this.flushFile(i)||(o=!1)}}return o||d.warn("[telemetry] retry failed"),Ye(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)K(o)&&await this.reclaimOrphan(E.join(t,o),e)}}async reclaimOrphan(e,t){let n;try{let g=await m.promises.stat(e);if(t-g.mtimeMs<qe)return;n=g.size}catch{return}let o=E.dirname(e),i=pe(E.basename(e));if(i===null)return;let s=await this.claimOrphan(e,o,i);if(s===null)return;let a=E.join(o,i),c=P-await this.fileSize(a);if(n>c){try{await m.promises.unlink(s)}catch{}d.warn(`[telemetry] dropped stale orphan pending: ${s} (${n} bytes > budget ${c})`);return}if(await this.mergeOrphanInto(s,a)){d.warn(`[telemetry] reclaimed orphan pending: ${s} (${n} bytes)`);return}d.warn(`[telemetry] merge failed, kept orphan pending for retry: ${s} (${n} bytes)`)}async claimOrphan(e,t,n){let o=E.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 d.warn(`[telemetry] merge orphan pending failed: ${e} -> ${t}: ${n instanceof Error?n.message:String(n)}`),!1}try{await m.promises.unlink(e)}catch(n){d.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=>E.join(this.storageDir,t)).sort()}async flushFile(e){let t=await this.fileSize(e);if(t>P){d.warn(`[telemetry] ${E.basename(e)} is ${t} bytes (> ${P}), 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
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=Ue(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 c=JSON.stringify(a),g=!1;try{g=await this.uploader.upload(c,this.installId)}catch{}if(!g){d.warn("[telemetry] upload failed");let v=t.slice(o).join(`
|
|
42
42
|
`)+`
|
|
43
43
|
`;return await this.moveToFailed(e,v),!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=E.basename(e,".pending"),o=E.join(this.failedDir,n),i=t.split(`
|
|
44
44
|
`).filter(Boolean),s=P-await this.fileSize(o),a=this.takeNewestWithinBudget(i,s);a.length<i.length&&d.warn(`[telemetry] failed file capped at ${P} 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=[],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 D=new M;import{execFile as
|
|
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 D=new M;import{execFile as Qi,spawn as es}from"child_process";import{existsSync as rs,readdirSync as ns,readFileSync as os}from"fs";import{spawn as ys}from"child_process";import{existsSync as vs}from"fs";import{dirname as Ts,join as Cs}from"path";import{fileURLToPath as As}from"url";var Zr=new Set(["C","POSIX"]);function xe(){let r=Qr();if(!r)return p("[region] locale \u65E0\u4FE1\u53F7"),null;if(p(()=>`[region] locale=${r}`),Zr.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=en(e);return t?(p(()=>`[region] locale region=${t}`),t):(p(()=>`[region] locale=${r} \u65E0 region \u5B50\u6807\u7B7E`),null)}function Qr(){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 en(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 we={"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 Re(){let r=xe();if(r)return{code:r,source:"locale"};let e=Ct();return e?{code:e,source:"timezone"}:(p("[region] Country code detection failed (no signal from locale or timezone)"),null)}function Ct(){let r;try{r=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}if(!r)return null;let e=we[r];return e?(p(()=>`[region] timezone ${r} -> ${e}`),e):(p(()=>`[region] timezone ${r} has no country mapping`),null)}import bt from"fs";import At from"path";import{homedir as tn}from"os";var rn="country.region.xml",nn=".config",on="deveco-cli";function xt(){let r=process.env.DEVECO_CLI_DATA_DIR?R():At.join(tn(),nn,on);return At.join(r,rn)}function Pe(){let r=xt();try{if(!bt.existsSync(r))return null;let t=bt.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 wt=Pe();if(wt)T.setCountryCode(wt);else{let r=Re();r&&T.setCountryCode(r.code)}if(!T.isCN())d.info("[telemetry] background upload skipped (non-CN region)");else{let r=sn.join(R(),"TraceLogData",T.countryCode);D.init(r),(async()=>{try{await D.flush(),await D.retryFailed()}catch(e){d.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
|
+
"version": "1.4.0-25",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"supportedDocsApi": 1,
|
|
6
6
|
"license": "MIT",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"ws": "^8.21.1",
|
|
69
69
|
"xpath": "^0.0.35",
|
|
70
70
|
"zod": "^4.4.3",
|
|
71
|
-
"@deveco-test/deveco-cli-knowledgebase": "1.
|
|
71
|
+
"@deveco-test/deveco-cli-knowledgebase": "1.4.0-25"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
74
|
"@types/adm-zip": "^0.5.8",
|
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
|
|
10
10
|
`devecocli` wraps DevEco Studio's `hvigor`, `ohpm`, `hdc`, emulator toolchain, and bundled skills installer.
|
|
11
11
|
|
|
12
|
-
Available commands: `build`, `check`, `run`, `debug`, `update`, `device`, `emulator`, `ui`, `skills`, `log`, `verify`, `create`, `init`, `serve`, `docs`, `signature`, `auth`, `design2arkts` (alias `d2a`), `testing`.
|
|
12
|
+
Available commands: `build`, `check`, `run`, `debug`, `update`, `device`, `emulator`, `ui`, `skills`, `log`, `verify`, `profiler`, `create`, `init`, `serve`, `docs`, `signature`, `auth`, `design2arkts` (alias `d2a`), `testing`.
|
|
13
13
|
|
|
14
14
|
**Sandbox Rule**: Commands tagged `[Outside sandbox]` must be run outside the sandbox.
|
|
15
15
|
|
|
@@ -409,6 +409,27 @@ devecocli testing run MemLeakTest --package com.example.myapp --sn <serial> --du
|
|
|
409
409
|
- **Progress**: run `testing run` through the globally installed CLI (`& "$env:APPDATA\npm\devecocli.cmd"` / `"$(npm prefix -g)/bin/devecocli"`) so output streams.
|
|
410
410
|
- **Result**: the run ends with `[REPORT] 报告已生成: <dir>`; read `<dir>/export/2d_report_data.json` (`isTaskPass`, `expandData[].resultSummary`, `expandData[].resultDetails[].status`) or `export/Task-*.html` — never print the JSON. No `2d_report_data.json` → `<dir>/report/<taskId>_report.json` (`taskResult.taskPass`). Exit code is `0` even on failure, so read `[ERROR]` / `[SUGGEST]`.
|
|
411
411
|
|
|
412
|
+
### `devecocli profiler`
|
|
413
|
+
Cold-start performance profiling. `record app-launch` records a cold launch on a device (Trace / Perf / RedundantFile); `analyze` subcommands analyze the recorded artifacts by dimension and `performance` subcommands provide scene/phase queries — both print the profiler backend's JSON envelope (`{code, message, data, requestId, costMs}`) **verbatim**: `devecocli` never reshapes, retypes or trims it, so field names and units always follow the backend. A non-zero backend exit code (0 ok / 2 usage / 3 input / 4 analysis / 5 not found) becomes the command's exit code. `app-stop` force-stops a target app on a device and `version` prints the backend jar version. Requires the Command Line Tools toolchain — set `DEVECO_CLI_CLT_PATH` when DevEco Studio is detected (the profiler command group — version check, recording device discovery, and the bridge process — uniformly prefers the CLT from `DEVECO_CLI_CLT_PATH` even when `DEVECO_CLI_STUDIO_PATH` is set). Analysis-window timestamps are in nanoseconds.
|
|
414
|
+
|
|
415
|
+
| Subcommand | Description | Key Options |
|
|
416
|
+
|---|---|---|
|
|
417
|
+
| `version` | Print the backend jar's version and build time — use it to confirm which build is actually deployed (the version number often stays the same) | — |
|
|
418
|
+
| `app-stop` | Force-stop a running application on a device via `aa force-stop` | Req `--bundle <name>`; Opt `--device <name\|serial>` (Req on multi-device hosts) |
|
|
419
|
+
| `record app-launch` | Record one cold launch, producing Trace / Perf / RedundantFile files with per-file status | Req `--bundle <name>`, `--output <dir>`; Opt `-t, --time <seconds>` (default `20`), `--device <name\|serial>` (Req on multi-device hosts) |
|
|
420
|
+
| `analyze high-cost-function` | Find CPU sampling hotspots of one thread within explicit time windows (leads, not root-cause evidence) | Req `--input <perf .data/.insight>`, `--pid`, `--tid`, `--start <ns>`, `--end <ns>`; Opt `--top <n>` (default `10`, 1-100) |
|
|
421
|
+
| `analyze main-thread-blocking` | Attribute main-thread blocking to async wakeup threads per frame window (not the main thread itself being slow) | Req `--input <.htrace>`, `--pid`, `--start <ns>`, `--end <ns>`; Opt second `--input <perf .data/.insight>`, `--min-idle <ns>`, `--top <n>` |
|
|
422
|
+
| `analyze network-optimization` | List slow requests within the launch window with optimization candidates (no automatic changes) | Req `--input <.htrace>`, `--pid`, `--start <ns>`, `--end <ns>`; Opt `--min-duration <ns>` (default `0`), `--top <n>` (default `10`) |
|
|
423
|
+
| `analyze component-complexity` | Locate component create/update hotspots and structure complexity per frame window | Req `--input <.htrace>`, `--pid`, `--start <ns>`, `--end <ns>`; Opt `--top <n>` |
|
|
424
|
+
| `analyze module-import` | Identify ETS/SO loads that could be deferred from a RedundantFile | Req `--input <RedundantFile .json/.txt>`; Opt `--top <n>` (default `20`) |
|
|
425
|
+
| `performance scene-reconstruction` | Enumerate apps and launch scenes in a trace with time and process context | Req `--input <.htrace>`; Opt `--bundle <name>`, `--scene-type launch` (default `launch`) |
|
|
426
|
+
| `performance launch-phases` | Query sub-phases of a selected cold launch, sorted to prioritize analysis | Req `--bundle <name>`, `--pid`, `--start <ns>`, `--end <ns>`, `--input <.htrace>` |
|
|
427
|
+
|
|
428
|
+
- **Typical flow**: `record app-launch` → `scene-reconstruction` (locate the launch scene and time window) → `launch-phases` (phase breakdown) → dimension-specific analysis with `--pid --start --end`. Scene items carry `start` / `end` / `duration` straight from the backend (current builds emit integer **nanoseconds**, the same unit analysis commands accept) — trust the response, not this note, since field names and units follow the backend.
|
|
429
|
+
- **Multiple inputs**: only `main-thread-blocking` accepts a second file, passed by repeating the flag (`--input <a> --input <b>`, at most 2 files). All other analysis commands take exactly one `--input <file>`.
|
|
430
|
+
*Ex*: `devecocli profiler record app-launch --bundle com.example.app --output ./launch-data -t 30`
|
|
431
|
+
*Ex*: `devecocli profiler performance launch-phases --bundle com.example.app --pid 12345 --start 1000000000000 --end 1100000000000 --input ./launch-data/app.htrace`
|
|
432
|
+
|
|
412
433
|
## 2. Setup
|
|
413
434
|
|
|
414
435
|
### Agent Plugins
|
|
@@ -129,7 +129,13 @@ python --version
|
|
|
129
129
|
无任何输出、退出码 9009、或弹出 Microsoft Store)时,改用 `py -3` 替代后续**所有** Python
|
|
130
130
|
命令中的 `python`,不要在 stub 上反复试探或另行包装调用;
|
|
131
131
|
- **编码约束**:调用本 Skill 及各 Analyzer 的 Python 脚本时,统一附加 `PYTHONIOENCODING=utf-8` 环境变量(如 `PYTHONIOENCODING=utf-8 python "<脚本>" ...`),确保中文输出在任意终端/locale(Windows GBK、无 LANG 环境等)下不乱码;若脚本输出出现乱码或 UnicodeEncodeError,先补加该环境变量重试,不得把乱码当作分析依据;
|
|
132
|
-
- 分诊必须依赖上述两条路径完成(强制规则 1):CLI
|
|
132
|
+
- 分诊必须依赖上述两条路径完成(强制规则 1):CLI 与兜底脚本均不可用时不得跳过检查自行判读日志,
|
|
133
|
+
应明确告知用户当前无法执行确定性分诊。**降级场景例外**(唯一真值源为上方「强制规则与放行条件」
|
|
134
|
+
规则 1 的降级例外,触发判定为「先实际尝试执行、以命令不可用/执行失败的真实输出为据」):
|
|
135
|
+
确认环境无脚本执行能力后,可依据日志自身结构特征(事件名、头部字段、栈帧形态,判据同
|
|
136
|
+
`identify_fault_log.py` 的正向特征集)给出**带受限标注的判定结论**(类型 + 置信度 low +
|
|
137
|
+
标注「脚本验证不可用,依据结构特征判定」),并按固定路由声明将加载的 Analyzer——该结论仅限
|
|
138
|
+
无脚本执行能力的隔离评测环境收尾使用,不作为正常交付形态。
|
|
133
139
|
|
|
134
140
|
调用方式(路径用绝对路径,不依赖当前工作目录):
|
|
135
141
|
|
|
@@ -196,8 +202,14 @@ L3 口述到故障类型的映射,判据统一为一条:
|
|
|
196
202
|
违反以下任一条即为缺陷:
|
|
197
203
|
|
|
198
204
|
1. **存在日志证据时必须执行识别脚本**,不得自行判读内容定类。文件名与你的直觉都不构成定类依据。
|
|
205
|
+
**降级例外**:先实际尝试执行上述两条路径(含 Python 可用性检查),以「命令不可用/执行失败」
|
|
206
|
+
的**真实输出**为据判定当前环境无脚本执行能力时,方可按「呈现与交付 → 无脚本执行环境的降级交付」
|
|
207
|
+
的例外路径给出带受限标注的结论(详见该节)。仅限隔离评测环境收尾,不作为正常交付形态;未尝试
|
|
208
|
+
执行脚本即自行判读的,仍属违反本条。
|
|
199
209
|
2. **L1 有结论时据此定类**;L2(文件名)与 L3(用户口述)仅用于一致性标注。
|
|
200
210
|
3. **L1 无结论时不得加载任何专项 Analyzer**。直接输出可解释的拒答结论,不猜测、不兜底选类。
|
|
211
|
+
**降级例外**:规则 1 的降级路径(以实际执行失败为据、环境无脚本执行能力)下按固定路由声明
|
|
212
|
+
加载对应 Analyzer 属于例外,但结论必须带受限标注。
|
|
201
213
|
**L1 结论为 `sample_stack`(采样栈/增强日志)时同样不得加载**——它只是冻屏分析的配套证据,
|
|
202
214
|
缺少 faultlog 主证据时先索取(见「配套证据归并与传递」),不得降级单独分析。
|
|
203
215
|
4. **冲突必须显式输出,不得静默纠正**。用户口述与证据判定不一致时,按证据继续,同时披露分歧与两种可能成因,并把用户口述作为线索传入专项 Analyzer。真正被禁止的是**静默采信**——按用户说法分析却不说明依据已被替换;用户明确要求且系统显式标注"类型系用户指定"不属自行改写(见「分诊结论被用户反驳」)。
|
|
@@ -240,7 +252,8 @@ L3 口述到故障类型的映射,判据统一为一条:
|
|
|
240
252
|
`实际分析文件:<path>`,不要为可自行消解的小偏差打断用户。
|
|
241
253
|
5. 多个候选同等合理、没有合理候选、关键内容不可读或需要扩大到不明确的搜索范围时,才使用 question
|
|
242
254
|
请求用户选择或补充信息。不得仅凭文件名强行确定类型。
|
|
243
|
-
6.
|
|
255
|
+
6. **批量场景**(目录含多份故障日志,多份日志文件一次性给出,或单条消息内以明确份数标记
|
|
256
|
+
粘贴多份日志——按份数标记或日志头部字段(如 Reason/Timestamp 行)切分边界,逐份独立处理):
|
|
244
257
|
- 已明确全量意图 → 不确认范围,对全部故障日志逐份执行识别脚本,每份独立走完决策表。
|
|
245
258
|
"明确全量意图"的真值源仅限**用户原话**(显式 /analyze 的 <DFX_USER_ARGUMENTS> 区块、
|
|
246
259
|
当前轮用户消息、或 question 回复)写明"全部 / 逐份 / 所有日志"。用户原话仅含路径、
|
|
@@ -251,11 +264,16 @@ L3 口述到故障类型的映射,判据统一为一条:
|
|
|
251
264
|
- 范围确认全量后按类型分组交付:同一类型多份由对应专项 Analyzer 逐份出分报告;跨类型时每个
|
|
252
265
|
命中类型按固定路由各加载一次对应 Analyzer(「专项 Analyzer 固定路由」单一加载规则的显式
|
|
253
266
|
例外),最终交付一份按日志逐份分节的合并报告,分诊摘要行按各份分别给出。
|
|
254
|
-
合并报告的**分节契约**:每份日志以 `### 日志 N
|
|
267
|
+
合并报告的**分节契约**:每份日志以 `### 日志 N:<文件名或序号>` 起节(粘贴/无文件名的日志按
|
|
268
|
+
序号编号),**分节首行为该份的分诊结论行**
|
|
255
269
|
(折叠一行协议),其下**完整遵循该类型 Analyzer
|
|
256
270
|
输出格式章节**(章节编号、命名与顺序逐一对齐,标题层级移到日志小节之下)——三级根因定位、
|
|
257
271
|
证据链等契约章节逐份必备,不得省略或合并;分诊摘要表逐份携带单份协议三字段
|
|
258
272
|
`类型 / 输入完整度 / 置信度`(其余列可自选,三项不得缺)。
|
|
273
|
+
合并交付时把「汇总表 → 各类型分节」的文件**按顺序逐一 `--input` 传给 export_report.py**(脚本
|
|
274
|
+
自动以 `---` 分隔拼接,UTF-8 全链路),**禁止先经 shell 合并成单文件**(机理与禁令见
|
|
275
|
+
「HTML 报告落盘」)。跨类型批量合并报告统一传 `--type batch`(类型标签为「批量合并报告」);
|
|
276
|
+
单类型批量合并可沿用该类型值(如全部为 `app_freeze` 时传 `--type app_freeze`)。
|
|
259
277
|
7. **采样栈(增强日志)不计入独立日志**:对枚举出的候选文件逐一执行识别脚本后,`type=sample_stack`
|
|
260
278
|
的文件不参与规则 6 的候选计数与范围确认("多份日志"只统计 faultlog),按「配套证据归并与传递」
|
|
261
279
|
归并到同事件的冻屏 faultlog;无冻屏 faultlog 可归并时,按「结果处置决策表」`sample_stack` 行
|
|
@@ -428,6 +446,14 @@ L3 口述到故障类型的映射,判据统一为一条:
|
|
|
428
446
|
| 明确类型(单份或批量合并) | 简洁摘要(见下节钉板) | **必须生成**,报告路径写入摘要 |
|
|
429
447
|
| `unknown` / 范围外 / 仅采样栈 / 冲突终止 | 直接输出对应结论块(见「分诊结论呈现」),不加载 Analyzer | 不生成 |
|
|
430
448
|
|
|
449
|
+
**无脚本执行环境的降级交付**:环境无 bash、无法运行 export_report.py 时(如仅 Read 工具的隔离沙箱),
|
|
450
|
+
不生成 HTML 报告,也**不交付「会话内摘要钉板」**——钉板的故障基本信息表、根因分析、修复建议等
|
|
451
|
+
正文依赖 Analyzer 完整章节与报告落盘,超出该环境能力。降级时会话内**仅交付三件**:① 标题为
|
|
452
|
+
「分诊摘要」的摘要表(批量场景逐份携带`类型 / 输入完整度 / 置信度` 三字段);② 分节结构声明
|
|
453
|
+
(批量场景每份以 `### 日志 N:<文件名或序号>` 起节);③ 合并路径声明(批量合并走多次 `--input`
|
|
454
|
+
直传、禁止 shell 拼接合并分节正文)。该环境**不得**在会话内逐份渲染完整 Analyzer 输出格式章节,
|
|
455
|
+
也不输出根因分析与证据链正文;有脚本执行能力的环境仍按上表与钉板交付。
|
|
456
|
+
|
|
431
457
|
### 会话内摘要钉板(强制)
|
|
432
458
|
|
|
433
459
|
明确类型时,子会话返回主会话的最终消息**固定为以下 markdown 结构**(关键信息用二级标题、粗体标签、表格与行内代码标记)——它同时就是主会话展示给用户的最终内容,主 Agent 原样转达即可,无需再总结或排版:
|
|
@@ -467,19 +493,25 @@ L3 口述到故障类型的映射,判据统一为一条:
|
|
|
467
493
|
### HTML 报告落盘(export_report.py)
|
|
468
494
|
|
|
469
495
|
完整报告由确定性脚本写入本地文件,你不得用 edit/write 工具直接写报告文件。**报告正文优先写入
|
|
470
|
-
临时文件并用 `--input` 文件参数传入**(脚本以 UTF-8 直读文件,不经过 shell
|
|
496
|
+
临时文件并用 `--input` 文件参数传入**(脚本以 UTF-8 直读文件,不经过 shell 管道编码)。`--input`
|
|
497
|
+
可重复传多份分节文件,脚本按传入顺序自动以 `---` 分隔拼接(分节文件内**不需要**自带分隔线):
|
|
471
498
|
|
|
472
499
|
```bash
|
|
473
|
-
python "<skill-base>/scripts/export_report.py" --type <type> [--title "<标题>"] --input "<报告正文.md>"
|
|
500
|
+
python "<skill-base>/scripts/export_report.py" --type <type> [--title "<标题>"] --input "<报告正文.md>" [--input "<分节2.md>" ...]
|
|
474
501
|
```
|
|
475
502
|
|
|
476
503
|
bash 环境也可用 stdin 重定向 `< <报告正文 markdown>`。**Windows/PowerShell 禁用
|
|
477
|
-
`Get-Content | python`
|
|
504
|
+
`Get-Content | python` 管道,也禁止用 shell 拼接合并分节正文**(`Get-Content | Set-Content`、
|
|
505
|
+
`Out-File`、`cat > 合并文件` 等)——PowerShell 5.1 的 `Get-Content` 缺省按 ANSI(GBK) 解码,
|
|
506
|
+
UTF-8 分节正文会在磁盘合并时被静默二次编码成乱码,且脚本读取不报错(成因、乱码特征与
|
|
507
|
+
已污染报告的还原方法见 `references/report-encoding-pitfalls.md`)。分节合并唯一合法路径是
|
|
508
|
+
多次 `--input`。
|
|
478
509
|
|
|
479
510
|
- 调用前先完成上方「Python 可用性检查」;Windows 中 `python` 为 WindowsApps 占位 stub
|
|
480
511
|
(执行无输出/退出码 9009)时直接改用 `py -3 "<skill-base>/scripts/export_report.py" ...`,
|
|
481
512
|
不得在 stub 上反复试探后另行包装调用;
|
|
482
|
-
- 报告正文经 stdin
|
|
513
|
+
- 报告正文经 `--input` 文件参数传入(bash 环境也可用 stdin 重定向),脚本写入
|
|
514
|
+
`<启动工程目录>/dfx-reports/dfx-report-<type>-<时间戳>.html`
|
|
483
515
|
并在 stdout 回显绝对路径(输出目录即当前工作目录下的 `dfx-reports/`,无需另行指定;该目录为
|
|
484
516
|
可见交付目录,建议用户将其加入 .gitignore 或按需清理);
|
|
485
517
|
- 报告正文必须**严格遵循**被路由到的专项 Analyzer `analyzer.md` 输出格式章节(appfreeze 为「输出格式
|
|
@@ -667,12 +699,13 @@ analyzer 输出格式章节定义),**不重复产出**;主 Skill 追加的
|
|
|
667
699
|
|
|
668
700
|
## 配套文件清单
|
|
669
701
|
|
|
670
|
-
|
|
702
|
+
主要配套文件(入口级,路径相对技能根目录):
|
|
671
703
|
|
|
672
704
|
- references/appfreeze/analyzer.md
|
|
673
705
|
- references/cppcrash/analyzer.md
|
|
674
706
|
- references/jscrash/analyzer.md
|
|
675
707
|
- references/white-screen/analyzer.md
|
|
708
|
+
- references/report-encoding-pitfalls.md
|
|
676
709
|
- scripts/collect/collect-hilog.mjs
|
|
677
710
|
- scripts/collect/jscrash-report.mjs
|
|
678
711
|
- scripts/collect/parse-jscrash-log.mjs
|
|
@@ -681,3 +714,4 @@ analyzer 输出格式章节定义),**不重复产出**;主 Skill 追加的
|
|
|
681
714
|
- scripts/collect/shared/utils.mjs
|
|
682
715
|
- scripts/export_report.py
|
|
683
716
|
- scripts/identify_fault_log.py
|
|
717
|
+
- scripts/report_template.html
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Windows/PowerShell 分节正文合并的 GBK 二次编码陷阱
|
|
2
|
+
|
|
3
|
+
适用范围:批量分析的分节正文在 Windows/PowerShell 下合并后再交给
|
|
4
|
+
`scripts/export_report.py` 的场景。
|
|
5
|
+
|
|
6
|
+
## 现象
|
|
7
|
+
|
|
8
|
+
最终 HTML 报告中**分析器正文全量中文乱码**(如「故障分析报告」→「鏁呴殰鍒嗘瀽鎶ュ憡」),
|
|
9
|
+
而分诊汇总表、标题、命令行参数传入的内容完全正常。
|
|
10
|
+
|
|
11
|
+
## 成因
|
|
12
|
+
|
|
13
|
+
PowerShell 5.1 的 `Get-Content` 缺省按 ANSI(GBK) 解码文件。用 shell 管道拼接合并
|
|
14
|
+
UTF-8 分节正文时(`Get-Content <分节> -Raw`、`Get-Content | Set-Content`、`Out-File`、
|
|
15
|
+
`cat > 合并文件` 等),UTF-8 字节被按 GBK 误解码再以 UTF-8 写回——形成二次编码。
|
|
16
|
+
|
|
17
|
+
三个特征使该污染**静默且难定位**:
|
|
18
|
+
|
|
19
|
+
1. 会话内文本全程正常(污染只发生在磁盘合并这一跳);
|
|
20
|
+
2. 脚本严格 UTF-8 读取不报错(二次编码后的字节序列本身是合法 UTF-8);
|
|
21
|
+
3. 命令行参数(如 `--title`)与脚本内联构造的内容不经该路径,保持正常——
|
|
22
|
+
报告内乱码/正常内容的分界线精确暴露污染范围。
|
|
23
|
+
|
|
24
|
+
数学验证:`'故障分析报告'.encode('utf-8').decode('gbk')` = `鏁呴殰鍒嗘瀽鎶ュ憡`,
|
|
25
|
+
与实测乱码逐字吻合。
|
|
26
|
+
|
|
27
|
+
## 预防(唯一合法路径)
|
|
28
|
+
|
|
29
|
+
分节合并不走 shell——把「汇总表 → 各类型分节」的文件**按顺序逐一 `--input` 传给
|
|
30
|
+
export_report.py**,由脚本在 Python 内以 UTF-8 全链路拼接。`PYTHONIOENCODING`
|
|
31
|
+
只管 Python 进程的 stdin/stdout 编码,管不到 PowerShell 读盘解码,不能作为替代手段。
|
|
32
|
+
|
|
33
|
+
已有相关护栏(本 Skill 的既有约定,与本文件互补):
|
|
34
|
+
|
|
35
|
+
- `Get-Content | python` 管道禁令(正文不经 shell 解码进脚本);
|
|
36
|
+
- 报告正文优先 `--input` 文件参数传入(文件直读,UTF-8 无歧义)。
|
|
37
|
+
|
|
38
|
+
## 已污染报告的恢复
|
|
39
|
+
|
|
40
|
+
二次编码可逆:`乱码文本.encode('gbk').decode('utf-8')` 即还原原文。对整份已污染的
|
|
41
|
+
HTML 报告,用同变换批量还原后重新落盘即可恢复。
|
|
@@ -4,11 +4,13 @@
|
|
|
4
4
|
Usage:
|
|
5
5
|
python export_report.py --type cpp_crash --title "..." < report.md
|
|
6
6
|
python export_report.py --type js_crash --input report.md --output-dir <dir>
|
|
7
|
+
python export_report.py --type batch --input 00-summary.md --input 01-appfreeze.md --input 02-cppcrash.md
|
|
7
8
|
|
|
8
9
|
Writes <output-dir>/dfx-report-<type>-<YYYYMMDD-HHMMSS>.html (output-dir
|
|
9
10
|
defaults to dfx-reports under the current working directory, i.e. the
|
|
10
11
|
project directory the tool was started in) and prints the absolute path of the
|
|
11
|
-
written file to stdout.
|
|
12
|
+
written file to stdout. Repeated --input files are joined in order with a ---
|
|
13
|
+
separator (batch sections).
|
|
12
14
|
|
|
13
15
|
Style contract: the HTML skeleton and all CSS live in report_template.html
|
|
14
16
|
(next to this script) as the single source of truth for report styling — the
|
|
@@ -274,6 +276,7 @@ TYPE_LABELS = {
|
|
|
274
276
|
"app_freeze": "应用冻屏(AppFreeze)",
|
|
275
277
|
"sample_stack": "采样栈(增强日志)",
|
|
276
278
|
"white_screen": "非崩溃型白屏(WhiteScreen)",
|
|
279
|
+
"batch": "批量合并报告",
|
|
277
280
|
"unknown": "无法判定",
|
|
278
281
|
}
|
|
279
282
|
|
|
@@ -334,13 +337,16 @@ def main():
|
|
|
334
337
|
parser = argparse.ArgumentParser(description="Export DFX analysis report markdown to a self-contained HTML file.")
|
|
335
338
|
parser.add_argument("--type", required=True, help="fault type from the triage verdict (e.g. cpp_crash)")
|
|
336
339
|
parser.add_argument("--title", default="", help="report title; defaults to 'DFX 故障分析报告 - <type>'")
|
|
337
|
-
parser.add_argument("--input", help="markdown report file; reads stdin when omitted")
|
|
340
|
+
parser.add_argument("--input", action="append", help="markdown report file; repeat for batch sections, joined in order with --- separators; reads stdin when omitted")
|
|
338
341
|
parser.add_argument("--output-dir", help="output directory; defaults to <cwd>/dfx-reports")
|
|
339
342
|
args = parser.parse_args()
|
|
340
343
|
|
|
341
344
|
if args.input:
|
|
342
|
-
|
|
343
|
-
|
|
345
|
+
parts = []
|
|
346
|
+
for input_path in args.input:
|
|
347
|
+
with open(input_path, "r", encoding="utf-8") as f:
|
|
348
|
+
parts.append(f.read())
|
|
349
|
+
md = "\n\n---\n\n".join(parts)
|
|
344
350
|
else:
|
|
345
351
|
md = sys.stdin.read()
|
|
346
352
|
|