@deveco-test/deveco-cli 1.3.1-Test.1 → 1.3.1-Test.2

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,9 +1,9 @@
1
- import Nt from"path";import*as S from"fs";import*as Y from"path";import{homedir as gt}from"os";import*as H from"fs";import*as m from"path";function J(r){let t=m.resolve(r),e=[],n=t;for(;;)try{let i=H.realpathSync(n);return e.length===0?i:m.join(i,...e.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=m.dirname(n);if(o===n)return t;e.push(m.basename(n)),n=o}}function P(r){let t=r.trim();return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t}function K(r){let t=P(r);if(!t)throw new Error("Path must not be empty.");return J(t)}var ht="deveco-cli",W,N=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function yt(){let r=process.env.DEVECO_CLI_DATA_DIR,e=(r===void 0||r===""?"":P(r))||Y.join(gt(),".local","share",ht);try{return K(e)}catch(n){throw new N(n instanceof Error?n.message:String(n))}}function X(){if(W!==void 0)return W;let r=yt();try{if(S.existsSync(r))return S.realpathSync(r)}catch{}return r}import mt from"crypto";import d from"fs";import z from"os";import y from"path";import St from"https";var q={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};var D=class r{static ENDPOINT=q.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(t,e){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:e.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(t,"utf8"))};try{let{body:i}=await this.httpPost(r.ENDPOINT,n,Buffer.from(t,"utf8"),6e4);return r.isSuccess(i)}catch{return!1}}static isSuccess(t){try{let e=JSON.parse(t),n=e?.code??e?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(t,e,n,i){let o=new URL(t);return new Promise((s,p)=>{let l=St.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:e,timeout:i},v=>{let h=[];v.on("data",w=>h.push(w)),v.on("end",()=>{s({code:v.statusCode??0,body:Buffer.concat(h).toString("utf8")})})});l.on("timeout",()=>{l.destroy(new Error("request timeout"))}),l.on("error",p),l.write(n),l.end()})}};var G={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()},M=class{constructor(t={}){this.config=t}config;serialize(t){let e=this.transform(t);return this.config.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}toObject(t){return this.transform(t)}transform(t){if(t==null)return t;if(Array.isArray(t))return t.map(o=>this.transform(o));if(typeof t!="object")return t;let e=this.config.namingStrategy??G.identity,n=this.config.fieldNames??{},i={};for(let[o,s]of Object.entries(t)){let p=n[o]??e(o);i[p]=this.transform(s)}return i}},Z=new M({namingStrategy:G.snakeCase,fieldNames:{}});import E from"crypto";import C from"fs";import Et from"path";var L="aes-256-gcm",xt=12,Tt="deveco-cli-trace-file",bt="trace-file-secret",tt=32;function Q(r){try{let t=C.readFileSync(r,"utf8").trim();return t&&Buffer.from(t,"base64").length===tt?t:null}catch{return null}}function et(r){let t=Et.join(r,bt),e=Q(t);if(e)return j(e);let n=E.randomBytes(tt).toString("base64");try{C.mkdirSync(r,{recursive:!0});try{C.writeFileSync(t,n,{flag:"wx"})}catch{let i=Q(t);if(i)return j(i);C.writeFileSync(t,n)}}catch{}return j(n)}function j(r){return E.createHash("sha256").update(Tt).update(r).digest()}function $(r,t){let e=E.randomBytes(xt),n=E.createCipheriv(L,t,e),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:L,ciphertext:i.toString("base64"),iv:e.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(o)}function rt(r,t){let e;try{e=JSON.parse(r)}catch{return null}if(!wt(e))return r;try{let n=E.createDecipheriv(L,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function wt(r){if(!r||typeof r!="object")return!1;let t=r;return t.version===1&&t.algorithm===L&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import*as a from"fs";import*as A from"path";import*as _ from"os";import*as g from"path";import ce from"json5";function nt(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??g.join(_.homedir(),"AppData","Local");return g.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?g.join(_.homedir(),"Library","Logs","devecocli-mcp-server"):g.join(_.homedir(),".local","share","devecocli-mcp-server","logs")}var it="mcp-server.log",Dt="mcp-server",Ct={maxSize:10*1024*1024,maxFiles:4},B=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(t,e){this.rotationOptions={...Ct,...e},this.minLevel=t?"debug":"info",t?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=nt(),this.currentLogFile=A.join(this.logDir,it),a.existsSync(this.logDir)||a.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let t=new Date,e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${i}`}getRotatedFileName(t,e){return A.join(this.logDir,`${Dt}-${t}.log.${e}`)}fileExists(t){try{return a.accessSync(t,a.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let t=a.readdirSync(this.logDir),e=[];for(let i of t)if(i===it||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=A.join(this.logDir,i),s=a.statSync(o);e.push({name:i,mtime:s.mtime,path:o})}e.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<e.length;i++)try{a.unlinkSync(e[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 t=this.getCurrentDateString(),e=this.getRotatedFileName(t,this.rotationOptions.maxFiles);this.fileExists(e)&&a.unlinkSync(e);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(t,i),s=this.getRotatedFileName(t,i+1);this.fileExists(o)&&a.renameSync(o,s)}let n=this.getRotatedFileName(t,1);a.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 t=a.statSync(this.currentLogFile);this.currentFileSize=t.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=a.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{a.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(t){let e=this.getCurrentDateString();this.currentDate&&this.currentDate!==e&&(this.rotateLog(),this.currentDate=e),this.currentFileSize+=t,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(t,e,...n){if(this.mode==="silent"||r.LEVEL_ORDER[t]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)).join(" "),o=i?`${e} ${i}`:e,p=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${t.toUpperCase()}] ${o}
2
- `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let l=Buffer.from(p);a.writeSync(this.fd,l),this.checkRotation(l.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(p)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{a.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},x=null;function Lt(r=!1){x&&x.dispose(),x=new B(r)}function F(){return x||Lt(!1),x}var f={debug:(r,...t)=>F().debug(r,...t),info:(r,...t)=>F().info(r,...t),warn:(r,...t)=>F().warn(r,...t),error:(r,...t)=>F().error(r,...t)};import ot from"fs";import _t from"path";var O=300*1e3,R=3600*1e3,st=10080*60*1e3;function k(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Ft="upload-state.json";function at(r){return _t.join(r,Ft)}function At(){return{firstEventAt:null,lastUploadAt:null,lastRetryAt:null}}function U(r){try{let t=ot.readFileSync(at(r),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null,lastRetryAt:typeof e.lastRetryAt=="number"?e.lastRetryAt:null}}catch{return At()}}function V(r,t){try{ot.writeFileSync(at(r),JSON.stringify(t),"utf8")}catch{}}function lt(r){let t=U(r);t.firstEventAt===null&&(t.firstEventAt=Date.now(),V(r,t))}function ct(r){let t=U(r);t.lastUploadAt=Date.now(),t.firstEventAt=null,V(r,t)}function ut(r){let t=U(r);t.lastRetryAt=Date.now(),V(r,t)}function pt(r){let t=r.match(/^telemetry-(\d{4})-(\d{2})-(\d{2})\.txt$/);if(!t)return null;let e=Date.parse(`${t[1]}-${t[2]}-${t[3]}T00:00:00`);return Number.isFinite(e)?e:null}import Ot from"crypto";import I from"fs";import Rt from"path";var kt="install-id";function It(r){return Rt.join(r,kt)}function ft(r){try{let t=I.readFileSync(r,"utf8").trim();return Pt(t)?t:null}catch{return null}}function Pt(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 dt(r){let t=It(r),e=ft(t);if(e)return e;let n=Ot.randomUUID();try{I.mkdirSync(r,{recursive:!0});try{I.writeFileSync(t,n,{flag:"wx"})}catch{let i=ft(t);if(i)return i;I.writeFileSync(t,n)}}catch{}return n}var T=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 D;storageDir="";failedDir="";installId="";disabled=k();traceFileKey=Buffer.alloc(0);sessionId=mt.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;retryInitialTimer=null;retryTimer=null;flushChain=Promise.resolve();constructor(){f.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=y.join(t,"failed"),this.cliVersion="1.3.1-Test.1",this.nodeVersion=process.version,this.installId=dt(t).replace(/-/g,""),this.traceFileKey=et(t),d.mkdirSync(t,{recursive:!0}),d.mkdirSync(this.failedDir,{recursive:!0}),f.info(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,f.info(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,f.info(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,f.info(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(!e){await this.record(t,0,!0,null);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code);return}let n=e,i=Date.now();try{let o=await n(),s=Date.now()-i;return await this.record(t,s,!0,null),o}catch(o){let s=Date.now()-i,p=this.toErrorCode(o);throw await this.record(t,s,!1,p),o}}async record(t,e,n,i){let o=this.buildTraceEvent(t,e,n,i);try{let s=$(JSON.stringify(o),this.traceFileKey);await d.promises.appendFile(this.currentFile(),s+`
3
- `,"utf8"),lt(this.storageDir)}catch{}}buildTraceEvent(t,e,n,i){let o=`${r.EVENT_PREFIX}${t.event}`,s=Z.toObject(t);return s&&typeof s=="object"&&delete s.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:mt.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,duration_ms:e,success:n,error_code:i,event_detail:s}}}toErrorCode(t){return t instanceof Error?t.code??t.name:"UnknownError"}resolveOsArch(){let t=z.arch();return t==="x64"?"amd64":t}resolveOsName(){switch(process.platform){case"win32":{let t=z.release().split(".");return(parseInt(t[t.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 z.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}formatVersion(t){return t?`${t}_${this.resolveOsSuffix()}`:""}dateString(){let t=new Date,e=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${e}-${n}`}currentFile(){return y.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){f.info("[telemetry] scheduler not started (telemetry disabled)");return}f.info(`[telemetry] scheduler started (flush every ${O/1e3}s, retry failed every ${R/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(()=>{}),this.intervalTimer=setInterval(()=>{this.flush().catch(()=>{})},O)},O),this.retryInitialTimer=setTimeout(()=>{this.retryFailed().catch(()=>{}),this.retryTimer=setInterval(()=>{this.retryFailed().catch(()=>{})},R)},R)}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.info("[telemetry] scheduler stopped")}async flush(){return this.disabled?!0:this.runExclusive(()=>this.performFlush())}async performFlush(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let t=await this.listPendingFiles(),e=!0;for(let n of t)await this.flushFile(n)||(e=!1);return ct(this.storageDir),e}async retryFailed(){return this.disabled?!0:this.runExclusive(()=>this.performRetryFailed())}async performRetryFailed(){if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");let t=Date.now(),e;try{e=await d.promises.readdir(this.failedDir)}catch{return!0}let n=e.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),p=pt(s);if(p!==null){if(t-p>st){try{await d.promises.unlink(o)}catch{}continue}await this.flushFile(o)||(i=!1)}}return i||f.warn("[telemetry] retry failed"),ut(this.storageDir),i}runExclusive(t){let e=()=>t(),n=this.flushChain.then(e,e);return this.flushChain=n.then(()=>{},()=>{}),n}async listPendingFiles(){let t;try{t=await d.promises.readdir(this.storageDir)}catch{return[]}return t.filter(e=>e.startsWith("telemetry-")&&e.endsWith(".txt")).map(e=>y.join(this.storageDir,e)).sort()}async flushFile(t){let e=t+".pending";try{await d.promises.rename(t,e)}catch{return!1}let n;try{n=await d.promises.readFile(e,"utf8")}catch{return!1}let i=n.split(`
4
- `).map(s=>s.trim()).filter(Boolean),o=[];for(let s of i){let p=rt(s,this.traceFileKey);p!==null&&o.push(p)}if(o.length===0){try{await d.promises.unlink(e)}catch{}return!0}return this.uploadInBatches(e,o)}async uploadInBatches(t,e){let n=0;for(;n<e.length;){let i=n,o=[],s=16;for(;n<e.length&&o.length<r.MAX_BATCH;){let h=e[n],w=Buffer.byteLength(h,"utf8")+1;if(o.length>0&&s+w>r.MAX_PAYLOAD_BYTES)break;o.push(h),s+=w,n++}let p=this.buildPayloadItems(o),l=JSON.stringify(p),v=!1;try{v=await this.uploader.upload(l,this.installId)}catch{}if(!v){f.warn("[telemetry] upload failed");let h=e.slice(i).join(`
1
+ import At from"path";import*as S from"fs";import*as K from"path";import{homedir as pt}from"os";import*as V from"fs";import*as d from"path";function P(r){let t=d.resolve(r),e=[],n=t;for(;;)try{let i=V.realpathSync(n);return e.length===0?i:d.join(i,...e.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=d.dirname(n);if(o===n)return t;e.push(d.basename(n)),n=o}}function R(r){let t=r.trim();return(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))&&(t=t.slice(1,-1).trim()),t}function z(r){let t=R(r);if(!t)throw new Error("Path must not be empty.");return P(t)}var ft="deveco-cli",H,$=class extends Error{constructor(t){super(t),this.name="CliDataDirError"}};function dt(){let r=process.env.DEVECO_CLI_DATA_DIR,e=(r===void 0||r===""?"":R(r))||K.join(pt(),".local","share",ft);try{return z(e)}catch(n){throw new $(n instanceof Error?n.message:String(n))}}function J(){if(H!==void 0)return H;let r=dt();try{if(S.existsSync(r))return S.realpathSync(r)}catch{}return r}import ut from"crypto";import g from"fs";import U from"os";import v from"path";import vt from"https";var W={devecoApiTraceUpload:"https://cn.devecostudio.huawei.com/codeGenie/cli/trace/upload"};import*as c from"fs";import*as L from"path";import*as x from"os";import*as h from"path";import qt from"json5";function Y(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??h.join(x.homedir(),"AppData","Local");return h.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?h.join(x.homedir(),"Library","Logs","devecocli-mcp-server"):h.join(x.homedir(),".local","share","devecocli-mcp-server","logs")}var q="mcp-server.log",mt="mcp-server",ht={maxSize:10*1024*1024,maxFiles:4},N=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(t,e){this.rotationOptions={...ht,...e},this.minLevel=t?"debug":"info",t?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=Y(),this.currentLogFile=L.join(this.logDir,q),c.existsSync(this.logDir)||c.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let t=new Date,e=t.getFullYear(),n=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${e}-${n}-${i}`}getRotatedFileName(t,e){return L.join(this.logDir,`${mt}-${t}.log.${e}`)}fileExists(t){try{return c.accessSync(t,c.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let t=c.readdirSync(this.logDir),e=[];for(let i of t)if(i===q||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=L.join(this.logDir,i),a=c.statSync(o);e.push({name:i,mtime:a.mtime,path:o})}e.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<e.length;i++)try{c.unlinkSync(e[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 t=this.getCurrentDateString(),e=this.getRotatedFileName(t,this.rotationOptions.maxFiles);this.fileExists(e)&&c.unlinkSync(e);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(t,i),a=this.getRotatedFileName(t,i+1);this.fileExists(o)&&c.renameSync(o,a)}let n=this.getRotatedFileName(t,1);c.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 t=c.statSync(this.currentLogFile);this.currentFileSize=t.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=c.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{c.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(t){let e=this.getCurrentDateString();this.currentDate&&this.currentDate!==e&&(this.rotateLog(),this.currentDate=e),this.currentFileSize+=t,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(t,e,...n){if(this.mode==="silent"||r.LEVEL_ORDER[t]<r.LEVEL_ORDER[this.minLevel])return;let i=n.map(l=>l instanceof Error?`${l.name}: ${l.message}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)).join(" "),o=i?`${e} ${i}`:e,f=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${t.toUpperCase()}] ${o}
2
+ `;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let l=Buffer.from(f);c.writeSync(this.fd,l),this.checkRotation(l.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(f)}debug(t,...e){this.write("debug",t,...e)}info(t,...e){this.write("info",t,...e)}warn(t,...e){this.write("warn",t,...e)}error(t,...e){this.write("error",t,...e)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{c.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},E=null;function yt(r=!1){E&&E.dispose(),E=new N(r)}function C(){return E||yt(!1),E}var s={debug:(r,...t)=>C().debug(r,...t),info:(r,...t)=>C().info(r,...t),warn:(r,...t)=>C().warn(r,...t),error:(r,...t)=>C().error(r,...t)};var _=class r{static DEBUG=!0;static ENDPOINT=W.devecoApiTraceUpload;static SENDER="deveco-cli";async upload(t,e){let n={"Content-Type":"application/json",sender:r.SENDER,deviceid:e.replace(/-/g,""),"Content-Length":String(Buffer.byteLength(t,"utf8"))};r.log(`upload request: URL=${r.ENDPOINT}`);try{let{code:i,body:o}=await this.httpPost(r.ENDPOINT,n,Buffer.from(t,"utf8"),6e4);return r.log(`upload response: status=${i}, body=${o}`),r.isSuccess(o)}catch(i){return r.log(`upload failed: ${i instanceof Error?i.message:String(i)}`),!1}}static isSuccess(t){try{let e=JSON.parse(t),n=e?.code??e?.errorCode;return String(n)==="200"}catch{return!1}}async httpPost(t,e,n,i){let o=new URL(t);return new Promise((a,f)=>{let l=vt.request({protocol:o.protocol,hostname:o.hostname,port:o.port||(o.protocol==="https:"?443:80),path:o.pathname+o.search,method:"POST",headers:e,timeout:i},y=>{let m=[];y.on("data",D=>m.push(D)),y.on("end",()=>{a({code:y.statusCode??0,body:Buffer.concat(m).toString("utf8")})})});l.on("timeout",()=>{l.destroy(new Error("request timeout"))}),l.on("error",f),l.write(n),l.end()})}static log(t){r.DEBUG&&s.info("[TRACE]"+t)}};var X={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()},M=class{constructor(t={}){this.config=t}serialize(t){let e=this.transform(t);return this.config.pretty?JSON.stringify(e,null,2):JSON.stringify(e)}toObject(t){return this.transform(t)}transform(t){if(t==null)return t;if(Array.isArray(t))return t.map(o=>this.transform(o));if(typeof t!="object")return t;let e=this.config.namingStrategy??X.identity,n=this.config.fieldNames??{},i={};for(let[o,a]of Object.entries(t)){let f=n[o]??e(o);i[f]=this.transform(a)}return i}},G=new M({namingStrategy:X.snakeCase,fieldNames:{}});import b from"crypto";import k from"fs";import St from"path";var F="aes-256-gcm",xt=12,Et="deveco-cli-trace-file",bt="trace-file-secret",Q=32;function Z(r){try{let t=k.readFileSync(r,"utf8").trim();return t&&Buffer.from(t,"base64").length===Q?t:null}catch{return null}}function tt(r){let t=St.join(r,bt),e=Z(t);if(e)return j(e);let n=b.randomBytes(Q).toString("base64");try{k.mkdirSync(r,{recursive:!0});try{k.writeFileSync(t,n,{flag:"wx"})}catch{let i=Z(t);if(i)return j(i);k.writeFileSync(t,n)}}catch{}return j(n)}function j(r){return b.createHash("sha256").update(Et).update(r).digest()}function B(r,t){let e=b.randomBytes(xt),n=b.createCipheriv(F,t,e),i=Buffer.concat([n.update(r,"utf8"),n.final()]),o={version:1,algorithm:F,ciphertext:i.toString("base64"),iv:e.toString("base64"),authTag:n.getAuthTag().toString("base64")};return JSON.stringify(o)}function et(r,t){let e;try{e=JSON.parse(r)}catch{return null}if(!Tt(e))return r;try{let n=b.createDecipheriv(F,t,Buffer.from(e.iv,"base64"));return n.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([n.update(Buffer.from(e.ciphertext,"base64")),n.final()]).toString("utf8")}catch{return null}}function Tt(r){if(!r||typeof r!="object")return!1;let t=r;return t.version===1&&t.algorithm===F&&typeof t.ciphertext=="string"&&typeof t.iv=="string"&&typeof t.authTag=="string"}import rt from"fs";import wt from"path";var T=300*1e3;function O(){let r=process.env.DEVECO_CLI_DISABLE_TELEMETRY;return r==="1"||r==="true"}var Dt="upload-state.json";function nt(r){return wt.join(r,Dt)}function Ct(){return{firstEventAt:null,lastUploadAt:null}}function it(r){try{let t=rt.readFileSync(nt(r),"utf8"),e=JSON.parse(t);return{firstEventAt:typeof e.firstEventAt=="number"?e.firstEventAt:null,lastUploadAt:typeof e.lastUploadAt=="number"?e.lastUploadAt:null}}catch{return Ct()}}function ot(r,t){try{rt.writeFileSync(nt(r),JSON.stringify(t),"utf8")}catch{}}function st(r){let t=it(r);t.firstEventAt===null&&(t.firstEventAt=Date.now(),ot(r,t))}function at(r){let t=it(r);t.lastUploadAt=Date.now(),t.firstEventAt=null,ot(r,t)}import Lt from"crypto";import A from"fs";import _t from"path";var kt="install-id";function Ft(r){return _t.join(r,kt)}function ct(r){try{let t=A.readFileSync(r,"utf8").trim();return Ot(t)?t:null}catch{return null}}function Ot(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 lt(r){let t=Ft(r),e=ct(t);if(e)return e;let n=Lt.randomUUID();try{A.mkdirSync(r,{recursive:!0});try{A.writeFileSync(t,n,{flag:"wx"})}catch{let i=ct(t);if(i)return i;A.writeFileSync(t,n)}}catch{}return n}var w=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="";disabled=O();traceFileKey=Buffer.alloc(0);sessionId=ut.randomUUID();cliVersion="";devecoStudioVersion=null;sourceType="";cltVersion=null;nodeVersion="";initialTimer=null;intervalTimer=null;constructor(){s.info(`[telemetry] instance created, sessionId=${this.sessionId}`)}init(t){this.storageDir=t,this.failedDir=v.join(t,"failed"),this.cliVersion="1.3.1-Test.2",this.nodeVersion=process.version,this.installId=lt(t).replace(/-/g,""),this.traceFileKey=tt(t),g.mkdirSync(t,{recursive:!0}),g.mkdirSync(this.failedDir,{recursive:!0}),s.info(`[telemetry] init: dir=${t}, failedDir=${this.failedDir}, cliVersion=${this.cliVersion}, os=${this.resolveOsName()}, arch=${this.resolveOsArch()}, node=${this.nodeVersion}`)}setStudioVersion(t){this.devecoStudioVersion=t,s.info(`[telemetry] studio version set: ${t}`)}setSourceType(t){this.sourceType=t,s.info(`[telemetry] sourceType set: ${t}`)}setCltVersion(t){this.cltVersion=t,s.info(`[telemetry] CLT version set: ${t}`)}async track(t,e){if(this.disabled)return typeof e=="function"?e():void 0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");if(s.info(`[telemetry] track: ${t.event}`),!e){await this.record(t,0,!0,null),s.info(`[telemetry] track recorded: ${t.event} (no measurement)`);return}if(typeof e!="function"){let o=e;await this.record(t,o.duration_ms,o.success,o.error_code),s.info(`[telemetry] track recorded: ${t.event} (measurement: duration=${o.duration_ms}ms, success=${o.success}, code=${o.error_code})`);return}let n=e,i=Date.now();try{let o=await n(),a=Date.now()-i;return await this.record(t,a,!0,null),s.info(`[telemetry] track success: ${t.event}, duration=${a}ms`),o}catch(o){let a=Date.now()-i,f=this.toErrorCode(o);throw await this.record(t,a,!1,f),s.info(`[telemetry] track failed: ${t.event}, duration=${a}ms, code=${f}`),o}}async record(t,e,n,i){let o=this.buildTraceEvent(t,e,n,i);try{let a=B(JSON.stringify(o),this.traceFileKey);await g.promises.appendFile(this.currentFile(),a+`
3
+ `,"utf8"),s.info(`[telemetry] event persisted: ${o.properties.trace_uuid}`),st(this.storageDir)}catch(a){s.error("[telemetry] track write error:",a)}}buildTraceEvent(t,e,n,i){let o=`${r.EVENT_PREFIX}${t.event}`,a=G.toObject(t);return a&&typeof a=="object"&&delete a.event,{countryCode:r.COUNTRY_CODE,event:o,eventtime:String(Date.now()),properties:{uid:this.installId,trace_uuid:ut.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,duration_ms:e,success:n,error_code:i,event_detail:a}}}toErrorCode(t){return t instanceof Error?t.code??t.name:"UnknownError"}resolveOsArch(){let t=U.arch();return t==="x64"?"amd64":t}resolveOsName(){switch(process.platform){case"win32":{let t=U.release().split(".");return(parseInt(t[t.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 U.arch()==="arm64"?"mac_arm":"mac";default:return"linux"}}formatVersion(t){return t?`${t}_${this.resolveOsSuffix()}`:""}dateString(){let t=new Date,e=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${e}-${n}`}currentFile(){return v.join(this.storageDir,`telemetry-${this.dateString()}.txt`)}startScheduler(){if(this.stopScheduler(),this.disabled){s.info("[telemetry] scheduler not started (telemetry disabled)");return}s.info(`[telemetry] scheduler started (first flush in ${T/1e3}s, then every ${T/1e3}s)`),this.initialTimer=setTimeout(()=>{this.flush().catch(t=>s.error("[telemetry] flush error:",t)),this.intervalTimer=setInterval(()=>{this.flush().catch(t=>s.error("[telemetry] flush error:",t))},T)},T)}stopScheduler(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null),s.info("[telemetry] scheduler stopped")}async flush(){if(this.disabled)return!0;if(!this.storageDir)throw new Error("Telemetry not initialized. Call init() first.");s.info("[telemetry] flush start");let t=await this.listPendingFiles();if(t.length===0)return s.info("[telemetry] flush: no event files"),!0;s.info(`[telemetry] flush: ${t.length} file(s) pending`);let e=!0;for(let n of t)await this.flushFile(n)||(e=!1);return s.info(`[telemetry] flush done, allOk=${e}`),at(this.storageDir),e}async listPendingFiles(){let t;try{t=await g.promises.readdir(this.storageDir)}catch{return[]}return t.filter(e=>e.startsWith("telemetry-")&&e.endsWith(".txt")).map(e=>v.join(this.storageDir,e)).sort()}async flushFile(t){let e=t+".pending";try{await g.promises.rename(t,e),s.info(`[telemetry] flush: renamed ${v.basename(t)} \u2192 pending`)}catch{return!1}let n;try{n=await g.promises.readFile(e,"utf8")}catch{return!1}let i=n.split(`
4
+ `).map(f=>f.trim()).filter(Boolean),o=[],a=0;for(let f of i){let l=et(f,this.traceFileKey);if(l===null){a++;continue}o.push(l)}if(a>0&&s.warn(`[telemetry] flush: skipped ${a} undecryptable line(s)`),o.length===0){try{await g.promises.unlink(e)}catch{}return!0}return this.uploadInBatches(e,o)}async uploadInBatches(t,e){let n=0;for(;n<e.length;){let i=n,o=[],a=16;for(;n<e.length&&o.length<r.MAX_BATCH;){let m=e[n],D=Buffer.byteLength(m,"utf8")+1;if(o.length>0&&a+D>r.MAX_PAYLOAD_BYTES)break;o.push(m),a+=D,n++}let f=this.buildPayloadItems(o),l=JSON.stringify(f);s.info(`[telemetry] flush: uploading batch (${f.length} events, ${Buffer.byteLength(l,"utf8")} bytes)`);let y=!1;try{y=await this.uploader.upload(l,this.installId)}catch(m){s.error("[telemetry] build/upload error:",m)}if(!y){let m=e.slice(i).join(`
5
5
  `)+`
6
- `;return await this.moveToFailed(t,h),!1}}try{await d.promises.unlink(t)}catch{}return!0}buildPayloadItems(t){let e=[];for(let n of t)try{let i=JSON.parse(n);e.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return e}async moveToFailed(t,e){let n=y.basename(t,".pending"),i=y.join(this.failedDir,n);try{let o=e.split(`
7
- `).filter(Boolean).map(s=>$(s,this.traceFileKey)).join(`
6
+ `;return await this.moveToFailed(t,m),!1}}try{await g.promises.unlink(t)}catch{}return s.info("[telemetry] flush: file done, pending removed"),!0}buildPayloadItems(t){let e=[];for(let n of t)try{let i=JSON.parse(n);e.push({action:i.event,detail:JSON.stringify(i.properties),timestamp:Number(i.eventtime)||Date.now()})}catch{}return e}async moveToFailed(t,e){let n=v.basename(t,".pending"),i=v.join(this.failedDir,n);s.info(`[telemetry] moving to failed: ${n}`);try{let o=e.split(`
7
+ `).filter(Boolean).map(a=>B(a,this.traceFileKey)).join(`
8
8
  `)+`
9
- `;await d.promises.appendFile(i,o,"utf8")}catch{return}try{await d.promises.unlink(t)}catch{}}};var b=new T;import{spawn as Ve}from"child_process";import{existsSync as He}from"fs";import{dirname as Ke,join as We}from"path";import{fileURLToPath as Xe}from"url";var Mt=Nt.join(X(),"TraceLogData");b.init(Mt);(async()=>{try{await b.flush(),await b.retryFailed()}catch(r){f.warn("[telemetry] background upload error:",r),process.exit(1)}})();
9
+ `;await g.promises.appendFile(i,o,"utf8")}catch(o){s.error("[telemetry] move to failed error:",o);return}try{await g.promises.unlink(t)}catch{}}};var I=new w;import{spawn as Ue}from"child_process";import{existsSync as ze}from"fs";import{dirname as Ke,join as Je}from"path";import{fileURLToPath as Ye}from"url";var It=At.join(J(),"TraceLogData");I.init(It);I.flush().then(r=>{r?s.info("[telemetry] background upload completed"):s.warn("[telemetry] background upload completed with failures")}).catch(r=>{s.error("[telemetry] background upload error:",r),process.exit(1)});
package/docs.zip CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/docs.zip
3
- size: 39956537 bytes
4
- sha256: 39cf91094a673c9a38b2900614288c8e9ddb3743e0d9c16c0f2a6e7a82fb4186
3
+ size: 40538363 bytes
4
+ sha256: 69cea82c1729991ed37837dc115cb43463b45b6381de6005f9d0c153399f6d1f
package/index.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/deveco-cli",
3
- "version": "1.3.1-Test.1",
3
+ "version": "1.3.1-Test.2",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -65,9 +65,9 @@
65
65
  },
66
66
  "dependencies": {
67
67
  "@modelcontextprotocol/sdk": "^1.29.0",
68
- "@sqlite.org/sqlite-wasm": "^3.49.1-build4",
69
- "adm-zip": "0.6.0",
70
- "axios": "1.19.0",
68
+ "@sqlite.org/sqlite-wasm": "3.54.1-build1",
69
+ "adm-zip": "0.6.1",
70
+ "axios": "1.20.0",
71
71
  "colorette": "^2.0.20",
72
72
  "commander": "^13.1.0",
73
73
  "execa": "^9.6.1",